Programs & Examples On #Polish

Polish is the English name for the language spoken in Poland.

Change language of Visual Studio 2017 RC

  1. Go to Tools -> Options
  2. Select International Settings in Environment and on the right side of a screen you should see a combo with the list of installed language packages. (so in my case Czech, English and same as on MS Windows )
  3. Click on Ok

You have to restart Visual Studio to see the change...

If you are polish (and got polish language settings)

  1. Narzedzia -> Opcje
  2. Ustawienia miedzynarodowe in Srodowisko

Hope this helps! Have a great time in Poland!

Adding Google Translate to a web site

{{-- Google Language Translator  START --}}
<style>
.google-translate {
    display: inline-block;
    vertical-align: top;
    padding-top: 15px;
}

.goog-logo-link {
    display: none !important;
}

.goog-te-gadget {
    color: transparent !important;
}

#google_translate_element {
    display: none;
}

.goog-te-banner-frame.skiptranslate {
    display: none !important;
}

body {
    top: 0px !important;
}

</style>

<script src="{{asset('js/translate-google.js')}}"></script>



<script type="text/javascript">
function googleTranslateElementInit2(){
    new google.translate.TranslateElement({
                    pageLanguage:'en',
                    includedLanguages: 'en,es',
        // https://ctrlq.org/code/19899-google-translate-languages
        // includedLanguages: 'en,it,la,fr',
        // layout:     google.translate.TranslateElement.InlineLayout.SIMPLE,
        autoDisplay:true
    },'google_translate_element2');
    var a = document.querySelector("#google_translate_element select");
    // console.log(a);

    if(a){
        a.selectedIndex=1;
        a.dispatchEvent(new Event('change'));
    }
}
</script>

<ul class="navbar-nav my-lg-0 m-r-10">
<li>
    <div class="google-translate">
        <div id="google_translate_element2"></div>
    </div>
</li>

{{-- Google Language Translator ENDS --}}

// translate-google.js
(function () {
var gtConstEvalStartTime = new Date();

function d(b) {
    var a = document.getElementsByTagName("head")[0];
    a || (a = document.body.parentNode.appendChild(document.createElement("head")));
    a.appendChild(b)
}

function _loadJs(b) {
    // console.log(b);
    var a = document.createElement("script");
    a.type = "text/javascript";
    a.charset = "UTF-8";
    a.src = b;
    d(a)
}

function _loadCss(b) {
    var a = document.createElement("link");
    a.type = "text/css";
    a.rel = "stylesheet";
    a.charset = "UTF-8";
    a.href = b;
    d(a)
}

function _isNS(b) {
    b = b.split(".");
    for (var a = window, c = 0; c < b.length; ++c)
        if (!(a = a[b[c]])) return !1;
    return !0
}

function _setupNS(b) {
    b = b.split(".");
    for (var a = window, c = 0; c < b.length; ++c) a.hasOwnProperty ? a.hasOwnProperty(b[c]) ? a = a[b[c]] : a = a[b[c]] = {} : a = a[b[c]] || (a[b[c]] = {});
    return a
}
window.addEventListener && "undefined" == typeof document.readyState && window.addEventListener("DOMContentLoaded", function () {
    document.readyState = "complete"
}, !1);
if (_isNS('google.translate.Element')) {
    return
}(function () {
    var c = _setupNS('google.translate._const');
    c._cest = gtConstEvalStartTime;
    gtConstEvalStartTime = undefined;
    c._cl = 'en';
    c._cuc = 'googleTranslateElementInit2';
    c._cac = '';
    c._cam = '';
    c._ctkk = eval('((function(){var a\x3d3002255536;var b\x3d-2533142796;return 425386+\x27.\x27+(a+b)})())');
    var h = 'translate.googleapis.com';
    var s = (true ? 'https' : window.location.protocol == 'https:' ? 'https' : 'http') + '://';
    var b = s + h;
    c._pah = h;
    c._pas = s;
    c._pbi = b + '/translate_static/img/te_bk.gif';
    c._pci = b + '/translate_static/img/te_ctrl3.gif';
    c._pli = b + '/translate_static/img/loading.gif';
    c._plla = h + '/translate_a/l';
    c._pmi = b + '/translate_static/img/mini_google.png';
    c._ps = b + '/translate_static/css/translateelement.css';
    c._puh = 'translate.google.com';
    _loadCss(c._ps);
    _loadJs(b + '/translate_static/js/element/main.js');
})();
})();

How to make a gui in python

Using Qt in Python is a really pleasant experience: http://wiki.python.org/moin/PyQt

For the quick tutorial: http://zetcode.com/tutorials/pyqt4/

how to check the version of jar file?

This simple program will list all the cases for version of jar namely

  • Version found in Manifest file
  • No version found in Manifest and even from jar name
  • Manifest file not found

    Map<String, String> jarsWithVersionFound   = new LinkedHashMap<String, String>();
    List<String> jarsWithNoManifest     = new LinkedList<String>();
    List<String> jarsWithNoVersionFound = new LinkedList<String>();
    
    //loop through the files in lib folder
    //pick a jar one by one and getVersion()
    //print in console..save to file(?)..maybe later
    
    File[] files = new File("path_to_jar_folder").listFiles();
    
    for(File file : files)
    {
        String fileName = file.getName();
    
    
        try
        {
            String jarVersion = new Jar(file).getVersion();
    
            if(jarVersion == null)
                jarsWithNoVersionFound.add(fileName);
            else
                jarsWithVersionFound.put(fileName, jarVersion);
    
        }
        catch(Exception ex)
        {
            jarsWithNoManifest.add(fileName);
        }
    }
    
    System.out.println("******* JARs with versions found *******");
    for(Entry<String, String> jarName : jarsWithVersionFound.entrySet())
        System.out.println(jarName.getKey() + " : " + jarName.getValue());
    
    System.out.println("\n \n ******* JARs with no versions found *******");
    for(String jarName : jarsWithNoVersionFound)
        System.out.println(jarName);
    
    System.out.println("\n \n ******* JARs with no manifest found *******");
    for(String jarName : jarsWithNoManifest)
        System.out.println(jarName);
    

It uses the javaxt-core jar which can be downloaded from http://www.javaxt.com/downloads/

Detect Browser Language in PHP

The official way to handle this is using the PECL HTTP library. Unlike some answers here, this correctly handles the language priorities (q-values), partial language matches and will return the closest match, or when there are no matches it falls back to the first language in your array.

PECL HTTP:
http://pecl.php.net/package/pecl_http

How to use:
http://php.net/manual/fa/function.http-negotiate-language.php

$supportedLanguages = [
    'en-US', // first one is the default/fallback
    'fr',
    'fr-FR',
    'de',
    'de-DE',
    'de-AT',
    'de-CH',
];

// Returns the negotiated language 
// or the default language (i.e. first array entry) if none match.
$language = http_negotiate_language($supportedLanguages, $result);

How to change default text file encoding in Eclipse?

Nanda's answer wasn't enough in my setup. What I needed to do is:

  • Window > Preferences > General > Content Types
  • Select Text > HTML in the tree
  • Select all file associations, particularly .html
  • Input "UTF-8" in the text-field "default encoding"

Get name of property as a string

Based on the answer which is already in the question and on this article: https://handcraftsman.wordpress.com/2008/11/11/how-to-get-c-property-names-without-magic-strings/ I am presenting my solution to this problem:

public static class PropertyNameHelper
{
    /// <summary>
    /// A static method to get the Propertyname String of a Property
    /// It eliminates the need for "Magic Strings" and assures type safety when renaming properties.
    /// See: http://stackoverflow.com/questions/2820660/get-name-of-property-as-a-string
    /// </summary>
    /// <example>
    /// // Static Property
    /// string name = PropertyNameHelper.GetPropertyName(() => SomeClass.SomeProperty);
    /// // Instance Property
    /// string name = PropertyNameHelper.GetPropertyName(() => someObject.SomeProperty);
    /// </example>
    /// <typeparam name="T"></typeparam>
    /// <param name="propertyLambda"></param>
    /// <returns></returns>
    public static string GetPropertyName<T>(Expression<Func<T>> propertyLambda)
    {
        var me = propertyLambda.Body as MemberExpression;

        if (me == null)
        {
            throw new ArgumentException("You must pass a lambda of the form: '() => Class.Property' or '() => object.Property'");
        }

        return me.Member.Name;
    }
    /// <summary>
    /// Another way to get Instance Property names as strings.
    /// With this method you don't need to create a instance first.
    /// See the example.
    /// See: https://handcraftsman.wordpress.com/2008/11/11/how-to-get-c-property-names-without-magic-strings/
    /// </summary>
    /// <example>
    /// string name = PropertyNameHelper((Firma f) => f.Firmenumsatz_Waehrung);
    /// </example>
    /// <typeparam name="T"></typeparam>
    /// <typeparam name="TReturn"></typeparam>
    /// <param name="expression"></param>
    /// <returns></returns>
    public static string GetPropertyName<T, TReturn>(Expression<Func<T, TReturn>> expression)
    {
        MemberExpression body = (MemberExpression)expression.Body;
        return body.Member.Name;
    }
}

And a Test which also shows the usage for instance and static properties:

[TestClass]
public class PropertyNameHelperTest
{
    private class TestClass
    {
        public static string StaticString { get; set; }
        public string InstanceString { get; set; }
    }

    [TestMethod]
    public void TestGetPropertyName()
    {
        Assert.AreEqual("StaticString", PropertyNameHelper.GetPropertyName(() => TestClass.StaticString));

        Assert.AreEqual("InstanceString", PropertyNameHelper.GetPropertyName((TestClass t) => t.InstanceString));
    }
}

conversion from infix to prefix

https://en.wikipedia.org/wiki/Shunting-yard_algorithm

The shunting yard algorithm can also be applied to produce prefix notation (also known as polish notation). To do this one would simply start from the end of a string of tokens to be parsed and work backwards, reverse the output queue (therefore making the output queue an output stack), and flip the left and right parenthesis behavior (remembering that the now-left parenthesis behavior should pop until it finds a now-right parenthesis).

from collections import deque
def convertToPN(expression):
    precedence = {}
    precedence["*"] = precedence["/"] = 3
    precedence["+"] = precedence["-"] = 2
    precedence[")"] = 1

    stack  = []
    result = deque([])
    for token in expression[::-1]:
        if token == ')':
            stack.append(token)
        elif token == '(':
            while stack:
                t = stack.pop()
                if t == ")": break
                result.appendleft(t)
        elif token not in precedence:
            result.appendleft(token)
        else:
            # XXX: associativity should be considered here
            # https://en.wikipedia.org/wiki/Operator_associativity
            while stack and precedence[stack[-1]] > precedence[token]:
                result.appendleft(stack.pop())
            stack.append(token)

    while stack:
        result.appendleft(stack.pop())

    return list(result)

expression = "(a - b) / c * (d + e - f / g)".replace(" ", "")
convertToPN(expression)

step through:

step 1 : token ) ; stack:[ ) ]
result:[  ]
step 2 : token g ; stack:[ ) ]
result:[ g ]
step 3 : token / ; stack:[ ) / ]
result:[ g ]
step 4 : token f ; stack:[ ) / ]
result:[ f g ]
step 5 : token - ; stack:[ ) - ]
result:[ / f g ]
step 6 : token e ; stack:[ ) - ]
result:[ e / f g ]
step 7 : token + ; stack:[ ) - + ]
result:[ e / f g ]
step 8 : token d ; stack:[ ) - + ]
result:[ d e / f g ]
step 9 : token ( ; stack:[  ]
result:[ - + d e / f g ]
step 10 : token * ; stack:[ * ]
result:[ - + d e / f g ]
step 11 : token c ; stack:[ * ]
result:[ c - + d e / f g ]
step 12 : token / ; stack:[ * / ]
result:[ c - + d e / f g ]
step 13 : token ) ; stack:[ * / ) ]
result:[ c - + d e / f g ]
step 14 : token b ; stack:[ * / ) ]
result:[ b c - + d e / f g ]
step 15 : token - ; stack:[ * / ) - ]
result:[ b c - + d e / f g ]
step 16 : token a ; stack:[ * / ) - ]
result:[ a b c - + d e / f g ]
step 17 : token ( ; stack:[ * / ]
result:[ - a b c - + d e / f g ]

# the final while
step 18 : token ( ; stack:[  ]
result:[ * / - a b c - + d e / f g ]

the best way to make codeigniter website multi-language. calling from lang arrays depends on lang session?

I've used Wiredesignz's MY_Language class with great success.

I've just published it on github, as I can't seem to find a trace of it anywhere.

https://github.com/meigwilym/CI_Language

My only changes are to rename the class to CI_Lang, in accordance with the new v2 changes.

Java Strings: "String s = new String("silly");"

String s1="foo";

literal will go in pool and s1 will refer.

String s2="foo";

this time it will check "foo" literal is already available in StringPool or not as now it exist so s2 will refer the same literal.

String s3=new String("foo");

"foo" literal will be created in StringPool first then through string arg constructor String Object will be created i.e "foo" in the heap due to object creation through new operator then s3 will refer it.

String s4=new String("foo");

same as s3

so System.out.println(s1==s2);// **true** due to literal comparison.

and System.out.println(s3==s4);// **false** due to object

comparison(s3 and s4 is created at different places in heap)

Git undo changes in some files

Why can't you simply mark what changes you want to have in a commit using "git add <file>" (or even "git add --interactive", or "git gui" which has option for interactive comitting), and then use "git commit" instead of "git commit -a"?

In your situation (for your example) it would be:

prompt> git add B
prompt> git commit

Only changes to file B would be comitted, and file A would be left "dirty", i.e. with those print statements in the working area version. When you want to remove those print statements, it would be enought to use

prompt> git reset A

or

prompt> git checkout HEAD -- A

to revert to comitted version (version from HEAD, i.e. "git show HEAD:A" version).

React / JSX Dynamic Component Name

Suspose we wish to access various views with dynamic component loading.The following code gives a working example of how to accomplish this by using a string parsed from the search string of a url.

Lets assume we want to access a page 'snozberrys' with two unique views using these url paths:

'http://localhost:3000/snozberrys?aComponent'

and

'http://localhost:3000/snozberrys?bComponent'

we define our view's controller like this:

import React, { Component } from 'react';
import ReactDOM from 'react-dom'
import {
  BrowserRouter as Router,
  Route
} from 'react-router-dom'
import AComponent from './AComponent.js';
import CoBComponent sole from './BComponent.js';

const views = {
  aComponent: <AComponent />,
  console: <BComponent />
}

const View = (props) => {
  let name = props.location.search.substr(1);
  let view = views[name];
  if(view == null) throw "View '" + name + "' is undefined";
  return view;
}

class ViewManager extends Component {
  render() {
    return (
      <Router>
        <div>
          <Route path='/' component={View}/>
        </div>
      </Router>
    );
  }
}

export default ViewManager

ReactDOM.render(<ViewManager />, document.getElementById('root'));

Which is the correct C# infinite loop, for (;;) or while (true)?

Even I also say the below one is better :)

while(true)
{

}

Stick button to right side of div

change the CSS as follows:

div button {
position:absolute;
    right:10px;
    top:25px;
}

How can I tell if a DOM element is visible in the current viewport?

Most of the usages in previous answers are failing at these points:

-When any pixel of an element is visible, but not "a corner",

-When an element is bigger than viewport and centered,

-Most of them are checking only for a singular element inside a document or window.

Well, for all these problems I've a solution and the plus sides are:

-You can return visible when only a pixel from any sides shows up and is not a corner,

-You can still return visible while element bigger than viewport,

-You can choose your parent element or you can automatically let it choose,

-Works on dynamically added elements too.

If you check the snippets below you will see the difference in using overflow-scroll in element's container will not cause any trouble and see that unlike other answers here even if a pixel shows up from any side or when an element is bigger than viewport and we are seeing inner pixels of the element it still works.

Usage is simple:

// For checking element visibility from any sides
isVisible(element)

// For checking elements visibility in a parent you would like to check
var parent = document; // Assuming you check if 'element' inside 'document'
isVisible(element, parent)

// For checking elements visibility even if it's bigger than viewport
isVisible(element, null, true) // Without parent choice
isVisible(element, parent, true) // With parent choice

A demonstration without crossSearchAlgorithm which is usefull for elements bigger than viewport check element3 inner pixels to see:

_x000D_
_x000D_
function isVisible(element, parent, crossSearchAlgorithm) {_x000D_
    var rect = element.getBoundingClientRect(),_x000D_
            prect = (parent != undefined) ? parent.getBoundingClientRect() : element.parentNode.getBoundingClientRect(),_x000D_
        csa = (crossSearchAlgorithm != undefined) ? crossSearchAlgorithm : false,_x000D_
        efp = function (x, y) { return document.elementFromPoint(x, y) };_x000D_
    // Return false if it's not in the viewport_x000D_
    if (rect.right < prect.left || rect.bottom < prect.top || rect.left > prect.right || rect.top > prect.bottom) {_x000D_
        return false;_x000D_
    }_x000D_
    var flag = false;_x000D_
    // Return true if left to right any border pixel reached_x000D_
    for (var x = rect.left; x < rect.right; x++) {_x000D_
        if (element.contains(efp(rect.top, x)) || element.contains(efp(rect.bottom, x))) {_x000D_
        flag = true;_x000D_
        break;_x000D_
      }_x000D_
    }_x000D_
    // Return true if top to bottom any border pixel reached_x000D_
    if (flag == false) {_x000D_
      for (var y = rect.top; y < rect.bottom; y++) {_x000D_
        if (element.contains(efp(rect.left, y)) || element.contains(efp(rect.right, y))) {_x000D_
          flag = true;_x000D_
          break;_x000D_
        }_x000D_
      }_x000D_
    }_x000D_
    if(csa) {_x000D_
      // Another algorithm to check if element is centered and bigger than viewport_x000D_
      if (flag == false) {_x000D_
        var x = rect.left;_x000D_
        var y = rect.top;_x000D_
        // From top left to bottom right_x000D_
        while(x < rect.right || y < rect.bottom) {_x000D_
          if (element.contains(efp(x,y))) {_x000D_
            flag = true;_x000D_
            break;_x000D_
          }_x000D_
          if(x < rect.right) { x++; }_x000D_
          if(y < rect.bottom) { y++; }_x000D_
        }_x000D_
        if (flag == false) {_x000D_
          x = rect.right;_x000D_
          y = rect.top;_x000D_
          // From top right to bottom left_x000D_
          while(x > rect.left || y < rect.bottom) {_x000D_
            if (element.contains(efp(x,y))) {_x000D_
              flag = true;_x000D_
              break;_x000D_
            }_x000D_
            if(x > rect.left) { x--; }_x000D_
            if(y < rect.bottom) { y++; }_x000D_
          }_x000D_
        }_x000D_
      }_x000D_
    }_x000D_
    return flag;_x000D_
}_x000D_
_x000D_
// Check multiple elements visibility_x000D_
document.getElementById('container').addEventListener("scroll", function() {_x000D_
    var elementList = document.getElementsByClassName("element");_x000D_
  var console = document.getElementById('console');_x000D_
    for (var i=0; i < elementList.length; i++) {_x000D_
      // I did not define parent, so it will be element's parent_x000D_
    if (isVisible(elementList[i])) {_x000D_
          console.innerHTML = "Element with id[" + elementList[i].id + "] is visible!";_x000D_
      break;_x000D_
    } else {_x000D_
        console.innerHTML = "Element with id[" + elementList[i].id + "] is hidden!";_x000D_
    }_x000D_
  }_x000D_
});_x000D_
_x000D_
// Dynamically added elements_x000D_
for(var i=4; i <= 6; i++) {_x000D_
  var newElement = document.createElement("div");_x000D_
  newElement.id = "element" + i;_x000D_
  newElement.classList.add("element");_x000D_
  document.getElementById('container').appendChild(newElement);_x000D_
}
_x000D_
#console { background-color: yellow; }_x000D_
#container {_x000D_
  width: 300px;_x000D_
  height: 100px;_x000D_
  background-color: lightblue;_x000D_
  overflow-y: auto;_x000D_
  padding-top: 150px;_x000D_
  margin: 45px;_x000D_
}_x000D_
.element {_x000D_
  margin: 400px;_x000D_
  width: 400px;_x000D_
  height: 320px;_x000D_
  background-color: green;_x000D_
}_x000D_
#element3 {_x000D_
  position: relative;_x000D_
  margin: 40px;_x000D_
  width: 720px;_x000D_
  height: 520px;_x000D_
  background-color: green;_x000D_
}_x000D_
#element3::before {_x000D_
  content: "";_x000D_
  position: absolute;_x000D_
  top: -10px;_x000D_
  left: -10px;_x000D_
  margin: 0px;_x000D_
  width: 740px;_x000D_
  height: 540px;_x000D_
  border: 5px dotted green;_x000D_
  background: transparent;_x000D_
}
_x000D_
<div id="console"></div>_x000D_
<div id="container">_x000D_
    <div id="element1" class="element"></div>_x000D_
    <div id="element2" class="element"></div>_x000D_
    <div id="element3" class="element"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You see, when you are inside the element3 it fails to tell if it's visible or not, because we are only checking if the element is visible from sides or corners.

