Programs & Examples On #Expression web

Microsoft Expression Web is a professional development and design tool to create modern, standards-based Web sites that use PHP, HTML/XHTML, CSS, JavaScript, ASP.NET or ASP.NET AJAX.

Drop-down menu that opens up/upward with pure css

Add bottom:100% to your #menu:hover ul li:hover ul rule

Demo 1

#menu:hover ul li:hover ul {
    position: absolute;
    margin-top: 1px;
    font: 10px;
    bottom: 100%; /* added this attribute */
}

Or better yet to prevent the submenus from having the same effect, just add this rule

Demo 2

#menu>ul>li:hover>ul { 
    bottom:100%;
}

Demo 3

source: http://jsfiddle.net/W5FWW/4/

And to get back the border you can add the following attribute

#menu>ul>li:hover>ul { 
    bottom:100%;
    border-bottom: 1px solid transparent
}

MySQLi count(*) always returns 1

You have to fetch that one record, it will contain the result of Count()

$result = $db->query("SELECT COUNT(*) FROM `table`");
$row = $result->fetch_row();
echo '#: ', $row[0];

Handling a timeout error in python sockets

Here is a solution I use in one of my project.

network_utils.telnet

import socket
from timeit import default_timer as timer

def telnet(hostname, port=23, timeout=1):
    start = timer()
    connection = socket.socket()
    connection.settimeout(timeout)
    try:
        connection.connect((hostname, port))
        end = timer()
        delta = end - start
    except (socket.timeout, socket.gaierror) as error:
        logger.debug('telnet error: ', error)
        delta = None
    finally:
        connection.close()

    return {
        hostname: delta
    }

Tests

def test_telnet_is_null_when_host_unreachable(self):
    hostname = 'unreachable'

    response = network_utils.telnet(hostname)

    self.assertDictEqual(response, {'unreachable': None})

def test_telnet_give_time_when_reachable(self):
    hostname = '127.0.0.1'

    response = network_utils.telnet(hostname, port=22)

    self.assertGreater(response[hostname], 0)

dereferencing pointer to incomplete type

this error usually shows if the name of your struct is different from the initialization of your struct in the code, so normally, c will find the name of the struct you put and if the original struct is not found, this would usually appear, or if you point a pointer pointed into that pointer, the error will show up.

Found conflicts between different versions of the same dependent assembly that could not be resolved

I followed the advice of several of the responses here to figure out what was wrong, but none of the answers seemed to explain how to fix it. My issue was that one reference required a different version of a second reference. So Newtonsoft was at version 6, but some other DLL wanted 4.5. Then I upgraded Newtonsoft as one of the other answers suggested and that made things worse.

So I actually downgraded my Newtonsoft install and the warning went away (VS 2017):

Right click References in the solution explorer and select Manage NuGet Packages... Under the "Installed" tab, find Newtonsoft (or whatever your conflict is) On the right side, a dropdown appears next to "Version" that you can change to older versions. It wasn't obvious to me that this dropdown could be used to downgrade.

How do I change file permissions in Ubuntu

If you just want to change file permissions, you want to be careful about using -R on chmod since it will change anything, files or folders. If you are doing a relative change (like adding write permission for everyone), you can do this:

sudo chmod -R a+w /var/www

But if you want to use the literal permissions of read/write, you may want to select files versus folders:

sudo find /var/www -type f -exec chmod 666 {} \;

(Which, by the way, for security reasons, I wouldn't recommend either of these.)

Or for folders:

sudo find /var/www -type d -exec chmod 755 {} \;

Copying PostgreSQL database to another server

Run this command with database name, you want to backup, to take dump of DB.

 pg_dump -U {user-name} {source_db} -f {dumpfilename.sql}

 eg. pg_dump -U postgres mydbname -f mydbnamedump.sql

Now scp this dump file to remote machine where you want to copy DB.

eg. scp mydbnamedump.sql user01@remotemachineip:~/some/folder/

On remote machine run following command in ~/some/folder to restore the DB.

 psql -U {user-name} -d {desintation_db}-f {dumpfilename.sql}

 eg. psql -U postgres -d mynewdb -f mydbnamedump.sql

Negative regex for Perl string pattern match

If my understanding is correct then you want to match any line which has Clinton and Reagan, in any order, but not Bush. As suggested by Stuck, here is a version with lookahead assertions:

#!/usr/bin/perl

use strict;
use warnings;

my $regex = qr/
    (?=.*clinton)  
    (?!.*bush) 
    .*reagan       
    /ix;

while (<DATA>) {
    chomp;
    next unless (/$regex/);
    print $_, "\n";
}


__DATA__
shouldn't match - reagan came first, then clinton, finally bush
first match - first two: reagan and clinton
second match - first two reverse: clinton and reagan
shouldn't match - last two: clinton and bush
shouldn't match - reverse: bush and clinton
shouldn't match - and then came obama, along comes mary
shouldn't match - to clinton with perl

Results

first match - first two: reagan and clinton
second match - first two reverse: clinton and reagan

as desired it matches any line which has Reagan and Clinton in any order.

You may want to try reading how lookahead assertions work with examples at http://www252.pair.com/comdog/mastering_perl/Chapters/02.advanced_regular_expressions.html

they are very tasty :)

Select a Dictionary<T1, T2> with LINQ

The extensions methods also provide a ToDictionary extension. It is fairly simple to use, the general usage is passing a lambda selector for the key and getting the object as the value, but you can pass a lambda selector for both key and value.

class SomeObject
{
    public int ID { get; set; }
    public string Name { get; set; }
}

SomeObject[] objects = new SomeObject[]
{
    new SomeObject { ID = 1, Name = "Hello" },
    new SomeObject { ID = 2, Name = "World" }
};

Dictionary<int, string> objectDictionary = objects.ToDictionary(o => o.ID, o => o.Name);

Then objectDictionary[1] Would contain the value "Hello"

How to add a class with React.js?

It is simple. take a look at this

https://codepen.io/anon/pen/mepogj?editors=001

basically you want to deal with states of your component so you check the currently active one. you will need to include

getInitialState: function(){}
//and 
isActive: function(){}

check out the code on the link

Disable/Enable Submit Button until all forms have been filled

I just posted this on Disable Submit button until Input fields filled in. Works for me.

Use the form onsubmit. Nice and clean. You don't have to worry about the change and keypress events firing. Don't have to worry about keyup and focus issues.

http://www.w3schools.com/jsref/event_form_onsubmit.asp

<form action="formpost.php" method="POST" onsubmit="return validateCreditCardForm()">
   ...
</form>

function validateCreditCardForm(){
    var result = false;
    if (($('#billing-cc-exp').val().length > 0) &&
        ($('#billing-cvv').val().length  > 0) &&
        ($('#billing-cc-number').val().length > 0)) {
            result = true;
    }
    return result;
}

Git: Merge a Remote branch locally

You can reference those remote tracking branches ~(listed with git branch -r) with the name of their remote.

You need to fetch the remote branch:

git fetch origin aRemoteBranch

If you want to merge one of those remote branches on your local branch:

git checkout master
git merge origin/aRemoteBranch

Note 1: For a large repo with a long history, you will want to add the --depth=1 option when you use git fetch.

Note 2: These commands also work with other remote repos so you can setup an origin and an upstream if you are working on a fork.

Note 3: user3265569 suggests the following alias in the comments:

From aLocalBranch, run git combine remoteBranch
Alias:

combine = !git fetch origin ${1} && git merge origin/${1}

Opposite scenario: If you want to merge one of your local branch on a remote branch (as opposed to a remote branch to a local one, as shown above), you need to create a new local branch on top of said remote branch first:

git checkout -b myBranch origin/aBranch
git merge anotherLocalBranch

The idea here, is to merge "one of your local branch" (here anotherLocalBranch) to a remote branch (origin/aBranch).
For that, you create first "myBranch" as representing that remote branch: that is the git checkout -b myBranch origin/aBranch part.
And then you can merge anotherLocalBranch to it (to myBranch).

How to clear jQuery validation error messages?

None of the above solutions worked for me. I was disappointed at wasting my time on them. However there is an easy solution.

The solution was achieved by comparing the HTML mark up for the valid state and HTML mark up for the error state.

No errors would produce:

        <div class="validation-summary-valid" data-valmsg-summary="true"></div>

when an error occurs this div is populated with the errors and the class is changed to validation-summary-errors:

        <div class="validation-summary-errors" data-valmsg-summary="true"> 

The solution is very simple. Clear the HTML of the div which contains the errors and then change the class back to the valid state.

        $('.validation-summary-errors').html()            
        $('.validation-summary-errors').addClass('validation-summary-valid');
        $('.validation-summary-valid').removeClass('validation-summary-errors');

Happy coding.

How do I search for an object by its ObjectId in the mongo console?

In MongoDB Stitch functions it can be done using BSON like below:

Use the ObjectId helper in the BSON utility package for this purpose like in the follwing example:

var id = "5bb9e9f84186b222c8901149";  
BSON.ObjectId(id);

Best solution to protect PHP code without encryption

They distribute their software under a proprietary license. The law protects their rights and prevents their customers from redistributing the source, though there is no actual difficulty doing so.

But as you might be well aware, copyright infringement (piracy) of software products is a pretty common phenomenon.

Explicit vs implicit SQL joins

Performance wise, it should not make any difference. The explicit join syntax seems cleaner to me as it clearly defines relationships between tables in the from clause and does not clutter up the where clause.

Run a single test method with maven

As of surefire plugin version 2.22.1 (possibly earlier) you can run single test using testnames property when using testng.xml

Given a following testng.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
    <test name="all-tests">
        <classes>
            <class name="server.Atest"/>
            <class name="server.Btest"/>
            <class name="server.Ctest"/>
        </classes>
    </test>
    <test name="run-A-test">
        <classes>
            <class name="server.Atest"/>
        </classes>
    </test>
    <test name="run-B-test">
        <classes>
            <class name="server.Btest"/>
        </classes>
    </test>
    <test name="run-C-test">
        <classes>
            <class name="server.Ctest"/>
        </classes>
    </test>
</suite> 

with the pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    [...]
    <properties>
        <selectedTests>all-tests</selectedTests>
    </properties>
    [...]
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.22.1</version>
            <configuration>
                <suiteXmlFiles>
                    <file>src/test/resources/testng.xml</file>
                </suiteXmlFiles>
                <properties>
                    <property>
                        <name>testnames</name>
                        <value>${selectedTests}</value>
                    </property>
                </properties>
            </configuration>
        </plugin>
    </plugins>
    [...]
</project>

From command line

mvn clean test -DselectedTests=run-B-test

Further reading - Maven surefire plugin using testng

How to read a file byte by byte in Python and how to print a bytelist as a binary?

Late to the party, but this may help anyone looking for a quick solution:

you can use bin(ord('b')).replace('b', '')bin() it gives you the binary representation with a 'b' after the last bit, you have to remove it. Also ord() gives you the ASCII number to the char or 8-bit/1 Byte coded character.

Cheers

jQuery select all except first

