Programs & Examples On #Android alarms

Android alarms is the facility provided by Android through AlarmManager to start an intent at a given time (by passing a pending intent).

How to get a JavaScript object's class?

Agree with dfa, that's why i consider the prototye as the class when no named class found

Here is an upgraded function of the one posted by Eli Grey, to match my way of mind

function what(obj){
    if(typeof(obj)==="undefined")return "undefined";
    if(obj===null)return "Null";
    var res = Object.prototype.toString.call(obj).match(/^\[object\s(.*)\]$/)[1];
    if(res==="Object"){
        res = obj.constructor.name;
        if(typeof(res)!='string' || res.length==0){
            if(obj instanceof jQuery)return "jQuery";// jQuery build stranges Objects
            if(obj instanceof Array)return "Array";// Array prototype is very sneaky
            return "Object";
        }
    }
    return res;
}

How to read line by line of a text area HTML tag

Two options: no JQuery required, or JQuery version

No JQuery (or anything else required)

var textArea = document.getElementById('myTextAreaId');
var lines = textArea.value.split('\n');    // lines is an array of strings

// Loop through all lines
for (var j = 0; j < lines.length; j++) {
  console.log('Line ' + j + ' is ' + lines[j])
}

JQuery version

var lines = $('#myTextAreaId').val().split('\n');   // lines is an array of strings

// Loop through all lines
for (var j = 0; j < lines.length; j++) {
  console.log('Line ' + j + ' is ' + lines[j])
}

Side note, if you prefer forEach a sample loop is

lines.forEach(function(line) {
  console.log('Line is ' + line)
})

How to get start and end of previous month in VB

This works reliably for me in my main sub.

Dim defDate1 As Date, defDate2 As Date

'** Set default date range to previous month
defDate1 = CDate(Month(Now) & "/1/" & Year(Now))
defDate1 = DateAdd("m", -1, defDate1)
defDate2 = DateAdd("d", -1, DateAdd("m", 1, defDate1))

LaTeX table positioning

You may want to add this to your preamble, and adjust the values as necessary:

 %------------begin Float Adjustment
%two column float page must be 90% full
\renewcommand\dblfloatpagefraction{.90}
%two column top float can cover up to 80% of page
\renewcommand\dbltopfraction{.80}
%float page must be 90% full
\renewcommand\floatpagefraction{.90}
%top float can cover up to 80% of page
\renewcommand\topfraction{.80}
%bottom float can cover up to 80% of page
\renewcommand\bottomfraction{.80}
%at least 10% of a normal page must contain text
\renewcommand\textfraction{.1}
%separation between floats and text
\setlength\dbltextfloatsep{9pt plus 5pt minus 3pt }
%separation between two column floats and text
\setlength\textfloatsep{4pt plus 2pt minus 1.5pt}

Particularly, the \floatpagefraction may be of interest.

-XX:MaxPermSize with or without -XX:PermSize

-XX:PermSize specifies the initial size that will be allocated during startup of the JVM. If necessary, the JVM will allocate up to -XX:MaxPermSize.

Get specific objects from ArrayList when objects were added anonymously?

List.indexOf() will give you what you want, provided you know precisely what you're after, and provided that the equals() method for Party is well-defined.

Party searchCandidate = new Party("FirstParty");
int index = cave.parties.indexOf(searchCandidate);

This is where it gets interesting - subclasses shouldn't be examining the private properties of their parents, so we'll define equals() in the superclass.

@Override
public boolean equals(Object o) {
    if (this == o) {
        return true;
    }
    if (!(o instanceof CaveElement)) {
        return false;
    }

    CaveElement that = (CaveElement) o;

    if (index != that.index) {
        return false;
    }
    if (name != null ? !name.equals(that.name) : that.name != null) {
        return false;
    }

    return true;
}

It's also wise to override hashCode if you override equals - the general contract for hashCode mandates that, if x.equals(y), then x.hashCode() == y.hashCode().

@Override
public int hashCode() {
    int result = name != null ? name.hashCode() : 0;
    result = 31 * result + index;
    return result;
}

Convert List into Comma-Separated String

You can refer below example for getting a comma separated string array from list.

Example:

List<string> testList= new List<string>();
testList.Add("Apple"); // Add string 1
testList.Add("Banana"); // 2
testList.Add("Mango"); // 3
testList.Add("Blue Berry"); // 4
testList.Add("Water Melon"); // 5

string JoinDataString = string.Join(",", testList.ToArray());

How to list all properties of a PowerShell object

I like

 Get-WmiObject Win32_computersystem | format-custom *

That seems to expand everything.

There's also a show-object command in the PowerShellCookbook module that does it in a GUI. Jeffrey Snover, the PowerShell creator, uses it in his unplugged videos (recommended).

Although most often I use

Get-WmiObject Win32_computersystem | fl *

It avoids the .format.ps1xml file that defines a table or list view for the object type, if there are any. The format file may even define column headers that don't match any property names.

Compare integer in bash, unary operator expected

Judging from the error message the value of i was the empty string when you executed it, not 0.

JavaScript get clipboard data on paste event (Cross browser)

This should work on all browsers that support the onpaste event and the mutation observer.

This solution goes a step beyond getting the text only, it actually allows you to edit the pasted content before it get pasted into an element.

It works by using contenteditable, onpaste event (supported by all major browsers) en mutation observers (supported by Chrome, Firefox and IE11+)

step 1

Create a HTML-element with contenteditable

<div contenteditable="true" id="target_paste_element"></div>

step 2

In your Javascript code add the following event

document.getElementById("target_paste_element").addEventListener("paste", pasteEventVerifierEditor.bind(window, pasteCallBack), false);

We need to bind pasteCallBack, since the mutation observer will be called asynchronously.

step 3

Add the following function to your code

function pasteEventVerifierEditor(callback, e)
{
   //is fired on a paste event. 
    //pastes content into another contenteditable div, mutation observer observes this, content get pasted, dom tree is copied and can be referenced through call back.
    //create temp div
    //save the caret position.
    savedCaret = saveSelection(document.getElementById("target_paste_element"));

    var tempDiv = document.createElement("div");
    tempDiv.id = "id_tempDiv_paste_editor";
    //tempDiv.style.display = "none";
    document.body.appendChild(tempDiv);
    tempDiv.contentEditable = "true";

    tempDiv.focus();

    //we have to wait for the change to occur.
    //attach a mutation observer
    if (window['MutationObserver'])
    {
        //this is new functionality
        //observer is present in firefox/chrome and IE11
        // select the target node
        // create an observer instance
        tempDiv.observer = new MutationObserver(pasteMutationObserver.bind(window, callback));
        // configuration of the observer:
        var config = { attributes: false, childList: true, characterData: true, subtree: true };

        // pass in the target node, as well as the observer options
        tempDiv.observer.observe(tempDiv, config);

    }   

}



function pasteMutationObserver(callback)
{

    document.getElementById("id_tempDiv_paste_editor").observer.disconnect();
    delete document.getElementById("id_tempDiv_paste_editor").observer;

    if (callback)
    {
        //return the copied dom tree to the supplied callback.
        //copy to avoid closures.
        callback.apply(document.getElementById("id_tempDiv_paste_editor").cloneNode(true));
    }
    document.body.removeChild(document.getElementById("id_tempDiv_paste_editor"));

}

function pasteCallBack()
{
    //paste the content into the element.
    restoreSelection(document.getElementById("target_paste_element"), savedCaret);
    delete savedCaret;

    pasteHtmlAtCaret(this.innerHTML, false, true);
}   


saveSelection = function(containerEl) {
if (containerEl == document.activeElement)
{
    var range = window.getSelection().getRangeAt(0);
    var preSelectionRange = range.cloneRange();
    preSelectionRange.selectNodeContents(containerEl);
    preSelectionRange.setEnd(range.startContainer, range.startOffset);
    var start = preSelectionRange.toString().length;

    return {
        start: start,
        end: start + range.toString().length
    };
}
};

restoreSelection = function(containerEl, savedSel) {
    containerEl.focus();
    var charIndex = 0, range = document.createRange();
    range.setStart(containerEl, 0);
    range.collapse(true);
    var nodeStack = [containerEl], node, foundStart = false, stop = false;

    while (!stop && (node = nodeStack.pop())) {
        if (node.nodeType == 3) {
            var nextCharIndex = charIndex + node.length;
            if (!foundStart && savedSel.start >= charIndex && savedSel.start <= nextCharIndex) {
                range.setStart(node, savedSel.start - charIndex);
                foundStart = true;
            }
            if (foundStart && savedSel.end >= charIndex && savedSel.end <= nextCharIndex) {
                range.setEnd(node, savedSel.end - charIndex);
                stop = true;
            }
            charIndex = nextCharIndex;
        } else {
            var i = node.childNodes.length;
            while (i--) {
                nodeStack.push(node.childNodes[i]);
            }
        }
    }

    var sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);
}

function pasteHtmlAtCaret(html, returnInNode, selectPastedContent) {
//function written by Tim Down

var sel, range;
if (window.getSelection) {
    // IE9 and non-IE
    sel = window.getSelection();
    if (sel.getRangeAt && sel.rangeCount) {
        range = sel.getRangeAt(0);
        range.deleteContents();

        // Range.createContextualFragment() would be useful here but is
        // only relatively recently standardized and is not supported in
        // some browsers (IE9, for one)
        var el = document.createElement("div");
        el.innerHTML = html;
        var frag = document.createDocumentFragment(), node, lastNode;
        while ( (node = el.firstChild) ) {
            lastNode = frag.appendChild(node);
        }
        var firstNode = frag.firstChild;
        range.insertNode(frag);

        // Preserve the selection
        if (lastNode) {
            range = range.cloneRange();
            if (returnInNode)
            {
                range.setStart(lastNode, 0); //this part is edited, set caret inside pasted node.
            }
            else
            {
                range.setStartAfter(lastNode); 
            }
            if (selectPastedContent) {
                range.setStartBefore(firstNode);
            } else {
                range.collapse(true);
            }
            sel.removeAllRanges();
            sel.addRange(range);
        }
    }
} else if ( (sel = document.selection) && sel.type != "Control") {
    // IE < 9
    var originalRange = sel.createRange();
    originalRange.collapse(true);
    sel.createRange().pasteHTML(html);
    if (selectPastedContent) {
        range = sel.createRange();
        range.setEndPoint("StartToStart", originalRange);
        range.select();
    }
}
}

What the code does:

  1. Somebody fires the paste event by using ctrl-v, contextmenu or other means
  2. In the paste event a new element with contenteditable is created (an element with contenteditable has elevated privileges)
  3. The caret position of the target element is saved.
  4. The focus is set to the new element
  5. The content gets pasted into the new element and is rendered in the DOM.
  6. The mutation observer catches this (it registers all changes to the dom tree and content). Then fires the mutation event.
  7. The dom of the pasted content gets cloned into a variable and returned to the callback. The temporary element is destroyed.
  8. The callback receives the cloned DOM. The caret is restored. You can edit this before you append it to your target. element. In this example I'm using Tim Downs functions for saving/restoring the caret and pasting HTML into the element.

Example