And this one includes crossSearchAlgorithm which allows you to still return visible when the element is bigger than the viewport:

_x000D_
_x000D_
function isVisible(element, parent, crossSearchAlgorithm) {_x000D_
    var rect = element.getBoundingClientRect(),_x000D_
            prect = (parent != undefined) ? parent.getBoundingClientRect() : element.parentNode.getBoundingClientRect(),_x000D_
        csa = (crossSearchAlgorithm != undefined) ? crossSearchAlgorithm : false,_x000D_
        efp = function (x, y) { return document.elementFromPoint(x, y) };_x000D_
    // Return false if it's not in the viewport_x000D_
    if (rect.right < prect.left || rect.bottom < prect.top || rect.left > prect.right || rect.top > prect.bottom) {_x000D_
        return false;_x000D_
    }_x000D_
    var flag = false;_x000D_
    // Return true if left to right any border pixel reached_x000D_
    for (var x = rect.left; x < rect.right; x++) {_x000D_
        if (element.contains(efp(rect.top, x)) || element.contains(efp(rect.bottom, x))) {_x000D_
        flag = true;_x000D_
        break;_x000D_
      }_x000D_
    }_x000D_
    // Return true if top to bottom any border pixel reached_x000D_
    if (flag == false) {_x000D_
      for (var y = rect.top; y < rect.bottom; y++) {_x000D_
        if (element.contains(efp(rect.left, y)) || element.contains(efp(rect.right, y))) {_x000D_
          flag = true;_x000D_
          break;_x000D_
        }_x000D_
      }_x000D_
    }_x000D_
    if(csa) {_x000D_
      // Another algorithm to check if element is centered and bigger than viewport_x000D_
      if (flag == false) {_x000D_
        var x = rect.left;_x000D_
        var y = rect.top;_x000D_
        // From top left to bottom right_x000D_
        while(x < rect.right || y < rect.bottom) {_x000D_
          if (element.contains(efp(x,y))) {_x000D_
            flag = true;_x000D_
            break;_x000D_
          }_x000D_
          if(x < rect.right) { x++; }_x000D_
          if(y < rect.bottom) { y++; }_x000D_
        }_x000D_
        if (flag == false) {_x000D_
          x = rect.right;_x000D_
          y = rect.top;_x000D_
          // From top right to bottom left_x000D_
          while(x > rect.left || y < rect.bottom) {_x000D_
            if (element.contains(efp(x,y))) {_x000D_
              flag = true;_x000D_
              break;_x000D_
            }_x000D_
            if(x > rect.left) { x--; }_x000D_
            if(y < rect.bottom) { y++; }_x000D_
          }_x000D_
        }_x000D_
      }_x000D_
    }_x000D_
    return flag;_x000D_
}_x000D_
_x000D_
// Check multiple elements visibility_x000D_
document.getElementById('container').addEventListener("scroll", function() {_x000D_
    var elementList = document.getElementsByClassName("element");_x000D_
  var console = document.getElementById('console');_x000D_
    for (var i=0; i < elementList.length; i++) {_x000D_
      // I did not define parent so it will be element's parent_x000D_
    // and it will do crossSearchAlgorithm_x000D_
    if (isVisible(elementList[i],null,true)) {_x000D_
          console.innerHTML = "Element with id[" + elementList[i].id + "] is visible!";_x000D_
      break;_x000D_
    } else {_x000D_
        console.innerHTML = "Element with id[" + elementList[i].id + "] is hidden!";_x000D_
    }_x000D_
  }_x000D_
});_x000D_
// Dynamically added elements_x000D_
for(var i=4; i <= 6; i++) {_x000D_
  var newElement = document.createElement("div");_x000D_
  newElement.id = "element" + i;_x000D_
  newElement.classList.add("element");_x000D_
  document.getElementById('container').appendChild(newElement);_x000D_
}
_x000D_
#console { background-color: yellow; }_x000D_
#container {_x000D_
  width: 300px;_x000D_
  height: 100px;_x000D_
  background-color: lightblue;_x000D_
  overflow-y: auto;_x000D_
  padding-top: 150px;_x000D_
  margin: 45px;_x000D_
}_x000D_
.element {_x000D_
  margin: 400px;_x000D_
  width: 400px;_x000D_
  height: 320px;_x000D_
  background-color: green;_x000D_
}_x000D_
#element3 {_x000D_
  position: relative;_x000D_
  margin: 40px;_x000D_
  width: 720px;_x000D_
  height: 520px;_x000D_
  background-color: green;_x000D_
}_x000D_
#element3::before {_x000D_
  content: "";_x000D_
  position: absolute;_x000D_
  top: -10px;_x000D_
  left: -10px;_x000D_
  margin: 0px;_x000D_
  width: 740px;_x000D_
  height: 540px;_x000D_
  border: 5px dotted green;_x000D_
  background: transparent;_x000D_
}
_x000D_
<div id="console"></div>_x000D_
<div id="container">_x000D_
    <div id="element1" class="element"></div>_x000D_
    <div id="element2" class="element"></div>_x000D_
    <div id="element3" class="element"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

JSFiddle to play with: http://jsfiddle.net/BerkerYuceer/grk5az2c/

This code is made for more precise information if any part of the element is shown in the view or not. For performance options or only vertical slides, do not use this! This code is more effective in drawing cases.

Floating Div Over An Image

Never fails, once I post the question to SO, I get some enlightening "aha" moment and figure it out. The solution:

_x000D_
_x000D_
    .container {_x000D_
       border: 1px solid #DDDDDD;_x000D_
       width: 200px;_x000D_
       height: 200px;_x000D_
       position: relative;_x000D_
    }_x000D_
    .tag {_x000D_
       float: left;_x000D_
       position: absolute;_x000D_
       left: 0px;_x000D_
       top: 0px;_x000D_
       z-index: 1000;_x000D_
       background-color: #92AD40;_x000D_
       padding: 5px;_x000D_
       color: #FFFFFF;_x000D_
       font-weight: bold;_x000D_
    }
_x000D_
<div class="container">_x000D_
       <div class="tag">Featured</div>_x000D_
       <img src="http://www.placehold.it/200x200">_x000D_
</div>
_x000D_
_x000D_
_x000D_

The key is the container has to be positioned relative and the tag positioned absolute.

How do I prevent the error "Index signature of object type implicitly has an 'any' type" when compiling typescript with noImplicitAny flag enabled?

Similar to @Piotr Lewandowski's answer, but within a forEach:

const config: MyConfig = { ... };

Object.keys(config)
  .forEach((key: keyof MyConfig) => {
    if (config[key]) {
      // ...
    }
  });

React router nav bar example

Note The accepted is perfectly fine - but wanted to add a version4 example because they are different enough.

Nav.js

  import React from 'react';
  import { Link } from 'react-router';

  export default class Nav extends React.Component {
    render() {    
      return (
        <nav className="Nav">
          <div className="Nav__container">
            <Link to="/" className="Nav__brand">
              <img src="logo.svg" className="Nav__logo" />
            </Link>

            <div className="Nav__right">
              <ul className="Nav__item-wrapper">
                <li className="Nav__item">
                  <Link className="Nav__link" to="/path1">Link 1</Link>
                </li>
                <li className="Nav__item">
                  <Link className="Nav__link" to="/path2">Link 2</Link>
                </li>
                <li className="Nav__item">
                  <Link className="Nav__link" to="/path3">Link 3</Link>
                </li>
              </ul>
            </div>
          </div>
        </nav>
      );
    }
  }

App.js

  import React from 'react';
  import { Link, Switch, Route } from 'react-router';
  import Nav from './nav';
  import Page1 from './page1';
  import Page2 from './page2';
  import Page3 from './page3';

  export default class App extends React.Component {
    render() {    
      return (
        <div className="App">
          <Router>
            <div>
              <Nav />
              <Switch>
                <Route exactly component={Landing} pattern="/" />
                <Route exactly component={Page1} pattern="/path1" />
                <Route exactly component={Page2} pattern="/path2" />
                <Route exactly component={Page3} pattern="/path3" />
                <Route component={Page404} />
              </Switch>
            </div>
          </Router>
        </div>
      );
    }
  }

Alternatively, if you want a more dynamic nav, you can look at the excellent v4 docs: https://reacttraining.com/react-router/web/example/sidebar

Edit

A few people have asked about a page without the Nav, such as a login page. I typically approach it with a wrapper Route component

  import React from 'react';
  import { Link, Switch, Route } from 'react-router';
  import Nav from './nav';
  import Page1 from './page1';
  import Page2 from './page2';
  import Page3 from './page3';

  const NavRoute = ({exact, path, component: Component}) => (
    <Route exact={exact} path={path} render={(props) => (
      <div>
        <Header/>
        <Component {...props}/>
      </div>
    )}/>
  )

  export default class App extends React.Component {
    render() {    
      return (
        <div className="App">
          <Router>
              <Switch>
                <NavRoute exactly component={Landing} pattern="/" />
                <Route exactly component={Login} pattern="/login" />
                <NavRoute exactly component={Page1} pattern="/path1" />
                <NavRoute exactly component={Page2} pattern="/path2" />
                <NavRoute component={Page404} />
              </Switch>
          </Router>
        </div>
      );
    }
  }

How to create an empty array in Swift?

Initiating an array with a predefined count:

Array(repeating: 0, count: 10)

I often use this for mapping statements where I need a specified number of mock objects. For example,

let myObjects: [MyObject] = Array(repeating: 0, count: 10).map { _ in return MyObject() }

How to restart tomcat 6 in ubuntu

if you are using extracted tomcat then,

startup.sh and shutdown.sh are two script located in TOMCAT/bin/ to start and shutdown tomcat, You could use that

if tomcat is installed then

/etc/init.d/tomcat5.5 start
/etc/init.d/tomcat5.5 stop
/etc/init.d/tomcat5.5 restart

Combination of async function + await + setTimeout

await setTimeout(()=>{}, 200);

Will work if your Node version is 15 and above.

Accessing nested JavaScript objects and arrays by string path

using eval:

var part1name = eval("someObject.part1.name");

wrap to return undefined on error

function path(obj, path) {
    try {
        return eval("obj." + path);
    } catch(e) {
        return undefined;
    }
}

http://jsfiddle.net/shanimal/b3xTw/

Please use common sense and caution when wielding the power of eval. It's a bit like a light saber, if you turn it on there's a 90% chance you'll sever a limb. Its not for everybody.

Difference between framework vs Library vs IDE vs API vs SDK vs Toolkits?

Consider Android Development:

IDE: Eclipse etc..

Library: android.app.Activity library (Class with all code)

API: Interface basically all functions with which we call

SDK: The Android SDK provides you the API libraries and developer tools necessary to build, test, and debug apps for Android (----tools - DDMS,Emulator ----platforms - Android OS versions, ----platform-tools - ADB, ----API docs)

ToolKit: Could be ADT Bundle

Framework: Big library but more of architecture-oriented

How to get the list of all printers in computer

If you need more information than just the name of the printer you can use the System.Management API to query them:

var printerQuery = new ManagementObjectSearcher("SELECT * from Win32_Printer");
foreach (var printer in printerQuery.Get())
{
    var name = printer.GetPropertyValue("Name");
    var status = printer.GetPropertyValue("Status");
    var isDefault = printer.GetPropertyValue("Default");
    var isNetworkPrinter = printer.GetPropertyValue("Network");

    Console.WriteLine("{0} (Status: {1}, Default: {2}, Network: {3}", 
                name, status, isDefault, isNetworkPrinter);
}

Capitalize or change case of an NSString in Objective-C

In case anyone needed the above in swift :

SWIFT 3.0 and above :

this will capitalize your string, make the first letter capital :

viewNoteDateMonth.text  = yourString.capitalized

this will uppercase your string, make all the string upper case :

viewNoteDateMonth.text  = yourString.uppercased()

C# convert int to string with padding zeros?

C# 6.0 style string interpolation

int i = 1;
var str1 = $"{i:D4}";
var str2 = $"{i:0000}";

Python: Fetch first 10 results from a list

check this

 list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

 list[0:10]

Outputs:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Android findViewById() in Custom View

Try this in your constructor

MainActivity maniActivity = (MainActivity)context;
EditText firstName = (EditText) maniActivity.findViewById(R.id.display_name);

Exposing a port on a live Docker container

I had to deal with this same issue and was able to solve it without stopping any of my running containers. This is a solution up-to-date as of February 2016, using Docker 1.9.1. Anyway, this answer is a detailed version of @ricardo-branco's answer, but in more depth for new users.

In my scenario, I wanted to temporarily connect to MySQL running in a container, and since other application containers are linked to it, stopping, reconfiguring, and re-running the database container was a non-starter.

Since I'd like to access the MySQL database externally (from Sequel Pro via SSH tunneling), I'm going to use port 33306 on the host machine. (Not 3306, just in case there is an outer MySQL instance running.)

About an hour of tweaking iptables proved fruitless, even though:

Step by step, here's what I did:

mkdir db-expose-33306
cd db-expose-33306
vim Dockerfile

Edit dockerfile, placing this inside:

# Exposes port 3306 on linked "db" container, to be accessible at host:33306
FROM ubuntu:latest # (Recommended to use the same base as the DB container)

RUN apt-get update && \
    apt-get -y install socat && \
    apt-get clean

USER nobody
EXPOSE 33306

CMD socat -dddd TCP-LISTEN:33306,reuseaddr,fork TCP:db:3306

Then build the image:

docker build -t your-namespace/db-expose-33306 .

Then run it, linking to your running container. (Use -d instead of -rm to keep it in the background until explicitly stopped and removed. I only want it running temporarily in this case.)

docker run -it --rm --name=db-33306 --link the_live_db_container:db -p 33306:33306  your-namespace/db-expose-33306

RegEx for Javascript to allow only alphanumeric

^\s*([0-9a-zA-Z]*)\s*$

or, if you want a minimum of one character:

^\s*([0-9a-zA-Z]+)\s*$

Square brackets indicate a set of characters. ^ is start of input. $ is end of input (or newline, depending on your options). \s is whitespace.

The whitespace before and after is optional.

The parentheses are the grouping operator to allow you to extract the information you want.

EDIT: removed my erroneous use of the \w character set.

"rm -rf" equivalent for Windows?

via Powershell

 Remove-Item -Recurse -Force "TestDirectory"

via Command Prompt

https://stackoverflow.com/a/35731786/439130

Compare two Timestamp in java

if (!mytime.before(fromtime) && !mytime.after(totime))

Unable to connect to SQL Server instance remotely

In addition to configuring the SQL Server Browser service in Services.msc to Automatic, and starting the service, I had to enable TCP/IP in: SQL Server Configuration Manager | SQL Server Network Configuration | Protocols for [INSTANCE NAME] | TCP/IP

enter image description here

How do I restore a dump file from mysqldump?

Run the command to enter into the DB

 # mysql -u root -p 

Enter the password for the user Then Create a New DB

mysql> create database MynewDB;
mysql> exit

And make exit.Afetr that.Run this Command

# mysql -u root -p  MynewDB < MynewDB.sql

Then enter into the db and type

mysql> show databases;
mysql> use MynewDB;
mysql> show tables;
mysql> exit

Thats it ........ Your dump will be restored from one DB to another DB

Or else there is an Alternate way for dump restore

# mysql -u root -p 

Then enter into the db and type

mysql> create database MynewDB;
mysql> show databases;
mysql> use MynewDB;
mysql> source MynewDB.sql;
mysql> show tables;
mysql> exit

SQL join: selecting the last records in a one-to-many relationship

Try this, It will help.

I have used this in my project.

SELECT 
*
FROM
customer c
OUTER APPLY(SELECT top 1 * FROM purchase pi 
WHERE pi.customer_id = c.Id order by pi.Id desc) AS [LastPurchasePrice]

Carriage return in C?

Program prints ab, goes back one character and prints si overwriting the b resulting asi. Carriage return returns the caret to the first column of the current line. That means the ha will be printed over as and the result is hai

How to redirect to another page using AngularJS?

You can use Angular $window:

$window.location.href = '/index.html';

Example usage in a contoller:

(function () {
    'use strict';

    angular
        .module('app')
        .controller('LoginCtrl', LoginCtrl);

    LoginCtrl.$inject = ['$window', 'loginSrv', 'notify'];

    function LoginCtrl($window, loginSrv, notify) {
        /* jshint validthis:true */
        var vm = this;
        vm.validateUser = function () {
             loginSrv.validateLogin(vm.username, vm.password).then(function (data) {          
                if (data.isValidUser) {    
                    $window.location.href = '/index.html';
                }
                else
                    alert('Login incorrect');
            });
        }
    }
})();

Java current machine name and logged in user?

Using user.name is not secure as environment variables can be faked. Method you were using is good, there are similar methods for unix based OS as well

cannot redeclare block scoped variable (typescript)

I got the same problem, and my solution looks like this:

// *./module1/module1.ts*
export module Module1 {
    export class Module1{
        greating(){ return 'hey from Module1'}
    }
}


// *./module2/module2.ts*
import {Module1} from './../module1/module1';

export module Module2{
    export class Module2{
        greating(){
            let m1 = new Module1.Module1()
            return 'hey from Module2 + and from loaded Model1: '+ m1.greating();
        }
    }
}

Now we can use it on the server side:

// *./server.ts*
/// <reference path="./typings/node/node.d.ts"/>
import {Module2} from './module2/module2';

export module Server {
    export class Server{
        greating(){
            let m2 = new Module2.Module2();
            return "hello from server & loaded modules: " + m2.greating();
        }
    }
}

exports.Server = Server;

// ./app.js
var Server = require('./server').Server.Server;
var server = new Server();
console.log(server.greating());

And on the client side too:

// *./public/javscripts/index/index.ts*

import {Module2} from './../../../module2/module2';

document.body.onload = function(){
    let m2 = new Module2.Module2();
    alert(m2.greating());
}

// ./views/index.jade
extends layout

block content
  h1= title
  p Welcome to #{title}
  script(src='main.js')
  //
    the main.js-file created by gulp-task 'browserify' below in the gulpfile.js

And, of course, a gulp-file for all of this:

// *./gulpfile.js*
var gulp = require('gulp'),
    ts = require('gulp-typescript'),
    runSequence = require('run-sequence'),
    browserify = require('gulp-browserify'),
    rename = require('gulp-rename');

gulp.task('default', function(callback) {

    gulp.task('ts1', function() {
        return gulp.src(['./module1/module1.ts'])
            .pipe(ts())
            .pipe(gulp.dest('./module1'))
    });

    gulp.task('ts2', function() {
        return gulp.src(['./module2/module2.ts'])
            .pipe(ts())
            .pipe(gulp.dest('./module2'))
    });

    gulp.task('ts3', function() {
        return gulp.src(['./public/javascripts/index/index.ts'])
            .pipe(ts())
            .pipe(gulp.dest('./public/javascripts/index'))
    });

    gulp.task('browserify', function() {
        return gulp.src('./public/javascripts/index/index.js', { read: false })
            .pipe(browserify({
                insertGlobals: true
            }))
            .pipe(rename('main.js'))
            .pipe(gulp.dest('./public/javascripts/'))
    });

    runSequence('ts1', 'ts2', 'ts3', 'browserify', callback);
})