_x000D_
_x000D_
$(document).ready(function(){_x000D_
_x000D_
  $(".btn1").click(function(){_x000D_
          $("div.test:not(:first)").hide();_x000D_
  });_x000D_
_x000D_
  $(".btn2").click(function(){_x000D_
           $("div.test").show();_x000D_
          $("div.test:not(:first):not(:last)").hide();_x000D_
  });_x000D_
_x000D_
  $(".btn3").click(function(){_x000D_
          $("div.test").hide();_x000D_
          $("div.test:not(:first):not(:last)").show();_x000D_
  });_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<button class="btn1">Hide All except First</button>_x000D_
<button class="btn2">Hide All except First & Last</button>_x000D_
<button class="btn3">Hide First & Last</button>_x000D_
_x000D_
<br/>_x000D_
_x000D_
<div class='test'>First</div>_x000D_
<div class='test'>Second</div>_x000D_
<div class='test'>Third</div>_x000D_
<div class='test'>Last</div>
_x000D_
_x000D_
_x000D_

How do I find out which process is locking a file using .NET?

This works for DLLs locked by other processes. This routine will not find out for example that a text file is locked by a word process.

C#:

using System.Management; 
using System.IO;   

static class Module1 
{ 
static internal ArrayList myProcessArray = new ArrayList(); 
private static Process myProcess; 

public static void Main() 
{ 

    string strFile = "c:\\windows\\system32\\msi.dll"; 
    ArrayList a = getFileProcesses(strFile); 
    foreach (Process p in a) { 
        Debug.Print(p.ProcessName); 
    } 
} 


private static ArrayList getFileProcesses(string strFile) 
{ 
    myProcessArray.Clear(); 
    Process[] processes = Process.GetProcesses; 
    int i = 0; 
    for (i = 0; i <= processes.GetUpperBound(0) - 1; i++) { 
        myProcess = processes(i); 
        if (!myProcess.HasExited) { 
            try { 
                ProcessModuleCollection modules = myProcess.Modules; 
                int j = 0; 
                for (j = 0; j <= modules.Count - 1; j++) { 
                    if ((modules.Item(j).FileName.ToLower.CompareTo(strFile.ToLower) == 0)) { 
                        myProcessArray.Add(myProcess); 
                        break; // TODO: might not be correct. Was : Exit For 
                    } 
                } 
            } 
            catch (Exception exception) { 
            } 
            //MsgBox(("Error : " & exception.Message)) 
        } 
    } 
    return myProcessArray; 
} 
} 

VB.Net:

Imports System.Management
Imports System.IO

Module Module1
Friend myProcessArray As New ArrayList
Private myProcess As Process

Sub Main()

    Dim strFile As String = "c:\windows\system32\msi.dll"
    Dim a As ArrayList = getFileProcesses(strFile)
    For Each p As Process In a
        Debug.Print(p.ProcessName)
    Next
End Sub


Private Function getFileProcesses(ByVal strFile As String) As ArrayList
    myProcessArray.Clear()
    Dim processes As Process() = Process.GetProcesses
    Dim i As Integer
    For i = 0 To processes.GetUpperBound(0) - 1
        myProcess = processes(i)
        If Not myProcess.HasExited Then
            Try
                Dim modules As ProcessModuleCollection = myProcess.Modules
                Dim j As Integer
                For j = 0 To modules.Count - 1
                    If (modules.Item(j).FileName.ToLower.CompareTo(strFile.ToLower) = 0) Then
                        myProcessArray.Add(myProcess)
                        Exit For
                    End If
                Next j
            Catch exception As Exception
                'MsgBox(("Error : " & exception.Message))
            End Try
        End If
    Next i
    Return myProcessArray
End Function
End Module

jQuery - Dynamically Create Button and Attach Event Handler

Your problem is that you're converting the button into an HTML snippet when you add it to the table, but that snippet is not the same object as the one that has the click handler on it.

$("#myButton").click(function () {
    var test = $('<button>Test</button>').click(function () {
        alert('hi');
    });

    $("#nodeAttributeHeader").css('display', 'table-row'); // NB: changed

    var tr = $('<tr>').insertBefore('#addNodeTable tr:last');
    var td = $('<td>').append(test).appendTo(tr);
});

AndroidStudio: Failed to sync Install build tools

There may be some file access permission/restriction problems. First check to access the below directory manually, check whether your TARGET_VERSION exists, Then check the android sdk manager.

  • sdk/build-tools/{TARGET_VERSION}

How can I add numbers in a Bash script?

You should declare metab as integer and then use arithmetic evaluation

declare -i metab num
...
num+=metab
...

For more information see https://www.gnu.org/software/bash/manual/html_node/Shell-Arithmetic.html#Shell-Arithmetic

How to prompt for user input and read command-line arguments

raw_input is no longer available in Python 3.x. But raw_input was renamed input, so the same functionality exists.

input_var = input("Enter something: ")
print ("you entered " + input_var) 

Documentation of the change

Query-string encoding of a Javascript Object

here is a simple implementation that gets an object and converts it to query params string

export function objectToQueryParams(queryParams: object): string {
  return queryParams ?
    Object.entries(queryParams).reduce((acc, [key, val], index) => {
      const sign = index === 0 ? '?' : '&';
      acc += `${sign}${encodeURIComponent(key)}=${encodeURIComponent(val)}`;
      return acc;
    }, '')
    : '';
}

Remove all special characters from a string

Update

The solution below has a "SEO friendlier" version:

function hyphenize($string) {
    $dict = array(
        "I'm"      => "I am",
        "thier"    => "their",
        // Add your own replacements here
    );
    return strtolower(
        preg_replace(
          array( '#[\\s-]+#', '#[^A-Za-z0-9. -]+#' ),
          array( '-', '' ),
          // the full cleanString() can be downloaded from http://www.unexpectedit.com/php/php-clean-string-of-utf8-chars-convert-to-similar-ascii-char
          cleanString(
              str_replace( // preg_replace can be used to support more complicated replacements
                  array_keys($dict),
                  array_values($dict),
                  urldecode($string)
              )
          )
        )
    );
}

function cleanString($text) {
    $utf8 = array(
        '/[áàâãªä]/u'   =>   'a',
        '/[ÁÀÂÃÄ]/u'    =>   'A',
        '/[ÍÌÎÏ]/u'     =>   'I',
        '/[íìîï]/u'     =>   'i',
        '/[éèêë]/u'     =>   'e',
        '/[ÉÈÊË]/u'     =>   'E',
        '/[óòôõºö]/u'   =>   'o',
        '/[ÓÒÔÕÖ]/u'    =>   'O',
        '/[úùûü]/u'     =>   'u',
        '/[ÚÙÛÜ]/u'     =>   'U',
        '/ç/'           =>   'c',
        '/Ç/'           =>   'C',
        '/ñ/'           =>   'n',
        '/Ñ/'           =>   'N',
        '/–/'           =>   '-', // UTF-8 hyphen to "normal" hyphen
        '/[’‘‹›‚]/u'    =>   ' ', // Literally a single quote
        '/[“”«»„]/u'    =>   ' ', // Double quote
        '/ /'           =>   ' ', // nonbreaking space (equiv. to 0x160)
    );
    return preg_replace(array_keys($utf8), array_values($utf8), $text);
}

The rationale for the above functions (which I find way inefficient - the one below is better) is that a service that shall not be named apparently ran spelling checks and keyword recognition on the URLs.

After losing a long time on a customer's paranoias, I found out they were not imagining things after all -- their SEO experts [I am definitely not one] reported that, say, converting "Viaggi Economy Perù" to viaggi-economy-peru "behaved better" than viaggi-economy-per (the previous "cleaning" removed UTF8 characters; Bogotà became bogot, Medellìn became medelln and so on).

There were also some common misspellings that seemed to influence the results, and the only explanation that made sense to me is that our URL were being unpacked, the words singled out, and used to drive God knows what ranking algorithms. And those algorithms apparently had been fed with UTF8-cleaned strings, so that "Perù" became "Peru" instead of "Per". "Per" did not match and sort of took it in the neck.

In order to both keep UTF8 characters and replace some misspellings, the faster function below became the more accurate (?) function above. $dict needs to be hand tailored, of course.

Previous answer

A simple approach:

// Remove all characters except A-Z, a-z, 0-9, dots, hyphens and spaces
// Note that the hyphen must go last not to be confused with a range (A-Z)
// and the dot, NOT being special (I know. My life was a lie), is NOT escaped

$str = preg_replace('/[^A-Za-z0-9. -]/', '', $str);

// Replace sequences of spaces with hyphen
$str = preg_replace('/  */', '-', $str);

// The above means "a space, followed by a space repeated zero or more times"
// (should be equivalent to / +/)

// You may also want to try this alternative:
$str = preg_replace('/\\s+/', '-', $str);

// where \s+ means "zero or more whitespaces" (a space is not necessarily the
// same as a whitespace) just to be sure and include everything

Note that you might have to first urldecode() the URL, since %20 and + both are actually spaces - I mean, if you have "Never%20gonna%20give%20you%20up" you want it to become Never-gonna-give-you-up, not Never20gonna20give20you20up . You might not need it, but I thought I'd mention the possibility.

So the finished function along with test cases:

function hyphenize($string) {
    return 
    ## strtolower(
          preg_replace(
            array('#[\\s-]+#', '#[^A-Za-z0-9. -]+#'),
            array('-', ''),
        ##     cleanString(
              urldecode($string)
        ##     )
        )
    ## )
    ;
}

print implode("\n", array_map(
    function($s) {
            return $s . ' becomes ' . hyphenize($s);
    },
    array(
    'Never%20gonna%20give%20you%20up',
    "I'm not the man I was",
    "'Légeresse', dit sa majesté",
    )));


Never%20gonna%20give%20you%20up    becomes  never-gonna-give-you-up
I'm not the man I was              becomes  im-not-the-man-I-was
'Légeresse', dit sa majesté        becomes  legeresse-dit-sa-majeste

To handle UTF-8 I used a cleanString implementation found online (link broken since, but a stripped down copy with all the not-too-esoteric UTF8 characters is at the beginning of the answer; it's also easy to add more characters to it if you need) that converts UTF8 characters to normal characters, thus preserving the word "look" as much as possible. It could be simplified and wrapped inside the function here for performance.

The function above also implements converting to lowercase - but that's a taste. The code to do so has been commented out.

python NameError: global name '__file__' is not defined

You will get this if you are running the commands from the python shell:

>>> __file__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '__file__' is not defined

You need to execute the file directly, by passing it in as an argument to the python command:

$ python somefile.py

In your case, it should really be python setup.py install

Comparing strings in C# with OR in an if statement

Try:

    if (textBox1.Text == "" || textBox2.Text == "")
    {
        // do something..
    }

Instead of:

    if (textBox1.Text == string.Empty || textBox2.Text == string.Empty)
    {
        // do something..
    }

Because string.Empty is different than - "".

How to fetch JSON file in Angular 2

Keep the json file in Assets (parallel to app dir) directory

Note that if you would have generated with ng new YourAppname- this assets directory exists same line with 'app' directory, and services should be child directory of app directory. May look like as below:

::app/services/myservice.ts

getOrderSummary(): Observable {
    // get users from api
    return this.http.get('assets/ordersummary.json')//, options)
        .map((response: Response) => {
            console.log("mock data" + response.json());
            return response.json();
        }
    )
    .catch(this.handleError);
} 

Function to clear the console in R and RStudio

In Ubuntu-Gnome, simply pressing CTRL+L should clear the screen.

This also seems to also work well in Windows 10 and 7 and Mac OS X Sierra.

Git ignore file for Xcode projects

I recommend using joe to generate a .gitignore file.

For an iOS project run the following command:

$ joe g osx,xcode > .gitignore

It will generate this .gitignore:

.DS_Store
.AppleDouble
.LSOverride

Icon
._*

.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns

.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk

build/
DerivedData

*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata

*.xccheckout
*.moved-aside
*.xcuserstate

Getting selected value of a combobox

I had a similar error, My Class is

public class ServerInfo
{
    public string Text { get; set; }
    public string Value { get; set; }
    public string PortNo { get; set; }

    public override string ToString()
    {
        return Text;
    }
}

But what I did, I casted my class to the SelectedItem property of the ComboBox. So, i'll have all of the class properties of the selected item.

// Code above
ServerInfo emailServer = (ServerInfo)cbServerName.SelectedItem;

mailClient.ServerName = emailServer.Value;
mailClient.ServerPort = emailServer.PortNo;

I hope this helps someone! Cheers!

HTML list-style-type dash

In my case adding this code to CSS

ul {
    list-style-type: '- ';
}

was enough. Simple as it is.

How to set placeholder value using CSS?

I recently had to do this with google's search box, this is an extreme hack reserved for extreme situations (the resulting selector was slightly different, but I made it work in this example)

_x000D_
_x000D_
/*_x000D_
 this is just used to calculate the resulting svg data url and need not be included in the final page_x000D_
*/_x000D_
_x000D_
var text = placeholder.outerHTML;_x000D_
 var url = "data:image/svg+xml;,"+text.replace(/id="placeholder"/g," ").replace(/\n|([ ] )/g,"");//.replace(/" /g,"\"");_x000D_
img.src = url;_x000D_
result.value = url;_x000D_
overlay.style.backgroundImage = "url('"+url+"')";
_x000D_
svg,img{_x000D_
  border: 3px dashed black;_x000D_
}_x000D_
textarea{_x000D_
width:50%;_x000D_
height:300px;_x000D_
vertical-align: top;_x000D_
}_x000D_
.wrapper{_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
}_x000D_
#overlay{_x000D_
  position:absolute;_x000D_
  left:0;_x000D_
  top:0;_x000D_
  right:0;_x000D_
  bottom:0;_x000D_
  pointer-events: none;_x000D_
  background-repeat: no-repeat;_x000D_
  background-position: center left;_x000D_
}_x000D_
#my_input:focus + #overlay{_x000D_
  display: none;_x000D_
}
_x000D_
As SVG <svg id="placeholder"xmlns="http://www.w3.org/2000/svg"width="235"height="13"><text x="0"y="10"font-family="Verdana"font-size="12" fill ="green">Some New Rad Placeholder</text></svg>_x000D_
<br>_x000D_
As IMG <img id="img">_x000D_
<br>_x000D_
As Data URI <textarea id="result"></textarea><br>_x000D_
_x000D_
As "Placeholder" <div class="wrapper">_x000D_
  <input id="my_input" />_x000D_
  <div id="overlay">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using multiple IF statements in a batch file

The explanation given by Merlyn above is pretty complete. However, I would like to elaborate on coding standards.

When several IF's are chained, the final command is executed when all the previous conditions are meet; this is equivalent to an AND operator. I used this behavior now and then, but I clearly indicate what I intend to do via an auxiliary Batch variable called AND:

SET AND=IF

IF EXIST somefile.txt %AND% EXIST someotherfile.txt SET var=somefile.txt,someotherfile.txt

Of course, this is NOT a true And operator and must not be used in combination with ELSE clause. This is just a programmer aid to increase the legibility of an instruction that is rarely used.

When I write Batch programs I always use several auxiliary variables that I designed with the sole purpose of write more readable code. For example:

SET AND=IF
SET THEN=(
SET ELSE=) ELSE (
SET NOELSE=
SET ENDIF=)
SET BEGIN=(
SET END=)
SET RETURN=EXIT /B

These variables aids in writting Batch programs in a much clearer way and helps to avoid subtle errors, as Merlyn suggested. For example:

IF EXIST "somefile.txt" %THEN%
  IF EXIST "someotherfile.txt" %THEN%
    SET var="somefile.txt,someotherfile.txt"
  %NOELSE%
  %ENDIF%
%NOELSE%
%ENDIF%

IF EXIST "%~1" %THEN%
  SET "result=%~1"
%ELSE%
  SET "result="
%ENDIF%

I even have variables that aids in writting WHILE-DO and REPEAT-UNTIL like constructs. This means that Batch variables may be used in some degree as preprocessor values.

What's the better (cleaner) way to ignore output in PowerShell?

Personally, I use ... | Out-Null because, as others have commented, that looks like the more "PowerShellish" approach compared to ... > $null and [void] .... $null = ... is exploiting a specific automatic variable and can be easy to overlook, whereas the other methods make it obvious with additional syntax that you intend to discard the output of an expression. Because ... | Out-Null and ... > $null come at the end of the expression I think they effectively communicate "take everything we've done up to this point and throw it away", plus you can comment them out easier for debugging purposes (e.g. ... # | Out-Null), compared to putting $null = or [void] before the expression to determine what happens after executing it.

Let's look at a different benchmark, though: not the amount of time it takes to execute each option, but the amount of time it takes to figure out what each option does. Having worked in environments with colleagues who were not experienced with PowerShell or even scripting at all, I tend to try to write my scripts in a way that someone coming along years later that might not even understand the language they're looking at can have a fighting chance at figuring out what it's doing since they might be in a position of having to support or replace it. This has never occurred to me as a reason to use one method over the others until now, but imagine you're in that position and you use the help command or your favorite search engine to try to find out what Out-Null does. You get a useful result immediately, right? Now try to do the same with [void] and $null =. Not so easy, is it?

Granted, suppressing the output of a value is a pretty minor detail compared to understanding the overall logic of a script, and you can only try to "dumb down" your code so much before you're trading your ability to write good code for a novice's ability to read...not-so-good code. My point is, it's possible that some who are fluent in PowerShell aren't even familiar with [void], $null =, etc., and just because those may execute faster or take less keystrokes to type, doesn't mean they're the best way to do what you're trying to do, and just because a language gives you quirky syntax doesn't mean you should use it instead of something clearer and better-known.*

* I am presuming that Out-Null is clear and well-known, which I don't know to be $true. Whichever option you feel is clearest and most accessible to future readers and editors of your code (yourself included), regardless of time-to-type or time-to-execute, that's the option I'm recommending you use.

MySQL: is a SELECT statement case sensitive?

Marc B's answer is mostly correct.

If you are using a nonbinary string (CHAR, VARCHAR, TEXT), comparisons are case-insensitive, per the default collation.

If you are using a binary string (BINARY, VARBINARY, BLOB), comparisons are case-sensitive, so you'll need to use LOWER as described in other answers.

If you are not using the default collation and you are using a nonbinary string, case sensitivity is decided by the chosen collation.

Source: https://dev.mysql.com/doc/refman/8.0/en/case-sensitivity.html. Read closely. Some others have mistaken it to say that comparisons are necessarily case-sensitive or insensitive. This is not the case.

How can I create an observable with a delay

It's little late to answer ... but just in case may be someone return to this question looking for an answer

'delay' is property(function) of an Observable

fakeObservable = Observable.create(obs => {
  obs.next([1, 2, 3]);
  obs.complete();
}).delay(3000);

This worked for me ...

How do I test if a variable is a number in Bash?

I found quite a short version:

function isnum()
{
    return `echo "$1" | awk -F"\n" '{print ($0 != $0+0)}'`
}

Git merge with force overwrite

When I tried using -X theirs and other related command switches I kept getting a merge commit. I probably wasn't understanding it correctly. One easy to understand alternative is just to delete the branch then track it again.

git branch -D <branch-name>
git branch --track <branch-name> origin/<branch-name>

This isn't exactly a "merge", but this is what I was looking for when I came across this question. In my case I wanted to pull changes from a remote branch that were force pushed.

How to remove leading zeros using C#

I just crafted this as I needed a good, simple way.

If it gets to the final digit, and if it is a zero, it will stay.

You could also use a foreach loop instead for super long strings.

I just replace each leading oldChar with the newChar.


This is great for a problem I just solved, after formatting an int into a string.

    /* Like this: */
    int counterMax = 1000;
    int counter = ...;
    string counterString = counter.ToString($"D{counterMax.ToString().Length}");
    counterString = RemoveLeadingChars('0', ' ', counterString);
    string fullCounter = $"({counterString}/{counterMax})";
    // = (   1/1000) ... ( 430/1000) ... (1000/1000)

    static string RemoveLeadingChars(char oldChar, char newChar, char[] chars)
    {
        string result = "";
        bool stop = false;
        for (int i = 0; i < chars.Length; i++)
        {
            if (i == (chars.Length - 1)) stop = true;
            if (!stop && chars[i] == oldChar) chars[i] = newChar;
            else stop = true;
            result += chars[i];
        }
        return result;
    }

    static string RemoveLeadingChars(char oldChar, char newChar, string text)
    {
        return RemoveLeadingChars(oldChar, newChar, text.ToCharArray());
    }

I always tend to make my functions suitable for my own library, so there are options.

Is there a C++ decompiler?

I haven't seen any decompilers that generate C++ code. I've seen a few experimental ones that make a reasonable attempt at generating C code, but they tended to be dependent on matching the code-generation patterns of a particular compiler (that may have changed, it's been awhile since I last looked into this). Of course any symbolic information will be gone. Google for "decompiler".

Iteration ng-repeat only X times in AngularJs

All answers here seem to assume that items is an array. However, in AngularJS, it might as well be an object. In that case, neither filtering with limitTo nor array.slice will work. As one possible solution, you can convert your object to an array, if you don't mind losing the object keys. Here is an example of a filter to do just that:

myFilter.filter('obj2arr', function() {
    return function(obj) {
        if (typeof obj === 'object') {
            var arr = [], i = 0, key;
            for( key in obj ) {
                arr[i] = obj[key];
                i++;
            }
            return arr;
        }
        else {
            return obj;
        }

    };
});

Once it is an array, use slice or limitTo, as stated in other answers.

Aggregate a dataframe on a given column and display another column

This is how I baseically think of the problem.

my.df <- data.frame(group = rep(c(1,2), each = 3), 
        score = runif(6), info = letters[1:6])
my.agg <- with(my.df, aggregate(score, list(group), max))
my.df.split <- with(my.df, split(x = my.df, f = group))
my.agg$info <- unlist(lapply(my.df.split, FUN = function(x) {
            x[which(x$score == max(x$score)), "info"]
        }))

> my.agg
  Group.1         x info
1       1 0.9344336    a
2       2 0.7699763    e

How to show an empty view with a RecyclerView?

For my projects I made this solution (RecyclerView with setEmptyView method):

public class RecyclerViewEmptySupport extends RecyclerView {
    private View emptyView;

    private AdapterDataObserver emptyObserver = new AdapterDataObserver() {


        @Override
        public void onChanged() {
            Adapter<?> adapter =  getAdapter();
            if(adapter != null && emptyView != null) {
                if(adapter.getItemCount() == 0) {
                    emptyView.setVisibility(View.VISIBLE);
                    RecyclerViewEmptySupport.this.setVisibility(View.GONE);
                }
                else {
                    emptyView.setVisibility(View.GONE);
                    RecyclerViewEmptySupport.this.setVisibility(View.VISIBLE);
                }
            }

        }
    };

    public RecyclerViewEmptySupport(Context context) {
        super(context);
    }

    public RecyclerViewEmptySupport(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RecyclerViewEmptySupport(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void setAdapter(Adapter adapter) {
        super.setAdapter(adapter);

        if(adapter != null) {
            adapter.registerAdapterDataObserver(emptyObserver);
        }

        emptyObserver.onChanged();
    }

    public void setEmptyView(View emptyView) {
        this.emptyView = emptyView;
    }
}

And you should use it instead of RecyclerView class:

<com.maff.utils.RecyclerViewEmptySupport android:id="@+id/list1"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    />

<TextView android:id="@+id/list_empty"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Empty"
    />

and

RecyclerViewEmptySupport list = 
    (RecyclerViewEmptySupport)rootView.findViewById(R.id.list1);
list.setLayoutManager(new LinearLayoutManager(context));
list.setEmptyView(rootView.findViewById(R.id.list_empty));

Get list of filenames in folder with Javascript

No, Javascript doesn't have access to the filesystem. Server side Javascript is a whole different story but I guess you don't mean that.

How to mock static methods in c# using MOQ framework?

Moq (and other DynamicProxy-based mocking frameworks) are unable to mock anything that is not a virtual or abstract method.

Sealed/static classes/methods can only be faked with Profiler API based tools, like Typemock (commercial) or Microsoft Moles (free, known as Fakes in Visual Studio 2012 Ultimate /2013 /2015).

Alternatively, you could refactor your design to abstract calls to static methods, and provide this abstraction to your class via dependency injection. Then you'd not only have a better design, it will be testable with free tools, like Moq.

A common pattern to allow testability can be applied without using any tools altogether. Consider the following method:

public class MyClass
{
    public string[] GetMyData(string fileName)
    {
        string[] data = FileUtil.ReadDataFromFile(fileName);
        return data;
    }
}

Instead of trying to mock FileUtil.ReadDataFromFile, you could wrap it in a protected virtual method, like this:

public class MyClass
{
    public string[] GetMyData(string fileName)
    {
        string[] data = GetDataFromFile(fileName);
        return data;
    }

    protected virtual string[] GetDataFromFile(string fileName)
    {
        return FileUtil.ReadDataFromFile(fileName);
    }
}

Then, in your unit test, derive from MyClass and call it TestableMyClass. Then you can override the GetDataFromFile method to return your own test data.

Hope that helps.

Converting from longitude\latitude to Cartesian coordinates

Theory for convert GPS(WGS84) to Cartesian coordinates https://en.wikipedia.org/wiki/Geographic_coordinate_conversion#From_geodetic_to_ECEF_coordinates

The following is what I am using:

  • Longitude in GPS(WGS84) and Cartesian coordinates are the same.
  • Latitude need be converted by WGS 84 ellipsoid parameters semi-major axis is 6378137 m, and
  • Reciprocal of flattening is 298.257223563.

I attached a VB code I wrote:

Imports System.Math

'Input GPSLatitude is WGS84 Latitude,h is altitude above the WGS 84 ellipsoid

Public Function GetSphericalLatitude(ByVal GPSLatitude As Double, ByVal h As Double) As Double

        Dim A As Double = 6378137 'semi-major axis 
        Dim f As Double = 1 / 298.257223563  '1/f Reciprocal of flattening
        Dim e2 As Double = f * (2 - f)
        Dim Rc As Double = A / (Sqrt(1 - e2 * (Sin(GPSLatitude * PI / 180) ^ 2)))
        Dim p As Double = (Rc + h) * Cos(GPSLatitude * PI / 180)
        Dim z As Double = (Rc * (1 - e2) + h) * Sin(GPSLatitude * PI / 180)
        Dim r As Double = Sqrt(p ^ 2 + z ^ 2)
        Dim SphericalLatitude As Double =  Asin(z / r) * 180 / PI
        Return SphericalLatitude
End Function

Please notice that the h is altitude above the WGS 84 ellipsoid.

Usually GPS will give us H of above MSL height. The MSL height has to be converted to height h above the WGS 84 ellipsoid by using the geopotential model EGM96 (Lemoine et al, 1998).
This is done by interpolating a grid of the geoid height file with a spatial resolution of 15 arc-minutes.

Or if you have some level professional GPS has Altitude H (msl,heigh above mean sea level) and UNDULATION,the relationship between the geoid and the ellipsoid (m) of the chosen datum output from internal table. you can get h = H(msl) + undulation

To XYZ by Cartesian coordinates:

x = R * cos(lat) * cos(lon)

y = R * cos(lat) * sin(lon)

z = R *sin(lat)

How to stop a PowerShell script on the first error?

$ErrorActionPreference = "Stop" will get you part of the way there (i.e. this works great for cmdlets).

However for EXEs you're going to need to check $LastExitCode yourself after every exe invocation and determine whether that failed or not. Unfortunately I don't think PowerShell can help here because on Windows, EXEs aren't terribly consistent on what constitutes a "success" or "failure" exit code. Most follow the UNIX standard of 0 indicating success but not all do. Check out the CheckLastExitCode function in this blog post. You might find it useful.

MySQL - Using If Then Else in MySQL UPDATE or SELECT Queries

Here's a query to update a table based on a comparison of another table. If record is not found in tableB, it will update the "active" value to "n". If it's found, will set the value to NULL

UPDATE tableA
LEFT JOIN tableB ON tableA.id = tableB.id
SET active = IF(tableB.id IS NULL, 'n', NULL)";

Hope this helps someone else.

Responsive css background images

Adaptive for square ratio with jQuery

var Height = $(window).height();
var Width = $(window).width();
var HW = Width/Height;

if(HW<1){
      $(".background").css("background-size","auto 100%");
    }
    else if(HW>1){
      $(".background").css("background-size","100% auto");
    }

Check if string begins with something?

Use stringObject.substring

if (pathname.substring(0, 6) == "/sub/1") {
    // ...
}

How can I wait In Node.js (JavaScript)? l need to pause for a period of time

This question is quite old, but recently V8 has added Generators which can accomplish what the OP requested. Generators are generally easiest to use for async interactions with the assistance of a library such as suspend or gen-run.

Here's an example using suspend:

suspend(function* () {
    console.log('Welcome to My Console,');
    yield setTimeout(suspend.resume(), 10000); // 10 seconds pass..
    console.log('Blah blah blah blah extra-blah');
})();

Related reading (by way of shameless self promotion): What's the Big Deal with Generators?.

List all kafka topics

Using Confluent's REST Proxy API:

curl -X GET -H "Accept: application/vnd.kafka.v2+json" localhost:8082/topics 

where localhost:8082 is Kafka Proxy address.

How to get back to the latest commit after checking out a previous commit?

Came across this question just now and have something to add

To go to the most recent commit:

git checkout $(git log --branches -1 --pretty=format:"%H")

Explanation:

git log --branches shows log of commits from all local branches
-1 limit to one commit → most recent commit
--pretty=format:"%H" format to only show commit hash
git checkout $(...) use output of subshell as argument for checkout

Note:

This will result in a detached head though (because we checkout directly to the commit). This can be avoided by extracting the branch name using sed, explained below.


To go to the branch of the most recent commit:

git checkout $(git log --branches -1 --pretty=format:'%D' | sed 's/.*, //g')

Explanation:

git log --branches shows log of commits from all local branches
-1 limit to one commit → most recent commit
--pretty=format:"%D" format to only show ref names
| sed 's/.*, //g' ignore all but the last of multiple refs (*)
git checkout $(...) use output of subshell as argument for checkout

*) HEAD and remote branches are listed first, local branches are listed last in alphabetically descending order, so the one remaining will be the alphabetically first branch name

Note:

This will always only use the (alphabetically) first branch name if there are multiple for that commit.


Anyway, I think the best solution would just be to display the ref names for the most recent commit to know where to checkout to:

git log --branches -1 --pretty=format:'%D'

E.g. create the alias git top for that command.

How to resolve the error on 'react-native start'

[Quick Answer]

There are a problem with Metro using some NPM and Node versions.

You can fix the problem changing some code in the file \node_modules\metro-config\src\defaults\blacklist.js .

Search this variable:

var sharedBlacklist = [
  /node_modules[/\\]react[/\\]dist[/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/
];

and change to this:

var sharedBlacklist = [
  /node_modules[\/\\]react[\/\\]dist[\/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/
];

Please note that if you run an npm install or a yarn install you need to change the code again.

Missing artifact com.sun:tools:jar

After struggling for a while I finally got this to work with eclipse.ini instead of the command line. After finally reading the documentation I realized that the -vm argument must be on a separate line, unquoted, and ahead of any -vmargs:

-vm
C:\Program Files\Java\jdk1.7.0_45\bin\javaw.exe

How to add a href link in PHP?

There is no need to invoke PHP for this. Just put it directly into the HTML:

<a href="http://www.example.com/">...

Bootstrap4 adding scrollbar to div

Use the overflow-y: scroll property on the element that contains the elements.

The overflow-y property specifies whether to clip the content, add a scroll bar, or display overflow content of a block-level element, when it overflows at the top and bottom edges.

Sometimes it is interesting to place a height for the element next to the overflow-y property, as in the example below:

<ul class="nav nav-pills nav-stacked" style="height: 250px; overflow-y: scroll;">
  <li class="nav-item">
    <a class="nav-link active" href="#">Active</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="#">Link</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="#">Link</a>
  </li>
  <li class="nav-item">
    <a class="nav-link disabled" href="#">Disabled</a>
  </li>
</ul>

What is the meaning of "this" in Java?

Quoting an article at programming.guide:


this has two uses in a Java program.

1. As a reference to the current object

The syntax in this case usually looks something like

this.someVariable = someVariable;

This type of use is described here: The 'this' reference (with examples)

2. To call a different constructor

The syntax in this case typically looks something like

MyClass() {
    this(DEFAULT_VALUE); // delegate to other constructor
}

MyClass(int value) {
    // ...
}

This type of use is described here: this(…) constructor call (with examples)

Xcode "Device Locked" When iPhone is unlocked

All the previous solutions didn't work.

Finlay, changing the iPhone's cable solved the problem.

How to solve "java.io.IOException: error=12, Cannot allocate memory" calling Runtime#exec()?

overcommit_memory

Controls overcommit of system memory, possibly allowing processes to allocate (but not use) more memory than is actually available.

0 - Heuristic overcommit handling. Obvious overcommits of address space are refused. Used for a typical system. It ensures a seriously wild allocation fails while allowing overcommit to reduce swap usage. root is allowed to allocate slighly more memory in this mode. This is the default.

1 - Always overcommit. Appropriate for some scientific applications.

2 - Don't overcommit. The total address space commit for the system is not permitted to exceed swap plus a configurable percentage (default is 50) of physical RAM. Depending on the percentage you use, in most situations this means a process will not be killed while attempting to use already-allocated memory but will receive errors on memory allocation as appropriate.

How is a tag different from a branch in Git? Which should I use, here?

Tags can be either signed or unsigned; branches are never signed.

Signed tags can never move because they are cryptographically bound (with a signature) to a particular commit. Unsigned tags are not bound and it is possible to move them (but moving tags is not a normal use case).

Branches can not only move to a different commit but are expected to do so. You should use a branch for your local development project. It doesn't quite make sense to commit work to a Git repository "on a tag".

How do I add a submodule to a sub-directory?

For those of you who share my weird fondness of manually editing config files, adding (or modifying) the following would also do the trick.

.git/config (personal config)

[submodule "cookbooks/apt"]
    url = https://github.com/opscode-cookbooks/apt

.gitmodules (committed shared config)

[submodule "cookbooks/apt"]
    path = cookbooks/apt
    url = https://github.com/opscode-cookbooks/apt

See this as well - difference between .gitmodules and specifying submodules in .git/config?

How to fix HTTP 404 on Github Pages?

I had the same issue after forking a repo with a gh-pages branch. I was able to fix by simply pushing a new commit (just whitespace in index.html) to my fork's gh-pages branch.

Can't clone a github repo on Linux via HTTPS

This is the dumbest answer to this question, but check the status of GitHub. This one got me :)

MySQL: When is Flush Privileges in MySQL really needed?

TL;DR

You should use FLUSH PRIVILEGES; only if you modify the grant tables directly using statements such as INSERT, UPDATE, or DELETE.

Trying to handle "back" navigation button action in iOS

None of the other solutions worked for me, but this does:

Create your own subclass of UINavigationController, make it implement the UINavigationBarDelegate (no need to manually set the navigation bar's delegate), add a UIViewController extension that defines a method to be called on a back button press, and then implement this method in your UINavigationController subclass:

func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {
    self.topViewController?.methodToBeCalledOnBackButtonPress()
    self.popViewController(animated: true)
    return true
}

AngularJS How to dynamically add HTML and bind to controller

See if this example provides any clarification. Basically you configure a set of routes and include partial templates based on the route. Setting ng-view in your main index.html allows you to inject those partial views.

The config portion looks like this:

  .config(['$routeProvider', function($routeProvider) {
    $routeProvider
      .when('/', {controller:'ListCtrl', templateUrl:'list.html'})
      .otherwise({redirectTo:'/'});
  }])

The point of entry for injecting the partial view into your main template is:

<div class="container" ng-view=""></div>

Create two blank lines in Markdown

For an empty line in Markdown, escape a space (\ ), and then add a new line.

Example:

"\

"

Remember: escape a space and escape a new line. That way is Markdown compliant and should compile properly in any compiler. You may have to select the example text to see how it is set up.

Best way to test exceptions with Assert to ensure they will be thrown

Now, 2017, you can do it easier with the new MSTest V2 Framework:

Assert.ThrowsException<Exception>(() => myClass.MyMethodWithError());

//async version
await Assert.ThrowsExceptionAsync<SomeException>(
  () => myObject.SomeMethodAsync()
);

Pass correct "this" context to setTimeout callback?

If you're using underscore, you can use bind.

E.g.

if (this.options.destroyOnHide) {
     setTimeout(_.bind(this.tip.destroy, this), 1000);
}

Set Radiobuttonlist Selected from Codebehind

We can change the item by value, here is the trick:

radio1.ClearSelection();
radio1.Items.FindByValue("1").Selected = true;// 1 is the value of option2

Can I do Android Programming in C++, C?

You can use the Android NDK, but answers should note that the Android NDK app is not free to use and there's no clear open source route to programming Android on Android in an increasingly Android-driven market that began as open source, with Android developer support or the extensiveness of the NDK app, meaning you're looking at abandoning Android as any kind of first steps programming platform without payments.

Note: I consider subscription requests as payments under duress and this is a freemium context which continues to go undefeated by the open source community.

Passing struct to function

When passing a struct to another function, it would usually be better to do as Donnell suggested above and pass it by reference instead.

A very good reason for this is that it makes things easier if you want to make changes that will be reflected when you return to the function that created the instance of it.

Here is an example of the simplest way to do this:

#include <stdio.h>

typedef struct student {
    int age;
} student;

void addStudent(student *s) {
    /* Here we can use the arrow operator (->) to dereference 
       the pointer and access any of it's members: */
    s->age = 10;
}

int main(void) {

    student aStudent = {0};     /* create an instance of the student struct */
    addStudent(&aStudent);      /* pass a pointer to the instance */

    printf("%d", aStudent.age);

    return 0;
}

In this example, the argument for the addStudent() function is a pointer to an instance of a student struct - student *s. In main(), we create an instance of the student struct and then pass a reference to it to our addStudent() function using the reference operator (&).

In the addStudent() function we can make use of the arrow operator (->) to dereference the pointer, and access any of it's members (functionally equivalent to: (*s).age).

Any changes that we make in the addStudent() function will be reflected when we return to main(), because the pointer gave us a reference to where in the memory the instance of the student struct is being stored. This is illustrated by the printf(), which will output "10" in this example.

Had you not passed a reference, you would actually be working with a copy of the struct you passed in to the function, meaning that any changes would not be reflected when you return to main - unless you implemented a way of passing the new version of the struct back to main or something along those lines!

Although pointers may seem off-putting at first, once you get your head around how they work and why they are so handy they become second nature, and you wonder how you ever coped without them!

Apple Mach-O Linker Error when compiling for device

I had the same Problem, As I was dragging some files .h and .m into my Project and Xcode started showing me this error clang: error: linker command failed with exit code 1 (use -v to see invocation) while running.

Later I discovered that I already have that .h & .m in my Xcode Project under some other SubFolder. So I deleted that Extra .h and .m , Cleaned my Project and Its working now.

clang: error: linker command failed with exit code 1 (use -v to see invocation) This error comes for a number of reason, Thats why this Question has so many Answers. You just need to see & check; what case you fall in.

how to include glyphicons in bootstrap 3

I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.

Bootstrap requires a specific file structure to work. I see from your code you have this:

<link href="bootstrap.css" rel="stylesheet" media="screen">

Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.

But first, let me recommend you setup your folder structure like so:

/css      <-- Bootstrap.css here
/fonts    <-- Bootstrap fonts here
/img
/js       <-- Bootstrap JavaScript here
index.html

If you notice, this is also how Bootstrap structures its files in its download ZIP.

You then include your Bootstrap file like so:

<link href="css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">

Depending on your server structure or what you're going for.

The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).

The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.

So, why do this?

Bootstrap.css has this specific line for Glyphfonts:

@font-face {
    font-family: 'Glyphicons Halflings';
    src: url('../fonts/glyphicons-halflings-regular.eot');
    src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}

What you can see is that that Glyphfonts are loaded by going up one directory ../ and then looking for a folder called /fonts and THEN loading the font file.

The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:

/fonts
Bootstrap.css
index.html

The CSS file is going one level deeper than looking for a /fonts folder.

So, let's say the actual location of these files are:

C:\www\fonts
C:\www\Boostrap.css
C:\www\index.html

The CSS file would technically be looking for a folder at:

C:\fonts

but your folder is actually in:

C:\www\fonts

So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.

When you get that fixed, your HTML should simply be:

<span class="glyphicon glyphicon-comment"></span>

Note, you need both classes. The first class glyphicon sets up the basic styles while glyphicon-comment sets the specific image.

HRESULT: 0x800A03EC on Worksheet.range

I've come across it several different times and every time it was always some error with either duplicating a tab name or in this current case it just occurred because I simply had a typo in the get_Range where I tried to get a Cell by number and number instead of the letter and number.
Drove me crazy because the error pointed me to a few lines down but I had commented out all of the creation of the other sheets above the "error line" and the ones in the line and below were created with no issue.
Happened to scan up a few lines above and saw that I put 6 + lastword, C + lastrow in my get_Range statement and of course you can't have a cell starting with a number it's always letter than number.

Specify sudo password for Ansible

After five years, I can see this is still a very relevant subject. Somewhat mirroring leucos's answer which I find the best in my case, using ansible tools only (without any centralised authentication, tokens or whatever). This assumes you have the same username and the same public key on all servers. If you don't, of course you'd need to be more specific and add the corresponding variables next to the hosts:

[all:vars]
ansible_ssh_user=ansible
ansible_ssh_private_key_file=home/user/.ssh/mykey
[group]
192.168.0.50 ansible_sudo_pass='{{ myserver_sudo }}'

ansible-vault create mypasswd.yml
ansible-vault edit mypasswd.yml

Add:

myserver_sudo: mysecretpassword

Then:

ansible-playbook -i inv.ini my_role.yml --ask-vault --extra-vars '@passwd.yml'

At least this way you don't have to write more the variables which point to the passwords.

enumerate() for dictionary in python

Python3:

One solution:

enumm = {0: 1, 1: 2, 2: 3, 4: 4, 5: 5, 6: 6, 7: 7}
for i, k in enumerate(enumm):
    print("{}) d.key={}, d.value={}".format(i, k, enumm[k]))

Output:
0) enumm.key=0, enumm.value=1
1) enumm.key=1, enumm.value=2
2) enumm.key=2, enumm.value=3
3) enumm.key=4, enumm.value=4
4) enumm.key=5, enumm.value=5
5) enumm.key=6, enumm.value=6
6) enumm.key=7, enumm.value=7

