Programs & Examples On #Lcds

Adobe LiveCycle Data Services (LCDS) its a framework used for connecting RIA applications written in Flex/HTML with Java/.NET backends. It offers solutions for real time messaging, data management, remoting, data modeling and code generation. It is one of the solution components included in Adobe Digital Enterprise Platform.

onClick not working on mobile (touch)

better to use touchstart event with .on() jQuery method:

$(window).load(function() { // better to use $(document).ready(function(){
    $('.List li').on('click touchstart', function() {
        $('.Div').slideDown('500');
    });
});

And i don't understand why you are using $(window).load() method because it waits for everything on a page to be loaded, this tend to be slow, while you can use $(document).ready() method which does not wait for each element on the page to be loaded first.

Arduino error: does not name a type?

I got the does not name a type error when installing the NeoMatrix library.

Solution: the .cpp and .h files need to be in the top folder when you copy it, e.g:

myArduinoFolder/libraries/Adafruit_NeoMatrix/Adafruit_NeoMatrix.cpp

When I used the default Windows unzip program, it nested the contents inside another folder:

myArduinoFolder/libraries/Adafruit_NeoMatrix/Adafruit_NeoMatrix/Adafruit_NeoMatrix.cpp

I moved the files up, so it was:

myArduinoFolder/libraries/Adafruit_NeoMatrix/Adafruit_NeoMatrix.cpp

This fixed the does not name a type problem.

Can I update a JSF component from a JSF backing bean method?

Everything is possible only if there is enough time to research :)

What I got to do is like having people that I iterate into a ui:repeat and display names and other fields in inputs. But one of fields was singleSelect - A and depending on it value update another input - B. even ui:repeat do not have id I put and it appeared in the DOM tree

<ui:repeat id="peopleRepeat"
value="#{myBean.people}"
var="person" varStatus="status">

Than the ids in the html were something like:

myForm:peopleRepeat:0:personType
myForm:peopleRepeat:1:personType

Than in the view I got one method like:

<p:ajax event="change"
listener="#{myBean.onPersonTypeChange(person, status.index)}"/>

And its implementation was in the bean like:

String componentId = "myForm:peopleRepeat" + idx + "personType";
PrimeFaces.current().ajax().update(componentId);

So this way I updated the element from the bean with no issues. PF version 6.2

Good luck and happy coding :)

How to get CRON to call in the correct PATHs

Set the required PATH in your cron

crontab -e

Edit: Press i

PATH=/usr/local/bin:/usr/local/:or_whatever

10 * * * * your_command

Save and exit :wq

Why am I getting "(304) Not Modified" error on some links when using HttpWebRequest?

This is intended behavior.

When you make an HTTP request, the server normally returns code 200 OK. If you set If-Modified-Since, the server may return 304 Not modified (and the response will not have the content). This is supposed to be your cue that the page has not been modified.

The authors of the class have foolishly decided that 304 should be treated as an error and throw an exception. Now you have to clean up after them by catching the exception every time you try to use If-Modified-Since.

Bash write to file without echo?

awk ' BEGIN { print "Hello, world" } ' > test.txt

would do it

Margin while printing html page

You should use cm or mm as unit when you specify for printing. Using pixels will cause the browser to translate it to something similar to what it looks like on screen. Using cm or mm will ensure consistent size on the paper.

body
{
  margin: 25mm 25mm 25mm 25mm;
}

For font sizes, use pt for the print media.

Note that setting the margin on the body in css style will not adjust the margin in the printer driver that defines the printable area of the printer, or margin controlled by the browser (may be adjustable in print preview on some browsers)... It will just set margin on the document inside the printable area.

You should also be aware that IE7++ automatically adjusts the size to best fit, and causes everything to be wrong even if you use cm or mm. To override this behaviour, the user must select 'Print preview' and then set the print size to 100% (default is Shrink To Fit).

A better option for full control on printed margins is to use the @page directive to set the paper margin, which will affect the margin on paper outside the html body element, which is normally controlled by the browser. See http://www.w3.org/TR/1998/REC-CSS2-19980512/page.html.
This currently works in all major browsers except Safari.
In Internet explorer, the margin is actually set to this value in the settings for this printing, and if you do Preview you will get this as default, but the user can change it in the preview.

@page  
{ 
    size: auto;   /* auto is the initial value */ 

    /* this affects the margin in the printer settings */ 
    margin: 25mm 25mm 25mm 25mm;  
} 

body  
{ 
    /* this affects the margin on the content before sending to printer */ 
    margin: 0px;  
} 

Related answer: Disabling browser print options (headers, footers, margins) from page?

Is ini_set('max_execution_time', 0) a bad idea?

Reason is to have some value other than zero. General practice to have it short globally and long for long working scripts like parsers, crawlers, dumpers, exporting & importing scripts etc.

  1. You can halt server, corrupt work of other people by memory consuming script without even knowing it.
  2. You will not be seeing mistakes where something, let's say, infinite loop happened, and it will be harder to diagnose.
  3. Such site may be easily DoSed by single user, when requesting pages with long execution time

Numpy array dimensions

import numpy as np   
>>> np.shape(a)
(2,2)

Also works if the input is not a numpy array but a list of lists

>>> a = [[1,2],[1,2]]
>>> np.shape(a)
(2,2)

Or a tuple of tuples

>>> a = ((1,2),(1,2))
>>> np.shape(a)
(2,2)

Create dynamic variable name

try this one, user json to serialize and deserialize:

 using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Web.Script.Serialization;

    namespace ConsoleApplication1
    {
       public class Program
       {
          static void Main(string[] args)
          {
              object newobj = new object();

              for (int i = 0; i < 10; i++)
              {
                List<int> temp = new List<int>();

                temp.Add(i);
                temp.Add(i + 1);

                 newobj = newobj.AddNewField("item_" + i.ToString(), temp.ToArray());
              }

         }

     }

      public static class DynamicExtention
      {
          public static object AddNewField(this object obj, string key, object value)
          {
              JavaScriptSerializer js = new JavaScriptSerializer();

              string data = js.Serialize(obj);

              string newPrametr = "\"" + key + "\":" + js.Serialize(value);

              if (data.Length == 2)
             {
                 data = data.Insert(1, newPrametr);
              }
            else
              {
                  data = data.Insert(data.Length-1, ","+newPrametr);
              }

              return js.DeserializeObject(data);
          }
      }
   }

How to print register values in GDB?

Gdb commands:

  • i r <register_name>: print a single register, e.g i r rax, i r eax
  • i r <register_name_1> <register_name_2> ...: print multiple registers, e.g i r rdi rsi,
  • i r: print all register except floating point & vector register (xmm, ymm, zmm).
  • i r a: print all register, include floating point & vector register (xmm, ymm, zmm).
  • i r f: print all FPU floating registers (st0-7 and a few other f*)

Other register groups besides a (all) and f (float) can be found with:

maint print reggroups

as documented at: https://sourceware.org/gdb/current/onlinedocs/gdb/Registers.html#Registers

Tips:

  • xmm0 ~ xmm15, are 128 bits, almost every modern machine has it, they are released in 1999.
  • ymm0 ~ ymm15, are 256 bits, new machine usually have it, they are released in 2011.
  • zmm0 ~ zmm31, are 512 bits, normal pc probably don't have it (as the year 2016), they are released in 2013, and mainly used in servers so far.
  • Only one serial of xmm / ymm / zmm will be shown, because they are the same registers in different mode. On my machine ymm is shown.

How to modify a text file?

Depends on what you want to do. To append you can open it with "a":

 with open("foo.txt", "a") as f:
     f.write("new line\n")

If you want to preprend something you have to read from the file first:

with open("foo.txt", "r+") as f:
     old = f.read() # read everything in the file
     f.seek(0) # rewind
     f.write("new line\n" + old) # write the new line before

Open a Web Page in a Windows Batch FIle

hh.exe (help pages renderer) is capable of opening some simple webpages:

hh http://www.nissan.com

This will work even if browsing is blocked through:

HKEY_CURRENT_USER\Software\Policies\Microsoft\Internet Explorer

Calculate cosine similarity given 2 sentence strings

The short answer is "no, it is not possible to do that in a principled way that works even remotely well". It is an unsolved problem in natural language processing research and also happens to be the subject of my doctoral work. I'll very briefly summarize where we are and point you to a few publications:

Meaning of words

The most important assumption here is that it is possible to obtain a vector that represents each word in the sentence in quesion. This vector is usually chosen to capture the contexts the word can appear in. For example, if we only consider the three contexts "eat", "red" and "fluffy", the word "cat" might be represented as [98, 1, 87], because if you were to read a very very long piece of text (a few billion words is not uncommon by today's standard), the word "cat" would appear very often in the context of "fluffy" and "eat", but not that often in the context of "red". In the same way, "dog" might be represented as [87,2,34] and "umbrella" might be [1,13,0]. Imagening these vectors as points in 3D space, "cat" is clearly closer to "dog" than it is to "umbrella", therefore "cat" also means something more similar to "dog" than to an "umbrella".

This line of work has been investigated since the early 90s (e.g. this work by Greffenstette) and has yielded some surprisingly good results. For example, here is a few random entries in a thesaurus I built recently by having my computer read wikipedia:

theory -> analysis, concept, approach, idea, method
voice -> vocal, tone, sound, melody, singing
james -> william, john, thomas, robert, george, charles

These lists of similar words were obtained entirely without human intervention- you feed text in and come back a few hours later.

The problem with phrases

You might ask why we are not doing the same thing for longer phrases, such as "ginger foxes love fruit". It's because we do not have enough text. In order for us to reliably establish what X is similar to, we need to see many examples of X being used in context. When X is a single word like "voice", this is not too hard. However, as X gets longer, the chances of finding natural occurrences of X get exponentially slower. For comparison, Google has about 1B pages containing the word "fox" and not a single page containing "ginger foxes love fruit", despite the fact that it is a perfectly valid English sentence and we all understand what it means.

Composition

To tackle the problem of data sparsity, we want to perform composition, i.e. to take vectors for words, which are easy to obtain from real text, and to put the together in a way that captures their meaning. The bad news is nobody has been able to do that well so far.

The simplest and most obvious way is to add or multiply the individual word vectors together. This leads to undesirable side effect that "cats chase dogs" and "dogs chase cats" would mean the same to your system. Also, if you are multiplying, you have to be extra careful or every sentences will end up represented by [0,0,0,...,0], which defeats the point.

Further reading

I will not discuss the more sophisticated methods for composition that have been proposed so far. I suggest you read Katrin Erk's "Vector space models of word meaning and phrase meaning: a survey". This is a very good high-level survey to get you started. Unfortunately, is not freely available on the publisher's website, email the author directly to get a copy. In that paper you will find references to many more concrete methods. The more comprehensible ones are by Mitchel and Lapata (2008) and Baroni and Zamparelli (2010).


Edit after comment by @vpekar: The bottom line of this answer is to stress the fact that while naive methods do exist (e.g. addition, multiplication, surface similarity, etc), these are fundamentally flawed and in general one should not expect great performance from them.

determine DB2 text string length

This will grab records with strings (in the fieldName column) that are 10 characters long:

 select * from table where length(fieldName)=10

TypeError: only length-1 arrays can be converted to Python scalars while plot showing

dataframe['column'].squeeze() should solve this. It basically changes the dataframe column to a list.

Prevent scrolling of parent element when inner element scroll position reaches top/bottom?

jQuery plugin with emulate natural scrolling for Internet Explorer

  $.fn.mousewheelStopPropagation = function(options) {
    options = $.extend({
        // defaults
        wheelstop: null // Function
        }, options);

    // Compatibilities
    var isMsIE = ('Microsoft Internet Explorer' === navigator.appName);
    var docElt = document.documentElement,
        mousewheelEventName = 'mousewheel';
    if('onmousewheel' in docElt) {
        mousewheelEventName = 'mousewheel';
    } else if('onwheel' in docElt) {
        mousewheelEventName = 'wheel';
    } else if('DOMMouseScroll' in docElt) {
        mousewheelEventName = 'DOMMouseScroll';
    }
    if(!mousewheelEventName) { return this; }

    function mousewheelPrevent(event) {
        event.preventDefault();
        event.stopPropagation();
        if('function' === typeof options.wheelstop) {
            options.wheelstop(event);
        }
    }

    return this.each(function() {
        var _this = this,
            $this = $(_this);
        $this.on(mousewheelEventName, function(event) {
            var origiEvent = event.originalEvent;
            var scrollTop = _this.scrollTop,
                scrollMax = _this.scrollHeight - $this.outerHeight(),
                delta = -origiEvent.wheelDelta;
            if(isNaN(delta)) {
                delta = origiEvent.deltaY;
            }
            var scrollUp = delta < 0;
            if((scrollUp && scrollTop <= 0) || (!scrollUp && scrollTop >= scrollMax)) {
                mousewheelPrevent(event);
            } else if(isMsIE) {
                // Fix Internet Explorer and emulate natural scrolling
                var animOpt = { duration:200, easing:'linear' };
                if(scrollUp && -delta > scrollTop) {
                    $this.stop(true).animate({ scrollTop:0 }, animOpt);
                    mousewheelPrevent(event);
                } else if(!scrollUp && delta > scrollMax - scrollTop) {
                    $this.stop(true).animate({ scrollTop:scrollMax }, animOpt);
                    mousewheelPrevent(event);
                }
            }
        });
    });
};

https://github.com/basselin/jquery-mousewheel-stop-propagation/blob/master/mousewheelStopPropagation.js

How to send password using sftp batch file

If you are generating a heap of commands to be run, then call that script from a terminal, you can try the following.

sftp login@host < /path/to/command/list

You will then be asked to enter your password (as per normal) however all the commands in the script run after that.

This is clearly not a completely automated option that can be used in a cron job, but it can be used from a terminal.

*.h or *.hpp for your class definitions

It does not matter which extension you use. Either one is OK.

I use *.h for C and *.hpp for C++.

jquery stop child triggering parent event

Do this:

$(document).ready(function(){
    $(".header").click(function(){
        $(this).children(".children").toggle();
    });
   $(".header a").click(function(e) {
        e.stopPropagation();
   });
});

If you want to read more on .stopPropagation(), look here.

How to always show the vertical scrollbar in a browser?

Here is a method. This will not only provide scrollbar container, but will also show the scrollbar even if content isnt enough (as per your requirement). Would also work on Iphone, and android devices as well..

<style>
    .scrollholder {
        position: relative;
        width: 310px; height: 350px;
        overflow: auto;
        z-index: 1;
    }
</style>

<script>
    function isTouchDevice() {
        try {
            document.createEvent("TouchEvent");
            return true;
        } catch (e) {
            return false;
        }
    }

    function touchScroll(id) {
        if (isTouchDevice()) { //if touch events exist...
            var el = document.getElementById(id);
            var scrollStartPos = 0;

            document.getElementById(id).addEventListener("touchstart", function (event) {
                scrollStartPos = this.scrollTop + event.touches[0].pageY;
                event.preventDefault();
            }, false);

            document.getElementById(id).addEventListener("touchmove", function (event) {
                this.scrollTop = scrollStartPos - event.touches[0].pageY;
                event.preventDefault();
            }, false);
        }
    }
</script>

<body onload="touchScroll('scrollMe')">

    <!-- title -->
    <!-- <div class="title" onselectstart="return false">Alarms</div> -->
    <div class="scrollholder" id="scrollMe">

</div>
</body>

How to use Servlets and Ajax?

Indeed, the keyword is "ajax": Asynchronous JavaScript and XML. However, last years it's more than often Asynchronous JavaScript and JSON. Basically, you let JS execute an asynchronous HTTP request and update the HTML DOM tree based on the response data.

Since it's pretty a tedious work to make it to work across all browsers (especially Internet Explorer versus others), there are plenty of JavaScript libraries out which simplifies this in single functions and covers as many as possible browser-specific bugs/quirks under the hoods, such as jQuery, Prototype, Mootools. Since jQuery is most popular these days, I'll use it in the below examples.

Kickoff example returning String as plain text

Create a /some.jsp like below (note: the code snippets in this answer doesn't expect the JSP file being placed in a subfolder, if you do so, alter servlet URL accordingly from "someservlet" to "${pageContext.request.contextPath}/someservlet"; it's merely omitted from the code snippets for brevity):

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>SO question 4112686</title>
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script>
            $(document).on("click", "#somebutton", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
                $.get("someservlet", function(responseText) {   // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
                    $("#somediv").text(responseText);           // Locate HTML DOM element with ID "somediv" and set its text content with the response text.
                });
            });
        </script>
    </head>
    <body>
        <button id="somebutton">press here</button>
        <div id="somediv"></div>
    </body>
</html>

Create a servlet with a doGet() method which look like this:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String text = "some text";

    response.setContentType("text/plain");  // Set content type of the response so that jQuery knows what it can expect.
    response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
    response.getWriter().write(text);       // Write response body.
}