Updated. Of course, it's not neccessary to compile typescript files separatly. runSequence(['ts1', 'ts2', 'ts3'], 'browserify', callback) works perfect.

How do I find an element position in std::vector?

std::vector has random-access iterators. You can do pointer arithmetic with them. In particular, this my_vec.begin() + my_vec.size() == my_vec.end() always holds. So you could do

const vector<type>::const_iterator pos = std::find_if( firstVector.begin()
                                                     , firstVector.end()
                                                     , some_predicate(parameter) );
if( position != firstVector.end() ) {
    const vector<type>::size_type idx = pos-firstVector.begin();
    doAction( secondVector[idx] );
}

As an alternative, there's always std::numeric_limits<vector<type>::size_type>::max() to be used as an invalid value.

REST API Best practice: How to accept list of parameter values as input

The standard way to pass a list of values as URL parameters is to repeat them:

http://our.api.com/Product?id=101404&id=7267261

Most server code will interpret this as a list of values, although many have single value simplifications so you may have to go looking.

Delimited values are also okay.

If you are needing to send JSON to the server, I don't like seeing it in in the URL (which is a different format). In particular, URLs have a size limitation (in practice if not in theory).

The way I have seen some do a complicated query RESTfully is in two steps:

  1. POST your query requirements, receiving back an ID (essentially creating a search criteria resource)
  2. GET the search, referencing the above ID
  3. optionally DELETE the query requirements if needed, but note that they requirements are available for reuse.

PHP cURL custom headers

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'X-Apple-Tz: 0',
    'X-Apple-Store-Front: 143444,12'
));

http://www.php.net/manual/en/function.curl-setopt.php

macOS on VMware doesn't recognize iOS device

I met the same problem. I found the solution in the solution from kb.vmware.com.
It works for me by adding

usb.quirks.device0 = "0xvid:0xpid skip-refresh"

Detail as below:


To add quirks:
  1. Shut down the virtual machine and quit Workstation/Fusion.

    Caution: Do not skip this step.
     
  2. Open the vmware.log file within the virtual machine bundle. For more information, see Locating a virtual machine bundle in VMware Workstation/Fusion (1007599).
  3. In the Filter box at the top of the Console window, enter the name of the device manufacturer.

    For example, if you enter the name Apple, you see a line that looks similar to:

    vmx | USB: Found device [name:Apple\ IR\ Receiver vid:05ac pid:8240 path:13/7/2 speed:full family:hid]



    The line has the name of the USB device and its vid and pid information. Make a note of the vid and pid values.
     

  4. Open the .vmx file using a text editor. For more information, see Editing the .vmx file for your Workstation/Fusion virtual machine (1014782).
  5. Add this line to the .vmx file, replacing vid and pid with the values noted in Step 2, each prefixed by the number 0 and the letter x .

    usb.quirks.device0 = "0xvid:0xpid skip-reset"

    For example, for the Apple device found in step 2, this line is:

    usb.quirks.device0 = "0x05ac:0x8240 skip-reset"
     

  6. Save the .vmx file.
  7. Re-open Workstation/Fusion. The edited .vmx file is reloaded with the changes.
  8. Start the virtual machine, and connect the device.
  9. If the issue is not resolved, replace the quirks line added in Step 4 with one of these lines, in the order provided, and repeat Steps 5 to 8:
usb.quirks.device0 = "0xvid:0xpid skip-refresh"
usb.quirks.device0 = "0xvid:0xpid skip-setconfig"
usb.quirks.device0 = "0xvid:0xpid skip-reset, skip-refresh, skip-setconfig"

Notes:

  • Use one of these lines at a time. If one does not work, replace it with another one in the list. Do not add more than one of these in the .vmx file at a time.
  • The last line uses all three quirks in combination. Use this only if the other three lines do not work.

Refer this to see in detail.

get parent's view from a layout

This also works:

this.getCurrentFocus()

It gets the view so I can use it.

How to create many labels and textboxes dynamically depending on the value of an integer variable?

Here is a simple example that should let you keep going add somethink that would act as a placeholder to your winform can be TableLayoutPanel

and then just add controls to it

   for ( int i = 0; i < COUNT; i++ ) {


    Label lblTitle = new Label();
    lblTitle.Text = i+"Your Text";
    youlayOut.Controls.Add( lblTitle, 0, i );

    TextBox txtValue = new TextBox();
    youlayOut.Controls.Add( txtValue, 2, i );
}

ASP.net using a form to insert data into an sql server table

Simple, make a simple asp page with the designer (just for the beginning) Lets say the body is something like this:

<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <br />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </div>
    <p>
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </p>
    </form>
</body>

Great, now every asp object IS an object. So you can access it in the asp's CS code. The asp's CS code is triggered by events (mostly). The class will probably inherit from System.Web.UI.Page

If you go to the cs file of the asp page, you'll see a protected void Page_Load(object sender, EventArgs e) ... That's the load event, you can use that to populate data into your objects when the page loads.

Now, go to the button in your designer (Button1) and look at its properties, you can design it, or add events from there. Just change to the events view, and create a method for the event.

The button is a web control Button Add a Click event to the button call it Button1Click:

void Button1Click(Object sender,EventArgs e) { }

Now when you click the button, this method will be called. Because ASP is object oriented, you can think of the page as the actual class, and the objects will hold the actual current data.

So if for example you want to access the text in TextBox1 you just need to call that object in the C# code:

String firstBox = TextBox1.Text;

In the same way you can populate the objects when event occur.

Now that you have the data the user posted in the textboxes , you can use regular C# SQL connections to add the data to your database.

Ruby: Easiest Way to Filter Hash Keys?

As for bonus question:

  1. If you have output from #select method like this (list of 2-element arrays):

    [[:choice1, "Oh look, another one"], [:choice2, "Even more strings"], [:choice3, "But wait"]]
    

    then simply take this result and execute:

    filtered_params.join("\t")
    # or if you want only values instead of pairs key-value
    filtered_params.map(&:last).join("\t")
    
  2. If you have output from #delete_if method like this (hash):

    {:choice1=>"Oh look, another one", :choice2=>"Even more strings", :choice3=>"But wait"}
    

    then:

    filtered_params.to_a.join("\t")
    # or
    filtered_params.values.join("\t")
    

Reactjs - setting inline styles correctly

It's not immediately obvious from the documentation why the following does not work:

<span style={font-size: 1.7} class="glyphicon glyphicon-remove-sign"></span>

But when doing it entirely inline:

  • You need double curly brackets
  • You don't need to put your values in quotes
  • React will add some default if you omit "em"
  • Remember to camelCase style names that have dashes in CSS - e.g. font-size becomes fontSize:
  • class is className

The correct way looks like this:

<span style={{fontSize: 1.7 + "em"}} className="glyphicon glyphicon-remove-sign"></span>

Is it necessary to assign a string to a variable before comparing it to another?

You can also use the NSString class methods which will also create an autoreleased instance and have more options like string formatting:

NSString *myString = [NSString stringWithString:@"abc"];
NSString *myString = [NSString stringWithFormat:@"abc %d efg", 42];

Removing input background colour for Chrome autocomplete?

For those who are using Compass:

@each $prefix in -webkit, -moz {
    @include with-prefix($prefix) {
        @each $element in input, textarea, select {
            #{$element}:#{$prefix}-autofill {
                @include single-box-shadow(0, 0, 0, 1000px, $white, inset);
            }
        }
    }
}

Bootstrap throws Uncaught Error: Bootstrap's JavaScript requires jQuery

You have provided wrong order for JAVASCRIPT and BOOTSTRAP

by convention bootstrap must follow jquery file definition

<!-- JQuery Core JavaScript -->
<script src="lib/js/jquery.min.js"></script>
<script src="lib/js/jquery-ui.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="lib/js/bootstrap.min.js"></script>

Colorized grep -- viewing the entire file with highlighted matches

I'd like to recommend ack -- better than grep, a power search tool for programmers.

$ ack --color --passthru --pager="${PAGER:-less -R}" pattern files
$ ack --color --passthru pattern files | less -R
$ export ACK_PAGER_COLOR="${PAGER:-less -R}"
$ ack --passthru pattern files

I love it because it defaults to recursive searching of directories (and does so much smarter than grep -r), supports full Perl regular expressions (rather than the POSIXish regex(3)), and has a much nicer context display when searching many files.

How to open SharePoint files in Chrome/Firefox

You can use web-based protocol handlers for the links as per https://sharepoint.stackexchange.com/questions/70178/how-does-sharepoint-2013-enable-editing-of-documents-for-chrome-and-fire-fox

Basically, just prepend ms-word:ofe|u| to the links to your SharePoint hosted Word documents.

Can a foreign key be NULL and/or duplicate?

Here's an example using Oracle syntax:
First let's create a table COUNTRY

CREATE TABLE TBL_COUNTRY ( COUNTRY_ID VARCHAR2 (50) NOT NULL ) ;
ALTER TABLE TBL_COUNTRY ADD CONSTRAINT COUNTRY_PK PRIMARY KEY ( COUNTRY_ID ) ;

Create the table PROVINCE

CREATE TABLE TBL_PROVINCE(
PROVINCE_ID VARCHAR2 (50) NOT NULL ,
COUNTRY_ID  VARCHAR2 (50)
);
ALTER TABLE TBL_PROVINCE ADD CONSTRAINT PROVINCE_PK PRIMARY KEY ( PROVINCE_ID ) ;
ALTER TABLE TBL_PROVINCE ADD CONSTRAINT PROVINCE_COUNTRY_FK FOREIGN KEY ( COUNTRY_ID ) REFERENCES TBL_COUNTRY ( COUNTRY_ID ) ;

This runs perfectly fine in Oracle. Notice the COUNTRY_ID foreign key in the second table doesn't have "NOT NULL".

Now to insert a row into the PROVINCE table, it's sufficient to only specify the PROVINCE_ID. However, if you chose to specify a COUNTRY_ID as well, it must exist already in the COUNTRY table.

event.preventDefault() vs. return false

return false from within a jQuery event handler is effectively the same as calling both e.preventDefault and e.stopPropagation on the passed jQuery.Event object.

e.preventDefault() will prevent the default event from occuring, e.stopPropagation() will prevent the event from bubbling up and return false will do both. Note that this behaviour differs from normal (non-jQuery) event handlers, in which, notably, return false does not stop the event from bubbling up.

Source: John Resig

Any benefit to using event.preventDefault() over "return false" to cancel out an href click?

How does the enhanced for statement work for arrays, and how to get an iterator for an array?

I'm a bit late to the game, but I noticed some key points that were left out, particularly regarding Java 8 and the efficiency of Arrays.asList.

1. How does the for-each loop work?

As Ciro Santilli ???? ??? ??? pointed out, there's a handy utility for examining bytecode that ships with the JDK: javap. Using that, we can determine that the following two code snippets produce identical bytecode as of Java 8u74:

For-each loop:

int[] arr = {1, 2, 3};
for (int n : arr) {
    System.out.println(n);
}

For loop:

int[] arr = {1, 2, 3};

{  // These extra braces are to limit scope; they do not affect the bytecode
    int[] iter = arr;
    int length = iter.length;
    for (int i = 0; i < length; i++) {
        int n = iter[i];
        System.out.println(n);
    }
}

2. How do I get an iterator for an array in Java?

While this doesn't work for primitives, it should be noted that converting an array to a List with Arrays.asList does not impact performance in any significant way. The impact on both memory and performance is nearly immeasurable.

Arrays.asList does not use a normal List implementation that is readily accessible as a class. It uses java.util.Arrays.ArrayList, which is not the same as java.util.ArrayList. It is a very thin wrapper around an array and cannot be resized. Looking at the source code for java.util.Arrays.ArrayList, we can see that it's designed to be functionally equivalent to an array. There is almost no overhead. Note that I have omitted all but the most relevant code and added my own comments.

public class Arrays {
    public static <T> List<T> asList(T... a) {
        return new ArrayList<>(a);
    }

    private static class ArrayList<E> extends AbstractList<E> implements RandomAccess, java.io.Serializable {
        private final E[] a;

        ArrayList(E[] array) {
            a = Objects.requireNonNull(array);
        }

        @Override
        public int size() {
            return a.length;
        }

        @Override
        public E get(int index) {
            return a[index];
        }

        @Override
        public E set(int index, E element) {
            E oldValue = a[index];
            a[index] = element;
            return oldValue;
        }
    }
}

The iterator is at java.util.AbstractList.Itr. As far as iterators go, it's very simple; it just calls get() until size() is reached, much like a manual for loop would do. It's the simplest and usually most efficient implementation of an Iterator for an array.

Again, Arrays.asList does not create a java.util.ArrayList. It's much more lightweight and suitable for obtaining an iterator with negligible overhead.

Primitive arrays

As others have noted, Arrays.asList can't be used on primitive arrays. Java 8 introduces several new technologies for dealing with collections of data, several of which could be used to extract simple and relatively efficient iterators from arrays. Note that if you use generics, you're always going to have the boxing-unboxing problem: you'll need to convert from int to Integer and then back to int. While boxing/unboxing is usually negligible, it does have an O(1) performance impact in this case and could lead to problems with very large arrays or on computers with very limited resources (i.e., SoC).

My personal favorite for any sort of array casting/boxing operation in Java 8 is the new stream API. For example:

int[] arr = {1, 2, 3};
Iterator<Integer> iterator = Arrays.stream(arr).mapToObj(Integer::valueOf).iterator();

The streams API also offers constructs for avoiding the boxing issue in the first place, but this requires abandoning iterators in favor of streams. There are dedicated stream types for int, long, and double (IntStream, LongStream, and DoubleStream, respectively).

int[] arr = {1, 2, 3};
IntStream stream = Arrays.stream(arr);
stream.forEach(System.out::println);

Interestingly, Java 8 also adds java.util.PrimitiveIterator. This provides the best of both worlds: compatibility with Iterator<T> via boxing along with methods to avoid boxing. PrimitiveIterator has three built-in interfaces that extend it: OfInt, OfLong, and OfDouble. All three will box if next() is called but can also return primitives via methods such as nextInt(). Newer code designed for Java 8 should avoid using next() unless boxing is absolutely necessary.

int[] arr = {1, 2, 3};
PrimitiveIterator.OfInt iterator = Arrays.stream(arr);

// You can use it as an Iterator<Integer> without casting:
Iterator<Integer> example = iterator;

// You can obtain primitives while iterating without ever boxing/unboxing:
while (iterator.hasNext()) {
    // Would result in boxing + unboxing:
    //int n = iterator.next();

    // No boxing/unboxing:
    int n = iterator.nextInt();

    System.out.println(n);
}

If you're not yet on Java 8, sadly your simplest option is a lot less concise and is almost certainly going to involve boxing:

final int[] arr = {1, 2, 3};
Iterator<Integer> iterator = new Iterator<Integer>() {
    int i = 0;

    @Override
    public boolean hasNext() {
        return i < arr.length;
    }

    @Override
    public Integer next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }

        return arr[i++];
    }
};

Or if you want to create something more reusable:

public final class IntIterator implements Iterator<Integer> {
    private final int[] arr;
    private int i = 0;

    public IntIterator(int[] arr) {
        this.arr = arr;
    }

    @Override
    public boolean hasNext() {
        return i < arr.length;
    }

    @Override
    public Integer next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }

        return arr[i++];
    }
}

You could get around the boxing issue here by adding your own methods for obtaining primitives, but it would only work with your own internal code.

3. Is the array converted to a list to get the iterator?

No, it is not. However, that doesn't mean wrapping it in a list is going to give you worse performance, provided you use something lightweight such as Arrays.asList.

How do you compare two version Strings in Java?

I liked the idea from @Peter Lawrey, And i extended it to further limits :

    /**
    * Normalize string array, 
    * Appends zeros if string from the array
    * has length smaller than the maxLen.
    **/
    private String normalize(String[] split, int maxLen){
        StringBuilder sb = new StringBuilder("");
        for(String s : split) {
            for(int i = 0; i<maxLen-s.length(); i++) sb.append('0');
            sb.append(s);
        }
        return sb.toString();
    }

    /**
    * Removes trailing zeros of the form '.00.0...00'
    * (and does not remove zeros from, say, '4.1.100')
    **/
    public String removeTrailingZeros(String s){
        int i = s.length()-1;
        int k = s.length()-1;
        while(i >= 0 && (s.charAt(i) == '.' || s.charAt(i) == '0')){
          if(s.charAt(i) == '.') k = i-1;
          i--;  
        } 
        return s.substring(0,k+1);
    }

    /**
    * Compares two versions(works for alphabets too),
    * Returns 1 if v1 > v2, returns 0 if v1 == v2,
    * and returns -1 if v1 < v2.
    **/
    public int compareVersion(String v1, String v2) {

        // Uncomment below two lines if for you, say, 4.1.0 is equal to 4.1
        // v1 = removeTrailingZeros(v1);
        // v2 = removeTrailingZeros(v2);

        String[] splitv1 = v1.split("\\.");
        String[] splitv2 = v2.split("\\.");
        int maxLen = 0;
        for(String str : splitv1) maxLen = Math.max(maxLen, str.length());
        for(String str : splitv2) maxLen = Math.max(maxLen, str.length());
        int cmp = normalize(splitv1, maxLen).compareTo(normalize(splitv2, maxLen));
        return cmp > 0 ? 1 : (cmp < 0 ? -1 : 0);
    }

Hope it helps someone. It passed all test cases in interviewbit and leetcode (need to uncomment two lines in compareVersion function).

Easily tested !

JPA & Criteria API - Select only specific columns

cq.select(cb.construct(entityClazz.class, root.get("ID"), root.get("VERSION")));  // HERE IS NO ERROR

https://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/Criteria#Constructors

Getting permission denied (public key) on gitlab

Try to use git clone XXX if you'd see LibreSSL SSL_connect: SSL_ERROR_SYSCALL in connection to XXX it might be the case that just updated your OS, installed some dev tools, e.g. Xcode with its tools on Mac, VPN, Antivirus (especially Kaspersky Antivirus) or something between/other.

In my case simply restarting my OS (macOS Catalina) fixed this issue.

How do I record audio on iPhone with AVAudioRecorder?

As per the above answers, I made some changes and I got the correct output.

Step 1: Under "inf.plist" add the Microphone usage permissions ==>

  <key>NSMicrophoneUsageDescription</key>
  <string>${PRODUCT_NAME} Microphone Usage</string>

Step 2:

  1. Save record audio file into Local Document Directory

  2. Play/Stop recording

  3. Get the Duration of Saved audio file

Here is the source code. Please have a look at once and use it.

ViewController.h

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface ViewController : UIViewController{
AVAudioPlayer *audioPlayer;
AVAudioRecorder *audioRecorder;
}

-(IBAction) startRecording;
-(IBAction) stopRecording;
-(IBAction) playRecording;
-(IBAction) stopPlaying;

@end

ViewController.m

#import "ViewController.h"
@interface ViewController () <AVAudioRecorderDelegate, AVAudioPlayerDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

-(IBAction) startRecording{
// Setup audio session
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *err = nil;
[audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
if(err)
{
    NSLog(@"audioSession: %@ %ld %@", [err domain], (long)[err code], [[err userInfo] description]);
    return;
}
[audioSession setActive:YES error:&err];
err = nil;
if(err)
{
    NSLog(@"audioSession: %@ %ld %@", [err domain], (long)[err code], [[err userInfo] description]);
    return;
}
AVAudioSessionRecordPermission permissionStatus = [audioSession recordPermission];
switch (permissionStatus) {
    case AVAudioSessionRecordPermissionUndetermined:{
        [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
            // CALL YOUR METHOD HERE - as this assumes being called only once from user interacting with permission alert!
            if (granted) {
                // Microphone enabled code
                NSLog(@"Mic permission granted.  Call method for granted stuff.");
                [self startRecordingAudioSound];
            }
            else {
                // Microphone disabled code
                NSLog(@"Mic permission indeterminate. Call method for indeterminate stuff.");
                //        UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)
            }
        }];
        break;
    }
    case AVAudioSessionRecordPermissionDenied:
        // direct to settings...
        NSLog(@"Mic permission denied. Call method for denied stuff.");

        break;
    case AVAudioSessionRecordPermissionGranted:
        // mic access ok...
        NSLog(@"Mic permission granted.  Call method for granted stuff.");
        [self startRecordingAudioSound];
        break;
    default:
        // this should not happen.. maybe throw an exception.
        break;
}
}