An another example:

d = {1 : {'a': 1, 'b' : 2, 'c' : 3},
     2 : {'a': 10, 'b' : 20, 'c' : 30}
    }    
for i, k in enumerate(d):
        print("{}) key={}, value={}".format(i, k, d[k])

Output:    
    0) key=1, value={'a': 1, 'b': 2, 'c': 3}
    1) key=2, value={'a': 10, 'b': 20, 'c': 30}

Regex Letters, Numbers, Dashes, and Underscores

Just escape the dashes to prevent them from being interpreted (I don't think underscore needs escaping, but it can't hurt). You don't say which regex you are using.

([A-Za-z0-9\-\_]+)

Line Break in HTML Select Option?

How about putting the long text in another <option> right below and disabling it? Might be a workaround for someone so posting here.

_x000D_
_x000D_
        <select>_x000D_
            <option>My real option text</option>_x000D_
            <option disabled style="font-style:italic">&nbsp;&nbsp;&nbsp;(...and my really really long option text that is basically a continuation of previous option)</option> _x000D_
            <option disabled style="font-style:italic">&nbsp;&nbsp;&nbsp;(...and still continuing my previous option)</option> _x000D_
            <option>Another real option text</option>_x000D_
        </select>
_x000D_
_x000D_
_x000D_