Map this servlet on an URL pattern of /someservlet or /someservlet/* as below (obviously, the URL pattern is free to your choice, but you'd need to alter the someservlet URL in JS code examples over all place accordingly):

package com.example;

@WebServlet("/someservlet/*")
public class SomeServlet extends HttpServlet {
    // ...
}

Or, when you're not on a Servlet 3.0 compatible container yet (Tomcat 7, Glassfish 3, JBoss AS 6, etc or newer), then map it in web.xml the old fashioned way (see also our Servlets wiki page):

<servlet>
    <servlet-name>someservlet</servlet-name>
    <servlet-class>com.example.SomeServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>someservlet</servlet-name>
    <url-pattern>/someservlet/*</url-pattern>
</servlet-mapping>

Now open the http://localhost:8080/context/test.jsp in the browser and press the button. You'll see that the content of the div get updated with the servlet response.

Returning List<String> as JSON

With JSON instead of plaintext as response format you can even get some steps further. It allows for more dynamics. First, you'd like to have a tool to convert between Java objects and JSON strings. There are plenty of them as well (see the bottom of this page for an overview). My personal favourite is Google Gson. Download and put its JAR file in /WEB-INF/lib folder of your webapplication.

Here's an example which displays List<String> as <ul><li>. The servlet:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    List<String> list = new ArrayList<>();
    list.add("item1");
    list.add("item2");
    list.add("item3");
    String json = new Gson().toJson(list);

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

The JS code:

$(document).on("click", "#somebutton", function() {  // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
    $.get("someservlet", function(responseJson) {    // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
        var $ul = $("<ul>").appendTo($("#somediv")); // Create HTML <ul> element and append it to HTML DOM element with ID "somediv".
        $.each(responseJson, function(index, item) { // Iterate over the JSON array.
            $("<li>").text(item).appendTo($ul);      // Create HTML <li> element, set its text content with currently iterated item and append it to the <ul>.
        });
    });
});

Do note that jQuery automatically parses the response as JSON and gives you directly a JSON object (responseJson) as function argument when you set the response content type to application/json. If you forget to set it or rely on a default of text/plain or text/html, then the responseJson argument wouldn't give you a JSON object, but a plain vanilla string and you'd need to manually fiddle around with JSON.parse() afterwards, which is thus totally unnecessary if you set the content type right in first place.

Returning Map<String, String> as JSON

Here's another example which displays Map<String, String> as <option>:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Map<String, String> options = new LinkedHashMap<>();
    options.put("value1", "label1");
    options.put("value2", "label2");
    options.put("value3", "label3");
    String json = new Gson().toJson(options);

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

And the JSP:

$(document).on("click", "#somebutton", function() {               // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
    $.get("someservlet", function(responseJson) {                 // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
        var $select = $("#someselect");                           // Locate HTML DOM element with ID "someselect".
        $select.find("option").remove();                          // Find all child elements with tag name "option" and remove them (just to prevent duplicate options when button is pressed again).
        $.each(responseJson, function(key, value) {               // Iterate over the JSON object.
            $("<option>").val(key).text(value).appendTo($select); // Create HTML <option> element, set its value with currently iterated key and its text content with currently iterated item and finally append it to the <select>.
        });
    });
});

with

<select id="someselect"></select>

Returning List<Entity> as JSON

Here's an example which displays List<Product> in a <table> where the Product class has the properties Long id, String name and BigDecimal price. The servlet:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    List<Product> products = someProductService.list();
    String json = new Gson().toJson(products);

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

The JS code:

$(document).on("click", "#somebutton", function() {        // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
    $.get("someservlet", function(responseJson) {          // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
        var $table = $("<table>").appendTo($("#somediv")); // Create HTML <table> element and append it to HTML DOM element with ID "somediv".
        $.each(responseJson, function(index, product) {    // Iterate over the JSON array.
            $("<tr>").appendTo($table)                     // Create HTML <tr> element, set its text content with currently iterated item and append it to the <table>.
                .append($("<td>").text(product.id))        // Create HTML <td> element, set its text content with id of currently iterated product and append it to the <tr>.
                .append($("<td>").text(product.name))      // Create HTML <td> element, set its text content with name of currently iterated product and append it to the <tr>.
                .append($("<td>").text(product.price));    // Create HTML <td> element, set its text content with price of currently iterated product and append it to the <tr>.
        });
    });
});

Returning List<Entity> as XML

Here's an example which does effectively the same as previous example, but then with XML instead of JSON. When using JSP as XML output generator you'll see that it's less tedious to code the table and all. JSTL is this way much more helpful as you can actually use it to iterate over the results and perform server side data formatting. The servlet:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    List<Product> products = someProductService.list();

    request.setAttribute("products", products);
    request.getRequestDispatcher("/WEB-INF/xml/products.jsp").forward(request, response);
}

The JSP code (note: if you put the <table> in a <jsp:include>, it may be reusable elsewhere in a non-ajax response):

<?xml version="1.0" encoding="UTF-8"?>
<%@page contentType="application/xml" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<data>
    <table>
        <c:forEach items="${products}" var="product">
            <tr>
                <td>${product.id}</td>
                <td><c:out value="${product.name}" /></td>
                <td><fmt:formatNumber value="${product.price}" type="currency" currencyCode="USD" /></td>
            </tr>
        </c:forEach>
    </table>
</data>

The JS code:

$(document).on("click", "#somebutton", function() {             // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
    $.get("someservlet", function(responseXml) {                // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response XML...
        $("#somediv").html($(responseXml).find("data").html()); // Parse XML, find <data> element and append its HTML to HTML DOM element with ID "somediv".
    });
});

You'll by now probably realize why XML is so much more powerful than JSON for the particular purpose of updating a HTML document using Ajax. JSON is funny, but after all generally only useful for so-called "public web services". MVC frameworks like JSF use XML under the covers for their ajax magic.

Ajaxifying an existing form

You can use jQuery $.serialize() to easily ajaxify existing POST forms without fiddling around with collecting and passing the individual form input parameters. Assuming an existing form which works perfectly fine without JavaScript/jQuery (and thus degrades gracefully when enduser has JavaScript disabled):

<form id="someform" action="someservlet" method="post">
    <input type="text" name="foo" />
    <input type="text" name="bar" />
    <input type="text" name="baz" />
    <input type="submit" name="submit" value="Submit" />
</form>

You can progressively enhance it with ajax as below:

$(document).on("submit", "#someform", function(event) {
    var $form = $(this);

    $.post($form.attr("action"), $form.serialize(), function(response) {
        // ...
    });

    event.preventDefault(); // Important! Prevents submitting the form.
});

You can in the servlet distinguish between normal requests and ajax requests as below:

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String foo = request.getParameter("foo");
    String bar = request.getParameter("bar");
    String baz = request.getParameter("baz");

    boolean ajax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));

    // ...

    if (ajax) {
        // Handle ajax (JSON or XML) response.
    } else {
        // Handle regular (JSP) response.
    }
}

The jQuery Form plugin does less or more the same as above jQuery example, but it has additional transparent support for multipart/form-data forms as required by file uploads.

Manually sending request parameters to servlet

If you don't have a form at all, but just wanted to interact with the servlet "in the background" whereby you'd like to POST some data, then you can use jQuery $.param() to easily convert a JSON object to an URL-encoded query string.

var params = {
    foo: "fooValue",
    bar: "barValue",
    baz: "bazValue"
};

$.post("someservlet", $.param(params), function(response) {
    // ...
});

The same doPost() method as shown here above can be reused. Do note that above syntax also works with $.get() in jQuery and doGet() in servlet.

Manually sending JSON object to servlet

If you however intend to send the JSON object as a whole instead of as individual request parameters for some reason, then you'd need to serialize it to a string using JSON.stringify() (not part of jQuery) and instruct jQuery to set request content type to application/json instead of (default) application/x-www-form-urlencoded. This can't be done via $.post() convenience function, but needs to be done via $.ajax() as below.

var data = {
    foo: "fooValue",
    bar: "barValue",
    baz: "bazValue"
};

$.ajax({
    type: "POST",
    url: "someservlet",
    contentType: "application/json", // NOT dataType!
    data: JSON.stringify(data),
    success: function(response) {
        // ...
    }
});

Do note that a lot of starters mix contentType with dataType. The contentType represents the type of the request body. The dataType represents the (expected) type of the response body, which is usually unnecessary as jQuery already autodetects it based on response's Content-Type header.

Then, in order to process the JSON object in the servlet which isn't being sent as individual request parameters but as a whole JSON string the above way, you only need to manually parse the request body using a JSON tool instead of using getParameter() the usual way. Namely, servlets don't support application/json formatted requests, but only application/x-www-form-urlencoded or multipart/form-data formatted requests. Gson also supports parsing a JSON string into a JSON object.

JsonObject data = new Gson().fromJson(request.getReader(), JsonObject.class);
String foo = data.get("foo").getAsString();
String bar = data.get("bar").getAsString();
String baz = data.get("baz").getAsString();
// ...

Do note that this all is more clumsy than just using $.param(). Normally, you want to use JSON.stringify() only if the target service is e.g. a JAX-RS (RESTful) service which is for some reason only capable of consuming JSON strings and not regular request parameters.

Sending a redirect from servlet

Important to realize and understand is that any sendRedirect() and forward() call by the servlet on an ajax request would only forward or redirect the ajax request itself and not the main document/window where the ajax request originated. JavaScript/jQuery would in such case only retrieve the redirected/forwarded response as responseText variable in the callback function. If it represents a whole HTML page and not an ajax-specific XML or JSON response, then all you could do is to replace the current document with it.

document.open();
document.write(responseText);
document.close();

Note that this doesn't change the URL as enduser sees in browser's address bar. So there are issues with bookmarkability. Therefore, it's much better to just return an "instruction" for JavaScript/jQuery to perform a redirect instead of returning the whole content of the redirected page. E.g. by returning a boolean, or an URL.

String redirectURL = "http://example.com";

Map<String, String> data = new HashMap<>();
data.put("redirect", redirectURL);
String json = new Gson().toJson(data);

response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
function(responseJson) {
    if (responseJson.redirect) {
        window.location = responseJson.redirect;
        return;
    }

    // ...
}

See also:

SSL cert "err_cert_authority_invalid" on mobile chrome only

I just spent the morning dealing with this. The problem wasn't that I had a certificate missing. It was that I had an extra.

I started out with my ssl.conf containing my server key and three files provided by my SSL certificate authority:

#   Server Certificate:
SSLCertificateFile /etc/pki/tls/certs/myserver.cer

#   Server Private Key:
SSLCertificateKeyFile /etc/pki/tls/private/myserver.key

#   Server Certificate Chain:
SSLCertificateChainFile /etc/pki/tls/certs/AddTrustExternalCARoot.pem

#   Certificate Authority (CA):
SSLCACertificateFile /etc/pki/tls/certs/InCommonServerCA.pem

It worked fine on desktops, but Chrome on Android gave me err_cert_authority_invalid

A lot of headaches, searching and poor documentation later, I figured out that it was the Server Certificate Chain:

SSLCertificateChainFile /etc/pki/tls/certs/AddTrustExternalCARoot.pem

That was creating a second certificate chain which was incomplete. I commented out that line, leaving me with

#   Server Certificate:
SSLCertificateFile /etc/pki/tls/certs/myserver.cer

#   Server Private Key:
SSLCertificateKeyFile /etc/pki/tls/private/myserver.key

#   Certificate Authority (CA):
SSLCACertificateFile /etc/pki/tls/certs/InCommonServerCA.pem

and now it's working on Android again. This was on Linux running Apache 2.2.

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

ORDER BY column OFFSET 0 ROWS

Surprisingly makes it work, what a strange feature.

A bigger example with a CTE as a way to temporarily "store" a long query to re-order it later:

;WITH cte AS (
    SELECT .....long select statement here....
)

SELECT * FROM 
(
    SELECT * FROM 
    ( -- necessary to nest selects for union to work with where & order clauses
        SELECT * FROM cte WHERE cte.MainCol= 1 ORDER BY cte.ColX asc OFFSET 0 ROWS 
    ) first
    UNION ALL
    SELECT * FROM 
    (  
        SELECT * FROM cte WHERE cte.MainCol = 0 ORDER BY cte.ColY desc OFFSET 0 ROWS 
    ) last
) as unionized
ORDER BY unionized.MainCol desc -- all rows ordered by this one
OFFSET @pPageSize * @pPageOffset ROWS -- params from stored procedure for pagination, not relevant to example
FETCH FIRST @pPageSize ROWS ONLY -- params from stored procedure for pagination, not relevant to example

So we get all results ordered by MainCol

But the results with MainCol = 1 get ordered by ColX

And the results with MainCol = 0 get ordered by ColY

Intellij IDEA Java classes not auto compiling on save

I was getting error: some jars are not in classpath.So I just delete the corrupted jar and perrform below steps

1.Project >  Setting>Build,Execution,Deployment>Compiler>check build project automatically
2.CTRL+SHIFT+A find/search **registry** --Check for below param
compiler.automake.allow.when.app.running
compiler.automake.trigger.delay=500---According to ur requirement
3.Add devtool in pom.xml
         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
4.Build ,If found any probelm while building ,saying some jar in not in class path.Just delete the corrupted jar
and re-build the project angain after sync with maven lib

How can I list all the deleted files in a Git repository?

git log --diff-filter=D --summary

See Find and restore a deleted file in a Git repository

If you don't want all the information about which commit they were removed in, you can just add a grep delete in there.

git log --diff-filter=D --summary | grep delete

How to get the file-path of the currently executing javascript code

Refining upon the answers found here I came up with the following:

getCurrentScript.js

var getCurrentScript = function () {
  if (document.currentScript) {
    return document.currentScript.src;
  } else {
    var scripts = document.getElementsByTagName('script');
    return scripts[scripts.length-1].src;

  }
};

module.exports = getCurrentScript;

getCurrentScriptPath.js

var getCurrentScript = require('./getCurrentScript');

var getCurrentScriptPath = function () {
  var script = getCurrentScript();
  var path = script.substring(0, script.lastIndexOf('/'));
  return path;
};

module.exports = getCurrentScriptPath;

BTW: I'm using CommonJS module format and bundling with webpack.

What is the difference between a URI, a URL and a URN?

A URI identifies a resource either by location, or a name, or both. More often than not, most of us use URIs that defines a location to a resource. The fact that a URI can identify a resources by both name and location has lead to a lot of the confusion in my opinion. A URI has two specializations known as URL and URN.

A URL is a specialization of URI that defines the network location of a specific resource. Unlike a URN, the URL defines how the resource can be obtained. We use URLs every day in the form of http://stackoverflow.com, etc. But a URL doesn’t have to be an HTTP URL, it can be ftp://example.com, etc.

How to remove all click event handlers using jQuery?

Is there a way to remove all previous click events that have been assigned to a button?

$('#saveBtn').unbind('click').click(function(){saveQuestion(id)});

Convert Enum to String

All of these internally end up calling a method called InternalGetValueAsString. The difference between ToString and GetName would be that GetName has to verify a few things first:

  1. The type you entered isn't null.
  2. The type you entered is, in fact an enumeration.
  3. The value you passed in isn't null.
  4. The value you passed in is of a type that an enumeration can actually use as it's underlying type, or of the type of the enumeration itself. It uses GetType on the value to check this.

.ToString doesn't have to worry about any of these above issues, because it is called on an instance of the class itself, and not on a passed in version, therefore, due to the fact that the .ToString method doesn't have the same verification issues as the static methods, I would conclude that .ToString is the fastest way to get the value as a string.

How do you add CSS with Javascript?

if you know at least one <style> tag exist in page , use this function :

CSS=function(i){document.getElementsByTagName('style')[0].innerHTML+=i};

usage :

CSS("div{background:#00F}");

Keep getting No 'Access-Control-Allow-Origin' error with XMLHttpRequest

Your server's response allows the request to include three specific non-simple headers:

Access-Control-Allow-Headers:origin, x-requested-with, content-type

but your request has a header not allowed by the server's response:

Access-Control-Request-Headers:access-control-allow-origin, content-type

All non-simple headers sent in a CORS request must be explicitly allowed by the Access-Control-Allow-Headers response header. The unnecessary Access-Control-Allow-Origin header sent in your request is not allowed by the server's CORS response. This is exactly what the "...not allowed by Access-Control-Allow-Headers" error message was trying to tell you.

There is no reason for the request to have this header: it does nothing, because Access-Control-Allow-Origin is a response header, not a request header.

Solution: Remove the setRequestHeader call that adds a Access-Control-Allow-Origin header to your request.

Writing outputs to log file and console

I have found a way to get the desired output. Though it may be somewhat unorthodox way. Anyways here it goes. In the redir.env file I have following code:

#####redir.env#####    
export LOG_FILE=log.txt

      exec 2>>${LOG_FILE}

    function log {
     echo "$1">>${LOG_FILE}
    }

    function message {
     echo "$1"
     echo "$1">>${LOG_FILE}
    }

Then in the actual script I have the following codes:

#!/bin/sh 
. redir.env
echo "Echoed to console only"
log "Written to log file only"
message "To console and log"
echo "This is stderr. Written to log file only" 1>&2

Here echo outputs only to console, log outputs to only log file and message outputs to both the log file and console.

After executing the above script file I have following outputs:

In console

In console
Echoed to console only
To console and log

For the Log file

In Log File Written to log file only
This is stderr. Written to log file only
To console and log

Hope this help.

Styling HTML5 input type number

<input type="number" name="numericInput" size="2" min="0" maxlength="2" value="0" />

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

str = str.replace(',', '.')

should do the trick.

What is "stdafx.h" used for in Visual Studio?

I just ran into this myself since I'm trying to create myself a bare bones framework but started out by creating a new Win32 Program option in Visual Studio 2017. "stdafx.h" is unnecessary and should be removed. Then you can remove the stupid "stdafx.h" and "stdafx.cpp" that is in your Solution Explorer as well as the files from your project. In it's place, you'll need to put

#include <Windows.h>

instead.

How to increment variable under DOS?

I built my answer thanks to previous contributors.

Not having time for a custom counter.exe, I downloaded sed for FREEDOS.

And then the batch code could be, emulating "wc -l" with the utility sed, something like this according to your loop (I just use it to increment through executions starting from "1" to n+1):

Just remember to manually create a file "test.txt" with written on the first row

0


sed -n '$=' test.txt > counter.txt
set /P Var=< counter.txt
echo 0 >> test.txt

How do I convert a dictionary to a JSON String in C#?

It seems a lot of different libraries and what not have seem to come and go over the previous years. However as of April 2016, this solution worked well for me. Strings easily replaced by ints.

TL/DR; Copy this if that's what you came here for:

    //outputfilename will be something like: "C:/MyFolder/MyFile.txt"
    void WriteDictionaryAsJson(Dictionary<string, List<string>> myDict, string outputfilename)
    {
        DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(Dictionary<string, List<string>>));
        MemoryStream ms = new MemoryStream();
        js.WriteObject(ms, myDict); //Does the serialization.

        StreamWriter streamwriter = new StreamWriter(outputfilename);
        streamwriter.AutoFlush = true; // Without this, I've run into issues with the stream being "full"...this solves that problem.

        ms.Position = 0; //ms contains our data in json format, so let's start from the beginning
        StreamReader sr = new StreamReader(ms); //Read all of our memory
        streamwriter.WriteLine(sr.ReadToEnd()); // and write it out.

        ms.Close(); //Shutdown everything since we're done.
        streamwriter.Close();
        sr.Close();
    }

Two import points. First, be sure to add System.Runtime.Serliazation as a reference in your project inside Visual Studio's Solution Explorer. Second, add this line,

using System.Runtime.Serialization.Json;

at the top of the file with the rest of your usings, so the DataContractJsonSerializer class can be found. This blog post has more information on this method of serialization.

Data Format (Input / Output)

My data is a dictionary with 3 strings, each pointing to a list of strings. The lists of strings have lengths 3, 4, and 1. The data looks like this:

StringKeyofDictionary1 => ["abc","def","ghi"]
StringKeyofDictionary2 => ["String01","String02","String03","String04"]
Stringkey3 => ["someString"]

The output written to file will be on one line, here is the formatted output:

 [{
     "Key": "StringKeyofDictionary1",
     "Value": ["abc",
     "def",
     "ghi"]
 },
 {
     "Key": "StringKeyofDictionary2",
     "Value": ["String01",
     "String02",
     "String03",
     "String04",
 ]
 },
 {
     "Key": "Stringkey3",
     "Value": ["SomeString"]
 }]

How does one check if a table exists in an Android SQLite database?

You mentioned that you've created an class that extends SQLiteOpenHelper and implemented the onCreate method. Are you making sure that you're performing all your database acquire calls with that class? You should only be getting SQLiteDatabase objects via the SQLiteOpenHelper#getWritableDatabase and getReadableDatabase otherwise the onCreate method will not be called when necessary. If you are doing that already check and see if th SQLiteOpenHelper#onUpgrade method is being called instead. If so, then the database version number was changed at some point in time but the table was never created properly when that happened.

As an aside, you can force the recreation of the database by making sure all connections to it are closed and calling Context#deleteDatabase and then using the SQLiteOpenHelper to give you a new db object.

HTML tag <a> want to add both href and onclick working

No jQuery needed.

Some people say using onclick is bad practice...

This example uses pure browser javascript. By default, it appears that the click handler will evaluate before the navigation, so you can cancel the navigation and do your own if you wish.

<a id="myButton" href="http://google.com">Click me!</a>
<script>
    window.addEventListener("load", () => {
        document.querySelector("#myButton").addEventListener("click", e => {
            alert("Clicked!");
            // Can also cancel the event and manually navigate
            // e.preventDefault();
            // window.location = e.target.href;
        });
    });
</script>

Determine if map contains a value for a key?

To succinctly summarize some of the other answers:

If you're not using C++ 20 yet, you can write your own mapContainsKey function:

bool mapContainsKey(std::map<int, int>& map, int key)
{
  if (map.find(key) == map.end()) return false;
  return true;
}

If you'd like to avoid many overloads for map vs unordered_map and different key and value types, you can make this a template function.

If you're using C++ 20 or later, there will be a built-in contains function:

std::map<int, int> myMap;

// do stuff with myMap here

int key = 123;

if (myMap.contains(key))
{
  // stuff here
}

Are string.Equals() and == operator really same?

There are plenty of descriptive answers here so I'm not going to repeat what has already been said. What I would like to add is the following code demonstrating all the permutations I can think of. The code is quite long due to the number of combinations. Feel free to drop it into MSTest and see the output for yourself (the output is included at the bottom).

This evidence supports Jon Skeet's answer.

Code:

[TestMethod]
public void StringEqualsMethodVsOperator()
{
    string s1 = new StringBuilder("string").ToString();
    string s2 = new StringBuilder("string").ToString();

    Debug.WriteLine("string a = \"string\";");
    Debug.WriteLine("string b = \"string\";");

    TryAllStringComparisons(s1, s2);

    s1 = null;
    s2 = null;

    Debug.WriteLine(string.Join(string.Empty, Enumerable.Repeat("-", 20)));
    Debug.WriteLine(string.Empty);
    Debug.WriteLine("string a = null;");
    Debug.WriteLine("string b = null;");

    TryAllStringComparisons(s1, s2);
}
private void TryAllStringComparisons(string s1, string s2)
{
    Debug.WriteLine(string.Empty);
    Debug.WriteLine("-- string.Equals --");
    Debug.WriteLine(string.Empty);
    Try((a, b) => string.Equals(a, b), s1, s2);
    Try((a, b) => string.Equals((object)a, b), s1, s2);
    Try((a, b) => string.Equals(a, (object)b), s1, s2);
    Try((a, b) => string.Equals((object)a, (object)b), s1, s2);

    Debug.WriteLine(string.Empty);
    Debug.WriteLine("-- object.Equals --");
    Debug.WriteLine(string.Empty);
    Try((a, b) => object.Equals(a, b), s1, s2);
    Try((a, b) => object.Equals((object)a, b), s1, s2);
    Try((a, b) => object.Equals(a, (object)b), s1, s2);
    Try((a, b) => object.Equals((object)a, (object)b), s1, s2);

    Debug.WriteLine(string.Empty);
    Debug.WriteLine("-- a.Equals(b) --");
    Debug.WriteLine(string.Empty);
    Try((a, b) => a.Equals(b), s1, s2);
    Try((a, b) => a.Equals((object)b), s1, s2);
    Try((a, b) => ((object)a).Equals(b), s1, s2);
    Try((a, b) => ((object)a).Equals((object)b), s1, s2);

    Debug.WriteLine(string.Empty);
    Debug.WriteLine("-- a == b --");
    Debug.WriteLine(string.Empty);
    Try((a, b) => a == b, s1, s2);
#pragma warning disable 252
    Try((a, b) => (object)a == b, s1, s2);
#pragma warning restore 252
#pragma warning disable 253
    Try((a, b) => a == (object)b, s1, s2);
#pragma warning restore 253
    Try((a, b) => (object)a == (object)b, s1, s2);
}
public void Try<T1, T2, T3>(Expression<Func<T1, T2, T3>> tryFunc, T1 in1, T2 in2)
{
    T3 out1;

    Try(tryFunc, e => { }, in1, in2, out out1);
}
public bool Try<T1, T2, T3>(Expression<Func<T1, T2, T3>> tryFunc, Action<Exception> catchFunc, T1 in1, T2 in2, out T3 out1)
{
    bool success = true;
    out1 = default(T3);

    try
    {
        out1 = tryFunc.Compile()(in1, in2);
        Debug.WriteLine("{0}: {1}", tryFunc.Body.ToString(), out1);
    }
    catch (Exception ex)
    {
        Debug.WriteLine("{0}: {1} - {2}", tryFunc.Body.ToString(), ex.GetType().ToString(), ex.Message);
        success = false;
        catchFunc(ex);
    }

    return success;
}

Output:

string a = "string";
string b = "string";

-- string.Equals --

Equals(a, b): True
Equals(Convert(a), b): True
Equals(a, Convert(b)): True
Equals(Convert(a), Convert(b)): True

-- object.Equals --

Equals(a, b): True
Equals(Convert(a), b): True
Equals(a, Convert(b)): True
Equals(Convert(a), Convert(b)): True

-- a.Equals(b) --

a.Equals(b): True
a.Equals(Convert(b)): True
Convert(a).Equals(b): True
Convert(a).Equals(Convert(b)): True

-- a == b --

(a == b): True
(Convert(a) == b): False
(a == Convert(b)): False
(Convert(a) == Convert(b)): False
--------------------

string a = null;
string b = null;

-- string.Equals --

Equals(a, b): True
Equals(Convert(a), b): True
Equals(a, Convert(b)): True
Equals(Convert(a), Convert(b)): True

-- object.Equals --

Equals(a, b): True
Equals(Convert(a), b): True
Equals(a, Convert(b)): True
Equals(Convert(a), Convert(b)): True

-- a.Equals(b) --

a.Equals(b): System.NullReferenceException - Object reference not set to an instance of an object.
a.Equals(Convert(b)): System.NullReferenceException - Object reference not set to an instance of an object.
Convert(a).Equals(b): System.NullReferenceException - Object reference not set to an instance of an object.
Convert(a).Equals(Convert(b)): System.NullReferenceException - Object reference not set to an instance of an object.

-- a == b --

(a == b): True
(Convert(a) == b): True
(a == Convert(b)): True
(Convert(a) == Convert(b)): True

Using Mockito to mock classes with generic parameters

One other way around this is to use @Mock annotation instead. Doesn't work in all cases, but looks much sexier :)

Here's an example:

@RunWith(MockitoJUnitRunner.class)
public class FooTests {

    @Mock
    public Foo<Bar> fooMock;

    @Test
    public void testFoo() {
        when(fooMock.getValue()).thenReturn(new Bar());
    }
}

The MockitoJUnitRunner initializes the fields annotated with @Mock.

Is there a combination of "LIKE" and "IN" in SQL?

do this

WHERE something + '%' in ('bla', 'foo', 'batz')
OR '%' + something + '%' in ('tra', 'la', 'la')

or

WHERE something + '%' in (select col from table where ....)

How to declare a constant in Java

final means that the value cannot be changed after initialization, that's what makes it a constant. static means that instead of having space allocated for the field in each object, only one instance is created for the class.

So, static final means only one instance of the variable no matter how many objects are created and the value of that variable can never change.

where to place CASE WHEN column IS NULL in this query

Try this:

CASE WHEN table3.col3 IS NULL THEN table2.col3 ELSE table3.col3 END as col4

The as col4 should go at the end of the CASE the statement. Also note that you're missing the END too.

Another probably more simple option would be:

IIf([table3.col3] Is Null,[table2.col3],[table3.col3])

Just to clarify, MS Access does not support COALESCE. If it would that would be the best way to go.

Edit after radical question change:

To turn the query into SQL Server then you can use COALESCE (so it was technically answered before too):

SELECT dbo.AdminID.CountryID, dbo.AdminID.CountryName, dbo.AdminID.RegionID, 
dbo.AdminID.[Region name], dbo.AdminID.DistrictID, dbo.AdminID.DistrictName,
dbo.AdminID.ADMIN3_ID, dbo.AdminID.ADMIN3,
COALESCE(dbo.EU_Admin3.EUID, dbo.EU_Admin2.EUID)
FROM dbo.AdminID

BTW, your CASE statement was missing a , before the field. That's why it didn't work.

How to use JUnit to test asynchronous processes

How about calling SomeObject.wait and notifyAll as described here OR using Robotiums Solo.waitForCondition(...) method OR use a class i wrote to do this (see comments and test class for how to use)

The request failed or the service did not respond in a timely fashion?

Above mentioned issue happened in my local system. Check in sql server configuration manager.
Step 1:
SQL server Network configuration
step 2:

  • Protocols for local server name
  • Protocol name VIA Disabled or not..
  • if not disabled , disable and check

.. after I made changes the sql server browser started working

Laravel-5 'LIKE' equivalent (Eloquent)

I think this is better, following the good practices of passing parameters to the query:

BookingDates::whereRaw('email = ? or name like ?', [$request->email,"%{$request->name}%"])->get();

You can see it in the documentation, Laravel 5.5.

You can also use the Laravel scout and make it easier with search. Here is the documentation.

iterating through Enumeration of hastable keys throws NoSuchElementException error

for (String key : Collections.list(e))
    System.out.println(key);

symfony 2 No route found for "GET /"

The above answers are wrong, respectively aren't answering why you're having troubles viewing the demo-content prod-mode.

Here's the correct answer: clear your "prod"-cache:

php app/console cache:clear --env prod

Is there a way to word-wrap long words in a div?

As david mentions, DIVs do wrap words by default.

If you are referring to really long strings of text without spaces, what I do is process the string server-side and insert empty spans:

thisIsAreallyLongStringThatIWantTo<span></span>BreakToFitInsideAGivenSpace

It's not exact as there are issues with font-sizing and such. The span option works if the container is variable in size. If it's a fixed width container, you could just go ahead and insert line breaks.

Angularjs error Unknown provider

Make sure you are loading those modules (myApp.services and myApp.directives) as dependencies of your main app module, like this:

angular.module('myApp', ['myApp.directives', 'myApp.services']);

plunker: http://plnkr.co/edit/wxuFx6qOMfbuwPq1HqeM?p=preview

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

Dim myRow() As Data.DataRow
myRow = dt.Select("MyColumnName = 'SomeColumnTitle'")
myRow(0)("SomeOtherColumnTitle") = strValue

Code above instantiates a DataRow. Where "dt" is a DataTable, you get a row by selecting any column (I know, sounds backwards). Then you can then set the value of whatever row you want (I chose the first row, or "myRow(0)"), for whatever column you want.

How to make/get a multi size .ico file?

Fresh answer 2018:

Step 1 Launch Microsoft Paint. Not Paint.Net but plain Paint

Step 2 Open the image you want to convert to icon format by clicking the “Paint” toolbar tab and selecting “Open.”

Step 3 Click the “Paint” tab, highlight the “Save As” option and select the “BMP picture” option. As 256-colored. There is a dropdown list.

Step 4 You have to open it in Paint.net now. Enter a file name for the icon and type “.ico” (without quotations) as the file extension. Select your preferred output folder for the icon and click “Save.”(still in bmp type) , exposing auto definition in saving parameters window.

This is a solution for those WHO DOESN'T WANT THE THIRD PARTY APPS TO GAIN PERMISSIONS ON THEIR COMP.
I use this simple way to create custom icons for folders on my desktop or documents.

PHP Error: Cannot use object of type stdClass as array (array and object issues)

The example you copied from is using data in the form of an array holding arrays, you are using data in the form of an array holding objects. Objects and arrays are not the same, and because of this they use different syntaxes for accessing data.

If you don't know the variable names, just do a var_dump($blog); within the loop to see them.

The simplest method - access $blog as an object directly:

Try (assuming those variables are correct):

<?php 
    foreach ($blogs as $blog) {
        $id         = $blog->id;
        $title      = $blog->title;
        $content    = $blog->content;
?>

<h1> <?php echo $title; ?></h1>
<h1> <?php echo $content; ?> </h1>

<?php } ?>

The alternative method - access $blog as an array:

Alternatively, you may be able to turn $blog into an array with get_object_vars (documentation):

<?php
    foreach($blogs as &$blog) {
        $blog     = get_object_vars($blog);
        $id       = $blog['id'];
        $title    = $blog['title'];
        $content  = $blog['content'];
?>

<h1> <?php echo $title; ?></h1>
<h1> <?php echo $content; ?> </h1>

<?php } ?> 

It's worth mentioning that this isn't necessarily going to work with nested objects so its viability entirely depends on the structure of your $blog object.

Better than either of the above - Inline PHP Syntax

Having said all that, if you want to use PHP in the most readable way, neither of the above are right. When using PHP intermixed with HTML, it's considered best practice by many to use PHP's alternative syntax, this would reduce your whole code from nine to four lines:

<?php foreach($blogs as $blog): ?>
    <h1><?php echo $blog->title; ?></h1>
    <p><?php echo $blog->content; ?></p>
<?php endforeach; ?>

Hope this helped.

How to get value of checked item from CheckedListBox?

foreach (int x in chklstTerms.CheckedIndices)
{
    chklstTerms.SelectedIndex=x;
    termids.Add(chklstTerms.SelectedValue.ToString());
}

.prop() vs .attr()

.attr():

  • Get the value of an attribute for the first element in the set of matched elements.
  • Gives you the value of element as it was defined in the html on page load

.prop():

  • Get the value of a property for the first element in the set of matched elements.
  • Gives the updated values of elements which is modified via javascript/jquery

How do I convert datetime to ISO 8601 in PHP

Object Oriented

This is the recommended way.

$datetime = new DateTime('2010-12-30 23:21:46');

echo $datetime->format(DateTime::ATOM); // Updated ISO8601

Procedural

For older versions of PHP, or if you are more comfortable with procedural code.

echo date(DATE_ISO8601, strtotime('2010-12-30 23:21:46'));

What's "this" in JavaScript onclick?

keyword this in addEventListener event

_x000D_
_x000D_
function getValue(o) {_x000D_
  alert(o.innerHTML);_x000D_
}_x000D_
_x000D_
function hide(current) {_x000D_
  current.setAttribute("style", "display: none");_x000D_
}_x000D_
_x000D_
var bullet = document.querySelectorAll(".bullet");_x000D_
_x000D_
for (var x in bullet) { _x000D_
  bullet[x].onclick = function() {_x000D_
    hide(this);_x000D_
  };_x000D_
};_x000D_
 _x000D_
/* Using dynamic DOM Event */_x000D_
document.querySelector("#li").addEventListener("click", function() {_x000D_
  getValue(this); /* this = document.querySelector("#li") Object */_x000D_
});
_x000D_
li {_x000D_
  cursor: pointer;_x000D_
}
_x000D_
<ul>_x000D_
  <li onclick="getValue(this);">A</li>_x000D_
  <li id="li" >B</li>_x000D_
  <hr />_x000D_
  <li class="bullet" >1</li>_x000D_
  <li class="bullet" >2</li>_x000D_
  <li class="bullet" >3</li>_x000D_
  <li class="bullet" >4</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