_x000D_
_x000D_
document.getElementById("target_paste_element").addEventListener("paste", pasteEventVerifierEditor.bind(window, pasteCallBack), false);_x000D_
_x000D_
_x000D_
function pasteEventVerifierEditor(callback, e) {_x000D_
  //is fired on a paste event. _x000D_
  //pastes content into another contenteditable div, mutation observer observes this, content get pasted, dom tree is copied and can be referenced through call back._x000D_
  //create temp div_x000D_
  //save the caret position._x000D_
  savedCaret = saveSelection(document.getElementById("target_paste_element"));_x000D_
_x000D_
  var tempDiv = document.createElement("div");_x000D_
  tempDiv.id = "id_tempDiv_paste_editor";_x000D_
  //tempDiv.style.display = "none";_x000D_
  document.body.appendChild(tempDiv);_x000D_
  tempDiv.contentEditable = "true";_x000D_
_x000D_
  tempDiv.focus();_x000D_
_x000D_
  //we have to wait for the change to occur._x000D_
  //attach a mutation observer_x000D_
  if (window['MutationObserver']) {_x000D_
    //this is new functionality_x000D_
    //observer is present in firefox/chrome and IE11_x000D_
    // select the target node_x000D_
    // create an observer instance_x000D_
    tempDiv.observer = new MutationObserver(pasteMutationObserver.bind(window, callback));_x000D_
    // configuration of the observer:_x000D_
    var config = {_x000D_
      attributes: false,_x000D_
      childList: true,_x000D_
      characterData: true,_x000D_
      subtree: true_x000D_
    };_x000D_
_x000D_
    // pass in the target node, as well as the observer options_x000D_
    tempDiv.observer.observe(tempDiv, config);_x000D_
_x000D_
  }_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
function pasteMutationObserver(callback) {_x000D_
_x000D_
  document.getElementById("id_tempDiv_paste_editor").observer.disconnect();_x000D_
  delete document.getElementById("id_tempDiv_paste_editor").observer;_x000D_
_x000D_
  if (callback) {_x000D_
    //return the copied dom tree to the supplied callback._x000D_
    //copy to avoid closures._x000D_
    callback.apply(document.getElementById("id_tempDiv_paste_editor").cloneNode(true));_x000D_
  }_x000D_
  document.body.removeChild(document.getElementById("id_tempDiv_paste_editor"));_x000D_
_x000D_
}_x000D_
_x000D_
function pasteCallBack() {_x000D_
  //paste the content into the element._x000D_
  restoreSelection(document.getElementById("target_paste_element"), savedCaret);_x000D_
  delete savedCaret;_x000D_
_x000D_
  //edit the copied content by slicing_x000D_
  pasteHtmlAtCaret(this.innerHTML.slice(3), false, true);_x000D_
}_x000D_
_x000D_
_x000D_
saveSelection = function(containerEl) {_x000D_
  if (containerEl == document.activeElement) {_x000D_
    var range = window.getSelection().getRangeAt(0);_x000D_
    var preSelectionRange = range.cloneRange();_x000D_
    preSelectionRange.selectNodeContents(containerEl);_x000D_
    preSelectionRange.setEnd(range.startContainer, range.startOffset);_x000D_
    var start = preSelectionRange.toString().length;_x000D_
_x000D_
    return {_x000D_
      start: start,_x000D_
      end: start + range.toString().length_x000D_
    };_x000D_
  }_x000D_
};_x000D_
_x000D_
restoreSelection = function(containerEl, savedSel) {_x000D_
  containerEl.focus();_x000D_
  var charIndex = 0,_x000D_
    range = document.createRange();_x000D_
  range.setStart(containerEl, 0);_x000D_
  range.collapse(true);_x000D_
  var nodeStack = [containerEl],_x000D_
    node, foundStart = false,_x000D_
    stop = false;_x000D_
_x000D_
  while (!stop && (node = nodeStack.pop())) {_x000D_
    if (node.nodeType == 3) {_x000D_
      var nextCharIndex = charIndex + node.length;_x000D_
      if (!foundStart && savedSel.start >= charIndex && savedSel.start <= nextCharIndex) {_x000D_
        range.setStart(node, savedSel.start - charIndex);_x000D_
        foundStart = true;_x000D_
      }_x000D_
      if (foundStart && savedSel.end >= charIndex && savedSel.end <= nextCharIndex) {_x000D_
        range.setEnd(node, savedSel.end - charIndex);_x000D_
        stop = true;_x000D_
      }_x000D_
      charIndex = nextCharIndex;_x000D_
    } else {_x000D_
      var i = node.childNodes.length;_x000D_
      while (i--) {_x000D_
        nodeStack.push(node.childNodes[i]);_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
_x000D_
  var sel = window.getSelection();_x000D_
  sel.removeAllRanges();_x000D_
  sel.addRange(range);_x000D_
}_x000D_
_x000D_
function pasteHtmlAtCaret(html, returnInNode, selectPastedContent) {_x000D_
  //function written by Tim Down_x000D_
_x000D_
  var sel, range;_x000D_
  if (window.getSelection) {_x000D_
    // IE9 and non-IE_x000D_
    sel = window.getSelection();_x000D_
    if (sel.getRangeAt && sel.rangeCount) {_x000D_
      range = sel.getRangeAt(0);_x000D_
      range.deleteContents();_x000D_
_x000D_
      // Range.createContextualFragment() would be useful here but is_x000D_
      // only relatively recently standardized and is not supported in_x000D_
      // some browsers (IE9, for one)_x000D_
      var el = document.createElement("div");_x000D_
      el.innerHTML = html;_x000D_
      var frag = document.createDocumentFragment(),_x000D_
        node, lastNode;_x000D_
      while ((node = el.firstChild)) {_x000D_
        lastNode = frag.appendChild(node);_x000D_
      }_x000D_
      var firstNode = frag.firstChild;_x000D_
      range.insertNode(frag);_x000D_
_x000D_
      // Preserve the selection_x000D_
      if (lastNode) {_x000D_
        range = range.cloneRange();_x000D_
        if (returnInNode) {_x000D_
          range.setStart(lastNode, 0); //this part is edited, set caret inside pasted node._x000D_
        } else {_x000D_
          range.setStartAfter(lastNode);_x000D_
        }_x000D_
        if (selectPastedContent) {_x000D_
          range.setStartBefore(firstNode);_x000D_
        } else {_x000D_
          range.collapse(true);_x000D_
        }_x000D_
        sel.removeAllRanges();_x000D_
        sel.addRange(range);_x000D_
      }_x000D_
    }_x000D_
  } else if ((sel = document.selection) && sel.type != "Control") {_x000D_
    // IE < 9_x000D_
    var originalRange = sel.createRange();_x000D_
    originalRange.collapse(true);_x000D_
    sel.createRange().pasteHTML(html);_x000D_
    if (selectPastedContent) {_x000D_
      range = sel.createRange();_x000D_
      range.setEndPoint("StartToStart", originalRange);_x000D_
      range.select();_x000D_
    }_x000D_
  }_x000D_
}
_x000D_
div {_x000D_
  border: 1px solid black;_x000D_
  height: 50px;_x000D_
  padding: 5px;_x000D_
}
_x000D_
<div contenteditable="true" id="target_paste_element"></div>
_x000D_
_x000D_
_x000D_


Many thanks to Tim Down See this post for the answer:

Get the pasted content on document on paste event

Get Hard disk serial Number

There is a simple way for @Sprunth's answer.

private void GetAllDiskDrives()
    {
        var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");

        foreach (ManagementObject wmi_HD in searcher.Get())
        {
            HardDrive hd = new HardDrive();
            hd.Model = wmi_HD["Model"].ToString();
            hd.InterfaceType = wmi_HD["InterfaceType"].ToString();
            hd.Caption = wmi_HD["Caption"].ToString();

            hd.SerialNo =wmi_HD.GetPropertyValue("SerialNumber").ToString();//get the serailNumber of diskdrive

            hdCollection.Add(hd);
        }

 }


public class HardDrive
{
    public string Model { get; set; }
    public string InterfaceType { get; set; }
    public string Caption { get; set; }
    public string SerialNo { get; set; }
}

Ignore .pyc files in git repository

You have probably added them to the repository before putting *.pyc in .gitignore.
First remove them from the repository.

Python: Get relative path from comparing two absolute paths

os.path.relpath:

Return a relative filepath to path either from the current directory or from an optional start point.

>>> from os.path import relpath
>>> relpath('/usr/var/log/', '/usr/var')
'log'
>>> relpath('/usr/var/log/', '/usr/var/sad/')
'../log'

So, if relative path starts with '..' - it means that the second path is not descendant of the first path.

In Python3 you can use PurePath.relative_to:

Python 3.5.1 (default, Jan 22 2016, 08:54:32)
>>> from pathlib import Path

>>> Path('/usr/var/log').relative_to('/usr/var/log/')
PosixPath('.')

>>> Path('/usr/var/log').relative_to('/usr/var/')
PosixPath('log')

>>> Path('/usr/var/log').relative_to('/etc/')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/pathlib.py", line 851, in relative_to
    .format(str(self), str(formatted)))
ValueError: '/usr/var/log' does not start with '/etc'

jquery - Click event not working for dynamically created button

the simple and easy way to do that is use on event:

$('body').on('click','#element',function(){
    //somthing
});

but we can say this is not the best way to do this. I suggest a another way to do this is use clone() method instead of using dynamic html. Write some html in you file for example:

<div id='div1'></div>

Now in the script tag make a clone of this div then all the properties of this div would follow with new element too. For Example:

var dynamicDiv = jQuery('#div1').clone(true);

Now use the element dynamicDiv wherever you want to add it or change its properties as you like. Now all jQuery functions will work with this element

User GETDATE() to put current date into SQL variable

Just use GetDate() not Select GetDate()

DECLARE @LastChangeDate as date 
SET @LastChangeDate = GETDATE() 

but if it's SQL Server, you can also initialize in same step as declaration...

DECLARE @LastChangeDate date = getDate()

Password encryption at client side

This won't be secure, and it's simple to explain why:

If you hash the password on the client side and use that token instead of the password, then an attacker will be unlikely to find out what the password is.

But, the attacker doesn't need to find out what the password is, because your server isn't expecting the password any more - it's expecting the token. And the attacker does know the token because it's being sent over unencrypted HTTP!

Now, it might be possible to hack together some kind of challenge/response form of encryption which means that the same password will produce a different token each request. However, this will require that the password is stored in a decryptable format on the server, something which isn't ideal, but might be a suitable compromise.

And finally, do you really want to require users to have javascript turned on before they can log into your website?

In any case, SSL is neither an expensive or especially difficult to set up solution any more

Error HRESULT E_FAIL has been returned from a call to a COM component VS2012 when debugging

I got this error when trying to install a nuget package that I had previously downloaded and installed in another project.

Clicking Clear all NuGet Cache(s) under Tools > Options > NuGet Package Manager solved this for me

How to fit Windows Form to any screen resolution?

You can simply set the window state

this.WindowState = System.Windows.Forms.FormWindowState.Maximized;

Undefined variable: $_SESSION

Turned out there was some extra code in the AppModel that was messing things up:

in beforeFind and afterFind:

App::Import("Session");
$session = new CakeSession();
$sim_id = $session->read("Simulation.id");

I don't know why, but that was what the problem was. Removing those lines fixed the issue I was having.

Remove characters from a String in Java

Strings in java are immutable. That means you need to create a new string or overwrite your old string to achieve the desired affect:

id = id.replace(".xml", "");

javascript jquery radio button click

You can use .change for what you want

$("input[@name='lom']").change(function(){
    // Do something interesting here
});

as of jQuery 1.3

you no longer need the '@'. Correct way to select is:

$("input[name='lom']")

Best way to style a TextBox in CSS

You could target all text boxes with input[type=text] and then explicitly define the class for the textboxes who need it.

You can code like below :

_x000D_
_x000D_
input[type=text] {_x000D_
  padding: 0;_x000D_
  height: 30px;_x000D_
  position: relative;_x000D_
  left: 0;_x000D_
  outline: none;_x000D_
  border: 1px solid #cdcdcd;_x000D_
  border-color: rgba(0, 0, 0, .15);_x000D_
  background-color: white;_x000D_
  font-size: 16px;_x000D_
}_x000D_
_x000D_
.advancedSearchTextbox {_x000D_
  width: 526px;_x000D_
  margin-right: -4px;_x000D_
}
_x000D_
<input type="text" class="advancedSearchTextBox" />
_x000D_
_x000D_
_x000D_

How do I select text nodes with jQuery?

Can also be done like this:

var textContents = $(document.getElementById("ElementId").childNodes).filter(function(){
        return this.nodeType == 3;
});

The above code filters the textNodes from direct children child nodes of a given element.

Is it possible to select the last n items with nth-child?

If you are using jQuery in your project, or are willing to include it you can call nth-last-child through its selector API (this is this simulated it will cross browser). Here is a link to an nth-last-child plugin. If you took this method of targeting the elements you were interested in:

$('ul li:nth-last-child(1)').addClass('last');

And then style again the last class instead of the nth-child or nth-last-child pseudo selectors, you will have a much more consistent cross browser experience.

What is the convention for word separator in Java package names?

All three are not the conventions.

Use com.stackoverflow.mypackage.

The package names do not follow camel casing or underscores or hyphens package naming convention.

Also, Google Java Style Guide specifies exactly the same (i.e. com.stackoverflow.mypackage) convention:

5.2.1 Package names

Package names are all lowercase, with consecutive words simply concatenated together (no underscores). For example, com.example.deepspace, not com.example.deepSpace or com.example.deep_space.

Google Java Style Guide: 5.2 Rules by identifier type: 5.2.1 Package names.

SQLSTATE[HY000] [1045] Access denied for user 'username'@'localhost' using CakePHP

Check Following Things

  • Make Sure You Have MySQL Server Running
  • Check connection with default credentials i.e. username : 'root' & password : '' [Blank Password]
  • Try login phpmyadmin with same credentials
  • Try to put 127.0.0.1 instead localhost or your lan IP would do too.
  • Make sure you are running MySql on 3306 and if you have configured make sure to state it while making a connection

Replace all occurrences of a string in a data frame

To remove all spaces in every column, you can use

data[] <- lapply(data, gsub, pattern = " ", replacement = "", fixed = TRUE)

or to constrict this to just the second and third columns (i.e. every column except the first),

data[-1] <- lapply(data[-1], gsub, pattern = " ", replacement = "", fixed = TRUE)

Cannot bulk load because the file could not be opened. Operating System Error Code 3

It's probably a permissions issue but you need to make sure to try these steps to troubleshoot:

  • Put the file on a local drive and see if the job works (you don't necessarily need RDP access if you can map a drive letter on your local workstation to a directory on the database server)
  • Put the file on a remote directory that doesn't require username and password (allows Everyone to read) and use the UNC path (\server\directory\file.csv)
  • Configure the SQL job to run as your own username
  • Configure the SQL job to run as sa and add the net use and net use /delete commands before and after

Remember to undo any changes (especially running as sa). If nothing else works, you can try to change the bulk load into a scheduled task, running on the database server or another server that has bcp installed.

Passing additional variables from command line to make

You have several options to set up variables from outside your makefile:

  • From environment - each environment variable is transformed into a makefile variable with the same name and value.

    You may also want to set -e option (aka --environments-override) on, and your environment variables will override assignments made into makefile (unless these assignments themselves use the override directive . However, it's not recommended, and it's much better and flexible to use ?= assignment (the conditional variable assignment operator, it only has an effect if the variable is not yet defined):

    FOO?=default_value_if_not_set_in_environment
    

    Note that certain variables are not inherited from environment:

    • MAKE is gotten from name of the script
    • SHELL is either set within a makefile, or defaults to /bin/sh (rationale: commands are specified within the makefile, and they're shell-specific).
  • From command line - make can take variable assignments as part of his command line, mingled with targets:

    make target FOO=bar
    

    But then all assignments to FOO variable within the makefile will be ignored unless you use the override directive in assignment. (The effect is the same as with -e option for environment variables).

  • Exporting from the parent Make - if you call Make from a Makefile, you usually shouldn't explicitly write variable assignments like this:

    # Don't do this!
    target:
            $(MAKE) -C target CC=$(CC) CFLAGS=$(CFLAGS)
    

    Instead, better solution might be to export these variables. Exporting a variable makes it into the environment of every shell invocation, and Make calls from these commands pick these environment variable as specified above.

    # Do like this
    CFLAGS=-g
    export CFLAGS
    target:
            $(MAKE) -C target
    

    You can also export all variables by using export without arguments.

Postgresql : syntax error at or near "-"

i was trying trying to GRANT read-only privileges to a particular table to a user called walters-ro. So when i ran the sql command # GRANT SELECT ON table_name TO walters-ro; --- i got the following error..`syntax error at or near “-”

The solution to this was basically putting the user_name into double quotes since there is a dash(-) between the name.

# GRANT SELECT ON table_name TO "walters-ro";

That solved the problem.

Why doesn't calling a Python string method do anything unless you assign its output?

All string functions as lower, upper, strip are returning a string without modifying the original. If you try to modify a string, as you might think well it is an iterable, it will fail.

x = 'hello'
x[0] = 'i' #'str' object does not support item assignment

There is a good reading about the importance of strings being immutable: Why are Python strings immutable? Best practices for using them

Display an image with Python

import IPython.display as display
from PIL import Image
image_path = 'my_image.jpg'
display.display(Image.open(image_path))

Align two inline-blocks left and right on same line

give it float: right and the h1 float:left and put an element with clear:both after them.

Why can't I reference System.ComponentModel.DataAnnotations?

This error occurs when the reference to the "System.dll" got removed.Solution to the problem is very simple add the reference to "System.dll".The dll is normally available in the following location
"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727" .Add the reference your problem will get solved .

"application blocked by security settings" prevent applets running using oracle SE 7 update 51 on firefox on Linux mint

I had this issue. The security settings in the ControlPanel seem to be user specific. Try running it as the user you are actually running your browser as (you are not browsing as root!??) and setting the security level to Medium there. - For me, that did it.

Fast and Lean PDF Viewer for iPhone / iPad / iOS - tips and hints?

For a simple and effective PDF viewer, when you require only limited functionality, you can now (iOS 4.0+) use the QuickLook framework:

First, you need to link against QuickLook.framework and #import <QuickLook/QuickLook.h>;

Afterwards, in either viewDidLoad or any of the lazy initialization methods:

QLPreviewController *previewController = [[QLPreviewController alloc] init];
previewController.dataSource = self;
previewController.delegate = self;
previewController.currentPreviewItemIndex = indexPath.row;
[self presentModalViewController:previewController animated:YES];
[previewController release];

How can I URL encode a string in Excel VBA?

Although, this one is very old. I have come up with a solution based in this answer:

Dim ScriptEngine As ScriptControl
Set ScriptEngine = New ScriptControl
ScriptEngine.Language = "JScript"

ScriptEngine.AddCode "function encode(str) {return encodeURIComponent(str);}"
Dim encoded As String
encoded = ScriptEngine.Run("encode", "€ömE.sdfds")

Add Microsoft Script Control as reference and you are done.

Just a side note, because of the JS part, this is fully UTF-8-compatible. VB will convert correctly from UTF-16 to UTF-8.

How to get the squared symbol (²) to display in a string

No need to get too complicated. If all you need is ² then use the unicode representation.

http://en.wikipedia.org/wiki/Unicode_subscripts_and_superscripts

(which is how I assume you got the ² to appear in your question. )

Inserting multiple rows in a single SQL query?

If you are inserting into a single table, you can write your query like this (maybe only in MySQL):

INSERT INTO table1 (First, Last)
VALUES
    ('Fred', 'Smith'),
    ('John', 'Smith'),
    ('Michael', 'Smith'),
    ('Robert', 'Smith');

Visual Studio SignTool.exe Not Found

Here is a solution for Visual Studio 2017. The installer looks a littlebit different from the VS 2015 version and the name of the installation packages are different.

How to export data as CSV format from SQL Server using sqlcmd?

Since following 2 reasons, you should run my solution in CMD:

  1. There may be double quotes in the query
  2. Login username & password is sometimes necessary to query a remote SQL Server instance

    sqlcmd -U [your_User]  -P[your_password] -S [your_remote_Server] -d [your_databasename]  -i "query.txt" -o "output.csv" -s"," -w 700
    

how does array[100] = {0} set the entire array to 0?

It depends where you put this initialisation.

If the array is static as in

char array[100] = {0};

int main(void)
{
...
}

then it is the compiler that reserves the 100 0 bytes in the data segement of the program. In this case you could have omitted the initialiser.

If your array is auto, then it is another story.

int foo(void)
{
char array[100] = {0};
...
}

In this case at every call of the function foo you will have a hidden memset.

The code above is equivalent to

int foo(void)
{ 
char array[100];

memset(array, 0, sizeof(array));
....
}

and if you omit the initializer your array will contain random data (the data of the stack).

If your local array is declared static like in

int foo(void)
{ 
static char array[100] = {0};
...
}

then it is technically the same case as the first one.

python-How to set global variables in Flask?

With:

global index_add_counter

You are not defining, just declaring so it's like saying there is a global index_add_counter variable elsewhere, and not create a global called index_add_counter. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global keyword and initialize your variable:

index_add_counter = 0

Now you can import it with:

from app import index_add_counter

The construction:

global index_add_counter

is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:

index_add_counter = 0
def test():
  global index_add_counter # means: in this scope, use the global name
  print(index_add_counter)

Javascript - Append HTML to container element without innerHTML

To give an alternative (as using DocumentFragment does not seem to work): You can simulate it by iterating over the children of the newly generated node and only append those.

var e = document.createElement('div');
e.innerHTML = htmldata;

while(e.firstChild) {
    element.appendChild(e.firstChild);
}

Write a function that returns the longest palindrome in a given string

The Algo 2 may not work for all string. Here is an example of such a string "ABCDEFCBA".

Not that the string has "ABC" and "CBA" as its substring. If you reverse the original string, it will be "ABCFEDCBA". and the longest matching substring is "ABC" which is not a palindrome.

You may need to additionally check if this longest matching substring is actually a palindrome which has the running time of O(n^3).

How to pass table value parameters to stored procedure from .net code

Further to Ryan's answer you will also need to set the DataColumn's Ordinal property if you are dealing with a table-valued parameter with multiple columns whose ordinals are not in alphabetical order.

As an example, if you have the following table value that is used as a parameter in SQL:

CREATE TYPE NodeFilter AS TABLE (
  ID int not null
  Code nvarchar(10) not null,
);

You would need to order your columns as such in C#:

table.Columns["ID"].SetOrdinal(0);
// this also bumps Code to ordinal of 1
// if you have more than 2 cols then you would need to set more ordinals

If you fail to do this you will get a parse error, failed to convert nvarchar to int.

Check if a given time lies between two times regardless of date

As many people noticed, it's not a date problem, it's a logic problem. Let's assume a day is splitted in two intervals: one lies between 20:11:13 and 14:49:00, while the other lies between 14:49:00 and 20:11:13 (which interval the extremes belong is up to you). If you want to check if a certain time is included in the 20:11:13/14:49:00 one, the one you're interested of, just check if it's included in the other one, 14:49:00/20:11:13, which is much easier because the natural order of the numbers, and then negate the result.

2 ways for "ClearContents" on VBA Excel, but 1 work fine. Why?

It is because you haven't qualified Cells(1, 1) with a worksheet object, and the same holds true for Cells(10, 2). For the code to work, it should look something like this:

Dim ws As Worksheet

Set ws = Sheets("SheetName")
Range(ws.Cells(1, 1), ws.Cells(10, 2)).ClearContents

Alternately:

With Sheets("SheetName")
    Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With

EDIT: The Range object will inherit the worksheet from the Cells objects when the code is run from a standard module or userform. If you are running the code from a worksheet code module, you will need to qualify Range also, like so:

ws.Range(ws.Cells(1, 1), ws.Cells(10, 2)).ClearContents

or

With Sheets("SheetName")
    .Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With

How to change a <select> value from JavaScript

Once you have done your processing in the selectFunction() you could do the following

document.getElementById('select').selectedIndex = 0;
document.getElementById('select').value = 'Default';

How to prevent page scrolling when scrolling a DIV element?

just offering this up as a possible solution if you don't think the user will have a negative experience on the obvious change. I simply changed the body's class of overflow to hidden when the mouse was over the target div; then I changed the body's div to hidden overflow when the mouse leaves.

Personally I don't think it looks bad, my code could use toggle to make it cleaner, and there are obvious benefits for making this effect possible without the user being aware. So this is probably the hackish-last-resort answer.

//listen mouse on and mouse off for the button
pxMenu.addEventListener("mouseover", toggleA1);
pxOptContainer.addEventListener("mouseout", toggleA2);
//show / hide the pixel option menu
function toggleA1(){
  pxOptContainer.style.display = "flex";
  body.style.overflow = "hidden";
}
function toggleA2(){
  pxOptContainer.style.display = "none";
  body.style.overflow = "hidden scroll";
}

javax.xml.bind.UnmarshalException: unexpected element. Expected elements are (none)

Alternatively if you want to persist in using the DocumentType class. Then you could just add the following annotation on top of your DocumentType class.

    @XmlRootElement(name="document")

Note: the String value "document" refers to the name of the root tag of the xml message.

What's the difference between "git reset" and "git checkout"?

The two commands (reset and checkout) are completely different.

checkout X IS NOT reset --hard X

If X is a branch name, checkout X will change the current branch while reset --hard X will not.

How to remove entity with ManyToMany relationship in JPA (and corresponding join table rows)?

This works for me on a similar issue where I failed to delete the user due to the reference. Thank you

@ManyToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST,CascadeType.REFRESH})

How to remove an HTML element using Javascript?

Try running this code in your script.

document.getElementById("dummy").remove();

And it will hopefully remove the element/button.

How to replace existing value of ArrayList element in Java

Use the set method to replace the old value with a new one.

list.set( 2, "New" );

Unable to connect to SQL Server instance remotely

I recently upgraded from SQL 2008 R2 to SQL 2012 and had a similar issue. The problem was the firewall, but more specifically the firewall rule for SQL SERVER. The custom rule was pointed to the prior version of SQL Server. Try this, open Windows Firewall>Advanced setting. Find the SQL Server Rule (it may have a custom name). Right-Click and go to properties, then Programs and Services Tab. If Programs-This program is selected, you should browse for the proper version of sqlserver.exe.

When should I create a destructor?

It's called a "finalizer", and you should usually only create one for a class whose state (i.e.: fields) include unmanaged resources (i.e.: pointers to handles retrieved via p/invoke calls). However, in .NET 2.0 and later, there's actually a better way to deal with clean-up of unmanaged resources: SafeHandle. Given this, you should pretty much never need to write a finalizer again.

How to convert string to integer in C#

Do something like:

var result = Int32.Parse(str);

Passing parameters to a JQuery function

If you want to do an ajax call or a simple javascript function, don't forget to close your function with the return false

like this:

function DoAction(id, name) 
{ 
    // your code
    return false;
}

How to show all shared libraries used by executables in Linux?

On OS X by default there is no ldd, objdump or lsof. As an alternative, try otool -L:

$ otool -L `which openssl`
/usr/bin/openssl:
    /usr/lib/libcrypto.0.9.8.dylib (compatibility version 0.9.8, current version 0.9.8)
    /usr/lib/libssl.0.9.8.dylib (compatibility version 0.9.8, current version 0.9.8)
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1213.0.0)

In this example, using which openssl fills in the fully qualified path for the given executable and current user environment.

Why em instead of px?

The main reason for using em or percentages is to allow the user to change the text size without breaking the design. If you design with fonts specified in px, they do not change size (in IE 6 and others) if the user chooses text size - larger. This is very bad for users with visual handicaps.

For several examples of and articles on designs like this (there are a myriad to choose from), see the latest issue of A List Apart: Fluid Grids, the older article How to Size Text in CSS or Dan Cederholm's Bulletproof Web Design.

Your images should still be displayed with px sizes, but, in general, it is not considered good form to size your text with px.

As much as I personally despise IE6, it is currently the only browser approved for the bulk of the users in our Fortune 200 company.

ConvergenceWarning: Liblinear failed to converge, increase the number of iterations

Normally when an optimization algorithm does not converge, it is usually because the problem is not well-conditioned, perhaps due to a poor scaling of the decision variables. There are a few things you can try.

  1. Normalize your training data so that the problem hopefully becomes more well conditioned, which in turn can speed up convergence. One possibility is to scale your data to 0 mean, unit standard deviation using Scikit-Learn's StandardScaler for an example. Note that you have to apply the StandardScaler fitted on the training data to the test data.
  2. Related to 1), make sure the other arguments such as regularization weight, C, is set appropriately.
  3. Set max_iter to a larger value. The default is 1000.
  4. Set dual = True if number of features > number of examples and vice versa. This solves the SVM optimization problem using the dual formulation. Thanks @Nino van Hooff for pointing this out, and @JamesKo for spotting my mistake.
  5. Use a different solver, for e.g., the L-BFGS solver if you are using Logistic Regression. See @5ervant's answer.

Note: One should not ignore this warning.

This warning came about because

  1. Solving the linear SVM is just solving a quadratic optimization problem. The solver is typically an iterative algorithm that keeps a running estimate of the solution (i.e., the weight and bias for the SVM). It stops running when the solution corresponds to an objective value that is optimal for this convex optimization problem, or when it hits the maximum number of iterations set.

  2. If the algorithm does not converge, then the current estimate of the SVM's parameters are not guaranteed to be any good, hence the predictions can also be complete garbage.

Edit

In addition, consider the comment by @Nino van Hooff and @5ervant to use the dual formulation of the SVM. This is especially important if the number of features you have, D, is more than the number of training examples N. This is what the dual formulation of the SVM is particular designed for and helps with the conditioning of the optimization problem. Credit to @5ervant for noticing and pointing this out.

Furthermore, @5ervant also pointed out the possibility of changing the solver, in particular the use of the L-BFGS solver. Credit to him (i.e., upvote his answer, not mine).

I would like to provide a quick rough explanation for those who are interested (I am :)) why this matters in this case. Second-order methods, and in particular approximate second-order method like the L-BFGS solver, will help with ill-conditioned problems because it is approximating the Hessian at each iteration and using it to scale the gradient direction. This allows it to get better convergence rate but possibly at a higher compute cost per iteration. That is, it takes fewer iterations to finish but each iteration will be slower than a typical first-order method like gradient-descent or its variants.

For e.g., a typical first-order method might update the solution at each iteration like

x(k + 1) = x(k) - alpha(k) * gradient(f(x(k)))

where alpha(k), the step size at iteration k, depends on the particular choice of algorithm or learning rate schedule.

A second order method, for e.g., Newton, will have an update equation

x(k + 1) = x(k) - alpha(k) * Hessian(x(k))^(-1) * gradient(f(x(k)))

That is, it uses the information of the local curvature encoded in the Hessian to scale the gradient accordingly. If the problem is ill-conditioned, the gradient will be pointing in less than ideal directions and the inverse Hessian scaling will help correct this.

In particular, L-BFGS mentioned in @5ervant's answer is a way to approximate the inverse of the Hessian as computing it can be an expensive operation.

However, second-order methods might converge much faster (i.e., requires fewer iterations) than first-order methods like the usual gradient-descent based solvers, which as you guys know by now sometimes fail to even converge. This can compensate for the time spent at each iteration.

In summary, if you have a well-conditioned problem, or if you can make it well-conditioned through other means such as using regularization and/or feature scaling and/or making sure you have more examples than features, you probably don't have to use a second-order method. But these days with many models optimizing non-convex problems (e.g., those in DL models), second order methods such as L-BFGS methods plays a different role there and there are evidence to suggest they can sometimes find better solutions compared to first-order methods. But that is another story.

Stripping non printable characters from a string in python

In Python there's no POSIX regex classes

There are when using the regex library: https://pypi.org/project/regex/

It is well maintained and supports Unicode regex, Posix regex and many more. The usage (method signatures) is very similar to Python's re.

From the documentation:

[[:alpha:]]; [[:^alpha:]]

POSIX character classes are supported. These are normally treated as an alternative form of \p{...}.

(I'm not affiliated, just a user.)

How do you use subprocess.check_output() in Python?

Adding on to the one mentioned by @abarnert

a better one is to catch the exception

import subprocess
try:
    py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'],stderr= subprocess.STDOUT)  
    #print('py2 said:', py2output)
    print "here"
except subprocess.CalledProcessError as e:
    print "Calledprocerr"

this stderr= subprocess.STDOUT is for making sure you dont get the filenotfound error in stderr- which cant be usually caught in filenotfoundexception, else you would end up getting

python: can't open file 'py2.py': [Errno 2] No such file or directory

Infact a better solution to this might be to check, whether the file/scripts exist and then to run the file/script

Background blur with CSS

In which way do you want it dynamic? If you want the popup to successfully map to the background, you need to create two backgrounds. It requires both the use of element() or -moz-element() and a filter (for Firefox, use a SVG filter like filter: url(#svgBlur) since Firefox does not support -moz-filter: blur() as yet?). It only works in Firefox at the time of writing.

See demo here.

I still need to create a simple demo to show how it is done. You're welcome to view the source.

C++ - struct vs. class

You could prove to yourself that there is no other difference by trying to define a function in a struct. I remember even my college professor who was teaching about structs and classes in C++ was surprised to learn this (after being corrected by a student). I believe it, though. It was kind of amusing. The professor kept saying what the differences were and the student kept saying "actually you can do that in a struct too". Finally the prof. asked "OK, what is the difference" and the student informed him that the only difference was the default accessibility of members.

A quick Google search suggests that POD stands for "Plain Old Data".

converting Java bitmap to byte array

Here is bitmap extension .convertToByteArray wrote in Kotlin.

/**
 * Convert bitmap to byte array using ByteBuffer.
 */
fun Bitmap.convertToByteArray(): ByteArray {
    //minimum number of bytes that can be used to store this bitmap's pixels
    val size = this.byteCount

    //allocate new instances which will hold bitmap
    val buffer = ByteBuffer.allocate(size)
    val bytes = ByteArray(size)

    //copy the bitmap's pixels into the specified buffer
    this.copyPixelsToBuffer(buffer)

    //rewinds buffer (buffer position is set to zero and the mark is discarded)
    buffer.rewind()

    //transfer bytes from buffer into the given destination array
    buffer.get(bytes)

    //return bitmap's pixels
    return bytes
}

Create an Excel file using vbscripts

Here is a sample code

strFileName = "c:\test.xls"

Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True

Set objWorkbook = objExcel.Workbooks.Add()
objWorkbook.SaveAs(strFileName)

objExcel.Quit

How can I find all the subsets of a set, with exactly n elements?

Here's a function that gives you all subsets of the integers [0..n], not just the subsets of a given length:

from itertools import combinations, chain

def allsubsets(n):
    return list(chain(*[combinations(range(n), ni) for ni in range(n+1)]))

so e.g.

>>> allsubsets(3)
[(), (0,), (1,), (2,), (0, 1), (0, 2), (1, 2), (0, 1, 2)]

Primitive type 'short' - casting in Java

Given that the "why int by default" question hasn't been answered ...

First, "default" is not really the right term (although close enough). As noted by VonC, an expression composed of ints and longs will have a long result. And an operation consisting of ints/logs and doubles will have a double result. The compiler promotes the terms of an expression to whatever type provides a greater range and/or precision in the result (floating point types are presumed to have greater range and precision than integral, although you do lose precision converting large longs to double).

One caveat is that this promotion happens only for the terms that need it. So in the following example, the subexpression 5/4 uses only integral values and is performed using integer math, even though the overall expression involves a double. The result isn't what you might expect...

(5/4) * 1000.0

OK, so why are byte and short promoted to int? Without any references to back me up, it's due to practicality: there are a limited number of bytecodes.

"Bytecode," as its name implies, uses a single byte to specify an operation. For example iadd, which adds two ints. Currently, 205 opcodes are defined, and integer math takes 18 for each type (ie, 36 total between integer and long), not counting conversion operators.

If short, and byte each got their own set of opcodes, you'd be at 241, limiting the ability of the JVM to expand. As I said, no references to back me up on this, but I suspect that Gosling et al said "how often do people actually use shorts?" On the other hand, promoting byte to int leads to this not-so-wonderful effect (the expected answer is 96, the actual is -16):

byte x = (byte)0xC0;
System.out.println(x >> 2);

Display array values in PHP

you can easily use join()

$fruits = array("apple", "banana", "orange");
print join(" ".$fruits);

Measure string size in Bytes in php

You have to figure out if the string is ascii encoded or encoded with a multi-byte format.

In the former case, you can just use strlen.

In the latter case you need to find the number of bytes per character.

the strlen documentation gives an example of how to do it : http://www.php.net/manual/en/function.strlen.php#72274

Example of SOAP request authenticated with WS-UsernameToken

May be this post (Secure Metro JAX-WS UsernameToken Web Service with Signature, Encryption and TLS (SSL)) provides more insight. As they mentioned "Remember, unless password text or digested password is sent on a secured channel or the token is encrypted, neither password digest nor cleartext password offers no real additional security. "

Django values_list vs values

You can get the different values with:

set(Article.objects.values_list('comment_id', flat=True))

Android: Rotate image in imageview by an angle

Another possible solution is to create your own custom Image view(say RotateableImageView extends ImageView )...and override the onDraw() to rotate either the canvas/bitmaps before redering on to the canvas.Don't forget to restore the canvas back.

But if you are going to rotate only a single instance of image view,your solution should be good enough.

Get HTML code from website in C#

Here's an example of using the HttpWebRequest class to fetch a URL

private void buttonl_Click(object sender, EventArgs e) 
{ 
    String url = TextBox_url.Text;
    HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url); 
    HttpWebResponse response = (HttpWebResponse) request.GetResponse(); 
    StreamReader sr = new StreamReader(response.GetResponseStream()); 
    richTextBox1.Text = sr.ReadToEnd(); 
    sr.Close(); 
} 

Url to a google maps page to show a pin given a latitude / longitude?

From my notes:

http://maps.google.com/maps?q=37.4185N+122.08774W+(label)&ll=37.419731,-122.088715&spn=0.004250,0.011579&t=h&iwloc=A&hl=en

Which parses like this:

    q=latN+lonW+(label)     location of teardrop

    t=k             keyhole (satelite map)
    t=h             hybrid

    ll=lat,-lon     center of map
    spn=w.w,h.h     span of map, degrees

iwloc has something to do with the info window. hl is obviously language.

See also: http://www.seomoz.org/ugc/everything-you-never-wanted-to-know-about-google-maps-parameters

How to send HTML-formatted email?

Setting isBodyHtml to true allows you to use HTML tags in the message body:

msg = new MailMessage("[email protected]",
                "[email protected]", "Message from PSSP System",
                "This email sent by the PSSP system<br />" +
                "<b>this is bold text!</b>");

msg.IsBodyHtml = true;

Private Variables and Methods in Python

Double underscore. That mangles the name. The variable can still be accessed, but it's generally a bad idea to do so.

Use single underscores for semi-private (tells python developers "only change this if you absolutely must") and doubles for fully private.

UTL_FILE.FOPEN() procedure not accepting path for directory?

The directory name seems to be case sensitive. I faced the same issue but when I provided the directory name in upper case it worked.

Zero-pad digits in string

There's also str_pad

<?php
$input = "Alien";
echo str_pad($input, 10);                      // produces "Alien     "
echo str_pad($input, 10, "-=", STR_PAD_LEFT);  // produces "-=-=-Alien"
echo str_pad($input, 10, "_", STR_PAD_BOTH);   // produces "__Alien___"
echo str_pad($input, 6 , "___");               // produces "Alien_"
?>

How to set the part of the text view is clickable

I would suggest a different approach that I think requires less code and is more "localization-friendly".

Supposing that your destination activity is called "ActivityStack", define in the manifest an intent filter for it with a custom scheme (e.g. "myappscheme") in AndroidManifest.xml:

<activity
    android:name=".ActivityStack">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:host="stack"/>
        <data android:scheme="myappscheme" />
    </intent-filter>
</activity>

Define the TextView without any special tag (it is important to NOT use the "android:autoLink" tag, see: https://stackoverflow.com/a/20647011/1699702):

<TextView
    android:id="@+id/stackView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/stack_string" />

then use a link with custom scheme and host in the text of the TextView as (in String.xml):

<string name="stack_string">Android is a Software <a href="myappscheme://stack">stack</a></string>

and "activate" the link with setMovementMethod() (in onCreate() for activities or onCreateView() for fragments):

TextView stack = findViewById(R.id.stackView);
stack.setMovementMethod(LinkMovementMethod.getInstance());

This will open the stack activity with a tap on the "stack" word.

How to prevent ENTER keypress to submit a web form?

The ENTER key merely activates the form's default submit button, which will be the first

<input type="submit" />

the browser finds within the form.

Therefore don't have a submit button, but something like

<input type="button" value="Submit" onclick="submitform()" /> 

EDIT: In response to discussion in comments:

This doesn't work if you have only one text field - but it may be that is the desired behaviour in that case.

The other issue is that this relies on Javascript to submit the form. This may be a problem from an accessibility point of view. This can be solved by writing the <input type='button'/> with javascript, and then put an <input type='submit' /> within a <noscript> tag. The drawback of this approach is that for javascript-disabled browsers you will then have form submissions on ENTER. It is up to the OP to decide what is the desired behaviour in this case.

I know of no way of doing this without invoking javascript at all.

How to put img inline with text

This should display the image inline:

.content-dir-item img.mail {
    display: inline-block;
    *display: inline; /* for older IE */
    *zoom: 1; /* for older IE */
}

How to search for file names in Visual Studio?

In VS2013 you can click in the solution explorer for this functionality.

The shortcut is:

ctrl + ;

To search only the names of files, and not the contents (especially in C#), uncheck these options:

Cannot make a static reference to the non-static method fxn(int) from the type Two

  1. A static method can NOT access a Non-static method or variable.

  2. public static void main(String[] args) is a static method, so can NOT access the Non-static public static int fxn(int y) method.

  3. Try it this way...

    static int fxn(int y)

    public class Two {
    
    
        public static void main(String[] args) {
            int x = 0;
    
            System.out.println("x = " + x);
            x = fxn(x);
            System.out.println("x = " + x);
        }
    
        static int fxn(int y) {
            y = 5;
            return y;
        }
    

    }

PowerShell: Format-Table without headers

Try the -HideTableHeaders parameter to Format-Table:

gci | ft -HideTableHeaders

(I'm using PowerShell v2. I don't know if this was in v1.)

Change Oracle port from port 8080

I assume you're talking about the Apache server that Oracle installs. Look for the file httpd.conf.

Open this file in a text editor and look for the line
Listen 8080
or
Listen {ip address}:8080

Change the port number and either restart the web server or just reboot the machine.

Installing tkinter on ubuntu 14.04

Try:

sudo apt-get install python-tk python3-tk tk-dev

If you're using python3, then Python3 virtual environment(venv) is also required. Use:

sudo apt install python3-venv

base_url() function not working in codeigniter

Check if you have something configured inside the config file /application/config/config.php e.g.

$config['base_url'] = 'http://example.com/';

get original element from ng-click

You need $event.currentTarget instead of $event.target.

How to check if a file exists in Documents folder?

If you set up your file system differently or looking for a different way of setting up a file system and then checking if a file exists in the documents folder heres an another example. also show dynamic checking

for (int i = 0; i < numberHere; ++i){
    NSFileManager* fileMgr = [NSFileManager defaultManager];
    NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString* imageName = [NSString stringWithFormat:@"image-%@.png", i];
    NSString* currentFile = [documentsDirectory stringByAppendingPathComponent:imageName];
    BOOL fileExists = [fileMgr fileExistsAtPath:currentFile];
    if (fileExists == NO){
        cout << "DOESNT Exist!" << endl;
    } else {
        cout << "DOES Exist!" << endl;
    }
}

How can I read numeric strings in Excel cells as string (not numbers)?

I don't think we had this class back when you asked the question, but today there is an easy answer.

What you want to do is use the DataFormatter class. You pass this a cell, and it does its best to return you a string containing what Excel would show you for that cell. If you pass it a string cell, you'll get the string back. If you pass it a numeric cell with formatting rules applied, it will format the number based on them and give you the string back.

For your case, I'd assume that the numeric cells have an integer formatting rule applied to them. If you ask DataFormatter to format those cells, it'll give you back a string with the integer string in it.

Also, note that lots of people suggest doing cell.setCellType(Cell.CELL_TYPE_STRING), but the Apache POI JavaDocs quite clearly state that you shouldn't do this! Doing the setCellType call will loose formatting, as the javadocs explain the only way to convert to a String with formatting remaining is to use the DataFormatter class.

Dynamic loading of images in WPF

You could try attaching handlers to various events of BitmapImage:

They might tell you a little about what's going on, as far as the image is concerned.

How to auto-generate a C# class file from a JSON string

Five options:

Pros and Cons:

  • jsonclassgenerator converts to PascalCase but the others do not.

  • app.quicktype.io has some logic to recognize dictionaries and handle JSON properties whose names are invalid c# identifiers.

How do I make a text input non-editable?

if you really want to use CSS, use following property which will make field non-editable.

pointer-events: none;

DateTime.TryParseExact() rejecting valid formats

This is the Simple method, Use ParseExact

CultureInfo provider = CultureInfo.InvariantCulture;
DateTime result;
String dateString = "Sun 08 Jun 2013 8:30 AM -06:00";
String format = "ddd dd MMM yyyy h:mm tt zzz";
result = DateTime.ParseExact(dateString, format, provider);

This should work for you.

MsgBox "" vs MsgBox() in VBScript

To my knowledge these are the rules for calling subroutines and functions in VBScript:

  • When calling a subroutine or a function where you discard the return value don't use parenthesis
  • When calling a function where you assign or use the return value enclose the arguments in parenthesis
  • When calling a subroutine using the Call keyword enclose the arguments in parenthesis

Since you probably wont be using the Call keyword you only need to learn the rule that if you call a function and want to assign or use the return value you need to enclose the arguments in parenthesis. Otherwise, don't use parenthesis.

Here are some examples:

  • WScript.Echo 1, "two", 3.3 - calling a subroutine

  • WScript.Echo(1, "two", 3.3) - syntax error

  • Call WScript.Echo(1, "two", 3.3) - keyword Call requires parenthesis

  • MsgBox "Error" - calling a function "like" a subroutine

  • result = MsgBox("Continue?", 4) - calling a function where the return value is used

  • WScript.Echo (1 + 2)*3, ("two"), (((3.3))) - calling a subroutine where the arguments are computed by expressions involving parenthesis (note that if you surround a variable by parenthesis in an argument list it changes the behavior from call by reference to call by value)

  • WScript.Echo(1) - apparently this is a subroutine call using parenthesis but in reality the argument is simply the expression (1) and that is what tends to confuse people that are used to other programming languages where you have to specify parenthesis when calling subroutines

  • I'm not sure how to interpret your example, Randomize(). Randomize is a subroutine that accepts a single optional argument but even if the subroutine didn't have any arguments it is acceptable to call it with an empty pair of parenthesis. It seems that the VBScript parser has a special rule for an empty argument list. However, my advice is to avoid this special construct and simply call any subroutine without using parenthesis.

I'm quite sure that these syntactic rules applies across different versions of operating systems.

Difference of keywords 'typename' and 'class' in templates?

typename and class are interchangeable in the basic case of specifying a template:

template<class T>
class Foo
{
};

and

template<typename T>
class Foo
{
};

are equivalent.

Having said that, there are specific cases where there is a difference between typename and class.

The first one is in the case of dependent types. typename is used to declare when you are referencing a nested type that depends on another template parameter, such as the typedef in this example:

template<typename param_t>
class Foo
{
    typedef typename param_t::baz sub_t;
};

The second one you actually show in your question, though you might not realize it:

template < template < typename, typename > class Container, typename Type >

When specifying a template template, the class keyword MUST be used as above -- it is not interchangeable with typename in this case (note: since C++17 both keywords are allowed in this case).

You also must use class when explicitly instantiating a template:

template class Foo<int>;

I'm sure that there are other cases that I've missed, but the bottom line is: these two keywords are not equivalent, and these are some common cases where you need to use one or the other.

Eclipse "Server Locations" section disabled and need to change to use Tomcat installation

Make sure that there is no project Deploy in server. If so ,please right click on server ,select add and remove ,Then remove all project. After this you can double click on server and the option will be enabled for you.

Objective-C implicit conversion loses integer precision 'NSUInteger' (aka 'unsigned long') to 'int' warning

Contrary to Martin's answer, casting to int (or ignoring the warning) isn't always safe even if you know your array doesn't have more than 2^31-1 elements. Not when compiling for 64-bit.

For example:

NSArray *array = @[@"a", @"b", @"c"];

int i = (int) [array indexOfObject:@"d"];
// indexOfObject returned NSNotFound, which is NSIntegerMax, which is LONG_MAX in 64 bit.
// We cast this to int and got -1.
// But -1 != NSNotFound. Trouble ahead!

if (i == NSNotFound) {
    // thought we'd get here, but we don't
    NSLog(@"it's not here");
}
else {
    // this is what actually happens
    NSLog(@"it's here: %d", i);

    // **** crash horribly ****
    NSLog(@"the object is %@", array[i]);
}

Converting a Date object to a calendar object

Here's your method:

public static Calendar toCalendar(Date date){ 
  Calendar cal = Calendar.getInstance();
  cal.setTime(date);
  return cal;
}

Everything else you are doing is both wrong and unnecessary.

BTW, Java Naming conventions suggest that method names start with a lower case letter, so it should be: dateToCalendar or toCalendar (as shown).


OK, let's milk your code, shall we?

DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
date = (Date)formatter.parse(date.toString()); 

DateFormat is used to convert Strings to Dates (parse()) or Dates to Strings (format()). You are using it to parse the String representation of a Date back to a Date. This can't be right, can it?

CSS background-image not working

The easy way is that, copy and past this background-image: url(../slide_button.png); instead of background-image: url(slide_button.png); In such case we need to use ../ before path. Either you need to give full path. One other thing is that, in case before doing any change just clear the browser history and then refresh the page.

NoClassDefFoundError for code in an Java library on Android

I tried all of the above said solutions but did not worked out for me, Here is what i did to get it done project-> config build path-> order and export-> move dependent project on top

Python readlines() usage and efficient practice for reading

Read line by line, not the whole file:

for line in open(file_name, 'rb'):
    # process line here

Even better use with for automatically closing the file:

with open(file_name, 'rb') as f:
    for line in f:
        # process line here

The above will read the file object using an iterator, one line at a time.

How to start anonymous thread class

Leaving this here for future reference, but its an answer too.

new Thread(() -> whatever()).start();

How to automatically update your docker containers, if base-images are updated

Above Answers are also correct

There are two Approach

  1. Use webhooks
  2. Run script for every specific minute to get fresh pull of docker images

I am just sharing script may be it will helpful for you! You can use it with cronjob, I tried succesfully on OSX

#!/bin/bash
##You can use below commented line for setting cron tab for running cron job and to store its O/P in one .txt file  
#* * * * * /usr/bin/sudo -u admin -i bash -c /Users/Swapnil/Documents/checkimg.sh > /Users/Swapnil/Documents/cron_output.log 2>&1
# Example for the Docker Hub V2 API
# Returns all images and tags associated with a Docker Hub organization account.
# Requires 'jq': https://stedolan.github.io/jq/

# set username, password, and organization
# Filepath where your docker-compose file is present
FILEPATH="/Users/Swapnil/Documents/lamp-alpine"
# Your Docker hub user name
UNAME="ur username"
# Your Docker hub user password
UPASS="ur pwd"
# e.g organisation_name/image_name:image_tag
ORG="ur org name"
IMGNAME="ur img name"
IMGTAG="ur img tag"
# Container name
CONTNAME="ur container name"
# Expected built mins
BUILDMINS="5"
#Generally cronjob frequency
CHECKTIME="5"
NETWORKNAME="${IMGNAME}_private-network"
#After Image pulling, need to bring up all docker services?
DO_DOCKER_COMPOSE_UP=true
# -------
echo "Eecuting Script @ date and time in YmdHMS: $(date +%Y%m%d%H%M%S)"
set -e
PIDFILE=/Users/Swapnil/Documents/$IMGNAME/forever.pid
if [ -f $PIDFILE ]
then
  PID=$(cat $PIDFILE)
  ps -p $PID > /dev/null 2>&1
  if [ $? -eq 0 ]
  then
    echo "Process already running"
    exit 1
  else
    ## Process not found assume not running
    echo $$
    echo $$ > $PIDFILE
    if [ $? -ne 0 ]
    then
      echo "Could not create PID file"
      exit 1
    fi
  fi
else
  echo $$ > $PIDFILE
  if [ $? -ne 0 ]
  then
    echo "Could not create PID file"
    exit 1
  fi
fi

# Check Docker is running or not; If not runing then exit
if docker info|grep Containers ; then
    echo "Docker is running"
else
    echo "Docker is not running"
    rm $PIDFILE
    exit 1
fi

# Check Container is running or not; and set variable
CONT_INFO=$(docker ps -f "name=$CONTNAME" --format "{{.Names}}")
if [ "$CONT_INFO" = "$CONTNAME" ]; then
    echo "Container is running"
    IS_CONTAINER_RUNNING=true
else
    echo "Container is not running"
    IS_CONTAINER_RUNNING=false
fi


# get token
echo "Retrieving token ..."
TOKEN=$(curl -s -H "Content-Type: application/json" -X POST -d '{"username": "'${UNAME}'", "password": "'${UPASS}'"}' https://hub.docker.com/v2/users/login/ | jq -r .token)

# get list of repositories
echo "Retrieving repository list ..."
REPO_LIST=$(curl -s -H "Authorization: JWT ${TOKEN}" https://hub.docker.com/v2/repositories/${ORG}/?page_size=100 | jq -r '.results|.[]|.name')

# output images & tags
echo "Images and tags for organization: ${ORG}"
echo
for i in ${REPO_LIST}
do
  echo "${i}:"
  # tags
  IMAGE_TAGS=$(curl -s -H "Authorization: JWT ${TOKEN}" https://hub.docker.com/v2/repositories/${ORG}/${i}/tags/?page_size=100 | jq -r '.results|.[]|.name')
  for j in ${IMAGE_TAGS}
  do
    echo "  - ${j}"
  done
  #echo
done

# Check Perticular image is the latest or not
#imm=$(curl -s -H "Authorization: JWT ${TOKEN}" https://hub.docker.com/v2/repositories/${ORG}/${IMGNAME}/tags/?page_size=100)
echo "-----------------"
echo "Last built date details about Image ${IMGNAME} : ${IMGTAG} for organization: ${ORG}"
IMAGE_UPDATED_DATE=$(curl -s -H "Authorization: JWT ${TOKEN}" https://hub.docker.com/v2/repositories/${ORG}/${IMGNAME}/tags/?page_size=100 | jq -r '.results|.[]|select(.name | contains("'${IMGTAG}'")).last_updated')
echo "On Docker Hub IMAGE_UPDATED_DATE---$IMAGE_UPDATED_DATE"
echo "-----------------"

IMAGE_CREATED_DATE=$(docker image inspect ${ORG}/${IMGNAME}:${IMGTAG} | jq -r '.[]|.Created')
echo "Locally IMAGE_CREATED_DATE---$IMAGE_CREATED_DATE"

updatedDate=$(date -jf '%Y-%m-%dT%H:%M' "${IMAGE_UPDATED_DATE:0:16}" +%Y%m%d%H%M%S) 
createdDate=$(date -jf '%Y-%m-%dT%H:%M' "${IMAGE_CREATED_DATE:0:16}" +%Y%m%d%H%M%S)
currentDate=$(date +%Y%m%d%H%M%S)

start_date=$(date -jf "%Y%m%d%H%M%S" "$currentDate" "+%s")
end_date=$(date -jf "%Y%m%d%H%M%S" "$updatedDate" "+%s")
updiffMins=$(( ($start_date - $end_date) / (60) ))
if [[ "$updiffMins" -lt $(($CHECKTIME+1)) ]]; then
        if [ ! -d "${FILEPATH}" ]; then
            mkdir "${FILEPATH}";
        fi
        cd "${FILEPATH}"
        pwd
        echo "updatedDate---$updatedDate" > "ScriptOutput_${currentDate}.txt"
        echo "createdDate---$createdDate" >> "ScriptOutput_${currentDate}.txt"
        echo "currentDate---$currentDate" >> "ScriptOutput_${currentDate}.txt"
        echo "Found after regular checking time -> Docker hub's latest updated image is new; Diff ${updiffMins} mins" >> "ScriptOutput_${currentDate}.txt"
        echo "Script is checking for latest updates after every ${CHECKTIME} mins" >> "ScriptOutput_${currentDate}.txt"
        echo "Fetching all new"
        echo "---------------------------"
        if $IS_CONTAINER_RUNNING ; then
            echo "Container is running"         
        else
            docker-compose down
            echo "Container stopped and removed; Network removed" >> "ScriptOutput_${currentDate}.txt"
        fi
        echo "Image_Created_Date=$currentDate" > ".env"
        echo "ORG=$ORG" >> ".env"
        echo "IMGNAME=$IMGNAME" >> ".env"
        echo "IMGTAG=$IMGTAG" >> ".env"
        echo "CONTNAME=$CONTNAME" >> ".env"
        echo "NETWORKNAME=$NETWORKNAME" >> ".env"
        docker-compose build --no-cache
        echo "Docker Compose built" >> "ScriptOutput_${currentDate}.txt"
        if $DO_DOCKER_COMPOSE_UP ; then
            docker-compose up -d
            echo "Docker services are up now, checked in" >> "ScriptOutput_${currentDate}.txt"  
        else
            echo "Docker services are down, checked in" >> "ScriptOutput_${currentDate}.txt"
        fi
elif [[ "$updatedDate" -gt "$createdDate" ]]; then 
    echo "Updated is latest"
    start_date=$(date -jf "%Y%m%d%H%M%S" "$updatedDate" "+%s")
    end_date=$(date -jf "%Y%m%d%H%M%S" "$createdDate" "+%s")
    diffMins=$(( ($start_date - $end_date) / (60) ))
    if [[ "$BUILDMINS" -lt "$diffMins" ]]; then
        if [ ! -d "${FILEPATH}" ]; then
            mkdir "${FILEPATH}";
        fi
        cd "${FILEPATH}"
        pwd
        echo "updatedDate---$updatedDate" > "ScriptOutput_${currentDate}.txt"
        echo "createdDate---$createdDate" >> "ScriptOutput_${currentDate}.txt"
        echo "currentDate---$currentDate" >> "ScriptOutput_${currentDate}.txt"
        echo "Found after comparing times -> Docker hub's latest updated image is new; Diff ${diffMins} mins" >> "ScriptOutput_${currentDate}.txt"
        echo "Actual image built time is less i.e. ${diffMins} mins than MAX expexted BUILD TIME i.e. ${BUILDMINS} mins" >> "ScriptOutput_${currentDate}.txt"
        echo "Fetching all new" >> "ScriptOutput_${currentDate}.txt"
        echo "-----------------------------"
        if $IS_CONTAINER_RUNNING ; then
            echo "Container is running"         
        else
            docker-compose down
            echo "Container stopped and removed; Network removed" >> "ScriptOutput_${currentDate}.txt"
        fi
        echo "Image_Created_Date=$currentDate" > ".env"
        echo "ORG=$ORG" >> ".env"
        echo "IMGNAME=$IMGNAME" >> ".env"
        echo "IMGTAG=$IMGTAG" >> ".env"
        echo "CONTNAME=$CONTNAME" >> ".env"
        echo "NETWORKNAME=$NETWORKNAME" >> ".env"
        docker-compose build --no-cache
        echo "Docker Compose built" >> "ScriptOutput_${currentDate}.txt"
        if $DO_DOCKER_COMPOSE_UP ; then
            docker-compose up -d
            echo "Docker services are up now" >> "ScriptOutput_${currentDate}.txt"  
        else
            echo "Docker services are down" >> "ScriptOutput_${currentDate}.txt"
        fi
    elif [[ "$BUILDMINS" -gt "$diffMins" ]]; then
        echo "Docker hub's latest updated image is NOT new; Diff ${diffMins} mins"
        echo "Docker images not fetched"
    else
        echo "Docker hub's latest updated image is NOT new; Diff ${diffMins} mins"
        echo "Docker images not fetched"
    fi
elif [[ "$createdDate" -gt "$updatedDate" ]]; then 
    echo "Created is latest"
    start_date=$(date -jf "%Y%m%d%H%M%S" "$createdDate" "+%s")
    end_date=$(date -jf "%Y%m%d%H%M%S" "$updatedDate" "+%s")
    echo "Docker hub has older docker image than local; Older than $(( ($start_date - $end_date) / (60) ))mins"
fi
echo 
echo "------------end---------------"
rm $PIDFILE

Here is my docker-compose file

version:  "3.2"
services:
  lamp-alpine:
    build:
      context: .
    container_name: "${CONTNAME}"
    image: "${ORG}/${IMGNAME}:${IMGTAG}"
    ports:
      - "127.0.0.1:80:80"
    networks:
      - private-network 

networks:
  private-network:
    driver: bridge

How to use the curl command in PowerShell?

In Powershell 3.0 and above there is both a Invoke-WebRequest and Invoke-RestMethod. Curl is actually an alias of Invoke-WebRequest in PoSH. I think using native Powershell would be much more appropriate than curl, but it's up to you :).

Invoke-WebRequest MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849901.aspx?f=255&MSPPError=-2147217396

Invoke-RestMethod MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849971.aspx?f=255&MSPPError=-2147217396

Connecting to smtp.gmail.com via command line

For OSX' terminal:

openssl s_client -connect smtp.gmail.com:25 -starttls smtp 

How do you create a dropdownlist from an enum in ASP.NET MVC?

I bumped into the same problem, found this question, and thought that the solution provided by Ash wasn't what I was looking for; Having to create the HTML myself means less flexibility compared to the built-in Html.DropDownList() function.

Turns out C#3 etc. makes this pretty easy. I have an enum called TaskStatus:

var statuses = from TaskStatus s in Enum.GetValues(typeof(TaskStatus))
               select new { ID = s, Name = s.ToString() };
ViewData["taskStatus"] = new SelectList(statuses, "ID", "Name", task.Status);

This creates a good ol' SelectList that can be used like you're used to in the view:

<td><b>Status:</b></td><td><%=Html.DropDownList("taskStatus")%></td></tr>

The anonymous type and LINQ makes this so much more elegant IMHO. No offence intended, Ash. :)

Get nodes where child node contains an attribute

Years later, but a useful option would be to utilize XPath Axes (https://www.w3schools.com/xml/xpath_axes.asp). More specifically, you are looking to use the descendants axes.

I believe this example would do the trick:

//book[descendant::title[@lang='it']]

This allows you to select all book elements that contain a child title element (regardless of how deep it is nested) containing language attribute value equal to 'it'.

I cannot say for sure whether or not this answer is relevant to the year 2009 as I am not 100% certain that the XPath Axes existed at that time. What I can confirm is that they do exist today and I have found them to be extremely useful in XPath navigation and I am sure you will as well.

Tensorflow set CUDA_VISIBLE_DEVICES within jupyter

You can also enable multiple GPU cores, like so:

import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]="0,2,3,4"

Entity Framework change connection at runtime

In my case I'm using the ObjectContext as opposed to the DbContext so I tweaked the code in the accepted answer for that purpose.

public static class ConnectionTools
{
    public static void ChangeDatabase(
        this ObjectContext source,
        string initialCatalog = "",
        string dataSource = "",
        string userId = "",
        string password = "",
        bool integratedSecuity = true,
        string configConnectionStringName = "")
    {
        try
        {
            // use the const name if it's not null, otherwise
            // using the convention of connection string = EF contextname
            // grab the type name and we're done
            var configNameEf = string.IsNullOrEmpty(configConnectionStringName)
                ? Source.GetType().Name
                : configConnectionStringName;

            // add a reference to System.Configuration
            var entityCnxStringBuilder = new EntityConnectionStringBuilder
                (System.Configuration.ConfigurationManager
                    .ConnectionStrings[configNameEf].ConnectionString);

            // init the sqlbuilder with the full EF connectionstring cargo
            var sqlCnxStringBuilder = new SqlConnectionStringBuilder
                (entityCnxStringBuilder.ProviderConnectionString);

            // only populate parameters with values if added
            if (!string.IsNullOrEmpty(initialCatalog))
                sqlCnxStringBuilder.InitialCatalog = initialCatalog;
            if (!string.IsNullOrEmpty(dataSource))
                sqlCnxStringBuilder.DataSource = dataSource;
            if (!string.IsNullOrEmpty(userId))
                sqlCnxStringBuilder.UserID = userId;
            if (!string.IsNullOrEmpty(password))
                sqlCnxStringBuilder.Password = password;

            // set the integrated security status
            sqlCnxStringBuilder.IntegratedSecurity = integratedSecuity;

            // now flip the properties that were changed
            source.Connection.ConnectionString
                = sqlCnxStringBuilder.ConnectionString;
        }
        catch (Exception ex)
        {
            // set log item if required
        }
    }
}

How to get ° character in a string in python?

Put this line at the top of your source

# -*- coding: utf-8 -*-

If your editor uses a different encoding, substitute for utf-8

Then you can include utf-8 characters directly in the source

How do I connect to this localhost from another computer on the same network?

That's definitely possible. We'll take a general case with Apache here.

Let's say you're a big Symfony2 fan and you would like to access your symfony website at http://symfony.local/ from 4 different computers (the main one hosting your website, as well as a Mac, a Windows and a Linux distro connected (wireless or not) to the main computer.

General Sketch:

enter image description here


1 Set up a virtual host:

You first need to set up a virtual host in your apache httpd-vhosts.conf file. On XAMP, you can find this file here: C:\xampp\apache\conf\extra\httpd-vhosts.conf. On MAMP, you can find this file here: Applications/MAMP/conf/apache/extra/httpd-vhosts.conf. This step prepares the Web server on your computer for handling symfony.local requests. You need to provide the name of the Virtual Host as well as the root/main folder of your website. To do this, add the following line at the end of that file. You need to change the DocumentRoot to wherever your main folder is. Here I have taken /Applications/MAMP/htdocs/Symfony/ as the root of my website.

<VirtualHost *:80>
    DocumentRoot "/Applications/MAMP/htdocs/Symfony/"
    ServerName symfony.local
</VirtualHost>

2 Configure your hosts file:

For the client (your browser in that case) to understand what symfony.local really means, you need to edit the hosts file on your computer. Everytime you type an URL in your browser, your computer tries to understand what it means! symfony.local doesn't mean anything for a computer. So it will try to resolve the name symfony.local to an IP address. It will do this by first looking into the hosts file on your computer to see if he can match an IP address to what you typed in the address bar. If it can't, then it will ask DNS servers. The trick here is to append the following to your hosts file.

  • On MAC, this file is in /private/etc/hosts;
  • On LINUX, this file is in /etc/hosts;
  • On WINDOWS, this file is in \Windows\system32\private\etc\hosts;
  • On WINDOWS 7, this file is in \Windows\system32\drivers\etc\hosts;
  • On WINDOWS 10, this file is in \Windows\system32\drivers\etc\hosts;

Hosts file

##
# Host Database
# localhost is used to configure the loopback interface
##
#...
127.0.0.1           symfony.local

From now on, everytime you type symfony.local on this computer, your computer will use the loopback interface to connect to symfony.local. It will understand that you want to work on localhost (127.0.0.1).

3 Access symfony.local from an other computer:

We finally arrive to your main question which is:

How can I now access my website through an other computer?

Well this is now easy! We just need to tell the other computers how they could find symfony.local! How do we do this?

3a Get the IP address of the computer hosting the website:

We first need to know the IP address on the computer that hosts the website (the one we've been working on since the very beginning). In the terminal, on MAC and LINUX type ifconfig |grep inet, on WINDOWS type ipconfig. Let's assume the IP address of this computer is 192.168.1.5.

3b Edit the hosts file on the computer you are trying to access the website from.:

Again, on MAC, this file is in /private/etc/hosts; on LINUX, in /etc/hosts; and on WINDOWS, in \Windows\system32\private\etc\hosts (if you're using WINDOWS 7, this file is in \Windows\system32\drivers\etc\hosts).. The trick is now to use the IP address of the computer we are trying to access/talk to:

##
# Host Database
# localhost is used to configure the loopback interface
##
#...
192.168.1.5         symfony.local

4 Finally enjoy the results in your browser

You can now go into your browser and type http://symfony.local to beautifully see your website on different computers! Note that you can apply the same strategy if you are a OSX user to test your website on Internet Explorer via Virtual Box (if you don't want to use a Windows computer). This is beautifully explained in Crafting Your Windows / IE Test Environment on OSX.


You can also access your localhost from mobile devices

You might wonder how to access your localhost website from a mobile device. In some cases, you won't be able to modify the hosts file (iPhone, iPad...) on your device (jailbreaking excluded).

Well, the solution then is to install a proxy server on the machine hosting the website and connect to that proxy from your iphone. It's actually very well explained in the following posts and is not that long to set up:

On a Mac, I would recommend: Testing a Mac OS X web site using a local hostname on a mobile device: Using SquidMan as a proxy. It's a 100% free solution. Some people can also use Charles as a proxy server but it's 50$.

On Linux, you can adapt the Mac OS way above by using Squid as a proxy server.

On Windows, you can do that using Fiddler. The solution is described in the following post: Monitoring iPhone traffic with Fiddler


Edit 23/11/2017: Hey I don't want to modify my Hosts file

@Dre. Any possible way to access the website from another computer by not editing the host file manually? let's say I have 100 computers wanted to access the website

This is an interesting question, and as it is related to the OP question, let me help.

You would have to do a change on your network so that every machine knows where your website is hosted. Most everyday routers don't do that so you would have to run your own DNS Server on your network.

Let's pretend you have a router (192.168.1.1). This router has a DHCP server and allocates IP addresses to 100 machines on the network.

Now, let's say you have, same as above, on the same network, a machine at 192.168.1.5 which has your website. We will call that machine pompei.

$ echo $HOSTNAME
pompei

Same as before, that machine pompei at 192.168.1.5 runs an HTTP Server which serves your website symfony.local.

For every machine to know that symfony.local is hosted on pompei we will now need a custom DNS Server on the network which knows where symfony.local is hosted. Devices on the network will then be able to resolve domain names served by pompei internally.

3 simple steps.

Step 1: DNS Server

Set-up a DNS Server on your network. Let's have it on pompei for convenience and use something like dnsmasq.

Dnsmasq provides Domain Name System (DNS) forwarder, ....

We want pompei to run DNSmasq to handle DNS requests Hey, pompei, where is symfony.local and respond Hey, sure think, it is on 192.168.1.5 but don't take my word for it.

Go ahead install dnsmasq, dnsmasq configuration file is typically in /etc/dnsmasq.conf depending on your environment.

I personally use no-resolv and google servers server=8.8.8.8 server=8.8.8.4.

*Note:* ALWAYS restart DNSmasq if modifying /etc/hosts file as no changes will take effect otherwise.

Step 2: Firewall

To work, pompei needs to allow incoming and outgoing 'domain' packets, which are going from and to port 53. Of course! These are DNS packets and if pompei does not allow them, there is no way for your DNS server to be reached at all. Go ahead and open that port 53. On linux, you would classically use iptables for this.

Sharing what I came up with but you will very likely have to dive into your firewall and understand everything well.

#
# Allow outbound DNS port 53
#
 iptables -A INPUT -p tcp --dport 53 -j ACCEPT
 iptables -A INPUT -p udp --dport 53 -j ACCEPT

 iptables -A OUTPUT -p tcp --dport 53 -j ACCEPT
 iptables -A OUTPUT -p udp --dport 53 -j ACCEPT

 iptables -A INPUT -p udp --sport 53 -j ACCEPT
 iptables -A INPUT -p tcp --sport 53 -j ACCEPT

 iptables -A OUTPUT -p tcp --sport 53 -j ACCEPT
 iptables -A OUTPUT -p udp --sport 53 -j ACCEPT

Step 3: Router

Tell your router that your dns server is on 192.168.1.5 now. Most of the time, you can just login into your router and change this manually very easily.

That's it, When you are on a machine and ask for symfony.local, it will ask your DNS Server where symfony.local is hosted, and as soon as it has received its answer from the DNS server, will then send the proper HTTP request to pompei on 192.168.1.5.

I let you play with this and enjoy the ride. These 2 steps are the main guidelines, so you will have to debug and spend a few hours if this is the first time you do it. Let's say this is a bit more advanced networking, there are primary DNS Server, secondary DNS Servers, etc.. Good luck!

Automatically pass $event with ng-click?

Add a $event to the ng-click, for example:

<button type="button" ng-click="saveOffer($event)" accesskey="S"></button>

Then the jQuery.Event was passed to the callback:

enter image description here

How can I set the default value for an HTML <select> element?

The problem with <select> is, it's sometimes disconnected with the state of what's currently rendered and unless something has changed in the option list, no change value is returned. This can be a problem when trying to select the first option from a list. The following code can get the first-option the first-time selected, but onchange="changeFontSize(this)" by its self would not. There are methods described above using a dummy option to force a user to make a change value to pickup the actual first value, such as starting the list with an empty value. Note: onclick would call the function twice, the following code does not, but solves the first-time problem.

<label>Font Size</label>
<select name="fontSize" id="fontSize" onfocus="changeFontSize(this)" onchange="changeFontSize(this)">           
    <option value="small">Small</option>
    <option value="medium">Medium</option>
    <option value="large">Large</option>
    <option value="extraLarge">Extra large</option>
</select>

<script>
function changeFontSize(x){
    body=document.getElementById('body');
    if (x.value=="extraLarge") {
        body.style.fontSize="25px";
    } else {
        body.style.fontSize=x.value;
    }
}
</script>

Centering brand logo in Bootstrap Navbar

Old question, but just for posterity.

I've found the easiest way to do it is to have the image as the background image of the navbar-brand. Just makes sure to put in a custom width.

.navbar-brand
{
    margin-left: auto;
    margin-right: auto;
    width: 150px;
    background-image: url('logo.png');
}

Read Variable from Web.Config

Assuming the key is contained inside the <appSettings> node:

ConfigurationSettings.AppSettings["theKey"];

As for "writing" - put simply, dont.

The web.config is not designed for that, if you're going to be changing a value constantly, put it in a static helper class.

The type WebMvcConfigurerAdapter is deprecated

In Spring every request will go through the DispatcherServlet. To avoid Static file request through DispatcherServlet(Front contoller) we configure MVC Static content.

Spring 3.1. introduced the ResourceHandlerRegistry to configure ResourceHttpRequestHandlers for serving static resources from the classpath, the WAR, or the file system. We can configure the ResourceHandlerRegistry programmatically inside our web context configuration class.

  • we have added the /js/** pattern to the ResourceHandler, lets include the foo.js resource located in the webapp/js/ directory
  • we have added the /resources/static/** pattern to the ResourceHandler, lets include the foo.html resource located in the webapp/resources/ directory
@Configuration
@EnableWebMvc
public class StaticResourceConfiguration implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        System.out.println("WebMvcConfigurer - addResourceHandlers() function get loaded...");
        registry.addResourceHandler("/resources/static/**")
                .addResourceLocations("/resources/");

        registry
            .addResourceHandler("/js/**")
            .addResourceLocations("/js/")
            .setCachePeriod(3600)
            .resourceChain(true)
            .addResolver(new GzipResourceResolver())
            .addResolver(new PathResourceResolver());
    }
}

XML Configuration

<mvc:annotation-driven />
  <mvc:resources mapping="/staticFiles/path/**" location="/staticFilesFolder/js/"
                 cache-period="60"/>

Spring Boot MVC Static Content if the file is located in the WAR’s webapp/resources folder.

spring.mvc.static-path-pattern=/resources/static/**

Determining type of an object in ruby

I would say "Yes". As "Matz" had said something like this in one of his talks, "Ruby objects have no types." Not all of it but the part that he is trying to get across to us. Why would anyone have said "Everything is an Object" then? To add he said "Data has Types not objects".

So we might enjoy this.

https://www.youtube.com/watch?v=1l3U1X3z0CE

But Ruby doesn't care to much about the type of object just the class. We use classes not types. All data then has a class.

12345.class

'my string'.class

They may also have ancestors

Object.ancestors

They also have meta classes but I'll save you the details on that.

Once you know the class then you'll be able to lookup what methods you may use for it. That's where the "data type" is needed. If you really want to get into details the look up...

"The Ruby Object Model"

This is the term used for how Ruby handles objects. It's all internal so you don't really see much of this but it's nice to know. But that's another topic.

Yes! The class is the data type. Objects have classes and data has types. So if you know about data bases then you know there are only a finite set of types.

text blocks numbers

How to replace comma with a dot in the number (or any replacement)

Per the docs, replace returns the new string - it does not modify the string you pass it.

var tt="88,9827";
tt = tt.replace(/,/g, '.');
^^^^
alert(tt);

Is there a numpy builtin to reject outliers from a list

Building on Benjamin's, using pandas.Series, and replacing MAD with IQR:

def reject_outliers(sr, iq_range=0.5):
    pcnt = (1 - iq_range) / 2
    qlow, median, qhigh = sr.dropna().quantile([pcnt, 0.50, 1-pcnt])
    iqr = qhigh - qlow
    return sr[ (sr - median).abs() <= iqr]

For instance, if you set iq_range=0.6, the percentiles of the interquartile-range would become: 0.20 <--> 0.80, so more outliers will be included.

Why am I getting "Thread was being aborted" in ASP.NET?

I got this error when I did a Response.Redirect after a successful login of the user.

I fixed it by doing a FormsAuthentication.RedirectFromLoginPage instead.

How to import spring-config.xml of one project into spring-config.xml of another project?

<import resource="classpath:spring-config.xml" />

Reference:

Android: adb: Permission Denied

Be careful with the slash, change "\" for "/" , like this: adb.exe push SuperSU-v2.79-20161205182033.apk /storage

How to force Hibernate to return dates as java.util.Date instead of Timestamp?

So, I spent some time with this issue and found a solution. It is not pretty one, but at least a start point - maybe someone will supplement this with some useful comments.

Some info about mapping that I found in process:

  • Class that contains basic mapping of Hibernate types to property types is org.hibernate.type.TypeFactory. All this mappings are stored in unmodifiable map

    private static final Map BASIC_TYPES;
    ...
    basics.put( java.util.Date.class.getName(), Hibernate.TIMESTAMP );
    ...
    BASIC_TYPES = Collections.unmodifiableMap( basics );
    

As you can see with java.util.Date type assosited with Hibernate type org.hibernate.type.TimestampType

  • Next interesting moment - creation of Hibernate org.hibernate.cfg.Configuration - object that contains all info about mapped classes. This classes and their properties can be extracted like this:

    Iterator clsMappings = cfg.getClassMappings();
    while(clsMappings.hasNext()){
        PersistentClass mapping = (PersistentClass) clsMappings.next();
        handleProperties(mapping.getPropertyIterator(), map);
    }
    
  • Vast majority of properties are the objects of org.hibernate.mapping.SimpleValue types. Our point of interest is the method SimpleValue.getType() - in this method is defined what type will be used to convert properties values back-and-forth while working with DB

    Type result = TypeFactory.heuristicType(typeName, typeParameters);
    

At this point I understand that I am unable to modify BASIC_TYPES - so the only way - to replace SimpleValue object to the properties of java.util.Date types to my custom Object that will be able to know the exact type to convert.

The solution:

  • Create custom container entity manager factory by extending HibernatePersistence class and overriding its method createContainerEntityManagerFactory:

    public class HibernatePersistenceExtensions extends HibernatePersistence {
    
        @Override
        public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map map) {
    
            if ("true".equals(map.get("hibernate.use.custom.entity.manager.factory"))) {
                return CustomeEntityManagerFactoryFactory.createCustomEntityManagerFactory(info, map);
            } else {
                return super.createContainerEntityManagerFactory(info, map);
            }
        }
    }
    
  • Create Hibernate configuration object, modify value ojects for java.util.Date properties and then create custom entity manager factory.

    public class ReattachingEntityManagerFactoryFactory {
    
    
        @SuppressWarnings("rawtypes")
        public static EntityManagerFactory createContainerEntityManagerFactory(
        PersistenceUnitInfo info, Map map) {
            Ejb3Configuration cfg = new Ejb3Configuration();
    
            Ejb3Configuration configured = cfg.configure( info, map );
    
            handleClassMappings(cfg, map);
    
            return configured != null ? configured.buildEntityManagerFactory() : null;
        }
    
        @SuppressWarnings("rawtypes")
        private static void handleClassMappings(Ejb3Configuration cfg, Map map) {
            Iterator clsMappings = cfg.getClassMappings();
            while(clsMappings.hasNext()){
                 PersistentClass mapping = (PersistentClass) clsMappings.next();
                 handleProperties(mapping.getPropertyIterator(), map);
            }
        } 
    
    
    
        private static void handleProperties(Iterator props, Map map) {
    
            while(props.hasNext()){
                 Property prop = (Property) props.next();
                 Value value = prop.getValue();
                 if (value instanceof Component) {
                     Component c = (Component) value;
                     handleProperties(c.getPropertyIterator(), map);
                 } else {
    
                     handleReturnUtilDateInsteadOfTimestamp(prop, map);
    
                 }
             }
    
        private static void handleReturnUtilDateInsteadOfTimestamp(Property prop, Map map) {
            if ("true".equals(map.get("hibernate.return.date.instead.of.timestamp"))) {
                Value value = prop.getValue();
    
                if (value instanceof SimpleValue) {
                    SimpleValue simpleValue = (SimpleValue) value;
                    String typeName = simpleValue.getTypeName();
                    if ("java.util.Date".equals(typeName)) {
                        UtilDateSimpleValue udsv = new UtilDateSimpleValue(simpleValue);
                        prop.setValue(udsv);
                    }
                }
            }
        }
    
    }
    

As you can see I just iterate over every property and substitute SimpleValue-object for UtilDateSimpleValue for properties of type java.util.Date. This is very simple class - it implements the same interface as SimpleValue object, e.g org.hibernate.mapping.KeyValue. In constructor original SimpleValue object is passed - so every call to UtilDateSimpleValue is redirected to the original object with one exception - method getType(...) return my custom Type.

public class UtilDateSimpleValue implements KeyValue{

    private SimpleValue value;

    public UtilDateSimpleValue(SimpleValue value) {
        this.value = value;
    }

    public SimpleValue getValue() {
        return value;
    }

    @Override
    public int getColumnSpan() {
        return value.getColumnSpan();
    }

    ...

    @Override
    public Type getType() throws MappingException {
        final String typeName = value.getTypeName();

        if (typeName == null) {
                throw new MappingException("No type name");
        }

        Type result = new UtilDateUserType();

        return result;
    }
    ...
}
  • And the last step is implementation of UtilDateUserType. I just extend original org.hibernate.type.TimestampType and override its method get() like this:

    public class UtilDateUserType extends TimestampType{
    
        @Override
        public Object get(ResultSet rs, String name) throws SQLException {
            Timestamp ts = rs.getTimestamp(name);
    
            Date result = null;
            if(ts != null){
                result = new Date(ts.getTime());
            }
    
            return result;
        }
    }
    

That is all. A little bit tricky, but now every java.util.Date property is returned as java.util.Date without any additional modifications of existing code (annotations or modifying setters). As I find out in Hibernate 4 or above there is a much more easier way to substitute your own type (see details here: Hibernate TypeResolver). Any suggestions or criticism are welcome.

How to cast int to enum in C++?

Test e = static_cast<Test>(1);

MySQL/SQL: Group by date only on a Datetime column

Or:

SELECT SUM(foo), DATE(mydate) mydate FROM a_table GROUP BY mydate;

More efficient (I think.) Because you don't have to cast mydate twice per row.

Is there an easy way to attach source in Eclipse?

Another option is to right click on your jar file which would be under (Your Project)->Referenced Libraries->(your jar) and click on properties. Then click on Java Source Attachment. And then in location path put in the location for your source jar file.

This is just another approach to attaching your source file.

How do I remove all null and empty string values from an object?

Using some ES6 / ES2015:

If you don't like to create an extra function and remove the items 'inline'.

Object.keys(obj).forEach(k => (!obj[k] && obj[k] !== undefined) && delete obj[k]);

jsbin

Same, written as a function.

const removeEmpty = (obj) => {
  Object.keys(obj).forEach((k) => (!obj[k] && obj[k] !== undefined) && delete obj[k]);
  return obj;
};

jsbin

This function uses recursion to delete items from nested objects as well:

const removeEmpty = (obj) => {
  Object.keys(obj).forEach(k =>
    (obj[k] && typeof obj[k] === 'object') && removeEmpty(obj[k]) ||
    (!obj[k] && obj[k] !== undefined) && delete obj[k]
  );
  return obj;
};

jsbin

Same as function before but with ES7 / 2016 Object.entries:

const removeEmpty = (obj) => {
  Object.entries(obj).forEach(([key, val])  =>
    (val && typeof val === 'object') && removeEmpty(val) ||
    (val === null || val === "") && delete obj[key]
  );
  return obj;
};

Same as third example but in plain ES5:

function removeEmpty(obj) {
  Object.keys(obj).forEach(function(key) {
    (obj[key] && typeof obj[key] === 'object') && removeEmpty(obj[key]) ||
    (obj[key] === '' || obj[key] === null) && delete obj[key]
  });
  return obj;
};

jsbin

Get last dirname/filename in a file path argument in Bash

basename does remove the directory prefix of a path:

$ basename /usr/local/svn/repos/example
example
$ echo "/server/root/$(basename /usr/local/svn/repos/example)"
/server/root/example

What is default list styling (CSS)?

You're resetting the margin on all elements in the second css block. Default margin is 40px - this should solve the problem:

.my_container ul {list-style:disc outside none; margin-left:40px;}

What is the definition of "interface" in object oriented programming

An interface separates out operations on a class from the implementation within. Thus, some implementations may provide for many interfaces.

People would usually describe it as a "contract" for what must be available in the methods of the class.

It is absolutely not a blueprint, since that would also determine implementation. A full class definition could be said to be a blueprint.

Python dictionary: Get list of values for list of keys

Try this:

mydict = {'one': 1, 'two': 2, 'three': 3}
mykeys = ['three', 'one'] # if there are many keys, use a set

[mydict[k] for k in mykeys]
=> [3, 1]

Git: cannot checkout branch - error: pathspec '...' did not match any file(s) known to git

Such a problem arise when you try to get branch your local git doesn`t know. First

git remote add origin yourremotegitrepository

After

git fetch //you should get all remote branches  

git checkout branchname

That is all.

handling DATETIME values 0000-00-00 00:00:00 in JDBC

Alternative answer, you can use this JDBC URL directly in your datasource configuration:

jdbc:mysql://yourserver:3306/yourdatabase?zeroDateTimeBehavior=convertToNull

Edit:

Source: MySQL Manual

Datetimes with all-zero components (0000-00-00 ...) — These values can not be represented reliably in Java. Connector/J 3.0.x always converted them to NULL when being read from a ResultSet.

Connector/J 3.1 throws an exception by default when these values are encountered as this is the most correct behavior according to the JDBC and SQL standards. This behavior can be modified using the zeroDateTimeBehavior configuration property. The allowable values are:

  • exception (the default), which throws an SQLException with an SQLState of S1009.
  • convertToNull, which returns NULL instead of the date.
  • round, which rounds the date to the nearest closest value which is 0001-01-01.

Update: Alexander reported a bug affecting mysql-connector-5.1.15 on that feature. See CHANGELOGS on the official website.

variable or field declared void

It for example happens in this case here:

void initializeJSP(unknownType Experiment);

Try using std::string instead of just string (and include the <string> header). C++ Standard library classes are within the namespace std::.

PHP $_FILES['file']['tmp_name']: How to preserve filename and extension?

$_FILES["file"]["tmp_name"] contains the actual copy of your file content on the server while
$_FILES["file"]["name"] contains the name of the file which you have uploaded from the client computer.

How do I convert NSMutableArray to NSArray?

If you're constructing an array via mutability and then want to return an immutable version, you can simply return the mutable array as an "NSArray" via inheritance.

- (NSArray *)arrayOfStrings {
    NSMutableArray *mutableArray = [NSMutableArray array];
    mutableArray[0] = @"foo";
    mutableArray[1] = @"bar";

    return mutableArray;
}

If you "trust" the caller to treat the (technically still mutable) return object as an immutable NSArray, this is a cheaper option than [mutableArray copy].

Apple concurs:

To determine whether it can change a received object, the receiver of a message must rely on the formal type of the return value. If it receives, for example, an array object typed as immutable, it should not attempt to mutate it. It is not an acceptable programming practice to determine if an object is mutable based on its class membership.

The above practice is discussed in more detail here:

Best Practice: Return mutableArray.copy or mutableArray if return type is NSArray

Convert PEM traditional private key to PKCS8 private key

To convert the private key from PKCS#1 to PKCS#8 with openssl:

# openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in pkcs1.key -out pkcs8.key

That will work as long as you have the PKCS#1 key in PEM (text format) as described in the question.

Using NSLog for debugging

The proper way of using NSLog, as the warning tries to explain, is the use of a formatter, instead of passing in a literal:

Instead of:

NSString *digit = [[sender titlelabel] text];
NSLog(digit);

Use:

NSString *digit = [[sender titlelabel] text];
NSLog(@"%@",digit);

It will still work doing that first way, but doing it this way will get rid of the warning.

Assert an object is a specific type

You can use the assertThat method and the Matchers that comes with JUnit.

Take a look at this link that describes a little bit about the JUnit Matchers.

Example:

public class BaseClass {
}

public class SubClass extends BaseClass {
}

Test:

import org.junit.Test;

import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertThat;

/**
 * @author maba, 2012-09-13
 */
public class InstanceOfTest {

    @Test
    public void testInstanceOf() {
        SubClass subClass = new SubClass();
        assertThat(subClass, instanceOf(BaseClass.class));
    }
}

jquery mobile background image

just simple replace your class with this.

.ui-page
{
   background: transparent url(images/EarthIcon.jpg) no-repeat center center;
}

I have same issue and i solved it.

How can I remove the outline around hyperlinks images?

There is the same border effect in Firefox and Internet Explorer (IE), it becomes visible when you click on some link.

This code will fix just IE:

a:active { outline: none; }.

And this one will fix both Firefox and IE:

:active, :focus { outline: none; -moz-outline-style: none; }

Last code should be added into your stylesheet, if you would like to remove the link borders from your site.

json Uncaught SyntaxError: Unexpected token :

You've told jQuery to expect a JSONP response, which is why jQuery has added the callback=jQuery16406345664265099913_1319854793396&_=1319854793399 part to the URL (you can see this in your dump of the request).

What you're returning is JSON, not JSONP. Your response looks like

{"red" : "#f00"}

and jQuery is expecting something like this:

jQuery16406345664265099913_1319854793396({"red" : "#f00"})

If you actually need to use JSONP to get around the same origin policy, then the server serving colors.json needs to be able to actually return a JSONP response.

If the same origin policy isn't an issue for your application, then you just need to fix the dataType in your jQuery.ajax call to be json instead of jsonp.

How To Include CSS and jQuery in my WordPress plugin?

For styles wp_register_style( 'namespace', 'http://locationofcss.com/mycss.css' );

Then use: wp_enqueue_style('namespace'); wherever you want the css to load.

Scripts are as above but the quicker way for loading jquery is just to use enqueue loaded in an init for the page you want it to load on: wp_enqueue_script('jquery');

Unless of course you want to use the google repository for jquery.

You can also conditionally load the jquery library that your script is dependent on:

wp_enqueue_script('namespaceformyscript', 'http://locationofscript.com/myscript.js', array('jquery'));

Update Sept. 2017

I wrote this answer a while ago. I should clarify that the best place to enqueue your scripts and styles is within the wp_enqueue_scripts hook. So for example:

add_action('wp_enqueue_scripts', 'callback_for_setting_up_scripts');
function callback_for_setting_up_scripts() {
    wp_register_style( 'namespace', 'http://locationofcss.com/mycss.css' );
    wp_enqueue_style( 'namespace' );
    wp_enqueue_script( 'namespaceformyscript', 'http://locationofscript.com/myscript.js', array( 'jquery' ) );
}

The wp_enqueue_scripts action will set things up for the "frontend". You can use the admin_enqueue_scripts action for the backend (anywhere within wp-admin) and the login_enqueue_scripts action for the login page.

How do I update pip itself from inside my virtual environment?

pip version 10 has an issue. It will manifest as the error:

ubuntu@mymachine-:~/mydir$ sudo pip install --upgrade pip
Traceback (most recent call last):
  File "/usr/bin/pip", line 9, in <module>
    from pip import main
ImportError: cannot import name main

The solution is to be in the venv you want to upgrade and then run:

sudo myvenv/bin/pip install --upgrade pip

rather than just

sudo pip install --upgrade pip

Of Countries and their Cities

From all my searching around, I strongly say that the most practical, accurate and free data source is provided by GeoNames.

You can access their data in 2 ways:

  1. The easy way through their free web services.
  2. Import their free text files into Database tables and use the data in any way you wish. This method offers much greater flexibility and have found that this method is better.

Meaning of Choreographer messages in Logcat

In my case I have these messages when I show the sherlock action bar inderterminate progressbar. Since its not my library, I decided to hide the Choreographer outputs.

You can hide the Choreographer outputs onto the Logcat view, using this filter expression :

tag:^((?!Choreographer).*)$

I used a regex explained elsewhere : Regular expression to match a line that doesn't contain a word?

Is there a shortcut to make a block comment in Xcode?

i managed to get this working well via an automator task and have used shortcut to bind it to key combination ctrl+option+command+b. all i have to do is highlight the code i want block commented in xcode and press the above keys and the selected text is block commented out using /* ... */.

i use code folding a fair bit so the reason i wanted this functionality was so i could easily fold down a block of commented code ... code commented the usual way using // wont fold.

im not familiar with using mac automator but i simply followed the instrux in the following wwdc video

in the WWDC 2012 video Session 402 - Working Efficiently with Xcode ( from around 6 minutes in) there's a description of how to use the Mac OSX Automator to add a service to manipulate selected text. The example shown in the video is to remove duplicates in a selection of text using the shell commands sort and uniq. Using this approach you do the same but you enter the following command instead of what he does in the video

awk 'BEGIN{print "/"}{print $0}END{print "/"}'

(note there are meant to be 2 asterisks in the previous line that for some reason are not showing .... they do show up in the screenshot below so copy that as the correct command to enter)

you should end up running a shell script like this

screenshot

this will, for any given selected text, put the comment delimiters before and after.

when you save it you should get options to name it (i called it blockcomment) and also to assign a keyboard shortcut

then you should be able to open xcode, select some text, right click, the context menu, and the name you gave to this script should show near the bottom

simply click the name and the script will run and block comment the selected code or use the keyboard shortcut you assigned.

hope this helps

How do you import an Eclipse project into Android Studio now?

Here is a simpler way to migrate:

Start off with a sample Android Studio project. Open android studio and create a new project (or) just download a ‘sample’ studio project here: https://github.com/AppLozic/eclipse-to-android-studio-migration. Now, open the downloaded project in Android Studio by following the below instructions.

Import eclipse project modules into Android Studio. Select File -> New -> Import Module Image title

Next, select the path of the eclipse project and import the modules. In case, if you see the message “Failed to sync Gradle project,” then click on “Install Build Tools and sync project…”

Now, remove the sample project modules by following the below simple steps:

Open settings.gradle and remove “include ‘:app’” Right click on “app” module and “Delete” it. Now, what we have is the Eclipse project open in Android studio with the Gradle build.

Here are few other links which might help you:

http://developer.android.com/sdk/installing/migrate.html Source: http://www.applozic.com/blog/migrating-project-from-eclipse-to-studio/

How to remove array element in mongodb?

You can simply use $pull to remove a sub-document. The $pull operator removes from an existing array all instances of a value or values that match a specified condition.

Collection.update({
    _id: parentDocumentId
  }, {
    $pull: {
      subDocument: {
        _id: SubDocumentId
      }
    }
  });

This will find your parent document against given ID and then will remove the element from subDocument which matched the given criteria.

Read more about pull here.

How to get a Static property with Reflection

The below seems to work for me.

using System;
using System.Reflection;

public class ReflectStatic
{
    private static int SomeNumber {get; set;}
    public static object SomeReference {get; set;}
    static ReflectStatic()
    {
        SomeReference = new object();
        Console.WriteLine(SomeReference.GetHashCode());
    }
}

public class Program
{
    public static void Main()
    {
        var rs = new ReflectStatic();
        var pi = rs.GetType().GetProperty("SomeReference",  BindingFlags.Static | BindingFlags.Public);
        if(pi == null) { Console.WriteLine("Null!"); Environment.Exit(0);}
        Console.WriteLine(pi.GetValue(rs, null).GetHashCode());


    }
}

How do I read the file content from the Internal storage - Android App

    String path = Environment.getExternalStorageDirectory().toString();
    Log.d("Files", "Path: " + path);
    File f = new File(path);
    File file[] = f.listFiles();
    Log.d("Files", "Size: " + file.length);
    for (int i = 0; i < file.length; i++) {
        //here populate your listview
        Log.d("Files", "FileName:" + file[i].getName());

    }

How to get duration, as int milli's and float seconds from <chrono>?

In AAA style using the explicitly typed initializer idiom:

#include <chrono>
#include <iostream>

int main(){
  auto start = std::chrono::high_resolution_clock::now();
  // Code to time here...
  auto end = std::chrono::high_resolution_clock::now();

  auto dur = end - start;
  auto i_millis = std::chrono::duration_cast<std::chrono::milliseconds>(dur);
  auto f_secs = std::chrono::duration_cast<std::chrono::duration<float>>(dur);
  std::cout << i_millis.count() << '\n';
  std::cout << f_secs.count() << '\n';
}

What is the best way to dump entire objects to a log in C#?

You could use reflection and loop through all the object properties, then get their values and save them to the log. The formatting is really trivial (you could use \t to indent an objects properties and its values):

MyObject
    Property1 = value
    Property2 = value2
    OtherObject
       OtherProperty = value ...

A message body writer for Java type, class myPackage.B, and MIME media type, application/octet-stream, was not found

This also happens if you're missing an empty public constructor for the Entity (could be for JSON, XML etc)..

How to write a switch statement in Ruby

You can write case expressions in two different ways in Ruby:

  1. Similar to a series of if statements
  2. Specify a target next to the case and each when clause is compared to the target.
age = 20
case 
when age >= 21
puts "display something"
when 1 == 0
puts "omg"
else
puts "default condition"
end

or:

case params[:unknown]
when /Something/ then 'Nothing'
when /Something else/ then 'I dont know'
end

Get number of digits with JavaScript

Note : This function will ignore the numbers after the decimal mean dot, If you wanna count with decimal then remove the Math.floor(). Direct to the point check this out!

function digitCount ( num )
{
     return Math.floor( num.toString()).length;
}

 digitCount(2343) ;

// ES5+

 const digitCount2 = num => String( Math.floor( Math.abs(num) ) ).length;

 console.log(digitCount2(3343))

Basically What's going on here. toString() and String() same build-in function for converting digit to string, once we converted then we'll find the length of the string by build-in function length.

Alert: But this function wouldn't work properly for negative number, if you're trying to play with negative number then check this answer Or simple put Math.abs() in it;

Cheer You!

CodeIgniter removing index.php from url

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]

use

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$1 [PT,L]

if you have url in this order site.com/index.php/class/method/id

NB:remove index.php in config.php should be config[index_page] = ""

NB: notice the difference at the last line instead of $0 use $1

How to Compare two Arrays are Equal using Javascript?

function isEqual(a) {
if (arrayData.length > 0) {
    for (var i in arrayData) {
        if (JSON.stringify(arrayData[i]) === JSON.stringify(a)) {
            alert("Ya existe un registro con esta informacion");
            return false;
        }
    }
}
}

Check this example

What's a decent SFTP command-line client for windows?

This little application does the job for me. I could not find another CLI based client that would access my IIS based TLS/SSL secured ftp site: http://netwinsite.com/surgeftp/sslftp.htm

Database, Table and Column Naming Conventions?

I hear the argument all the time that whether or not a table is pluralized is all a matter of personal taste and there is no best practice. I don't believe that is true, especially as a programmer as opposed to a DBA. As far as I am aware, there are no legitimate reasons to pluralize a table name other than "It just makes sense to me because it's a collection of objects," while there are legitimate gains in code by having singular table names. For example:

  1. It avoids bugs and mistakes caused by plural ambiguities. Programmers aren't exactly known for their spelling expertise, and pluralizing some words are confusing. For example, does the plural word end in 'es' or just 's'? Is it persons or people? When you work on a project with large teams, this can become an issue. For example, an instance where a team member uses the incorrect method to pluralize a table he creates. By the time I interact with this table, it is used all over in code I don't have access to or would take too long to fix. The result is I have to remember to spell the table wrong every time I use it. Something very similar to this happened to me. The easier you can make it for every member of the team to consistently and easily use the exact, correct table names without errors or having to look up table names all the time, the better. The singular version is much easier to handle in a team environment.

  2. If you use the singular version of a table name AND prefix the primary key with the table name, you now have the advantage of easily determining a table name from a primary key or vice versa via code alone. You can be given a variable with a table name in it, concatenate "Id" to the end, and you now have the primary key of the table via code, without having to do an additional query. Or you can cut off "Id" from the end of a primary key to determine a table name via code. If you use "id" without a table name for the primary key, then you cannot via code determine the table name from the primary key. In addition, most people who pluralize table names and prefix PK columns with the table name use the singular version of the table name in the PK (for example statuses and status_id), making it impossible to do this at all.

  3. If you make table names singular, you can have them match the class names they represent. Once again, this can simplify code and allow you to do really neat things, like instantiating a class by having nothing but the table name. It also just makes your code more consistent, which leads to...

  4. If you make the table name singular, it makes your naming scheme consistent, organized, and easy to maintain in every location. You know that in every instance in your code, whether it's in a column name, as a class name, or as the table name, it's the same exact name. This allows you to do global searches to see everywhere that data is used. When you pluralize a table name, there will be cases where you will use the singular version of that table name (the class it turns into, in the primary key). It just makes sense to not have some instances where your data is referred to as plural and some instances singular.

To sum it up, if you pluralize your table names you are losing all sorts of advantages in making your code smarter and easier to handle. There may even be cases where you have to have lookup tables/arrays to convert your table names to object or local code names you could have avoided. Singular table names, though perhaps feeling a little weird at first, offer significant advantages over pluralized names and I believe are best practice.

Java generics - why is "extends T" allowed but not "implements T"?

It's sort of arbitrary which of the terms to use. It could have been either way. Perhaps the language designers thought of "extends" as the most fundamental term, and "implements" as the special case for interfaces.

But I think implements would make slightly more sense. I think that communicates more that the parameter types don't have to be in an inheritance relationship, they can be in any kind of subtype relationship.

The Java Glossary expresses a similar view.

Static nested class in Java, why?

  1. JVM knows no nested classes. Nesting is just syntactic sugar.

    Below images shows Java file:

    enter image description here

    Below images show class files representation of the java file :

    enter image description here

    Notice that 2 class files are generated, one for parent and another for nested class.

  2. Non-static nested class' objects have access to the enclosing scope. That access to the enclosing scope is maintained by holding an implicit reference of the enclosing scope object in the nested object

  3. Nested class is a way to represent the intent that the nested class type represents a component of the parent class.

    public class Message {
    
    private MessageType messageType; // component of parent class
    
    public enum MessageType {
        SENT, RECEIVE;
    }
    }
    
    
    
    class Otherclass {
    
    public boolean isSent(Message message) {
        if (message.getMessageType() == MessageType.SENT) { // accessible at other places as well
            return true;
        }
        return false;
    }
    }
    
  4. private static nested class represents Point#3 & the fact the nested type can only be the subcomponent to the parent class. It can't be used separately.

    public class Message {
    
     private Content content; // Component of message class
    
     private static class Content { // can only be a component of message class
    
      private String body;
      private int sentBy;
    
      public String getBody() {
         return body;
      }
    
      public int getSentBy() {
         return sentBy;
      }
    
    }
    }
    
    class Message2 {
      private Message.Content content; // Not possible
    }
    
  5. More details here.

Python: Finding differences between elements of a list

I suspect this is what the numpy diff command does anyway, but just for completeness you can simply difference the sub-vectors:

from numpy import array as a
a(x[1:])-a(x[:-1])

In addition, I wanted to add these solutions to generalizations of the question:

Solution with periodic boundaries

Sometimes with numerical integration you will want to difference a list with periodic boundary conditions (so the first element calculates the difference to the last. In this case the numpy.roll function is helpful:

v-np.roll(v,1)

Solutions with zero prepended

Another numpy solution (just for completeness) is to use

numpy.ediff1d(v)

This works as numpy.diff, but only on a vector (it flattens the input array). It offers the ability to prepend or append numbers to the resulting vector. This is useful when handling accumulated fields that is often the case fluxes in meteorological variables (e.g. rain, latent heat etc), as you want a resulting list of the same length as the input variable, with the first entry untouched.

Then you would write

np.ediff1d(v,to_begin=v[0])

Of course, you can also do this with the np.diff command, in this case though you need to prepend zero to the series with the prepend keyword:

np.diff(v,prepend=0.0) 

All the above solutions return a vector that is the same length as the input.

Passing multiple variables to another page in url

from php.net

Warning The superglobals $_GET and $_REQUEST are already decoded. Using urldecode() on an element in $_GET or $_REQUEST could have unexpected and dangerous results.

link: http://php.net/manual/en/function.urldecode.php

be careful.

Asynchronously wait for Task<T> to complete with timeout

Definitely don't do this, but it is an option if ... I can't think of a valid reason.

((CancellationTokenSource)cancellationToken.GetType().GetField("m_source",
    System.Reflection.BindingFlags.NonPublic |
    System.Reflection.BindingFlags.Instance
).GetValue(cancellationToken)).Cancel();

Node.js: socket.io close client connection

For socket.io version 1.4.5:

On server:

socket.on('end', function (){
    socket.disconnect(0);
});

On client:

var io = io();
io.emit('end');

How to get the android Path string to a file on Assets folder?

Just to add on Jacek's perfect solution. If you're trying to do this in Kotlin, it wont work immediately. Instead, you'll want to use this:

@Throws(IOException::class)
fun getSplashVideo(context: Context): File {
    val cacheFile = File(context.cacheDir, "splash_video")
    try {
        val inputStream = context.assets.open("splash_video")
        val outputStream = FileOutputStream(cacheFile)
        try {
            inputStream.copyTo(outputStream)
        } finally {
            inputStream.close()
            outputStream.close()
        }
    } catch (e: IOException) {
        throw IOException("Could not open splash_video", e)
    }
    return cacheFile
}

formatFloat : convert float number to string

Try this

package main

import "fmt"
import "strconv"

func FloatToString(input_num float64) string {
    // to convert a float number to a string
    return strconv.FormatFloat(input_num, 'f', 6, 64)
}

func main() {
    fmt.Println(FloatToString(21312421.213123))
}

If you just want as many digits precision as possible, then the special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly. Eg

strconv.FormatFloat(input_num, 'f', -1, 64)

Personally I find fmt easier to use. (Playground link)

fmt.Printf("x = %.6f\n", 21312421.213123)

Or if you just want to convert the string

fmt.Sprintf("%.6f", 21312421.213123)

When restoring a backup, how do I disconnect all active connections?

This code worked for me, it kills all existing connections of a database. All you have to do is change the line Set @dbname = 'databaseName' so it has your database name.

Use Master
Go

Declare @dbname sysname

Set @dbname = 'databaseName'

Declare @spid int
Select @spid = min(spid) from master.dbo.sysprocesses
where dbid = db_id(@dbname)
While @spid Is Not Null
Begin
        Execute ('Kill ' + @spid)
        Select @spid = min(spid) from master.dbo.sysprocesses
        where dbid = db_id(@dbname) and spid > @spid
End

after this I was able to restore it

Android : How to set onClick event for Button in List item of ListView

I find

final Button yourButton = (Button)view.findViewById(R.id.your_button);
yourButton.setFocusable(false);
yourButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        ...///);

can solve the problem. If you want to get some data when clicking the button, using tags is helpful. Here the button is declared final because it will be used within inner class.

Check if list contains element that contains a string and get that element

It is possible to combine Any, Where, First and FirstOrDefault; or just place the predicate in any of those methods depending on what is needed.

You should probably avoid using First unless you want to have an exception thrown when no match is found. FirstOrDefault is usually the better option as long as you know it will return the type's default if no match is found (string's default is null, int is 0, bool is false, etc).

using System.Collections.Generic;
using System.Linq;


bool exists;
string firstMatch;
IEnumerable<string> matchingList;

var myList = new List<string>() { "foo", "bar", "foobar" };

exists = myList.Any(x => x.Contains("o"));
// exists => true

firstMatch = myList.FirstOrDefault(x => x.Contains("o"));
firstMatch = myList.First(x => x.Contains("o"));
// firstMatch => "foo"

firstMatch = myList.First(x => x.Contains("dark side"));
// throws exception because no element contains "dark side"

firstMatch = myList.FirstOrDefault(x => x.Contains("dark side"));
// firstMatch => null

matchingList = myList.Where(x => x.Contains("o")); 
// matchingList => { "foo", "foobar" }

Test this code @ https://rextester.com/TXDL57489

Test a weekly cron job

I'm using Webmin because its a productivity gem for someone who finds command line administration a bit daunting and impenetrable.

There is a "Save and Run Now" button in the "System > Scheduled Cron Jobs > Edit Cron Job" web interface.

It displays the output of the command and is exactly what I needed.

Firebase Permission Denied

By default the database in a project in the Firebase Console is only readable/writeable by administrative users (e.g. in Cloud Functions, or processes that use an Admin SDK). Users of the regular client-side SDKs can't access the database, unless you change the server-side security rules.


You can change the rules so that the database is only readable/writeable by authenticated users:

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

See the quickstart for the Firebase Database security rules.

But since you're not signing the user in from your code, the database denies you access to the data. To solve that you will either need to allow unauthenticated access to your database, or sign in the user before accessing the database.

Allow unauthenticated access to your database

The simplest workaround for the moment (until the tutorial gets updated) is to go into the Database panel in the console for you project, select the Rules tab and replace the contents with these rules:

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

This makes your new database readable and writeable by anyone who knows the database's URL. Be sure to secure your database again before you go into production, otherwise somebody is likely to start abusing it.

Sign in the user before accessing the database

For a (slightly) more time-consuming, but more secure, solution, call one of the signIn... methods of Firebase Authentication to ensure the user is signed in before accessing the database. The simplest way to do this is using anonymous authentication:

firebase.auth().signInAnonymously().catch(function(error) {
  // Handle Errors here.
  var errorCode = error.code;
  var errorMessage = error.message;
  // ...
});

And then attach your listeners when the sign-in is detected

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
    var isAnonymous = user.isAnonymous;
    var uid = user.uid;
    var userRef = app.dataInfo.child(app.users);
    
    var useridRef = userRef.child(app.userid);
    
    useridRef.set({
      locations: "",
      theme: "",
      colorScheme: "",
      food: ""
    });

  } else {
    // User is signed out.
    // ...
  }
  // ...
});

move div with CSS transition

Something like this?

DEMO

And the code I used:

.box{
    position: relative;
    overflow: hidden;
}

.box:hover .hidden{

    left: 0px;
}

.box .hidden {    
    background: yellow;
    height: 300px;    
    position: absolute; 
    top: 0;
    left: -500px;    
    width: 500px;
    opacity: 1;    
    -webkit-transition: all 0.7s ease-out;
       -moz-transition: all 0.7s ease-out;
        -ms-transition: all 0.7s ease-out;
         -o-transition: all 0.7s ease-out;
            transition: all 0.7s ease-out;
}

I may also add that it's possible to move an elment using transform: translate(); , which in this case could work something like this - DEMO nr2

How can I create a self-signed cert for localhost?

I would recomment Pluralsight's tool for creating self-signed-certs: http://blog.pluralsight.com/selfcert-create-a-self-signed-certificate-interactively-gui-or-programmatically-in-net

Make your cert as a .pfx and import it into IIS. And add it as a trusted root cert authority.

Is Python faster and lighter than C++?

Also: Psyco vs. C++.

It's still a bad comparison, since noone would do the numbercrunchy stuff benchmarks tend to focus on in pure Python anyway. A better one would be comparing the performance of realistic applications, or C++ versus NumPy, to get an idea whether your program will be noticeably slower.

How to check if any flags of a flag combination are set?

If you want to know if letter has any of the letters in AB you must use the AND & operator. Something like:

if ((letter & Letters.AB) != 0)
{
    // Some flag (A,B or both) is enabled
}
else
{
    // None of them are enabled
}

Vertical alignment of text and icon in button

Just wrap the button label in an extra span and add class="align-middle" to both (the icon and the label). This will center your icon with text vertical.

<button id="edit-listing-form-house_Continue" 
    class="btn btn-large btn-primary"
    style=""
    value=""
    name="Continue"
    type="submit">
<span class="align-middle">Continue</span>
<i class="icon-ok align-middle" style="font-size:40px;"></i>

jQuery event to trigger action when a div is made visible

redsquare's solution is the right answer.

But as an IN-THEORY solution you can write a function which is selecting the elements classed by .visibilityCheck (not all visible elements) and check their visibility property value; if true then do something.

Afterward, the function should be performed periodically using the setInterval() function. You can stop the timer using the clearInterval() upon successful call-out.

Here's an example:

function foo() {
    $('.visibilityCheck').each(function() {
        if ($(this).is(':visible')){
            // do something
        }
    });
}

window.setInterval(foo, 100);

You can also perform some performance improvements on it, however, the solution is basically absurd to be used in action. So...

How to remove a column from an existing table?

Your example is simple and doesn’t require any additional table changes but generally speaking this is not so trivial.

If this column is referenced by other tables then you need to figure out what to do with other tables/columns. One option is to remove foreign keys and keep referenced data in other tables.

Another option is to find all referencing columns and remove them as well if they are not needed any longer.

In such cases the real challenge is finding all foreign keys. You can do this by querying system tables or using third party tools such as ApexSQL Search (free) or Red Gate Dependency tracker (premium but more features). There a whole thread on foreign keys here

How to get a parent element to appear above child

Fortunately a solution exists. You must add a wrapper for parent and change z-index of this wrapper for example 10, and set z-index for child to -1:

_x000D_
_x000D_
.parent {_x000D_
    position: relative;_x000D_
    width: 750px;_x000D_
    height: 7150px;_x000D_
    background: red;_x000D_
    border: solid 1px #000;_x000D_
    z-index: initial;_x000D_
}_x000D_
_x000D_
.child {_x000D_
    position: relative;_x000D_
    background-color: blue;_x000D_
    z-index: -1;_x000D_
    color: white;_x000D_
}_x000D_
_x000D_
.wrapper {_x000D_
    position: relative;_x000D_
    background: green;_x000D_
    z-index: 10;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
    <div class="parent">parent parent_x000D_
        <div class="child">child child child</div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

ADB not recognising Nexus 4 under Windows 7

I had the same problem and none of the above worked, but the following solution worked for me:

On my Nexus 4:

  • Go to Settings

  • Choose Developer options (from the end of the list after pressing seven times on "About phone")

  • Check the "USB debugging" and press OK.

Current time formatting with Javascript

You may want to try

var d = new Date();
d.toLocaleString();       // -> "2/1/2013 7:37:08 AM"
d.toLocaleDateString();   // -> "2/1/2013"
d.toLocaleTimeString();  // -> "7:38:05 AM"

Documentation

Angular EXCEPTION: No provider for Http

If you have this error in your tests, you should create Fake Service for all services:

For example:

import { YourService1 } from '@services/your1.service';
import { YourService2 } from '@services/your2.service';

class FakeYour1Service {
 public getSomeData():any { return null; }
}

class FakeYour2Service {
  public getSomeData():any { return null; }
}

And in beforeEach:

beforeEach(async(() => {
  TestBed.configureTestingModule({
    providers: [
      Your1Service,
      Your2Service,
      { provide: Your1Service, useClass: FakeYour1Service },
      { provide: Your2Service, useClass: FakeYour2Service }
    ]
  }).compileComponents();  // compile template and css
}));

An App ID with Identifier '' is not available. Please enter a different string

If not the AppId's business,just try to change the Team in TARGETS/identity to your company's team.

Relay access denied on sending mail, Other domain outside of network

Configuring $mail->SMTPAuth = true; was the solution for me. The reason why is because without authentication the mail server answers with 'Relay access denied'. Since putting this in my code, all mails work fine.

Compilation fails with "relocation R_X86_64_32 against `.rodata.str1.8' can not be used when making a shared object"

Do what the compiler tells you to do, i.e. recompile with -fPIC. To learn what does this flag do and why you need it in this case, see Code Generation Options of the GCC manual.

In brief, the term position independent code (PIC) refers to the generated machine code which is memory address agnostic, i.e. does not make any assumptions about where it was loaded into RAM. Only position independent code is supposed to be included into shared objects (SO) as they should have an ability to dynamically change their location in RAM.

Finally, you can read about it on Wikipedia too.

Auto expand a textarea using jQuery

People seem to have very over worked solutions...

This is how I do it:

  $('textarea').keyup(function()
  {
    var 
    $this  = $(this),
    height = parseInt($this.css('line-height'),     10),
    padTop = parseInt($this.css('padding-top'),     10),
    padBot = parseInt($this.css('padding-bottom'),  10);

    $this.height(0);

    var 
    scroll = $this.prop('scrollHeight'),
    lines  = (scroll  - padTop - padBot) / height;

    $this.height(height * lines);
  });

This will work with long lines, as well as line breaks.. grows and shrinks..

How to remove all leading zeroes in a string

I don't think preg_replace is the answer.. old thread but just happen to looking for this today. ltrim and (int) casting is the winner.

<?php
 $numString = "0000001123000";
 $actualInt = "1123000";

 $fixed_str1 = preg_replace('/000+/','',$numString);
 $fixed_str2 = ltrim($numString, '0');
 $fixed_str3 = (int)$numString;

 echo $numString . " Original";
 echo "<br>"; 
 echo $fixed_str1 . " Fix1";
 echo "<br>"; 
 echo $fixed_str2 . " Fix2";
 echo "<br>";
 echo $fixed_str3 . " Fix3";
 echo "<br>";
 echo $actualInt . " Actual integer in string";

 //output

 0000001123000 Origina
 1123 Fix1
 1123000 Fix2
 1123000 Fix3
 1123000 Actual integer in tring

Encoding URL query parameters in Java

String param="2019-07-18 19:29:37";
param="%27"+param.trim().replace(" ", "%20")+"%27";

I observed in case of Datetime (Timestamp) URLEncoder.encode(param,"UTF-8") does not work.

How do you make a deep copy of an object?

Here is a generic deep cloning method using object serialization and deserialization with byte array streams (to avoid writing to a file).

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

@SuppressWarnings("unchecked")
public static <T extends Serializable> T deepClone(T t) {
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);) {
        oos.writeObject(t);
        byte[] bytes = baos.toByteArray();
        try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes))) {
            return (T) ois.readObject();
        }
    } catch (IOException | ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
}

Python string prints as [u'String']

Use dir or type on the 'string' to find out what it is. I suspect that it's one of BeautifulSoup's tag objects, that prints like a string, but really isn't one. Otherwise, its inside a list and you need to convert each string separately.

In any case, why are you objecting to using Unicode? Any specific reason?

Argument list too long error for rm, cp, mv commands

I had the same problem with a folder full of temporary images that was growing day by day and this command helped me to clear the folder

find . -name "*.png" -mtime +50 -exec rm {} \;

The difference with the other commands is the mtime parameter that will take only the files older than X days (in the example 50 days)

Using that multiple times, decreasing on every execution the day range, I was able to remove all the unnecessary files

How to delete a file after checking whether it exists

  if (System.IO.File.Exists(@"C:\Users\Public\DeleteTest\test.txt"))
    {
        // Use a try block to catch IOExceptions, to 
        // handle the case of the file already being 
        // opened by another process. 
        try
        {
            System.IO.File.Delete(@"C:\Users\Public\DeleteTest\test.txt");
        }
        catch (System.IO.IOException e)
        {
            Console.WriteLine(e.Message);
            return;
        }
    }

What is the best method to merge two PHP objects?

You could create another object that dispatches calls to magic methods to the underlying objects. Here's how you'd handle __get, but to get it working fully you'd have to override all the relevant magic methods. You'll probably find syntax errors since I just entered it off the top of my head.

class Compositor {
  private $obj_a;
  private $obj_b;

  public function __construct($obj_a, $obj_b) {
    $this->obj_a = $obj_a;
    $this->obj_b = $obj_b;
  }

  public function __get($attrib_name) {
    if ($this->obj_a->$attrib_name) {
       return $this->obj_a->$attrib_name;
    } else {
       return $this->obj_b->$attrib_name;
    }
  }
}

Good luck.