#pragma mark - Audio Recording
- (BOOL)startRecordingAudioSound{
NSError *error = nil;
NSMutableDictionary *recorderSettings = [[NSMutableDictionary alloc] init];
[recorderSettings setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
[recorderSettings setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recorderSettings setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
[recorderSettings setValue :[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
[recorderSettings setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
[recorderSettings setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];

// Create a new audio file
NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath_ = [searchPaths objectAtIndex: 0];
NSString *pathToSave = [documentPath_ stringByAppendingPathComponent:[self dateString]];
NSLog(@"the path is %@",pathToSave);

// File URL
NSURL *url = [NSURL fileURLWithPath:pathToSave];//FILEPATH];

//Save recording path to preferences
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setURL:url forKey:@"Test1"];
[prefs synchronize];

audioRecorder = [[AVAudioRecorder alloc] initWithURL:url settings:recorderSettings error:&error];
if (!audioRecorder)
{
    NSLog(@"Error establishing recorder: %@", error.localizedFailureReason);
    return NO;
}

// Initialize degate, metering, etc.
audioRecorder.delegate = self;
audioRecorder.meteringEnabled = YES;
//self.title = @"0:00";

if (![audioRecorder prepareToRecord])
{
    NSLog(@"Error: Prepare to record failed");
    //[self say:@"Error while preparing recording"];
    return NO;
}

if (![audioRecorder record])
{
    NSLog(@"Error: Record failed");
    //  [self say:@"Error while attempting to record audio"];
    return NO;
}
NSLog(@"Recroding Started");
return YES;
}

#pragma mark - AVAudioRecorderDelegate
- (void) audioRecorderDidFinishRecording:(AVAudioRecorder *)avrecorder successfully:(BOOL)flag{
NSLog (@"audioRecorderDidFinishRecording:successfully:");
}

#pragma mark - AVAudioPlayerDelegate
- (void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
NSLog (@"audioPlayerDidFinishPlaying:successfully:");
}

- (NSString *) dateString {
// return a formatted string for a file name
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"ddMMMYY_hhmmssa";
return [[formatter stringFromDate:[NSDate date]]stringByAppendingString:@".aif"];
}

-(IBAction) stopRecording{
NSLog(@"stopRecording");
[audioRecorder stop];
NSLog(@"stopped");
}

-(IBAction) playRecording{
//Load recording path from preferences
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSURL *temporaryRecFile = [prefs URLForKey:@"Test1"];

//Get Duration of Audio File
AVURLAsset* audioAsset = [AVURLAsset URLAssetWithURL:temporaryRecFile options:nil];
CMTime audioDuration = audioAsset.duration;
float audioDurationSeconds = CMTimeGetSeconds(audioDuration);
NSLog(@"Duration Of Audio: %f", audioDurationSeconds);

audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:temporaryRecFile error:nil];
audioPlayer.delegate = self;
[audioPlayer setNumberOfLoops:0];
audioPlayer.volume = 1;
[audioPlayer prepareToPlay];
[audioPlayer play];
NSLog(@"playing");
}

-(IBAction) stopPlaying{
NSLog(@"stopPlaying");
[audioPlayer stop];
NSLog(@"stopped");
 }

 @end

How to pass complex object to ASP.NET WebApi GET from jQuery ajax call?

After finding this StackOverflow question/answer

Complex type is getting null in a ApiController parameter

the [FromBody] attribute on the controller method needs to be [FromUri] since a GET does not have a body. After this change the "filter" complex object is passed correctly.

Get JSONArray without array name?

I've assumed a named JSONArray is a JSONObject and accessed the data from the server to populate an Android GridView. For what it is worth my method is:

private String[] fillTable( JSONObject jsonObject ) {
   String[] dummyData = new String[] {"1", "2", "3", "4", "5", "6", "7","1", "2", "3", "4", "5", "6", "7","1", "2", "3", "4", "5", "6", "7", };
  if( jsonObject != null ) {
      ArrayList<String> data = new ArrayList<String>();
      try {
          // jsonArray looks like { "everything" : [{}, {},] }
          JSONArray jsonArray = jsonObject.getJSONArray( "everything" );
          int number = jsonArray.length(); //How many rows have got from the database?
          Log.i( Constants.INFORMATION, "Number of ows returned:  " + Integer.toString( number ) );
                  // Array elements look like this
          //{"success":1,"error":0,"name":"English One","owner":"Tutor","description":"Initial Alert","posted":"2013-08-09 15:35:40"}
          for( int element = 0; element < number; element++ ) { //visit each element
             JSONObject jsonObject_local = jsonArray.getJSONObject( element );
             //  Overkill on the error/success checking
             Log.e("JSON SUCCESS", Integer.toString( jsonObject_local.getInt(Constants.KEY_SUCCESS) ) );
             Log.e("JSON ERROR", Integer.toString( jsonObject_local.getInt(Constants.KEY_ERROR) ) );
                if ( jsonObject_local.getInt( Constants.KEY_SUCCESS) == Constants.JSON_SUCCESS ) {
                   String name = jsonObject_local.getString( Constants.KEY_NAME );
                   data.add( name );
                   String owner = jsonObject_local.getString( Constants.KEY_OWNER );
                   data.add( owner );
                   String description = jsonObject_local.getString( Constants.KEY_DESCRIPTION );
                   Log.i( "DESCRIPTION", description );
                   data.add( description ); 
                   String date = jsonObject_local.getString( Constants.KEY_DATE );
                   data.add( date );
                }
                else {
                    for( int i = 0; i < 4; i++ ) {
                        data.add( "ERROR" );
                    }
                }
          }
  }  //JSON object is null
  catch ( JSONException jsone) {
      Log.e( "JSON EXCEPTION", jsone.getMessage() );
  }
      dummyData = data.toArray( dummyData );
  }
  return dummyData;

}

Python: Get the first character of the first string in a list?

Get the first character of a bare python string:

>>> mystring = "hello"
>>> print(mystring[0])
h
>>> print(mystring[:1])
h
>>> print(mystring[3])
l
>>> print(mystring[-1])
o
>>> print(mystring[2:3])
l
>>> print(mystring[2:4])
ll

Get the first character from a string in the first position of a python list:

>>> myarray = []
>>> myarray.append("blah")
>>> myarray[0][:1]
'b'
>>> myarray[0][-1]
'h'
>>> myarray[0][1:3]
'la'

Many people get tripped up here because they are mixing up operators of Python list objects and operators of Numpy ndarray objects:

Numpy operations are very different than python list operations.

Wrap your head around the two conflicting worlds of Python's "list slicing, indexing, subsetting" and then Numpy's "masking, slicing, subsetting, indexing, then numpy's enhanced fancy indexing".

These two videos cleared things up for me:

"Losing your Loops, Fast Numerical Computing with NumPy" by PyCon 2015: https://youtu.be/EEUXKG97YRw?t=22m22s

"NumPy Beginner | SciPy 2016 Tutorial" by Alexandre Chabot LeClerc: https://youtu.be/gtejJ3RCddE?t=1h24m54s

Python: Removing list element while iterating over list

Why not rewrite it to be

for element in somelist: 
   do_action(element)  

if check(element): 
    remove_element_from_list

See this question for how to remove from the list, though it looks like you've already seen that Remove items from a list while iterating

Another option is to do this if you really want to keep this the same

newlist = [] 
for element in somelist: 
   do_action(element)  

   if not check(element): 
      newlst.append(element)

calling a java servlet from javascript

The code here will use AJAX to print text to an HTML5 document dynamically (Ajax code is similar to book Internet & WWW (Deitel)):

Javascript code:

var asyncRequest;    
function start(){
    try
    {
        asyncRequest = new XMLHttpRequest();
        asyncRequest.addEventListener("readystatechange", stateChange, false);
        asyncRequest.open('GET', '/Test', true);    //   /Test is url to Servlet!
        asyncRequest.send(null);
    }
    catch(exception)
   {
    alert("Request failed");
   }
}

function stateChange(){
if(asyncRequest.readyState == 4 && asyncRequest.status == 200)
    {
    var text = document.getElementById("text");         //  text is an id of a 
    text.innerHTML = asyncRequest.responseText;         //  div in HTML document
    }
}

window.addEventListener("load", start(), false);

Servlet java code:

public class Test extends HttpServlet{
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws IOException{
        resp.setContentType("text/plain");
        resp.getWriter().println("Servlet wrote this! (Test.java)");
    }
}

HTML document

 <div id = "text"></div>

EDIT

I wrote answer above when I was new with web programming. I let it stand, but the javascript part should definitely be in jQuery instead, it is 10 times easier than raw javascript.

How to make java delay for a few seconds?

A couple problems, you aren't delaying by much (.sleep is milliseconds, not seconds), and you're attempting to print in your catch statement. Your code should look more like:

if (i==1) {
    try {
        System.out.println("Scanning...");
        Thread.sleep(1000); // 1 second
    } catch (InterruptedException ex) {
        // handle error
    }
}

How to change the remote a branch is tracking?

Another option to have a lot of control over what's happening is to edit your configurations by hand:

git config --edit

or the shorthand

git config -e

Then edit the file at will, save and your modifications will be applied.

Most efficient method to groupby on an array of objects

just simple if you use lodash library

let temp = []
  _.map(yourCollectionData, (row) => {
    let index = _.findIndex(temp, { 'Phase': row.Phase })
    if (index > -1) {
      temp[index].Value += row.Value 
    } else {
      temp.push(row)
    }
  })

'Java' is not recognized as an internal or external command

If you have set the environment variables (JAVA_HOME and PATH) under user variables, command prompt (run as administrator) will not identify java. For that you need to set environment variables under system variables.

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

See Wikipedia article on this topic. Sample Manacher's Algorithm Java implementation for linear O(n) solution from the article below:

import java.util.Arrays; public class ManachersAlgorithm { public static String findLongestPalindrome(String s) { if (s==null || s.length()==0) return "";

char[] s2 = addBoundaries(s.toCharArray());
int[] p = new int[s2.length]; 
int c = 0, r = 0; // Here the first element in s2 has been processed.
int m = 0, n = 0; // The walking indices to compare if two elements are the same
for (int i = 1; i<s2.length; i++) {
  if (i>r) {
    p[i] = 0; m = i-1; n = i+1;
  } else {
    int i2 = c*2-i;
    if (p[i2]<(r-i)) {
      p[i] = p[i2];
      m = -1; // This signals bypassing the while loop below. 
    } else {
      p[i] = r-i;
      n = r+1; m = i*2-n;
    }
  }
  while (m>=0 && n<s2.length && s2[m]==s2[n]) {
    p[i]++; m--; n++;
  }
  if ((i+p[i])>r) {
    c = i; r = i+p[i];
  }
}
int len = 0; c = 0;
for (int i = 1; i<s2.length; i++) {
  if (len<p[i]) {
    len = p[i]; c = i;
  }
}
char[] ss = Arrays.copyOfRange(s2, c-len, c+len+1);
return String.valueOf(removeBoundaries(ss));   }
private static char[] addBoundaries(char[] cs) {
if (cs==null || cs.length==0)
  return "||".toCharArray();

char[] cs2 = new char[cs.length*2+1];
for (int i = 0; i<(cs2.length-1); i = i+2) {
  cs2[i] = '|';
  cs2[i+1] = cs[i/2];
}
cs2[cs2.length-1] = '|';
return cs2;   }
private static char[] removeBoundaries(char[] cs) {
if (cs==null || cs.length<3)
  return "".toCharArray();

char[] cs2 = new char[(cs.length-1)/2];
for (int i = 0; i<cs2.length; i++) {
  cs2[i] = cs[i*2+1];
}
return cs2;   }     }

How to edit default dark theme for Visual Studio Code?

In VS code 'User Settings', you can edit visible colours using the following tags(this is a sample and there are much more tags),

"workbench.colorCustomizations": {
    "list.inactiveSelectionBackground": "#C5DEF0",
    "sideBar.background": "#F8F6F6",
    "sideBar.foreground": "#000000",
    "editor.background": "#FFFFFF",
    "editor.foreground": "#000000",
    "sideBarSectionHeader.background": "#CAC9C9",
    "sideBarSectionHeader.foreground": "#000000",
    "activityBar.border": "#FFFFFF",
    "statusBar.background": "#102F97",
    "scrollbarSlider.activeBackground": "#77D4CB",
    "scrollbarSlider.hoverBackground": "#8CE6DA",
    "badge.background": "#81CA91"}

If you want to edit some C++ color tokens, use the following tag,

"editor.tokenColorCustomizations": {
    "numbers": "#2247EB",
    "comments": "#6D929C",
    "functions": "#0D7C28"
}

Calculating Pearson correlation and significance in Python

Hmm, many of these responses have long and hard to read code...

I'd suggest using numpy with its nifty features when working with arrays:

import numpy as np
def pcc(X, Y):
   ''' Compute Pearson Correlation Coefficient. '''
   # Normalise X and Y
   X -= X.mean(0)
   Y -= Y.mean(0)
   # Standardise X and Y
   X /= X.std(0)
   Y /= Y.std(0)
   # Compute mean product
   return np.mean(X*Y)

# Using it on a random example
from random import random
X = np.array([random() for x in xrange(100)])
Y = np.array([random() for x in xrange(100)])
pcc(X, Y)

How to check if an array is empty?

Your test:

if (numberSet.length < 2) {
    return 0;
}

should be done before you allocate an array of that length in the below statement:

int[] differenceArray = new int[numberSet.length-1];

else you are already creating an array of size -1, when the numberSet.length = 0. That is quite odd. So, move your if statement as the first statement in your method.

How do you auto format code in Visual Studio?

On mac : Shift + Option + F

On ubuntu : Ctrl + Shift + I

How to join components of a path when you are constructing a URL in Python

How about this: It is Somewhat Efficient & Somewhat Simple. Only need to join '2' parts of url path:

def UrlJoin(a , b):
    a, b = a.strip(), b.strip()
    a = a if a.endswith('/') else a + '/'
    b = b if not b.startswith('/') else b[1:]
    return a + b

OR: More Conventional, but Not as efficient if joining only 2 url parts of a path.

def UrlJoin(*parts):
    return '/'.join([p.strip().strip('/') for p in parts])

Test Cases:

>>> UrlJoin('https://example.com/', '/TestURL_1')
'https://example.com/TestURL_1'

>>> UrlJoin('https://example.com', 'TestURL_2')
'https://example.com/TestURL_2'

Note: I may be splitting hairs here, but it is at least good practice and potentially more readable.

Pointers in JavaScript?

You refer to 'x' from window object

var x = 0;

function a(key, ref) {
    ref = ref || window;  // object reference - default window
    ref[key]++;
}

a('x');                   // string
alert(x);

How to delete a record in Django models?

If you want to delete one item

wishlist = Wishlist.objects.get(id = 20)
wishlist.delete()

If you want to delete all items in Wishlist for example

Wishlist.objects.all().delete()

Which Architecture patterns are used on Android?

Binder uses "Observer Pattern" for Death Recipient notifications.

How to hide underbar in EditText

If you want this to affect all instances of EditText and any class that inherits from it, then you should set in your theme the value for the attribute, editTextBackground.

  <item name="android:editTextBackground">@drawable/bg_no_underline</item>

An example of the drawable I use is:

<inset xmlns:android="http://schemas.android.com/apk/res/android"
     android:insetLeft="@dimen/abc_edit_text_inset_horizontal_material"
     android:insetRight="@dimen/abc_edit_text_inset_horizontal_material"
     android:insetTop="@dimen/abc_edit_text_inset_top_material"
     android:insetBottom="@dimen/abc_edit_text_inset_bottom_material">
    <selector>
      <item android:drawable="@android:color/transparent"/>
    </selector>
</inset>

This is slightly modified version of what the default material design implementation is.

When applied it will make all your EditText remove the underline throughout the app, and you don't have to apply the style to each and every one manually.

CSV parsing in Java - working example..?

My approach would not be to start by writing your own API. Life's too short, and there are more pressing problems to solve. In this situation, I typically:

  • Find a library that appears to do what I want. If one doesn't exist, then implement it.
  • If a library does exist, but I'm not sure it'll be suitable for my needs, write a thin adapter API around it, so I can control how it's called. The adapter API expresses the API I need, and it maps those calls to the underlying API.
  • If the library doesn't turn out to be suitable, I can swap another one in underneath the adapter API (whether it's another open source one or something I write myself) with a minimum of effort, without affecting the callers.

Start with something someone has already written. Odds are, it'll do what you want. You can always write your own later, if necessary. OpenCSV is as good a starting point as any.

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions

You do not need to use ORDER BY in inner query after WHERE clause because you have already used it in ROW_NUMBER() OVER (ORDER BY VRDATE DESC).

SELECT 
    * 
FROM (
    SELECT 
        Stockmain.VRNOA, 
        item.description as item_description, 
        party.name as party_name, 
        stockmain.vrdate, 
        stockdetail.qty, 
        stockdetail.rate, 
        stockdetail.amount, 
        ROW_NUMBER() OVER (ORDER BY VRDATE DESC) AS RowNum  --< ORDER BY
    FROM StockMain 
    INNER JOIN StockDetail 
        ON StockMain.stid = StockDetail.stid 
    INNER JOIN party 
        ON party.party_id = stockmain.party_id 
    INNER JOIN item 
        ON item.item_id = stockdetail.item_id 
    WHERE stockmain.etype='purchase' 
) AS MyDerivedTable
WHERE 
    MyDerivedTable.RowNum BETWEEN 1 and 5 

Drop default constraint on a column in TSQL

This is how you would drop the constraint

ALTER TABLE <schema_name, sysname, dbo>.<table_name, sysname, table_name>
   DROP CONSTRAINT <default_constraint_name, sysname, default_constraint_name>
GO

With a script

-- t-sql scriptlet to drop all constraints on a table
DECLARE @database nvarchar(50)
DECLARE @table nvarchar(50)

set @database = 'dotnetnuke'
set @table = 'tabs'

DECLARE @sql nvarchar(255)
WHILE EXISTS(select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where constraint_catalog = @database and table_name = @table)
BEGIN
    select    @sql = 'ALTER TABLE ' + @table + ' DROP CONSTRAINT ' + CONSTRAINT_NAME 
    from    INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
    where    constraint_catalog = @database and 
            table_name = @table
    exec    sp_executesql @sql
END

Credits go to Jon Galloway http://weblogs.asp.net/jgalloway/archive/2006/04/12/442616.aspx

How to make an embedded Youtube video automatically start playing?

Add &autoplay=1 to your syntax, like this

<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/zGPuazETKkI&amp;autoplay=1" frameborder="0" allowfullscreen></iframe>

When to favor ng-if vs. ng-show/ng-hide?

The answer is not simple:

It depends on the target machines (mobile vs desktop), it depends on the nature of your data, the browser, the OS, the hardware it runs on... you will need to benchmark if you really want to know.

It is mostly a memory vs computation problem ... as with most performance issues the difference can become significant with repeated elements (n) like lists, especially when nested (n x n, or worse) and also what kind of computations you run inside these elements:

  • ng-show: If those optional elements are often present (dense), like say 90% of the time, it may be faster to have them ready and only show/hide them, especially if their content is cheap (just plain text, nothing to compute or load). This consumes memory as it fills the DOM with hidden elements, but just show/hide something which already exists is likely to be a cheap operation for the browser.

  • ng-if: If on the contrary elements are likely not to be shown (sparse) just build them and destroy them in real time, especially if their content is expensive to get (computations/sorted/filtered, images, generated images). This is ideal for rare or 'on-demand' elements, it saves memory in terms of not filling the DOM but can cost a lot of computation (creating/destroying elements) and bandwidth (getting remote content). It also depends on how much you compute in the view (filtering/sorting) vs what you already have in the model (pre-sorted/pre-filtered data).

What does "@" mean in Windows batch scripts

In batch file:

1 @echo off(solo)=>output nothing enter image description here

2 echo off(solo)=> the “echo off” shows in the command line

enter image description here

3 echo off(then echo something) => enter image description here

4 @echo off(then echo something)=> enter image description here

See, echo off(solo), means no output in the command line, but itself shows; @echo off(solo), means no output in the command line, neither itself;

How to disable compiler optimizations in gcc?

Long time ago, but still needed.

info - https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html
list - gcc -Q --help=optimizers test.c | grep enabled
disable as many as you like with:
  gcc **-fno-web** -Q --help=optimizers test.c | grep enabled

Remove and Replace Printed items

import sys
import time

a = 0  
for x in range (0,3):  
    a = a + 1  
    b = ("Loading" + "." * a)
    # \r prints a carriage return first, so `b` is printed on top of the previous line.
    sys.stdout.write('\r'+b)
    time.sleep(0.5)
print (a)

Note that you might have to run sys.stdout.flush() right after sys.stdout.write('\r'+b) depending on which console you are doing the printing to have the results printed when requested without any buffering.

AttributeError: 'str' object has no attribute

The problem is in your playerMovement method. You are creating the string name of your room variables (ID1, ID2, ID3):

letsago = "ID" + str(self.dirDesc.values())

However, what you create is just a str. It is not the variable. Plus, I do not think it is doing what you think its doing:

>>>str({'a':1}.values())
'dict_values([1])'

If you REALLY needed to find the variable this way, you could use the eval function:

>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'

or the globals function:

class Foo(object):
    def __init__(self):
        super(Foo, self).__init__()
    def test(self, name):
        print(globals()[name])

foo = Foo()
bar = 'Hello World!'
foo.text('bar')

However, instead I would strongly recommend you rethink you class(es). Your userInterface class is essentially a Room. It shouldn't handle player movement. This should be within another class, maybe GameManager or something like that.

What should a JSON service return on failure / error

I would definitely return a 500 error with a JSON object describing the error condition, similar to how an ASP.NET AJAX "ScriptService" error returns. I believe this is fairly standard. It's definitely nice to have that consistency when handling potentially unexpected error conditions.

Aside, why not just use the built in functionality in .NET, if you're writing it in C#? WCF and ASMX services make it easy to serialize data as JSON, without reinventing the wheel.

how we add or remove readonly attribute from textbox on clicking radion button in cakephp using jquery?

You could use prop as well. Check the following code below.

$(document).ready(function(){

   $('.staff_on_site').click(function(){

     var rBtnVal = $(this).val();

     if(rBtnVal == "yes"){
         $("#no_of_staff").prop("readonly", false); 
     }
     else{ 
         $("#no_of_staff").prop("readonly", true); 
     }
   });
});

How to get status code from webclient?

Tried it out. ResponseHeaders do not include status code.

If I'm not mistaken, WebClient is capable of abstracting away multiple distinct requests in a single method call (e.g. correctly handling 100 Continue responses, redirects, and the like). I suspect that without using HttpWebRequest and HttpWebResponse, a distinct status code may not be available.

It occurs to me that, if you are not interested in intermediate status codes, you can safely assume the final status code is in the 2xx (successful) range, otherwise, the call would not be successful.

The status code unfortunately isn't present in the ResponseHeaders dictionary.

Read tab-separated file line into array

If you really want to split every word (bash meaning) into a different array index completely changing the array in every while loop iteration, @ruakh's answer is the correct approach. But you can use the read property to split every read word into different variables column1, column2, column3 like in this code snippet

while IFS=$'\t' read -r column1 column2 column3 ; do
  printf "%b\n" "column1<${column1}>"
  printf "%b\n" "column2<${column2}>"
  printf "%b\n" "column3<${column3}>"
done < "myfile"

to reach a similar result avoiding array index access and improving your code readability by using meaningful variable names (of course using columnN is not a good idea to do so).

python plot normal distribution

I don't think there is a function that does all that in a single call. However you can find the Gaussian probability density function in scipy.stats.

So the simplest way I could come up with is:

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm

# Plot between -10 and 10 with .001 steps.
x_axis = np.arange(-10, 10, 0.001)
# Mean = 0, SD = 2.
plt.plot(x_axis, norm.pdf(x_axis,0,2))
plt.show()

Sources:

How to Convert an int to a String?

Did you try:

text_Rate.setText(String.valueOf(sdRate));

How do I run git log to see changes only for a specific branch?

For those using Magit, hit l and =m to toggle --no-merges and =pto toggle --first-parent.

Then either just hit l again to show commits from the current branch (with none of commits merged onto it) down to end of history, or, if you want the log to end where it was branched off from master, hit o and type master.. as your range:

enter image description here

write() versus writelines() and concatenated strings

Actually, I think the problem is that your variable "lines" is bad. You defined lines as a tuple, but I believe that write() requires a string. All you have to change is your commas into pluses (+).

nl = "\n"
lines = line1+nl+line2+nl+line3+nl
textdoc.writelines(lines)

should work.

How to assign the output of a command to a Makefile variable

Beware of recipes like this

target:
    MY_ID=$(GENERATE_ID);
    echo $MY_ID;

It does two things wrong. The first line in the recipe is executed in a separate shell instance from the second line. The variable is lost in the meantime. Second thing wrong is that the $ is not escaped.

target:
    MY_ID=$(GENERATE_ID); \
    echo $$MY_ID;

Both problems have been fixed and the variable is useable. The backslash combines both lines to run in one single shell, hence the setting of the variable and the reading of the variable afterwords, works.

I realize the original post said how to get the results of a shell command into a MAKE variable, and this answer shows how to get it into a shell variable. But other readers may benefit.

One final improvement, if the consumer expects an "environment variable" to be set, then you have to export it.

my_shell_script
    echo $MY_ID

would need this in the makefile

target:
    export MY_ID=$(GENERATE_ID); \
    ./my_shell_script;

Hope that helps someone. In general, one should avoid doing any real work outside of recipes, because if someone use the makefile with '--dry-run' option, to only SEE what it will do, it won't have any undesirable side effects. Every $(shell) call is evaluated at compile time and some real work could accidentally be done. Better to leave the real work, like generating ids, to the inside of the recipes when possible.

MySQL JOIN the most recent row only?

I know this question is old, but it's got a lot of attention over the years and I think it's missing a concept which may help someone in a similar case. I'm adding it here for completeness sake.

If you cannot modify your original database schema, then a lot of good answers have been provided and solve the problem just fine.

If you can, however, modify your schema, I would advise to add a field in your customer table that holds the id of the latest customer_data record for this customer:

CREATE TABLE customer (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  current_data_id INT UNSIGNED NULL DEFAULT NULL
);

CREATE TABLE customer_data (
   id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
   customer_id INT UNSIGNED NOT NULL, 
   title VARCHAR(10) NOT NULL,
   forename VARCHAR(10) NOT NULL,
   surname VARCHAR(10) NOT NULL
);

Querying customers

Querying is as easy and fast as it can be:

SELECT c.*, d.title, d.forename, d.surname
FROM customer c
INNER JOIN customer_data d on d.id = c.current_data_id
WHERE ...;

The drawback is the extra complexity when creating or updating a customer.

Updating a customer

Whenever you want to update a customer, you insert a new record in the customer_data table, and update the customer record.

INSERT INTO customer_data (customer_id, title, forename, surname) VALUES(2, 'Mr', 'John', 'Smith');
UPDATE customer SET current_data_id = LAST_INSERT_ID() WHERE id = 2;

Creating a customer

Creating a customer is just a matter of inserting the customer entry, then running the same statements:

INSERT INTO customer () VALUES ();

SET @customer_id = LAST_INSERT_ID();
INSERT INTO customer_data (customer_id, title, forename, surname) VALUES(@customer_id, 'Mr', 'John', 'Smith');
UPDATE customer SET current_data_id = LAST_INSERT_ID() WHERE id = @customer_id;

Wrapping up

The extra complexity for creating/updating a customer might be fearsome, but it can easily be automated with triggers.

Finally, if you're using an ORM, this can be really easy to manage. The ORM can take care of inserting the values, updating the ids, and joining the two tables automatically for you.

Here is how your mutable Customer model would look like:

class Customer
{
    private int id;
    private CustomerData currentData;

    public Customer(String title, String forename, String surname)
    {
        this.update(title, forename, surname);
    }

    public void update(String title, String forename, String surname)
    {
        this.currentData = new CustomerData(this, title, forename, surname);
    }

    public String getTitle()
    {
        return this.currentData.getTitle();
    }

    public String getForename()
    {
        return this.currentData.getForename();
    }

    public String getSurname()
    {
        return this.currentData.getSurname();
    }
}

And your immutable CustomerData model, that contains only getters:

class CustomerData
{
    private int id;
    private Customer customer;
    private String title;
    private String forename;
    private String surname;

    public CustomerData(Customer customer, String title, String forename, String surname)
    {
        this.customer = customer;
        this.title    = title;
        this.forename = forename;
        this.surname  = surname;
    }

    public String getTitle()
    {
        return this.title;
    }

    public String getForename()
    {
        return this.forename;
    }

    public String getSurname()
    {
        return this.surname;
    }
}

Python loop counter in a for loop

I'll sometimes do this:

def draw_menu(options, selected_index):
    for i in range(len(options)):
        if i == selected_index:
            print " [*] %s" % options[i]
        else:
            print " [ ] %s" % options[i]

Though I tend to avoid this if it means I'll be saying options[i] more than a couple of times.

Angular JS break ForEach

var ary = ["JavaScript", "Java", "CoffeeScript", "TypeScript"];
var keepGoing = true;
ary.forEach(function(value, index, _ary) {
    console.log(index)
    keepGoing = true;
    ary.forEach(function(value, index, _ary) {
        if(keepGoing){ 
            if(index==2){
                keepGoing=false;
            }
            else{
                console.log(value)
            }

        }      
    });
});

text box input height

Use CSS:

<input type="text" class="bigText"  name=" item" align="left" />

.bigText {
    height:30px;
}

Dreamweaver is a poor testing tool. It is not a browser.

String.Format for Hex

The number 0 in {0:X} refers to the position in the list or arguments. In this case 0 means use the first value, which is Blue. Use {1:X} for the second argument (Green), and so on.

colorstring = String.Format("#{0:X}{1:X}{2:X}{3:X}", Blue, Green, Red, Space);

The syntax for the format parameter is described in the documentation:

Format Item Syntax

Each format item takes the following form and consists of the following components:

{ index[,alignment][:formatString]}

The matching braces ("{" and "}") are required.

Index Component

The mandatory index component, also called a parameter specifier, is a number starting from 0 that identifies a corresponding item in the list of objects. That is, the format item whose parameter specifier is 0 formats the first object in the list, the format item whose parameter specifier is 1 formats the second object in the list, and so on.

Multiple format items can refer to the same element in the list of objects by specifying the same parameter specifier. For example, you can format the same numeric value in hexadecimal, scientific, and number format by specifying a composite format string like this: "{0:X} {0:E} {0:N}".

Each format item can refer to any object in the list. For example, if there are three objects, you can format the second, first, and third object by specifying a composite format string like this: "{1} {0} {2}". An object that is not referenced by a format item is ignored. A runtime exception results if a parameter specifier designates an item outside the bounds of the list of objects.

Alignment Component

The optional alignment component is a signed integer indicating the preferred formatted field width. If the value of alignment is less than the length of the formatted string, alignment is ignored and the length of the formatted string is used as the field width. The formatted data in the field is right-aligned if alignment is positive and left-aligned if alignment is negative. If padding is necessary, white space is used. The comma is required if alignment is specified.

Format String Component

The optional formatString component is a format string that is appropriate for the type of object being formatted. Specify a standard or custom numeric format string if the corresponding object is a numeric value, a standard or custom date and time format string if the corresponding object is a DateTime object, or an enumeration format string if the corresponding object is an enumeration value. If formatString is not specified, the general ("G") format specifier for a numeric, date and time, or enumeration type is used. The colon is required if formatString is specified.

Note that in your case you only have the index and the format string. You have not specified (and do not need) an alignment component.

How to remove the character at a given index from a string in C?

Another solution, using memmove() along with index() and sizeof():

char buf[100] = "abcdef";
char remove = 'b';

char* c;
if ((c = index(buf, remove)) != NULL) {
    size_t len_left = sizeof(buf) - (c+1-buf);
    memmove(c, c+1, len_left);
}

buf[] now contains "acdef"

Difference between "git add -A" and "git add ."

The -A option adds, modifies, and removes index entries to match the working tree.

In Git 2 the -A option is now the default.

When a . is added that limits the scope of the update to the directory you are currently in, as per the Git documentation

If no <pathspec> is given when -A option is used, all files in the entire working tree are updated (old versions of Git used to limit the update to the current directory and its subdirectories).

One thing that I would add is that if the --interactive or -p mode is used then git add will behave as if the update (-u) flag was used and not add new files.

Difference between decimal, float and double in .NET?

  • float: ±1.5 x 10^-45 to ±3.4 x 10^38 (~7 significant figures
  • double: ±5.0 x 10^-324 to ±1.7 x 10^308 (15-16 significant figures)
  • decimal: ±1.0 x 10^-28 to ±7.9 x 10^28 (28-29 significant figures)

Inserting values into tables Oracle SQL

You can expend the following function in order to pull out more parameters from the DB before the insert:

--
-- insert_employee  (Function) 
--
CREATE OR REPLACE FUNCTION insert_employee(p_emp_id in number, p_emp_name in varchar2, p_emp_address in varchar2, p_emp_state in varchar2, p_emp_position in varchar2, p_emp_manager in varchar2) 
RETURN VARCHAR2 AS

   p_state_id varchar2(30) := '';
 BEGIN    
      select state_id 
      into   p_state_id
      from states where lower(emp_state) = state_name;

      INSERT INTO Employee (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager) VALUES 
                (p_emp_id, p_emp_name, p_emp_address, p_state_id, p_emp_position, p_emp_manager);

    return 'SUCCESS';

 EXCEPTION 
   WHEN others THEN
    RETURN 'FAIL';
 END;
/

AJAX in Chrome sending OPTIONS instead of GET/POST/PUT/DELETE?

I agree with Kevin B, the bug report says it all. It sounds like you are trying to make cross-domain ajax calls. If you're not familiar with the same origin policy you can start here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Same_origin_policy_for_JavaScript.

If this is not intended to be a cross-domain ajax call, try making your target url relative and see if the problem goes away. If you're really desperate look into the JSONP, but beware, mayhem lurks. There really isn't much more we can do to help you.

How to check python anaconda version installed on Windows 10 PC?

On the anaconda prompt, do a

  • conda -V or conda --version to get the conda version.
  • python -V or python --version to get the python version.
  • conda list anaconda$ to get the Anaconda version.
  • conda list to get the Name, Version, Build & Channel details of all the packages installed (in the current environment).
  • conda info to get all the current environment details.
  • conda info --envs To see a list of all your environments

Detailed description here, download cheat sheet from here

React: Expected an assignment or function call and instead saw an expression

Not sure about solutions but a temporary workaround is to ask eslint to ignore it by adding the following on top of the problem line.

// eslint-disable-next-line @typescript-eslint/no-unused-expressions

(Built-in) way in JavaScript to check if a string is a valid number

PFB the working solution:

 function(check){ 
    check = check + "";
    var isNumber =   check.trim().length>0? !isNaN(check):false;
    return isNumber;
    }

Run Excel Macro from Outside Excel Using VBScript From Command Line

Since my related question was removed by a righteous hand after I had killed the whole day searching how to beat the "macro not found or disabled" error, posting here the only syntax that worked for me (application.run didn't, no matter what I tried)

Set objExcel = CreateObject("Excel.Application")

' Didn't run this way from the Modules
'objExcel.Application.Run "c:\app\Book1.xlsm!Sub1"
' Didn't run this way either from the Sheet
'objExcel.Application.Run "c:\app\Book1.xlsm!Sheet1.Sub1"
' Nor did it run from a named Sheet
'objExcel.Application.Run "c:\app\Book1.xlsm!Named_Sheet.Sub1"

' Only ran like this (from the Module1)

Set objWorkbook = objExcel.Workbooks.Open("c:\app\Book1.xlsm")
objExcel.Run "Sub1"

Excel 2010, Win 7

how to convert string into dictionary in python 3.*?

  1. literal_eval, a somewhat safer version of eval (will only evaluate literals ie strings, lists etc):

    from ast import literal_eval
    
    python_dict = literal_eval("{'a': 1}")
    
  2. json.loads but it would require your string to use double quotes:

    import json
    
    python_dict = json.loads('{"a": 1}')
    

Unable to open project... cannot be opened because the project file cannot be parsed

Try to find HEAD and _HEAD between the lines and delete this words in project.pbxproj. Backup this file before doing this..

How to find whether or not a variable is empty in Bash?

The question asks how to check if a variable is an empty string and the best answers are already given for that.

But I landed here after a period passed programming in PHP, and I was actually searching for a check like the empty function in PHP working in a Bash shell.

After reading the answers I realized I was not thinking properly in Bash, but anyhow in that moment a function like empty in PHP would have been soooo handy in my Bash code.

As I think this can happen to others, I decided to convert the PHP empty function in Bash.

According to the PHP manual:

a variable is considered empty if it doesn't exist or if its value is one of the following:

  • "" (an empty string)
  • 0 (0 as an integer)
  • 0.0 (0 as a float)
  • "0" (0 as a string)
  • an empty array
  • a variable declared, but without a value

Of course the null and false cases cannot be converted in bash, so they are omitted.

function empty
{
    local var="$1"

    # Return true if:
    # 1.    var is a null string ("" as empty string)
    # 2.    a non set variable is passed
    # 3.    a declared variable or array but without a value is passed
    # 4.    an empty array is passed
    if test -z "$var"
    then
        [[ $( echo "1" ) ]]
        return

    # Return true if var is zero (0 as an integer or "0" as a string)
    elif [ "$var" == 0 2> /dev/null ]
    then
        [[ $( echo "1" ) ]]
        return

    # Return true if var is 0.0 (0 as a float)
    elif [ "$var" == 0.0 2> /dev/null ]
    then
        [[ $( echo "1" ) ]]
        return
    fi

    [[ $( echo "" ) ]]
}



Example of usage:

if empty "${var}"
    then
        echo "empty"
    else
        echo "not empty"
fi



Demo:
The following snippet:

#!/bin/bash

vars=(
    ""
    0
    0.0
    "0"
    1
    "string"
    " "
)

for (( i=0; i<${#vars[@]}; i++ ))
do
    var="${vars[$i]}"

    if empty "${var}"
        then
            what="empty"
        else
            what="not empty"
    fi
    echo "VAR \"$var\" is $what"
done

exit

outputs:

VAR "" is empty
VAR "0" is empty
VAR "0.0" is empty
VAR "0" is empty
VAR "1" is not empty
VAR "string" is not empty
VAR " " is not empty

Having said that in a Bash logic the checks on zero in this function can cause side problems imho, anyone using this function should evaluate this risk and maybe decide to cut those checks off leaving only the first one.

How do I convert an integer to binary in JavaScript?

This is how I manage to handle it:

const decbin = nbr => {
  if(nbr < 0){
     nbr = 0xFFFFFFFF + nbr + 1
  }
  return parseInt(nbr, 10).toString(2)
};

got it from this link: https://locutus.io/php/math/decbin/

AngularJS multiple filter with custom filter function

In view file (HTML or EJS)

<div ng-repeat="item in vm.itemList  | filter: myFilter > </div>

and In Controller

$scope.myFilter = function(item) {
return (item.propertyA === 'value' || item.propertyA === 'value');
}

typesafe select onChange event using reactjs and typescript

I tried using React.FormEvent<HTMLSelectElement> but it led to an error in the editor, even though there is no EventTarget visible in the code:

The property 'value' does not exist on value of type 'EventTarget'

Then I changed React.FormEvent to React.ChangeEvent and it helped:

private changeName(event: React.ChangeEvent<HTMLSelectElement>) {
    event.preventDefault();
    this.props.actions.changeName(event.target.value);
}

What is the difference between children and childNodes in JavaScript?

Element.children returns only element children, while Node.childNodes returns all node children. Note that elements are nodes, so both are available on elements.

I believe childNodes is more reliable. For example, MDC (linked above) notes that IE only got children right in IE 9. childNodes provides less room for error by browser implementors.

Referencing another schema in Mongoose

It sounds like the populate method is what your looking for. First make small change to your post schema:

var postSchema = new Schema({
    name: String,
    postedBy: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
    dateCreated: Date,
    comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
});

Then make your model:

var Post = mongoose.model('Post', postSchema);

Then, when you make your query, you can populate references like this:

Post.findOne({_id: 123})
.populate('postedBy')
.exec(function(err, post) {
    // do stuff with post
});

Matplotlib: "Unknown projection '3d'" error

Import mplot3d whole to use "projection = '3d'".

Insert the command below in top of your script. It should run fine.

from mpl_toolkits import mplot3d

jQuery remove all list items from an unordered list

If you have multiple ul and want to empty specific ul then use id eg:

<ul id="randomName">
   <li>1</li>
   <li>2</li>
   <li>3</li>
</ul>


<script>
  $('#randomName').empty();
</script>

_x000D_
_x000D_
$('input').click(function() {_x000D_
  $('#randomName').empty()_x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<ul id="randomName">_x000D_
  <li>1</li>_x000D_
  <li>2</li>_x000D_
  <li>3</li>_x000D_
</ul>_x000D_
_x000D_
<ul>_x000D_
  <li>4</li>_x000D_
  <li>5</li>_x000D_
</ul>_x000D_
<input type="button" value="click me" />
_x000D_
_x000D_
_x000D_

Request Monitoring in Chrome

You can also just right click on the page in the browser and select "Inspect Element" to bring up the developer tools.

https://developer.chrome.com/devtools

Producing a new line in XSLT

I added the DOCTYPE directive you see here:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xsl:stylesheet [
  <!ENTITY nl "&#xa;">
]>
<xsl:stylesheet xmlns:x="http://www.w3.org/2005/02/query-test-XQTSCatalog"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                version="2.0">

This allows me to use &nl; instead of &#xa; to produce a newline in the output. Like other solutions, this is typically placed inside a <xsl:text> tag.

Firestore Getting documents id from collection

Can get ID before add documents in database:

var idBefore =  this.afs.createId();
console.log(idBefore);

Replace part of a string in Python?

You can easily use .replace() as also previously described. But it is also important to keep in mind that strings are immutable. Hence if you do not assign the change you are making to a variable, then you will not see any change. Let me explain by;

    >>stuff = "bin and small"
    >>stuff.replace('and', ',')
    >>print(stuff)
    "big and small" #no change

To observe the change you want to apply, you can assign same or another variable;

    >>stuff = "big and small"
    >>stuff = stuff.replace("and", ",")   
    >>print(stuff)
    'big, small'

WARNING in budgets, maximum exceeded for initial

What is Angular CLI Budgets? Budgets is one of the less known features of the Angular CLI. It’s a rather small but a very neat feature!

As applications grow in functionality, they also grow in size. Budgets is a feature in the Angular CLI which allows you to set budget thresholds in your configuration to ensure parts of your application stay within boundaries which you setOfficial Documentation

Or in other words, we can describe our Angular application as a set of compiled JavaScript files called bundles which are produced by the build process. Angular budgets allows us to configure expected sizes of these bundles. More so, we can configure thresholds for conditions when we want to receive a warning or even fail build with an error if the bundle size gets too out of control!

How To Define A Budget? Angular budgets are defined in the angular.json file. Budgets are defined per project which makes sense because every app in a workspace has different needs.

Thinking pragmatically, it only makes sense to define budgets for the production builds. Prod build creates bundles with “true size” after applying all optimizations like tree-shaking and code minimization.

Oops, a build error! The maximum bundle size was exceeded. This is a great signal that tells us that something went wrong…

  1. We might have experimented in our feature and didn’t clean up properly
  2. Our tooling can go wrong and perform a bad auto-import, or we pick bad item from the suggested list of imports
  3. We might import stuff from lazy modules in inappropriate locations
  4. Our new feature is just really big and doesn’t fit into existing budgets

First Approach: Are your files gzipped?

Generally speaking, gzipped file has only about 20% the size of the original file, which can drastically decrease the initial load time of your app. To check if you have gzipped your files, just open the network tab of developer console. In the “Response Headers”, if you should see “Content-Encoding: gzip”, you are good to go.

How to gzip? If you host your Angular app in most of the cloud platforms or CDN, you should not worry about this issue as they probably have handled this for you. However, if you have your own server (such as NodeJS + expressJS) serving your Angular app, definitely check if the files are gzipped. The following is an example to gzip your static assets in a NodeJS + expressJS app. You can hardly imagine this dead simple middleware “compression” would reduce your bundle size from 2.21MB to 495.13KB.

const compression = require('compression')
const express = require('express')
const app = express()
app.use(compression())

Second Approach:: Analyze your Angular bundle

If your bundle size does get too big you may want to analyze your bundle because you may have used an inappropriate large-sized third party package or you forgot to remove some package if you are not using it anymore. Webpack has an amazing feature to give us a visual idea of the composition of a webpack bundle.

enter image description here

It’s super easy to get this graph.

  1. npm install -g webpack-bundle-analyzer
  2. In your Angular app, run ng build --stats-json (don’t use flag --prod). By enabling --stats-json you will get an additional file stats.json
  3. Finally, run webpack-bundle-analyzer ./dist/stats.json and your browser will pop up the page at localhost:8888. Have fun with it.

ref 1: How Did Angular CLI Budgets Save My Day And How They Can Save Yours

ref 2: Optimize Angular bundle size in 4 steps

Reset all changes after last commit in git

There are two commands which will work in this situation,

root>git reset --hard HEAD~1

root>git push -f

For more git commands refer this page

How to extract a substring using regex

Apache Commons Lang provides a host of helper utilities for the java.lang API, most notably String manipulation methods. In your case, the start and end substrings are the same, so just call the following function.

StringUtils.substringBetween(String str, String tag)

Gets the String that is nested in between two instances of the same String.

If the start and the end substrings are different then use the following overloaded method.

StringUtils.substringBetween(String str, String open, String close)

Gets the String that is nested in between two Strings.

If you want all instances of the matching substrings, then use,

StringUtils.substringsBetween(String str, String open, String close)

Searches a String for substrings delimited by a start and end tag, returning all matching substrings in an array.

For the example in question to get all instances of the matching substring

String[] results = StringUtils.substringsBetween(mydata, "'", "'");

Python, remove all non-alphabet chars from string

Use re.sub

import re

regex = re.compile('[^a-zA-Z]')
#First parameter is the replacement, second parameter is your input string
regex.sub('', 'ab3d*E')
#Out: 'abdE'

Alternatively, if you only want to remove a certain set of characters (as an apostrophe might be okay in your input...)

regex = re.compile('[,\.!?]') #etc.

Replace HTML Table with Divs

Basically it boils down to using a fixed-width page and setting the width for those labels and controls. This is the most common way in which table-less layouts are implemented.

There are many ways to go about setting widths. Blueprint.css is a very popular css framework which can help you set up columns/widths.

How to read files and stdout from a running Docker container

The stdout of the process started by the docker container is available through the docker logs $containerid command (use -f to keep it going forever). Another option would be to stream the logs directly through the docker remote API.

For accessing log files (only if you must, consider logging to stdout or other standard solution like syslogd) your only real-time option is to configure a volume (like Marcus Hughes suggests) so the logs are stored outside the container and available for processing from the host or another container.

If you do not need real-time access to the logs, you can export the files (in tar format) with docker export

List of phone number country codes

Here is a JS function that converts "Country Code" (ISO3) to Telephone "Calling Code":

function country_iso3_to_country_calling_code(country_iso3) {
        if(country_iso3 == 'AFG') return '93';
        if(country_iso3 == 'ALB') return '355';
        if(country_iso3 == 'DZA') return '213';
        if(country_iso3 == 'ASM') return '1684';
        if(country_iso3 == 'AND') return '376';
        if(country_iso3 == 'AGO') return '244';
        if(country_iso3 == 'AIA') return '1264';
        if(country_iso3 == 'ATA') return '672';
        if(country_iso3 == 'ATG') return '1268';
        if(country_iso3 == 'ARG') return '54';
        if(country_iso3 == 'ARM') return '374';
        if(country_iso3 == 'ABW') return '297';
        if(country_iso3 == 'AUS') return '61';
        if(country_iso3 == 'AUT') return '43';
        if(country_iso3 == 'AZE') return '994';
        if(country_iso3 == 'BHS') return '1242';
        if(country_iso3 == 'BHR') return '973';
        if(country_iso3 == 'BGD') return '880';
        if(country_iso3 == 'BRB') return '1246';
        if(country_iso3 == 'BLR') return '375';
        if(country_iso3 == 'BEL') return '32';
        if(country_iso3 == 'BLZ') return '501';
        if(country_iso3 == 'BEN') return '229';
        if(country_iso3 == 'BMU') return '1441';
        if(country_iso3 == 'BTN') return '975';
        if(country_iso3 == 'BOL') return '591';
        if(country_iso3 == 'BIH') return '387';
        if(country_iso3 == 'BWA') return '267';
        if(country_iso3 == 'BVT') return '_55';
        if(country_iso3 == 'BRA') return '55';
        if(country_iso3 == 'IOT') return '1284';
        if(country_iso3 == 'BRN') return '673';
        if(country_iso3 == 'BGR') return '359';
        if(country_iso3 == 'BFA') return '226';
        if(country_iso3 == 'BDI') return '257';
        if(country_iso3 == 'KHM') return '855';
        if(country_iso3 == 'CMR') return '237';
        if(country_iso3 == 'CAN') return '1';
        if(country_iso3 == 'CPV') return '238';
        if(country_iso3 == 'CYM') return '1345';
        if(country_iso3 == 'CAF') return '236';
        if(country_iso3 == 'TCD') return '235';
        if(country_iso3 == 'CHL') return '56';
        if(country_iso3 == 'CHN') return '86';
        if(country_iso3 == 'CXR') return '618';
        if(country_iso3 == 'CCK') return '61';
        if(country_iso3 == 'COL') return '57';
        if(country_iso3 == 'COM') return '269';
        if(country_iso3 == 'COG') return '242';
        if(country_iso3 == 'COD') return '243';
        if(country_iso3 == 'COK') return '682';
        if(country_iso3 == 'CRI') return '506';
        if(country_iso3 == 'HRV') return '385';
        if(country_iso3 == 'CUB') return '53';
        if(country_iso3 == 'CYP') return '357';
        if(country_iso3 == 'CZE') return '420';
        if(country_iso3 == 'DNK') return '45';
        if(country_iso3 == 'DJI') return '253';
        if(country_iso3 == 'DMA') return '1767';
        if(country_iso3 == 'DOM') return '1';
        if(country_iso3 == 'ECU') return '593';
        if(country_iso3 == 'EGY') return '20';
        if(country_iso3 == 'SLV') return '503';
        if(country_iso3 == 'GNQ') return '240';
        if(country_iso3 == 'ERI') return '291';
        if(country_iso3 == 'EST') return '372';
        if(country_iso3 == 'ETH') return '251';
        if(country_iso3 == 'FLK') return '500';
        if(country_iso3 == 'FRO') return '298';
        if(country_iso3 == 'FJI') return '679';
        if(country_iso3 == 'FIN') return '358';
        if(country_iso3 == 'FRA') return '33';
        if(country_iso3 == 'GUF') return '594';
        if(country_iso3 == 'PYF') return '689';
        if(country_iso3 == 'GAB') return '241';
        if(country_iso3 == 'GMB') return '220';
        if(country_iso3 == 'GEO') return '995';
        if(country_iso3 == 'DEU') return '49';
        if(country_iso3 == 'GHA') return '233';
        if(country_iso3 == 'GIB') return '350';
        if(country_iso3 == 'GRC') return '30';
        if(country_iso3 == 'GRL') return '299';
        if(country_iso3 == 'GRD') return '1473';
        if(country_iso3 == 'GLP') return '590';
        if(country_iso3 == 'GUM') return '1671';
        if(country_iso3 == 'GTM') return '502';
        if(country_iso3 == 'GIN') return '224';
        if(country_iso3 == 'GNB') return '245';
        if(country_iso3 == 'GUY') return '592';
        if(country_iso3 == 'HTI') return '509';
        if(country_iso3 == 'HMD') return '61';
        if(country_iso3 == 'VAT') return '3';
        if(country_iso3 == 'HND') return '504';
        if(country_iso3 == 'HKG') return '852';
        if(country_iso3 == 'HUN') return '36';
        if(country_iso3 == 'ISL') return '354';
        if(country_iso3 == 'IND') return '91';
        if(country_iso3 == 'IDN') return '62';
        if(country_iso3 == 'IRN') return '98';
        if(country_iso3 == 'IRQ') return '964';
        if(country_iso3 == 'IRL') return '353';
        if(country_iso3 == 'ISR') return '972';
        if(country_iso3 == 'ITA') return '39';
        if(country_iso3 == 'CIV') return '225';
        if(country_iso3 == 'JAM') return '1876';
        if(country_iso3 == 'JPN') return '81';
        if(country_iso3 == 'JOR') return '962';
        if(country_iso3 == 'KAZ') return '7';
        if(country_iso3 == 'KEN') return '254';
        if(country_iso3 == 'KIR') return '686';
        if(country_iso3 == 'PRK') return '850';
        if(country_iso3 == 'KOR') return '82';
        if(country_iso3 == 'KWT') return '965';
        if(country_iso3 == 'KGZ') return '7';
        if(country_iso3 == 'LAO') return '856';
        if(country_iso3 == 'LVA') return '371';
        if(country_iso3 == 'LBN') return '961';
        if(country_iso3 == 'LSO') return '266';
        if(country_iso3 == 'LBR') return '231';
        if(country_iso3 == 'LBY') return '218';
        if(country_iso3 == 'LIE') return '423';
        if(country_iso3 == 'LTU') return '370';
        if(country_iso3 == 'LUX') return '352';
        if(country_iso3 == 'MAC') return '853';
        if(country_iso3 == 'MKD') return '389';
        if(country_iso3 == 'MDG') return '261';
        if(country_iso3 == 'MWI') return '265';
        if(country_iso3 == 'MYS') return '60';
        if(country_iso3 == 'MDV') return '960';
        if(country_iso3 == 'MLI') return '223';
        if(country_iso3 == 'MLT') return '356';
        if(country_iso3 == 'MHL') return '692';
        if(country_iso3 == 'MTQ') return '596';
        if(country_iso3 == 'MRT') return '222';
        if(country_iso3 == 'MUS') return '230';
        if(country_iso3 == 'MYT') return '262';
        if(country_iso3 == 'MEX') return '52';
        if(country_iso3 == 'FSM') return '691';
        if(country_iso3 == 'MDA') return '373';
        if(country_iso3 == 'MCO') return '377';
        if(country_iso3 == 'MNG') return '976';
        if(country_iso3 == 'MSR') return '1664';
        if(country_iso3 == 'MAR') return '212';
        if(country_iso3 == 'MOZ') return '258';
        if(country_iso3 == 'MMR') return '95';
        if(country_iso3 == 'NAM') return '264';
        if(country_iso3 == 'NRU') return '674';
        if(country_iso3 == 'NPL') return '977';
        if(country_iso3 == 'NLD') return '31';
        if(country_iso3 == 'ANT') return '599';
        if(country_iso3 == 'NCL') return '687';
        if(country_iso3 == 'NZL') return '64';
        if(country_iso3 == 'NIC') return '505';
        if(country_iso3 == 'NER') return '227';
        if(country_iso3 == 'NGA') return '234';
        if(country_iso3 == 'NIU') return '683';
        if(country_iso3 == 'NFK') return '672';
        if(country_iso3 == 'MNP') return '1670';
        if(country_iso3 == 'NOR') return '47';
        if(country_iso3 == 'OMN') return '968';
        if(country_iso3 == 'PAK') return '92';
        if(country_iso3 == 'PLW') return '680';
        if(country_iso3 == 'PSE') return '970';
        if(country_iso3 == 'PAN') return '507';
        if(country_iso3 == 'PNG') return '675';
        if(country_iso3 == 'PRY') return '595';
        if(country_iso3 == 'PER') return '51';
        if(country_iso3 == 'PHL') return '63';
        if(country_iso3 == 'PCN') return '870';
        if(country_iso3 == 'POL') return '48';
        if(country_iso3 == 'PRT') return '351';
        if(country_iso3 == 'PRI') return '1';
        if(country_iso3 == 'QAT') return '974';
        if(country_iso3 == 'REU') return '262';
        if(country_iso3 == 'ROM') return '40';
        if(country_iso3 == 'RUS') return '7';
        if(country_iso3 == 'RWA') return '250';
        if(country_iso3 == 'SHN') return '290';
        if(country_iso3 == 'KNA') return '1869';
        if(country_iso3 == 'LCA') return '1758';
        if(country_iso3 == 'SPM') return '508';
        if(country_iso3 == 'VCT') return '1758';
        if(country_iso3 == 'WSM') return '685';
        if(country_iso3 == 'SMR') return '378';
        if(country_iso3 == 'STP') return '239';
        if(country_iso3 == 'SAU') return '966';
        if(country_iso3 == 'SEN') return '221';
        if(country_iso3 == 'SRB') return '381';
        if(country_iso3 == 'SYC') return '248';
        if(country_iso3 == 'SLE') return '232';
        if(country_iso3 == 'SGP') return '65';
        if(country_iso3 == 'SVK') return '421';
        if(country_iso3 == 'SVN') return '386';
        if(country_iso3 == 'SLB') return '677';
        if(country_iso3 == 'SOM') return '252';
        if(country_iso3 == 'ZAF') return '27';
        if(country_iso3 == 'SGS') return '44';
        if(country_iso3 == 'ESP') return '34';
        if(country_iso3 == 'LKA') return '94';
        if(country_iso3 == 'SDN') return '249';
        if(country_iso3 == 'SUR') return '597';
        if(country_iso3 == 'SJM') return '47';
        if(country_iso3 == 'SWZ') return '268';
        if(country_iso3 == 'SWE') return '46';
        if(country_iso3 == 'CHE') return '41';
        if(country_iso3 == 'SYR') return '963';
        if(country_iso3 == 'TWN') return '886';
        if(country_iso3 == 'TJK') return '992';
        if(country_iso3 == 'TZA') return '255';
        if(country_iso3 == 'THA') return '66';
        if(country_iso3 == 'TLS') return '670';
        if(country_iso3 == 'TGO') return '228';
        if(country_iso3 == 'TKL') return '690';
        if(country_iso3 == 'TON') return '676';
        if(country_iso3 == 'TTO') return '1868';
        if(country_iso3 == 'TUN') return '216';
        if(country_iso3 == 'TUR') return '90';
        if(country_iso3 == 'TKM') return '993';
        if(country_iso3 == 'TCA') return '1649';
        if(country_iso3 == 'TUV') return '688';
        if(country_iso3 == 'UGA') return '256';
        if(country_iso3 == 'UKR') return '380';
        if(country_iso3 == 'ARE') return '971';
        if(country_iso3 == 'GBR') return '44';
        if(country_iso3 == 'USA') return '1';
        if(country_iso3 == 'UMI') return '1340';
        if(country_iso3 == 'URY') return '598';
        if(country_iso3 == 'UZB') return '998';
        if(country_iso3 == 'VUT') return '678';
        if(country_iso3 == 'VEN') return '58';
        if(country_iso3 == 'VNM') return '84';
        if(country_iso3 == 'VGB') return '1284';
        if(country_iso3 == 'VIR') return '1340';
        if(country_iso3 == 'WLF') return '681';
        if(country_iso3 == 'YEM') return '260';
        if(country_iso3 == 'ZMB') return '260';
        if(country_iso3 == 'ZWE') return '263';


    }

Calendar date to yyyy-MM-dd format in java

Your code is wrong. No point of parsing date and keep that as Date object.

You can format the calender date object when you want to display and keep that as a string.

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
Date date = cal.getTime();             
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");          
String inActiveDate = null;
try {
    inActiveDate = format1.format(date);
    System.out.println(inActiveDate );
} catch (ParseException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}

How do I implement a callback in PHP?

The manual uses the terms "callback" and "callable" interchangeably, however, "callback" traditionally refers to a string or array value that acts like a function pointer, referencing a function or class method for future invocation. This has allowed some elements of functional programming since PHP 4. The flavors are:

$cb1 = 'someGlobalFunction';
$cb2 = ['ClassName', 'someStaticMethod'];
$cb3 = [$object, 'somePublicMethod'];

// this syntax is callable since PHP 5.2.3 but a string containing it
// cannot be called directly
$cb2 = 'ClassName::someStaticMethod';
$cb2(); // fatal error

// legacy syntax for PHP 4
$cb3 = array(&$object, 'somePublicMethod');

This is a safe way to use callable values in general:

if (is_callable($cb2)) {
    // Autoloading will be invoked to load the class "ClassName" if it's not
    // yet defined, and PHP will check that the class has a method
    // "someStaticMethod". Note that is_callable() will NOT verify that the
    // method can safely be executed in static context.

    $returnValue = call_user_func($cb2, $arg1, $arg2);
}

Modern PHP versions allow the first three formats above to be invoked directly as $cb(). call_user_func and call_user_func_array support all the above.

See: http://php.net/manual/en/language.types.callable.php

Notes/Caveats:

  1. If the function/class is namespaced, the string must contain the fully-qualified name. E.g. ['Vendor\Package\Foo', 'method']
  2. call_user_func does not support passing non-objects by reference, so you can either use call_user_func_array or, in later PHP versions, save the callback to a var and use the direct syntax: $cb();
  3. Objects with an __invoke() method (including anonymous functions) fall under the category "callable" and can be used the same way, but I personally don't associate these with the legacy "callback" term.
  4. The legacy create_function() creates a global function and returns its name. It's a wrapper for eval() and anonymous functions should be used instead.

How do I create a datetime in Python from milliseconds?

What about this? I presume it can be counted on to handle dates before 1970 and after 2038.

target_date_time_ms = 200000 # or whatever
base_datetime = datetime.datetime( 1970, 1, 1 )
delta = datetime.timedelta( 0, 0, 0, target_date_time_ms )
target_date = base_datetime + delta

as mentioned in the Python standard lib:

fromtimestamp() may raise ValueError, if the timestamp is out of the range of values supported by the platform C localtime() or gmtime() functions. It’s common for this to be restricted to years in 1970 through 2038.

List all the files and folders in a Directory with PHP recursive function

My proposal without ugly "foreach" control structures is

$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
$allFiles = array_filter(iterator_to_array($iterator), function($file) {
    return $file->isFile();
});

You may only want to extract the filepath, which you can do so by:

array_keys($allFiles);

Still 4 lines of code, but more straight forward than using a loop or something.

When should an Excel VBA variable be killed or set to Nothing?

VB6/VBA uses deterministic approach to destoying objects. Each object stores number of references to itself. When the number reaches zero, the object is destroyed.

Object variables are guaranteed to be cleaned (set to Nothing) when they go out of scope, this decrements the reference counters in their respective objects. No manual action required.

There are only two cases when you want an explicit cleanup:

  1. When you want an object to be destroyed before its variable goes out of scope (e.g., your procedure is going to take long time to execute, and the object holds a resource, so you want to destroy the object as soon as possible to release the resource).

  2. When you have a circular reference between two or more objects.

    If objectA stores a references to objectB, and objectB stores a reference to objectA, the two objects will never get destroyed unless you brake the chain by explicitly setting objectA.ReferenceToB = Nothing or objectB.ReferenceToA = Nothing.

The code snippet you show is wrong. No manual cleanup is required. It is even harmful to do a manual cleanup, as it gives you a false sense of more correct code.

If you have a variable at a class level, it will be cleaned/destroyed when the class instance is destructed. You can destroy it earlier if you want (see item 1.).

If you have a variable at a module level, it will be cleaned/destroyed when your program exits (or, in case of VBA, when the VBA project is reset). You can destroy it earlier if you want (see item 1.).

Access level of a variable (public vs. private) does not affect its life time.

Android Activity without ActionBar

Haha, I have been stuck at that point a while ago as well, so I am glad I can help you out with a solution, that worked for me at least :)

What you want to do is define a new style within values/styles.xml so it looks like this

<resources>
    <style name = "AppTheme" parent = "android:Theme.Holo.Light.DarkActionBar">
        <!-- Customize your theme here. -->
    </style>

    <style name = "NoActionBar" parent = "@android:style/Theme.Holo.Light">
        <item name = "android:windowActionBar">false</item>
        <item name = "android:windowNoTitle">true</item>
    </style>

</resources>

Only the NoActionBar style is intresting for you. At last you have to set is as your application's theme in the AndroidManifest.xml so it looks like this

<application
    android:allowBackup = "true"
    android:icon = "@drawable/ic_launcher"
    android:label = "@string/app_name"
    android:theme = "@style/NoActionBar"   <!--This is the important line-->
    >
    <activity
    [...]

I hope this helps, if not, let me know.

Trying to git pull with error: cannot open .git/FETCH_HEAD: Permission denied

This worked for me:

  1. Right click .git folder
  2. click get info
  3. set permission to your user
  4. click the Cog icon and click apply to enclosed items

No more permission denied errors in git.

Add some word to all or some rows in Excel?

  • Select All cells that want to change.
  • right click and select Format cell.
  • In category select Custom.
  • In Type select General and insert this formol ----> "k"@

How to sort a HashSet?

Use java.util.TreeSet as the actual object. When you iterate over this collection, the values come back in a well-defined order.

If you use java.util.HashSet then the order depends on an internal hash function which is almost certainly not lexicographic (based on content).

How to make a rest post call from ReactJS code?

Here is a util function modified (another post on stack) for get and post both. Make Util.js file.

let cachedData = null;
let cachedPostData = null;

const postServiceData = (url, params) => {
    console.log('cache status' + cachedPostData );
    if (cachedPostData === null) {
        console.log('post-data: requesting data');
        return fetch(url, {
            method: 'POST',
            headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(params)
          })
        .then(response => {
            cachedPostData = response.json();
            return cachedPostData;
        });
    } else {
        console.log('post-data: returning cachedPostData data');
        return Promise.resolve(cachedPostData);
    }
}

const getServiceData = (url) => {
    console.log('cache status' + cachedData );
    if (cachedData === null) {
        console.log('get-data: requesting data');
        return fetch(url, {})
        .then(response => {
            cachedData = response.json();
            return cachedData;
        });
    } else {
        console.log('get-data: returning cached data');
        return Promise.resolve(cachedData);
    }
};

export  { getServiceData, postServiceData };

Usage like below in another component

import { getServiceData, postServiceData } from './../Utils/Util';

constructor(props) {
    super(props)
    this.state = {
      datastore : []
    }
  }

componentDidMount = () => {  
    let posturl = 'yoururl'; 
    let getdataString = { name: "xys", date:"today"};  
    postServiceData(posturl, getdataString)
      .then(items => { 
        this.setState({ datastore: items }) 
      console.log(items);   
    });
  }

How can I change the language (to english) in Oracle SQL Developer?

You can also configure directly on the file ..sqldeveloper\ide\bin\ide.conf:

Just add the JVM Option:

AddVMOption -Duser.language=en

The file will be like this:

enter image description here

jQuery set radio button

Why do you need 'input:radio[name=cols]'. Don't know your html, but assuming that ids are unique, you can simply do this.

$('#'+newcol).prop('checked', true);

How do I remove the last comma from a string using PHP?

rtrim function

rtrim($my_string,',');

Second parameter indicates that comma to be deleted from right side.

no pg_hba.conf entry for host

also check the PGHOST variable:

ECHO $PGHOST

to see if it matches the local machine name

How to convert Moment.js date to users local timezone?

Here's what I did:

var timestamp = moment.unix({{ time }});
var utcOffset = moment().utcOffset();
var local_time = timestamp.add(utcOffset, "minutes");
var dateString = local_time.fromNow();

Where {{ time }} is the utc timestamp.

Laravel PDOException SQLSTATE[HY000] [1049] Unknown database 'forge'

first clear your cache using this command

php artisan cache:clear

Then restart the server using this command

php artisan serve

Uncaught ReferenceError: <function> is not defined at HTMLButtonElement.onclick

Place your script inside the body tag

<body>
  // Rest of html
  <script>
  function hideButton() {
    $(".loading").hide();
  }
function showButton() {
  $(".loading").show();
}
</script> 
< /body>

If you check this JSFIDDLE and click on javascript, you will see the load Type body is selected

How to get the index with the key in Python dictionary?

No, there is no straightforward way because Python dictionaries do not have a set ordering.

From the documentation:

Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.

In other words, the 'index' of b depends entirely on what was inserted into and deleted from the mapping before:

>>> map={}
>>> map['b']=1
>>> map
{'b': 1}
>>> map['a']=1
>>> map
{'a': 1, 'b': 1}
>>> map['c']=1
>>> map
{'a': 1, 'c': 1, 'b': 1}

As of Python 2.7, you could use the collections.OrderedDict() type instead, if insertion order is important to your application.

Text in HTML Field to disappear when clicked?

To accomplish that, you can use the two events onfocus and onblur:

<input type="text" name="theName" value="DefaultValue"
  onblur="if(this.value==''){ this.value='DefaultValue'; this.style.color='#BBB';}"
  onfocus="if(this.value=='DefaultValue'){ this.value=''; this.style.color='#000';}"
  style="color:#BBB;" />

How can I see if a Perl hash already has a certain key?

I guess that this code should answer your question:

use strict;
use warnings;

my @keys = qw/one two three two/;
my %hash;
for my $key (@keys)
{
    $hash{$key}++;
}

for my $key (keys %hash)
{
   print "$key: ", $hash{$key}, "\n";
}

Output:

three: 1
one: 1
two: 2

The iteration can be simplified to:

$hash{$_}++ for (@keys);

(See $_ in perlvar.) And you can even write something like this:

$hash{$_}++ or print "Found new value: $_.\n" for (@keys);

Which reports each key the first time it’s found.

href="javascript:" vs. href="javascript:void(0)"

This method seems ok in all browsers, if you set the onclick with a jQuery event:

<a href="javascript:;">Click me!</a>

As said before, href="#" with change the url hash and can trigger data re/load if you use a History (or ba-bbq) JS plugin.

SQL to search objects, including stored procedures, in Oracle

ALL_SOURCE describes the text source of the stored objects accessible to the current user.

Here is one of the solution

select * from ALL_SOURCE where text like '%some string%';

Java executors: how to be notified, without blocking, when a task completes?

Just to add to Matt's answer, which helped, here is a more fleshed-out example to show the use of a callback.

private static Primes primes = new Primes();

public static void main(String[] args) throws InterruptedException {
    getPrimeAsync((p) ->
        System.out.println("onPrimeListener; p=" + p));

    System.out.println("Adios mi amigito");
}
public interface OnPrimeListener {
    void onPrime(int prime);
}
public static void getPrimeAsync(OnPrimeListener listener) {
    CompletableFuture.supplyAsync(primes::getNextPrime)
        .thenApply((prime) -> {
            System.out.println("getPrimeAsync(); prime=" + prime);
            if (listener != null) {
                listener.onPrime(prime);
            }
            return prime;
        });
}

The output is:

    getPrimeAsync(); prime=241
    onPrimeListener; p=241
    Adios mi amigito

Hashing with SHA1 Algorithm in C#

I'll throw my hat in here:

(as part of a static class, as this snippet is two extensions)

//hex encoding of the hash, in uppercase.
public static string Sha1Hash (this string str)
{
    byte[] data = UTF8Encoding.UTF8.GetBytes (str);
    data = data.Sha1Hash ();
    return BitConverter.ToString (data).Replace ("-", "");
}
// Do the actual hashing
public static byte[] Sha1Hash (this byte[] data)
{
    using (SHA1Managed sha1 = new SHA1Managed ()) {
    return sha1.ComputeHash (data);
}

Basic text editor in command prompt?

I want to add that it is very strange to introduce Core and Nano servers without native console full-featured editor. Like others I`ll recommend to use vim or nano. But my suggestion is to install it via OneGet (require WMF5)! They both are presented in Chocolatey repository so installation is simple and fast:


PS C:> Find-Package -Name vim | Format-Table -AutoSize
Name Version Status    ProviderName Source     Summary
---- ------- ------    ------------ ------     -------
vim  7.4.638 Available Chocolatey   chocolatey Vim is an advanced text editor...

PS C:> Install-Package vim

Oracle SQL: Use sequence in insert with Select Statement

I tested and the script run ok!

INSERT INTO HISTORICAL_CAR_STATS (HISTORICAL_CAR_STATS_ID, YEAR,MONTH,MAKE,MODEL,REGION,AVG_MSRP,COUNT) 
WITH DATA AS
(
    SELECT '2010' YEAR,'12' MONTH ,'ALL' MAKE,'ALL' MODEL,REGION,sum(AVG_MSRP*COUNT)/sum(COUNT) AVG_MSRP,sum(Count) COUNT
    FROM HISTORICAL_CAR_STATS
    WHERE YEAR = '2010' AND MONTH = '12'
    AND MAKE != 'ALL' GROUP BY REGION
)
SELECT MY_SEQ.NEXTVAL, YEAR,MONTH,MAKE,MODEL,REGION,AVG_MSRP,COUNT
FROM DATA;

you can read this article to understand more! http://www.orafaq.com/wiki/ORA-02287

The container 'Maven Dependencies' references non existing library - STS

I got the same problem and this is how i solved. :

  1. Right click your Spring MVC project, choose Run As -> Maven install. Observe the output console to see the installation progress. After the installation is finished, you can continue to the next step.

enter image description here

enter image description here

  1. Right click your Spring MVC project, choose Maven -> Update Project.

enter image description here

  1. Choose your project and click OK. Wait until update process is finished.
  2. The error still yet, then do Project->Clean and then be sure you have selected our project directory and then do the follow Project->Build.

json_decode returns NULL after webservice call

EDIT: Just did some quick inspection of the string provided by the OP. The small "character" in front of the curly brace is a UTF-8 B(yte) O(rder) M(ark) 0xEF 0xBB 0xBF. I don't know why this byte sequence is displayed as ? here.

Essentially the system you aquire the data from sends it encoded in UTF-8 with a BOM preceding the data. You should remove the first three bytes from the string before you throw it into json_decode() (a substr($string, 3) will do).

string(62) "?{"action":"set","user":"123123123123","status":"OK"}"
            ^
            |
            This is the UTF-8 BOM

As Kuroki Kaze discovered, this character surely is the reason why json_decode fails. The string in its given form is not correctly a JSON formated structure (see RFC 4627)

Implementing autocomplete

I have created a module for anuglar2 autocomplete In this module you can use array, or url npm link : ang2-autocomplete

Parsing JSON with Unix tools

Here is a good reference. In this case:

curl 'http://twitter.com/users/username.json' | sed -e 's/[{}]/''/g' | awk -v k="text" '{n=split($0,a,","); for (i=1; i<=n; i++) { where = match(a[i], /\"text\"/); if(where) {print a[i]} }  }'

How do I start PowerShell from Windows Explorer?

Another option are the excellent Elevation PowerToys by Michael Murgolo on TechNet at http://technet.microsoft.com/en-us/magazine/2008.06.elevation.aspx.

They include PowerShell Prompt Here and PowerShell Prompt Here as Administrator.

What exactly does the .join() method do?

To expand a bit more on what others are saying, if you wanted to use join to simply concatenate your two strings, you would do this:

strid = repr(595)
print ''.join([array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
    .tostring(), strid])

Programmatically change input type of the EditText from PASSWORD to NORMAL & vice versa

The Password Visibility Toggle feature has been added to support library version 24.2.0 enabling you to toggle the password straight from the EditText without the need for a CheckBox.

You can make that work basically by first updating your support library version to 24.2.0 and then setting an inputType of password on the TextInputEditText. Here's how to do that:

<android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/password"
            android:inputType="textPassword"/>
</android.support.design.widget.TextInputLayout>

You can get more information about the new feature on the developer documentation for TextInputLayout.

Casting string to enum

.NET 4.0+ has a generic Enum.TryParse

ContentEnum content;
Enum.TryParse(fileContentMessage, out content);

AngularJS ng-repeat handle empty list case

You might want to check out the angular-ui directive ui-if if you just want to remove the ul from the DOM when the list is empty:

<ul ui-if="!!events.length">
    <li ng-repeat="event in events">{{event.title}}</li>
</ul>

How do I convert from a money datatype in SQL server?

Normal money conversions will preserve individual pennies:

SELECT convert(varchar(30), moneyfield, 1)

The last parameter decides what the output format looks like:

0 (default) No commas every three digits to the left of the decimal point, and two digits to the right of the decimal point; for example, 4235.98.

1 Commas every three digits to the left of the decimal point, and two digits to the right of the decimal point; for example, 3,510.92.

2 No commas every three digits to the left of the decimal point, and four digits to the right of the decimal point; for example, 4235.9819.

If you want to truncate the pennies, and count in pounds, you can use rounding to the nearest pound, floor to the lowest whole pound, or ceiling to round up the pounds:

SELECT convert(int, round(moneyfield, 0))
SELECT convert(int, floor(moneyfield))
SELECT convert(int, ceiling(moneyfield))

Python style - line continuation with strings?

Since adjacent string literals are automatically joint into a single string, you can just use the implied line continuation inside parentheses as recommended by PEP 8:

print("Why, hello there wonderful "
      "stackoverflow people!")

How can I move all the files from one folder to another using the command line?

move c:\sourcefolder c:\targetfolder

will work, but you will end up with a structure like this:

c:\targetfolder\sourcefolder\[all the subfolders & files]

If you want to move just the contents of one folder to another, then this should do it:

SET src_folder=c:\srcfold
SET tar_folder=c:\tarfold

for /f %%a IN ('dir "%src_folder%" /b') do move "%src_folder%\%%a" "%tar_folder%\"

pause

Warning "Do not Access Superglobal $_POST Array Directly" on Netbeans 7.4 for PHP

Here is part of a line in my code that brought the warning up in NetBeans:

$page = (!empty($_GET['p'])) 

After much research and seeing how there are about a bazillion ways to filter this array, I found one that was simple. And my code works and NetBeans is happy:

$p = filter_input(INPUT_GET, 'p');
$page = (!empty($p))

What is the regex for "Any positive integer, excluding 0"

You might want this (edit: allow number of the form 0123):

^\\+?[1-9]$|^\\+?\d+$

however, if it were me, I would instead do

int x = Integer.parseInt(s)
if (x > 0) {...}

Check if a given key already exists in a dictionary and increment it

I personally like using setdefault()

my_dict = {}

my_dict.setdefault(some_key, 0)
my_dict[some_key] += 1

Remove First and Last Character C++

My BASIC interpreter chops beginning and ending quotes with

str->pop_back();
str->erase(str->begin());

Of course, I always expect well-formed BASIC style strings, so I will abort with failed assert if not:

assert(str->front() == '"' && str->back() == '"');

Just my two cents.

Android set bitmap to Imageview

this code works with me

 ImageView carView = (ImageView) v.findViewById(R.id.car_icon);

                            byte[] decodedString = Base64.decode(picture, Base64.NO_WRAP);
                            InputStream input=new ByteArrayInputStream(decodedString);
                            Bitmap ext_pic = BitmapFactory.decodeStream(input);
                            carView.setImageBitmap(ext_pic);

How to install both Python 2.x and Python 3.x in Windows

To install and run any version of Python in the same system follow my guide below.


For example say you want to install Python 2.x and Python 3.x on the same Windows system.

  1. Install both of their binary releases anywhere you want.

    • When prompted do not register their file extensions and
    • do not add them automatically to the PATH environment variable
  2. Running simply the command python the executable that is first met in PATH will be chosen for launch. In other words, add the Python directories manually. The one you add first will be selected when you type python. Consecutive python programs (increasing order that their directories are placed in PATH) will be chosen like so:

    • py -2 for the second python
    • py -3 for the third python etc..
  3. No matter the order of "pythons" you can:

    • run Python 2.x scripts using the command: py -2 (Python 3.x functionality) (ie. the first Python 2.x installation program found in your PATH will be selected)
    • run Python 3.x scripts using the command: or py -3 (ie. the first Python 3.x installation program found in your PATH will be selected)

In my example I have Python 2.7.14 installed first and Python 3.5.3. This is how my PATH variable starts with:

PATH=C:\Program Files\Microsoft MPI\Bin\;C:\Python27;C:\Program Files\Python_3.6\Scripts\;C:\Program Files\Python_3.6\;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Common Files\Intel\Shared

...

Note that Python 2.7 is first and Python 3.5 second.

  • So running python command will launch python 2.7 (if Python 3.5 the same command would launch Python 3.5).
  • Running py -2 launches Python 2.7 (because it happens that the second Python is Python 3.5 which is incompatible with py -2). Running py -3 launches Python 3.5 (because it's Python 3.x)
  • If you had another python later in your path you would launch like so: py -4. This may change if/when Python version 4 is released.

Now py -4 or py -5 etc. on my system outputs: Requested Python version (4) not installed or Requested Python version (5) not installed etc.

Hopefully this is clear enough.

Get array of object's keys

Use Object.keys:

_x000D_
_x000D_
var foo = {_x000D_
  'alpha': 'puffin',_x000D_
  'beta': 'beagle'_x000D_
};_x000D_
_x000D_
var keys = Object.keys(foo);_x000D_
console.log(keys) // ['alpha', 'beta'] _x000D_
// (or maybe some other order, keys are unordered).
_x000D_
_x000D_
_x000D_

This is an ES5 feature. This means it works in all modern browsers but will not work in legacy browsers.

The ES5-shim has a implementation of Object.keys you can steal

When should I use "this" in a class?

“This” keyword in java is used to refer current class objects.

There are 6 uses of “this” keyword in java

  1. Accessing class level variable: mostly used if local and class level variable is same
  2. Accessing class methods : this is default behavior and can be ignored
  3. For calling other constructor of same class
  4. Using ‘this’ keyword as return value : for returning current instance from method
  5. Passing ‘this’ keyword as argument to method Passing : for passing current class instance as argument
  6. this keyword as argument to constructor : for passing current class instance as argument

ref: https://stacktraceguru.com/java/this-keyword-in-java

Convert hex string to int in Python

int(hexstring, 16) does the trick, and works with and without the 0x prefix:

>>> int("a", 16)
10
>>> int("0xa", 16)
10

Sending email from Azure

I know this is an old post but I've just signed up for Azure and I get 25,000 emails a month for free via SendGrid. These instructions are excellent, I was up and running in minutes:

How to Send Email Using SendGrid with Azure

Azure customers can unlock 25,000 free emails each month.

check if a file is open in Python

You could use with open("path") as file: so that it automatically closes, else if it's open in another process you can maybe try as in Tims example you should use except IOError to not ignore any other problem with your code :)

try:
   with open("path", "r") as file: # or just open
       # Code here
except IOError:
   # raise error or print

How to Run a jQuery or JavaScript Before Page Start to Load

If you don't want anything to display before the redirect, then you will need to use some server side scripting to accomplish the task before the page is served. The page has already begun loading by the time your Javascript is executed on the client side.

If Javascript is your only option, your best best is to make your script the first .js file included in the <head> of your document.

Instead of Javascript, I recommend setting up your redirect logic in your Apache or nginx server configuration.

Freeze the top row for an html table only (Fixed Table Header Scrolling)

This is called Fixed Header Scrolling. There are a number of documented approaches:

http://www.imaputz.com/cssStuff/bigFourVersion.html

You won't effectively pull this off without JavaScript ... especially if you want cross browser support.

There are a number of gotchyas with any approach you take, especially concerning cross browser/version support.

Edit:

Even if it's not the header you want to fix, but the first row of data, the concept is still the same. I wasn't 100% which you were referring to.

Additional thought I was tasked by my company to research a solution for this that could function in IE7+, Firefox, and Chrome.

After many moons of searching, trying, and frustration it really boiled down to a fundamental problem. For the most part, in order to gain the fixed header, you need to implement fixed height/width columns because most solutions involve using two separate tables, one for the header which will float and stay in place over the second table that contains the data.

//float this one right over second table
<table>
  <tr>
    <th>Header 1</th>
    <th>Header 2</th>
  </tr>
</table>

<table>
//Data
</table>

An alternative approach some try is utilize the tbody and thead tags but that is flawed too because IE will not allow you put a scrollbar on the tbody which means you can't limit its height (so stupid IMO).

<table>
  <thead style="do some stuff to fix its position">
  <tr>
    <th>Header 1</th>
    <th>Header 2</th>
  </tr>
  </thead>
  <tbody style="No scrolling allowed here!">
     Data here
  </tbody>
</table>

This approach has many issues such as ensures EXACT pixel widths because tables are so cute in that different browsers will allocate pixels differently based on calculations and you simply CANNOT (AFAIK) guarantee that the distribution will be perfect in all cases. It becomes glaringly obvious if you have borders within your table.

I took a different approach and said screw tables since you can't make this guarantee. I used divs to mimic tables. This also has issues of positioning the rows and columns (mainly because floating has issues, using in-line block won't work for IE7, so it really left me with using absolute positioning to put them in their proper places).

There is someone out there that made the Slick Grid which has a very similar approach to mine and you can use and a good (albeit complex) example for achieving this.

https://github.com/6pac/SlickGrid/wiki

How to set the title text color of UIButton?

You can set UIButton title color with hex code

btn.setTitleColor(UIColor(hexString: "#95469F"), for: .normal)

<code> vs <pre> vs <samp> for inline and block code snippets

Show HTML code, as-is, using the (obsolete) <xmp> tag:

_x000D_
_x000D_
<xmp>
<div>
  <input placeholder='write something' value='test'>
</div>
</xmp>
_x000D_
_x000D_
_x000D_

It is very sad this tag has been deprecated, but it does still works on browsers, it it is a bad-ass tag. no need to escape anything inside it. What a joy!


Show HTML code, as-is, using the <textarea> tag:

_x000D_
_x000D_
<textarea readonly rows="4" style="background:none; border:none; resize:none; outline:none; width:100%;">
<div>
  <input placeholder='write something' value='test'>
</div>
</textarea>
_x000D_
_x000D_
_x000D_

Force IE compatibility mode off using tags

If you want each individual web page to load the chosen content and are using asp.net. Just apply it as the first tag under the heading tag in Views>shared>Layout.cshtml

just a tip

How do I run SSH commands on remote system using Java?

I created solution based on JSch library:

import com.google.common.io.CharStreams
import com.jcraft.jsch.ChannelExec
import com.jcraft.jsch.JSch
import com.jcraft.jsch.JSchException
import com.jcraft.jsch.Session

import static java.util.Arrays.asList

class RunCommandViaSsh {

    private static final String SSH_HOST = "test.domain.com"
    private static final String SSH_LOGIN = "username"
    private static final String SSH_PASSWORD = "password"

    public static void main() {
        System.out.println(runCommand("pwd"))
        System.out.println(runCommand("ls -la"));
    }

    private static List<String> runCommand(String command) {
        Session session = setupSshSession();
        session.connect();

        ChannelExec channel = (ChannelExec) session.openChannel("exec");
        try {
            channel.setCommand(command);
            channel.setInputStream(null);
            InputStream output = channel.getInputStream();
            channel.connect();

            String result = CharStreams.toString(new InputStreamReader(output));
            return asList(result.split("\n"));

        } catch (JSchException | IOException e) {
            closeConnection(channel, session)
            throw new RuntimeException(e)

        } finally {
            closeConnection(channel, session)
        }
    }

    private static Session setupSshSession() {
        Session session = new JSch().getSession(SSH_LOGIN, SSH_HOST, 22);
        session.setPassword(SSH_PASSWORD);
        session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
        session.setConfig("StrictHostKeyChecking", "no"); // disable check for RSA key
        return session;
    }

    private static void closeConnection(ChannelExec channel, Session session) {
        try {
            channel.disconnect()
        } catch (Exception ignored) {
        }
        session.disconnect()
    }
}

Efficient SQL test query or validation query that will work across all (or most) databases

I use this for Firebird

select 1 from RDB$RELATION_FIELDS rows 1

How to set environment variables in Python?

if i do os.environ["DEBUSSY"] = 1, it complains saying that 1 has to be string.

Then do

os.environ["DEBUSSY"] = "1"

I also want to know how to read the environment variables in python(in the later part of the script) once i set it.

Just use os.environ["DEBUSSY"], as in

some_value = os.environ["DEBUSSY"]

Reordering Chart Data Series

This function gets the series names, puts them into an array, sorts the array and based on that defines the plotting order which will give the desired output.

Function Increasing_Legend_Sort(mychart As Chart)


    Dim Arr()
    ReDim Arr(1 To mychart.FullSeriesCollection.Count)

        'Assigning Series names to an array
        For i = LBound(Arr) To UBound(Arr)
        Arr(i) = mychart.FullSeriesCollection(i).Name
        Next i

        'Bubble-Sort (Sort the array in increasing order)
        For r1 = LBound(Arr) To UBound(Arr)
            rval = Arr(r1)
                For r2 = LBound(Arr) To UBound(Arr)
                    If Arr(r2) > rval Then 'Change ">" to "<" to make it decreasing
                        Arr(r1) = Arr(r2)
                        Arr(r2) = rval
                        rval = Arr(r1)
                    End If
                Next r2
        Next r1

    'Defining the PlotOrder
    For i = LBound(Arr) To UBound(Arr)
    mychart.FullSeriesCollection(Arr(i)).PlotOrder = i
    Next i

End Function

How can I concatenate two arrays in Java?

Here's an adaptation of silvertab's solution, with generics retrofitted:

static <T> T[] concat(T[] a, T[] b) {
    final int alen = a.length;
    final int blen = b.length;
    final T[] result = (T[]) java.lang.reflect.Array.
            newInstance(a.getClass().getComponentType(), alen + blen);
    System.arraycopy(a, 0, result, 0, alen);
    System.arraycopy(b, 0, result, alen, blen);
    return result;
}

NOTE: See Joachim's answer for a Java 6 solution. Not only does it eliminate the warning; it's also shorter, more efficient and easier to read!

HTML img scaling

No Javascript required.

IE6 Internet Explorer 6

Percent only works for the width of an element, but height:100%; does not work without the correct code.

CSS

html, body { height:100%; } 

Then using a percentage works properly, and dynamically updates on window resize.

<img src="image.jpg" style="height:80%;">

You do not need a width attribute, the width scales proportionately as the browser window size is changed.

And this little gem, is in case the image is scaled up, it will not look (overly) blocky (it interpolates).

img { -ms-interpolation-mode: bicubic; }

Props go to this source: Ultimate IE6 Cheatsheet: How To Fix 25+ Internet Explorer 6 Bugs

How to use a BackgroundWorker?

I know this is a bit old, but in case another beginner is going through this, I'll share some code that covers a bit more of the basic operations, here is another example that also includes the option to cancel the process and also report to the user the status of the process. I'm going to add on top of the code given by Alex Aza in the solution above

public Form1()
{
    InitializeComponent();

    backgroundWorker1.DoWork += backgroundWorker1_DoWork;
    backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
    backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;  //Tell the user how the process went
    backgroundWorker1.WorkerReportsProgress = true;
    backgroundWorker1.WorkerSupportsCancellation = true; //Allow for the process to be cancelled
}

//Start Process
private void button1_Click(object sender, EventArgs e)
{
    backgroundWorker1.RunWorkerAsync();
}

//Cancel Process
private void button2_Click(object sender, EventArgs e)
{
    //Check if background worker is doing anything and send a cancellation if it is
    if (backgroundWorker1.IsBusy)
    {
        backgroundWorker1.CancelAsync();
    }

}

private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(1000);
        backgroundWorker1.ReportProgress(i);

        //Check if there is a request to cancel the process
        if (backgroundWorker1.CancellationPending)
        {
            e.Cancel = true;
            backgroundWorker1.ReportProgress(0);
            return;
        }
    }
    //If the process exits the loop, ensure that progress is set to 100%
    //Remember in the loop we set i < 100 so in theory the process will complete at 99%
    backgroundWorker1.ReportProgress(100);
}

private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
    if (e.Cancelled)
    {
         lblStatus.Text = "Process was cancelled";
    }
    else if (e.Error != null)
    {
         lblStatus.Text = "There was an error running the process. The thread aborted";
    }
    else
    {
       lblStatus.Text = "Process was completed";
    }
}

Are the days of passing const std::string & as a parameter over?

IMO using the C++ reference for std::string is a quick and short local optimization, while using passing by value could be (or not) a better global optimization.

So the answer is: it depends on circumstances:

  1. If you write all the code from the outside to the inside functions, you know what the code does, you can use the reference const std::string &.
  2. If you write the library code or use heavily library code where strings are passed, you likely gain more in global sense by trusting std::string copy constructor behavior.

Calculate mean and standard deviation from a vector of samples in C++ using Boost

If performance is important to you, and your compiler supports lambdas, the stdev calculation can be made faster and simpler: In tests with VS 2012 I've found that the following code is over 10 X quicker than the Boost code given in the chosen answer; it's also 5 X quicker than the safer version of the answer using standard libraries given by musiphil.

Note I'm using sample standard deviation, so the below code gives slightly different results (Why there is a Minus One in Standard Deviations)

double sum = std::accumulate(std::begin(v), std::end(v), 0.0);
double m =  sum / v.size();

double accum = 0.0;
std::for_each (std::begin(v), std::end(v), [&](const double d) {
    accum += (d - m) * (d - m);
});

double stdev = sqrt(accum / (v.size()-1));

MySQL Insert with While Loop

drop procedure if exists doWhile;
DELIMITER //  
CREATE PROCEDURE doWhile()   
BEGIN
DECLARE i INT DEFAULT 2376921001; 
WHILE (i <= 237692200) DO
    INSERT INTO `mytable` (code, active, total) values (i, 1, 1);
    SET i = i+1;
END WHILE;
END;
//  

CALL doWhile(); 

Understanding the set() function

After reading the other answers, I still had trouble understanding why the set comes out un-ordered.

Mentioned this to my partner and he came up with this metaphor: take marbles. You put them in a tube a tad wider than marble width : you have a list. A set, however, is a bag. Even though you feed the marbles one-by-one into the bag; when you pour them from a bag back into the tube, they will not be in the same order (because they got all mixed up in a bag).

clearing a char array c

Why not use memset()? That's how to do it.

Setting the first element leaves the rest of the memory untouched, but str functions will treat the data as empty.

Creating and writing lines to a file

You'll need to deal with File System Object. See this OpenTextFile method sample.

python date of the previous month

datetime and the datetime.timedelta classes are your friend.

  1. find today.
  2. use that to find the first day of this month.
  3. use timedelta to backup a single day, to the last day of the previous month.
  4. print the YYYYMM string you're looking for.

Like this:

 import datetime
 today = datetime.date.today()
 first = today.replace(day=1)
 lastMonth = first - datetime.timedelta(days=1)
 print(lastMonth.strftime("%Y%m"))

201202 is printed.

What is the meaning of @_ in Perl?

Usually, you expand the parameters passed to a sub using the @_ variable:

sub test{
  my ($a, $b, $c) = @_;
  ...
}

# call the test sub with the parameters
test('alice', 'bob', 'charlie');

That's the way claimed to be correct by perlcritic.

How to compare two List<String> to each other?

I discovered that SequenceEqual is not the most efficient way to compare two lists of strings (initially from http://www.dotnetperls.com/sequenceequal).

I wanted to test this myself so I created two methods:

    /// <summary>
    /// Compares two string lists using LINQ's SequenceEqual.
    /// </summary>
    public bool CompareLists1(List<string> list1, List<string> list2)
    {
        return list1.SequenceEqual(list2);
    }

    /// <summary>
    /// Compares two string lists using a loop.
    /// </summary>
    public bool CompareLists2(List<string> list1, List<string> list2)
    {
        if (list1.Count != list2.Count)
            return false;

        for (int i = 0; i < list1.Count; i++)
        {
            if (list1[i] != list2[i])
                return false;
        }

        return true;
    }

The second method is a bit of code I encountered and wondered if it could be refactored to be "easier to read." (And also wondered if LINQ optimization would be faster.)

As it turns out, with two lists containing 32k strings, over 100 executions:

  • Method 1 took an average of 6761.8 ticks
  • Method 2 took an average of 3268.4 ticks

I usually prefer LINQ for brevity, performance, and code readability; but in this case I think a loop-based method is preferred.

Edit:

I recompiled using optimized code, and ran the test for 1000 iterations. The results still favor the loop (even more so):

  • Method 1 took an average of 4227.2 ticks
  • Method 2 took an average of 1831.9 ticks

Tested using Visual Studio 2010, C# .NET 4 Client Profile on a Core i7-920

True/False vs 0/1 in MySQL

Bit is also an option if tinyint isn't to your liking. A few links:

Not surprisingly, more info about numeric types is available in the manual.

One more link: http://blog.mclaughlinsoftware.com/2010/02/26/mysql-boolean-data-type/

And a quote from the comment section of the article above:

  • TINYINT(1) isn’t a synonym for bit(1).
  • TINYINT(1) can store -9 to 9.
  • TINYINT(1) UNSIGNED: 0-9
  • BIT(1): 0, 1. (Bit, literally).

Edit: This edit (and answer) is only remotely related to the original question...

Additional quotes by Justin Rovang and the author maclochlainn (comment section of the linked article).

Excuse me, seems I’ve fallen victim to substr-ism: TINYINT(1): -128-+127 TINYINT(1) UNSIGNED: 0-255 (Justin Rovang 25 Aug 11 at 4:32 pm)

True enough, but the post was about what PHPMyAdmin listed as a Boolean, and there it only uses 0 or 1 from the entire wide range of 256 possibilities. (maclochlainn 25 Aug 11 at 11:35 pm)

How can I initialize a String array with length 0 in Java?

Ok I actually found the answer but thought I would 'import' the question into SO anyway

String[] files = new String[0];
or
int[] files = new int[0];

Conversion failed when converting from a character string to uniqueidentifier - Two GUIDs

DECLARE @t TABLE (ID UNIQUEIDENTIFIER DEFAULT NEWID(),myid UNIQUEIDENTIFIER
                , friendid UNIQUEIDENTIFIER, time1 Datetime, time2 Datetime)
insert into @t (myid,friendid,time1,time2) 
values
 ( CONVERT(uniqueidentifier,'0C6A36BA-10E4-438F-BA86-0D5B68A2BB15'),
   CONVERT(uniqueidentifier,'DF215E10-8BD4-4401-B2DC-99BB03135F2E'),
   '2014-01-05 02:04:41.953','2014-01-05 12:04:41.953')

SELECT * FROM @t

Result Set With out any errors

+------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
¦                  ID                  ¦                 myid                 ¦               friendid               ¦          time1          ¦          time2          ¦
¦--------------------------------------+--------------------------------------+--------------------------------------+-------------------------+-------------------------¦
¦ CF628202-33F3-49CF-8828-CB2D93C69675 ¦ 0C6A36BA-10E4-438F-BA86-0D5B68A2BB15 ¦ DF215E10-8BD4-4401-B2DC-99BB03135F2E ¦ 2014-01-05 02:04:41.953 ¦ 2014-01-05 12:04:41.953 ¦
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

How to import jquery using ES6 syntax?

If you are using Webpack 4, the answer is to use the ProvidePlugin. Their documentation specifically covers angular.js with jquery use case:

new webpack.ProvidePlugin({
  'window.jQuery': 'jquery'
});

The issue is that when using import syntax angular.js and jquery will always be imported before you have a chance to assign jquery to window.jQuery (import statements will always run first no matter where they are in the code!). This means that angular will always see window.jQuery as undefined until you use ProvidePlugin.

How to check if type of a variable is string?

In Python 2.x, you would do

isinstance(s, basestring)

basestring is the abstract superclass of str and unicode. It can be used to test whether an object is an instance of str or unicode.


In Python 3.x, the correct test is

isinstance(s, str)

The bytes class isn't considered a string type in Python 3.