How to add RSA key to authorized_keys file?

mkdir -p ~/.ssh/

To overwrite authorized_keys

cat your_key > ~/.ssh/authorized_keys

To append to the end of authorized_keys

cat your_key >> ~/.ssh/authorized_keys

Can someone explain __all__ in Python?

Short answer

__all__ affects from <module> import * statements.

Long answer

Consider this example:

foo
+-- bar.py
+-- __init__.py

In foo/__init__.py:

  • (Implicit) If we don't define __all__, then from foo import * will only import names defined in foo/__init__.py.

  • (Explicit) If we define __all__ = [], then from foo import * will import nothing.

  • (Explicit) If we define __all__ = [ <name1>, ... ], then from foo import * will only import those names.

Note that in the implicit case, python won't import names starting with _. However, you can force importing such names using __all__.

You can view the Python document here.

How to change FontSize By JavaScript?

<span id="span">HOI</span>
<script>
   var span = document.getElementById("span");
   console.log(span);

   span.style.fontSize = "25px";
   span.innerHTML = "String";
</script>

You have two errors in your code:

  1. document.getElementById - This retrieves the element with an Id that is "span", you did not specify an id on the span-element.

  2. Capitals in Javascript - Also you forgot the capital of Size.

PostgreSQL error 'Could not connect to server: No such file or directory'

for me command rm /usr/local/var/postgres/postmaster.pid didn't work cause I installed a specific version of postgresql with homebrew.

the right command is rm /usr/local/var/postgres@10/postmaster.pid.

then brew services restart postgresql@10.

PHPmailer sending HTML CODE

// Excuse my beginner's english

There is msgHTML() method, which, also, call IsHTML().

Hrm... name IsHTML is confusing...