ng-repeat :filter by single field

Specify the property (i.e. colour) where you want the filter to be applied:

<div ng-repeat="product in products | filter:{ colour: by_colour }">

Query for documents where array size is greater than 1

Although the above answers all work, What you originally tried to do was the correct way, however you just have the syntax backwards (switch "$size" and "$gt")..

Correct:

db.collection.find({items: {$gt: {$size: 1}}})

Incorrect:

db.collection.find({items: {$size: {$gt: 1}}})

failed to open stream: No such file or directory in

Failed to open stream error occurs because the given path is wrong such as:

$uploadedFile->saveAs(Yii::app()->request->baseUrl.'/images/'.$model->user_photo);

It will give an error if the images folder will not allow you to store images, be sure your folder is readable

Using AJAX to pass variable to PHP and retrieve those using AJAX again

Use dataType:"json" for json data

$.ajax({
     url: 'ajax.php', //This is the current doc
     type: "POST",
     dataType:'json', // add json datatype to get json
     data: ({name: 145}),
     success: function(data){
         console.log(data);
     }
});  

Read Docs http://api.jquery.com/jQuery.ajax/

Also in PHP

<?php
  $userAnswer = $_POST['name']; 
  $sql="SELECT * FROM <tablename> where color='".$userAnswer."'" ;
  $result=mysql_query($sql);
  $row=mysql_fetch_array($result);
  // for first row only and suppose table having data
  echo json_encode($row);  // pass array in json_encode  
?>

Python: slicing a multi-dimensional array

If you use numpy, this is easy:

slice = arr[:2,:2]

or if you want the 0's,

slice = arr[0:2,0:2]

You'll get the same result.

*note that slice is actually the name of a builtin-type. Generally, I would advise giving your object a different "name".


Another way, if you're working with lists of lists*:

slice = [arr[i][0:2] for i in range(0,2)]

(Note that the 0's here are unnecessary: [arr[i][:2] for i in range(2)] would also work.).

What I did here is that I take each desired row 1 at a time (arr[i]). I then slice the columns I want out of that row and add it to the list that I'm building.

If you naively try: arr[0:2] You get the first 2 rows which if you then slice again arr[0:2][0:2], you're just slicing the first two rows over again.

*This actually works for numpy arrays too, but it will be slow compared to the "native" solution I posted above.

Sass - Converting Hex to RGBa for background opacity

you can try this solution, is the best... url(github)

// Transparent Background
// From: http://stackoverflow.com/questions/6902944/sass-mixin-for-background-transparency-back-to-ie8

// Extend this class to save bytes
.transparent-background {
  background-color: transparent;
  zoom: 1;
}

// The mixin
@mixin transparent($color, $alpha) {
  $rgba: rgba($color, $alpha);
  $ie-hex-str: ie-hex-str($rgba);
  @extend .transparent-background;
  background-color: $rgba;
  filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#{$ie-hex-str},endColorstr=#{$ie-hex-str});
}

// Loop through opacities from 90 to 10 on an alpha scale
@mixin transparent-shades($name, $color) {
  @each $alpha in 90, 80, 70, 60, 50, 40, 30, 20, 10 {
    .#{$name}-#{$alpha} {
      @include transparent($color, $alpha / 100);
    }
  }
}

