Programs & Examples On #Datapump

A server based bulk import and export facility in Oracle

How to convert C++ Code to C

Maybe good ol' cfront will do?

How to convert Json array to list of objects in c#

You may use Json.Net framework to do this. Just like this :

Account account = JsonConvert.DeserializeObject<Account>(json);

the home page : http://json.codeplex.com/

the document about this : http://james.newtonking.com/json/help/index.html#

Java String.split() Regex

You could split on a word boundary with \b

Most popular screen sizes/resolutions on Android phones

Another alternative to see popular android resolutions or aspect ratios is Unity statistics:

LATEST UNITY STATISTICS (on 2019.06 return http503) web arhive

Top on 2017-01:

Display Resolutions:

  • 1280 x 720: 28.9%
  • 1920 x 1080: 21.4%
  • 800 x 480: 10.3%
  • 854 x 480: 9.7%
  • 960 x 540: 8.9%
  • 1024 x 600: 7.8%
  • 1280 x 800: 5.0%
  • 2560 x 1440: 2.4%
  • 480 x 320: 1.2%
  • 1920 x 1200: 0.8%
  • 1024 x 768: 0.8%

Display Aspect Ratios:

  • 16:9: 72.4%
  • 5:3: 18.2%
  • 16:10: 6.2%
  • 4:3: 1.7%
  • 3:2: 1.2%
  • 5:4: 0.1%

Multiple commands on a single line in a Windows batch file

Can be achieved also with scriptrunner

ScriptRunner.exe -appvscript demoA.cmd arg1 arg2 -appvscriptrunnerparameters -wait -timeout=30 -rollbackonerror -appvscript demoB.ps1 arg3 arg4 -appvscriptrunnerparameters -wait -timeout=30 

Which also have some features as rollback , timeout and waiting.

Git merge is not possible because I have unmerged files

I repeatedly had the same challenge sometime ago. This problem occurs mostly when you are trying to pull from the remote repository and you have some files on your local instance conflicting with the remote version, if you are using git from an IDE such as IntelliJ, you will be prompted and allowed to make a choice if you want to retain your own changes or you prefer the changes in the remote version to overwrite yours'. If you don't make any choice then you fall into this conflict. all you need to do is run:

git merge --abort # The unresolved conflict will be cleared off

And you can continue what you were doing before the break.

Add a common Legend for combined ggplots

If the legend is the same for both plots, there is a simple solution using grid.arrange(assuming you want your legend to align with both plots either vertically or horizontally). Simply keep the legend for the bottom-most or right-most plot while omitting the legend for the other. Adding a legend to just one plot, however, alters the size of one plot relative to the other. To avoid this use the heights command to manually adjust and keep them the same size. You can even use grid.arrange to make common axis titles. Note that this will require library(grid) in addition to library(gridExtra). For vertical plots:

y_title <- expression(paste(italic("E. coli"), " (CFU/100mL)"))

grid.arrange(arrangeGrob(p1, theme(legend.position="none"), ncol=1), 
   arrangeGrob(p2, theme(legend.position="bottom"), ncol=1), 
   heights=c(1,1.2), left=textGrob(y_title, rot=90, gp=gpar(fontsize=20)))

Here is the result for a similar graph for a project I was working on: enter image description here

Form/JavaScript not working on IE 11 with error DOM7011

I run into this when click on a html , it is fixed by adding type = "button" attribute.

How to search in commit messages using command line?

git log --grep=<pattern>
    Limit the commits output to ones with log message that matches the 
    specified pattern (regular expression).

--git help log

MVC Return Partial View as JSON

Instead of RenderViewToString I prefer a approach like

return Json(new { Url = Url.Action("Evil", model) });

then you can catch the result in your javascript and do something like

success: function(data) {
    $.post(data.Url, function(partial) { 
        $('#IdOfDivToUpdate').html(partial);
    });
}

IE6/IE7 css border on select element

From my personal experience where we tryed to put the border red when an invalid entry was selected, it is impossible to put border red of select element in IE.

As stated before the ocntrols in internet explorer uses WindowsAPI to draw and render and you have nothing to solve this.

What was our solution was to put the background color of select element light red (for text to be readable). background color was working in every browser, but in IE we had a side effects that the element where the same background color as the select.

So to summarize the solution we putted :

select
{
  background-color:light-red;
  border: 2px solid red;
}
option
{
  background-color:white;
}

Note that color was set with hex code, I just don't remember which.

This solution was giving us the wanted effect in every browser except for the border red in IE.

Good luck

VBA ADODB excel - read data from Recordset

I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.

Set cn = CreateObject("ADODB.Connection")
With cn
 .Provider = "Microsoft.Jet.OLEDB.4.0"
  .ConnectionString = "Data Source=D:\test.xls " & _
  ";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
  For i = 0 To rs.Fields.Count - 1
    Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
    strNaam = rs.Fields(0).Value
  Next
  rs.MoveNext
Loop
rs.Close

There are other ways, depending on what you want to do, such as GetString (GetString Method Description).

An error occurred while executing the command definition. See the inner exception for details

Does the actual query return no results? First() will fail if there are no results.

Reverting to a specific commit based on commit id with Git?

git reset c14809fafb08b9e96ff2879999ba8c807d10fb07 is what you're after...

Function in JavaScript that can be called only once

keep it as simple as possible

function sree(){
  console.log('hey');
  window.sree = _=>{};
}

You can see the result

script result

Maximum and minimum values in a textbox

Set Attributes in CodeBehind

textWeight.Attributes.Add("minimum", minValue.ToString());
textWeight.Attributes.Add("maximum", maxValue.ToString());

Result:

<input type="text" minimum="0" maximum="100" id="textWeight" value="2" name="textWeight">

By jQuery

    jQuery(document).ready(function () {

        var textWeight = $("input[type='text']#textWeight");

        textWeight.change(function () {

              var min = textWeight.attr("minimum");

              var max= textWeight.attr("maximum");

              var value = textWeight.val();

              if(val < min || val > max)
              {
                    alert("Your Message");

                    textWeight.val(min);
              }

        });
    });

In Python, how do I convert all of the items in a list to floats?

you can use numpy to avoid looping:

import numpy as np
list(np.array(my_list).astype(float)

What is the "continue" keyword and how does it work in Java?

continue must be inside a loop Otherwise it showsThe error below:

Continue outside the loop

How do I get an apk file from an Android device?

One liner which works for all Android versions:

adb shell 'cat `pm path com.example.name | cut -d':' -f2`' > app.apk

How can I detect browser type using jQuery?

$.browser.chrome = /chrom(e|ium)/.test(navigator.userAgent.toLowerCase()); 

if($.browser.chrome){
  alert(1);      
}

UPDATE:(10x to @Mr. Bacciagalupe)

jQuery has removed $.browser from 1.9 and their latest release.

But you can still use $.browser as a standalone plugin, found here

How to remove outliers in boxplot in R?

See ?boxplot for all the help you need.

 outline: if ‘outline’ is not true, the outliers are not drawn (as
          points whereas S+ uses lines).

boxplot(x,horizontal=TRUE,axes=FALSE,outline=FALSE)

And for extending the range of the whiskers and suppressing the outliers inside this range:

   range: this determines how far the plot whiskers extend out from the
          box.  If ‘range’ is positive, the whiskers extend to the most
          extreme data point which is no more than ‘range’ times the
          interquartile range from the box. A value of zero causes the
          whiskers to extend to the data extremes.

# change the value of range to change the whisker length
boxplot(x,horizontal=TRUE,axes=FALSE,range=2)

How to get all registered routes in Express?

Hacky copy/paste answer courtesy of Doug Wilson on the express github issues. Dirty but works like a charm.

function print (path, layer) {
  if (layer.route) {
    layer.route.stack.forEach(print.bind(null, path.concat(split(layer.route.path))))
  } else if (layer.name === 'router' && layer.handle.stack) {
    layer.handle.stack.forEach(print.bind(null, path.concat(split(layer.regexp))))
  } else if (layer.method) {
    console.log('%s /%s',
      layer.method.toUpperCase(),
      path.concat(split(layer.regexp)).filter(Boolean).join('/'))
  }
}

function split (thing) {
  if (typeof thing === 'string') {
    return thing.split('/')
  } else if (thing.fast_slash) {
    return ''
  } else {
    var match = thing.toString()
      .replace('\\/?', '')
      .replace('(?=\\/|$)', '$')
      .match(/^\/\^((?:\\[.*+?^${}()|[\]\\\/]|[^.*+?^${}()|[\]\\\/])*)\$\//)
    return match
      ? match[1].replace(/\\(.)/g, '$1').split('/')
      : '<complex:' + thing.toString() + '>'
  }
}

app._router.stack.forEach(print.bind(null, []))

Produces

screengrab

Disable hover effects on mobile browsers

What I've done to solve the same problem is to have a feature detection (I use something like this code), seeing if onTouchMove is defined, and if so I add the css class "touchMode" to the body, else i add "desktopMode".

Then every time some style effect only applies to a touch device, or only to a desktop the css rule is prepended with the appropriate class:

.desktopMode .someClass:hover{ color: red }
.touchMode .mainDiv { width: 100%; margin: 0; /*etc.*/ }

Edit: This strategy of course adds a few extra characters to your css, so If you're concerned about css size, you could search for the touchMode and desktopMode definitons and put them into different files, so you can serve optimized css for each device type; or you could change the class names to something much shorter before going to prod.

Insert a new row into DataTable

In c# following code insert data into datatable on specified position

DataTable dt = new DataTable();
dt.Columns.Add("SL");
dt.Columns.Add("Amount");

dt.rows.add(1, 1000)
dt.rows.add(2, 2000)

dt.Rows.InsertAt(dt.NewRow(), 3);

var rowPosition = 3;
dt.Rows[rowPosition][dt.Columns.IndexOf("SL")] = 3;
dt.Rows[rowPosition][dt.Columns.IndexOf("Amount")] = 3000;

How to remove undefined and null values from an object using lodash?

I encountered a similar problem with removing undefined from an object (deeply), and found that if you are OK to convert your plain old object and use JSON, a quick and dirty helper function would look like this:

function stripUndefined(obj) {
  return JSON.parse(JSON.stringify(obj));
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description

"...If undefined, a function, or a symbol is encountered during conversion it is either omitted (when it is found in an object) or censored to null (when it is found in an array)."

PHP shorthand for isset()?

PHP 7.4+; with the null coalescing assignment operator

$var ??= '';

PHP 7.0+; with the null coalescing operator

$var = $var ?? '';

PHP 5.3+; with the ternary operator shorthand

isset($var) ?: $var = '';

Or for all/older versions with isset:

$var = isset($var) ? $var : '';

or

!isset($var) && $var = '';

How to get a Char from an ASCII Character Code in c#

You can simply write:

char c = (char) 2;

or

char c = Convert.ToChar(2);

or more complex option for ASCII encoding only

char[] characters = System.Text.Encoding.ASCII.GetChars(new byte[]{2});
char c = characters[0];

Rails: How can I set default values in ActiveRecord?

We put the default values in the database through migrations (by specifying the :default option on each column definition) and let Active Record use these values to set the default for each attribute.

IMHO, this approach is aligned with the principles of AR : convention over configuration, DRY, the table definition drives the model, not the other way around.

Note that the defaults are still in the application (Ruby) code, though not in the model but in the migration(s).

Get the filename of a fileupload in a document through JavaScript

RaYell, You don't need to parse the value returned. document.getElementById("FileUpload1").value returns only the file name with extension. This was useful for me because I wanted to copy the name of the file to be uploaded to an input box called 'title'. In my application, the uploaded file is renamed to the index generated by the backend database and the title is stored in the database.

The right way of setting <a href=""> when it's a local file

By definition, file: URLs are system-dependent, and they have little use. A URL as in your example works when used locally, i.e. the linking page itself is in the user’s computer. But browsers generally refuse to follow file: links on a page that it has fetched with the HTTP protocol, so that the page's own URL is an http: URL. When you click on such a link, nothing happens. The purpose is presumably security: to prevent a remote page from accessing files in the visitor’s computer. (I think this feature was first implemented in Mozilla, then copied to other browsers.)

So if you work with HTML documents in your computer, the file: URLs should work, though there are system-dependent issues in their syntax (how you write path names and file names in such a URL).

If you really need to work with an HTML document on your computers and another HTML document on a web server, the way to make links work is to use the local file as primary and, if needed, use client-side scripting to fetch the document from the server,

How to create JNDI context in Spring Boot with Embedded Tomcat Container

Have you tried @Lazy loading the datasource? Because you're initialising your embedded Tomcat container within the Spring context, you have to delay the initialisation of your DataSource (until the JNDI vars have been setup).

N.B. I haven't had a chance to test this code yet!

@Lazy
@Bean(destroyMethod="")
public DataSource jndiDataSource() throws IllegalArgumentException, NamingException {
    JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
    bean.setJndiName("java:comp/env/jdbc/myDataSource");
    bean.setProxyInterface(DataSource.class);
    //bean.setLookupOnStartup(false);
    bean.afterPropertiesSet();
    return (DataSource)bean.getObject();
}

You may also need to add the @Lazy annotation wherever the DataSource is being used. e.g.

@Lazy
@Autowired
private DataSource dataSource;

How can I get selector from jQuery object

In collaboration with @drzaus we've come up with the following jQuery plugin.

jQuery.getSelector

!(function ($, undefined) {
    /// adapted http://jsfiddle.net/drzaus/Hgjfh/5/

    var get_selector = function (element) {
        var pieces = [];

        for (; element && element.tagName !== undefined; element = element.parentNode) {
            if (element.className) {
                var classes = element.className.split(' ');
                for (var i in classes) {
                    if (classes.hasOwnProperty(i) && classes[i]) {
                        pieces.unshift(classes[i]);
                        pieces.unshift('.');
                    }
                }
            }
            if (element.id && !/\s/.test(element.id)) {
                pieces.unshift(element.id);
                pieces.unshift('#');
            }
            pieces.unshift(element.tagName);
            pieces.unshift(' > ');
        }

        return pieces.slice(1).join('');
    };

    $.fn.getSelector = function (only_one) {
        if (true === only_one) {
            return get_selector(this[0]);
        } else {
            return $.map(this, function (el) {
                return get_selector(el);
            });
        }
    };

})(window.jQuery);

Minified Javascript

// http://stackoverflow.com/questions/2420970/how-can-i-get-selector-from-jquery-object/15623322#15623322
!function(e,t){var n=function(e){var n=[];for(;e&&e.tagName!==t;e=e.parentNode){if(e.className){var r=e.className.split(" ");for(var i in r){if(r.hasOwnProperty(i)&&r[i]){n.unshift(r[i]);n.unshift(".")}}}if(e.id&&!/\s/.test(e.id)){n.unshift(e.id);n.unshift("#")}n.unshift(e.tagName);n.unshift(" > ")}return n.slice(1).join("")};e.fn.getSelector=function(t){if(true===t){return n(this[0])}else{return e.map(this,function(e){return n(e)})}}}(window.jQuery)

Usage and Gotchas

<html>
    <head>...</head>
    <body>
        <div id="sidebar">
            <ul>
                <li>
                    <a href="/" id="home">Home</a>
                </li>
            </ul>
        </div>
        <div id="main">
            <h1 id="title">Welcome</h1>
        </div>

        <script type="text/javascript">

            // Simple use case
            $('#main').getSelector();           // => 'HTML > BODY > DIV#main'

            // If there are multiple matches then an array will be returned
            $('body > div').getSelector();      // => ['HTML > BODY > DIV#main', 'HTML > BODY > DIV#sidebar']

            // Passing true to the method will cause it to return the selector for the first match
            $('body > div').getSelector(true);  // => 'HTML > BODY > DIV#main'

        </script>
    </body>
</html>

Fiddle w/ QUnit tests

http://jsfiddle.net/CALY5/5/

Reading file using fscanf() in C

First of all, you're testing fp twice. so printf("Error Reading File\n"); never gets executed.

Then, the output of fscanf should be equal to 2 since you're reading two values.

Create an ArrayList with multiple object types?

You can make it like :

List<Object> sections = new ArrayList <Object>();

(Recommended) Another possible solution would be to make a custom model class with two parameters one Integer and other String. Then using an ArrayList of that object.

Log4Net configuring log level

you can use log4net.Filter.LevelMatchFilter. other options can be found at log4net tutorial - filters

in ur appender section add

<filter type="log4net.Filter.LevelMatchFilter">
    <levelToMatch value="Info" />
    <acceptOnMatch value="true" />
</filter>

the accept on match default is true so u can leave it out but if u set it to false u can filter out log4net filters

How do I set the driver's python version in spark?

Please look at the below snippet:

#setting environment variable for pyspark in linux||ubuntu
#goto --- /usr/local/spark/conf
#create a new file named spark-env.sh copy all content of spark-env.sh.template to it
#then add below lines to it, with path to python

PYSPARK_PYTHON="/usr/bin/python3"
PYSPARK_DRIVER_PYTHON="/usr/bin/python3"
PYSPARK_DRIVER_PYTHON_OPTS="notebook --no-browser"
#i was running python 3.6 ||run - 'which python' in terminal to find the path of python

Bootstrap 3 truncate long text inside rows of a table in a responsive way

I'm using bootstrap.
I used css parameters.

.table {
  table-layout:fixed;
}

.table td {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

and bootstrap grid system parameters, like this.

<th class="col-sm-2">Name</th>

<td class="col-sm-2">hoge</td>

What is the C++ function to raise a number to a power?

pow(2.0,1.0)
pow(2.0,2.0)
pow(2.0,3.0)

Your original question title is misleading. To just square, use 2*2.

Reading a cell value in Excel vba and write in another Cell

I have this function for this case ..

Function GetValue(r As Range, Tag As String) As Integer
Dim c, nRet As String
Dim n, x As Integer
Dim bNum As Boolean

c = r.Value
n = InStr(c, Tag)
For x = n + 1 To Len(c)
  Select Case Mid(c, x, 1)
    Case ":":    bNum = True
    Case " ": Exit For
    Case Else: If bNum Then nRet = nRet & Mid(c, x, 1)
  End Select
Next
GetValue = val(nRet)
End Function

To fill cell BC .. (assumed that you check cell A1)

Worksheets("Übersicht_2013").Cells(i, "BC") = GetValue(range("A1"),"S")

How can I shuffle the lines of a text file on the Unix command line or in a shell script?

Not mentioned as of yet:

  1. The unsort util. Syntax (somewhat playlist oriented):

    unsort [-hvrpncmMsz0l] [--help] [--version] [--random] [--heuristic]
           [--identity] [--filenames[=profile]] [--separator sep] [--concatenate] 
           [--merge] [--merge-random] [--seed integer] [--zero-terminated] [--null] 
           [--linefeed] [file ...]
    
  2. msort can shuffle by line, but it's usually overkill:

    seq 10 | msort -jq -b -l -n 1 -c r
    

How to highlight text using javascript

The solutions offered here are quite bad.

  1. You can't use regex, because that way, you search/highlight in the html tags.
  2. You can't use regex, because it doesn't work properly with UTF* (anything with non-latin/English characters).
  3. You can't just do an innerHTML.replace, because this doesn't work when the characters have a special HTML notation, e.g. &amp; for &, &lt; for <, &gt; for >, &auml; for ä, &ouml; for ö &uuml; for ü &szlig; for ß, etc.

What you need to do:

Loop through the HTML document, find all text nodes, get the textContent, get the position of the highlight-text with indexOf (with an optional toLowerCase if it should be case-insensitive), append everything before indexof as textNode, append the matched Text with a highlight span, and repeat for the rest of the textnode (the highlight string might occur multiple times in the textContent string).

Here is the code for this:

var InstantSearch = {

    "highlight": function (container, highlightText)
    {
        var internalHighlighter = function (options)
        {

            var id = {
                container: "container",
                tokens: "tokens",
                all: "all",
                token: "token",
                className: "className",
                sensitiveSearch: "sensitiveSearch"
            },
            tokens = options[id.tokens],
            allClassName = options[id.all][id.className],
            allSensitiveSearch = options[id.all][id.sensitiveSearch];


            function checkAndReplace(node, tokenArr, classNameAll, sensitiveSearchAll)
            {
                var nodeVal = node.nodeValue, parentNode = node.parentNode,
                    i, j, curToken, myToken, myClassName, mySensitiveSearch,
                    finalClassName, finalSensitiveSearch,
                    foundIndex, begin, matched, end,
                    textNode, span, isFirst;

                for (i = 0, j = tokenArr.length; i < j; i++)
                {
                    curToken = tokenArr[i];
                    myToken = curToken[id.token];
                    myClassName = curToken[id.className];
                    mySensitiveSearch = curToken[id.sensitiveSearch];

                    finalClassName = (classNameAll ? myClassName + " " + classNameAll : myClassName);

                    finalSensitiveSearch = (typeof sensitiveSearchAll !== "undefined" ? sensitiveSearchAll : mySensitiveSearch);

                    isFirst = true;
                    while (true)
                    {
                        if (finalSensitiveSearch)
                            foundIndex = nodeVal.indexOf(myToken);
                        else
                            foundIndex = nodeVal.toLowerCase().indexOf(myToken.toLowerCase());

                        if (foundIndex < 0)
                        {
                            if (isFirst)
                                break;

                            if (nodeVal)
                            {
                                textNode = document.createTextNode(nodeVal);
                                parentNode.insertBefore(textNode, node);
                            } // End if (nodeVal)

                            parentNode.removeChild(node);
                            break;
                        } // End if (foundIndex < 0)

                        isFirst = false;


                        begin = nodeVal.substring(0, foundIndex);
                        matched = nodeVal.substr(foundIndex, myToken.length);

                        if (begin)
                        {
                            textNode = document.createTextNode(begin);
                            parentNode.insertBefore(textNode, node);
                        } // End if (begin)

                        span = document.createElement("span");
                        span.className += finalClassName;
                        span.appendChild(document.createTextNode(matched));
                        parentNode.insertBefore(span, node);

                        nodeVal = nodeVal.substring(foundIndex + myToken.length);
                    } // Whend

                } // Next i 
            }; // End Function checkAndReplace 

            function iterator(p)
            {
                if (p === null) return;

                var children = Array.prototype.slice.call(p.childNodes), i, cur;

                if (children.length)
                {
                    for (i = 0; i < children.length; i++)
                    {
                        cur = children[i];
                        if (cur.nodeType === 3)
                        {
                            checkAndReplace(cur, tokens, allClassName, allSensitiveSearch);
                        }
                        else if (cur.nodeType === 1)
                        {
                            iterator(cur);
                        }
                    }
                }
            }; // End Function iterator

            iterator(options[id.container]);
        } // End Function highlighter
        ;


        internalHighlighter(
            {
                container: container
                , all:
                    {
                        className: "highlighter"
                    }
                , tokens: [
                    {
                        token: highlightText
                        , className: "highlight"
                        , sensitiveSearch: false
                    }
                ]
            }
        ); // End Call internalHighlighter 

    } // End Function highlight

};

Then you can use it like this:

function TestTextHighlighting(highlightText)
{
    var container = document.getElementById("testDocument");
    InstantSearch.highlight(container, highlightText);
}

Here's an example HTML document

<!DOCTYPE html>
<html>
    <head>
        <title>Example of Text Highlight</title>
        <style type="text/css" media="screen">
            .highlight{ background: #D3E18A;}
            .light{ background-color: yellow;}
        </style>
    </head>
    <body>
        <div id="testDocument">
            This is a test
            <span> This is another test</span>
            äöüÄÖÜäöüÄÖÜ
            <span>Test123&auml;&ouml;&uuml;&Auml;&Ouml;&Uuml;</span>
        </div>
    </body>
</html>

By the way, if you search in a database with LIKE,
e.g. WHERE textField LIKE CONCAT('%', @query, '%') [which you shouldn't do, you should use fulltext-search or Lucene], then you can escape every character with \ and add an SQL-escape-statement, that way you'll find special characters that are LIKE-expressions.

e.g.

WHERE textField LIKE CONCAT('%', @query, '%') ESCAPE '\'

and the value of @query is not '%completed%' but '%\c\o\m\p\l\e\t\e\d%'

(tested, works with SQL-Server and PostgreSQL, and every other RDBMS system that supports ESCAPE)


A revised typescript-version:

namespace SearchTools 
{


    export interface IToken
    {
        token: string;
        className: string;
        sensitiveSearch: boolean;
    }


    export class InstantSearch 
    {

        protected m_container: Node;
        protected m_defaultClassName: string;
        protected m_defaultCaseSensitivity: boolean;
        protected m_highlightTokens: IToken[];


        constructor(container: Node, tokens: IToken[], defaultClassName?: string, defaultCaseSensitivity?: boolean)
        {
            this.iterator = this.iterator.bind(this);
            this.checkAndReplace = this.checkAndReplace.bind(this);
            this.highlight = this.highlight.bind(this);
            this.highlightNode = this.highlightNode.bind(this);    

            this.m_container = container;
            this.m_defaultClassName = defaultClassName || "highlight";
            this.m_defaultCaseSensitivity = defaultCaseSensitivity || false;
            this.m_highlightTokens = tokens || [{
                token: "test",
                className: this.m_defaultClassName,
                sensitiveSearch: this.m_defaultCaseSensitivity
            }];
        }


        protected checkAndReplace(node: Node)
        {
            let nodeVal: string = node.nodeValue;
            let parentNode: Node = node.parentNode;
            let textNode: Text = null;

            for (let i = 0, j = this.m_highlightTokens.length; i < j; i++)
            {
                let curToken: IToken = this.m_highlightTokens[i];
                let textToHighlight: string = curToken.token;
                let highlightClassName: string = curToken.className || this.m_defaultClassName;
                let caseSensitive: boolean = curToken.sensitiveSearch || this.m_defaultCaseSensitivity;

                let isFirst: boolean = true;
                while (true)
                {
                    let foundIndex: number = caseSensitive ?
                        nodeVal.indexOf(textToHighlight)
                        : nodeVal.toLowerCase().indexOf(textToHighlight.toLowerCase());

                    if (foundIndex < 0)
                    {
                        if (isFirst)
                            break;

                        if (nodeVal)
                        {
                            textNode = document.createTextNode(nodeVal);
                            parentNode.insertBefore(textNode, node);
                        } // End if (nodeVal)

                        parentNode.removeChild(node);
                        break;
                    } // End if (foundIndex < 0)

                    isFirst = false;


                    let begin: string = nodeVal.substring(0, foundIndex);
                    let matched: string = nodeVal.substr(foundIndex, textToHighlight.length);

                    if (begin)
                    {
                        textNode = document.createTextNode(begin);
                        parentNode.insertBefore(textNode, node);
                    } // End if (begin)

                    let span: HTMLSpanElement = document.createElement("span");

                    if (!span.classList.contains(highlightClassName))
                        span.classList.add(highlightClassName);

                    span.appendChild(document.createTextNode(matched));
                    parentNode.insertBefore(span, node);

                    nodeVal = nodeVal.substring(foundIndex + textToHighlight.length);
                } // Whend

            } // Next i 

        } // End Sub checkAndReplace 


        protected iterator(p: Node)
        {
            if (p == null)
                return;

            let children: Node[] = Array.prototype.slice.call(p.childNodes);

            if (children.length)
            {
                for (let i = 0; i < children.length; i++)
                {
                    let cur: Node = children[i];

                    // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
                    if (cur.nodeType === Node.TEXT_NODE) 
                    {
                        this.checkAndReplace(cur);
                    }
                    else if (cur.nodeType === Node.ELEMENT_NODE) 
                    {
                        this.iterator(cur);
                    }
                } // Next i 

            } // End if (children.length) 

        } // End Sub iterator


        public highlightNode(n:Node)
        {
            this.iterator(n);
        } // End Sub highlight 


        public highlight()
        {
            this.iterator(this.m_container);
        } // End Sub highlight 


    } // End Class InstantSearch 


} // End Namespace SearchTools 

Usage:

let searchText = document.getElementById("txtSearchText");
let searchContainer = document.body; // document.getElementById("someTable");
let highlighter = new SearchTools.InstantSearch(searchContainer, [
    {
        token: "this is the text to highlight" // searchText.value,
        className: "highlight", // this is the individual highlight class
        sensitiveSearch: false
    }
]);


// highlighter.highlight(); // this would highlight in the entire table
// foreach tr - for each td2 
highlighter.highlightNode(td2); // this highlights in the second column of table

Window.Open with PDF stream instead of PDF location

It looks like window.open will take a Data URI as the location parameter.

So you can open it like this from the question: Opening PDF String in new window with javascript:

window.open("data:application/pdf;base64, " + base64EncodedPDF);

Here's an runnable example in plunker, and sample pdf file that's already base64 encoded.

Then on the server, you can convert the byte array to base64 encoding like this:

string fileName = @"C:\TEMP\TEST.pdf";
byte[] pdfByteArray = System.IO.File.ReadAllBytes(fileName);
string base64EncodedPDF = System.Convert.ToBase64String(pdfByteArray);

NOTE: This seems difficult to implement in IE because the URL length is prohibitively small for sending an entire PDF.

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

As I mentioned here Purge Kafka Queue:

Tested in Kafka 0.8.2, for the quick-start example: First, Add one line to server.properties file under config folder:

delete.topic.enable=true

then, you can run this command:

bin/kafka-topics.sh --zookeeper localhost:2181 --delete --topic test

How to parse JSON without JSON.NET library?

For those who do not have 4.5, Here is my library function that reads json. It requires a project reference to System.Web.Extensions.

using System.Web.Script.Serialization;

public object DeserializeJson<T>(string Json)
{
    JavaScriptSerializer JavaScriptSerializer = new JavaScriptSerializer();
    return JavaScriptSerializer.Deserialize<T>(Json);
}

Usually, json is written out based on a contract. That contract can and usually will be codified in a class (T). Sometimes you can take a word from the json and search the object browser to find that type.

Example usage:

Given the json

{"logEntries":[],"value":"My Code","text":"My Text","enabled":true,"checkedIndices":[],"checkedItemsTextOverflows":false}

You could parse it into a RadComboBoxClientState object like this:

string ClientStateJson = Page.Request.Form("ReportGrid1_cboReportType_ClientState");
RadComboBoxClientState RadComboBoxClientState = DeserializeJson<RadComboBoxClientState>(ClientStateJson);
return RadComboBoxClientState.Value;

Python reading from a file and saving to utf-8

You can also get through it by the code below:

file=open(completefilepath,'r',encoding='utf8',errors="ignore")
file.read()

test attribute in JSTL <c:if> tag

Attributes in JSP tag libraries in general can be either static or resolved at request time. If they are resolved at request time the JSP will resolve their value at runtime and pass the output on to the tag. This means you can put pretty much any JSP code into the attribute and the tag will behave accordingly to what output that produces.

If you look at the jstl taglib docs you can see which attributes are reuest time and which are not. http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/index.html

How to write a file or data to an S3 object using boto3

You may use the below code to write, for example an image to S3 in 2019. To be able to connect to S3 you will have to install AWS CLI using command pip install awscli, then enter few credentials using command aws configure:

import urllib3
import uuid
from pathlib import Path
from io import BytesIO
from errors import custom_exceptions as cex

BUCKET_NAME = "xxx.yyy.zzz"
POSTERS_BASE_PATH = "assets/wallcontent"
CLOUDFRONT_BASE_URL = "https://xxx.cloudfront.net/"


class S3(object):
    def __init__(self):
        self.client = boto3.client('s3')
        self.bucket_name = BUCKET_NAME
        self.posters_base_path = POSTERS_BASE_PATH

    def __download_image(self, url):
        manager = urllib3.PoolManager()
        try:
            res = manager.request('GET', url)
        except Exception:
            print("Could not download the image from URL: ", url)
            raise cex.ImageDownloadFailed
        return BytesIO(res.data)  # any file-like object that implements read()

    def upload_image(self, url):
        try:
            image_file = self.__download_image(url)
        except cex.ImageDownloadFailed:
            raise cex.ImageUploadFailed

        extension = Path(url).suffix
        id = uuid.uuid1().hex + extension
        final_path = self.posters_base_path + "/" + id
        try:
            self.client.upload_fileobj(image_file,
                                       self.bucket_name,
                                       final_path
                                       )
        except Exception:
            print("Image Upload Error for URL: ", url)
            raise cex.ImageUploadFailed

        return CLOUDFRONT_BASE_URL + id

Fade Effect on Link Hover?

Try this in your css:

.a {
    transition: color 0.3s ease-in-out;
}
.a {
    color:turquoise;
}
.a:hover {
    color: #454545;
}

Cannot use a leading ../ to exit above the top directory

I had such a problem and the answer, although frustrating to find, was solved by doing a search on the offending page for the ".." in the error message. I am using Visual Studio Express and the solution was changing "../../Images/" to "~/Images/" . Hopefully this will help someone.

Is it possible to see more than 65536 rows in Excel 2007?

I am not 100% sure where all of the other suggestions are trying to go, but the issue is basically related to the extension that you have on the file. If you save the file as a Excel 97/2003 workbook it will not allow you to see all million rows. Create a new sheet and save it as a workbook and you will see all million. Note: the extension will be .xlsx

Entity Framework: There is already an open DataReader associated with this Command

In my case the issue had nothing to do with MARS connection string but with json serialization. After upgrading my project from NetCore2 to 3 i got this error.

More information can be found here

How to get base url with jquery or javascript?

Getting the base url |Calls controller from js

function getURL() {

var windowurl = window.location.href;
var baseUrl = windowurl.split('://')[1].split('/')[0]; //split function

var xhr = new XMLHttpRequest();
var url='http://'+baseUrl+'/url from controller';
xhr.open("GET", url);
xhr.send(); //object use to send

xhr.onreadystatechange=function() {
    if(xhr.readyState==4 && this.status==200){
 //console.log(xhr.responseText); //the response of the request
        
 document.getElementById("id from where you called the function").innerHTML = xhr.responseText;
}
  }
}

Hosting a Maven repository on github

The best solution I've been able to find consists of these steps:

  1. Create a branch called mvn-repo to host your maven artifacts.
  2. Use the github site-maven-plugin to push your artifacts to github.
  3. Configure maven to use your remote mvn-repo as a maven repository.

There are several benefits to using this approach:

  • Maven artifacts are kept separate from your source in a separate branch called mvn-repo, much like github pages are kept in a separate branch called gh-pages (if you use github pages)
  • Unlike some other proposed solutions, it doesn't conflict with your gh-pages if you're using them.
  • Ties in naturally with the deploy target so there are no new maven commands to learn. Just use mvn deploy as you normally would

The typical way you deploy artifacts to a remote maven repo is to use mvn deploy, so let's patch into that mechanism for this solution.

First, tell maven to deploy artifacts to a temporary staging location inside your target directory. Add this to your pom.xml:

<distributionManagement>
    <repository>
        <id>internal.repo</id>
        <name>Temporary Staging Repository</name>
        <url>file://${project.build.directory}/mvn-repo</url>
    </repository>
</distributionManagement>

<plugins>
    <plugin>
        <artifactId>maven-deploy-plugin</artifactId>
        <version>2.8.1</version>
        <configuration>
            <altDeploymentRepository>internal.repo::default::file://${project.build.directory}/mvn-repo</altDeploymentRepository>
        </configuration>
    </plugin>
</plugins>

Now try running mvn clean deploy. You'll see that it deployed your maven repository to target/mvn-repo. The next step is to get it to upload that directory to GitHub.

Add your authentication information to ~/.m2/settings.xml so that the github site-maven-plugin can push to GitHub:

<!-- NOTE: MAKE SURE THAT settings.xml IS NOT WORLD READABLE! -->
<settings>
  <servers>
    <server>
      <id>github</id>
      <username>YOUR-USERNAME</username>
      <password>YOUR-PASSWORD</password>
    </server>
  </servers>
</settings>

(As noted, please make sure to chmod 700 settings.xml to ensure no one can read your password in the file. If someone knows how to make site-maven-plugin prompt for a password instead of requiring it in a config file, let me know.)

Then tell the GitHub site-maven-plugin about the new server you just configured by adding the following to your pom:

<properties>
    <!-- github server corresponds to entry in ~/.m2/settings.xml -->
    <github.global.server>github</github.global.server>
</properties>

Finally, configure the site-maven-plugin to upload from your temporary staging repo to your mvn-repo branch on Github:

<build>
    <plugins>
        <plugin>
            <groupId>com.github.github</groupId>
            <artifactId>site-maven-plugin</artifactId>
            <version>0.11</version>
            <configuration>
                <message>Maven artifacts for ${project.version}</message>  <!-- git commit message -->
                <noJekyll>true</noJekyll>                                  <!-- disable webpage processing -->
                <outputDirectory>${project.build.directory}/mvn-repo</outputDirectory> <!-- matches distribution management repository url above -->
                <branch>refs/heads/mvn-repo</branch>                       <!-- remote branch name -->
                <includes><include>**/*</include></includes>
                <repositoryName>YOUR-REPOSITORY-NAME</repositoryName>      <!-- github repo name -->
                <repositoryOwner>YOUR-GITHUB-USERNAME</repositoryOwner>    <!-- github username  -->
            </configuration>
            <executions>
              <!-- run site-maven-plugin's 'site' target as part of the build's normal 'deploy' phase -->
              <execution>
                <goals>
                  <goal>site</goal>
                </goals>
                <phase>deploy</phase>
              </execution>
            </executions>
        </plugin>
    </plugins>
</build>

The mvn-repo branch does not need to exist, it will be created for you.

Now run mvn clean deploy again. You should see maven-deploy-plugin "upload" the files to your local staging repository in the target directory, then site-maven-plugin committing those files and pushing them to the server.

[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building DaoCore 1.3-SNAPSHOT
[INFO] ------------------------------------------------------------------------
...
[INFO] --- maven-deploy-plugin:2.5:deploy (default-deploy) @ greendao ---
Uploaded: file:///Users/mike/Projects/greendao-emmby/DaoCore/target/mvn-repo/com/greendao-orm/greendao/1.3-SNAPSHOT/greendao-1.3-20121223.182256-3.jar (77 KB at 2936.9 KB/sec)
Uploaded: file:///Users/mike/Projects/greendao-emmby/DaoCore/target/mvn-repo/com/greendao-orm/greendao/1.3-SNAPSHOT/greendao-1.3-20121223.182256-3.pom (3 KB at 1402.3 KB/sec)
Uploaded: file:///Users/mike/Projects/greendao-emmby/DaoCore/target/mvn-repo/com/greendao-orm/greendao/1.3-SNAPSHOT/maven-metadata.xml (768 B at 150.0 KB/sec)
Uploaded: file:///Users/mike/Projects/greendao-emmby/DaoCore/target/mvn-repo/com/greendao-orm/greendao/maven-metadata.xml (282 B at 91.8 KB/sec)
[INFO] 
[INFO] --- site-maven-plugin:0.7:site (default) @ greendao ---
[INFO] Creating 24 blobs
[INFO] Creating tree with 25 blob entries
[INFO] Creating commit with SHA-1: 0b8444e487a8acf9caabe7ec18a4e9cff4964809
[INFO] Updating reference refs/heads/mvn-repo from ab7afb9a228bf33d9e04db39d178f96a7a225593 to 0b8444e487a8acf9caabe7ec18a4e9cff4964809
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 8.595s
[INFO] Finished at: Sun Dec 23 11:23:03 MST 2012
[INFO] Final Memory: 9M/81M
[INFO] ------------------------------------------------------------------------

Visit github.com in your browser, select the mvn-repo branch, and verify that all your binaries are now there.

enter image description here

Congratulations!

You can now deploy your maven artifacts to a poor man's public repo simply by running mvn clean deploy.

There's one more step you'll want to take, which is to configure any poms that depend on your pom to know where your repository is. Add the following snippet to any project's pom that depends on your project:

<repositories>
    <repository>
        <id>YOUR-PROJECT-NAME-mvn-repo</id>
        <url>https://github.com/YOUR-USERNAME/YOUR-PROJECT-NAME/raw/mvn-repo/</url>
        <snapshots>
            <enabled>true</enabled>
            <updatePolicy>always</updatePolicy>
        </snapshots>
    </repository>
</repositories>

Now any project that requires your jar files will automatically download them from your github maven repository.

Edit: to avoid the problem mentioned in the comments ('Error creating commit: Invalid request. For 'properties/name', nil is not a string.'), make sure you state a name in your profile on github.

Where are Magento's log files located?

To create your custom log file, try this code

Mage::log('your debug message', null, 'yourlog_filename.log');

Refer this Answer

Parsing JSON from XmlHttpRequest.responseJSON

I think you have to include jQuery to use responseJSON.

Without jQuery, you could try with responseText and try like eval("("+req.responseText+")");

UPDATE:Please read the comment regarding eval, you can test with eval, but don't use it in working extension.

OR

use json_parse : it does not use eval

Change marker size in Google maps V3

The size arguments are in pixels. So, to double your example's marker size the fifth argument to the MarkerImage constructor would be:

new google.maps.Size(42,68)

I find it easiest to let the map API figure out the other arguments, unless I need something other than the bottom/center of the image as the anchor. In your case you could do:

var pinIcon = new google.maps.MarkerImage(
    "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor,
    null, /* size is determined at runtime */
    null, /* origin is 0,0 */
    null, /* anchor is bottom center of the scaled image */
    new google.maps.Size(42, 68)
);

how to make label visible/invisible?

You should be able to get it to hide/show by setting:

.style.display = 'none';
.style.display = 'inline';

How to check if a variable is equal to one string or another string?

This does not do what you expect:

if var is 'stringone' or 'stringtwo':
    dosomething()

It is the same as:

if (var is 'stringone') or 'stringtwo':
    dosomething()

Which is always true, since 'stringtwo' is considered a "true" value.

There are two alternatives:

if var in ('stringone', 'stringtwo'):
    dosomething()

Or you can write separate equality tests,

if var == 'stringone' or var == 'stringtwo':
    dosomething()

Don't use is, because is compares object identity. You might get away with it sometimes because Python interns a lot of strings, just like you might get away with it in Java because Java interns a lot of strings. But don't use is unless you really want object identity.

>>> 'a' + 'b' == 'ab'
True
>>> 'a' + 'b' is 'abc'[:2]
False # but could be True
>>> 'a' + 'b' is 'ab'
True  # but could be False

How to resolve Error : Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation

You can't show dialog box ON SERVER from ASP.NET application, well of course tehnically you can do that but it makes no sense since your user is using browser and it can't see messages raised on server. You have to understand how web sites work, server side code (ASP.NET in your case) produces html, javascript etc on server and then browser loads that content and displays it to the user, so in order to present modal message box to the user you have to use Javascript, for example alert function.

Here is the example for asp.net :

https://www.madskristensen.net/blog/javascript-alertshow(e2809dmessagee2809d)-from-aspnet-code-behind/

Keras, How to get the output of each layer?

Assuming you have:

1- Keras pre-trained model.

2- Input x as image or set of images. The resolution of image should be compatible with dimension of the input layer. For example 80*80*3 for 3-channels (RGB) image.

3- The name of the output layer to get the activation. For example, "flatten_2" layer. This should be include in the layer_names variable, represents name of layers of the given model.

4- batch_size is an optional argument.

Then you can easily use get_activation function to get the activation of the output layer for a given input x and pre-trained model:

import six
import numpy as np
import keras.backend as k
from numpy import float32
def get_activations(x, model, layer, batch_size=128):
"""
Return the output of the specified layer for input `x`. `layer` is specified by layer index (between 0 and
`nb_layers - 1`) or by name. The number of layers can be determined by counting the results returned by
calling `layer_names`.
:param x: Input for computing the activations.
:type x: `np.ndarray`. Example: x.shape = (80, 80, 3)
:param model: pre-trained Keras model. Including weights.
:type model: keras.engine.sequential.Sequential. Example: model.input_shape = (None, 80, 80, 3)
:param layer: Layer for computing the activations
:type layer: `int` or `str`. Example: layer = 'flatten_2'
:param batch_size: Size of batches.
:type batch_size: `int`
:return: The output of `layer`, where the first dimension is the batch size corresponding to `x`.
:rtype: `np.ndarray`. Example: activations.shape = (1, 2000)
"""

    layer_names = [layer.name for layer in model.layers]
    if isinstance(layer, six.string_types):
        if layer not in layer_names:
            raise ValueError('Layer name %s is not part of the graph.' % layer)
        layer_name = layer
    elif isinstance(layer, int):
        if layer < 0 or layer >= len(layer_names):
            raise ValueError('Layer index %d is outside of range (0 to %d included).'
                             % (layer, len(layer_names) - 1))
        layer_name = layer_names[layer]
    else:
        raise TypeError('Layer must be of type `str` or `int`.')

    layer_output = model.get_layer(layer_name).output
    layer_input = model.input
    output_func = k.function([layer_input], [layer_output])

    # Apply preprocessing
    if x.shape == k.int_shape(model.input)[1:]:
        x_preproc = np.expand_dims(x, 0)
    else:
        x_preproc = x
    assert len(x_preproc.shape) == 4

    # Determine shape of expected output and prepare array
    output_shape = output_func([x_preproc[0][None, ...]])[0].shape
    activations = np.zeros((x_preproc.shape[0],) + output_shape[1:], dtype=float32)

    # Get activations with batching
    for batch_index in range(int(np.ceil(x_preproc.shape[0] / float(batch_size)))):
        begin, end = batch_index * batch_size, min((batch_index + 1) * batch_size, x_preproc.shape[0])
        activations[begin:end] = output_func([x_preproc[begin:end]])[0]

    return activations

Edit and Continue: "Changes are not allowed when..."

what worked for me was unchecking "Use Managed Compatibility Mode" under

Tools -> Options -> Debugging

TBN: checking or unchecking "Require source file to exactly match the original version" seems not influences the E&C

Hope this can help.

Java ArrayList of Doubles

1) "Unnecessarily complicated" is IMHO to create first an unmodifiable List before adding its elements to the ArrayList.

2) The solution matches exact the question: "Is there a way to define an ArrayList with the double type?"

double type:

double[] arr = new double[] {1.38, 2.56, 4.3};

ArrayList:

ArrayList<Double> list = DoubleStream.of( arr ).boxed().collect(
    Collectors.toCollection( new Supplier<ArrayList<Double>>() {
      public ArrayList<Double> get() {
        return( new ArrayList<Double>() );
      }
    } ) );

…and this creates the same compact and fast compilation as its Java 1.8 short-form:

ArrayList<Double> list = DoubleStream.of( arr ).boxed().collect(
    Collectors.toCollection( ArrayList::new ) );

TypeError: '<=' not supported between instances of 'str' and 'int'

Change

vote = input('Enter the name of the player you wish to vote for')

to

vote = int(input('Enter the name of the player you wish to vote for'))

You are getting the input from the console as a string, so you must cast that input string to an int object in order to do numerical operations.

Current user in Magento?

You can get current login customer name from session in following way :

$customer = Mage::getSingleton('customer/session')->getCustomer();

This will return the customer details of current login customer.

Now you can get customer name by using getName()

echo $customer->getName();

How to store Configuration file and read it using React

If you used Create React App, you can set an environment variable using a .env file. The documentation is here:

https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables

Basically do something like this in the .env file at the project root.

REACT_APP_NOT_SECRET_CODE=abcdef

Note that the variable name must start with REACT_APP_

You can access it from your component with

process.env.REACT_APP_NOT_SECRET_CODE

How to colorize diff on the command line?

Actually there seems to be yet another option (which I only noticed recently, when running into the problem described above):

git diff --no-index <file1> <file2>
# output to console instead of opening a pager
git --no-pager diff --no-index <file1> <file2>

If you have Git around (which you already might be using anyway), then you will be able to use it for comparison, even if the files themselves are not under version control. If not enabled for you by default, then enabling color support here seems to be considerably easier than some of the previously mentioned workarounds.

Kotlin - Property initialization using "by lazy" vs. "lateinit"

If you are using Spring container and you want to initialize non-nullable bean field, lateinit is better suited.

    @Autowired
    lateinit var myBean: MyBean

How can I remove the search bar and footer added by the jQuery DataTables plugin?

You could hide them via css:

#example_info, #example_filter{display: none}

How to know installed Oracle Client is 32 bit or 64 bit?

Go to %ORACLE_HOME%\inventory\ContentsXML folder and open comps.xml file

Look for <DEP_LIST> on ~second screen.
If following lines have

  • PLAT="NT_AMD64" then this Oracle Home is 64 bit.
  • PLAT="NT_X86" then - 32 bit.

    You may have both 32-bit and 64-bit Oracle Homes installed.

  • printf() formatting for hex

    The "0x" counts towards the eight character count. You need "%#010x".

    Note that # does not append the 0x to 0 - the result will be 0000000000 - so you probably actually should just use "0x%08x" anyway.

    Pandas: Creating DataFrame from Series

    I guess anther way, possibly faster, to achieve this is 1) Use dict comprehension to get desired dict (i.e., taking 2nd col of each array) 2) Then use pd.DataFrame to create an instance directly from the dict without loop over each col and concat.

    Assuming your mat looks like this (you can ignore this since your mat is loaded from file):

    In [135]: mat = {'a': np.random.randint(5, size=(4,2)),
       .....: 'b': np.random.randint(5, size=(4,2))}
    
    In [136]: mat
    Out[136]: 
    {'a': array([[2, 0],
            [3, 4],
            [0, 1],
            [4, 2]]), 'b': array([[1, 0],
            [1, 1],
            [1, 0],
            [2, 1]])}
    

    Then you can do:

    In [137]: df = pd.DataFrame ({name:mat[name][:,1] for name in mat})
    
    In [138]: df
    Out[138]: 
       a  b
    0  0  0
    1  4  1
    2  1  0
    3  2  1
    
    [4 rows x 2 columns]
    

    Set timeout for webClient.DownloadFile()

    Assuming you wanted to do this synchronously, using the WebClient.OpenRead(...) method and setting the timeout on the Stream that it returns will give you the desired result:

    using (var webClient = new WebClient())
    using (var stream = webClient.OpenRead(streamingUri))
    {
         if (stream != null)
         {
              stream.ReadTimeout = Timeout.Infinite;
              using (var reader = new StreamReader(stream, Encoding.UTF8, false))
              {
                   string line;
                   while ((line = reader.ReadLine()) != null)
                   {
                        if (line != String.Empty)
                        {
                            Console.WriteLine("Count {0}", count++);
                        }
                        Console.WriteLine(line);
                   }
              }
         }
    }
    

    Deriving from WebClient and overriding GetWebRequest(...) to set the timeout @Beniamin suggested, didn't work for me as, but this did.

    Fragment onResume() & onPause() is not called on backstack

    While creating a fragment transaction, make sure to add the following code.

    // Replace whatever is in the fragment_container view with this fragment, 
    // and add the transaction to the back stack 
    transaction.replace(R.id.fragment_container, newFragment); 
    transaction.addToBackStack(null); 
    

    Also make sure, to commit the transaction after adding it to backstack

    Set Matplotlib colorbar size to match graph

    You can do this easily with a matplotlib AxisDivider.

    The example from the linked page also works without using subplots:

    import matplotlib.pyplot as plt
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    import numpy as np
    
    plt.figure()
    ax = plt.gca()
    im = ax.imshow(np.arange(100).reshape((10,10)))
    
    # create an axes on the right side of ax. The width of cax will be 5%
    # of ax and the padding between cax and ax will be fixed at 0.05 inch.
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    
    plt.colorbar(im, cax=cax)
    

    enter image description here

    How can I output UTF-8 from Perl?

    TMTOWTDI, chose the method that best fits how you work. I use the environment method so I don't have to think about it.

    In the environment:

    export PERL_UNICODE=SDL
    

    on the command line:

    perl -CSDL -le 'print "\x{1815}"';
    

    or with binmode:

    binmode(STDOUT, ":utf8");          #treat as if it is UTF-8
    binmode(STDIN, ":encoding(utf8)"); #actually check if it is UTF-8
    

    or with PerlIO:

    open my $fh, ">:utf8", $filename
        or die "could not open $filename: $!\n";
    
    open my $fh, "<:encoding(utf-8)", $filename
        or die "could not open $filename: $!\n";
    

    or with the open pragma:

    use open ":encoding(utf8)";
    use open IN => ":encoding(utf8)", OUT => ":utf8";
    

    How to tell which commit a tag points to in Git?

    From Igor Zevaka:

    Summary

    Since there are about 4 almost equally acceptable yet different answers I will summarise all the different ways to skin a tag.

    1. git rev-list -1 $TAG (answer). git rev-list outputs the commits that lead up to the $TAG similar to git log but only showing the SHA1 of the commit. The -1 limits the output to the commit it points at.

    2. git show-ref --tags (answer) will show all tags (local and fetched from remote) and their SHA1s.

    3. git show-ref $TAG (answer) will show the tag and its path along with the SHA1.

    4. git rev-parse $TAG (answer) will show the SHA1 of an unannotated tag.

    5. git rev-parse --verify $TAG^{commit} (answer) will show a SHA1 of both annotated and unannotated tags. On Windows use git rev-parse --verify %TAG%^^^^{commit} (four hats).

    6. cat .git/refs/tags/* or cat .git/packed-refs (answer) depending on whether or not the tag is local or fetched from remote.

    How to programmatically disable page scrolling with jQuery

    To turn OFF scrolling try this:

    var current = $(window).scrollTop();
    $(window).scroll(function() {
        $(window).scrollTop(current);
    });
    

    to reset:

    $(window).off('scroll');
    

    Android - running a method periodically using postDelayed() call

    Handler h = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what==0){
                // do stuff
                h.removeMessages(0);  // clear the handler for those messages with what = 0
                h.sendEmptyMessageDelayed(0, 2000); 
            }
        }
    };
    
    
     h.sendEmptyMessage(0);  
    

    exception.getMessage() output with class name

    My guess is that you've got something in method1 which wraps one exception in another, and uses the toString() of the nested exception as the message of the wrapper. I suggest you take a copy of your project, and remove as much as you can while keeping the problem, until you've got a short but complete program which demonstrates it - at which point either it'll be clear what's going on, or we'll be in a better position to help fix it.

    Here's a short but complete program which demonstrates RuntimeException.getMessage() behaving correctly:

    public class Test {
        public static void main(String[] args) {
            try {
                failingMethod();
            } catch (Exception e) {
                System.out.println("Error: " + e.getMessage());
            }
        }       
    
        private static void failingMethod() {
            throw new RuntimeException("Just the message");
        }
    }
    

    Output:

    Error: Just the message
    

    Is there a better alternative than this to 'switch on type'?

    Switching on types is definitely lacking in C# (UPDATE: in C#7 / VS 2017 switching on types is supported - see Zachary Yates's answer below). In order to do this without a large if/else if/else statement, you'll need to work with a different structure. I wrote a blog post awhile back detailing how to build a TypeSwitch structure.

    https://docs.microsoft.com/archive/blogs/jaredpar/switching-on-types

    Short version: TypeSwitch is designed to prevent redundant casting and give a syntax that is similar to a normal switch/case statement. For example, here is TypeSwitch in action on a standard Windows form event

    TypeSwitch.Do(
        sender,
        TypeSwitch.Case<Button>(() => textBox1.Text = "Hit a Button"),
        TypeSwitch.Case<CheckBox>(x => textBox1.Text = "Checkbox is " + x.Checked),
        TypeSwitch.Default(() => textBox1.Text = "Not sure what is hovered over"));
    

    The code for TypeSwitch is actually pretty small and can easily be put into your project.

    static class TypeSwitch {
        public class CaseInfo {
            public bool IsDefault { get; set; }
            public Type Target { get; set; }
            public Action<object> Action { get; set; }
        }
    
        public static void Do(object source, params CaseInfo[] cases) {
            var type = source.GetType();
            foreach (var entry in cases) {
                if (entry.IsDefault || entry.Target.IsAssignableFrom(type)) {
                    entry.Action(source);
                    break;
                }
            }
        }
    
        public static CaseInfo Case<T>(Action action) {
            return new CaseInfo() {
                Action = x => action(),
                Target = typeof(T)
            };
        }
    
        public static CaseInfo Case<T>(Action<T> action) {
            return new CaseInfo() {
                Action = (x) => action((T)x),
                Target = typeof(T)
            };
        }
    
        public static CaseInfo Default(Action action) {
            return new CaseInfo() {
                Action = x => action(),
                IsDefault = true
            };
        }
    }
    

    Working with UTF-8 encoding in Python source

    Do not forget to verify if your text editor encodes properly your code in UTF-8.

    Otherwise, you may have invisible characters that are not interpreted as UTF-8.

    How can I get the client's IP address in ASP.NET MVC?

    How I account for my site being behind an Amazon AWS Elastic Load Balancer (ELB):

    public class GetPublicIp {
    
        /// <summary>
        /// account for possbility of ELB sheilding the public IP address
        /// </summary>
        /// <returns></returns>
        public static string Execute() {
            try {
                Console.WriteLine(string.Join("|", new List<object> {
                        HttpContext.Current.Request.UserHostAddress,
                        HttpContext.Current.Request.Headers["X-Forwarded-For"],
                        HttpContext.Current.Request.Headers["REMOTE_ADDR"]
                    })
                );
    
                var ip = HttpContext.Current.Request.UserHostAddress;
                if (HttpContext.Current.Request.Headers["X-Forwarded-For"] != null) {
                    ip = HttpContext.Current.Request.Headers["X-Forwarded-For"];
                    Console.WriteLine(ip + "|X-Forwarded-For");
                }
                else if (HttpContext.Current.Request.Headers["REMOTE_ADDR"] != null) {
                    ip = HttpContext.Current.Request.Headers["REMOTE_ADDR"];
                    Console.WriteLine(ip + "|REMOTE_ADDR");
                }
                return ip;
            }
            catch (Exception ex) {
                Console.Error.WriteLine(ex.Message);
            }
            return null;
        }
    }
    

    Android: Bitmaps loaded from gallery are rotated in ImageView

    Solved it in my case with this code using help of this post:

                Bitmap myBitmap = getBitmap(imgFile.getAbsolutePath());
    
                try {
                    ExifInterface exif = new ExifInterface(imgFile.getAbsolutePath());
                    int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
                    Log.d("EXIF", "Exif: " + orientation);
                    Matrix matrix = new Matrix();
                    if (orientation == 6) {
                        matrix.postRotate(90);
                    }
                    else if (orientation == 3) {
                        matrix.postRotate(180);
                    }
                    else if (orientation == 8) {
                        matrix.postRotate(270);
                    }
                    myBitmap = Bitmap.createBitmap(myBitmap, 0, 0, myBitmap.getWidth(), myBitmap.getHeight(), matrix, true); // rotating bitmap
                }
                catch (Exception e) {
    
                }
                ImageView img = (ImageView) findViewById(R.id.imgTakingPic);
                img.setImageBitmap(myBitmap);
    

    Hope it saves someone's time!

    How to set proper codeigniter base url?

    Try to add the controller to your index page aswell. Just looked at as similar structure on one of my own site and I hade my base url set to = "somedomain.com/v2/controller"

    jQuery duplicate DIV into another DIV

    Copy code using clone and appendTo function :

    Here is also working example jsfiddle

    <!DOCTYPE html>
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    </head>
    <body>
    <div id="copy"><a href="http://brightwaay.com">Here</a> </div>
    <br/>
    <div id="copied"></div>
    <script type="text/javascript">
        $(function(){
            $('#copy').clone().appendTo('#copied');
        });
    </script>
    </body>
    </html>
    

    Execute Immediate within a stored procedure keeps giving insufficient priviliges error

    Alternatively you can grant the user DROP_ANY_TABLE privilege if need be and the procedure will run as is without the need for any alteration. Dangerous maybe but depends what you're doing :)

    How can I update a row in a DataTable in VB.NET?

    The problem you're running into is that you're trying to replace an entire row object. That is not allowed by the DataTable API. Instead you have to update the values in the columns of a row object. Or add a new row to the collection.

    To update the column of a particular row you can access it by name or index. For instance you could write the following code to update the column "Foo" to be the value strVerse

    dtResult.Rows(i)("Foo") = strVerse
    

    Save image from url with curl PHP

    Option #1

    Instead of picking the binary/raw data into a variable and then writing, you can use CURLOPT_FILE option to directly show a file to the curl for the downloading.

    Here is the function:

    // takes URL of image and Path for the image as parameter
    function download_image1($image_url, $image_file){
        $fp = fopen ($image_file, 'w+');              // open file handle
    
        $ch = curl_init($image_url);
        // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // enable if you want
        curl_setopt($ch, CURLOPT_FILE, $fp);          // output to file
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 1000);      // some large value to allow curl to run for a long time
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
        // curl_setopt($ch, CURLOPT_VERBOSE, true);   // Enable this line to see debug prints
        curl_exec($ch);
    
        curl_close($ch);                              // closing curl handle
        fclose($fp);                                  // closing file handle
    }
    

    And here is how you should call it:

    // test the download function
    download_image1("http://www.gravatar.com/avatar/10773ae6687b55736e171c038b4228d2", "local_image1.jpg");
    

    Option #2

    Now, If you want to download a very large file, that case above function may not become handy. You can use the below function this time for handling a big file. Also, you can print progress(in % or in any other format) if you want. Below function is implemented using a callback function that writes a chunk of data in to the file in to the progress of downloading.

    // takes URL of image and Path for the image as parameter
    function download_image2($image_url){
        $ch = curl_init($image_url);
        // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // enable if you want
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 1000);      // some large value to allow curl to run for a long time
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
        curl_setopt($ch, CURLOPT_WRITEFUNCTION, "curl_callback");
        // curl_setopt($ch, CURLOPT_VERBOSE, true);   // Enable this line to see debug prints
        curl_exec($ch);
    
        curl_close($ch);                              // closing curl handle
    }
    
    /** callback function for curl */
    function curl_callback($ch, $bytes){
        global $fp;
        $len = fwrite($fp, $bytes);
        // if you want, you can use any progress printing here
        return $len;
    }
    

    And here is how to call this function:

    // test the download function
    $image_file = "local_image2.jpg";
    $fp = fopen ($image_file, 'w+');              // open file handle
    download_image2("http://www.gravatar.com/avatar/10773ae6687b55736e171c038b4228d2");
    fclose($fp);                                  // closing file handle
    

    Angularjs ng-model doesn't work inside ng-if

    Yes, ng-hide (or ng-show) directive won't create child scope.

    Here is my practice:

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular.min.js"></script>
    
    <script>
        function main($scope) {
            $scope.testa = false;
            $scope.testb = false;
            $scope.testc = false;
            $scope.testd = false;
        }
    </script>
    
    <div ng-app >
        <div ng-controller="main">
    
            Test A: {{testa}}<br />
            Test B: {{testb}}<br />
            Test C: {{testc}}<br />
            Test D: {{testd}}<br />
    
            <div>
                testa (without ng-if): <input type="checkbox" ng-model="testa" />
            </div>
            <div ng-if="!testa">
                testb (with ng-if): <input type="checkbox" ng-model="$parent.testb" />
            </div>
            <div ng-show="!testa">
                testc (with ng-show): <input type="checkbox" ng-model="testc" />
            </div>
            <div ng-hide="testa">
                testd (with ng-hide): <input type="checkbox" ng-model="testd" />
            </div>
    
        </div>
    </div>
    

    http://jsfiddle.net/bn64Lrzu/

    What is the difference between Nexus and Maven?

    Whatever I understood from my learning and what I think it is is here. I am Quoting some part from a book i learnt this things. Nexus Repository Manager and Nexus Repository Manager OSS started as a repository manager supporting the Maven repository format. While it supports many other repository formats now, the Maven repository format is still the most common and well supported format for build and provisioning tools running on the JVM and beyond. This chapter shows example configurations for using the repository manager with Apache Maven and a number of other tools. The setups take advantage of merging many repositories and exposing them via a repository group. Setting this up is documented in the chapter in addition to the configuration used by specific tools.

    Details

    Returning multiple values from a C++ function

    With C++17 you can also return one ore more unmovable/uncopyable values (in certain cases). The possibility to return unmovable types come via the new guaranteed return value optimization, and it composes nicely with aggregates, and what can be called templated constructors.

    template<typename T1,typename T2,typename T3>
    struct many {
      T1 a;
      T2 b;
      T3 c;
    };
    
    // guide:
    template<class T1, class T2, class T3>
    many(T1, T2, T3) -> many<T1, T2, T3>;
    
    auto f(){ return many{string(),5.7, unmovable()}; }; 
    
    int main(){
       // in place construct x,y,z with a string, 5.7 and unmovable.
       auto [x,y,z] = f();
    }
    

    The pretty thing about this is that it is guaranteed to not cause any copying or moving. You can make the example many struct variadic too. More details:

    Returning variadic aggregates (struct) and syntax for C++17 variadic template 'construction deduction guide'

    How to subtract 30 days from the current datetime in mysql?

    Let's not use NOW() as you're losing any query caching or optimization because the query is different every time. See the list of functions you should not use in the MySQL documentation.

    In the code below, let's assume this table is growing with time. New stuff is added and you want to show just the stuff in the last 30 days. This is the most common case.

    Note that the date has been added as a string. It is better to add the date in this way, from your calling code, than to use the NOW() function as it kills your caching.

    SELECT * FROM table WHERE exec_datetime >= DATE_SUB('2012-06-12', INTERVAL 30 DAY);
    

    You can use BETWEEN if you really just want stuff from this very second to 30 days before this very second, but that's not a common use case in my experience, so I hope the simplified query can serve you well.

    Showing empty view when ListView is empty

    A programmatically solution will be:

    TextView textView = new TextView(context);
    textView.setId(android.R.id.empty);
    textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    textView.setText("No result found");
    listView.setEmptyView(textView);
    

    What is the difference between Python and IPython?

    Compared to Python, IPython (created by Fernando Perez in 2001) can do every thing what python can do. Ipython provides even extra features like tab-completion, testing, debugging, system calls and many other features. You can think IPython as a powerful interface to the Python language.

    You can install Ipython using pip - pip install ipython

    You can run Ipython by typing ipython in your terminal window.

    Loading and parsing a JSON file with multiple JSON objects

    You have a JSON Lines format text file. You need to parse your file line by line:

    import json
    
    data = []
    with open('file') as f:
        for line in f:
            data.append(json.loads(line))
    

    Each line contains valid JSON, but as a whole, it is not a valid JSON value as there is no top-level list or object definition.

    Note that because the file contains JSON per line, you are saved the headaches of trying to parse it all in one go or to figure out a streaming JSON parser. You can now opt to process each line separately before moving on to the next, saving memory in the process. You probably don't want to append each result to one list and then process everything if your file is really big.

    If you have a file containing individual JSON objects with delimiters in-between, use How do I use the 'json' module to read in one JSON object at a time? to parse out individual objects using a buffered method.

    How to insert a line break <br> in markdown

    I know this post is about adding a single line break but I thought I would mention that you can create multiple line breaks with the backslash (\) character:

    Hello
    \
    \
    \
    World!
    

    This would result in 3 new lines after "Hello". To clarify, that would mean 2 empty lines between "Hello" and "World!". It would display like this:


    Hello



    World!



    Personally I find this cleaner for a large number of line breaks compared to using <br>.

    Note that backslashes are not recommended for compatibility reasons. So this may not be supported by your Markdown parser but it's handy when it is.

    Make outer div be automatically the same height as its floating content

    You can set the outerdiv's CSS to this

    #outerdiv {
        overflow: hidden; /* make sure this doesn't cause unexpected behaviour */
    }
    

    You can also do this by adding an element at the end with clear: both. This can be added normally, with JS (not a good solution) or with :after CSS pseudo element (not widely supported in older IEs).

    The problem is that containers won't naturally expand to include floated children. Be warned with using the first example, if you have any children elements outside the parent element, they will be hidden. You can also use 'auto' as the property value, but this will invoke scrollbars if any element appears outside.

    You can also try floating the parent container, but depending on your design, this may be impossible/difficult.

    How to validate an e-mail address in swift?

    There are a lot of right answers here, but many of the "regex" are incomplete and it can happen that an email like: "name@domain" results a valid email, but it is not. Here the complete solution:

    extension String {
    
        var isEmailValid: Bool {
            do {
                let regex = try NSRegularExpression(pattern: "(?:[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])", options: .CaseInsensitive)
                return regex.firstMatchInString(self, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count)) != nil
            } catch {
                return false
            }
        }
    }
    

    How can one tell the version of React running at runtime in the browser?

    With the React Devtools installed you can run this from the browser console:

    __REACT_DEVTOOLS_GLOBAL_HOOK__.renderers.forEach(r => console.log(`${r.rendererPackageName}: ${r.version}`))
    

    Which outputs something like:

    react-dom: 16.12.0
    

    How to measure time taken by a function to execute

    export default class Singleton {
    
      static myInstance: Singleton = null;
    
      _timers: any = {};
    
      /**
       * @returns {Singleton}
       */
      static getInstance() {
        if (Singleton.myInstance == null) {
          Singleton.myInstance = new Singleton();
        }
    
        return this.myInstance;
      }
    
      initTime(label: string) {
        this._timers[label] = Date.now();
        return this._timers[label];
      }
    
      endTime(label: string) {
        const endTime = Date.now();
        if (this._timers[label]) {
          const delta = endTime - this._timers[label];
          const finalTime = `${label}: ${delta}ms`;
          delete this._timers[label];
          return finalTime;
        } else {
          return null;
        }
      }
    }
    

    InitTime related to string.

    return Singleton.getInstance().initTime(label); // Returns the time init

    return Singleton.getInstance().endTime(label); // Returns the total time between init and end

    Add / remove input field dynamically with jQuery

    I took the liberty of putting together a jsFiddle illustrating the functionality of building a custom form using jQuery. Here it is...

    EDIT: Updated the jsFiddle to include remove buttons for each field.

    EDIT: As per the request in the last comment, code from the jsFiddle is below.

    EDIT: As per Abhishek's comment, I have updated the jsFiddle (and code below) to cater for scenarios where duplicate field IDs might arise.

    HTML:

    <fieldset id="buildyourform">
        <legend>Build your own form!</legend>
    </fieldset>
    <input type="button" value="Preview form" class="add" id="preview" />
    <input type="button" value="Add a field" class="add" id="add" />
    

    JavaScript:

    $(document).ready(function() {
        $("#add").click(function() {
            var lastField = $("#buildyourform div:last");
            var intId = (lastField && lastField.length && lastField.data("idx") + 1) || 1;
            var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
            fieldWrapper.data("idx", intId);
            var fName = $("<input type=\"text\" class=\"fieldname\" />");
            var fType = $("<select class=\"fieldtype\"><option value=\"checkbox\">Checked</option><option value=\"textbox\">Text</option><option value=\"textarea\">Paragraph</option></select>");
            var removeButton = $("<input type=\"button\" class=\"remove\" value=\"-\" />");
            removeButton.click(function() {
                $(this).parent().remove();
            });
            fieldWrapper.append(fName);
            fieldWrapper.append(fType);
            fieldWrapper.append(removeButton);
            $("#buildyourform").append(fieldWrapper);
        });
        $("#preview").click(function() {
            $("#yourform").remove();
            var fieldSet = $("<fieldset id=\"yourform\"><legend>Your Form</legend></fieldset>");
            $("#buildyourform div").each(function() {
                var id = "input" + $(this).attr("id").replace("field","");
                var label = $("<label for=\"" + id + "\">" + $(this).find("input.fieldname").first().val() + "</label>");
                var input;
                switch ($(this).find("select.fieldtype").first().val()) {
                    case "checkbox":
                        input = $("<input type=\"checkbox\" id=\"" + id + "\" name=\"" + id + "\" />");
                        break;
                    case "textbox":
                        input = $("<input type=\"text\" id=\"" + id + "\" name=\"" + id + "\" />");
                        break;
                    case "textarea":
                        input = $("<textarea id=\"" + id + "\" name=\"" + id + "\" ></textarea>");
                        break;    
                }
                fieldSet.append(label);
                fieldSet.append(input);
            });
            $("body").append(fieldSet);
        });
    });
    

    CSS:

    body
    {
        font-family:Gill Sans MT;
        padding:10px;
    }
    fieldset
    {
        border: solid 1px #000;
        padding:10px;
        display:block;
        clear:both;
        margin:5px 0px;
    }
    legend
    {
        padding:0px 10px;
        background:black;
        color:#FFF;
    }
    input.add
    {
        float:right;
    }
    input.fieldname
    {
        float:left;
        clear:left;
        display:block;
        margin:5px;
    }
    select.fieldtype
    {
        float:left;
        display:block;
        margin:5px;
    }
    input.remove
    {
        float:left;
        display:block;
        margin:5px;
    }
    #yourform label
    {
        float:left;
        clear:left;
        display:block;
        margin:5px;
    }
    #yourform input, #yourform textarea
    {
        float:left;
        display:block;
        margin:5px;
    }
    

    string comparison in batch file

    Just put quotes around the Environment variable (as you have done) :
    if "%DevEnvDir%" == "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\"
    but it's the way you put opening bracket without a space that is confusing it.

    Works for me...

    C:\if "%gtk_basepath%" == "C:\Program Files\GtkSharp\2.12\" (echo yes)
    yes
    

    Get all files modified in last 30 days in a directory

    A couple of issues

    • You're not limiting it to files, so when it finds a matching directory it will list every file within it.
    • You can't use > in -exec without something like bash -c '... > ...'. Though the > will overwrite the file, so you want to redirect the entire find anyway rather than each -exec.
    • +30 is older than 30 days, -30 would be modified in last 30 days.
    • -exec really isn't needed, you could list everything with various -printf options.

    Something like below should work

    find . -type f -mtime -30 -exec ls -l {} \; > last30days.txt
    

    Example with -printf

    find . -type f -mtime -30 -printf "%M %u %g %TR %TD %p\n" > last30days.txt
    

    This will list files in format "permissions owner group time date filename". -printf is generally preferable to -exec in cases where you don't have to do anything complicated. This is because it will run faster as a result of not having to execute subshells for each -exec. Depending on the version of find, you may also be able to use -ls, which has a similar format to above.

    RegEx to match stuff between parentheses

    You need to make your regex pattern 'non-greedy' by adding a '?' after the '.+'

    By default, '*' and '+' are greedy in that they will match as long a string of chars as possible, ignoring any matches that might occur within the string.

    Non-greedy makes the pattern only match the shortest possible match.

    See Watch Out for The Greediness! for a better explanation.

    Or alternately, change your regex to

    \(([^\)]+)\)
    

    which will match any grouping of parens that do not, themselves, contain parens.

    Inject service in app.config

    Set up your service as a custom AngularJS Provider

    Despite what the Accepted answer says, you actually CAN do what you were intending to do, but you need to set it up as a configurable provider, so that it's available as a service during the configuration phase.. First, change your Service to a provider as shown below. The key difference here is that after setting the value of defer, you set the defer.promise property to the promise object returned by $http.get:

    Provider Service: (provider: service recipe)

    app.provider('dbService', function dbServiceProvider() {
    
      //the provider recipe for services require you specify a $get function
      this.$get= ['dbhost',function dbServiceFactory(dbhost){
         // return the factory as a provider
         // that is available during the configuration phase
         return new DbService(dbhost);  
      }]
    
    });
    
    function DbService(dbhost){
        var status;
    
        this.setUrl = function(url){
            dbhost = url;
        }
    
        this.getData = function($http) {
            return $http.get(dbhost+'db.php/score/getData')
                .success(function(data){
                     // handle any special stuff here, I would suggest the following:
                     status = 'ok';
                     status.data = data;
                 })
                 .error(function(message){
                     status = 'error';
                     status.message = message;
                 })
                 .then(function(){
                     // now we return an object with data or information about error 
                     // for special handling inside your application configuration
                     return status;
                 })
        }    
    }
    

    Now, you have a configurable custom Provider, you just need to inject it. Key difference here being the missing "Provider on your injectable".

    config:

    app.config(function ($routeProvider) { 
        $routeProvider
            .when('/', {
                templateUrl: "partials/editor.html",
                controller: "AppCtrl",
                resolve: {
                    dbData: function(DbService, $http) {
                         /*
                         *dbServiceProvider returns a dbService instance to your app whenever
                         * needed, and this instance is setup internally with a promise, 
                         * so you don't need to worry about $q and all that
                         */
                        return DbService('http://dbhost.com').getData();
                    }
                }
            })
    });
    

    use resolved data in your appCtrl

    app.controller('appCtrl',function(dbData, DbService){
         $scope.dbData = dbData;
    
         // You can also create and use another instance of the dbService here...
         // to do whatever you programmed it to do, by adding functions inside the 
         // constructor DbService(), the following assumes you added 
         // a rmUser(userObj) function in the factory
         $scope.removeDbUser = function(user){
             DbService.rmUser(user);
         }
    
    })
    

    Possible Alternatives

    The following alternative is a similar approach, but allows definition to occur within the .config, encapsulating the service to within the specific module in the context of your app. Choose the method that right for you. Also see below for notes on a 3rd alternative and helpful links to help you get the hang of all these things

    app.config(function($routeProvider, $provide) {
        $provide.service('dbService',function(){})
        //set up your service inside the module's config.
    
        $routeProvider
            .when('/', {
                templateUrl: "partials/editor.html",
                controller: "AppCtrl",
                resolve: {
                    data: 
                }
            })
    });
    

    A few helpful Resources

    • John Lindquist has an excellent 5 minute explanation and demonstration of this at egghead.io, and it's one of the free lessons! I basically modified his demonstration by making it $http specific in the context of this request
    • View the AngularJS Developer guide on Providers
    • There is also an excellent explanation about factory/service/provider at clevertech.biz.

    The provider gives you a bit more configuration over the .service method, which makes it better as an application level provider, but you could also encapsulate this within the config object itself by injecting $provide into config like so:

    Embedding SVG into ReactJS

    According to a react developer, you dont need the namespace xmlns. If you need the attribute xlink:href you can use xlinkHref from react 0.14

    Example

    Icon = (props) => {
      return <svg className="icon">
        <use xlinkHref={ '#' + props.name }></use>
      </svg>;
    }
    

    How to calculate a mod b in Python?

    Why don't you use % ?

    
    print 4 % 2 # 0
    

    How to skip to next iteration in jQuery.each() util?

    Javascript sort of has the idea of 'truthiness' and 'falsiness'. If a variable has a value then, generally 9as you will see) it has 'truthiness' - null, or no value tends to 'falsiness'. The snippets below might help:

    var temp1; 
    if ( temp1 )...  // false
    
    var temp2 = true;
    if ( temp2 )...  // true
    
    var temp3 = "";
    if ( temp3 ).... // false
    
    var temp4 = "hello world";
    if ( temp4 )...  // true
    

    Hopefully that helps?

    Also, its worth checking out these videos from Douglas Crockford

    update: thanks @cphpython for spotting the broken links - I've updated to point at working versions now

    The Javascript language

    Javascript - The Good Parts

    Node.js quick file server (static files over HTTP)

    Here is my one-file/lightweight node.js static file web-server pet project with no-dependency that I believe is a quick and rich tool which its use is as easy as issuing this command on your Linux/Unix/macOS terminal (or termux on Android) when node.js (or nodejs-legacy on Debian/Ubuntu) is installed:

    curl pad.js.org | node 
    

    (different commands exist for Windows users on the documentation)

    It supports different things that I believe can be found useful,

    • Hierarchical directory index creation/serving
      • With sort capability on the different criteria
      • Upload from browser by [multi-file] drag-and-drop and file/text-only copy-paste and system clipboard screen-shot paste on Chrome, Firefox and other browsers may with some limitations (which can be turned off by command line options it provides)
      • Folder/note-creation/upload button
    • Serving correct MIMEs for well known file types (with possibility for disabling that)
    • Possibility of installation as a npm package and local tool or, one-linear installation as a permanent service with Docker
    • HTTP 206 file serving (multipart file transfer) for faster transfers
    • Uploads from terminal and browser console (in fact it was originally intended to be a file-system proxy for JS console of browsers on other pages/domains)
    • CORS download/uploads (which also can be turned off)
    • Easy HTTPS integration
    • Lightweight command line options for achieving better secure serving with it:
      • With my patch on node.js 8, you can have access to the options without first installation: curl pad.js.org | node - -h
      • Or first install it as a system-global npm package by [sudo] npm install -g pad.js and then use its installed version to have access to its options: pad -h
      • Or use the provided Docker image which uses relatively secure options by default. [sudo] docker run --restart=always -v /files:/files --name pad.js -d -p 9090:9090 quay.io/ebraminio/pad.js

    Screenshot of a folder index using the tool

    The features described above are mostly documented on the main page of the tool http://pad.js.org which by some nice trick I used is also the place the tool source itself is also served from!

    The tool source is on GitHub which welcomes your feedback, feature requests and ?s!

    Use virtualenv with Python with Visual Studio Code in Ubuntu

    I was able to use the workspace setting that other people on this page have been asking for.

    In Preferences, ?+P, search for python.pythonPath in the search bar.

    You should see something like:

    // Path to Python, you can use a custom version of Python by modifying this setting to include the full path.
    "python.pythonPath": "python"
    

    Then click on the WORKSPACE SETTINGS tab on the right side of the window. This will make it so the setting is only applicable to the workspace you're in.

    Afterwards, click on the pencil icon next to "python.pythonPath". This should copy the setting over the workspace settings.

    Change the value to something like:

    "python.pythonPath": "${workspaceFolder}/venv"
    

    What does <> mean in excel?

    It means "not equal to" (as in, the values in cells E37-N37 are not equal to "", or in other words, they are not empty.)

    Make HTML5 video poster be same size as video itself

    You can use a transparent poster image in combination with a CSS background image to achieve this (example); however, to have a background stretched to the height and the width of a video, you'll have to use an absolutely positioned <img> tag (example).

    It is also possible to set background-size to 100% 100% in browsers that support background-size (example).


    Update

    A better way to do this would be to use the object-fit CSS property as @Lars Ericsson suggests.

    Use

    object-fit: cover;
    

    if you don't want to display those parts of the image that don't fit the video's aspect ratio, and

    object-fit: fill;
    

    to stretch the image to fit your video's aspect ratio

    Example

    Multiple submit buttons on HTML form – designate one button as default

    Set type=submit to the button you'd like to be default and type=button to other buttons. Now in the form below you can hit Enter in any input fields, and the Render button will work (despite the fact it is the second button in the form).

    Example:

        <button id='close_button' class='btn btn-success'
                type=button>
          <span class='glyphicon glyphicon-edit'> </span> Edit program
        </button>
        <button id='render_button' class='btn btn-primary'
                type=submit>             <!--  Here we use SUBMIT, not BUTTON -->
          <span class='glyphicon glyphicon-send'> </span> Render
        </button>
    

    Tested in FF24 and Chrome 35.

    How to access share folder in virtualbox. Host Win7, Guest Fedora 16?

    These are the steps to share a folder from Windows to Linux Virtual Box

    Step 1 : Install Virtual Box Extension Pack from this link

    Step 2: Install Oracle Guest Additions:

    By pressing -> Right Ctrl and d together

    Run the command sudo /media/VBOXADDITIONS_4.*/VBoxLinuxAdditions.run

    Step 3 : Create Shared Folder by Clicking Settings in Vbox Then Shared Folders -> + and give a name to the folder (e.g. VB_Share) Select the Shared Folder path on Windows (e.g. D:\VBox_Share)

    Step 4: Create a folder in named VB_share in home\user-name (e.g. home\satish\VB_share) and share mkdir VB_Share chmod 777 VB_share

    Step 5: Run the following command sudo mount –t vboxsf vBox_Share VB_Share

    Java Date vs Calendar

    I generally use Date if possible. Although it is mutable, the mutators are actually deprecated. In the end it basically wraps a long that would represent the date/time. Conversely, I would use Calendars if I have to manipulate the values.

    You can think of it this way: you only use StringBuffer only when you need to have Strings that you can easily manipulate and then convert them into Strings using toString() method. In the same way, I only use Calendar if I need to manipulate temporal data.

    For best practice, I tend to use immutable objects as much as possible outside of the domain model. It significantly reduces the chances of any side effects and it is done for you by the compiler, rather than a JUnit test. You use this technique by creating private final fields in your class.

    And coming back to the StringBuffer analogy. Here is some code that shows you how to convert between Calendar and Date

    String s = "someString"; // immutable string
    StringBuffer buf = new StringBuffer(s); // mutable "string" via StringBuffer
    buf.append("x");
    assertEquals("someStringx", buf.toString()); // convert to immutable String
    
    // immutable date with hard coded format.  If you are hard
    // coding the format, best practice is to hard code the locale
    // of the format string, otherwise people in some parts of Europe
    // are going to be mad at you.
    Date date =     new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse("2001-01-02");
    
    // Convert Date to a Calendar
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    
    // mutate the value
    cal.add(Calendar.YEAR, 1);
    
    // convert back to Date
    Date newDate = cal.getTime();
    
    // 
    assertEquals(new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse("2002-01-02"), newDate);
    

    What does `unsigned` in MySQL mean and when to use it?

    MySQL says:

    All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.

    When do I use it ?

    Ask yourself this question: Will this field ever contain a negative value?
    If the answer is no, then you want an UNSIGNED data type.

    A common mistake is to use a primary key that is an auto-increment INT starting at zero, yet the type is SIGNED, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.

    Apache SSL Configuration Error (SSL Connection Error)

    I encountered this issue, also due to misconfiguration. I was using tomcat and in the server.xml had specified my connector as such:

    <Connector port="17443" SSLEnabled="true"
               protocol="org.apache.coyote.http11.Http11NioProtocol"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS"
               keyAlias="wrong" keystorePass="secret"
               keystoreFile="/ssl/right.jks" />
    

    When i fixed it thusly:

    <Connector port="17443" SSLEnabled="true"
               protocol="org.apache.coyote.http11.Http11NioProtocol"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS"
               keyAlias="right" keystorePass="secret"
               keystoreFile="/ssl/right.jks" />
    

    It worked as expected. In other words, verify that you not only have the right keystore, but that you have specified the correct alias underneath it. Thanks for the invaluable hint user396404.

    How can I force WebKit to redraw/repaint to propagate style changes?

    the "display/offsetHeight" hack didn't work in my case, at least when it was applied to the element being animated.

    i had a dropdown menu that was being open/closed over the page content. the artifacts were being left on the page content after the menu had closed (only in webkit browsers). the only way the "display/offsetHeight" hack worked is if i applied it to the body, which seems nasty.

    however, i did find another solution:

    1. before the element starts animating, add a class that defines "-webkit-backface-visibility: hidden;" on the element (you could also use inline style, i'd guess)
    2. when it's done animating, remove the class (or style)

    this is still pretty hacky (it uses a CSS3 property to force hardware rendering), but at least it only affects the element in question, and worked for me on both safari and chrome on PC and Mac.

    System.IO.FileNotFoundException: Could not load file or assembly 'X' or one of its dependencies when deploying the application

    's up guys i read every single forum about this topic i still had problem (occurred trying to project from git)

    after 4 hours and a lot of swearing i solved this issue by myself just by changing target framework setting in project properties (right click on project -> properties) -> application and changed target framework from .net core 3.0 to .net 5.0 i hope it will help anybody

    happy coding gl hf nerds

    Position of a string within a string using Linux shell script?

    You can use grep to get the byte-offset of the matching part of a string:

    echo $str | grep -b -o str
    

    As per your example:

    [user@host ~]$ echo "The cat sat on the mat" | grep -b -o cat
    4:cat
    

    you can pipe that to awk if you just want the first part

    echo $str | grep -b -o str | awk 'BEGIN {FS=":"}{print $1}'
    

    make div's height expand with its content

    I know this is kind of old thread, however, this can be achieved with min-height CSS property in a clean way, so I'll leave this here for future references:

    I made a fiddle based on the OP posted code here: http://jsfiddle.net/U5x4T/1/, as you remove and add divs inside, you'll notice how does the container expands or reduces in size

    The only 2 things you need to achieve this, additional to the OP code is:

    *Overflow in the main container (required for the floating divs)

    *min-height css property, more info available here: http://www.w3schools.com/cssref/pr_dim_min-height.asp

    How to compress a String in Java?

    Huffman encoding is a sensible option here. Gzip and friends do this, but the way they work is to build a Huffman tree for the input, send that, then send the data encoded with the tree. If the tree is large relative to the data, there may be no not saving in size.

    However, it is possible to avoid sending a tree: instead, you arrange for the sender and receiver to already have one. It can't be built specifically for every string, but you can have a single global tree used to encode all strings. If you build it from the same language as the input strings (English or whatever), you should still get good compression, although not as good as with a custom tree for every input.

    How can I install an older version of a package via NuGet?

    I've used Xavier's answer quite a bit. I want to add that restricting the package version to a specified range is easy and useful in the latest versions of NuGet.

    For example, if you never want Newtonsoft.Json to be updated past version 3.x.x in your project, change the corresponding package element in your packages.config file to look like this:

    <package id="Newtonsoft.Json" version="3.5.8" allowedVersions="[3.0, 4.0)" targetFramework="net40" />
    

    Notice the allowedVersions attribute. This will limit the version of that package to versions between 3.0 (inclusive) and 4.0 (exclusive). Then, when you do an Update-Package on the whole solution, you don't need to worry about that particular package being updated past version 3.x.x.

    The documentation for this functionality is here.

    SELECT * FROM in MySQLi

    You can still use it (mysqli is just another way of communicating with the server, the SQL language itself is expanded, not changed). Prepared statements are safer, though - since you don't need to go through the trouble of properly escaping your values each time. You can leave them as they were, if you want to but the risk of sql piggybacking is reduced if you switch.

    Search and replace part of string in database

    I think 2 update calls should do

    update VersionedFields
    set Value = replace(value,'<iframe','<a><iframe')
    
    update VersionedFields
    set Value = replace(value,'> </iframe>','</a>')
    

    What are the file limits in Git (number and size)?

    If you add files that are too large (GBs in my case, Cygwin, XP, 3 GB RAM), expect this.

    fatal: Out of memory, malloc failed

    More details here

    Update 3/2/11: Saw similar in Windows 7 x64 with Tortoise Git. Tons of memory used, very very slow system response.

    How to show disable HTML select option in by default?

    we can disable using this technique.

    <select class="form-control" name="option_select">
      <option selected="true" disabled="disabled">Select option </option>
      <option value="Option A">Option A</option>
      <option value="Option B">Option B</option>
      <option value="Option C">Option C</option>
    </select>
    

    Invariant Violation: Could not find "store" in either the context or props of "Connect(SportsDatabase)"

    As the official docs of redux suggest, better to export the unconnected component as well.

    In order to be able to test the App component itself without having to deal with the decorator, we recommend you to also export the undecorated component:

    import { connect } from 'react-redux'
    
    // Use named export for unconnected component (for tests)
    export class App extends Component { /* ... */ }
     
    // Use default export for the connected component (for app)
    export default connect(mapStateToProps)(App)
    

    Since the default export is still the decorated component, the import statement pictured above will work as before so you won't have to change your application code. However, you can now import the undecorated App components in your test file like this:

    // Note the curly braces: grab the named export instead of default export
    import { App } from './App'
    

    And if you need both:

    import ConnectedApp, { App } from './App'
    

    In the app itself, you would still import it normally:

    import App from './App'
    

    You would only use the named export for tests.

    Convert String to java.util.Date

    I think your date format does not make sense. There is no 13:00 PM. Remove the "aaa" at the end of your format or turn the HH into hh.

    Nevertheless, this works fine for me:

    String testDate = "29-Apr-2010,13:00:14 PM";
    DateFormat formatter = new SimpleDateFormat("d-MMM-yyyy,HH:mm:ss aaa");
    Date date = formatter.parse(testDate);
    System.out.println(date);
    

    It prints "Thu Apr 29 13:00:14 CEST 2010".

    Error in eval(expr, envir, enclos) : object not found

    Don't know why @Janos deleted his answer, but it's correct: your data frame Train doesn't have a column named pre. When you pass a formula and a data frame to a model-fitting function, the names in the formula have to refer to columns in the data frame. Your Train has columns called residual.sugar, total.sulfur, alcohol and quality. You need to change either your formula or your data frame so they're consistent with each other.

    And just to clarify: Pre is an object containing a formula. That formula contains a reference to the variable pre. It's the latter that has to be consistent with the data frame.

    Capturing image from webcam in java?

    Here is a similar question with some - yet unaccepted - answers. One of them mentions FMJ as a java alternative to JMF.

    Select 50 items from list at random to write to file

    Say your list has 100 elements and you want to pick 50 of them in a random way. Here are the steps to follow:

    1. Import the libraries
    2. Create the seed for random number generator, I have put it at 2
    3. Prepare a list of numbers from which to pick up in a random way
    4. Make the random choices from the numbers list

    Code:

    from random import seed
    from random import choice
    
    seed(2)
    numbers = [i for i in range(100)]
    
    print(numbers)
    
    for _ in range(50):
        selection = choice(numbers)
        print(selection)
    

    XAMPP Apache Webserver localhost not working on MAC OS

    I had success with easy killing all active httpd processes in Monitor Activity tool:

    1) close XAMPP control

    2) open Monitor Activity

    3) select filter for All processes (default is My processes)

    4) in fulltext search type: httpd

    5) kill all showen items

    6) relaunch XAMPP control and launch apache again

    Using grep and sed to find and replace a string

    You can use find and -exec directly into sed rather than first locating oldstr with grep. It's maybe a bit less efficient, but that might not be important. This way, the sed replacement is executed over all files listed by find, but if oldstr isn't there it obviously won't operate on it.

    find /path -type f -exec sed -i 's/oldstr/newstr/g' {} \;
    

    How to convert list to string

    By using ''.join

    list1 = ['1', '2', '3']
    str1 = ''.join(list1)
    

    Or if the list is of integers, convert the elements before joining them.

    list1 = [1, 2, 3]
    str1 = ''.join(str(e) for e in list1)
    

    CSS change button style after click

    It is possible to do with CSS only by selecting active and focus pseudo element of the button.

    button:active{
        background:olive;
    }
    
    button:focus{
        background:olive;
    }
    

    See codepen: http://codepen.io/fennefoss/pen/Bpqdqx

    You could also write a simple jQuery click function which changes the background color.

    HTML:

    <button class="js-click">Click me!</button>
    

    CSS:

    button {
      background: none;
    }
    

    JavaScript:

      $( ".js-click" ).click(function() {
        $( ".js-click" ).css('background', 'green');
      });
    

    Check out this codepen: http://codepen.io/fennefoss/pen/pRxrVG

    Get css top value as number not as string?

    You can use the parseInt() function to convert the string to a number, e.g:

    parseInt($('#elem').css('top'));
    

    Update: (as suggested by Ben): You should give the radix too:

    parseInt($('#elem').css('top'), 10);
    

    Forces it to be parsed as a decimal number, otherwise strings beginning with '0' might be parsed as an octal number (might depend on the browser used).

    How to find cube root using Python?

    def cube(x):
        if 0<=x: return x**(1./3.)
        return -(-x)**(1./3.)
    print (cube(8))
    print (cube(-8))
    

    Here is the full answer for both negative and positive numbers.

    >>> 
    2.0
    -2.0
    >>> 
    

    Or here is a one-liner;

    root_cube = lambda x: x**(1./3.) if 0<=x else -(-x)**(1./3.)
    

    Is there a standardized method to swap two variables in Python?

    Does not work for multidimensional arrays, because references are used here.

    import numpy as np
    
    # swaps
    data = np.random.random(2)
    print(data)
    data[0], data[1] = data[1], data[0]
    print(data)
    
    # does not swap
    data = np.random.random((2, 2))
    print(data)
    data[0], data[1] = data[1], data[0]
    print(data)
    

    See also Swap slices of Numpy arrays

    Inheriting from a template class in c++

    class Rectangle : public Area<int> {
    };
    

    How to programmatically set drawableLeft on Android button?

    Following is the way to change the color of the left icon in edit text and set it in left side.

     Drawable img = getResources().getDrawable( R.drawable.user );
    img.setBounds( 0, 0, 60, 60 );
    mNameEditText.setCompoundDrawables(img,null, null, null);
    
    int color = ContextCompat.getColor(this, R.color.blackColor);
    
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        DrawableCompat.setTint(img, color);
    
    } else {
        img.mutate().setColorFilter(color, PorterDuff.Mode.SRC_IN);
    }
    

    How can I join on a stored procedure?

    It has already been answered, the best way work-around is to convert the Stored Procedure into an SQL Function or a View.

    The short answer, just as mentioned above, is that you cannot directly JOIN a Stored Procedure in SQL, not unless you create another stored procedure or function using the stored procedure's output into a temporary table and JOINing the temporary table, as explained above.

    I will answer this by converting your Stored Procedure into an SQL function and show you how to use it inside a query of your choice.

    CREATE FUNCTION fnMyFunc()
    RETURNS TABLE AS
    RETURN 
    (
      SELECT tenant.ID AS TenantID, 
           SUM(ISNULL(trans.Amount,0)) AS TenantBalance 
      FROM tblTenant tenant
        LEFT JOIN tblTransaction trans ON tenant.ID = trans.TenantID
      GROUP BY tenant.ID
    )
    

    Now to use that function, in your SQL...

    SELECT t.TenantName, 
           t.CarPlateNumber, 
           t.CarColor, 
           t.Sex, 
           t.SSNO, 
           t.Phone, 
           t.Memo,
           u.UnitNumber,
           p.PropertyName
    FROM tblTenant t
        LEFT JOIN tblRentalUnit u ON t.UnitID = u.ID
        LEFT JOIN tblProperty p ON u.PropertyID = p.ID
        LEFT JOIN dbo.fnMyFunc() AS a
             ON a.TenantID = t.TenantID
    ORDER BY p.PropertyName, t.CarPlateNumber
    

    If you wish to pass parameters into your function from within the above SQL, then I recommend you use CROSS APPLY or CROSS OUTER APPLY.

    Read up on that here.

    Cheers

    How to read a value from the Windows registry

    Typically the register key and value are constants in the program. If so, here is an example how to read a DWORD registry value Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem\LongPathsEnabled:

    #include <windows.h>
    
    DWORD val;
    DWORD dataSize = sizeof(val);
    if (ERROR_SUCCESS == RegGetValueA(HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Control\\FileSystem", "LongPathsEnabled", RRF_RT_DWORD, nullptr /*type not required*/, &val, &dataSize)) {
      printf("Value is %i\n", val);
      // no CloseKey needed because it is a predefined registry key
    }
    else {
      printf("Error reading.\n");
    }
    

    To adapt for other value types, see https://docs.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-reggetvaluea for complete spec.

    To prevent a memory leak, the JDBC Driver has been forcibly unregistered

    This error happened to me in a Grails Application with the JTDS Driver 1.3.0 (SQL Server). The problem was an incorrect login in SQL Server. After solve this issue (in SQL Server) my app was correctly deployed in Tomcat. Tip: I saw the error in stacktrace.log

    How to install pip for Python 3.6 on Ubuntu 16.10?

    Let's suppose that you have a system running Ubuntu 16.04, 16.10, or 17.04, and you want Python 3.6 to be the default Python.

    If you're using Ubuntu 16.04 LTS, you'll need to use a PPA:

    sudo add-apt-repository ppa:jonathonf/python-3.6  # (only for 16.04 LTS)
    

    Then, run the following (this works out-of-the-box on 16.10 and 17.04):

    sudo apt update
    sudo apt install python3.6
    sudo apt install python3.6-dev
    sudo apt install python3.6-venv
    wget https://bootstrap.pypa.io/get-pip.py
    sudo python3.6 get-pip.py
    sudo ln -s /usr/bin/python3.6 /usr/local/bin/python3
    sudo ln -s /usr/local/bin/pip /usr/local/bin/pip3
    
    # Do this only if you want python3 to be the default Python
    # instead of python2 (may be dangerous, esp. before 2020):
    # sudo ln -s /usr/bin/python3.6 /usr/local/bin/python
    

    When you have completed all of the above, each of the following shell commands should indicate Python 3.6.1 (or a more recent version of Python 3.6):

    python --version   # (this will reflect your choice, see above)
    python3 --version
    $(head -1 `which pip` | tail -c +3) --version
    $(head -1 `which pip3` | tail -c +3) --version
    

    Why doesn't Dijkstra's algorithm work for negative weight edges?

    Try Dijkstra's algorithm on the following graph, assuming A is the source node and D is the destination, to see what is happening:

    Graph

    Note that you have to follow strictly the algorithm definition and you should not follow your intuition (which tells you the upper path is shorter).

    The main insight here is that the algorithm only looks at all directly connected edges and it takes the smallest of these edge. The algorithm does not look ahead. You can modify this behavior , but then it is not the Dijkstra algorithm anymore.

    Check string for nil & empty

    Swift 3 This works well to check if the string is really empty. Because isEmpty returns true when there's a whitespace.

    extension String {
        func isEmptyAndContainsNoWhitespace() -> Bool {
            guard self.isEmpty, self.trimmingCharacters(in: .whitespaces).isEmpty
                else {
                   return false
            }
            return true
        }
    }
    

    Examples:

    let myString = "My String"
    myString.isEmptyAndContainsNoWhitespace() // returns false
    
    let myString = ""
    myString.isEmptyAndContainsNoWhitespace() // returns true
    
    let myString = " "
    myString.isEmptyAndContainsNoWhitespace() // returns false
    

    How to add a "sleep" or "wait" to my Lua Script?

    if you're using a MacBook or UNIX based system, use this:

    function wait(time)
    if tonumber(time) ~= nil then
    os.execute("Sleep "..tonumber(time))
    else
    os.execute("Sleep "..tonumber("0.1"))
    end
    wait()
    

    Git update submodules recursively

    As it may happens that the default branch of your submodules are not master (which happens a lot in my case), this is how I automate the full Git submodules upgrades:

    git submodule init
    git submodule update
    git submodule foreach 'git fetch origin; git checkout $(git rev-parse --abbrev-ref HEAD); git reset --hard origin/$(git rev-parse --abbrev-ref HEAD); git submodule update --recursive; git clean -dfx'
    

    What is the documents directory (NSDocumentDirectory)?

    Aside from the Documents folder, iOS also lets you save files to the temp and Library folders.

    For more information on which one to use, see this link from the documentation:

    in a "using" block is a SqlConnection closed on return or exception?

    Using generates a try / finally around the object being allocated and calls Dispose() for you.

    It saves you the hassle of manually creating the try / finally block and calling Dispose()

    ASP.NET MVC3 Razor - Html.ActionLink style

    Here's the signature.

    public static string ActionLink(this HtmlHelper htmlHelper, 
                                    string linkText,
                                    string actionName,
                                    string controllerName,
                                    object values, 
                                    object htmlAttributes)
    

    What you are doing is mixing the values and the htmlAttributes together. values are for URL routing.

    You might want to do this.

    @Html.ActionLink(Context.User.Identity.Name, "Index", "Account", null, 
         new { @style="text-transform:capitalize;" });
    

    Batch - Echo or Variable Not Working

    Try the following (note that there should not be a space between the VAR, =, and GREG).

    SET VAR=GREG
    ECHO %VAR%
    PAUSE
    

    How can I combine flexbox and vertical scroll in a full-height app?

    Thanks to https://stackoverflow.com/users/1652962/cimmanon that gave me the answer.

    The solution is setting a height to the vertical scrollable element. For example:

    #container article {
        flex: 1 1 auto;
        overflow-y: auto;
        height: 0px;
    }
    

    The element will have height because flexbox recalculates it unless you want a min-height so you can use height: 100px; that it is exactly the same as: min-height: 100px;

    #container article {
        flex: 1 1 auto;
        overflow-y: auto;
        height: 100px; /* == min-height: 100px*/
    }
    

    So the best solution if you want a min-height in the vertical scroll:

    #container article {
        flex: 1 1 auto;
        overflow-y: auto;
        min-height: 100px;
    }
    

    If you just want full vertical scroll in case there is no enough space to see the article:

    #container article {
        flex: 1 1 auto;
        overflow-y: auto;
        min-height: 0px;
    }
    

    The final code: http://jsfiddle.net/ch7n6/867/

    Hex transparency in colors

    Using python to calculate this, for example(written in python 3), 50% transparency :

    hex(round(256*0.50))
    

    :)

    Check difference in seconds between two times

    This version always returns the number of seconds difference as a positive number (same result as @freedeveloper's solution):

    var seconds = System.Math.Abs((date1 - date2).TotalSeconds);
    

    Java - remove last known item from ArrayList

    This line means you instantiated a "List of ClientThread Objects".

    private List<ClientThread> clients = new ArrayList<ClientThread>();
    

    This line has two problems.

    String hey = clients.get(clients.size());
    

    1. This part of the line:

    clients.get(clients.size());
    

    ALWAYS throws IndexOutOfBoundsException because a collections size is always one bigger than its last elements index;

    2. Compiler complains about incompatible types because you cant assign a ClientThread object to String object. Correct one should be like this.

    ClientThread hey = clients.get(clients.size()-1);
    

    Last but not least. If you know index of the object to remove just write

     clients.remove(23); //Lets say it is in 23. index
    

    Don't write

       ClientThread hey = clients.get(23); 
    
       clients.remove(hey);
    

    because you are forcing the list to search for the index that you already know. If you plan to do something with the removed object later. Write

       ClientThread hey = clients.remove(23); 
    

    This way you can remove the object and get a reference to it at the same line.

    Bonus: Never ever call your instance variable with name "hey". Find something meaningful.

    And Here is your corrected and ready-to-run code:

    public class ListExampleForDan {
    
        private List<ClientThread> clients = new ArrayList<ClientThread>();
    
        public static void main(String args[]) {
    
            clients.add(new ClientThread("First and Last Client Thread"));
    
            boolean success = removeLastElement(clients);
    
            if (success) {
    
                System.out.println("Last Element Removed.");
    
            } else {
    
                System.out.println("List Is Null/Empty, Operation Failed.");
    
            }
    
        }
    
        public static boolean removeLastElement(List clients) {
    
            if (clients == null || clients.isEmpty()) {
    
                return false;
    
            } else {
    
                clients.remove(clients.size() - 1);
    
                return true;
    
            }
    
        }
    }
    

    Enjoy!

    Two arrays in foreach loop

    foreach operates on only one array at a time.

    The way your array is structured, you can array_combine() them into an array of key-value pairs then foreach that single array:

    foreach (array_combine($codes, $names) as $code => $name) {
        echo '<option value="' . $code . '">' . $name . '</option>';
    }
    

    Or as seen in the other answers, you can hardcode an associative array instead.

    POST JSON fails with 415 Unsupported media type, Spring 3 mvc

    A small side note - stumbled upon this same error while developing a web application. The mistake we found, by toying with the service with Firefox Poster, was that both fields and values in the Json should be surrounded by double quotes. For instance..

    [ {"idProductCategory" : "1" , "description":"Descrizione1"}, 
      {"idProductCategory" : "2" , "description":"Descrizione2"} ]
    

    In our case we filled the json via javascript, which can be a little confusing when it comes with dealing with single/double quotes, from what I've heard.

    What's been said before in this and other posts, like including the 'Accept' and 'Content-Type' headers, applies too.

    Hope t'helps.

    How to split one string into multiple strings separated by at least one space in bash shell?

    (A) To split a sentence into its words (space separated) you can simply use the default IFS by using

    array=( $string )
    


    Example running the following snippet

    #!/bin/bash
    
    sentence="this is the \"sentence\"   'you' want to split"
    words=( $sentence )
    
    len="${#words[@]}"
    echo "words counted: $len"
    
    printf "%s\n" "${words[@]}" ## print array
    

    will output

    words counted: 8
    this
    is
    the
    "sentence"
    'you'
    want
    to
    split
    

    As you can see you can use single or double quotes too without any problem

    Notes:
    -- this is basically the same of mob's answer, but in this way you store the array for any further needing. If you only need a single loop, you can use his answer, which is one line shorter :)
    -- please refer to this question for alternate methods to split a string based on delimiter.


    (B) To check for a character in a string you can also use a regular expression match.
    Example to check for the presence of a space character you can use:

    regex='\s{1,}'
    if [[ "$sentence" =~ $regex ]]
        then
            echo "Space here!";
    fi
    

    How to redirect to an external URL in Angular2?

    An Angular approach to the methods previously described is to import DOCUMENT from @angular/common (or @angular/platform-browser in Angular < 4) and use

    document.location.href = 'https://stackoverflow.com';
    

    inside a function.

    some-page.component.ts

    import { DOCUMENT } from '@angular/common';
    ...
    constructor(@Inject(DOCUMENT) private document: Document) { }
    
    goToUrl(): void {
        this.document.location.href = 'https://stackoverflow.com';
    }
    

    some-page.component.html

    <button type="button" (click)="goToUrl()">Click me!</button>
    

    Check out the plateformBrowser repo for more info.

    Get file name from a file location in Java

    new File(fileName).getName();
    

    or

    int idx = fileName.replaceAll("\\\\", "/").lastIndexOf("/");
    return idx >= 0 ? fileName.substring(idx + 1) : fileName;
    

    Notice that the first solution is system dependent. It only takes the system's path separator character into account. So if your code runs on a Unix system and receives a Windows path, it won't work. This is the case when processing file uploads being sent by Internet Explorer.

    How to cd into a directory with space in the name?

    To change to a directory with spaces on the name you just have to type like this:

    cd My\ Documents

    Hit enter and you will be good

    How to tell PowerShell to wait for each command to end before starting the next?

    Besides using Start-Process -Wait, piping the output of an executable will make Powershell wait. Depending on the need, I will typically pipe to Out-Null, Out-Default, Out-String or Out-String -Stream. Here is a long list of some other output options.

    # Saving output as a string to a variable.
    $output = ping.exe example.com | Out-String
    
    # Filtering the output.
    ping stackoverflow.com | where { $_ -match '^reply' }
    
    # Using Start-Process affords the most control.
    Start-Process -Wait SomeExecutable.com
    

    I do miss the CMD/Bash style operators that you referenced (&, &&, ||). It seems we have to be more verbose with Powershell.

    Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document'

    Although this is valid in HTML, you can't use an ID starting with an integer in CSS selectors.

    As pointed out, you can use getElementById instead, but you can also still achieve the same with a querySelector:

    document.querySelector("[id='22']")
    

    Why is vertical-align:text-top; not working in CSS

    The all above not work for me, I have just checked this and its work :

    vertical-align: super;

     <div id="lbk_mng_rdooption" style="float: left;">
         <span class="bold" style="vertical-align: super;">View:</span>
     </div>
    

    I know by padding or margin will work, but that is last choise I prefer.

    JavaScript getElementByID() not working

    Because when the script executes the browser has not yet parsed the <body>, so it does not know that there is an element with the specified id.

    Try this instead:

    <html>
    <head>
        <title></title>
        <script type="text/javascript">
            window.onload = (function () {
                var refButton = document.getElementById("btnButton");
    
                refButton.onclick = function() {
                    alert('Dhoor shala!');
                };
            });
        </script>
        </head>
    <body>
        <form id="form1">
        <div>
            <input id="btnButton" type="button" value="Click me"/>
        </div>
    </form>
    </body>
    </html>
    

    Note that you may as well use addEventListener instead of window.onload = ... to make that function only execute after the whole document has been parsed.

    How can I install a local gem?

    if you download the project file from github or other scm host site, use gem build to build the project first, so you can get a whatever.gem file in current directory. Then gem install it!

    SQL Server - NOT IN

    SELECT [T1].*
    FROM [Table1] AS [T1]
    WHERE  NOT EXISTS (SELECT 
        1 AS [C1]
        FROM [Table2] AS [T2]
        WHERE ([T2].[MAKE] = [T1].[MAKE]) AND
            ([T2].[MODEL] = [T1].[MODEL]) AND
            ([T2].[Serial Number] = [T1].[Serial Number])
    );
    

    How to get the second column from command output?

    This should work to get a specific column out of the command output "docker images":

    REPOSITORY                          TAG                 IMAGE ID            CREATED             SIZE
    ubuntu                              16.04               12543ced0f6f        10 months ago       122 MB
    ubuntu                              latest              12543ced0f6f        10 months ago       122 MB
    selenium/standalone-firefox-debug   2.53.0              9f3bab6e046f        12 months ago       613 MB
    selenium/node-firefox-debug         2.53.0              d82f2ab74db7        12 months ago       613 MB
    
    
    docker images | awk '{print $3}'
    
    IMAGE
    12543ced0f6f
    12543ced0f6f
    9f3bab6e046f
    d82f2ab74db7
    

    This is going to print the third column

    Printing Batch file results to a text file

    For showing result of batch file in text file, you can use

    this command

    chdir > test.txt
    

    This command will redirect result to test.txt.

    When you open test.txt you will found current path of directory in test.txt

    Responsive width Facebook Page Plugin

    After struggling for some time, I think I found out quite simple solution.

    Inspired by Robin Wilson I made this simple JS function (the original resizes both width and height, mine is just for the width):

     function changeFBPagePlugin() {
        var container_width = Number($('.fb-container').width()).toFixed(0);
        if (!isNaN(container_width)) {
            $(".fb-page").attr("data-width", container_width);
        }
        if (typeof FB !== 'undefined') {
            FB.XFBML.parse();
        }
    };
    

    It checks for the current width of the wrapping div and then puts the value inside fb-page div. The magic is done with FB.XFBML object, that is a part of Facebook SDK, which becomes available when you initialize the fb-page itself via window.fbAsyncInit

    I bind my function to html body's onLoad and onResize:

    <body onload="changeFBPagePlugin()" onresize="changeFBPagePlugin()">
    

    On the page I have my fb-page plugin wrapped in another div that is used as reference:

    <div class="fb-container"> 
        <div class="fb-page" ...stuff you need for FB page plugin... </div>
    </div>
    

    Finally the simple CSS for the wrapper to assure it stretches over the available space:

    .fb-container {
        width: 95%;
        margin: 0px auto;
    }
    

    Putting all this together the results seem quite satisfying. Hopefuly this will help someone, although the question was posted quite a long time ago.

    Javascript: getFullyear() is not a function

    One way to get this error is to forget to use the 'new' keyword when instantiating your Date in javascript like this:

    > d = Date();
    'Tue Mar 15 2016 20:05:53 GMT-0400 (EDT)'
    > typeof(d);
    'string'
    > d.getFullYear();
    TypeError: undefined is not a function
    

    Had you used the 'new' keyword, it would have looked like this:

    > el@defiant $ node
    > d = new Date();
    Tue Mar 15 2016 20:08:58 GMT-0400 (EDT)
    > typeof(d);
    'object'
    > d.getFullYear(0);
    2016
    

    Another way to get that error is to accidentally re-instantiate a variable in javascript between when you set it and when you use it, like this:

    el@defiant $ node
    > d = new Date();
    Tue Mar 15 2016 20:12:13 GMT-0400 (EDT)
    > d.getFullYear();
    2016
    > d = 57 + 23;
    80
    > d.getFullYear();
    TypeError: undefined is not a function
    

    Generate random numbers with a given (numerical) distribution

    An advantage to generating the list using CDF is that you can use binary search. While you need O(n) time and space for preprocessing, you can get k numbers in O(k log n). Since normal Python lists are inefficient, you can use array module.

    If you insist on constant space, you can do the following; O(n) time, O(1) space.

    def random_distr(l):
        r = random.uniform(0, 1)
        s = 0
        for item, prob in l:
            s += prob
            if s >= r:
                return item
        return item  # Might occur because of floating point inaccuracies
    

    java.util.NoSuchElementException - Scanner reading user input

    The problem is

    When a Scanner is closed, it will close its input source if the source implements the Closeable interface.

    http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

    Thus scan.close() closes System.in.

    To fix it you can make

    Scanner scan static and do not close it in PromptCustomerQty. Code below works.

    public static void main (String[] args) {   
    
    // Create a customer
    // Future proofing the possabiltiies of multiple customers
    Customer customer = new Customer("Will");
    
    // Create object for each Product
    // (Name,Code,Description,Price)
    // Initalize Qty at 0
    Product Computer = new Product("Computer","PC1003","Basic Computer",399.99); 
    Product Monitor = new Product("Monitor","MN1003","LCD Monitor",99.99);
    Product Printer = new Product("Printer","PR1003x","Inkjet Printer",54.23);
    
    // Define internal variables 
    // ## DONT CHANGE 
    ArrayList<Product> ProductList = new ArrayList<Product>(); // List to store Products
    String formatString = "%-15s %-10s %-20s %-10s %-10s %n"; // Default format for output
    
    // Add objects to list
    ProductList.add(Computer);
    ProductList.add(Monitor);
    ProductList.add(Printer);
    
    // Ask users for quantities 
    PromptCustomerQty(customer, ProductList);
    
    // Ask user for payment method
    PromptCustomerPayment(customer);
    
    // Create the header
    PrintHeader(customer, formatString);
    
    // Create Body
    PrintBody(ProductList, formatString);   
    }
    
    static Scanner scan;
    
    public static void PromptCustomerQty(Customer customer, ArrayList<Product> ProductList)               {
    // Initiate a Scanner
    scan = new Scanner(System.in);
    
    // **** VARIABLES ****
    int qty = 0;
    
    // Greet Customer
    System.out.println("Hello " + customer.getName());
    
    // Loop through each item and ask for qty desired
    for (Product p : ProductList) {
    
        do {
        // Ask user for qty
        System.out.println("How many would you like for product: " + p.name);
        System.out.print("> ");
    
        // Get input and set qty for the object
        qty = scan.nextInt();
    
        }
        while (qty < 0); // Validation
    
        p.setQty(qty); // Set qty for object
        qty = 0; // Reset count
    }
    
    // Cleanup
    
    }
    
    public static void PromptCustomerPayment (Customer customer) {
    // Variables
    String payment = "";
    
    // Prompt User
    do {
    System.out.println("Would you like to pay in full? [Yes/No]");
    System.out.print("> ");
    
    payment = scan.next();
    
    } while ((!payment.toLowerCase().equals("yes")) && (!payment.toLowerCase().equals("no")));
    
    // Check/set result
    if (payment.toLowerCase() == "yes") {
        customer.setPaidInFull(true);
    }
    else {
        customer.setPaidInFull(false);
    }
    }
    

    On a side note, you shouldn't use == for String comparision, use .equals instead.

    single line comment in HTML

    No, <!-- ... --> is the only comment syntax in HTML.

    Google Chrome form autofill and its yellow background

    Solution here:

    if (navigator.userAgent.toLowerCase().indexOf("chrome") >= 0) {
        $(window).load(function(){
            $('input:-webkit-autofill').each(function(){
                var text = $(this).val();
                var name = $(this).attr('name');
                $(this).after(this.outerHTML).remove();
                $('input[name=' + name + ']').val(text);
            });
        });
    }
    

    dplyr change many data types

    You can use the standard evaluation version of mutate_each (which is mutate_each_) to change the column classes:

    dat %>% mutate_each_(funs(factor), l1) %>% mutate_each_(funs(as.numeric), l2)
    

    Resize to fit image in div, and center horizontally and vertically

    SOLUTION

    <style>
    .container {
        margin: 10px;
        width: 115px;
        height: 115px;
        line-height: 115px;
        text-align: center;
        border: 1px solid red;
        background-image: url("http://i.imgur.com/H9lpVkZ.jpg");
        background-repeat: no-repeat;
        background-position: center;
        background-size: contain;
    
    }
    
    </style>
    
    <div class='container'>
    </div>
    
    <div class='container' style='width:50px;height:100px;line-height:100px'>
    </div>
    
    <div class='container' style='width:140px;height:70px;line-height:70px'>
    </div>
    

    git visual diff between branches

    If you use Eclipse you can visually compare your current branch on the workspace with another tag/branch:

    Eclipse workspace compare

    How to receive JSON as an MVC 5 action method parameter

    Unfortunately, Dictionary has problems with Model Binding in MVC. Read the full story here. Instead, create a custom model binder to get the Dictionary as a parameter for the controller action.

    To solve your requirement, here is the working solution -

    First create your ViewModels in following way. PersonModel can have list of RoleModels.

    public class PersonModel
    {
        public List<RoleModel> Roles { get; set; }
        public string Name { get; set; }
    }
    
    public class RoleModel
    {
        public string RoleName { get; set;}
        public string Description { get; set;}
    }
    

    Then have a index action which will be serving basic index view -

    public ActionResult Index()
    {
        return View();
    }
    

    Index view will be having following JQuery AJAX POST operation -

    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script>
        $(function () {
            $('#click1').click(function (e) {
    
                var jsonObject = {
                    "Name" : "Rami",
                    "Roles": [{ "RoleName": "Admin", "Description" : "Admin Role"}, { "RoleName": "User", "Description" : "User Role"}]
                };
    
                $.ajax({
                    url: "@Url.Action("AddUser")",
                    type: "POST",
                    data: JSON.stringify(jsonObject),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    error: function (response) {
                        alert(response.responseText);
                },
                    success: function (response) {
                        alert(response);
                    }
                });
    
            });
        });
    </script>
    
    <input type="button" value="click1" id="click1" />
    

    Index action posts to AddUser action -

    [HttpPost]
    public ActionResult AddUser(PersonModel model)
    {
        if (model != null)
        {
            return Json("Success");
        }
        else
        {
            return Json("An Error Has occoured");
        }
    }
    

    So now when the post happens you can get all the posted data in the model parameter of action.

    Update:

    For asp.net core, to get JSON data as your action parameter you should add the [FromBody] attribute before your param name in your controller action. Note: if you're using ASP.NET Core 2.1, you can also use the [ApiController] attribute to automatically infer the [FromBody] binding source for your complex action method parameters. (Doc)

    enter image description here

    Why does PEP-8 specify a maximum line length of 79 characters?

    I agree with Justin. To elaborate, overly long lines of code are harder to read by humans and some people might have console widths that only accommodate 80 characters per line.

    The style recommendation is there to ensure that the code you write can be read by as many people as possible on as many platforms as possible and as comfortably as possible.

    Converting a date string to a DateTime object using Joda Time library

    I know this is an old question, but I wanted to add that, as of JodaTime 2.0, you can do this with a one-liner:

    DateTime date = DateTime.parse("04/02/2011 20:27:05", 
                      DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss"));
    

    What is the equivalent of "!=" in Excel VBA?

    Because the inequality operator in VBA is <>

    If strTest <> "" Then
        .....
    

    the operator != is used in C#, C++.

    Using Mysql in the command line in osx - command not found?

    You have to create a symlink to your mysql installation if it is not the most recent version of mysql.

    $ brew link --force [email protected]
    

    see this post by Alex Todd

    Redirecting to a relative URL in JavaScript

    https://developer.mozilla.org/en-US/docs/Web/API/Location/assign

    • window.location.assign("../"); // one level up
    • window.location.assign("/path"); // relative to domain

    How to display Woocommerce Category image?

    You may also used foreach loop for display category image and etc from parent category given by parent id.

    for example, i am giving 74 id of parent category, then i will display the image from child category and its slug also.

    **<?php
    $catTerms = get_terms('product_cat', array('hide_empty' => 0, 'orderby' => 'ASC', 'child_of'=>'74'));
    foreach($catTerms as $catTerm) : ?>
    <?php $thumbnail_id = get_woocommerce_term_meta( $catTerm->term_id, 'thumbnail_id', true ); 
    
    // get the image URL
    $image = wp_get_attachment_url( $thumbnail_id );  ?>
    <li><img src="<?php echo $image; ?>" width="152" height="245"/><span><?php echo $catTerm->name; ?></span></li>
    <?php endforeach; ?>** 
    

    How do I find Waldo with Mathematica?

    I agree with @GregoryKlopper that the right way to solve the general problem of finding Waldo (or any object of interest) in an arbitrary image would be to train a supervised machine learning classifier. Using many positive and negative labeled examples, an algorithm such as Support Vector Machine, Boosted Decision Stump or Boltzmann Machine could likely be trained to achieve high accuracy on this problem. Mathematica even includes these algorithms in its Machine Learning Framework.

    The two challenges with training a Waldo classifier would be:

    1. Determining the right image feature transform. This is where @Heike's answer would be useful: a red filter and a stripped pattern detector (e.g., wavelet or DCT decomposition) would be a good way to turn raw pixels into a format that the classification algorithm could learn from. A block-based decomposition that assesses all subsections of the image would also be required ... but this is made easier by the fact that Waldo is a) always roughly the same size and b) always present exactly once in each image.
    2. Obtaining enough training examples. SVMs work best with at least 100 examples of each class. Commercial applications of boosting (e.g., the face-focusing in digital cameras) are trained on millions of positive and negative examples.

    A quick Google image search turns up some good data -- I'm going to have a go at collecting some training examples and coding this up right now!

    However, even a machine learning approach (or the rule-based approach suggested by @iND) will struggle for an image like the Land of Waldos!

    How to install a private NPM module without my own registry?

    Can I just install an NPM package that sits on the local filesystem, or perhaps even from git?

    Yes you can! From the docs https://docs.npmjs.com/cli/install

    A package is:

    • a) a folder containing a program described by a package.json file
    • b) a gzipped tarball containing (a)
    • c) a url that resolves to (b)
    • d) a <name>@<version> that is published on the registry with (c)
    • e) a <name>@<tag> that points to (d)
    • f) a <name> that has a "latest" tag satisfying (e)
    • g) a <git remote url> that resolves to (b)

    Isn't npm brilliant?

    UTF-8 all the way through

    I have just went through the same issue and found a good solution at PHP manuals.

    I changed all my file encoding to UTF8 then the default encoding on my connection. This solved all the problems.

    if (!$mysqli->set_charset("utf8")) {
        printf("Error loading character set utf8: %s\n", $mysqli->error);
    } else {
       printf("Current character set: %s\n", $mysqli->character_set_name());
    }
    

    View Source

    How do you test a public/private DSA keypair?

    Encrypt something with the public key, and see which private key decrypts it.

    This Code Project article by none other than Jeff Atwood implements a simplified wrapper around the .NET cryptography classes. Assuming these keys were created for use with RSA, use the asymmetric class with your public key to encrypt, and the same with your private key to decrypt.

    Eclipse "Invalid Project Description" when creating new project from existing source

    I've been having this problem in Linux, with a project that I renamed, removed, and reimported. Somewhere in the .metadata, it's still there evidently.

    I finally solved it by the following steps:

    close Eclipse
    mv .metadata .metadata_orig
    start Eclipse
    reset default workspace
    reimport projects
    

    This may not work for everyone, especially if you already have lots of projects in multiple workspaces. But if you're used to reconfiguring Eclipse (which I do every time I upgrade to the next Eclipse release) it's not too bad.

    How to delete rows from a pandas DataFrame based on a conditional expression

    You can assign the DataFrame to a filtered version of itself:

    df = df[df.score > 50]
    

    This is faster than drop:

    %%timeit
    test = pd.DataFrame({'x': np.random.randn(int(1e6))})
    test = test[test.x < 0]
    # 54.5 ms ± 2.02 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
    
    %%timeit
    test = pd.DataFrame({'x': np.random.randn(int(1e6))})
    test.drop(test[test.x > 0].index, inplace=True)
    # 201 ms ± 17.9 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
    
    %%timeit
    test = pd.DataFrame({'x': np.random.randn(int(1e6))})
    test = test.drop(test[test.x > 0].index)
    # 194 ms ± 7.03 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
    

    css transform, jagged edges in chrome

    Just thought that we'd throw in our solution too as we had the exact same problem on Chrome/Windows.

    We tried the solution by @stevenWatkins above, but still had the "stepping".

    Instead of

    -webkit-backface-visibility: hidden;
    

    We used:

    -webkit-backface-visibility: initial;
    

    For us this did the trick

    HTML5 Audio stop function

    As a side note and because I was recently using the stop method provided in the accepted answer, according to this link:

    https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Media_events

    by setting currentTime manually one may fire the 'canplaythrough' event on the audio element. In the link it mentions Firefox, but I encountered this event firing after setting currentTime manually on Chrome. So if you have behavior attached to this event you might end up in an audio loop.

    Convert a String of Hex into ASCII in Java

    Just use a for loop to go through each couple of characters in the string, convert them to a character and then whack the character on the end of a string builder:

    String hex = "75546f7272656e745c436f6d706c657465645c6e667375635f6f73745f62795f6d757374616e675c50656e64756c756d2d392c303030204d696c65732e6d7033006d7033006d7033004472756d202620426173730050656e64756c756d00496e2053696c69636f00496e2053696c69636f2a3b2a0050656e64756c756d0050656e64756c756d496e2053696c69636f303038004472756d2026204261737350656e64756c756d496e2053696c69636f30303800392c303030204d696c6573203c4d757374616e673e50656e64756c756d496e2053696c69636f3030380050656e64756c756d50656e64756c756d496e2053696c69636f303038004d50330000";
    StringBuilder output = new StringBuilder();
    for (int i = 0; i < hex.length(); i+=2) {
        String str = hex.substring(i, i+2);
        output.append((char)Integer.parseInt(str, 16));
    }
    System.out.println(output);
    

    Or (Java 8+) if you're feeling particularly uncouth, use the infamous "fixed width string split" hack to enable you to do a one-liner with streams instead:

    System.out.println(Arrays
            .stream(hex.split("(?<=\\G..)")) //https://stackoverflow.com/questions/2297347/splitting-a-string-at-every-n-th-character
            .map(s -> Character.toString((char)Integer.parseInt(s, 16)))
            .collect(Collectors.joining()));
    

    Either way, this gives a few lines starting with the following:

    uTorrent\Completed\nfsuc_ost_by_mustang\Pendulum-9,000 Miles.mp3

    Hmmm... :-)