/**
 * Create a message from an HTML string.
 * Automatically makes modifications for inline images and backgrounds
 * and creates a plain-text version by converting the HTML.
 * Overwrites any existing values in $this->Body and $this->AltBody
 * @access public
 * @param string $message HTML message string
 * @param string $basedir baseline directory for path
 * @param bool $advanced Whether to use the advanced HTML to text converter
 * @return string $message
 */
public function msgHTML($message, $basedir = '', $advanced = false)

Less aggressive compilation with CSS3 calc

A very common usecase of calc is take 100% width and adding some margin around the element.

One can do so with:

@someMarginVariable = 15px;

margin: @someMarginVariable;
width: calc(~"100% - "@someMarginVariable*2);
width: -moz-calc(~"100% - "@someMarginVariable*2);
width: -webkit-calc(~"100% - "@someMarginVariable*2);

How to save and load numpy.array() data properly?

np.fromfile() has a sep= keyword argument:

Separator between items if file is a text file. Empty (“”) separator means the file should be treated as binary. Spaces (” ”) in the separator match zero or more whitespace characters. A separator consisting only of spaces must match at least one whitespace.

The default value of sep="" means that np.fromfile() tries to read it as a binary file rather than a space-separated text file, so you get nonsense values back. If you use np.fromfile('markers.txt', sep=" ") you will get the result you are looking for.

However, as others have pointed out, np.loadtxt() is the preferred way to convert text files to numpy arrays, and unless the file needs to be human-readable it is usually better to use binary formats instead (e.g. np.load()/np.save()).

What is the best way to get the minimum or maximum value from an Array of numbers?

This depends on real world application requirements.

If your question is merely hypothetical, then the basics have already been explained. It is a typical search vs. sort problem. It has already been mentioned that algorithmically you are not going to achieve better than O(n) for that case.

However, if you are looking at practical use, things get more interesting. You would then need to consider how large the array is, and the processes involved in adding and removing from the data set. In these cases, it can be best to take the computational 'hit' at insertion / removal time by sorting on the fly. Insertions into a pre-sorted array are not that expensive.

The quickest query response to the Min Max request will always be from a sorted array, because as others have mentioned, you simply take the first or last element - giving you an O(1) cost.

For a bit more of a technical explanation on the computational costs involved, and Big O notation, check out the Wikipedia article here.

Nick.

What version of JBoss I am running?

If it helps there is also a jar-versions.xml in my JBoss installation in JBoss root folder. This doesn't require you to wget or jar xvf.

E.g.

$  grep jboss-system.jar /opt/jboss-5.1.0.GA/jar-versions.xml | fold
  <jar name="jboss-system.jar" specVersion="5.1.0.GA" specVendor="JBoss (http://
www.jboss.org/)" specTitle="JBoss" implVersion="5.1.0.GA (build: SVNTag=JBoss_5_
1_0_GA date=200905221634)" implVendor="JBoss Inc." implTitle="JBoss [The Oracle]
" implVendorID="http://www.jboss.org/" implURL="http://www.jboss.org/" sealed="f
alse" md5Digest="c97e8a3dde7433b6c26d723413e17dbc"/>
$

SQL UPDATE SET one column to be equal to a value in a related table referenced by a different column?

I was having the same question. Here is a working solution which is similar to eglasius's. I am using postgresql.

UPDATE QuestionTrackings
SET QuestionID = a.QuestionID
FROM QuestionTrackings q, QuestionAnswers a
WHERE q.QuestionID IS NULL

It complains if q was used in place of table name in line 1, and nothing should precede QuestionID in line 2.

Generating combinations in c++

A simple way using std::next_permutation:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    int n, r;
    std::cin >> n;
    std::cin >> r;

    std::vector<bool> v(n);
    std::fill(v.end() - r, v.end(), true);

    do {
        for (int i = 0; i < n; ++i) {
            if (v[i]) {
                std::cout << (i + 1) << " ";
            }
        }
        std::cout << "\n";
    } while (std::next_permutation(v.begin(), v.end()));
    return 0;
}

or a slight variation that outputs the results in an easier to follow order:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
   int n, r;
   std::cin >> n;
   std::cin >> r;

   std::vector<bool> v(n);
   std::fill(v.begin(), v.begin() + r, true);

   do {
       for (int i = 0; i < n; ++i) {
           if (v[i]) {
               std::cout << (i + 1) << " ";
           }
       }
       std::cout << "\n";
   } while (std::prev_permutation(v.begin(), v.end()));
   return 0;
}

A bit of explanation:

It works by creating a "selection array" (v), where we place r selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v.


You can implement it if you note that for each level r you select a number from 1 to n.

In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance

#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>

using namespace std;

struct combinations
{
    typedef vector<int> combination_t;

    // initialize status
   combinations(int N, int R) :
       completed(N < 1 || R > N),
       generated(0),
       N(N), R(R)
   {
       for (int c = 1; c <= R; ++c)
           curr.push_back(c);
   }

   // true while there are more solutions
   bool completed;

   // count how many generated
   int generated;

   // get current and compute next combination
   combination_t next()
   {
       combination_t ret = curr;

       // find what to increment
       completed = true;
       for (int i = R - 1; i >= 0; --i)
           if (curr[i] < N - R + i + 1)
           {
               int j = curr[i] + 1;
               while (i <= R-1)
                   curr[i++] = j++;
               completed = false;
               ++generated;
               break;
           }

       return ret;
   }

private:

   int N, R;
   combination_t curr;
};

int main(int argc, char **argv)
{
    int N = argc >= 2 ? atoi(argv[1]) : 5;
    int R = argc >= 3 ? atoi(argv[2]) : 2;
    combinations cs(N, R);
    while (!cs.completed)
    {
        combinations::combination_t c = cs.next();
        copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
        cout << endl;
    }
    return cs.generated;
}

test output:

1,2,
1,3,
1,4,
1,5,
2,3,
2,4,
2,5,
3,4,
3,5,
4,5,

What's the foolproof way to tell which version(s) of .NET are installed on a production Windows Server?

Also, see the Stack Overflow question How to detect what .NET Framework versions and service packs are installed? which also mentions:

There is an official Microsoft answer to this question at the knowledge base article [How to determine which versions and service pack levels of the Microsoft .NET Framework are installed][2]

Article ID: 318785 - Last Review: November 7, 2008 - Revision: 20.1 How to determine which versions of the .NET Framework are installed and whether service packs have been applied.

Unfortunately, it doesn't appear to work, because the mscorlib.dll version in the 2.0 directory has a 2.0 version, and there is no mscorlib.dll version in either the 3.0 or 3.5 directories even though 3.5 SP1 is installed ... Why would the official Microsoft answer be so misinformed?

C# Macro definitions in Preprocessor

I would suggest you to write extension, something like below.

public static class WriteToConsoleExtension
{
   // Extension to all types
   public static void WriteToConsole(this object instance, 
                                     string format, 
                                     params object[] data)
   {
       Console.WriteLine(format, data);
   }
}

class Program
{
    static void Main(string[] args)
    {
        Program p = new Program();
        // Usage of extension
        p.WriteToConsole("Test {0}, {1}", DateTime.Now, 1);
    }
}

Hope this helps (and not too late :) )

Jest spyOn function called

In your test code your are trying to pass App to the spyOn function, but spyOn will only work with objects, not classes. Generally you need to use one of two approaches here:

1) Where the click handler calls a function passed as a prop, e.g.

class App extends Component {

  myClickFunc = () => {
      console.log('clickity clickcty');
      this.props.someCallback();
  }
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <p className="App-intro" onClick={this.myClickFunc}>
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

You can now pass in a spy function as a prop to the component, and assert that it is called:

describe('my sweet test', () => {
 it('clicks it', () => {
    const spy = jest.fn();
    const app = shallow(<App someCallback={spy} />)
    const p = app.find('.App-intro')
    p.simulate('click')
    expect(spy).toHaveBeenCalled()
 })
})

2) Where the click handler sets some state on the component, e.g.

class App extends Component {
  state = {
      aProperty: 'first'
  }

  myClickFunc = () => {
      console.log('clickity clickcty');
      this.setState({
          aProperty: 'second'
      });
  }
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <p className="App-intro" onClick={this.myClickFunc}>
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

You can now make assertions about the state of the component, i.e.

describe('my sweet test', () => {
 it('clicks it', () => {
    const app = shallow(<App />)
    const p = app.find('.App-intro')
    p.simulate('click')
    expect(app.state('aProperty')).toEqual('second');
 })
})

How to determine day of week by passing specific date?

import java.text.SimpleDateFormat;
import java.util.Scanner;

class DayFromDate {

    public static void main(String args[]) {

        System.out.println("Enter the date(dd/mm/yyyy):");
        Scanner scan = new Scanner(System.in);
        String Date = scan.nextLine();

        try {
            boolean dateValid = dateValidate(Date);

            if(dateValid == true) {
                SimpleDateFormat df = new SimpleDateFormat( "dd/MM/yy" );  
                java.util.Date date = df.parse( Date );   
                df.applyPattern( "EEE" );  
                String day= df.format( date ); 

                if(day.compareTo("Sat") == 0 || day.compareTo("Sun") == 0) {
                    System.out.println(day + ": Weekend");
                } else {
                    System.out.println(day + ": Weekday");
                }
            } else {
                System.out.println("Invalid Date!!!");
            }
        } catch(Exception e) {
            System.out.println("Invalid Date Formats!!!");
        }
     }

    static public boolean dateValidate(String d) {

        String dateArray[] = d.split("/");
        int day = Integer.parseInt(dateArray[0]);
        int month = Integer.parseInt(dateArray[1]);
        int year = Integer.parseInt(dateArray[2]);
        System.out.print(day + "\n" + month + "\n" + year + "\n");
        boolean leapYear = false;

        if((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0)) {
            leapYear = true;
        }

        if(year > 2099 || year < 1900)
            return false;

        if(month < 13) {
            if(month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
                if(day > 31)
                    return false;
            } else if(month == 4 || month == 6 || month == 9 || month == 11) {
                if(day > 30)
                    return false;
            } else if(leapYear == true && month == 2) {
                if(day > 29)
                    return false;
            } else if(leapYear == false && month == 2) {
                if(day > 28)
                    return false;
            }

            return true;    
        } else return false;
    }
}

change PATH permanently on Ubuntu

Try to add export PATH=$PATH:/home/me/play in ~/.bashrc file.

How to set width to 100% in WPF

It is the container of the Grid that is imposing on its width. In this case, that's a ListBoxItem, which is left-aligned by default. You can set it to stretch as follows:

<ListBox>
    <!-- other XAML omitted, you just need to add the following bit -->
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="HorizontalAlignment" Value="Stretch"/>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

Typescript empty object for a typed variable

you can do this as below in typescript

 const _params = {} as any;

 _params.name ='nazeh abel'

since typescript does not behave like javascript so we have to make the type as any otherwise it won't allow you to assign property dynamically to an object

How do you Programmatically Download a Webpage in Java

I'd use a decent HTML parser like Jsoup. It's then as easy as:

String html = Jsoup.connect("http://stackoverflow.com").get().html();

It handles GZIP and chunked responses and character encoding fully transparently. It offers more advantages as well, like HTML traversing and manipulation by CSS selectors like as jQuery can do. You only have to grab it as Document, not as a String.

Document document = Jsoup.connect("http://google.com").get();

You really don't want to run basic String methods or even regex on HTML to process it.

See also:

Change value of input onchange?

You can't access your fieldname as a global variable. Use document.getElementById:

function updateInput(ish){
    document.getElementById("fieldname").value = ish;
}

and

onchange="updateInput(this.value)"

Call parent method from child class c#

To follow up on the comment by suhendri to Rory McCrossan answer. Here is an Action delegate example:

In child add:

public Action UpdateProgress;  // In place of event handler declaration
                               // declare an Action delegate
.
.
.
private LoadData() {
    this.UpdateProgress();    // call to Action delegate - MyMethod in
                              // parent
}

In parent add:

// The 3 lines in the parent becomes:
ChildClass child = new ChildClass();
child.UpdateProgress = this.MyMethod;  // assigns MyMethod to child delegate

Android: show/hide status bar/power bar

with this method, using SYSTEM_UI_FLAG_IMMERSIVE_STICKY the full screen come back with one tap without any implementation. Just copy past this method below and call it where you want in your activity. More details here

private void hideSystemUI() {
    getWindow().getDecorView().setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_IMMERSIVE
                    // Set the content to appear under the system bars so that the
                    // content doesn't resize when the system bars hide and show.
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    // Hide the nav bar and status bar
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN);
}

WMI "installed" query different from add/remove programs list?

Not the best, but whether it is practical method:

Use HijackThis.

Run hijack this, click the "Open the Misc Tools section" button

HijackThis Main Menu

click "Open Uninstall Manager"

HijackThis Configuration

click save list (*.txt), yes to the prompts, notepad will open with your add/remove programs list.

HijackThis Add/Remove Programs Manager


Source

SQL Server FOR EACH Loop

[CREATE PROCEDURE [rat].[GetYear]

AS
BEGIN

-- variable for storing start date
Declare @StartYear as int
-- Variable for the End date 
Declare @EndYear as int 

-- Setting the value in strat Date
select @StartYear = Value from   rat.Configuration where Name = 'REPORT_START_YEAR'; 

-- Setting the End date 
select @EndYear = Value from   rat.Configuration where Name = 'REPORT_END_YEAR'; 


-- Creating Tem table 
    with [Years] as
    (
        --Selecting the Year
        select @StartYear [Year] 
        --doing Union 
        union all
         -- doing the loop in Years table 
         select Year+1 Year from [Years] where Year < @EndYear
     )
    --Selecting the Year table 
selec]

How to sort a HashMap in Java

Sorting by key:

public static void main(String[] args) {
    Map<String,String> map = new HashMap<>();

    map.put("b", "dd");
    map.put("c", "cc");
    map.put("a", "aa");

    map = new TreeMap<>(map);

    for (String key : map.keySet()) {
        System.out.println(key+"="+map.get(key));
    }
}

SelectSingleNode returning null for known good xml node path using XPath