// Generate semi-transparent backgrounds for the colors we want
@include transparent-shades('dark', #000000);
@include transparent-shades('light', #ffffff);

Type converting slices of interfaces

In case you need more shorting your code, you can creating new type for helper

type Strings []string

func (ss Strings) ToInterfaceSlice() []interface{} {
    iface := make([]interface{}, len(ss))
    for i := range ss {
        iface[i] = ss[i]
    }
    return iface
}

then

a := []strings{"a", "b", "c", "d"}
sliceIFace := Strings(a).ToInterfaceSlice()

Convert JavaScript String to be all lower case?

Try

<input type="text" style="text-transform: uppercase">  //uppercase
<input type="text" style="text-transform: lowercase">  //lowercase

Demo - JSFiddle

Kill python interpeter in linux from the terminal

You can try the killall command:

killall python

How do you create an asynchronous method in C#?

If you didn't want to use async/await inside your method, but still "decorate" it so as to be able to use the await keyword from outside, TaskCompletionSource.cs:

public static Task<T> RunAsync<T>(Func<T> function)
{ 
    if (function == null) throw new ArgumentNullException(“function”); 
    var tcs = new TaskCompletionSource<T>(); 
    ThreadPool.QueueUserWorkItem(_ =>          
    { 
        try 
        {  
           T result = function(); 
           tcs.SetResult(result);  
        } 
        catch(Exception exc) { tcs.SetException(exc); } 
   }); 
   return tcs.Task; 
}

From here and here

To support such a paradigm with Tasks, we need a way to retain the Task façade and the ability to refer to an arbitrary asynchronous operation as a Task, but to control the lifetime of that Task according to the rules of the underlying infrastructure that’s providing the asynchrony, and to do so in a manner that doesn’t cost significantly. This is the purpose of TaskCompletionSource.

I saw it's also used in the .NET source, e.g. WebClient.cs:

    [HostProtection(ExternalThreading = true)]
    [ComVisible(false)]
    public Task<string> UploadStringTaskAsync(Uri address, string method, string data)
    {
        // Create the task to be returned
        var tcs = new TaskCompletionSource<string>(address);

        // Setup the callback event handler
        UploadStringCompletedEventHandler handler = null;
        handler = (sender, e) => HandleCompletion(tcs, e, (args) => args.Result, handler, (webClient, completion) => webClient.UploadStringCompleted -= completion);
        this.UploadStringCompleted += handler;

        // Start the async operation.
        try { this.UploadStringAsync(address, method, data, tcs); }
        catch
        {
            this.UploadStringCompleted -= handler;
            throw;
        }

        // Return the task that represents the async operation
        return tcs.Task;
    }

Finally, I also found the following useful:

I get asked this question all the time. The implication is that there must be some thread somewhere that’s blocking on the I/O call to the external resource. So, asynchronous code frees up the request thread, but only at the expense of another thread elsewhere in the system, right? No, not at all.

To understand why asynchronous requests scale, I’ll trace a (simplified) example of an asynchronous I/O call. Let’s say a request needs to write to a file. The request thread calls the asynchronous write method. WriteAsync is implemented by the Base Class Library (BCL), and uses completion ports for its asynchronous I/O. So, the WriteAsync call is passed down to the OS as an asynchronous file write. The OS then communicates with the driver stack, passing along the data to write in an I/O request packet (IRP).

This is where things get interesting: If a device driver can’t handle an IRP immediately, it must handle it asynchronously. So, the driver tells the disk to start writing and returns a “pending” response to the OS. The OS passes that “pending” response to the BCL, and the BCL returns an incomplete task to the request-handling code. The request-handling code awaits the task, which returns an incomplete task from that method and so on. Finally, the request-handling code ends up returning an incomplete task to ASP.NET, and the request thread is freed to return to the thread pool.

Introduction to Async/Await on ASP.NET

If the target is to improve scalability (rather than responsiveness), it all relies on the existence of an external I/O that provides the opportunity to do that.

jQuery .each() index?

jQuery takes care of this for you. The first argument to your .each() callback function is the index of the current iteration of the loop. The second being the current matched DOM element So:

$('#list option').each(function(index, element){
  alert("Iteration: " + index)
});

How to get milliseconds from LocalDateTime in Java 8

To get the current time in milliseconds (since the epoch), use System.currentTimeMillis().

Why is there no Char.Empty like String.Empty?

If you want to eliminate the empty char in string, the following will work. Just convert to any datatype representation you want.

private void button1_Click(object sender, EventArgs e)
{

    Int32 i;

    String name;

    Int32[] array_number = new int[100];

    name = "1 3  5  17   8    9    6";

    name = name.Replace(' ', 'x');

    char[] chr = name.ToCharArray();


    for (i = 0; i < name.Length; i++)
    {
        if ((chr[i] != 'x'))
        {
            array_number[i] = Convert.ToInt32(chr[i].ToString());
            MessageBox.Show(array_number[i].ToString());
        }
    }
}

How can I undo a mysql statement that I just executed?

in case you do not only need to undo your last query (although your question actually only points on that, I know) and therefore if a transaction might not help you out, you need to implement a workaround for this:

copy the original data before commiting your query and write it back on demand based on the unique id that must be the same in both tables; your rollback-table (with the copies of the unchanged data) and your actual table (containing the data that should be "undone" than). for databases having many tables, one single "rollback-table" containing structured dumps/copies of the original data would be better to use then one for each actual table. it would contain the name of the actual table, the unique id of the row, and in a third field the content in any desired format that represents the data structure and values clearly (e.g. XML). based on the first two fields this third one would be parsed and written back to the actual table. a fourth field with a timestamp would help cleaning up this rollback-table.

since there is no real undo in SQL-dialects despite "rollback" in a transaction (please correct me if I'm wrong - maybe there now is one), this is the only way, I guess, and you have to write the code for it on your own.

What does Statement.setFetchSize(nSize) method really do in SQL Server JDBC driver?

The fetchSize parameter is a hint to the JDBC driver as to many rows to fetch in one go from the database. But the driver is free to ignore this and do what it sees fit. Some drivers, like the Oracle one, fetch rows in chunks, so you can read very large result sets without needing lots of memory. Other drivers just read in the whole result set in one go, and I'm guessing that's what your driver is doing.

You can try upgrading your driver to the SQL Server 2008 version (which might be better), or the open-source jTDS driver.

Changing precision of numeric column in Oracle

Assuming that you didn't set a precision initially, it's assumed to be the maximum (38). You're reducing the precision because you're changing it from 38 to 14.

The easiest way to handle this is to rename the column, copy the data over, then drop the original column:

alter table EVAPP_FEES rename column AMOUNT to AMOUNT_OLD;

alter table EVAPP_FEES add AMOUNT NUMBER(14,2);

update EVAPP_FEES set AMOUNT = AMOUNT_OLD;

alter table EVAPP_FEES drop column AMOUNT_OLD;

If you really want to retain the column ordering, you can move the data twice instead:

alter table EVAPP_FEES add AMOUNT_TEMP NUMBER(14,2);

update EVAPP_FEES set AMOUNT_TEMP = AMOUNT;

update EVAPP_FEES set AMOUNT = null;

alter table EVAPP_FEES modify AMOUNT NUMBER(14,2);

update EVAPP_FEES set AMOUNT = AMOUNT_TEMP;

alter table EVAPP_FEES drop column AMOUNT_TEMP;

PHP function to build query string from array

Implode will combine an array into a string for you, but to make an SQL query out a kay/value pair you'll have to write your own function.

Display all post meta keys and meta values of the same post ID in wordpress

WordPress have the function get_metadata this get all meta of object (Post, term, user...)

Just use

get_metadata( 'post', 15 );

Tools to selectively Copy HTML+CSS+JS From A Specific Element of DOM

I've created this tool years ago for the same purpose:
http://www.betterprogramming.com/htmlclipper.html

You're welcome to use and improve upon it.

How to get WooCommerce order details

WOOCOMMERCE ORDERS IN VERSION 3.0+

Since Woocommerce mega major Update 3.0+ things have changed quite a lot:

Related:
How to get Customer details from Order in WooCommerce?
Get Order items and WC_Order_Item_Product in WooCommerce 3

So the Order items properties will not be accessible as before in a foreach loop and you will have to use these specific getter and setter methods instead.

Using some WC_Order and WC_Abstract_Order methods (example):

// Get an instance of the WC_Order object (same as before)
$order = wc_get_order( $order_id );

$order_id  = $order->get_id(); // Get the order ID
$parent_id = $order->get_parent_id(); // Get the parent order ID (for subscriptions…)

$user_id   = $order->get_user_id(); // Get the costumer ID
$user      = $order->get_user(); // Get the WP_User object

$order_status  = $order->get_status(); // Get the order status (see the conditional method has_status() below)
$currency      = $order->get_currency(); // Get the currency used  
$payment_method = $order->get_payment_method(); // Get the payment method ID
$payment_title = $order->get_payment_method_title(); // Get the payment method title
$date_created  = $order->get_date_created(); // Get date created (WC_DateTime object)
$date_modified = $order->get_date_modified(); // Get date modified (WC_DateTime object)

$billing_country = $order->get_billing_country(); // Customer billing country

// ... and so on ...

For order status as a conditional method (where "the_targeted_status" need to be defined and replaced by an order status to target a specific order status):

if ( $order->has_status('completed') ) {
    // Do something
}

Get and access to the order data properties (in an array of values):

// Get an instance of the WC_Order object
$order = wc_get_order( $order_id );

$order_data = $order->get_data(); // The Order data

$order_id = $order_data['id'];
$order_parent_id = $order_data['parent_id'];
$order_status = $order_data['status'];
$order_currency = $order_data['currency'];
$order_version = $order_data['version'];
$order_payment_method = $order_data['payment_method'];
$order_payment_method_title = $order_data['payment_method_title'];
$order_payment_method = $order_data['payment_method'];
$order_payment_method = $order_data['payment_method'];

## Creation and modified WC_DateTime Object date string ##

// Using a formated date ( with php date() function as method)
$order_date_created = $order_data['date_created']->date('Y-m-d H:i:s');
$order_date_modified = $order_data['date_modified']->date('Y-m-d H:i:s');

// Using a timestamp ( with php getTimestamp() function as method)
$order_timestamp_created = $order_data['date_created']->getTimestamp();
$order_timestamp_modified = $order_data['date_modified']->getTimestamp();

$order_discount_total = $order_data['discount_total'];
$order_discount_tax = $order_data['discount_tax'];
$order_shipping_total = $order_data['shipping_total'];
$order_shipping_tax = $order_data['shipping_tax'];
$order_total = $order_data['total'];
$order_total_tax = $order_data['total_tax'];
$order_customer_id = $order_data['customer_id']; // ... and so on

## BILLING INFORMATION:

$order_billing_first_name = $order_data['billing']['first_name'];
$order_billing_last_name = $order_data['billing']['last_name'];
$order_billing_company = $order_data['billing']['company'];
$order_billing_address_1 = $order_data['billing']['address_1'];
$order_billing_address_2 = $order_data['billing']['address_2'];
$order_billing_city = $order_data['billing']['city'];
$order_billing_state = $order_data['billing']['state'];
$order_billing_postcode = $order_data['billing']['postcode'];
$order_billing_country = $order_data['billing']['country'];
$order_billing_email = $order_data['billing']['email'];
$order_billing_phone = $order_data['billing']['phone'];

## SHIPPING INFORMATION:

$order_shipping_first_name = $order_data['shipping']['first_name'];
$order_shipping_last_name = $order_data['shipping']['last_name'];
$order_shipping_company = $order_data['shipping']['company'];
$order_shipping_address_1 = $order_data['shipping']['address_1'];
$order_shipping_address_2 = $order_data['shipping']['address_2'];
$order_shipping_city = $order_data['shipping']['city'];
$order_shipping_state = $order_data['shipping']['state'];
$order_shipping_postcode = $order_data['shipping']['postcode'];
$order_shipping_country = $order_data['shipping']['country'];

Get the order items and access the data with WC_Order_Item_Product and WC_Order_Item methods:

// Get an instance of the WC_Order object
$order = wc_get_order($order_id);

// Iterating through each WC_Order_Item_Product objects
foreach ($order->get_items() as $item_key => $item ):

    ## Using WC_Order_Item methods ##

    // Item ID is directly accessible from the $item_key in the foreach loop or
    $item_id = $item->get_id();

    ## Using WC_Order_Item_Product methods ##

    $product      = $item->get_product(); // Get the WC_Product object

    $product_id   = $item->get_product_id(); // the Product id
    $variation_id = $item->get_variation_id(); // the Variation id

    $item_type    = $item->get_type(); // Type of the order item ("line_item")

    $item_name    = $item->get_name(); // Name of the product
    $quantity     = $item->get_quantity();  
    $tax_class    = $item->get_tax_class();
    $line_subtotal     = $item->get_subtotal(); // Line subtotal (non discounted)
    $line_subtotal_tax = $item->get_subtotal_tax(); // Line subtotal tax (non discounted)
    $line_total        = $item->get_total(); // Line total (discounted)
    $line_total_tax    = $item->get_total_tax(); // Line total tax (discounted)

    ## Access Order Items data properties (in an array of values) ##
    $item_data    = $item->get_data();

    $product_name = $item_data['name'];
    $product_id   = $item_data['product_id'];
    $variation_id = $item_data['variation_id'];
    $quantity     = $item_data['quantity'];
    $tax_class    = $item_data['tax_class'];
    $line_subtotal     = $item_data['subtotal'];
    $line_subtotal_tax = $item_data['subtotal_tax'];
    $line_total        = $item_data['total'];
    $line_total_tax    = $item_data['total_tax'];

    // Get data from The WC_product object using methods (examples)
    $product        = $item->get_product(); // Get the WC_Product object

    $product_type   = $product->get_type();
    $product_sku    = $product->get_sku();
    $product_price  = $product->get_price();
    $stock_quantity = $product->get_stock_quantity();

endforeach;

So using get_data() method allow us to access to the protected data (associative array mode) …

invalid types 'int[int]' for array subscript

What to change? Aside from the 3 or 4 dimensional array problem, you should get rid of the magic numbers (10 and 9).

const int DIM_SIZE = 10;
int myArray[DIM_SIZE][DIM_SIZE][DIM_SIZE];

for (int i = 0; i < DIM_SIZE; ++i){
    for (int t = 0; t < DIM_SIZE; ++t){            
        for (int x = 0; x < DIM_SIZE; ++x){

HTML select dropdown list

I'm sorry to necro an old post - but I found a better way of doing this

What I believe this poster wanted was :

<label for="mydropdown" datalabel="mydropdown">Country:</label>    
<select name="mydropdown">
    <option value="United States">United States</option>
    <option value="Canada">Canada</option>
    <option value="Mexico">Mexico</option>
    <option value="Other">Not Listed</option>
</select>

I found this information in another post while searching for this same answer - Thanks

Number format in excel: Showing % value without multiplying with 100

In Excel workbook - Select the Cell-goto Format Cells - Number - Custom - in the Type box type as shows (0.00%)

Get the second largest number in a list in linear time

Max out the value by comparing each one to the max_item. In the first if, every time the value of max_item changes it gives its previous value to second_max. To tightly couple the two second if ensures the boundary

def secondmax(self, list):
    max_item = list[0]
    second_max = list[1]
    for item in list:
        if item > max_item:
            second_max =  max_item
            max_item = item
        if max_item < second_max:
            max_item = second_max
    return second_max

Django request.GET

from django.http import QueryDict

def search(request):
if request.GET.\__contains__("q"):
    message = 'You submitted: %r' % request.GET['q']
else:
    message = 'You submitted nothing!'
return HttpResponse(message)

Use this way, django offical document recommended __contains__ method. See https://docs.djangoproject.com/en/1.9/ref/request-response/

Fixed position but relative to container

Actually this is possible and the accepted answer only deals with centralising, which is straightforward enough. Also you really don't need to use JavaScript.

This will let you deal with any scenario:

Set everything up as you would if you want to position: absolute inside a position: relative container, and then create a new fixed position div inside the div with position: absolute, but do not set its top and left properties. It will then be fixed wherever you want it, relative to the container.

For example:

_x000D_
_x000D_
/* Main site body */_x000D_
.wrapper {_x000D_
    width: 940px;_x000D_
    margin: 0 auto;_x000D_
    position: relative; /* Ensure absolute positioned child elements are relative to this*/_x000D_
}_x000D_
_x000D_
/* Absolute positioned wrapper for the element you want to fix position */_x000D_
.fixed-wrapper {_x000D_
    width: 220px;_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    left: -240px; /* Move this out to the left of the site body, leaving a 20px gutter */_x000D_
}_x000D_
_x000D_
/* The element you want to fix the position of */_x000D_
.fixed {_x000D_
    width: 220px;_x000D_
    position: fixed;_x000D_
    /* Do not set top / left! */_x000D_
}
_x000D_
<div class="wrapper">_x000D_
    <div class="fixed-wrapper">_x000D_
        <div class="fixed">_x000D_
            Content in here will be fixed position, but 240px to the left of the site body._x000D_
        </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Sadly, I was hoping this thread might solve my issue with Android's WebKit rendering box-shadow blur pixels as margins on fixed position elements, but it seems it's a bug.
Anyway, I hope this helps!

How can I properly handle 404 in ASP.NET MVC?

Here is another method using MVC tools which you can handle requests to bad controller names, bad route names, and any other criteria you see fit inside of an Action method. Personally, I prefer to avoid as many web.config settings as possible, because they do the 302 / 200 redirect and do not support ResponseRewrite (Server.Transfer) using Razor views. I'd prefer to return a 404 with a custom error page for SEO reasons.

Some of this is new take on cottsak's technique above.

This solution also uses minimal web.config settings favoring the MVC 3 Error Filters instead.

Usage

Just throw a HttpException from an action or custom ActionFilterAttribute.

Throw New HttpException(HttpStatusCode.NotFound, "[Custom Exception Message Here]")

Step 1

Add the following setting to your web.config. This is required to use MVC's HandleErrorAttribute.

<customErrors mode="On" redirectMode="ResponseRedirect" />

Step 2

Add a custom HandleHttpErrorAttribute similar to the MVC framework's HandleErrorAttribute, except for HTTP errors:

<AttributeUsage(AttributeTargets.All, AllowMultiple:=True)>
Public Class HandleHttpErrorAttribute
    Inherits FilterAttribute
    Implements IExceptionFilter

    Private Const m_DefaultViewFormat As String = "ErrorHttp{0}"

    Private m_HttpCode As HttpStatusCode
    Private m_Master As String
    Private m_View As String

    Public Property HttpCode As HttpStatusCode
        Get
            If m_HttpCode = 0 Then
                Return HttpStatusCode.NotFound
            End If
            Return m_HttpCode
        End Get
        Set(value As HttpStatusCode)
            m_HttpCode = value
        End Set
    End Property

    Public Property Master As String
        Get
            Return If(m_Master, String.Empty)
        End Get
        Set(value As String)
            m_Master = value
        End Set
    End Property

    Public Property View As String
        Get
            If String.IsNullOrEmpty(m_View) Then
                Return String.Format(m_DefaultViewFormat, Me.HttpCode)
            End If
            Return m_View
        End Get
        Set(value As String)
            m_View = value
        End Set
    End Property

    Public Sub OnException(filterContext As System.Web.Mvc.ExceptionContext) Implements System.Web.Mvc.IExceptionFilter.OnException
        If filterContext Is Nothing Then Throw New ArgumentException("filterContext")

        If filterContext.IsChildAction Then
            Return
        End If

        If filterContext.ExceptionHandled OrElse Not filterContext.HttpContext.IsCustomErrorEnabled Then
            Return
        End If

        Dim ex As HttpException = TryCast(filterContext.Exception, HttpException)
        If ex Is Nothing OrElse ex.GetHttpCode = HttpStatusCode.InternalServerError Then
            Return
        End If

        If ex.GetHttpCode <> Me.HttpCode Then
            Return
        End If

        Dim controllerName As String = filterContext.RouteData.Values("controller")
        Dim actionName As String = filterContext.RouteData.Values("action")
        Dim model As New HandleErrorInfo(filterContext.Exception, controllerName, actionName)

        filterContext.Result = New ViewResult With {
            .ViewName = Me.View,
            .MasterName = Me.Master,
            .ViewData = New ViewDataDictionary(Of HandleErrorInfo)(model),
            .TempData = filterContext.Controller.TempData
        }
        filterContext.ExceptionHandled = True
        filterContext.HttpContext.Response.Clear()
        filterContext.HttpContext.Response.StatusCode = Me.HttpCode
        filterContext.HttpContext.Response.TrySkipIisCustomErrors = True
    End Sub
End Class

Step 3

Add Filters to the GlobalFilterCollection (GlobalFilters.Filters) in Global.asax. This example will route all InternalServerError (500) errors to the Error shared view (Views/Shared/Error.vbhtml). NotFound (404) errors will be sent to ErrorHttp404.vbhtml in the shared views as well. I've added a 401 error here to show you how this can be extended for additional HTTP error codes. Note that these must be shared views, and they all use the System.Web.Mvc.HandleErrorInfo object as a the model.

filters.Add(New HandleHttpErrorAttribute With {.View = "ErrorHttp401", .HttpCode = HttpStatusCode.Unauthorized})
filters.Add(New HandleHttpErrorAttribute With {.View = "ErrorHttp404", .HttpCode = HttpStatusCode.NotFound})
filters.Add(New HandleErrorAttribute With {.View = "Error"})

Step 4

Create a base controller class and inherit from it in your controllers. This step allows us to handle unknown action names and raise the HTTP 404 error to our HandleHttpErrorAttribute.

Public Class BaseController
    Inherits System.Web.Mvc.Controller

    Protected Overrides Sub HandleUnknownAction(actionName As String)
        Me.ActionInvoker.InvokeAction(Me.ControllerContext, "Unknown")
    End Sub

    Public Function Unknown() As ActionResult
        Throw New HttpException(HttpStatusCode.NotFound, "The specified controller or action does not exist.")
        Return New EmptyResult
    End Function
End Class

Step 5

Create a ControllerFactory override, and override it in your Global.asax file in Application_Start. This step allows us to raise the HTTP 404 exception when an invalid controller name has been specified.

Public Class MyControllerFactory
    Inherits DefaultControllerFactory

    Protected Overrides Function GetControllerInstance(requestContext As System.Web.Routing.RequestContext, controllerType As System.Type) As System.Web.Mvc.IController
        Try
            Return MyBase.GetControllerInstance(requestContext, controllerType)
        Catch ex As HttpException
            Return DependencyResolver.Current.GetService(Of BaseController)()
        End Try
    End Function
End Class

'In Global.asax.vb Application_Start:

controllerBuilder.Current.SetControllerFactory(New MyControllerFactory)

Step 6

Include a special route in your RoutTable.Routes for the BaseController Unknown action. This will help us raise a 404 in the case where a user accesses an unknown controller, or unknown action.

'BaseController
routes.MapRoute( _
    "Unknown", "BaseController/{action}/{id}", _
    New With {.controller = "BaseController", .action = "Unknown", .id = UrlParameter.Optional} _
)

Summary

This example demonstrated how one can use the MVC framework to return 404 Http Error Codes to the browser without a redirect using filter attributes and shared error views. It also demonstrates showing the same custom error page when invalid controller names and action names are specified.

I'll add a screenshot of an invalid controller name, action name, and a custom 404 raised from the Home/TriggerNotFound action if I get enough votes to post one =). Fiddler returns a 404 message when I access the following URLs using this solution:

/InvalidController
/Home/InvalidRoute
/InvalidController/InvalidRoute
/Home/TriggerNotFound

cottsak's post above and these articles were good references.

Which is more efficient, a for-each loop, or an iterator?

The foreach underhood is creating the iterator, calling hasNext() and calling next() to get the value; The issue with the performance comes only if you are using something that implements the RandomomAccess.

for (Iterator<CustomObj> iter = customList.iterator(); iter.hasNext()){
   CustomObj custObj = iter.next();
   ....
}

Performance issues with the iterator-based loop is because it is:

  1. allocating an object even if the list is empty (Iterator<CustomObj> iter = customList.iterator(););
  2. iter.hasNext() during every iteration of the loop there is an invokeInterface virtual call (go through all the classes, then do method table lookup before the jump).
  3. the implementation of the iterator has to do at least 2 fields lookup in order to make hasNext() call figure the value: #1 get current count and #2 get total count
  4. inside the body loop, there is another invokeInterface virtual call iter.next(so: go through all the classes and do method table lookup before the jump) and as well has to do fields lookup: #1 get the index and #2 get the reference to the array to do the offset into it (in every iteration).

A potential optimiziation is to switch to an index iteration with the cached size lookup:

for(int x = 0, size = customList.size(); x < size; x++){
  CustomObj custObj = customList.get(x);
  ...
}

Here we have:

  1. one invokeInterface virtual method call customList.size() on the initial creation of the for loop to get the size
  2. the get method call customList.get(x) during the body for loop, which is a field lookup to the array and then can do the offset into the array

We reduced a ton of method calls, field lookups. This you don't want to do with LinkedList or with something that is not a RandomAccess collection obj, otherwise the customList.get(x) is gonna turn into something that has to traverse the LinkedList on every iteration.

This is perfect when you know that is any RandomAccess based list collection.

How to embed fonts in CSS?

Go through http://www.w3.org/TR/css3-fonts/

Try this:

  @font-face {
        font-family: 'EntezareZohoor2';
        src: url('EntezareZohoor2.eot');
        src: local('EntezareZohoor2'), local('EntezareZohoor2'), url('EntezareZohoor2.ttf') format('svg');
       font-weight: normal;
       font-style: normal;
    }

jQuery: Selecting by class and input type

Just in case any dummies like me tried the suggestions here with a button and found nothing worked, you probably want this:

$(':button.myclass')

Having both a Created and Last Updated timestamp columns in MySQL 4.0

This is how can you have automatic & flexible createDate/lastModified fields using triggers:

First define them like this:

CREATE TABLE `entity` (
  `entityid` int(11) NOT NULL AUTO_INCREMENT,
  `createDate` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `lastModified` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `name` varchar(255) DEFAULT NULL,
  `comment` text,
  PRIMARY KEY (`entityid`),
)

Then add these triggers:

DELIMITER ;;
CREATE trigger entityinsert BEFORE INSERT ON entity FOR EACH ROW BEGIN SET NEW.createDate=IF(ISNULL(NEW.createDate) OR NEW.createDate='0000-00-00 00:00:00', CURRENT_TIMESTAMP, IF(NEW.createDate<CURRENT_TIMESTAMP, NEW.createDate, CURRENT_TIMESTAMP));SET NEW.lastModified=NEW.createDate; END;;
DELIMITER ;
CREATE trigger entityupdate BEFORE UPDATE ON entity FOR EACH ROW SET NEW.lastModified=IF(NEW.lastModified<OLD.lastModified, OLD.lastModified, CURRENT_TIMESTAMP);
  • If you insert without specifying createDate or lastModified, they will be equal and set to the current timestamp.
  • If you update them without specifying createDate or lastModified, the lastModified will be set to the current timestamp.

But here's the nice part:

  • If you insert, you can specify a createDate older than the current timestamp, allowing imports from older times to work well (lastModified will be equal to createDate).
  • If you update, you can specify a lastModified older than the previous value ('0000-00-00 00:00:00' works well), allowing to update an entry if you're doing cosmetic changes (fixing a typo in a comment) and you want to keep the old lastModified date. This will not modify the lastModified date.

Rounding float in Ruby

When displaying, you can use (for example)

>> '%.2f' % 2.3465
=> "2.35"

If you want to store it rounded, you can use

>> (2.3465*100).round / 100.0
=> 2.35

String Resource new line /n not possible?

After I tried next solution

  • add \n
  • add \n without spaces after it
  • use "" and press Enter inside text
  • text with press Enter
  • use lines=2

What solves me is br tag

<string name="successfullyfeatured">successfully<br/> You are now a member</string>

Update

the most reliable solution is to use Translation editor and edit text and it will handle new lines for you

Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION]

Check your TLS version:

python2 -c "import urllib2,json; print(json.loads(urllib2.urlopen('https://www.howsmyssl.com/a/check').read())['tls_version'])"

If your TLS version is less than 1.2 you have to upgrade it since the PyPI repository is on a brownout period of deprecating early TLS.

Source - Time To Upgrade Your Python: TLS v1.2 Will Soon Be Mandatory

You can upgrade the TLS version using the following command:

sudo apt-get update && sudo apt-get install openssl libssl-dev

This should fix your problem. Good luck!

EDIT: You can download packages using your own private python package repository regardless of TLS version. Private Python Package Repository

how do you insert null values into sql server

If you're using SSMS (or old school Enterprise Manager) to edit the table directly, press CTRL+0 to add a null.

Awaiting multiple Tasks with different results

You can use Task.WhenAll as mentioned, or Task.WaitAll, depending on whether you want the thread to wait. Take a look at the link for an explanation of both.

WaitAll vs WhenAll

How to compare two colors for similarity/difference

I've tried various methods like LAB color space, HSV comparisons and I've found that luminosity works pretty well for this purpose.

Here is Python version

def lum(c):
    def factor(component):
        component = component / 255;
        if (component <= 0.03928):
            component = component / 12.92;
        else:
            component = math.pow(((component + 0.055) / 1.055), 2.4);

        return component
    components = [factor(ci) for ci in c]

    return (components[0] * 0.2126 + components[1] * 0.7152 + components[2] * 0.0722) + 0.05;

def color_distance(c1, c2):

    l1 = lum(c1)
    l2 = lum(c2)
    higher = max(l1, l2)
    lower = min(l1, l2)

    return (higher - lower) / higher


c1 = ImageColor.getrgb('white')
c2 = ImageColor.getrgb('yellow')
print(color_distance(c1, c2))

Will give you

0.0687619047619048

Complex CSS selector for parent of active child

The first draft of Selectors Level 4 outlines a way to explicitly set the subject of a selector. This would allow the OP to style the list element with the selector $li > a.active

From Determining the Subject of a Selector:

For example, the following selector represents a list item LI unique child of an ordered list OL:

OL > LI:only-child

However the following one represents an ordered list OL having a unique child, that child being a LI:

$OL > LI:only-child

The structures represented by these two selectors are the same, but the subjects of the selectors are not.

Edit: Given how "drafty" a draft spec can be, it's best to keep tabs on this by checking the CSSWG's page on selectors level 4.

Initializing IEnumerable<string> In C#

IEnumerable<T> is an interface. You need to initiate with a concrete type (that implements IEnumerable<T>). Example:

IEnumerable<string> m_oEnum = new List<string>() { "1", "2", "3"};

How do you do dynamic / dependent drop downs in Google Sheets?

Continuing the evolution of this solution I've upped the ante by adding support for multiple root selections and deeper nested selections. This is a further development of JavierCane's solution (which in turn built on tarheel's).

_x000D_
_x000D_
/**_x000D_
 * "on edit" event handler_x000D_
 *_x000D_
 * Based on JavierCane's answer in _x000D_
 * _x000D_
 *   http://stackoverflow.com/questions/21744547/how-do-you-do-dynamic-dependent-drop-downs-in-google-sheets_x000D_
 *_x000D_
 * Each set of options has it own sheet named after the option. The _x000D_
 * values in this sheet are used to populate the drop-down._x000D_
 *_x000D_
 * The top row is assumed to be a header._x000D_
 *_x000D_
 * The sub-category column is assumed to be the next column to the right._x000D_
 *_x000D_
 * If there are no sub-categories the next column along is cleared in _x000D_
 * case the previous selection did have options._x000D_
 */_x000D_
_x000D_
function onEdit() {_x000D_
_x000D_
  var NESTED_SELECTS_SHEET_NAME = "Sitemap"_x000D_
  var NESTED_SELECTS_ROOT_COLUMN = 1_x000D_
  var SUB_CATEGORY_COLUMN = NESTED_SELECTS_ROOT_COLUMN + 1_x000D_
  var NUMBER_OF_ROOT_OPTION_CELLS = 3_x000D_
  var OPTION_POSSIBLE_VALUES_SHEET_SUFFIX = ""_x000D_
  _x000D_
  var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet()_x000D_
  var activeSheet = SpreadsheetApp.getActiveSheet()_x000D_
  _x000D_
  if (activeSheet.getName() !== NESTED_SELECTS_SHEET_NAME) {_x000D_
  _x000D_
    // Not in the sheet with nested selects, exit!_x000D_
    return_x000D_
  }_x000D_
  _x000D_
  var activeCell = SpreadsheetApp.getActiveRange()_x000D_
  _x000D_
  // Top row is the header_x000D_
  if (activeCell.getColumn() > SUB_CATEGORY_COLUMN || _x000D_
      activeCell.getRow() === 1 ||_x000D_
      activeCell.getRow() > NUMBER_OF_ROOT_OPTION_CELLS + 1) {_x000D_
_x000D_
    // Out of selection range, exit!_x000D_
    return_x000D_
  }_x000D_
  _x000D_
  var sheetWithActiveOptionPossibleValues = activeSpreadsheet_x000D_
    .getSheetByName(activeCell.getValue() + OPTION_POSSIBLE_VALUES_SHEET_SUFFIX)_x000D_
  _x000D_
  if (sheetWithActiveOptionPossibleValues === null) {_x000D_
  _x000D_
    // There are no further options for this value, so clear out any old_x000D_
    // values_x000D_
    activeSheet_x000D_
      .getRange(activeCell.getRow(), activeCell.getColumn() + 1)_x000D_
      .clearDataValidations()_x000D_
      .clearContent()_x000D_
      _x000D_
    return_x000D_
  }_x000D_
  _x000D_
  // Get all possible values_x000D_
  var activeOptionPossibleValues = sheetWithActiveOptionPossibleValues_x000D_
    .getSheetValues(1, 1, -1, 1)_x000D_
  _x000D_
  var possibleValuesValidation = SpreadsheetApp.newDataValidation()_x000D_
  possibleValuesValidation.setAllowInvalid(false)_x000D_
  possibleValuesValidation.requireValueInList(activeOptionPossibleValues, true)_x000D_
  _x000D_
  activeSheet_x000D_
    .getRange(activeCell.getRow(), activeCell.getColumn() + 1)_x000D_
    .setDataValidation(possibleValuesValidation.build())_x000D_
    _x000D_
} // onEdit()
_x000D_
_x000D_
_x000D_

As Javier says:

  • Create the sheet where you'll have the nested selectors
  • Go to the "Tools" > "Script Editor…" and select the "Blank project" option
  • Paste the code attached to this answer
  • Modify the constants at the top of the script setting up your values and save it
  • Create one sheet within this same document for each possible value of the "root selector". They must be named as the value + the specified suffix.

And if you wanted to see it in action I've created a demo sheet and you can see the code if you take a copy.

How to access your website through LAN in ASP.NET

You will need to configure you IIS (assuming this is the web server your are/will using) allowing access from WLAN/LAN to specific users (or anonymous). Allow IIS trought your firewall if you have one.

Your application won't need to be changed, that's just networking problems ans configuration you will have to face to allow acces only trought LAN and WLAN.

What is the difference between `git merge` and `git merge --no-ff`?

The --no-ff option ensures that a fast forward merge will not happen, and that a new commit object will always be created. This can be desirable if you want git to maintain a history of feature branches.             git merge --no-ff vs git merge In the above image, the left side is an example of the git history after using git merge --no-ff and the right side is an example of using git merge where an ff merge was possible.

EDIT: A previous version of this image indicated only a single parent for the merge commit. Merge commits have multiple parent commits which git uses to maintain a history of the "feature branch" and of the original branch. The multiple parent links are highlighted in green.

How do I convert a C# List<string[]> to a Javascript array?

Many of these answers do work, but I have found the easiest way by far is to send data through ViewData or ViewBag and let JSON.Net serialize it.

I use this technique when Javascript is needed for HTML generation before the page load or when AJAX overhead needs to be avoided:

In the controller:

public ActionResult MyController()
{
    var addresses = myAddressesGetter();
    ViewData["addresses"] = addresses ;
    return View();
}

In the view:

@section scripts {
<script type="text/javascript">
    var MyjavascriptAddresses: @Html.Raw(JsonConvert.SerializeObject(ViewData["addresses"])),
</script>
}

You can always rely on JSON.NET whereas some browsers have poor JSON deserialization support. Another benefit over some methods in that you can see the Javascript using your browser's View --> Source, since it is simply text generated server-side.

Note that In most situations, Web API a more elegant way to get JSON to the client.

How to check if C string is empty

Since C-style strings are always terminated with the null character (\0), you can check whether the string is empty by writing

do {
   ...
} while (url[0] != '\0');

Alternatively, you could use the strcmp function, which is overkill but might be easier to read:

do {
   ...
} while (strcmp(url, ""));

Note that strcmp returns a nonzero value if the strings are different and 0 if they're the same, so this loop continues to loop until the string is nonempty.

Hope this helps!

Alter user defined type in SQL Server

The simplest way to do this is through Visual Studio's object explorer, which is also supported in the Community edition.

Once you have made a connection to SQL server, browse to the type, right click and select View Code, make your changes to the schema of the user defined type and click update. Visual Studio should show you all of the dependencies for that object and generate scripts to update the type and recompile dependencies.

Xcode 4 - build output directory

Keep derived data but use the DSTROOT to specify the destination.

Use DEPLOYMENT_LOCATION to force deployment.

Use the undocumented DWARF_DSYM_FOLDER_PATH to copy the dSYM over too.

This allows you to use derived data location from xcodebuild and not have to do wacky stuff to find the app.

xcodebuild -sdk "iphoneos" -workspace Foo.xcworkspace -scheme Foo -configuration "Debug" DEPLOYMENT_LOCATION=YES DSTROOT=tmp DWARF_DSYM_FOLDER_PATH=tmp build

How to make full screen background in a web page

I have followed this tutorial: https://css-tricks.com/perfect-full-page-background-image/

Specifically, the first Demo was the one that helped me out a lot!

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

this might help!

How to check version of a CocoaPods framework

pod --version used this to check the version of the last installed pod

Matching an empty input box using CSS

I'm wondered by answers we have clear attribute to get empty input boxes, take a look at this code

/*empty input*/
input:empty{
    border-color: red;
}
/*input with value*/
input:not(:empty){
    border-color: black;
}

UPDATE

input, select, textarea {
    border-color: @green;
    &:empty {
        border-color: @red;
    }
}

More over for having a great look in the validation

 input, select, textarea {
    &[aria-invalid="true"] {
        border-color: amber !important;
    }

    &[aria-invalid="false"], &.valid {
        border-color: green !important;
    }
}

Is there a sleep function in JavaScript?

You can use the setTimeout or setInterval functions.

Laravel check if collection is empty

From php7 you can use Null Coalesce Opperator:

$employee = $mentors->intern ?? $mentors->intern->employee

This will return Null or the employee.

How do I set vertical space between list items?

<br>between <li></li> line entries seems to work perfectly well in all web browsers that I've tried, but it fails to pass the on-line W3C CSS3 checker. It gives me precisely the line spacing I am after. As far as I am concerned, since it undoubtedly works, I am persisting in using it, whatever W3C says, until someone can come up with a good legal alternative.

Set Google Maps Container DIV width and height 100%

I just added inline style .
<div id="map_canvas" style="width:750px;height:484px;"></div>
And it worked for me .

How to use the new Material Design Icon themes: Outlined, Rounded, Two-Tone and Sharp?

What worked for me is using _outline not _outlined after the icon name.

<mat-icon>info</mat-icon>

vs

<mat-icon>info_outline</mat-icon>

How to change already compiled .class file without decompile?

You can follow these steps to modify your java class:

  1. Decompile the .class file as you have done and save it as .java
  2. Create a project in Eclipse with that java file, the original JAR as library, and all its dependencies
  3. Change the .java and compile
  4. Get the modified .class file and put it again inside the original JAR.

How to permanently remove few commits from remote branch

 git reset --soft commit_id
 git stash save "message"
 git reset --hard commit_id
 git stash apply stash stash@{0}
 git push --force

Bootstrap Columns Not Working

<div class="container">
    <div class="row">
        <div class="col-md-12">
            <div class="row">
                <div class="col-md-4">  
                    <a href="">About</a>
                </div>
                <div class="col-md-4">
                    <img src="image.png">
                </div>
                <div class="col-md-4"> 
                    <a href="#myModal1" data-toggle="modal">SHARE</a>
                </div>
            </div>
        </div>
    </div>
</div>

You need to nest the interior columns inside of a row rather than just another column. It offsets the padding caused by the column with negative margins.

A simpler way would be

<div class="container">
   <div class="row">
       <div class="col-md-4">  
          <a href="">About</a>
       </div>
       <div class="col-md-4">
          <img src="image.png">
       </div>
       <div class="col-md-4"> 
           <a href="#myModal1" data-toggle="modal">SHARE</a>
       </div>
    </div>
</div>

Renaming the current file in Vim

You can also do it using netrw

The explore command opens up netrw in the directory of the open file

:E

Move the cursor over the file you want to rename:

R

Type in the new name, press enter, press y.

PHP: Inserting Values from the Form into MySQL

When you click the Button

if(isset($_POST['save'])){
        $sql = "INSERT INTO `members`(`id`, `membership_id`, `email`, `first_name`)
        VALUES ('".$_POST["id"]."','".$_POST["membership_id"]."','".$_POST["email"]."','".$_POST["firstname"]."')";
    **if ($conn->query($sql) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }**
}

This will execute the Query in the variable $sql

    if ($conn->query($sql) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

List<T> or IList<T>

You would because defining an IList or an ICollection would open up for other implementations of your interfaces.

You might want to have an IOrderRepository that defines a collection of orders in either a IList or ICollection. You could then have different kinds of implementations to provide a list of orders as long as they conform to "rules" defined by your IList or ICollection.

What method in the String class returns only the first N characters?

Simply:

public static String Truncate(String input,int maxLength)
{
   if(input.Length > maxLength)
      return input.Substring(0,maxLength);
   return input;
}

How do I check if a property exists on a dynamic anonymous type in c#?

I'm not sure why these answer are so complex, try:

dynamic settings = new
            {
                Filename = "temp.txt",
                Size = 10
            };

string fileName = settings.Filename;

var fileNameExists = fileName != null;

Byte Array to Image object

If you know the type of image and only want to generate a file, there's no need to get a BufferedImage instance. Just write the bytes to a file with the correct extension.

try (OutputStream out = new BufferedOutputStream(new FileOutputStream(path))) {
    out.write(bytes);
}

Inserting HTML elements with JavaScript

Instead of directly messing with innerHTML it might be better to create a fragment and then insert that:

function create(htmlStr) {
    var frag = document.createDocumentFragment(),
        temp = document.createElement('div');
    temp.innerHTML = htmlStr;
    while (temp.firstChild) {
        frag.appendChild(temp.firstChild);
    }
    return frag;
}

var fragment = create('<div>Hello!</div><p>...</p>');
// You can use native DOM methods to insert the fragment:
document.body.insertBefore(fragment, document.body.childNodes[0]);

Benefits:

  1. You can use native DOM methods for insertion such as insertBefore, appendChild etc.
  2. You have access to the actual DOM nodes before they're inserted; you can access the fragment's childNodes object.
  3. Using document fragments is very quick; faster than creating elements outside of the DOM and in certain situations faster than innerHTML.

Even though innerHTML is used within the function, it's all happening outside of the DOM so it's much faster than you'd think...

Starting a shell in the Docker Alpine container

Nowadays, Alpine images will boot directly into /bin/sh by default, without having to specify a shell to execute:

$ sudo docker run -it --rm alpine  
/ # echo $0  
/bin/sh  

This is since the alpine image Dockerfiles now contain a CMD command, that specifies the shell to execute when the container starts: CMD ["/bin/sh"].

In older Alpine image versions (pre-2017), the CMD command was not used, since Docker used to create an additional layer for CMD which caused the image size to increase. This is something that the Alpine image developers wanted to avoid. In recent Docker versions (1.10+), CMD no longer occupies a layer, and so it was added to alpine images. Therefore, as long as CMD is not overridden, recent Alpine images will boot into /bin/sh.

For reference, see the following commit to the official Alpine Dockerfiles by Glider Labs:
https://github.com/gliderlabs/docker-alpine/commit/ddc19dd95ceb3584ced58be0b8d7e9169d04c7a3#diff-db3dfdee92c17cf53a96578d4900cb5b

span with onclick event inside a tag

I would use jQuery to get the results that you're looking for. You wouldn't need to use an anchor tag at that point but if you did it would look like:

<a href="page" style="text-decoration:none;display:block;">

<span onclick="hide()">Hide me</span>

</a>

<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.2.min.js' /
<script type='text/javascript'>
$(document).ready(function(){
     $('span').click(function(){
           $(this).hide();
     }
}

How to split data into trainset and testset randomly?

This can be done similarly in Python using lists, (note that the whole list is shuffled in place).

import random

with open("datafile.txt", "rb") as f:
    data = f.read().split('\n')

random.shuffle(data)

train_data = data[:50]
test_data = data[50:]

How do I redirect in expressjs while passing some context?

There are a few ways of passing data around to different routes. The most correct answer is, of course, query strings. You'll need to ensure that the values are properly encodeURIComponent and decodeURIComponent.

app.get('/category', function(req, res) {
  var string = encodeURIComponent('something that would break');
  res.redirect('/?valid=' + string);
});

You can snag that in your other route by getting the parameters sent by using req.query.

app.get('/', function(req, res) {
  var passedVariable = req.query.valid;
  // Do something with variable
});

For more dynamic way you can use the url core module to generate the query string for you:

const url = require('url');    
app.get('/category', function(req, res) {
    res.redirect(url.format({
       pathname:"/",
       query: {
          "a": 1,
          "b": 2,
          "valid":"your string here"
        }
     }));
 });

So if you want to redirect all req query string variables you can simply do

res.redirect(url.format({
       pathname:"/",
       query:req.query,
     });
 });

And if you are using Node >= 7.x you can also use the querystring core module

const querystring = require('querystring');    
app.get('/category', function(req, res) {
      const query = querystring.stringify({
          "a": 1,
          "b": 2,
          "valid":"your string here"
      });
      res.redirect('/?' + query);
 });

Another way of doing it is by setting something up in the session. You can read how to set it up here, but to set and access variables is something like this:

app.get('/category', function(req, res) {
  req.session.valid = true;
  res.redirect('/');
});

And later on after the redirect...

app.get('/', function(req, res) {
  var passedVariable = req.session.valid;
  req.session.valid = null; // resets session variable
  // Do something
});

There is also the option of using an old feature of Express, req.flash. Doing so in newer versions of Express will require you to use another library. Essentially it allows you to set up variables that will show up and reset the next time you go to a page. It's handy for showing errors to users, but again it's been removed by default. EDIT: Found a library that adds this functionality.

Hopefully that will give you a general idea how to pass information around in an Express application.

Check if an HTML input element is empty or has no value entered by user

The getElementById method returns an Element object that you can use to interact with the element. If the element is not found, null is returned. In case of an input element, the value property of the object contains the string in the value attribute.

By using the fact that the && operator short circuits, and that both null and the empty string are considered "falsey" in a boolean context, we can combine the checks for element existence and presence of value data as follows:

var myInput = document.getElementById("customx");
if (myInput && myInput.value) {
  alert("My input has a value!");
}

Why won't my PHP app send a 404 error?

A little bit shorter version. Suppress odd echo.

if (strstr($_SERVER['REQUEST_URI'],'index.php')){
  header('HTTP/1.0 404 Not Found');
  exit("<h1>404 Not Found</h1>\nThe page that you have requested could not be found.");
}

wait process until all subprocess finish?

A Popen object has a .wait() method exactly defined for this: to wait for the completion of a given subprocess (and, besides, for retuning its exit status).

If you use this method, you'll prevent that the process zombies are lying around for too long.

(Alternatively, you can use subprocess.call() or subprocess.check_call() for calling and waiting. If you don't need IO with the process, that might be enough. But probably this is not an option, because your if the two subprocesses seem to be supposed to run in parallel, which they won't with (check_)call().)

If you have several subprocesses to wait for, you can do

exit_codes = [p.wait() for p in p1, p2]

which returns as soon as all subprocesses have finished. You then have a list of return codes which you maybe can evaluate.

Split a python list into other "sublists" i.e smaller lists

Actually I think using plain slices is the best solution in this case:

for i in range(0, len(data), 100):
    chunk = data[i:i + 100]
    ...

If you want to avoid copying the slices, you could use itertools.islice(), but it doesn't seem to be necessary here.

The itertools() documentation also contains the famous "grouper" pattern:

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

You would need to modify it to treat the last chunk correctly, so I think the straight-forward solution using plain slices is preferable.

How to remove all click event handlers using jQuery?

$('#saveBtn').off('click').on('click',function(){
   saveQuestion(id)
});

Use jquery's off and on

Can regular expressions be used to match nested patterns?

Yes, if it is .NET RegEx-engine. .Net engine supports finite state machine supplied with an external stack. see details

How to test whether a service is running from the command line

SERVICO.BAT
@echo off
echo Servico: %1
if "%1"=="" goto erro
sc query %1 | findstr RUNNING
if %ERRORLEVEL% == 2 goto trouble
if %ERRORLEVEL% == 1 goto stopped
if %ERRORLEVEL% == 0 goto started
echo unknown status
goto end
:trouble
echo trouble
goto end
:started
echo started
goto end
:stopped
echo stopped
goto end
:erro
echo sintaxe: servico NOMESERVICO
goto end

:end

No Application Encryption Key Has Been Specified

In my case, while cloning the project from git there was no .env

file. So I copy the .env file from the source project and paste in my current project and change its configuration of database and it run successfully.

What is best way to start and stop hadoop ecosystem, with command line?

Starting

start-dfs.sh (starts the namenode and the datanode)
start-mapred.sh (starts the jobtracker and the tasktracker)

Stopping

stop-dfs.sh
stop-mapred.sh

Parsing xml using powershell

First step is to load your xml string into an XmlDocument, using powershell's unique ability to cast strings to [xml]

$doc = [xml]@'
<xml>
    <Section name="BackendStatus">
        <BEName BE="crust" Status="1" />
        <BEName BE="pizza" Status="1" />
        <BEName BE="pie" Status="1" />
        <BEName BE="bread" Status="1" />
        <BEName BE="Kulcha" Status="1" />
        <BEName BE="kulfi" Status="1" />
        <BEName BE="cheese" Status="1" />
    </Section>
</xml>
'@

Powershell makes it really easy to parse xml with the dot notation. This statement will produce a sequence of XmlElements for your BEName elements:

$doc.xml.Section.BEName

Then you can pipe these objects into the where-object cmdlet to filter down the results. You can use ? as a shortcut for where

$doc.xml.Section.BEName | ? { $_.Status -eq 1 }

The expression inside the braces will be evaluated for each XmlElement in the pipeline, and only those that have a Status of 1 will be returned. The $_ operator refers to the current object in the pipeline (an XmlElement).

If you need to do something for every object in your pipeline, you can pipe the objects into the foreach-object cmdlet, which executes a block for every object in the pipeline. % is a shortcut for foreach:

$doc.xml.Section.BEName | ? { $_.Status -eq 1 } | % { $_.BE + " is delicious" }

Powershell is great at this stuff. It's really easy to assemble pipelines of objects, filter pipelines, and do operations on each object in the pipeline.

Mark error in form using Bootstrap

One can also use the following class while using bootstrap modal class (v 3.3.7) ... help-inline and help-block did not work in modal.

<span class="error text-danger">Some Errors related to something</span>

Output looks like something below:

Example of error text in modal

Android Studio - Gradle sync project failed

This may be helpful for some.

My problem exactly is incomplete gradle-1.12-all file download.

Below is screen shot of the Error

enter image description here

  1. I re-downloaded the file from the gradle site here and extracted it in path/to/the/gradle, in my case was in C:\Users\maneeOsman\.gradle\wrapper\dists\gradle-1.12-all\2apkk7d25miauqf1pdjp1bm0uo
  2. I closed the android studio and reopen it in administrator privilege (Run as administrator).

The android studio starts downloading the necessary files for building and debugging. You can notice that from bottom-left indicator bar.

After this, it is working fine.

See the screen shot below

enter image description here

Rotating a view in Android

That's simple, in Java

your_component.setRotation(15);

or

your_component.setRotation(295.18f);

in XML

<Button android:rotation="15" />

Count number of matches of a regex in Javascript

As mentioned in my earlier answer, you can use RegExp.exec() to iterate over all matches and count each occurrence; the advantage is limited to memory only, because on the whole it's about 20% slower than using String.match().

var re = /\s/g,
count = 0;

while (re.exec(text) !== null) {
    ++count;
}

return count;

Convert unix time stamp to date in java

You need to convert it to milliseconds by multiplying the timestamp by 1000:

java.util.Date dateTime=new java.util.Date((long)timeStamp*1000);

Get month name from number

To print all months at once:

 import datetime

 monthint = list(range(1,13))

 for X in monthint:
     month = datetime.date(1900, X , 1).strftime('%B')
     print(month)

How to store a dataframe using Pandas

Arctic is a high performance datastore for Pandas, numpy and other numeric data. It sits on top of MongoDB. Perhaps overkill for the OP, but worth mentioning for other folks stumbling across this post

Head and tail in one line

>>> mylist = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
>>> head, tail = mylist[0], mylist[1:]
>>> head
1
>>> tail
[1, 2, 3, 5, 8, 13, 21, 34, 55]

R - Concatenate two dataframes?

Try the plyr package:

rbind.fill(a,b,c)

What is the difference between re.search and re.match?

search ⇒ find something anywhere in the string and return a match object.

match ⇒ find something at the beginning of the string and return a match object.

Force GUI update from UI Thread

I had the same problem with property Enabled and I discovered a first chance exception raised because of it is not thread-safe. I found solution about "How to update the GUI from another thread in C#?" here https://stackoverflow.com/a/661706/1529139 And it works !

How do I find out if first character of a string is a number?

To verify only first letter is number or character -- For number Character.isDigit(str.charAt(0)) --return true

For character Character.isLetter(str.charAt(0)) --return true

How to upload multiple files using PHP, jQuery and AJAX

Using this source code you can upload multiple file like google one by one through ajax. Also you can see the uploading progress

HTML

 <input type="file" id="multiupload" name="uploadFiledd[]" multiple >
 <button type="button" id="upcvr" class="btn btn-primary">Start Upload</button>
 <div id="uploadsts"></div>

Javascript

    <script>

    function uploadajax(ttl,cl){

    var fileList = $('#multiupload').prop("files");
    $('#prog'+cl).removeClass('loading-prep').addClass('upload-image');

    var form_data =  "";

    form_data = new FormData();
    form_data.append("upload_image", fileList[cl]);


    var request = $.ajax({
              url: "upload.php",
              cache: false,
              contentType: false,
              processData: false,
              async: true,
              data: form_data,
              type: 'POST', 
              xhr: function() {  
                  var xhr = $.ajaxSettings.xhr();
                  if(xhr.upload){ 
                  xhr.upload.addEventListener('progress', function(event){
                      var percent = 0;
                      if (event.lengthComputable) {
                          percent = Math.ceil(event.loaded / event.total * 100);
                      }
                      $('#prog'+cl).text(percent+'%') 
                   }, false);
                 }
                 return xhr;
              },
              success: function (res, status) {
                  if (status == 'success') {
                      percent = 0;
                      $('#prog' + cl).text('');
                      $('#prog' + cl).text('--Success: ');
                      if (cl < ttl) {
                          uploadajax(ttl, cl + 1);
                      } else {
                          alert('Done');
                      }
                  }
              },
              fail: function (res) {
                  alert('Failed');
              }    
          })
    }

    $('#upcvr').click(function(){
        var fileList = $('#multiupload').prop("files");
        $('#uploadsts').html('');
        var i;
        for ( i = 0; i < fileList.length; i++) {
            $('#uploadsts').append('<p class="upload-page">'+fileList[i].name+'<span class="loading-prep" id="prog'+i+'"></span></p>');
            if(i == fileList.length-1){
                uploadajax(fileList.length-1,0);
            }
         }
    });
    </script>

PHP

upload.php
    move_uploaded_file($_FILES["upload_image"]["tmp_name"],$_FILES["upload_image"]["name"]);

Section vs Article HTML5

My interpretation is: I think of YouTube it has a comment-section, and inside the comment-section there are multiple articles (in this case comments).

So a section is like a div-container that holds articles.

Python dict how to create key or append an element to key?

Use dict.setdefault():

dic.setdefault(key,[]).append(value)

help(dict.setdefault):

    setdefault(...)
        D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D

Invalid URI: The format of the URI could not be determined

Check possible reasons here: http://msdn.microsoft.com/en-us/library/z6c2z492(v=VS.100).aspx

EDIT:

You need to put the protocol prefix in front the address, i.e. in your case "ftp://"

Parsing HTTP Response in Python

When I printed response.read() I noticed that b was preprended to the string (e.g. b'{"a":1,..). The "b" stands for bytes and serves as a declaration for the type of the object you're handling. Since, I knew that a string could be converted to a dict by using json.loads('string'), I just had to convert the byte type to a string type. I did this by decoding the response to utf-8 decode('utf-8'). Once it was in a string type my problem was solved and I was easily able to iterate over the dict.

I don't know if this is the fastest or most 'pythonic' way of writing this but it works and theres always time later of optimization and improvement! Full code for my solution:

from urllib.request import urlopen
import json

# Get the dataset
url = 'http://www.quandl.com/api/v1/datasets/FRED/GDP.json'
response = urlopen(url)

# Convert bytes to string type and string type to dict
string = response.read().decode('utf-8')
json_obj = json.loads(string)

print(json_obj['source_name']) # prints the string with 'source_name' key

How to import a new font into a project - Angular 5

You can try creating a css for your font with font-face (like explained here)

Step #1

Create a css file with font face and place it somewhere, like in assets/fonts

customfont.css

@font-face {
    font-family: YourFontFamily;
    src: url("/assets/font/yourFont.otf") format("truetype");
}

Step #2

Add the css to your .angular-cli.json in the styles config

"styles":[
 //...your other styles
 "assets/fonts/customFonts.css"
 ]

Do not forget to restart ng serve after doing this

Step #3

Use the font in your code

component.css

span {font-family: YourFontFamily; }

mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists

Work for me in CentOS:

$ service mysql stop
$ mysqld --skip-grant-tables &
$ mysql -u root mysql

mysql> FLUSH PRIVILEGES;
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';

$ service mysql restart

Responding with a JSON object in Node.js (converting object/array to JSON string)

Using res.json with Express:

function random(response) {
  console.log("response.json sets the appropriate header and performs JSON.stringify");
  response.json({ 
    anObject: { item1: "item1val", item2: "item2val" }, 
    anArray: ["item1", "item2"], 
    another: "item"
  });
}

Alternatively:

function random(response) {
  console.log("Request handler random was called.");
  response.writeHead(200, {"Content-Type": "application/json"});
  var otherArray = ["item1", "item2"];
  var otherObject = { item1: "item1val", item2: "item2val" };
  var json = JSON.stringify({ 
    anObject: otherObject, 
    anArray: otherArray, 
    another: "item"
  });
  response.end(json);
}

What is the difference between WCF and WPF?

WCF = Windows COMMUNICATION Foundation

WPF = Windows PRESENTATION Foundation.

WCF deals with communication (in simple terms - sending and receiving data as well as formatting and serialization involved), WPF deals with presentation (UI)

Spring Boot + JPA : Column name annotation ignored

you have to follow some naming strategy when you work with spring jpa. The column name should be in lowercase or uppercase.

@Column(name="TESTNAME")
private String testName;

or

@Column(name="testname")
private String testName;

keep in mind that, if you have your column name "test_name" format in the database then you have to follow the following way

@Column(name="TestName")
private String testName;

or

@Column(name="TEST_NAME")
private String testName;

or

@Column(name="test_name")
private String testName;

How to distinguish mouse "click" and "drag"

For a public action on an OSM map (position a marker on click) the question was: 1) how to determine the duration of mouse down->up (you can't imagine creating a new marker for each click) and 2) did the mouse move during down->up (i.e user is dragging the map).

const map = document.getElementById('map');

map.addEventListener("mousedown", position); 
map.addEventListener("mouseup", calculate);

let posX, posY, endX, endY, t1, t2, action;

function position(e) {

  posX = e.clientX;
  posY = e.clientY;
  t1 = Date.now();

}

function calculate(e) {

  endX = e.clientX;
  endY = e.clientY;
  t2 = (Date.now()-t1)/1000;
  action = 'inactive';

  if( t2 > 0.5 && t2 < 1.5) { // Fixing duration of mouse down->up

      if( Math.abs( posX-endX ) < 5 && Math.abs( posY-endY ) < 5 ) { // 5px error on mouse pos while clicking
         action = 'active';
         // --------> Do something
      }
  }
  console.log('Down = '+posX + ', ' + posY+'\nUp = '+endX + ', ' + endY+ '\nAction = '+ action);    

}

Find files in created between a date range

Try this:

find /var/tmp -mtime +2 -a -mtime -8 -ls

to find files older than 2 days but not older than 8 days.

How to recognize vehicle license / number plate (ANPR) from an image?

EDIT: I wrote a Python script for this.

As your objective is blurring (for privacy protection), you basically need a high recall detector as a first step. Here's how to go about doing this. The included code hints use OpenCV with Python.

  1. Convert to Grayscale.
  2. Apply Gaussian Blur.

    img = cv2.imread('input.jpg',1)
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    img_gray = cv2.GaussianBlur(img_gray, (5,5), 0)  
    

Let the input image be the following.

enter image description here

  1. Apply Sobel Filter to detect vertical edges.
  2. Threshold the resultant image using strict threshold or OTSU's binarization.

    cv2.Sobel(image, -1, 1, 0)
    cv2.threshold() 
    
  3. Apply a Morphological Closing operation using suitable structuring element. (I used 16x4 as structuring element)

    se = cv2.getStructuringElement(cv2.MORPH_RECT,(16,4))
    cv2.morphologyEx(image, cv2.MORPH_CLOSE, se)  
    

Resultant Image after Step 5.

enter image description here

  1. Find external contours of this image.

    cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) 
    
  2. For each contour, find the minAreaRect() bounding it.

  3. Select rectangles based on aspect ratio, minimum and maximum area, and angle with the horizontal. (I used 2.2 <= Aspect Ratio <= 8, 500 <= Area <=15000, and angle <= 45 degrees)

All minAreaRect()s are shown in orange and the one which satisfies our criteria is in green.

enter image description here

  1. There may be false positives after this step, to filter it, use edge density. Edge Density is defined as the number of white pixels/total number of pixels in a rectangle. Set a threshold for edge density. (I used 0.5)

enter image description here

  1. Blur the detected regions.

enter image description here

You can apply other filters you deem suitable to increase recall and precision. The detection can also be trained using HOG+SVM to increase precision.

zsh compinit: insecure directories

None of the solutions listed worked for me. Instead, I ended up uninstalling and reinstalling Homebrew, which did the trick. Uninstall instructions may be found here: http://osxdaily.com/2018/08/12/how-uninstall-homebrew-mac/

Function overloading in Javascript - Best practices

You can now do function overloading in ECMAScript 2018 without polyfills, checking var length/type, etc., just use the spread syntax.

_x000D_
_x000D_
function foo(var1, var2, opts){_x000D_
  // set default values for parameters_x000D_
  const defaultOpts = {_x000D_
    a: [1,2,3],_x000D_
    b: true,_x000D_
    c: 0.3289,_x000D_
    d: "str",_x000D_
  }_x000D_
  // merge default and passed-in parameters_x000D_
  // defaultOpts must go first!_x000D_
  const mergedOpts = {...defaultOpts, ...opts};_x000D_
_x000D_
  // you can now refer to parameters like b as mergedOpts.b,_x000D_
  // or just assign mergedOpts.b to b_x000D_
  console.log(mergedOpts.a);_x000D_
  console.log(mergedOpts.b);_x000D_
  console.log(mergedOpts.c);  _x000D_
  console.log(mergedOpts.d);_x000D_
}_x000D_
// the parameters you passed in override the default ones_x000D_
// all JS types are supported: primitives, objects, arrays, functions, etc._x000D_
let var1, var2="random var";_x000D_
foo(var1, var2, {a: [1,2], d: "differentString"});_x000D_
_x000D_
// parameter values inside foo:_x000D_
//a: [1,2]_x000D_
//b: true_x000D_
//c: 0.3289_x000D_
//d: "differentString"
_x000D_
_x000D_
_x000D_

What is spread syntax?

The Rest/Spread Properties for ECMAScript proposal (stage 4) adds spread properties to object literals. It copies own enumerable properties from a provided object onto a new object. More on mdn

Note: spread syntax in object literals doesn't work in Edge and IE and it is an experimental feature. see browser compatability

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

According to the select_list Oracle select documentation the AS is optional.

As a personal note I think it is easier to read with the AS

HTML text input field with currency symbol

Consider simulating an input field with a fixed prefix or suffix using a span with a border around a borderless input field. Here's a basic kickoff example:

_x000D_
_x000D_
.currencyinput {_x000D_
    border: 1px inset #ccc;_x000D_
}_x000D_
.currencyinput input {_x000D_
    border: 0;_x000D_
}
_x000D_
<span class="currencyinput">$<input type="text" name="currency"></span>
_x000D_
_x000D_
_x000D_

Select datatype of the field in postgres

Try this request :

SELECT column_name, data_type FROM information_schema.columns WHERE 
table_name = 'YOUR_TABLE' AND column_name = 'YOUR_FIELD';

How do you get the current project directory from C# code when creating a custom MSBuild task?

I had a similar situation, and after fruitless Googles, I declared a public string, which mods a string value of the debug / release path to get the project path. A benefit of using this method is that since it uses the currect project's directory, it matters not if you are working from a debug directory or a release directory:

public string DirProject()
{
    string DirDebug = System.IO.Directory.GetCurrentDirectory();
    string DirProject = DirDebug;

    for (int counter_slash = 0; counter_slash < 4; counter_slash++)
    {
        DirProject = DirProject.Substring(0, DirProject.LastIndexOf(@"\"));
    }

    return DirProject;
}

You would then be able to call it whenever you want, using only one line:

string MyProjectDir = DirProject();

This should work in most cases.

java.lang.ClassNotFoundException: com.fasterxml.jackson.annotation.JsonInclude$Value

Even though this answer was too late, I'm adding it because I also went through a horrible time finding answer for the same matter. Only different was, I was struggling with AWS Comprehend Medical API.

At the moment I'm writing this answer, if anyone come across the same issue with any AWS SDKs please downgrade jackson-annotaions or any jackson dependencies to 2.8.* versions. The latest 2.9.* versions does not working properly with AWS SDK for some reason. Anyone have any idea about the reason behind that feel free to comment below.

Just in case if anyone is lazy to google maven repos, I have linked down necessary repos.Check them out!

convert streamed buffers to utf8-string

Single Buffer

If you have a single Buffer you can use its toString method that will convert all or part of the binary contents to a string using a specific encoding. It defaults to utf8 if you don't provide a parameter, but I've explicitly set the encoding in this example.

var req = http.request(reqOptions, function(res) {
    ...

    res.on('data', function(chunk) {
        var textChunk = chunk.toString('utf8');
        // process utf8 text chunk
    });
});

Streamed Buffers

If you have streamed buffers like in the question above where the first byte of a multi-byte UTF8-character may be contained in the first Buffer (chunk) and the second byte in the second Buffer then you should use a StringDecoder. :

var StringDecoder = require('string_decoder').StringDecoder;

var req = http.request(reqOptions, function(res) {
    ...
    var decoder = new StringDecoder('utf8');

    res.on('data', function(chunk) {
        var textChunk = decoder.write(chunk);
        // process utf8 text chunk
    });
});

This way bytes of incomplete characters are buffered by the StringDecoder until all required bytes were written to the decoder.

initialize a const array in a class initializer in C++

With C++11 the answer to this question has now changed and you can in fact do:

struct a {
    const int b[2];
    // other bits follow

    // and here's the constructor
    a();
};

a::a() :
    b{2,3}
{
     // other constructor work
}

int main() {
 a a;
}

How do CSS triangles work?

The borders use an angled edge where they intersect (45° angle with equal width borders, but changing the border widths can skew the angle).

Border example

_x000D_
_x000D_
div {_x000D_
  width: 60px;_x000D_
  border-width: 30px;_x000D_
  border-color: red blue green yellow;_x000D_
  border-style: solid;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

Have a look to the jsFiddle.

By hiding certain borders, you can get the triangle effect (as you can see above by making the different portions different colours). transparent is often used as an edge colour to achieve the triangle shape.

How to initialize all members of an array to the same value?

There is a fast way to initialize array of any type with given value. It works very well with large arrays. Algorithm is as follows:

  • initialize first element of the array (usual way)
  • copy part which has been set into part which has not been set, doubling the size with each next copy operation

For 1 000 000 elements int array it is 4 times faster than regular loop initialization (i5, 2 cores, 2.3 GHz, 4GiB memory, 64 bits):

loop runtime 0.004248 [seconds]

memfill() runtime 0.001085 [seconds]


#include <stdio.h>
#include <time.h>
#include <string.h>
#define ARR_SIZE 1000000

void memfill(void *dest, size_t destsize, size_t elemsize) {
   char   *nextdest = (char *) dest + elemsize;
   size_t movesize, donesize = elemsize;

   destsize -= elemsize;
   while (destsize) {
      movesize = (donesize < destsize) ? donesize : destsize;
      memcpy(nextdest, dest, movesize);
      nextdest += movesize; destsize -= movesize; donesize += movesize;
   }
}    
int main() {
    clock_t timeStart;
    double  runTime;
    int     i, a[ARR_SIZE];

    timeStart = clock();
    for (i = 0; i < ARR_SIZE; i++)
        a[i] = 9;    
    runTime = (double)(clock() - timeStart) / (double)CLOCKS_PER_SEC;
    printf("loop runtime %f [seconds]\n",runTime);

    timeStart = clock();
    a[0] = 10;
    memfill(a, sizeof(a), sizeof(a[0]));
    runTime = (double)(clock() - timeStart) / (double)CLOCKS_PER_SEC;
    printf("memfill() runtime %f [seconds]\n",runTime);
    return 0;
}

What does this format means T00:00:00.000Z?

As one person may have already suggested,

I passed the ISO 8601 date string directly to moment like so...

`moment.utc('2019-11-03T05:00:00.000Z').format('MM/DD/YYYY')`

or

`moment('2019-11-03T05:00:00.000Z').utc().format('MM/DD/YYYY')`

either of these solutions will give you the same result.

`console.log(moment('2019-11-03T05:00:00.000Z').utc().format('MM/DD/YYYY')) // 11/3/2019`

How to split data into training/testing sets using sample function

This is almost the same code, but in more nice look

bound <- floor((nrow(df)/4)*3)         #define % of training and test set

df <- df[sample(nrow(df)), ]           #sample rows 
df.train <- df[1:bound, ]              #get training set
df.test <- df[(bound+1):nrow(df), ]    #get test set

Java - Change int to ascii

There are many ways to convert an int to ASCII (depending on your needs) but here is a way to convert each integer byte to an ASCII character:

private static String toASCII(int value) {
    int length = 4;
    StringBuilder builder = new StringBuilder(length);
    for (int i = length - 1; i >= 0; i--) {
        builder.append((char) ((value >> (8 * i)) & 0xFF));
    }
    return builder.toString();
}

For example, the ASCII text for "TEST" can be represented as the byte array:

byte[] test = new byte[] { (byte) 0x54, (byte) 0x45, (byte) 0x53, (byte) 0x54 };

Then you could do the following:

int value = ByteBuffer.wrap(test).getInt(); // 1413829460
System.out.println(toASCII(value)); // outputs "TEST"

...so this essentially converts the 4 bytes in a 32-bit integer to 4 separate ASCII characters (one character per byte).