Well... I had the same issue and it was a headache. Since I didn't care much about the namespace or the xml schema, I just deleted this data from my xml and it solved all my issues. May not be the best answer? Probably, but if you don't want to deal with all of this and you ONLY care about the data (and won't be using the xml for some other task) deleting the namespace may solve your problems.

XmlDocument vinDoc = new XmlDocument();
string vinInfo = "your xml string";
vinDoc.LoadXml(vinInfo);

vinDoc.InnerXml = vinDoc.InnerXml.Replace("xmlns=\"http://tempuri.org\/\", "");

WordPress query single post by slug

As wordpress api has changed, you can´t use get_posts with param 'post_name'. I´ve modified Maartens function a bit:

function get_post_id_by_slug( $slug, $post_type = "post" ) {
    $query = new WP_Query(
        array(
            'name'   => $slug,
            'post_type'   => $post_type,
            'numberposts' => 1,
            'fields'      => 'ids',
        ) );
    $posts = $query->get_posts();
    return array_shift( $posts );
}

Adding link a href to an element using css

No. Its not possible to add link through css. But you can use jquery

$('.case').each(function() {
  var link = $(this).html();
  $(this).contents().wrap('<a href="example.com/script.php?id="></a>');
});

Here the demo: http://jsfiddle.net/r5uWX/1/

Getting the name of the currently executing method

Util.java:

public static String getCurrentClassAndMethodNames() {
    final StackTraceElement e = Thread.currentThread().getStackTrace()[2];
    final String s = e.getClassName();
    return s.substring(s.lastIndexOf('.') + 1, s.length()) + "." + e.getMethodName();
}

SomeClass.java:

public class SomeClass {
    public static void main(String[] args) {
        System.out.println(Util.getCurrentClassAndMethodNames()); // output: SomeClass.main
    }
}

Error inflating class android.support.v7.widget.Toolbar?

I have fixed this problem by modifying app build.gradle file.

For Gradle Plugin 2.0+

 android {  
   defaultConfig {  
     vectorDrawables.useSupportLibrary = true  
    }  
 }  

For Gradle Plugin 1.5

 android {  
   defaultConfig {  

     generatedDensities = []  
  }  

  aaptOptions {  
    additionalParameters "--no-version-vectors"  
  }  
 } 

Maven : error in opening zip file when running maven

I just have this error. You can delete the files and run the compiling command again:

$ sudo rm /Users/Chaklader/.m2/repository/org/apache/poi/poi/3.17/poi-3.17.jar
$ sudo rm /Users/Chaklader/.m2/repository/com/fasterxml/jackson/core/jackson-databind/2.7.5/jackson-databind-2.7.5.jar
$ sudo rm /Users/Chaklader/.m2/repository/com/fasterxml/jackson/core/jackson-core/2.7.5/jackson-core-2.7.5.jar

Now, run the command for the clean compile:

$ mvn -U clean compile

cmake and libpthread

@Manuel was part way there. You can add the compiler option as well, like this:

If you have CMake 3.1.0+, this becomes even easier:

set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
target_link_libraries(my_app PRIVATE Threads::Threads)

If you are using CMake 2.8.12+, you can simplify this to:

find_package(Threads REQUIRED)
if(THREADS_HAVE_PTHREAD_ARG)
  target_compile_options(my_app PUBLIC "-pthread")
endif()
if(CMAKE_THREAD_LIBS_INIT)
  target_link_libraries(my_app "${CMAKE_THREAD_LIBS_INIT}")
endif()

Older CMake versions may require:

find_package(Threads REQUIRED)
if(THREADS_HAVE_PTHREAD_ARG)
  set_property(TARGET my_app PROPERTY COMPILE_OPTIONS "-pthread")
  set_property(TARGET my_app PROPERTY INTERFACE_COMPILE_OPTIONS "-pthread")
endif()
if(CMAKE_THREAD_LIBS_INIT)
  target_link_libraries(my_app "${CMAKE_THREAD_LIBS_INIT}")
endif()

If you want to use one of the first two methods with CMake 3.1+, you will need set(THREADS_PREFER_PTHREAD_FLAG ON) there too.

Save Javascript objects in sessionStorage

Use case:

 sesssionStorage.setObj(1,{date:Date.now(),action:'save firstObject'});
 sesssionStorage.setObj(2,{date:Date.now(),action:'save 2nd object'}); 
 //Query first object
  sesssionStorage.getObj(1)
  //Retrieve date created of 2nd object
  new Date(sesssionStorage.getObj(1).date)

API

Storage.prototype.setObj = function(key, obj) {

        return this.setItem(key, JSON.stringify(obj))
    };
    
    Storage.prototype.getObj = function(key) {
        return JSON.parse(this.getItem(key))
    };

Difference between \w and \b regular expression meta characters

The metacharacter \b is an anchor like the caret and the dollar sign. It matches at a position that is called a "word boundary". This match is zero-length.

There are three different positions that qualify as word boundaries:

  • Before the first character in the string, if the first character is a word character.
  • After the last character in the string, if the last character is a word character.
  • Between two characters in the string, where one is a word character and the other is not a word character.

Simply put: \b allows you to perform a "whole words only" search using a regular expression in the form of \bword\b. A "word character" is a character that can be used to form words. All characters that are not "word characters" are "non-word characters".

In all flavors, the characters [a-zA-Z0-9_] are word characters. These are also matched by the short-hand character class \w. Flavors showing "ascii" for word boundaries in the flavor comparison recognize only these as word characters.

\w stands for "word character", usually [A-Za-z0-9_]. Notice the inclusion of the underscore and digits.

\B is the negated version of \b. \B matches at every position where \b does not. Effectively, \B matches at any position between two word characters as well as at any position between two non-word characters.

\W is short for [^\w], the negated version of \w.

Losing scope when using ng-include

As @Renan mentioned, ng-include creates a new child scope. This scope prototypically inherits (see dashed lines below) from the HomeCtrl scope. ng-model="lineText" actually creates a primitive scope property on the child scope, not HomeCtrl's scope. This child scope is not accessible to the parent/HomeCtrl scope:

ng-include scope

To store what the user typed into HomeCtrl's $scope.lines array, I suggest you pass the value to the addLine function:

 <form ng-submit="addLine(lineText)">

In addition, since lineText is owned by the ngInclude scope/partial, I feel it should be responsible for clearing it:

 <form ng-submit="addLine(lineText); lineText=''">

Function addLine() would thus become:

$scope.addLine = function(lineText) {
    $scope.chat.addLine(lineText);
    $scope.lines.push({
        text: lineText
    });
};

Fiddle.

Alternatives:

  • define an object property on HomeCtrl's $scope, and use that in the partial: ng-model="someObj.lineText; fiddle
  • not recommended, this is more of a hack: use $parent in the partial to create/access a lineText property on the HomeCtrl $scope:  ng-model="$parent.lineText"; fiddle

It is a bit involved to explain why the above two alternatives work, but it is fully explained here: What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

I don't recommend using this in the addLine() function. It becomes much less clear which scope is being accessed/manipulated.

How to make flexbox items the same size?

Im no expert with flex but I got there by setting the basis to 50% for the two items i was dealing with. Grow to 1 and shrink to 0.

Inline styling: flex: '1 0 50%',

Turning multiple lines into one comma separated line

based on your input example, this awk line works. (without trailing comma)

awk -vRS="" -vOFS=',' '$1=$1' file

test:

kent$  echo "foo
bar
qux
zuu
sdf
sdfasdf"|awk -vRS="" -vOFS=',' '$1=$1' 
foo,bar,qux,zuu,sdf,sdfasdf

When to use "new" and when not to, in C++?

You should use new when you want an object to be created on the heap instead of the stack. This allows an object to be accessed from outside the current function or procedure, through the aid of pointers.

It might be of use to you to look up pointers and memory management in C++ since these are things you are unlikely to have come across in other languages.

Printing long int value in C

To take input " long int " and output " long int " in C is :

long int n;
scanf("%ld", &n);
printf("%ld", n);

To take input " long long int " and output " long long int " in C is :

long long int n;
scanf("%lld", &n);
printf("%lld", n);

Hope you've cleared..

Initialize array of strings

There is no right way, but you can initialize an array of literals:

char **values = (char *[]){"a", "b", "c"};

or you can allocate each and initialize it:

char **values = malloc(sizeof(char*) * s);
for(...)
{
    values[i] = malloc(sizeof(char) * l);
    //or
    values[i] = "hello";
}

How to insert a new line in Linux shell script?

You could use the printf(1) command, e.g. like

printf "Hello times %d\nHere\n" $[2+3] 

The  printf command may accept arguments and needs a format control string similar (but not exactly the same) to the one for the standard C printf(3) function...

Array as session variable

Yes, PHP supports arrays as session variables. See this page for an example.

As for your second question: once you set the session variable, it will remain the same until you either change it or unset it. So if the 3rd page doesn't change the session variable, it will stay the same until the 2nd page changes it again.

Get hostname of current request in node.js Express

If you need a fully qualified domain name and have no HTTP request, on Linux, you could use:

var child_process = require("child_process");

child_process.exec("hostname -f", function(err, stdout, stderr) {
  var hostname = stdout.trim();
});

Using app.config in .Net Core

  1. You can use Microsoft.Extensions.Configuration API with any .NET Core app, not only with ASP.NET Core app. Look into sample provided in the link, that shows how to read configs in the console app.

  2. In most cases, the JSON source (read as .json file) is the most suitable config source.

    Note: don't be confused when someone says that config file should be appsettings.json. You can use any file name, that is suitable for you and file location may be different - there are no specific rules.

    But, as the real world is complicated, there are a lot of different configuration providers:

    • File formats (INI, JSON, and XML)
    • Command-line arguments
    • Environment variables

    and so on. You even could use/write a custom provider.

  3. Actually, app.config configuration file was an XML file. So you can read settings from it using XML configuration provider (source on github, nuget link). But keep in mind, it will be used only as a configuration source - any logic how your app behaves should be implemented by you. Configuration Provider will not change 'settings' and set policies for your apps, but only read data from the file.

Can I set an opacity only to the background image of a div?

I implemented Marcus Ekwall's solution but was able to remove a few things to make it simpler and it still works. Maybe 2017 version of html/css?

html:

<div id="content">
  <div id='bg'></div>
  <h2>What is Lorem Ipsum?</h2>
  <p><strong>Lorem Ipsum</strong> is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
    book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with
    desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
</div>

css:

#content {
  text-align: left;
  width: 75%;
  margin: auto;
  position: relative;
}

#bg {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: url('https://static.pexels.com/photos/6644/sea-water-ocean-waves.jpg') center center;
  opacity: .4;
  width: 100%;
  height: 100%;
}

https://jsfiddle.net/abalter/3te9fjL5/

How can I create and style a div using JavaScript?

Another thing I like to do is creating an object and then looping thru the object and setting the styles like that because it can be tedious writing every single style one by one.

var bookStyles = {
   color: "red",
   backgroundColor: "blue",
   height: "300px",
   width: "200px"
};

let div = document.createElement("div");

for (let style in bookStyles) {
 div.style[style] = bookStyles[style];
}

body.appendChild(div);

Responsive dropdown navbar with angular-ui bootstrap (done in the correct angular kind of way)

Update 2015-06

Based on antoinepairet's comment/example:

Using uib-collapse attribute provides animations: http://plnkr.co/edit/omyoOxYnCdWJP8ANmTc6?p=preview

<nav class="navbar navbar-default" role="navigation">
    <div class="navbar-header">

        <!-- note the ng-init and ng-click here: -->
        <button type="button" class="navbar-toggle" ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" href="#">Brand</a>
    </div>

    <div class="collapse navbar-collapse" uib-collapse="navCollapsed">
        <ul class="nav navbar-nav">
        ...
        </ul>
    </div>
</nav>

Ancient..

I see that the question is framed around BS2, but I thought I'd pitch in with a solution for Bootstrap 3 using ng-class solution based on suggestions in ui.bootstrap issue 394:

The only variation from the official bootstrap example is the addition of ng- attributes noted by comments, below:

<nav class="navbar navbar-default" role="navigation">
  <div class="navbar-header">

    <!-- note the ng-init and ng-click here: -->
    <button type="button" class="navbar-toggle" ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed">
      <span class="sr-only">Toggle navigation</span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>
    <a class="navbar-brand" href="#">Brand</a>
  </div>

  <!-- note the ng-class here -->
  <div class="collapse navbar-collapse" ng-class="{'in':!navCollapsed}">

    <ul class="nav navbar-nav">
    ...

Here is an updated working example: http://plnkr.co/edit/OlCCnbGlYWeO7Nxwfj5G?p=preview (hat tip Lars)

This seems to works for me in simple use cases, but you'll note in the example that the second dropdown is cut off… good luck!

jQuery animate margin top

As said marginTop - not MarginTop.

Also why not animate it back? :)

See: http://jsfiddle.net/kX7b6/2/

Can you put two conditions in an xslt test attribute?

Maybe this is a no-brainer for the xslt-professional, but for me at beginner/intermediate level, this got me puzzled. I wanted to do exactly the same thing, but I had to test a responsetime value from an xml instead of a plain number. Following this thread, I tried this:

<xsl:when test="responsetime/@value &gt;= 5000 and responsetime/@value &lt;= 8999"> 

which generated an error. This works:

<xsl:when test="number(responsetime/@value) &gt;= 5000 and number(responsetime/@value) &lt;= 8999">

Don't really understand why it doesn't work without number(), though. Could it be that without number() the value is treated as a string and you can't compare numbers with a string?

Anyway, hope this saves someone a lot of searching...

Are (non-void) self-closing tags valid in HTML5?

Self-closing tags are valid in HTML5, but not required.

<br> and <br /> are both fine.

Delete empty lines using sed

I believe this is the easiest and fastest one:

cat file.txt | grep .

If you need to ignore all white-space lines as well then try this:

cat file.txt | grep '\S'

Example:

s="\
\
a\
 b\
\
Below is TAB:\
    \
Below is space:\
 \
c\
\
"; echo "$s" | grep . | wc -l; echo "$s" | grep '\S' | wc -l

outputs

7
5

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

What I do is something just a little bit different from @Chase answer:

var employees = {};

// ...and then:
employees.accounting = new Array();

for (var i = 0; i < someArray.length; i++) {
    var temp_item = someArray[i];

    // Maybe, here make something like:
    // temp_item.name = 'some value'

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

And that work form me!

I hope it could be useful for some body else!

HikariCP - connection is not available

From stack trace:

HikariPool: Timeout failure pool HikariPool-0 stats (total=20, active=20, idle=0, waiting=0) Means pool reached maximum connections limit set in configuration.

The next line: HikariPool-0 - Connection is not available, request timed out after 30000ms. Means pool waited 30000ms for free connection but your application not returned any connection meanwhile.

Mostly it is connection leak (connection is not closed after borrowing from pool), set leakDetectionThreshold to the maximum value that you expect SQL query would take to execute.

otherwise, your maximum connections 'at a time' requirement is higher than 20 !

Why does my 'git branch' have no master?

if it is a new repo you've cloned, it may still be empty, in which case:

git push -u origin master

should likely sort it out.

(did in my case. not sure this is the same issue, thought i should post this just incase. might help others.)

Select All distinct values in a column using LINQ

To have unique Categories:

var uniqueCategories =  repository.GetAllProducts()
                                  .Select(p=>p.Category)
                                  .Distinct();

How do I count cells that are between two numbers in Excel?

=COUNTIFS(H5:H21000,">=100", H5:H21000,"<999")

C# go to next item in list based on if statement in foreach

Try this:

foreach (Item item in myItemsList)
{
  if (SkipCondition) continue;
  // More stuff here
}

contenteditable change events

The onchange event doesn't fires when an element with the contentEditable attribute is changed, a suggested approach could be to add a button, to "save" the edition.

Check this plugin which handles the issue in that way:

Changing datagridview cell color dynamically

Considere use DataBindingComplete event for update the style. The next code change the style of the cell:

    private void Grid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        this.Grid.Rows[2].Cells[1].Style.BackColor = Color.Green;
    }

How do you make a LinearLayout scrollable?

Whenever you wanted to make a layout scrollable, you can use <ScrollView> With a layout or component in it.

Is there a way to get a textarea to stretch to fit its content without using PHP or JavaScript?

Here is a function that works with jQuery (for height only, not width):

function setHeight(jq_in){
    jq_in.each(function(index, elem){
        // This line will work with pure Javascript (taken from NicB's answer):
        elem.style.height = elem.scrollHeight+'px'; 
    });
}
setHeight($('<put selector here>'));

Note: The op asked for a solution that does not use Javascript, however this should be helpful to many people who come across this question.

How to convert all tables from MyISAM into InnoDB?

for mysqli connect;

<?php

$host       = "host";
$user       = "user";
$pass       = "pss";
$database   = "db_name";


$connect = new mysqli($host, $user, $pass, $database);  

// Actual code starts here Dont forget to change db_name !!
$sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_SCHEMA = 'db_name' 
    AND ENGINE = 'MyISAM'";

$rs = $connect->query($sql);

while($row = $rs->fetch_array())
{
    $tbl = $row[0];
    $sql = "ALTER TABLE `$tbl` ENGINE=INNODB";
    $connect->query($sql);
} ?>

Server.Mappath in C# classlibrary

You should reference System.Web and call:

  HttpContext.Current.Server.MapPath(...)

How to use wget in php?

This method is only one class and doesn't require importing other libraries or reusing code.

Personally I use this script that I made a while ago. Located here but for those who don't want to click on that link you can view it below. It lets the developer use the static method HTTP::GET($url, $options) to use the get method in curl while being able to pass through custom curl options. You can also use HTTP::POST($url, $options) but I hardly use that method.

/**
  *  echo HTTP::POST('http://accounts.kbcomp.co',
  *      array(
  *            'user_name'=>'[email protected]',
  *            'user_password'=>'demo1234'
  *      )
  *  );
  *  OR
  *  echo HTTP::GET('http://api.austinkregel.com/colors/E64B3B/1');
  *                  
  */

class HTTP{
   public static function GET($url,Array $options=array()){
    $ch = curl_init();
    if(count($options>0)){
       curl_setopt_array($ch, $options);
       curl_setopt($ch, CURLOPT_URL, $url);
       $json = curl_exec($ch);
       curl_close($ch);
       return $json;
     }
   }
   public static function POST($url, $postfields, $options = null){
       $ch = curl_init();
       $options = array(
          CURLOPT_URL=>$url,
          CURLOPT_RETURNTRANSFER => TRUE,
          CURLOPT_POSTFIELDS => $postfields,
          CURLOPT_HEADER => true
          //CURLOPT_HTTPHEADER, array('Content-Type:application/json')
          ); 
       if(count($options>0)){
           curl_setopt_array($ch, $options);
       }
       $json = curl_exec($ch);
       curl_close($ch);
       return $json;
   }
}

Convert Int to String in Swift

let intAsString = 45.description     // "45"
let stringAsInt = Int("45")          // 45

How can I set the font-family & font-size inside of a div?

Append a semicolon to the following line to fix the issue.

font-family:    Arial, Helvetica, sans-serif;

PostgreSQL: role is not permitted to log in

try to run

sudo su - postgres
psql
ALTER ROLE 'dbname'

Pass mouse events through absolutely-positioned element

The reason you are not receiving the event is because the absolutely positioned element is not a child of the element you are wanting to "click" (blue div). The cleanest way I can think of is to put the absolute element as a child of the one you want clicked, but I'm assuming you can't do that or you wouldn't have posted this question here :)

Another option would be to register a click event handler for the absolute element and call the click handler for the blue div, causing them both to flash.

Due to the way events bubble up through the DOM I'm not sure there is a simpler answer for you, but I'm very curious if anyone else has any tricks I don't know about!

Setting the default Java character encoding

I can't answer your original question but I would like to offer you some advice -- don't depend on the JVM's default encoding. It's always best to explicitly specify the desired encoding (i.e. "UTF-8") in your code. That way, you know it will work even across different systems and JVM configurations.

JQuery Ajax POST in Codeigniter

    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

    class UserController extends CI_Controller {

        public function verifyUser()    {
            $userName =  $_POST['userName'];
            $userPassword =  $_POST['userPassword'];
            $status = array("STATUS"=>"false");
            if($userName=='admin' && $userPassword=='admin'){
                $status = array("STATUS"=>"true");  
            }
            echo json_encode ($status) ;    
        }
    }


function makeAjaxCall(){
    $.ajax({
        type: "post",
        url: "http://localhost/CodeIgnitorTutorial/index.php/usercontroller/verifyUser",
        cache: false,               
        data: $('#userForm').serialize(),
        success: function(json){                        
        try{        
            var obj = jQuery.parseJSON(json);
            alert( obj['STATUS']);


        }catch(e) {     
            alert('Exception while request..');
        }       
        },
        error: function(){                      
            alert('Error while request..');
        }
 });
}

Specify JDK for Maven to use

Maven uses variable $JAVACMD as the final java command, set it to where the java executable is will switch maven to different JDK.

How can I make a list of installed packages in a certain virtualenv?

In my case the flask version was only visible under so I had to go to C:\Users\\AppData\Local\flask\venv\Scripts>pip freeze --local

C# difference between == and Equals()

== and .Equals are both dependent upon the behavior defined in the actual type and the actual type at the call site. Both are just methods / operators which can be overridden on any type and given any behavior the author so desires. In my experience, I find it's common for people to implement .Equals on an object but neglect to implement operator ==. This means that .Equals will actually measure the equality of the values while == will measure whether or not they are the same reference.

When I'm working with a new type whose definition is in flux or writing generic algorithms, I find the best practice is the following

  • If I want to compare references in C#, I use Object.ReferenceEquals directly (not needed in the generic case)
  • If I want to compare values I use EqualityComparer<T>.Default

In some cases when I feel the usage of == is ambiguous I will explicitly use Object.Reference equals in the code to remove the ambiguity.

Eric Lippert recently did a blog post on the subject of why there are 2 methods of equality in the CLR. It's worth the read

jackson deserialization json to java-objects

You have to change the line

product userFromJSON = mapper.readValue(userDataJSON, product.class);

to

product[] userFromJSON = mapper.readValue(userDataJSON, product[].class);

since you are deserializing an array (btw: you should start your class names with upper case letters as mentioned earlier). Additionally you have to create setter methods for your fields or mark them as public in order to make this work.

Edit: You can also go with Steven Schlansker's suggestion and use

List<product> userFromJSON =
        mapper.readValue(userDataJSON, new TypeReference<List<product>>() {});

instead if you want to avoid arrays.

Transparent color of Bootstrap-3 Navbar

.navbar {
   background-color: transparent;
   background: transparent;
   border-color: transparent;
}

.navbar li { color: #000 } 

http://bootply.com/106969

Python - 'ascii' codec can't decode byte

If you're using Python < 3, you'll need to tell the interpreter that your string literal is Unicode by prefixing it with a u:

Python 2.7.2 (default, Jan 14 2012, 23:14:09) 
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> "??".encode("utf8")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)
>>> u"??".encode("utf8")
'\xe4\xbd\xa0\xe5\xa5\xbd'

Further reading: Unicode HOWTO.

Finding the max value of an attribute in an array of objects

I'd like to explain the terse accepted answer step-by-step:

_x000D_
_x000D_
var objects = [{ x: 3 }, { x: 1 }, { x: 2 }];_x000D_
_x000D_
// array.map lets you extract an array of attribute values_x000D_
var xValues = objects.map(function(o) { return o.x; });_x000D_
// es6_x000D_
xValues = Array.from(objects, o => o.x);_x000D_
_x000D_
// function.apply lets you expand an array argument as individual arguments_x000D_
// So the following is equivalent to Math.max(3, 1, 2)_x000D_
// The first argument is "this" but since Math.max doesn't need it, null is fine_x000D_
var xMax = Math.max.apply(null, xValues);_x000D_
// es6_x000D_
xMax = Math.max(...xValues);_x000D_
_x000D_
// Finally, to find the object that has the maximum x value (note that result is array):_x000D_
var maxXObjects = objects.filter(function(o) { return o.x === xMax; });_x000D_
_x000D_
// Altogether_x000D_
xMax = Math.max.apply(null, objects.map(function(o) { return o.x; }));_x000D_
var maxXObject = objects.filter(function(o) { return o.x === xMax; })[0];_x000D_
// es6_x000D_
xMax = Math.max(...Array.from(objects, o => o.x));_x000D_
maxXObject = objects.find(o => o.x === xMax);_x000D_
_x000D_
_x000D_
document.write('<p>objects: ' + JSON.stringify(objects) + '</p>');_x000D_
document.write('<p>xValues: ' + JSON.stringify(xValues) + '</p>');_x000D_
document.write('<p>xMax: ' + JSON.stringify(xMax) + '</p>');_x000D_
document.write('<p>maxXObjects: ' + JSON.stringify(maxXObjects) + '</p>');_x000D_
document.write('<p>maxXObject: ' + JSON.stringify(maxXObject) + '</p>');
_x000D_
_x000D_
_x000D_

Further information:

ERROR Error: No value accessor for form control with unspecified name attribute on switch

In my case I forgot to add providers: [INPUT_VALUE_ACCESSOR] to my custom component

I had INPUT_VALUE_ACCESSOR created as:

export const INPUT_VALUE_ACCESSOR = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => TextEditorComponent),
  multi: true,
};

Conversion failed when converting date and/or time from character string while inserting datetime

The datetime format actually that runs on sql server is

yyyy-mm-dd hh:MM:ss

pass **kwargs argument to another function with **kwargs

Expanding on @gecco 's answer, the following is an example that'll show you the difference:

def foo(**kwargs):
    for entry in kwargs.items():
        print("Key: {}, value: {}".format(entry[0], entry[1]))

# call using normal keys:
foo(a=1, b=2, c=3)
# call using an unpacked dictionary:
foo(**{"a": 1, "b":2, "c":3})

# call using a dictionary fails because the function will think you are
# giving it a positional argument
foo({"a": 1, "b": 2, "c": 3})
# this yields the same error as any other positional argument
foo(3)
foo("string")

Here you can see how unpacking a dictionary works, and why sending an actual dictionary fails

Finding height in Binary Search Tree

I know that I’m late to the party. After looking into wonderful answers provided here, I thought mine will add some value to this post. Although the posted answers are amazing and easy to understand however, all are calculating the height to the BST in linear time. I think this can be improved and Height can be retrieved in constant time, hence writing this answer – hope you will like it. Let’s start with the Node class:

public class Node
{
    public Node(string key)
    {
        Key = key;
        Height = 1;
    }    

    public int Height { get; set; } 
    public string Key { get; set; }
    public Node Left { get; set; }
    public Node Right { get; set; }

    public override string ToString()
    {
        return $"{Key}";
    }
}

BinarySearchTree class

So you might have guessed the trick here… Im keeping node instance variable Height to keep track of each node when added. Lets move to the BinarySearchTree class that allows us to add nodes into our BST:

public class BinarySearchTree
{
    public Node RootNode { get; private set; }

    public void Put(string key)
    {
        if (ContainsKey(key))
        {
            return;
        }

        RootNode = Put(RootNode, key);
    }

    private Node Put(Node node, string key)
    {
        if (node == null) return new Node(key);

        if (node.Key.CompareTo(key) < 0)
        {
            node.Right = Put(node.Right, key);
        }
        else
        {
            node.Left = Put(node.Left, key);
        }       
        
        // since each node has height property that is maintained through this Put method that creates the binary search tree.
        // calculate the height of this node by getting the max height of its left or right subtree and adding 1 to it.        
        node.Height = Math.Max(GetHeight(node.Left), GetHeight(node.Right)) + 1;
        return node;
    }

    private int GetHeight(Node node)
    {
        return node?.Height ?? 0;
    }

    public Node Get(Node node, string key)
    {
        if (node == null) return null;
        if (node.Key == key) return node;

        if (node.Key.CompareTo(key) < 0)
        {
            // node.Key = M, key = P which results in -1
            return Get(node.Right, key);
        }

        return Get(node.Left, key);
    }

    public bool ContainsKey(string key)
    {
        Node node = Get(RootNode, key);
        return node != null;
    }
}

Once we have added the key, values in the BST, we can just call Height property on the RootNode object that will return us the Height of the RootNode tree in constant time. The trick is to keep the height updated when a new node is added into the tree. Hope this helps someone out there in the wild world of computer science enthusiast!

Unit test:

[TestCase("SEARCHEXAMPLE", 6)]
[TestCase("SEBAQRCHGEXAMPLE", 6)]
[TestCase("STUVWXYZEBAQRCHGEXAMPLE", 8)]
public void HeightTest(string data, int expectedHeight)
{
    // Arrange.
    var runner = GetRootNode(data);

    
    //  Assert.
    Assert.AreEqual(expectedHeight, runner.RootNode.Height);
}

private BinarySearchTree GetRootNode(string data)
{
    var runner = new BinarySearchTree();
    foreach (char nextKey in data)
    {
        runner.Put(nextKey.ToString());
    }

    return runner;
}

Note: This idea of keeping the Height of tree maintained in every Put operation is inspired by the Size of BST method found in the 3rd chapter (page 399) of Algorithm (Fourth Edition) book.

Getting permission denied (public key) on gitlab

I know, I'm answering this very late and even StackOverflow confirmed if I really want to answer. I'm answering because no one actually described the actual problem so wanted to share the same.

The Basics

First, understand that what is the remote here. Remote is GitLab and your system is the local so when we talk about the remote origin, whatever URL is set in your git remote -v output is your remote URL.

The Protocols

Basically, Git clone/push/pull works on two different protocols majorly (there are others as well)-

  1. HTTP protocol
  2. SSH protocol

When you clone a repo (or change the remote URL) and use the HTTPs URL like https://gitlab.com/wizpanda/backend-app.git then it uses the first protocol i.e. HTTP protocol.

While if you clone the repo (or change the remote URL) and uses the URL like [email protected]:wizpanda/backend-app.git then it uses the SSH protocol.

HTTP Protocol

In this protocol, every remote operation i.e. clone, push & pull uses the simple authentication i.e. username & password of your remote (GitLab in this case) that means for every operation, you have to type-in your username & password which might be cumbersome.

So when you push/pull/clone, GitLab/GitHub authenticate you with your username & password and it allows you to do the operation.

If you want to try this, you can switch to HTTP URL by running the command git remote set-url origin <http-git-url>.

To avoid that case, you can use the SSH protocol.

SSH Protocol

A simple SSH connection works on public-private key pairs. So in your case, GitLab can't authenticate you because you are using SSH URL to communicate. Now, GitLab must know you in some way. For that, you have to create a public-private key-pair and give the public key to GitLab.

Now when you push/pull/clone with GitLab, GIT (SSH internally) will by default offer your private key to GitLab and confirms your identity and then GitLab will allow you to perform the operation.

So I won't repeat the steps which are already given by Muhammad, I'll repeat them theoretically.

  1. Generate a key pair `ssh-keygen -t rsa -b 2048 -C "My Common SSH Key"
  2. The generated key pair will be by default in ~/.ssh named id_rsa.pub (public key) & id_rsa (private key).
  3. You will store the public key to your GitLab account (the same key can be used in multiple or any server/accounts).
  4. When you clone/push/pull, GIT offers your private key.
  5. GitLab matches the private key with your public key and allows you to perform.

Tips

You should always create a strong rsa key with at least 2048 bytes. So the command can be ssh-keygen -t rsa -b 2048.

https://gitlab.com/help/ssh/README#generating-a-new-ssh-key-pair

General thought

Both the approach have their pros & cons. After I typed the above text, I went to search more about this because I never read something about this.

I found this official doc https://git-scm.com/book/en/v2/Git-on-the-Server-The-Protocols which tells more about this. My point here is that, by reading the error and giving a thought on the error, you can make your own theory or understanding and then can match with some Google results to fix the issue :)

How to determine CPU and memory consumption from inside a process?

Linux

A portable way of reading memory and load numbers is the sysinfo call

Usage

   #include <sys/sysinfo.h>

   int sysinfo(struct sysinfo *info);

DESCRIPTION

   Until Linux 2.3.16, sysinfo() used to return information in the
   following structure:

       struct sysinfo {
           long uptime;             /* Seconds since boot */
           unsigned long loads[3];  /* 1, 5, and 15 minute load averages */
           unsigned long totalram;  /* Total usable main memory size */
           unsigned long freeram;   /* Available memory size */
           unsigned long sharedram; /* Amount of shared memory */
           unsigned long bufferram; /* Memory used by buffers */
           unsigned long totalswap; /* Total swap space size */
           unsigned long freeswap;  /* swap space still available */
           unsigned short procs;    /* Number of current processes */
           char _f[22];             /* Pads structure to 64 bytes */
       };

   and the sizes were given in bytes.

   Since Linux 2.3.23 (i386), 2.3.48 (all architectures) the structure
   is:

       struct sysinfo {
           long uptime;             /* Seconds since boot */
           unsigned long loads[3];  /* 1, 5, and 15 minute load averages */
           unsigned long totalram;  /* Total usable main memory size */
           unsigned long freeram;   /* Available memory size */
           unsigned long sharedram; /* Amount of shared memory */
           unsigned long bufferram; /* Memory used by buffers */
           unsigned long totalswap; /* Total swap space size */
           unsigned long freeswap;  /* swap space still available */
           unsigned short procs;    /* Number of current processes */
           unsigned long totalhigh; /* Total high memory size */
           unsigned long freehigh;  /* Available high memory size */
           unsigned int mem_unit;   /* Memory unit size in bytes */
           char _f[20-2*sizeof(long)-sizeof(int)]; /* Padding to 64 bytes */
       };

   and the sizes are given as multiples of mem_unit bytes.

Load CSV data into MySQL in Python

  from __future__ import print_function
import csv
import MySQLdb

print("Enter  File  To Be Export")
conn = MySQLdb.connect(host="localhost", port=3306, user="root", passwd="", db="database")
cursor = conn.cursor()
#sql = 'CREATE DATABASE test1'
sql ='''DROP TABLE IF EXISTS `test1`; CREATE TABLE test1 (policyID int, statecode varchar(255), county varchar(255))'''
cursor.execute(sql)

with open('C:/Users/Desktop/Code/python/sample.csv') as csvfile:
    reader = csv.DictReader(csvfile, delimiter = ',')
    for row in reader:
        print(row['policyID'], row['statecode'], row['county'])
        # insert
        conn = MySQLdb.connect(host="localhost", port=3306, user="root", passwd="", db="database")
        sql_statement = "INSERT INTO test1(policyID ,statecode,county) VALUES (%s,%s,%s)"
        cur = conn.cursor()
        cur.executemany(sql_statement,[(row['policyID'], row['statecode'], row['county'])])
        conn.escape_string(sql_statement)
        conn.commit()

INSERT INTO ... SELECT FROM ... ON DUPLICATE KEY UPDATE

MySQL will assume the part before the equals references the columns named in the INSERT INTO clause, and the second part references the SELECT columns.

INSERT INTO lee(exp_id, created_by, location, animal, starttime, endtime, entct, 
                inact, inadur, inadist, 
                smlct, smldur, smldist, 
                larct, lardur, lardist, 
                emptyct, emptydur)
SELECT id, uid, t.location, t.animal, t.starttime, t.endtime, t.entct, 
       t.inact, t.inadur, t.inadist, 
       t.smlct, t.smldur, t.smldist, 
       t.larct, t.lardur, t.lardist, 
       t.emptyct, t.emptydur 
FROM tmp t WHERE uid=x
ON DUPLICATE KEY UPDATE entct=t.entct, inact=t.inact, ...

Django 1.7 - "No migrations to apply" when run migrate after makemigrations

I had this same problem. Make sure the app's migrations folder is created (YOURAPPNAME/ migrations). Delete the folder and enter the commands:

python manage.py migrate --fake
python manage.py makemigrations <app_name>
python manage.py migrate --fake-initial

I inserted this lines in each class in models.py:

class Meta:
    app_label = '<app_name>'

This solved my problem.

How to use a filter in a controller?

Use below code if we want to add multiple conditions, instead of single value in javascript angular filter:

var modifiedArray = $filter('filter')(array,function(item){return (item.ColumnName == 'Value1' || item.ColumnName == 'Value2');},true)

How to check whether input value is integer or float?

Do this to distinguish that.

If for example your number is 3.1214 and stored in num but you don't know kind of num:

num = 3.1214
// cast num to int
int x = (int)num;
if(x == num)
{
  // num is a integer
} 
else
  // num is float
}

In this example we see that num is not integer.

WSDL validator?

If you would to validate WSDL programatically then you use WSDL Validator out of eclipse. http://wiki.eclipse.org/Using_the_WSDL_Validator_Outside_of_Eclipse should help or try this tool Graphical WSDL 1.1/2.0 editor.

Check if a number is a perfect square

The idea is to run a loop from i = 1 to floor(sqrt(n)) then check if squaring it makes n.

bool isPerfectSquare(int n) 
{ 
    for (int i = 1; i * i <= n; i++) { 

        // If (i * i = n) 
        if ((n % i == 0) && (n / i == i)) { 
            return true; 
        } 
    } 
    return false; 
} 

Changing the default icon in a Windows Forms application

select Main form -> properties -> Windows style -> icon -> browse your ico

this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));

Fixed positioned div within a relative parent div

This is possible if you move the fixed <div> using margins and not positions:

#wrap{ position:absolute;left:100px;top:100px; }
#fixed{ 
   position:fixed;
   width:10px;
   height:10px;
   background-color:#333;
   margin-left:200px;
   margin-top:200px;
}

And this HTML:

<div id="wrap">
   <div id="fixed"></div>
</div>

Play around with this jsfiddle.

How to turn on/off MySQL strict mode in localhost (xampp)?

on server console:

$ mysql -u root -p -e "SET GLOBAL sql_mode = 'NO_ENGINE_SUBSTITUTION';" 

Examples of GoF Design Patterns in Java's core libraries

  1. Observer pattern throughout whole swing (Observable, Observer)
  2. MVC also in swing
  3. Adapter pattern: InputStreamReader and OutputStreamWriter NOTE: ContainerAdapter, ComponentAdapter, FocusAdapter, KeyAdapter, MouseAdapter are not adapters; they are actually Null Objects. Poor naming choice by Sun.
  4. Decorator pattern (BufferedInputStream can decorate other streams such as FilterInputStream)
  5. AbstractFactory Pattern for the AWT Toolkit and the Swing pluggable look-and-feel classes
  6. java.lang.Runtime#getRuntime() is Singleton
  7. ButtonGroup for Mediator pattern
  8. Action, AbstractAction may be used for different visual representations to execute same code -> Command pattern
  9. Interned Strings or CellRender in JTable for Flyweight Pattern (Also think about various pools - Thread pools, connection pools, EJB object pools - Flyweight is really about management of shared resources)
  10. The Java 1.0 event model is an example of Chain of Responsibility, as are Servlet Filters.
  11. Iterator pattern in Collections Framework
  12. Nested containers in AWT/Swing use the Composite pattern
  13. Layout Managers in AWT/Swing are an example of Strategy

and many more I guess

How to create cron job using PHP?

Added to Alister, you can edit the crontab usually (not always the case) by entering crontab -e in a ssh session on the server.

The stars represent (* means every of this unit):

[Minute] [Hour] [Day] [Month] [Day of week (0 =sunday to 6 =saturday)] [Command]

You could read some more about this here.

How to shut down the computer from C#

System.Diagnostics.Process.Start("shutdown", "/s /t 0")

Should work.

For restart, it's /r

This will restart the PC box directly and cleanly, with NO dialogs.

MySql difference between two timestamps in days?

SELECT DATEDIFF( now(), '2013-06-20' );

here datediff takes two arguments 'upto-date', 'from-date'

What i have done is, using now() function, i can get no. of days since 20-june-2013 till today.

Python3: ImportError: No module named '_ctypes' when using Value from module multiprocessing

You have to load the missing php3 (Python3) modules from the package manager. If you have Ubuntu I recommend the Synaptic Package Manager:

sudo apt-get install synaptic

There you can simply search for the missing modules. search for ctypes and install all the packages. Then go to your Python dir and do

./configure
make install.

This should solve your problem.

How do you create a Swift Date object?

Personally I think it should be a failable initialiser:

extension Date {

    init?(dateString: String) {
        let dateStringFormatter = DateFormatter()
        dateStringFormatter.dateFormat = "yyyy-MM-dd"
        if let d = dateStringFormatter.date(from: dateString) {
            self.init(timeInterval: 0, since: d)
        } else {
            return nil
        }
    }
}

Otherwise a string with an invalid format will raise an exception.

Git: How to rebase to a specific commit?

Use the "onto" option:

git rebase --onto master^ D^ D

JSON.Net Self referencing loop detected

You must set Preserving Object References:

var jsonSerializerSettings = new JsonSerializerSettings
{
    PreserveReferencesHandling = PreserveReferencesHandling.Objects
};

Then call your query var q = (from a in db.Events where a.Active select a).ToList(); like

string jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(q, jsonSerializerSettings);

See: https://www.newtonsoft.com/json/help/html/PreserveObjectReferences.htm

ImportError: cannot import name

The problem is that you have a circular import: in app.py

from mod_login import mod_login

in mod_login.py

from app import app

This is not permitted in Python. See Circular import dependency in Python for more info. In short, the solution are

  • either gather everything in one big file
  • delay one of the import using local import

How to check sbt version?

You can use sbt about

Example: 
    C:\Users\smala>sbt about
    [info] Set current project to smala (in build file:/C:/Users/smala/)
    [info] This is sbt 0.13.6
    [info] The current project is {file:/C:/Users/smala/}smala 0.1-SNAPSHOT
    [info] The current project is built against Scala 2.10.4
    [info] Available Plugins: sbt.plugins.IvyPlugin, sbt.plugins.JvmPlugin,   sbt.plugins.CorePlugin, sbt.plugins.JUnitXmlReportPlugin
    [info] sbt, sbt plugins, and build definitions are using Scala 2.10.4"

Android Open External Storage directory(sdcard) for storing file

The internal storage is referred to as "external storage" in the API.

As mentioned in the Environment documentation

Note: don't be confused by the word "external" here. This directory can better be thought as media/shared storage. It is a filesystem that can hold a relatively large amount of data and that is shared across all applications (does not enforce permissions). Traditionally this is an SD card, but it may also be implemented as built-in storage in a device that is distinct from the protected internal storage and can be mounted as a filesystem on a computer.

To distinguish whether "Environment.getExternalStorageDirectory()" actually returned physically internal or external storage, call Environment.isExternalStorageEmulated(). If it's emulated, than it's internal. On newer devices that have internal storage and sdcard slot Environment.getExternalStorageDirectory() will always return the internal storage. While on older devices that have only sdcard as a media storage option it will always return the sdcard.

There is no way to retrieve all storages using current Android API.

I've created a helper based on Vitaliy Polchuk's method in the answer below

How can I get the list of mounted external storage of android device

NOTE: starting KitKat secondary storage is accessible only as READ-ONLY, you may want to check for writability using the following method

/**
 * Checks whether the StorageVolume is read-only
 * 
 * @param volume
 *            StorageVolume to check
 * @return true, if volume is mounted read-only
 */
public static boolean isReadOnly(@NonNull final StorageVolume volume) {
    if (volume.mFile.equals(Environment.getExternalStorageDirectory())) {
        // is a primary storage, check mounted state by Environment
        return android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED_READ_ONLY);
    } else {
        if (volume.getType() == Type.USB) {
            return volume.isReadOnly();
        }
        //is not a USB storagem so it's read-only if it's mounted read-only or if it's a KitKat device
        return volume.isReadOnly() || Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
    }
}

StorageHelper class

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.StringTokenizer;

import android.os.Environment;

public final class StorageHelper {

    //private static final String TAG = "StorageHelper";

    private StorageHelper() {
    }

    private static final String STORAGES_ROOT;

    static {
        final String primaryStoragePath = Environment.getExternalStorageDirectory()
                .getAbsolutePath();
        final int index = primaryStoragePath.indexOf(File.separatorChar, 1);
        if (index != -1) {
            STORAGES_ROOT = primaryStoragePath.substring(0, index + 1);
        } else {
            STORAGES_ROOT = File.separator;
        }
    }

    private static final String[] AVOIDED_DEVICES = new String[] {
        "rootfs", "tmpfs", "dvpts", "proc", "sysfs", "none"
    };

    private static final String[] AVOIDED_DIRECTORIES = new String[] {
        "obb", "asec"
    };

    private static final String[] DISALLOWED_FILESYSTEMS = new String[] {
        "tmpfs", "rootfs", "romfs", "devpts", "sysfs", "proc", "cgroup", "debugfs"
    };

    /**
     * Returns a list of mounted {@link StorageVolume}s Returned list always
     * includes a {@link StorageVolume} for
     * {@link Environment#getExternalStorageDirectory()}
     * 
     * @param includeUsb
     *            if true, will include USB storages
     * @return list of mounted {@link StorageVolume}s
     */
    public static List<StorageVolume> getStorages(final boolean includeUsb) {
        final Map<String, List<StorageVolume>> deviceVolumeMap = new HashMap<String, List<StorageVolume>>();

        // this approach considers that all storages are mounted in the same non-root directory
        if (!STORAGES_ROOT.equals(File.separator)) {
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new FileReader("/proc/mounts"));
                String line;
                while ((line = reader.readLine()) != null) {
                    // Log.d(TAG, line);
                    final StringTokenizer tokens = new StringTokenizer(line, " ");

                    final String device = tokens.nextToken();
                    // skipped devices that are not sdcard for sure
                    if (arrayContains(AVOIDED_DEVICES, device)) {
                        continue;
                    }

                    // should be mounted in the same directory to which
                    // the primary external storage was mounted
                    final String path = tokens.nextToken();
                    if (!path.startsWith(STORAGES_ROOT)) {
                        continue;
                    }

                    // skip directories that indicate tha volume is not a storage volume
                    if (pathContainsDir(path, AVOIDED_DIRECTORIES)) {
                        continue;
                    }

                    final String fileSystem = tokens.nextToken();
                    // don't add ones with non-supported filesystems
                    if (arrayContains(DISALLOWED_FILESYSTEMS, fileSystem)) {
                        continue;
                    }

                    final File file = new File(path);
                    // skip volumes that are not accessible
                    if (!file.canRead() || !file.canExecute()) {
                        continue;
                    }

                    List<StorageVolume> volumes = deviceVolumeMap.get(device);
                    if (volumes == null) {
                        volumes = new ArrayList<StorageVolume>(3);
                        deviceVolumeMap.put(device, volumes);
                    }

                    final StorageVolume volume = new StorageVolume(device, file, fileSystem);
                    final StringTokenizer flags = new StringTokenizer(tokens.nextToken(), ",");
                    while (flags.hasMoreTokens()) {
                        final String token = flags.nextToken();
                        if (token.equals("rw")) {
                            volume.mReadOnly = false;
                            break;
                        } else if (token.equals("ro")) {
                            volume.mReadOnly = true;
                            break;
                        }
                    }
                    volumes.add(volume);
                }

            } catch (IOException ex) {
                ex.printStackTrace();
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException ex) {
                        // ignored
                    }
                }
            }
        }

        // remove volumes that are the same devices
        boolean primaryStorageIncluded = false;
        final File externalStorage = Environment.getExternalStorageDirectory();
        final List<StorageVolume> volumeList = new ArrayList<StorageVolume>();
        for (final Entry<String, List<StorageVolume>> entry : deviceVolumeMap.entrySet()) {
            final List<StorageVolume> volumes = entry.getValue();
            if (volumes.size() == 1) {
                // go ahead and add
                final StorageVolume v = volumes.get(0);
                final boolean isPrimaryStorage = v.file.equals(externalStorage);
                primaryStorageIncluded |= isPrimaryStorage;
                setTypeAndAdd(volumeList, v, includeUsb, isPrimaryStorage);
                continue;
            }
            final int volumesLength = volumes.size();
            for (int i = 0; i < volumesLength; i++) {
                final StorageVolume v = volumes.get(i);
                if (v.file.equals(externalStorage)) {
                    primaryStorageIncluded = true;
                    // add as external storage and continue
                    setTypeAndAdd(volumeList, v, includeUsb, true);
                    break;
                }
                // if that was the last one and it's not the default external
                // storage then add it as is
                if (i == volumesLength - 1) {
                    setTypeAndAdd(volumeList, v, includeUsb, false);
                }
            }
        }
        // add primary storage if it was not found
        if (!primaryStorageIncluded) {
            final StorageVolume defaultExternalStorage = new StorageVolume("", externalStorage, "UNKNOWN");
            defaultExternalStorage.mEmulated = Environment.isExternalStorageEmulated();
            defaultExternalStorage.mType =
                    defaultExternalStorage.mEmulated ? StorageVolume.Type.INTERNAL
                            : StorageVolume.Type.EXTERNAL;
            defaultExternalStorage.mRemovable = Environment.isExternalStorageRemovable();
            defaultExternalStorage.mReadOnly =
                    Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY);
            volumeList.add(0, defaultExternalStorage);
        }
        return volumeList;
    }

    /**
     * Sets {@link StorageVolume.Type}, removable and emulated flags and adds to
     * volumeList
     * 
     * @param volumeList
     *            List to add volume to
     * @param v
     *            volume to add to list
     * @param includeUsb
     *            if false, volume with type {@link StorageVolume.Type#USB} will
     *            not be added
     * @param asFirstItem
     *            if true, adds the volume at the beginning of the volumeList
     */
    private static void setTypeAndAdd(final List<StorageVolume> volumeList,
            final StorageVolume v,
            final boolean includeUsb,
            final boolean asFirstItem) {
        final StorageVolume.Type type = resolveType(v);
        if (includeUsb || type != StorageVolume.Type.USB) {
            v.mType = type;
            if (v.file.equals(Environment.getExternalStorageDirectory())) {
                v.mRemovable = Environment.isExternalStorageRemovable();
            } else {
                v.mRemovable = type != StorageVolume.Type.INTERNAL;
            }
            v.mEmulated = type == StorageVolume.Type.INTERNAL;
            if (asFirstItem) {
                volumeList.add(0, v);
            } else {
                volumeList.add(v);
            }
        }
    }

    /**
     * Resolved {@link StorageVolume} type
     * 
     * @param v
     *            {@link StorageVolume} to resolve type for
     * @return {@link StorageVolume} type
     */
    private static StorageVolume.Type resolveType(final StorageVolume v) {
        if (v.file.equals(Environment.getExternalStorageDirectory())
                && Environment.isExternalStorageEmulated()) {
            return StorageVolume.Type.INTERNAL;
        } else if (containsIgnoreCase(v.file.getAbsolutePath(), "usb")) {
            return StorageVolume.Type.USB;
        } else {
            return StorageVolume.Type.EXTERNAL;
        }
    }

    /**
     * Checks whether the array contains object
     * 
     * @param array
     *            Array to check
     * @param object
     *            Object to find
     * @return true, if the given array contains the object
     */
    private static <T> boolean arrayContains(T[] array, T object) {
        for (final T item : array) {
            if (item.equals(object)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Checks whether the path contains one of the directories
     * 
     * For example, if path is /one/two, it returns true input is "one" or
     * "two". Will return false if the input is one of "one/two", "/one" or
     * "/two"
     * 
     * @param path
     *            path to check for a directory
     * @param dirs
     *            directories to find
     * @return true, if the path contains one of the directories
     */
    private static boolean pathContainsDir(final String path, final String[] dirs) {
        final StringTokenizer tokens = new StringTokenizer(path, File.separator);
        while (tokens.hasMoreElements()) {
            final String next = tokens.nextToken();
            for (final String dir : dirs) {
                if (next.equals(dir)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * Checks ifString contains a search String irrespective of case, handling.
     * Case-insensitivity is defined as by
     * {@link String#equalsIgnoreCase(String)}.
     * 
     * @param str
     *            the String to check, may be null
     * @param searchStr
     *            the String to find, may be null
     * @return true if the String contains the search String irrespective of
     *         case or false if not or {@code null} string input
     */
    public static boolean containsIgnoreCase(final String str, final String searchStr) {
        if (str == null || searchStr == null) {
            return false;
        }
        final int len = searchStr.length();
        final int max = str.length() - len;
        for (int i = 0; i <= max; i++) {
            if (str.regionMatches(true, i, searchStr, 0, len)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Represents storage volume information
     */
    public static final class StorageVolume {

        /**
         * Represents {@link StorageVolume} type
         */
        public enum Type {
            /**
             * Device built-in internal storage. Probably points to
             * {@link Environment#getExternalStorageDirectory()}
             */
            INTERNAL,

            /**
             * External storage. Probably removable, if no other
             * {@link StorageVolume} of type {@link #INTERNAL} is returned by
             * {@link StorageHelper#getStorages(boolean)}, this might be
             * pointing to {@link Environment#getExternalStorageDirectory()}
             */
            EXTERNAL,

            /**
             * Removable usb storage
             */
            USB
        }

        /**
         * Device name
         */
        public final String device;

        /**
         * Points to mount point of this device
         */
        public final File file;

        /**
         * File system of this device
         */
        public final String fileSystem;

        /**
         * if true, the storage is mounted as read-only
         */
        private boolean mReadOnly;

        /**
         * If true, the storage is removable
         */
        private boolean mRemovable;

        /**
         * If true, the storage is emulated
         */
        private boolean mEmulated;

        /**
         * Type of this storage
         */
        private Type mType;

        StorageVolume(String device, File file, String fileSystem) {
            this.device = device;
            this.file = file;
            this.fileSystem = fileSystem;
        }

        /**
         * Returns type of this storage
         * 
         * @return Type of this storage
         */
        public Type getType() {
            return mType;
        }

        /**
         * Returns true if this storage is removable
         * 
         * @return true if this storage is removable
         */
        public boolean isRemovable() {
            return mRemovable;
        }

        /**
         * Returns true if this storage is emulated
         * 
         * @return true if this storage is emulated
         */
        public boolean isEmulated() {
            return mEmulated;
        }

        /**
         * Returns true if this storage is mounted as read-only
         * 
         * @return true if this storage is mounted as read-only
         */
        public boolean isReadOnly() {
            return mReadOnly;
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((file == null) ? 0 : file.hashCode());
            return result;
        }

        /**
         * Returns true if the other object is StorageHelper and it's
         * {@link #file} matches this one's
         * 
         * @see Object#equals(Object)
         */
        @Override
        public boolean equals(Object obj) {
            if (obj == this) {
                return true;
            }
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            final StorageVolume other = (StorageVolume) obj;
            if (file == null) {
                return other.file == null;
            }
            return file.equals(other.file);
        }

        @Override
        public String toString() {
            return file.getAbsolutePath() + (mReadOnly ? " ro " : " rw ") + mType + (mRemovable ? " R " : "")
                    + (mEmulated ? " E " : "") + fileSystem;
        }
    }
}

What's the best way to join on the same table twice?

First, I would try and refactor these tables to get away from using phone numbers as natural keys. I am not a fan of natural keys and this is a great example why. Natural keys, especially things like phone numbers, can change and frequently so. Updating your database when that change happens will be a HUGE, error-prone headache. *

Method 1 as you describe it is your best bet though. It looks a bit terse due to the naming scheme and the short aliases but... aliasing is your friend when it comes to joining the same table multiple times or using subqueries etc.

I would just clean things up a bit:

SELECT t.PhoneNumber1, t.PhoneNumber2, 
   t1.SomeOtherFieldForPhone1, t2.someOtherFieldForPhone2
FROM Table1 t
JOIN Table2 t1 ON t1.PhoneNumber = t.PhoneNumber1
JOIN Table2 t2 ON t2.PhoneNumber = t.PhoneNumber2

What i did:

  • No need to specify INNER - it's implied by the fact that you don't specify LEFT or RIGHT
  • Don't n-suffix your primary lookup table
  • N-Suffix the table aliases that you will use multiple times to make it obvious

*One way DBAs avoid the headaches of updating natural keys is to not specify primary keys and foreign key constraints which further compounds the issues with poor db design. I've actually seen this more often than not.

Join/Where with LINQ and Lambda

Your key selectors are incorrect. They should take an object of the type of the table in question and return the key to use in the join. I think you mean this:

var query = database.Posts.Join(database.Post_Metas,
                                post => post.ID,
                                meta => meta.Post_ID,
                                (post, meta) => new { Post = post, Meta = meta });

You can apply the where clause afterwards, not as part of the key selector.

programming a servo thru a barometer

You could define a mapping of air pressure to servo angle, for example:

def calc_angle(pressure, min_p=1000, max_p=1200):     return 360 * ((pressure - min_p) / float(max_p - min_p))  angle = calc_angle(pressure) 

This will linearly convert pressure values between min_p and max_p to angles between 0 and 360 (you could include min_a and max_a to constrain the angle, too).

To pick a data structure, I wouldn't use a list but you could look up values in a dictionary:

d = {1000:0, 1001: 1.8, ...}  angle = d[pressure] 

but this would be rather time-consuming to type out!

Converting from signed char to unsigned char and back again?

Yes this is safe.

The c language uses a feature called integer promotion to increase the number of bits in a value before performing calculations. Therefore your CLAMP255 macro will operate at integer (probably 32 bit) precision. The result is assigned to a jbyte, which reduces the integer precision back to 8 bits fit in to the jbyte.

Excel - Using COUNTIF/COUNTIFS across multiple sheets/same column

This could be solved without VBA by the following technique.

In this example I am counting all the threes (3) in the range A:A of the sheets Page M904, Page M905 and Page M906.

List all the sheet names in a single continuous range like in the following example. Here listed in the range D3:D5.

enter image description here

Then by having the lookup value in cell B2, the result can be found in cell B4 by using the following formula:

=SUMPRODUCT(COUNTIF(INDIRECT("'"&D3:D5&"'!A:A"), B2))

How to run a program without an operating system?

Operating System as the inspiration

The operating system is also a program, so we can also create our own program by creating from scratch or changing (limiting or adding) features of one of the small operating systems, and then run it during the boot process (using an ISO image).

For example, this page can be used as a starting point:

How to write a simple operating system

Here, the entire Operating System fit entirely in a 512-byte boot sector (MBR)!

Such or similar simple OS can be used to create a simple framework that will allow us:

make the bootloader load subsequent sectors on the disk into RAM, and jump to that point to continue execution. Or you could read up on FAT12, the filesystem used on floppy drives, and implement that.

There are many possibilities, however. For for example to see a bigger x86 assembly language OS we can explore the MykeOS, x86 operating system which is a learning tool to show the simple 16-bit, real-mode OSes work, with well-commented code and extensive documentation.

Boot Loader as the inspiration

Other common type of programs that run without the operating system are also Boot Loaders. We can create a program inspired by such a concept for example using this site:

How to develop your own Boot Loader

The above article presents also the basic architecture of such a programs:

  1. Correct loading to the memory by 0000:7C00 address.
  2. Calling the BootMain function that is developed in the high-level language.
  3. Show “”Hello, world…”, from low-level” message on the display.

As we can see, this architecture is very flexible and allows us to implement any program, not necessarily a boot loader.

In particular, it shows how to use the "mixed code" technique thanks to which it is possible to combine high-level constructions (from C or C++) with low-level commands (from Assembler). This is a very useful method, but we have to remember that:

to build the program and obtain executable file you will need the compiler and linker of Assembler for 16-bit mode. For C/C++ you will need only the compiler that can create object files for 16-bit mode.

The article shows also how to see the created program in action and how to perform its testing and debug.

UEFI applications as the inspiration

The above examples used the fact of loading the sector MBR on the data medium. However, we can go deeper into the depths by plaing for example with the UEFI applications:

Beyond loading an OS, UEFI can run UEFI applications, which reside as files on the EFI System Partition. They can be executed from the UEFI command shell, by the firmware's boot manager, or by other UEFI applications. UEFI applications can be developed and installed independently of the system manufacturer.

A type of UEFI application is an OS loader such as GRUB, rEFInd, Gummiboot, and Windows Boot Manager; which loads an OS file into memory and executes it. Also, an OS loader can provide a user interface to allow the selection of another UEFI application to run. Utilities like the UEFI shell are also UEFI applications.

If we would like to start creating such programs, we can, for example, start with these websites:

Programming for EFI: Creating a "Hello, World" Program / UEFI Programming - First Steps

Exploring security issues as the inspiration

It is well known that there is a whole group of malicious software (which are programs) that are running before the operating system starts.

A huge group of them operate on the MBR sector or UEFI applications, just like the all above solutions, but there are also those that use another entry point such as the Volume Boot Record (VBR) or the BIOS:

There are at least four known BIOS attack viruses, two of which were for demonstration purposes.

or perhaps another one too.

Attacks before system startup

Bootkits have evolved from Proof-of-Concept development to mass distribution and have now effectively become open-source software.

Different ways to boot

I also think that in this context it is also worth mentioning that there are various forms of booting the operating system (or the executable program intended for this). There are many, but I would like to pay attention to loading the code from the network using Network Boot option (PXE), which allows us to run the program on the computer regardless of its operating system and even regardless of any storage medium that is directly connected to the computer:

What Is Network Booting (PXE) and How Can You Use It?

how to delete the content of text file without deleting itself

How about below:

File temp = new File("<your file name>");
if (temp.exists()) {
    RandomAccessFile raf = new RandomAccessFile(temp, "rw");
    raf.setLength(0);
}

How to sort the letters in a string alphabetically in Python

You can use reduce

>>> a = 'ZENOVW'
>>> reduce(lambda x,y: x+y, sorted(a))
'ENOVWZ'

How to determine the Schemas inside an Oracle Data Pump Export file

Assuming that you do not have the log file from the expdp job that generated the file in the first place, the easiest option would probably be to use the SQLFILE parameter to have impdp generate a file of DDL (based on a full import). Then you can grab the schema names from that file. Not ideal, of course, since impdp has to read the entire dump file to extract the DDL and then again to get to the schema you're interested in, and you have to do a bit of text file searching for the various CREATE USER statements, but it should be doable.

How does tuple comparison work in Python?

I had some confusion before regarding integer comparsion, so I will explain it to be more beginner friendly with an example

a = ('A','B','C') # see it as the string "ABC" b = ('A','B','D')

A is converted to its corresponding ASCII ord('A') #65 same for other elements

So, >> a>b # True you can think of it as comparing between string (It is exactly, actually)

the same thing goes for integers too.

x = (1,2,2) # see it the string "123" y = (1,2,3) x > y # False

because (1 is not greater than 1, move to the next, 2 is not greater than 2, move to the next 2 is less than three -lexicographically -)

The key point is mentioned in the answer above

think of it as an element is before another alphabetically not element is greater than an element and in this case consider all the tuple elements as one string.

PowerShell: Store Entire Text File Contents in Variable

To get the entire contents of a file:

$content = [IO.File]::ReadAllText(".\test.txt")

Number of lines:

([IO.File]::ReadAllLines(".\test.txt")).length

or

(gc .\test.ps1).length

Sort of hackish to include trailing empty line:

[io.file]::ReadAllText(".\desktop\git-python\test.ps1").split("`n").count

Sending data through POST request from a node.js server to a node.js server

Posting data is a matter of sending a query string (just like the way you would send it with an URL after the ?) as the request body.

This requires Content-Type and Content-Length headers, so the receiving server knows how to interpret the incoming data. (*)

var querystring = require('querystring');
var http = require('http');

var data = querystring.stringify({
      username: yourUsernameValue,
      password: yourPasswordValue
    });

var options = {
    host: 'my.url',
    port: 80,
    path: '/login',
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(data)
    }
};

var req = http.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log("body: " + chunk);
    });
});

req.write(data);
req.end();

(*) Sending data requires the Content-Type header to be set correctly, i.e. application/x-www-form-urlencoded for the traditional format that a standard HTML form would use.

It's easy to send JSON (application/json) in exactly the same manner; just JSON.stringify() the data beforehand.

URL-encoded data supports one level of structure (i.e. key and value). JSON is useful when it comes to exchanging data that has a nested structure.

The bottom line is: The server must be able to interpret the content type in question. It could be text/plain or anything else; there is no need to convert data if the receiving server understands it as it is.

Add a charset parameter (e.g. application/json; charset=Windows-1252) if your data is in an unusual character set, i.e. not UTF-8. This can be necessary if you read it from a file, for example.

MySQL Workbench Edit Table Data is read only

if the table does not have primary key or unique non-nullable defined, then MySql workbench could not able to edit the data.

Can Android Studio be used to run standard Java projects?

With Android Studio 0.6.1+ (and possibly earlier) you can easily develop standard Java (non-Android) apps.

This method has been tested on 0.8.2:

Start by creating a vanilla Android Phone app, using File > New Project. Then add a Java Library module to hold your Java Application code. (Choose 'Java Library' even if you're building an application). You'll find you can build and run Java apps with main() methods, Swing apps etc.

You'll want to delete the auto-generated Android "app" module, which you're not using. Go to File -> Project Structure, and delete it (select the "app" module in the box on the left, and click the 'minus' icon above the box). Now when you reopen File -> Project Structure -> Project, you'll see options for selecting the project SDK and language level, plus a bunch of other options that were previously hidden. You can go ahead and delete the "app" module from the disk.

In 0.6.1 you could avoid creating the android module in the first place:

Go to File > New Project. Fill in your application name. On the "form factors" selection page, where you state your minimum Android SDK, deselect the Mobile checkbox, and proceed with creating your project.

Once the project is created, go to File -> Project Structure -> Project, and set your JDK as the "Project SDK". Add a Java Library module to hold your application code as above.

using CASE in the WHERE clause

You can transform logical implication A => B to NOT A or B. This is one of the most basic laws of logic. In your case it is something like this:

SELECT *
FROM logs 
WHERE pw='correct' AND (id>=800 OR success=1)  
AND YEAR(timestamp)=2011

I also transformed NOT id<800 to id>=800, which is also pretty basic.

Spring @Transactional read-only propagation

By default transaction propagation is REQUIRED, meaning that the same transaction will propagate from a transactional caller to transactional callee. In this case also the read-only status will propagate. E.g. if a read-only transaction will call a read-write transaction, the whole transaction will be read-only.

Could you use the Open Session in View pattern to allow lazy loading? That way your handle method does not need to be transactional at all.

How to hide UINavigationBar 1px bottom line

A nice short Swift function to find the hairline in the subviews is this one:

 func findHairLineInImageViewUnder(view view: UIView) -> UIImageView? {
    if let hairLineView = view as? UIImageView where hairLineView.bounds.size.height <= 1.0 {
        return hairLineView
    }

    if let hairLineView = view.subviews.flatMap({self.findHairLineInImageViewUnder(view: $0)}).first {
      return hairLineView
    }

    return nil
}

Jenkins - how to build a specific branch

Best solution can be:

Add a string parameter in the existing job enter image description here

Then in the Source Code Management section update Branches to build to use the string parameter you defined enter image description here

If you see a checkbox labeled Lightweight checkout, make sure it is unchecked.

The configuration indicated in the images will tell the jenkins job to use master as the default branch, and for manual builds it will ask you to enter branch details (FYI: by default it's set to master)enter image description here

XML string to XML document

Depending on what document type you want you can use XmlDocument.LoadXml or XDocument.Load.

Using XAMPP, how do I swap out PHP 5.3 for PHP 5.2?

For OSX it's even easier. Your machine should come with a version of Apache already installed. All you need to do is locate the php lib for that version (which is likely 5.2.x) and swap it out.

This is the command you'd run from terminal*

cp /usr/libexec/apache2/libphp5.so /Applications/XAMPP/xamppfiles/modules/libphp5.so

I tested this on 10.5 (Leopard), so ymmv. * all the caveats about this might break your system, make a backup, blah blah blah.

Edit: On 10.4 (Tiger), Xampp 1.73, using the libphp5.so-files found at Mamp, this does not work at all.

How to get folder path from file path with CMD

In case the accepted answer by Wadih didn't work for you, try echo %CD%

Java Returning method which returns arraylist?

List<Integer> numbers = new TheClassName().myNumbers();

C# static class why use?

If a class is declared as static then the variables and methods need to be declared as static.

A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.

Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.

->The main features of a static class are:

  • They only contain static members.
  • They cannot be instantiated.
  • They are sealed.
  • They cannot contain Instance Constructors or simply constructors as we know that they are associated with objects and operates on data when an object is created.

Example

static class CollegeRegistration
{
  //All static member variables
   static int nCollegeId; //College Id will be same for all the students studying
   static string sCollegeName; //Name will be same
   static string sColegeAddress; //Address of the college will also same

    //Member functions
   public static int GetCollegeId()
   {
     nCollegeId = 100;
     return (nCollegeID);
   }
    //similarly implementation of others also.
} //class end


public class student
{
    int nRollNo;
    string sName;

    public GetRollNo()
    {
       nRollNo += 1;
       return (nRollNo);
    }
    //similarly ....
    public static void Main()
   {
     //Not required.
     //CollegeRegistration objCollReg= new CollegeRegistration();

     //<ClassName>.<MethodName>
     int cid= CollegeRegistration.GetCollegeId();
    string sname= CollegeRegistration.GetCollegeName();


   } //Main end
}

Difference between two numpy arrays in python

This is pretty simple with numpy, just subtract the arrays:

diffs = array1 - array2

I get:

diffs == array([ 0.1,  0.2,  0.3])

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

try this=> numpy.array(r) or numpy.array(yourvariable) followed by the command to compare whatever you wish to.

SOAP Action WSDL

We put together Web Services on Windows Server and were trying to connect with PHP on Apache. We got the same error. The issue ended up being different versions of the Soap client on the different servers. Matching the SOAP versions in the options on both servers solved the issue in our case.

415 Unsupported Media Type - POST json to OData service in lightswitch 2012

It looks like this issue has to do with the difference between the Content-Type and Accept headers. In HTTP, Content-Type is used in request and response payloads to convey the media type of the current payload. Accept is used in request payloads to say what media types the server may use in the response payload.

So, having a Content-Type in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type does matter.

If a server is not able to process the Content-Type of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept header, it will return a 406 error.)

In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.

You could fix this in one of two ways:

  1. Make the Content-Type "application/json;odata=verbose" in your POST request, or
  2. Include the DataServiceVersion header in the request and set it be less than v3. For example:

    DataServiceVersion: 2.0;
    

(Option 2 assumes that you aren't using any v3 features in your request payload.)

Errors: Data path ".builders['app-shell']" should have required property 'class'

it's work reinstall @angular-devkit/[email protected]

npm install @angular-devkit/[email protected] --save-dev

How to open a txt file and read numbers in Java

Good news in Java 8 we can do it in one line:

List<Integer> ints = Files.lines(Paths.get(fileName))
                          .map(Integer::parseInt)
                          .collect(Collectors.toList());

How to use if statements in LESS

LESS has guard expressions for mixins, not individual attributes.

So you'd create a mixin like this:

.debug(@debug) when (@debug = true) {
    header {
      background-color: yellow;
      #title {
          background-color: orange;
      }
    }

    article {
      background-color: red;
    }
}

And turn it on or off by calling .debug(true); or .debug(false) (or not calling it at all).

How to get the list of all database users

For the SQL Server Owner, you should be able to use:

select suser_sname(owner_sid) as 'Owner', state_desc, *
from sys.databases

For a list of SQL Users:

select * from master.sys.server_principals

Ref. SQL Server Tip: How to find the owner of a database through T-SQL

How do you test for the existence of a user in SQL Server?

dynamically add and remove view to viewpager

After figuring out which ViewPager methods are called by ViewPager and which are for other purposes, I came up with a solution. I present it here since I see a lot of people have struggled with this and I didn't see any other relevant answers.

First, here's my adapter; hopefully comments within the code are sufficient:

public class MainPagerAdapter extends PagerAdapter
{
  // This holds all the currently displayable views, in order from left to right.
  private ArrayList<View> views = new ArrayList<View>();

  //-----------------------------------------------------------------------------
  // Used by ViewPager.  "Object" represents the page; tell the ViewPager where the
  // page should be displayed, from left-to-right.  If the page no longer exists,
  // return POSITION_NONE.
  @Override
  public int getItemPosition (Object object)
  {
    int index = views.indexOf (object);
    if (index == -1)
      return POSITION_NONE;
    else
      return index;
  }

  //-----------------------------------------------------------------------------
  // Used by ViewPager.  Called when ViewPager needs a page to display; it is our job
  // to add the page to the container, which is normally the ViewPager itself.  Since
  // all our pages are persistent, we simply retrieve it from our "views" ArrayList.
  @Override
  public Object instantiateItem (ViewGroup container, int position)
  {
    View v = views.get (position);
    container.addView (v);
    return v;
  }

  //-----------------------------------------------------------------------------
  // Used by ViewPager.  Called when ViewPager no longer needs a page to display; it
  // is our job to remove the page from the container, which is normally the
  // ViewPager itself.  Since all our pages are persistent, we do nothing to the
  // contents of our "views" ArrayList.
  @Override
  public void destroyItem (ViewGroup container, int position, Object object)
  {
    container.removeView (views.get (position));
  }

  //-----------------------------------------------------------------------------
  // Used by ViewPager; can be used by app as well.
  // Returns the total number of pages that the ViewPage can display.  This must
  // never be 0.
  @Override
  public int getCount ()
  {
    return views.size();
  }

  //-----------------------------------------------------------------------------
  // Used by ViewPager.
  @Override
  public boolean isViewFromObject (View view, Object object)
  {
    return view == object;
  }

  //-----------------------------------------------------------------------------
  // Add "view" to right end of "views".
  // Returns the position of the new view.
  // The app should call this to add pages; not used by ViewPager.
  public int addView (View v)
  {
    return addView (v, views.size());
  }

  //-----------------------------------------------------------------------------
  // Add "view" at "position" to "views".
  // Returns position of new view.
  // The app should call this to add pages; not used by ViewPager.
  public int addView (View v, int position)
  {
    views.add (position, v);
    return position;
  }

  //-----------------------------------------------------------------------------
  // Removes "view" from "views".
  // Retuns position of removed view.
  // The app should call this to remove pages; not used by ViewPager.
  public int removeView (ViewPager pager, View v)
  {
    return removeView (pager, views.indexOf (v));
  }

  //-----------------------------------------------------------------------------
  // Removes the "view" at "position" from "views".
  // Retuns position of removed view.
  // The app should call this to remove pages; not used by ViewPager.
  public int removeView (ViewPager pager, int position)
  {
    // ViewPager doesn't have a delete method; the closest is to set the adapter
    // again.  When doing so, it deletes all its views.  Then we can delete the view
    // from from the adapter and finally set the adapter to the pager again.  Note
    // that we set the adapter to null before removing the view from "views" - that's
    // because while ViewPager deletes all its views, it will call destroyItem which
    // will in turn cause a null pointer ref.
    pager.setAdapter (null);
    views.remove (position);
    pager.setAdapter (this);

    return position;
  }

  //-----------------------------------------------------------------------------
  // Returns the "view" at "position".
  // The app should call this to retrieve a view; not used by ViewPager.
  public View getView (int position)
  {
    return views.get (position);
  }

  // Other relevant methods:

  // finishUpdate - called by the ViewPager - we don't care about what pages the
  // pager is displaying so we don't use this method.
}

And here's some snips of code showing how to use the adapter.

class MainActivity extends Activity
{
  private ViewPager pager = null;
  private MainPagerAdapter pagerAdapter = null;

  //-----------------------------------------------------------------------------
  @Override
  public void onCreate (Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView (R.layout.main_activity);

    ... do other initialization, such as create an ActionBar ...

    pagerAdapter = new MainPagerAdapter();
    pager = (ViewPager) findViewById (R.id.view_pager);
    pager.setAdapter (pagerAdapter);

    // Create an initial view to display; must be a subclass of FrameLayout.
    LayoutInflater inflater = context.getLayoutInflater();
    FrameLayout v0 = (FrameLayout) inflater.inflate (R.layout.one_of_my_page_layouts, null);
    pagerAdapter.addView (v0, 0);
    pagerAdapter.notifyDataSetChanged();
  }

  //-----------------------------------------------------------------------------
  // Here's what the app should do to add a view to the ViewPager.
  public void addView (View newPage)
  {
    int pageIndex = pagerAdapter.addView (newPage);
    // You might want to make "newPage" the currently displayed page:
    pager.setCurrentItem (pageIndex, true);
  }

  //-----------------------------------------------------------------------------
  // Here's what the app should do to remove a view from the ViewPager.
  public void removeView (View defunctPage)
  {
    int pageIndex = pagerAdapter.removeView (pager, defunctPage);
    // You might want to choose what page to display, if the current page was "defunctPage".
    if (pageIndex == pagerAdapter.getCount())
      pageIndex--;
    pager.setCurrentItem (pageIndex);
  }

  //-----------------------------------------------------------------------------
  // Here's what the app should do to get the currently displayed page.
  public View getCurrentPage ()
  {
    return pagerAdapter.getView (pager.getCurrentItem());
  }

  //-----------------------------------------------------------------------------
  // Here's what the app should do to set the currently displayed page.  "pageToShow" must
  // currently be in the adapter, or this will crash.
  public void setCurrentPage (View pageToShow)
  {
    pager.setCurrentItem (pagerAdapter.getItemPosition (pageToShow), true);
  }
}

Finally, you can use the following for your activity_main.xml layout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/view_pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

</android.support.v4.view.ViewPager>