Programs & Examples On #Onsubmit

onSubmit is the HTML event called when a submit button is pressed on a HTML form. The event is also called the form.submit() function is called. It can be used to trigger JavaScript to validate the form, pre-process its data, or block the submission altogether.

Should jQuery's $(form).submit(); not trigger onSubmit within the form tag?

Try to trigger() event in your function:

$("form").trigger('submit'); // and then... do submit()

Testing if value is a function

You can try modifying this technique to suit your needs:

 function isFunction() {
   var functionName = window.prompt('Function name: ');
   var isDefined = eval('(typeof ' + functionName + '==\'function\');');
   if (isDefined)
     eval(functionName + '();');
     alert('Function ' + functionName + ' does not exist');
 function anotherFunction() {
   alert('message from another function.');

Setting onSubmit in React.js

In your doSomething() function, pass in the event e and use e.preventDefault().

doSomething = function (e) {
    alert('it works!');

HTML form action and onsubmit issues



Oracle SQL - REGEXP_LIKE contains characters other than a-z or A-Z

Something like

select *
  from foo
 where regexp_like( col1, '[^[:alpha:]]' ) ;

should work

SQL> create table foo( col1 varchar2(100) );

Table created.

SQL> insert into foo values( 'abc' );

1 row created.

SQL> insert into foo values( 'abc123' );

1 row created.

SQL> insert into foo values( 'def' );

1 row created.

SQL> select *
  2    from foo
  3   where regexp_like( col1, '[^[:alpha:]]' ) ;


Age from birthdate in python

As I did not see the correct implementation, I recoded mine this way...

    def age_in_years(from_date,
  if (DEBUG):
    logger.debug("def age_in_years(from_date='%s', to_date='%s')" % (from_date, to_date))

  if (from_date>to_date): # swap when the lower bound is not the lower bound
    logger.debug('Swapping dates ...')
    tmp = from_date
    from_date = to_date
    to_date = tmp

  age_delta = to_date.year - from_date.year
  month_delta = to_date.month - from_date.month
  day_delta = -

  if (DEBUG):
    logger.debug("Delta's are : %i  / %i / %i " % (age_delta, month_delta, day_delta))

  if (month_delta>0  or (month_delta==0 and day_delta>=0)): 
    return age_delta 

  return (age_delta-1)

Assumption of being "18" on the 28th of Feb when born on the 29th is just wrong. Swapping the bounds can be left out ... it is just a personal convenience for my code :)

add an element to int [] array in java

public int[] return_Array() {

int[] a =new int[10];   
int b = 25;
for(int i=0; i<10; i++) {               
    a[i] = b * i;
return a;


Javascript : get <img> src and set as variable?

in this situation, you would grab the element by its id using getElementById and then just use .src

var youtubeimgsrc = document.getElementById("youtubeimg").src;

Check if a string has white space

With additions to the language it is much easier, plus you can take advantage of early return:

// Use includes method on string
function hasWhiteSpace(s) {
  const whitespaceChars = [' ', '\t', '\n'];
  return whitespaceChars.some(char => s.includes(char));

// Use character comparison
function hasWhiteSpace(s) {
  const whitespaceChars = [' ', '\t', '\n'];
  return Array.from(s).some(char => whitespaceChars.includes(char));

const withSpace = "Hello World!";
const noSpace = "HelloWorld!";



I did not run performance benchmark but these should be faster than regex but for small text snippets there won't be that much difference anyway.

How to get root access on Android emulator?

Here is the list of commands you have to run while the emulator is running, I test this solution for an avd on Android 2.2 :

adb shell mount -o rw,remount -t yaffs2 /dev/block/mtdblock03 /system  
adb push su /system/xbin/su  
adb shell chmod 06755 /system  
adb shell chmod 06755 /system/xbin/su

It assumes that the su binary is located in the working directory. You can find su and superuser here : You need to run these commands each time you launch the emulator. You can write a script that launch the emulator and root it.

How do I convert a number to a numeric, comma-separated formatted string?

You really shouldn't be doing that in SQL - you should be formatting it in the middleware instead. But I recognize that sometimes there is an edge case that requires one to do such a thing.

This looks like it might have your answer:

How do I format a number with commas in T-SQL?

$(document).ready not Working

function pageLoad() {
    $(document).ready(function () {

its the ScriptManager ajax making the problem use pageLoad() instead

How do you list volumes in docker containers?

You can get information about which volumes were specifically baked into the container by inspecting the container and looking in the JSON output and comparing a couple of the fields. When you run docker inspect myContainer, the Volumes and VolumesRW fields give you information about ALL of the volumes mounted inside a container, including volumes mounted in both the Dockerfile with the VOLUME directive, and on the command line with the docker run -v command. However, you can isolate which volumes were mounted in the container using the docker run -v command by checking for the HostConfig.Binds field in the docker inspect JSON output. To clarify, this HostConfig.Binds field tells you which volumes were mounted specifically in your docker run command with the -v option. So if you cross-reference this field with the Volumes field, you will be able to determine which volumes were baked into the container using VOLUME directives in the Dockerfile.

A grep could accomplish this like:

$ docker inspect myContainer | grep -C2 Binds
"HostConfig": {
    "Binds": [


$ docker inspect myContainer | grep -C3 -e "Volumes\":"
"Volumes": {
    "/data": "/var/lib/docker...",
    "/config": "/var/lib/docker...",
    "/registry": "/var/docker/docker-registry/config"

And in my example, you can see I've mounted /var/docker/docker-registry/config into the container as /registry using the -v option in my docker run command, and I've mounted the /data and /config volumes using the VOLUME directive in my Dockerfile. The container does not need to be running to get this information, but it needs to have been run at least one time in order to populate the HostConfig JSON output of your docker inspect command.

What determines the monitor my app runs on?

Do not hold me to this but I am pretty sure it depends on the application it self. I know many always open on the main monitor, some will reopen to the same monitor they were previously run in, and some you can set. I know for example I have shortcuts to open command windows to particular directories, and each has an option in their properties to the location to open the window in. While Outlook just remembers and opens in the last screen it was open in. Then other apps open in what ever window the current focus is in.

So I am not sure there is a way to tell every program where to open. Hope that helps some.

How to draw vertical lines on a given plot in matplotlib

For multiple lines

xposition = [0.3, 0.4, 0.45]
for xc in xposition:
    plt.axvline(x=xc, color='k', linestyle='--')

Command to find information about CPUs on a UNIX machine

Firstly, it probably depends which version of Solaris you're running, but also what hardware you have.

On SPARC at least, you have psrinfo to show you processor information, which run on its own will show you the number of CPUs the machine sees. psrinfo -p shows you the number of physical processors installed. From that you can deduce the number of threads/cores per physical processors.

prtdiag will display a fair bit of info about the hardware in your machine. It looks like on a V240 you do get memory channel info from prtdiag, but you don't on a T2000. I guess that's an architecture issue between UltraSPARC IIIi and UltraSPARC T1.

How to validate an email address using a regular expression?

Nice, I converted the code into java to match the compiler

String pattern ="(?:[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?|\\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-zA-Z0-9-]*[a-zA-Z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";

How to insert text in a td with id, using JavaScript

append a text node as follows

var td1 = document.getElementById('td1');
var text = document.createTextNode("some text");

How to use GROUP_CONCAT in a CONCAT in MySQL


PHP Warning: mysqli_connect(): (HY000/2002): Connection refused

For me to make it work again I just deleted the files





from :


Mac 10.13.3
MAMP:Version 4.3 (853)

How do you declare an interface in C++?

My answer is basically the same as the others but I think there are two other important things to do:

  1. Declare a virtual destructor in your interface or make a protected non-virtual one to avoid undefined behaviours if someone tries to delete an object of type IDemo.

  2. Use virtual inheritance to avoid problems whith multiple inheritance. (There is more often multiple inheritance when we use interfaces.)

And like other answers:

  • Make a class with pure virtual methods.
  • Use the interface by creating another class that overrides those virtual methods.

    class IDemo
            virtual void OverrideMe() = 0;
            virtual ~IDemo() {}


    class IDemo
            virtual void OverrideMe() = 0;
            ~IDemo() {}


    class Child : virtual public IDemo
            virtual void OverrideMe()
                //do stuff

Specify the date format in XMLGregorianCalendar

Much simpler using only SimpleDateFormat, without passing all the parameters individual:

    String FORMATER = "yyyy-MM-dd'T'HH:mm:ss'Z'";

    DateFormat format = new SimpleDateFormat(FORMATER);

    Date date = new Date();
    XMLGregorianCalendar gDateFormatted =

Full example here.

Note: This is working only to remove the last 2 fields: milliseconds and timezone or to remove the entire time component using formatter yyyy-MM-dd.

How to scroll HTML page to given anchor?

Way simpler:

var element_to_scroll_to = document.getElementById('anchorName2');
// Or:
var element_to_scroll_to = document.querySelectorAll('.my-element-class')[0];
// Or:
var element_to_scroll_to = $('.my-element-class')[0];
// Basically `element_to_scroll_to` just have to be a reference
// to any DOM element present on the page
// Then:

C# List<> Sort by x then y

I had an issue where OrderBy and ThenBy did not give me the desired result (or I just didn't know how to use them correctly).

I went with a list.Sort solution something like this.

    var data = (from o in database.Orders Where o.ClientId.Equals(clientId) select new {
    OrderId =,
    OrderDate = o.orderDate,
    OrderBoolean = (SomeClass.SomeFunction(o.orderBoolean) ? 1 : 0)

    data.Sort((o1, o2) => (o2.OrderBoolean.CompareTo(o1.OrderBoolean) != 0
    o2.OrderBoolean.CompareTo(o1.OrderBoolean) : o1.OrderDate.Value.CompareTo(o2.OrderDate.Value)));

default value for struct member in C

Another approach, if the struct allows it, is to use a #define with the default values inside:

#define MYSTRUCT_INIT { 0, 0, true }

typedef struct
    int id;
    int flag;
    bool foo;
} MyStruct;


MyStruct val = MYSTRUCT_INIT;

jQuery - Sticky header that shrinks when scrolling down

Based on twitter scroll trouble (

Here is my solution, throttling the js scroll event (usefull for mobile devices)


$(function() {
    var $document, didScroll, offset;
    offset = $('.menu').position().top;
    $document = $(document);
    didScroll = false;
    $(window).on('scroll touchmove', function() {
      return didScroll = true;
    return setInterval(function() {
      if (didScroll) {
        $('.menu').toggleClass('fixed', $document.scrollTop() > offset);
        return didScroll = false;
    }, 250);


.menu {
  background: pink;
  top: 5px;

.fixed {
  width: 100%;
  position: fixed;
  top: 0;


<div class="menu">MENU FIXED ON TOP</div>

Jenkins Host key verification failed

Best way you can just use your "git url" in 'https" URL format in the Jenkinsfile or wherever you want.

git url: ''

What is the meaning of 'No bundle URL present' in react-native?

As instructed in the error message:

Agreeing to the Xcode/iOS license requires admin privileges, please run "sudo xcodebuild -license" and then retry this command.

Running the following command worked:

sudo xcodebuild -license

Spring schemaLocation fails when there is no internet connection

You should check that the spring.handlers and spring.schemas files are on the classpath and have the right content.

This can be done with ClassLoader.getResource(..). You can run the method with a remote debugger in the runtime environment. The extensible XML authoring setup is described in the Spring Reference B.5. Registering the handler and the schema.

Normally, the files should be in the spring jar (springframework.jar/META-INF/) and on the classpath when Spring can be initiated.

Get HTML inside iframe using jQuery

var iframe = document.getElementById('iframe');

How do I create a shortcut via command-line in Windows?

Nirsoft's NirCMD can create shortcuts from a command line, too. (Along with a pile of other functions.) Free and available here:

Full instructions here: (Scroll down to the "shortcut" section.)

Yes, using nircmd does mean you are using another 3rd-party .exe, but it can do some functions not in (most of) the above solutions (e.g., pick a icon # in a dll with multiple icons, assign a hot-key, and set the shortcut target to be minimized or maximized).

Though it appears that the shortcutjs.bat solution above can do most of that, too, but you'll need to dig more to find how to properly assign those settings. Nircmd is probably simpler.

What is a quick way to force CRLF in C# / .NET?

This is a quick way to do that, I mean.

It does not use an expensive regex function. It also does not use multiple replacement functions that each individually did loop over the data with several checks, allocations, etc.

So the search is done directly in one for loop. For the number of times that the capacity of the result array has to be increased, a loop is also used within the Array.Copy function. That are all the loops. In some cases, a larger page size might be more efficient.

public static string NormalizeNewLine(this string val)
    if (string.IsNullOrEmpty(val))
        return val;

    const int page = 6;
    int a = page;
    int j = 0;
    int len = val.Length;
    char[] res = new char[len];

    for (int i = 0; i < len; i++)
        char ch = val[i];

        if (ch == '\r')
            int ni = i + 1;
            if (ni < len && val[ni] == '\n')
                res[j++] = '\r';
                res[j++] = '\n';
                if (a == page) // Ensure capacity
                    char[] nres = new char[res.Length + page];
                    Array.Copy(res, 0, nres, 0, res.Length);
                    res = nres;
                    a = 0;

                res[j++] = '\r';
                res[j++] = '\n';
        else if (ch == '\n')
            int ni = i + 1;
            if (ni < len && val[ni] == '\r')
                res[j++] = '\r';
                res[j++] = '\n';
                if (a == page) // Ensure capacity
                    char[] nres = new char[res.Length + page];
                    Array.Copy(res, 0, nres, 0, res.Length);
                    res = nres;
                    a = 0;

                res[j++] = '\r';
                res[j++] = '\n';
            res[j++] = ch;

    return new string(res, 0, j);

I now that '\n\r' is not actually used on basic platforms. But who would use two types of linebreaks in succession to indicate two linebreaks?

If you want to know that, then you need to take a look before to know if the \n and \r both are used separately in the same document.

How to find common elements from multiple vectors?

A good answer already, but there are a couple of other ways to do this:



tst <- c(unique(a),unique(b),unique(c))
tst <- tst[duplicated(tst)]

You can obviously omit the unique calls if you know that there are no repeated values within a, b or c.

Compare two objects in Java with possible null values

This is what Java internal code uses (on other compare methods):

public static boolean compare(String str1, String str2) {
    return (str1 == null ? str2 == null : str1.equals(str2));

How to Rotate a UIImage 90 degrees?

I believe the easiest way (and thread safe too) is to do:

//assume that the image is loaded in landscape mode from disk
UIImage * landscapeImage = [UIImage imageNamed:imgname];
UIImage * portraitImage = [[UIImage alloc] initWithCGImage: landscapeImage.CGImage
                                                     scale: 1.0
                                               orientation: UIImageOrientationRight];

Note: As Brainware said this only modifies the orientation data of the image - the pixel data is untouched. For some applications, this may not be enough.

Or in Swift:

    let landscapeImage = UIImage(named: "imgname"),
    let landscapeCGImage = landscapeImage.cgImage
else { return }
let portraitImage = UIImage(cgImage: landscapeCGImage, scale: landscapeImage.scale, orientation: .right)

SQL Server 2005 Using CHARINDEX() To split a string

Here's a little function that will do "NATO encoding" for you:

   @String varchar(max)
   L2 (N) AS (SELECT 1 FROM L1, L1 B),
   L3 (N) AS (SELECT 1 FROM L2, L2 B),
   L4 (N) AS (SELECT 1 FROM L3, L3 B),
   L5 (N) AS (SELECT 1 FROM L4, L4 C),
   L6 (N) AS (SELECT 1 FROM L5, L5 C),
   Nums (Num) AS (SELECT Row_Number() OVER (ORDER BY (SELECT 1)) FROM L6)
      NATOString = Substring((
            Convert(varchar(max), ' ' + D.Word)
            Nums N
            INNER JOIN (VALUES
               ('A', 'Alpha'),
               ('B', 'Beta'),
               ('C', 'Charlie'),
               ('D', 'Delta'),
               ('E', 'Echo'),
               ('F', 'Foxtrot'),
               ('G', 'Golf'),
               ('H', 'Hotel'),
               ('I', 'India'),
               ('J', 'Juliet'),
               ('K', 'Kilo'),
               ('L', 'Lima'),
               ('M', 'Mike'),
               ('N', 'November'),
               ('O', 'Oscar'),
               ('P', 'Papa'),
               ('Q', 'Quebec'),
               ('R', 'Romeo'),
               ('S', 'Sierra'),
               ('T', 'Tango'),
               ('U', 'Uniform'),
               ('V', 'Victor'),
               ('W', 'Whiskey'),
               ('X', 'X-Ray'),
               ('Y', 'Yankee'),
               ('Z', 'Zulu'),
               ('0', 'Zero'),
               ('1', 'One'),
               ('2', 'Two'),
               ('3', 'Three'),
               ('4', 'Four'),
               ('5', 'Five'),
               ('6', 'Six'),
               ('7', 'Seven'),
               ('8', 'Eight'),
               ('9', 'Niner')
            ) D (Digit, Word)
               ON Substring(@String, N.Num, 1) = D.Digit
            N.Num <= Len(@String)
         FOR XML PATH(''), TYPE
      ).value('.[1]', 'varchar(max)'), 2, 2147483647)

This function will work on even very long strings, and performs pretty well (I ran it against a 100,000-character string and it returned in 589 ms). Here's an example of how to use it:

SELECT NATOString FROM dbo.NATOEncode('LD-23DSP-1430');
-- Output: Lima Delta Two Three Delta Sierra Papa One Four Three Zero

I intentionally made it a table-valued function so it could be inlined into a query if you run it against many rows at once, just use CROSS APPLY or wrap the above example in parentheses to use it as a value in the SELECT clause (you can put a column name in the function parameter position).

How to use FormData for AJAX file upload?

Good morning.

I was have the same problem with upload of multiple images. Solution was more simple than I had imagined: include [] in the name field.

<input type="file" name="files[]" multiple>

I did not make any modification on FormData.

Why is exception.printStackTrace() considered bad practice?

In server applications the stacktrace blows up your stdout/stderr file. It may become larger and larger and is filled with useless data because usually you have no context and no timestamp and so on.

e.g. catalina.out when using tomcat as container

How can I pass data from Flask to JavaScript in a template?

Using a data attribute on an HTML element avoids having to use inline scripting, which in turn means you can use stricter CSP rules for increased security.

Specify a data attribute like so:

<div id="mydiv" data-geocode='{{ geocode|tojson }}'>...</div>

Then access it in a static JavaScript file like so:

// Raw JavaScript
var geocode = JSON.parse(document.getElementById("mydiv").dataset.geocode);

// jQuery
var geocode = JSON.parse($("#mydiv").data("geocode"));

Using LINQ to group by multiple properties and sum

Use the .Select() after grouping:

var agencyContracts = _agencyContractsRepository.AgencyContracts
    .GroupBy(ac => new
                       ac.AgencyContractID, // required by your view model. should be omited
                                            // in most cases because group by primary key
                                            // makes no sense.
    .Select(ac => new AgencyContractViewModel
                       AgencyContractID = ac.Key.AgencyContractID,
                       AgencyId = ac.Key.AgencyID,
                       VendorId = ac.Key.VendorID,
                       RegionId = ac.Key.RegionID,
                       Amount = ac.Sum(acs => acs.Amount),
                       Fee = ac.Sum(acs => acs.Fee)

Why am I getting the message, "fatal: This operation must be run in a work tree?"

If none of the above usual ways help you, look at the call trace underneath this error message ("fatal: This operation . . .") and locate the script and line which is raising the actual error. Once you locate that error() call, disable it and see if the operation you are trying completes even with some warnings/messages - ignore them for now. If so, finally after completing it might mention the part of the operation that was not completed successfully. Now, address this part separately as applicable.

Relating above logic to my case, I was getting this error message "fatal: This operation . . ." when I was trying to get the Android-x86 code with repo sync . . .. and the call trace showed raise GitError("cannot initialize work tree") as the error() call causing the above error message ("fatal: . . ."). So, after commenting that GitError() in .repo/repo/, repo sync . . . continued and finally indicated error for three projects that were not properly synced. I just deleted their *.git folders from their relevant paths in the Android-x86 source tree locally and ran repo sync . . . again and tasted success!

Https Connection Android

I don't know about the Android specifics for ssl certificates, but it would make sense that Android won't accept a self signed ssl certificate off the bat. I found this post from android forums which seems to be addressing the same issue:

How to generate a number of most distinctive colors in R?

I joined all qualitative palettes from RColorBrewer package. Qualitative palettes are supposed to provide X most distinctive colours each. Of course, mixing them joins into one palette also similar colours, but that's the best I can get (74 colors).

n <- 60
qual_col_pals =[$category == 'qual',]
col_vector = unlist(mapply(brewer.pal, qual_col_pals$maxcolors, rownames(qual_col_pals)))
pie(rep(1,n), col=sample(col_vector, n))


Other solution is: take all R colors from graphical devices and sample from them. I removed shades of grey as they are too similar. This gives 433 colors

color = grDevices::colors()[grep('gr(a|e)y', grDevices::colors(), invert = T)]

set of 20 colours

pie(rep(1,n), col=sample(color, n))

with 200 colors n = 200:

pie(rep(1,n), col=sample(color, n))

set of 200 colours

How does the 'binding' attribute work in JSF? When and how should it be used?

How does it work?

When a JSF view (Facelets/JSP file) get built/restored, a JSF component tree will be produced. At that moment, the view build time, all binding attributes are evaluated (along with id attribtues and taghandlers like JSTL). When the JSF component needs to be created before being added to the component tree, JSF will check if the binding attribute returns a precreated component (i.e. non-null) and if so, then use it. If it's not precreated, then JSF will autocreate the component "the usual way" and invoke the setter behind binding attribute with the autocreated component instance as argument.

In effects, it binds a reference of the component instance in the component tree to a scoped variable. This information is in no way visible in the generated HTML representation of the component itself. This information is in no means relevant to the generated HTML output anyway. When the form is submitted and the view is restored, the JSF component tree is just rebuilt from scratch and all binding attributes will just be re-evaluated like described in above paragraph. After the component tree is recreated, JSF will restore the JSF view state into the component tree.

Component instances are request scoped!

Important to know and understand is that the concrete component instances are effectively request scoped. They're newly created on every request and their properties are filled with values from JSF view state during restore view phase. So, if you bind the component to a property of a backing bean, then the backing bean should absolutely not be in a broader scope than the request scope. See also JSF 2.0 specitication chapter 3.1.5:

3.1.5 Component Bindings


Component bindings are often used in conjunction with JavaBeans that are dynamically instantiated via the Managed Bean Creation facility (see Section 5.8.1 “VariableResolver and the Default VariableResolver”). It is strongly recommend that application developers place managed beans that are pointed at by component binding expressions in “request” scope. This is because placing it in session or application scope would require thread-safety, since UIComponent instances depends on running inside of a single thread. There are also potentially negative impacts on memory management when placing a component binding in “session” scope.

Otherwise, component instances are shared among multiple requests, possibly resulting in "duplicate component ID" errors and "weird" behaviors because validators, converters and listeners declared in the view are re-attached to the existing component instance from previous request(s). The symptoms are clear: they are executed multiple times, one time more with each request within the same scope as the component is been bound to.

And, under heavy load (i.e. when multiple different HTTP requests (threads) access and manipulate the very same component instance at the same time), you may face sooner or later an application crash with e.g. Stuck thread at UIComponent.popComponentFromEL, or Java Threads at 100% CPU utilization using richfaces UIDataAdaptorBase and its internal HashMap, or even some "strange" IndexOutOfBoundsException or ConcurrentModificationException coming straight from JSF implementation source code while JSF is busy saving or restoring the view state (i.e. the stack trace indicates saveState() or restoreState() methods and like).

Using binding on a bean property is bad practice

Regardless, using binding this way, binding a whole component instance to a bean property, even on a request scoped bean, is in JSF 2.x a rather rare use case and generally not the best practice. It indicates a design smell. You normally declare components in the view side and bind their runtime attributes like value, and perhaps others like styleClass, disabled, rendered, etc, to normal bean properties. Then, you just manipulate exactly that bean property you want instead of grabbing the whole component and calling the setter method associated with the attribute.

In cases when a component needs to be "dynamically built" based on a static model, better is to use view build time tags like JSTL, if necessary in a tag file, instead of createComponent(), new SomeComponent(), getChildren().add() and what not. See also How to refactor snippet of old JSP to some JSF equivalent?

Or, if a component needs to be "dynamically rendered" based on a dynamic model, then just use an iterator component (<ui:repeat>, <h:dataTable>, etc). See also How to dynamically add JSF components.

Composite components is a completely different story. It's completely legit to bind components inside a <cc:implementation> to the backing component (i.e. the component identified by <cc:interface componentType>. See also a.o. Split java.util.Date over two h:inputText fields representing hour and minute with f:convertDateTime and How to implement a dynamic list with a JSF 2.0 Composite Component?

Only use binding in local scope

However, sometimes you'd like to know about the state of a different component from inside a particular component, more than often in use cases related to action/value dependent validation. For that, the binding attribute can be used, but not in combination with a bean property. You can just specify an in the local EL scope unique variable name in the binding attribute like so binding="#{foo}" and the component is during render response elsewhere in the same view directly as UIComponent reference available by #{foo}. Here are several related questions where such a solution is been used in the answer:

See also:

Styling Password Fields in CSS

When I needed to create similar dots in input[password] I use a custom font in base64 (with 2 glyphs see above 25CF and 2022)

SCSS styles

@font-face {
  font-family: 'pass';
  font-style: normal;
  font-weight: 400;

input.password {
  font-family: 'pass', 'Roboto', Helvetica, Arial, sans-serif ;
  font-size: 18px;
  &::-webkit-input-placeholder {
    transform: scale(0.77);
    transform-origin: 0 50%;
  &::-moz-placeholder {
    font-size: 14px;
    opacity: 1;
  &:-ms-input-placeholder {
    font-size: 14px;
    font-family: 'Roboto', Helvetica, Arial, sans-serif;

After that, I got identical display input[password]

Retrieve a single file from a repository

I use this

$ cat ~/.wgetrc
check_certificate = off

$ wget
HTTP request sent, awaiting response... 200 OK
Length: 11339 (11K) [text/plain]
Saving to: `grunt.js'

LINQ Aggregate algorithm explained

Aggregate is basically used to Group or Sum up data.

According to MSDN "Aggregate Function Applies an accumulator function over a sequence."

Example 1: Add all the numbers in a array.

int[] numbers = new int[] { 1,2,3,4,5 };
int aggregatedValue = numbers.Aggregate((total, nextValue) => total + nextValue);

*important: The initial aggregate value by default is the 1 element in the sequence of collection. i.e: the total variable initial value will be 1 by default.

variable explanation

total: it will hold the sum up value(aggregated value) returned by the func.

nextValue: it is the next value in the array sequence. This value is than added to the aggregated value i.e total.

Example 2: Add all items in an array. Also set the initial accumulator value to start adding with from 10.

int[] numbers = new int[] { 1,2,3,4,5 };
int aggregatedValue = numbers.Aggregate(10, (total, nextValue) => total + nextValue);

arguments explanation:

the first argument is the initial(starting value i.e seed value) which will be used to start addition with the next value in the array.

the second argument is a func which is a func that takes 2 int. this will hold same as before the sum up value(aggregated value) returned by the func after the calculation.

2.nextValue: : it is the next value in the array sequence. This value is than added to the aggregated value i.e total.

Also debugging this code will give you a better understanding of how aggregate work.

Python ValueError: too many values to unpack

for k, m in self.materials.items():


miles_dict = {'Monday':1, 'Tuesday':2.3, 'Wednesday':3.5, 'Thursday':0.9}
for k, v in miles_dict.items():
    print("%s: %s" % (k, v))

Sort a list alphabetically

You can sort a list in-place just by calling List<T>.Sort:


That will use the natural ordering of elements, which is fine in your case.

EDIT: Note that in your code, you'd need


as the Sort method is only defined in List<T>, not IList<T>. If you need to sort it from the outside where you don't have access to it as a List<T> (you shouldn't cast it as the List<T> part is an implementation detail) you'll need to do a bit more work.

I don't know of any IList<T>-based in-place sorts in .NET, which is slightly odd now I come to think of it. IList<T> provides everything you'd need, so it could be written as an extension method. There are lots of quicksort implementations around if you want to use one of those.

If you don't care about a bit of inefficiency, you could always use:

public void Sort<T>(IList<T> list)
    List<T> tmp = new List<T>(list);
    for (int i = 0; i < tmp.Count; i++)
        list[i] = tmp[i];

In other words, copy, sort in place, then copy the sorted list back.

You can use LINQ to create a new list which contains the original values but sorted:

var sortedList = list.OrderBy(x => x).ToList();

It depends which behaviour you want. Note that your shuffle method isn't really ideal:

  • Creating a new Random within the method runs into some of the problems shown here
  • You can declare val inside the loop - you're not using that default value
  • It's more idiomatic to use the Count property when you know you're working with an IList<T>
  • To my mind, a for loop is simpler to understand than traversing the list backwards with a while loop

There are other implementations of shuffling with Fisher-Yates on Stack Overflow - search and you'll find one pretty quickly.

Does Spring @Transactional attribute work on a private method?

The answer is no. Please see Spring Reference: Using @Transactional :

The @Transactional annotation may be placed before an interface definition, a method on an interface, a class definition, or a public method on a class

Upload artifacts to Nexus, without Maven

If you need a convenient command line interface or python API, look at repositorytools

Using it, you can upload artifact to nexus with command

artifact upload foo-1.2.3.ext releases com.fooware

To make it work, you will also need to set some environment variables

export REPOSITORY_USER=admin
export REPOSITORY_PASSWORD=mysecretpassword

How to lose margin/padding in UITextView?

In case you want to set a HTML string and avoid the bottom padding, please make sure that you are not using block tags i.e. div, p.

In my case this was the reason. You can easily test it out by replacing occurrences of block tags with i.e. span tag.

CMake does not find Visual C++ compiler

This might be another solution for those with the latest Windows 10 creator version:

Stack Overflow post Fatal error LNK1104: cannot open file 'gdi32.lib'

HTML/CSS: Making two floating divs the same height

you can get this working with js:

    $(document).ready(function() {
        var height = Math.max($("#left").height(), $("#right").height());

How to put wildcard entry into /etc/hosts?

It happens that /etc/hosts file doesn't support wild card entries.

You'll have to use other services like dnsmasq. To enable it in dnsmasq, just edit dnsmasq.conf and add the following line:


adb connection over tcp not working now

Try to do port forwarding,

adb forward tcp:<PC port> tcp:<device port>.


adb forward tcp:5555 tcp:5555.

sounds like 5555 port is captured so use other one. As I know 7612 is empty


C:\Users\m>adb forward tcp:7612 tcp:7612

C:\Users\m>adb tcpip 7612
restarting in TCP mode port: 7612

C:\Users\m>adb connect
connected to

Be sure that you connect to the right IP address. (You can download Network Info 2 to check your IP)

How to pass parameters to the DbContext.Database.ExecuteSqlCommand method?

If your underlying database data types are varchar then you should stick with the approach below. Otherwise the query would have a huge performance impact.

var firstName = new SqlParameter("@firstName", System.Data.SqlDbType.VarChar, 20)
                                Value = "whatever"

var id = new SqlParameter("@id", System.Data.SqlDbType.Int)
                                Value = 1
ctx.Database.ExecuteSqlCommand(@"Update [User] SET FirstName = @firstName WHERE Id = @id"
                               , firstName, id);

You can check Sql profiler to see the difference.

Downloading folders from aws s3, cp or sync?

In case you need to use another profile, especially cross account. you need to add the profile in the config file

[profile profileName]
region = us-east-1
role_arn = arn:aws:iam::XXX:role/XXXX
source_profile = default

and then if you are accessing only a single file

aws s3 cp s3://crossAccountBucket/dir localdir --profile profileName

Jquery If radio button is checked

Try this:

if ( jQuery('#postageyes').is(':checked') ){ ... }

How to find all links / pages on a website

function getalllinks($url) {
    $links = array();
    if ($fp = fopen($url, 'r')) {
        $content = '';
        while ($line = fread($fp, 1024)) {
            $content. = $line;
    $textLen = strlen($content);
    if ($textLen > 10) {
        $startPos = 0;
        $valid = true;
        while ($valid) {
            $spos = strpos($content, '<a ', $startPos);
            if ($spos < $startPos) $valid = false;
            $spos = strpos($content, 'href', $spos);
            $spos = strpos($content, '"', $spos) + 1;
            $epos = strpos($content, '"', $spos);
            $startPos = $epos;
            $link = substr($content, $spos, $epos - $spos);
            if (strpos($link, 'http://') !== false) $links[] = $link;
    return $links;

try this code....

Pass variables by reference in JavaScript

JavaScript not being strong type. It allows you to resolve problems in many different ways, as it seem in this question.

However, for a maintainability point of view, I would have to agree with Bart Hofland. A function should get arguments to do something with and return the result. Making them easily reusable.

If you feel that variables need to be passed by reference, you may be better served building them into objects, IMHO.

How to VueJS router-link active style

The :active pseudo-class is not the same as adding a class to style the element.

The :active CSS pseudo-class represents an element (such as a button) that is being activated by the user. When using a mouse, "activation" typically starts when the mouse button is pressed down and ends when it is released.

What we are looking for is a class, such as .active, which we can use to style the navigation item.

For a clearer example of the difference between :active and .active see the following snippet:

li:active {_x000D_
  background-color: #35495E;_x000D_
_x000D_ {_x000D_
  background-color: #41B883;_x000D_
  <li>:active (pseudo-class) - Click me!</li>_x000D_
  <li class="active">.active (class)</li>_x000D_


vue-router automatically applies two active classes, .router-link-active and .router-link-exact-active, to the <router-link> component.


This class is applied automatically to the <router-link> component when its target route is matched.

The way this works is by using an inclusive match behavior. For example, <router-link to="/foo"> will get this class applied as long as the current path starts with /foo/ or is /foo.

So, if we had <router-link to="/foo"> and <router-link to="/foo/bar">, both components would get the router-link-active class when the path is /foo/bar.


This class is applied automatically to the <router-link> component when its target route is an exact match. Take into consideration that both classes, router-link-active and router-link-exact-active, will be applied to the component in this case.

Using the same example, if we had <router-link to="/foo"> and <router-link to="/foo/bar">, the router-link-exact-activeclass would only be applied to <router-link to="/foo/bar"> when the path is /foo/bar.

The exact prop

Lets say we have <router-link to="/">, what will happen is that this component will be active for every route. This may not be something that we want, so we can use the exact prop like so: <router-link to="/" exact>. Now the component will only get the active class applied when it is an exact match at /.


We can use these classes to style our element, like so:

 nav li:hover,
 nav li.router-link-active,
 nav li.router-link-exact-active {
   background-color: indianred;
   cursor: pointer;

The <router-link> tag was changed using the tag prop, <router-link tag="li" />.

Change default classes globally

If we wish to change the default classes provided by vue-router globally, we can do so by passing some options to the vue-router instance like so:

const router = new VueRouter({
  linkActiveClass: "active",
  linkExactActiveClass: "exact-active",

Change default classes per component instance (<router-link>)

If instead we want to change the default classes per <router-link> and not globally, we can do so by using the active-class and exact-active-class attributes like so:

<router-link to="/foo" active-class="active">foo</router-link>

<router-link to="/bar" exact-active-class="exact-active">bar</router-link>

v-slot API

Vue Router 3.1.0+ offers low level customization through a scoped slot. This comes handy when we wish to style the wrapper element, like a list element <li>, but still keep the navigation logic in the anchor element <a>.

  v-slot="{ href, route, navigate, isActive, isExactActive }"
    :class="[isActive && 'router-link-active', isExactActive && 'router-link-exact-active']"
    <a :href="href" @click="navigate">{{ route.fullPath }}</a>

Check if an array item is set in JS

The most effective way:

if (array.indexOf(element) > -1) {


How to create a custom scrollbar on a div (Facebook style)

Facebook uses a very clever technique I described in context of my scrollbar plugin jsFancyScroll:

The scrolled content is actually scrolled natively by the browser scrolling mechanisms while the native scrollbar is hidden by using overflow definitions and the custom scrollbar is kept in sync by bi-directional event listening.

Feel free to use my plugin for your project: :)

I highly recommend it over plugins such as TinyScrollbar that come with terrible performance issues!

How do I convert seconds to hours, minutes and seconds?

This is how I got it.

def sec2time(sec, n_msec=3):
    ''' Convert seconds to 'D days, HH:MM:SS.FFF' '''
    if hasattr(sec,'__len__'):
        return [sec2time(s) for s in sec]
    m, s = divmod(sec, 60)
    h, m = divmod(m, 60)
    d, h = divmod(h, 24)
    if n_msec > 0:
        pattern = '%%02d:%%02d:%%0%d.%df' % (n_msec+3, n_msec)
        pattern = r'%02d:%02d:%02d'
    if d == 0:
        return pattern % (h, m, s)
    return ('%d days, ' + pattern) % (d, h, m, s)

Some examples:

$ sec2time(10, 3)
Out: '00:00:10.000'

$ sec2time(1234567.8910, 0)
Out: '14 days, 06:56:07'

$ sec2time(1234567.8910, 4)
Out: '14 days, 06:56:07.8910'

$ sec2time([12, 345678.9], 3)
Out: ['00:00:12.000', '4 days, 00:01:18.900']

Character reading from file in Python

Not sure about the (errors="ignore") option but it seems to work for files with strange Unicode characters.

with open(fName, "rb") as fData:
    lines =
    lines = [line.decode("utf-8", errors="ignore") for line in lines]

Appending values to dictionary in Python

To append entries to the table:

for row in data:
    name = ???     # figure out the name of the drug
    number = ???   # figure out the number you want to append

To loop through the data:

for name, numbers in drug_dictionary.items():
    print name, numbers

Using pg_dump to only get insert statements from one table within database

Put into a script I like something like that:

set -o xtrace # remove me after debug

LOCATION="${BASE_DIR}/myApp_$(date +%Y%m%d_%H%M%S)"

# Create backups directory if not exists
if [[ ! -e $BASE_DIR ]];then
       mkdir $BASE_DIR
       chown -R postgres:postgres $BASE_DIR

sudo -H -u postgres pg_dump --column-inserts --data-only --table=$TABLE $DB_NAME > $FNAME
sudo gzip $FNAME

Using Oracle to_date function for date string with milliseconds

You have to change date class to timestamp.

String s=df.format(c.getTime());
java.util.Date parsedUtilDate = df.parse(s);  
java.sql.Timestamp timestamp = new java.sql.Timestamp(parsedUtilDate.getTime());

What is the most efficient way to store a list in the Django models?

A simple way to store a list in Django is to just convert it into a JSON string, and then save that as Text in the model. You can then retrieve the list by converting the (JSON) string back into a python list. Here's how:

The "list" would be stored in your Django model like so:

class MyModel(models.Model):
    myList = models.TextField(null=True) # JSON-serialized (text) version of your list

In your view/controller code:

Storing the list in the database:

import simplejson as json # this would be just 'import json' in Python 2.7 and later

myModel = MyModel()
listIWantToStore = [1,2,3,4,5,'hello']
myModel.myList = json.dumps(listIWantToStore)

Retrieving the list from the database:

jsonDec = json.decoder.JSONDecoder()
myPythonList = jsonDec.decode(myModel.myList)

Conceptually, here's what's going on:

>>> myList = [1,2,3,4,5,'hello']
>>> import simplejson as json
>>> myJsonList = json.dumps(myList)
>>> myJsonList
'[1, 2, 3, 4, 5, "hello"]'
>>> myJsonList.__class__
<type 'str'>
>>> jsonDec = json.decoder.JSONDecoder()
>>> myPythonList = jsonDec.decode(myJsonList)
>>> myPythonList
[1, 2, 3, 4, 5, u'hello']
>>> myPythonList.__class__
<type 'list'>

Error: Expression must have integral or unscoped enum type

Your variable size is declared as: float size;

You can't use a floating point variable as the size of an array - it needs to be an integer value.

You could cast it to convert to an integer:

float *temp = new float[(int)size];

Your other problem is likely because you're writing outside of the bounds of the array:

   float *temp = new float[size];

    //Getting input from the user
    for (int x = 1; x <= size; x++){
        cout << "Enter temperature " << x << ": ";

        // cin >> temp[x];
        // This should be:
        cin >> temp[x - 1];

Arrays are zero based in C++, so this is going to write beyond the end and never write the first element in your original code.

Gulp error: The following tasks did not complete: Did you forget to signal async completion?

Since your task might contain asynchronous code you have to signal gulp when your task has finished executing (= "async completion").

In Gulp 3.x you could get away without doing this. If you didn't explicitly signal async completion gulp would just assume that your task is synchronous and that it is finished as soon as your task function returns. Gulp 4.x is stricter in this regard. You have to explicitly signal task completion.

You can do that in six ways:

1. Return a Stream

This is not really an option if you're only trying to print something, but it's probably the most frequently used async completion mechanism since you're usually working with gulp streams. Here's a (rather contrived) example demonstrating it for your use case:

var print = require('gulp-print');

gulp.task('message', function() {
  return gulp.src('package.json')
    .pipe(print(function() { return 'HTTP Server Started'; }));

The important part here is the return statement. If you don't return the stream, gulp can't determine when the stream has finished.

2. Return a Promise

This is a much more fitting mechanism for your use case. Note that most of the time you won't have to create the Promise object yourself, it will usually be provided by a package (e.g. the frequently used del package returns a Promise).

gulp.task('message', function() { 
  return new Promise(function(resolve, reject) {
    console.log("HTTP Server Started");

Using async/await syntax this can be simplified even further. All functions marked async implicitly return a Promise so the following works too (if your node.js version supports it):

gulp.task('message', async function() {
  console.log("HTTP Server Started");

3. Call the callback function

This is probably the easiest way for your use case: gulp automatically passes a callback function to your task as its first argument. Just call that function when you're done:

gulp.task('message', function(done) {
  console.log("HTTP Server Started");

4. Return a child process

This is mostly useful if you have to invoke a command line tool directly because there's no node.js wrapper available. It works for your use case but obviously I wouldn't recommend it (especially since it's not very portable):

var spawn = require('child_process').spawn;

gulp.task('message', function() {
  return spawn('echo', ['HTTP', 'Server', 'Started'], { stdio: 'inherit' });

5. Return a RxJS Observable.

I've never used this mechanism, but if you're using RxJS it might be useful. It's kind of overkill if you just want to print something:

var of = require('rxjs').of;

gulp.task('message', function() {
  var o = of('HTTP Server Started');
  o.subscribe(function(msg) { console.log(msg); });
  return o;

6. Return an EventEmitter

Like the previous one I'm including this for completeness sake, but it's not really something you're going to use unless you're already using an EventEmitter for some reason.

gulp.task('message3', function() {
  var e = new EventEmitter();
  e.on('msg', function(msg) { console.log(msg); });
  setTimeout(() => { e.emit('msg', 'HTTP Server Started'); e.emit('finish'); });
  return e;

Difference in boto3 between resource, client, and session?

Here's some more detailed information on what Client, Resource, and Session are all about.


  • low-level AWS service access
  • generated from AWS service description
  • exposes botocore client to the developer
  • typically maps 1:1 with the AWS service API
  • all AWS service operations are supported by clients
  • snake-cased method names (e.g. ListBuckets API => list_buckets method)

Here's an example of client-level access to an S3 bucket's objects (at most 1000**):

import boto3

client = boto3.client('s3')
response = client.list_objects_v2(Bucket='mybucket')
for content in response['Contents']:
    obj_dict = client.get_object(Bucket='mybucket', Key=content['Key'])
    print(content['Key'], obj_dict['LastModified'])

** you would have to use a paginator, or implement your own loop, calling list_objects() repeatedly with a continuation marker if there were more than 1000.


  • higher-level, object-oriented API
  • generated from resource description
  • uses identifiers and attributes
  • has actions (operations on resources)
  • exposes subresources and collections of AWS resources
  • does not provide 100% API coverage of AWS services

Here's the equivalent example using resource-level access to an S3 bucket's objects (all):

import boto3

s3 = boto3.resource('s3')
bucket = s3.Bucket('mybucket')
for obj in bucket.objects.all():
    print(obj.key, obj.last_modified)

Note that in this case you do not have to make a second API call to get the objects; they're available to you as a collection on the bucket. These collections of subresources are lazily-loaded.

You can see that the Resource version of the code is much simpler, more compact, and has more capability (it does pagination for you). The Client version of the code would actually be more complicated than shown above if you wanted to include pagination.


  • stores configuration information (primarily credentials and selected region)
  • allows you to create service clients and resources
  • boto3 creates a default session for you when needed

A useful resource to learn more about these boto3 concepts is the introductory re:Invent video.

What is the difference between screenX/Y, clientX/Y and pageX/Y?

Here's a picture explaining the difference between pageY and clientY.

pageY vs clientY

Same for pageX and clientX, respectively.

pageX/Y coordinates are relative to the top left corner of the whole rendered page (including parts hidden by scrolling),

while clientX/Y coordinates are relative to the top left corner of the visible part of the page, "seen" through browser window.

See Demo

You'll probably never need screenX/Y

How do I use ROW_NUMBER()?

For the first question, why not just use?


to get the count.

And for the second question, the primary key of the row is what should be used to identify a particular row. Don't try and use the row number for that.

If you returned Row_Number() in your main query,

SELECT ROW_NUMBER() OVER (Order by Id) AS RowNumber, Field1, Field2, Field3

Then when you want to go 5 rows back then you can take the current row number and use the following query to determine the row with currentrow -5

     FROM User ) us 
WHERE Row = CurrentRow - 5   

Simple If/Else Razor Syntax

A little bit off topic maybe, but for modern browsers (IE9 and newer) you can use the css odd/even selectors to achieve want you want.

tr:nth-child(even) { /* your alt-row stuff */}
tr:nth-child(odd) { /* the other rows */ }


tr { /* all table rows */ }
tr:nth-child(even) { /* your alt-row stuff */}

How can I pass a username/password in the header to a SOAP WCF Service

Suppose you are calling a web service using HttpWebRequest and HttpWebResponse, because .Net client doest support the structure of the WSLD that your are trying to consume.

In that case you can add the security credentials on the headers like:

    <wsse:Security soap:mustUnderstand='true' xmlns:wsse='' xmlns:wsu=''><wsse:UsernameToken wsu:Id='UsernameToken-3DAJDJSKJDHFJASDKJFKJ234JL2K3H2K3J42'><wsse:Username>YOU_USERNAME/wsse:Username><wsse:Password Type=''>YOU_PASSWORD</wsse:Password><wsse:Nonce EncodingType=''>3WSOKcKKm0jdi3943ts1AQ==</wsse:Nonce><wsu:Created>2015-01-12T16:46:58.386Z</wsu:Created></wsse:UsernameToken></wsse:Security>


You can use SOAPUI to get the wsse Security, using the http log.

Be careful because it is not a safe scenario.

Looping through rows in a DataView

You can iterate DefaultView as the following code by Indexer:

DataTable dt = new DataTable();
// add some rows to your table
// ...
dt.DefaultView.Sort = "OneColumnName ASC"; // For example
for (int i = 0; i < dt.Rows.Count; i++)
    DataRow oRow = dt.DefaultView[i].Row;
    // Do your stuff with oRow
    // ...

check if a file is open in Python

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

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

How to pass parameters in $ajax POST?

Your code was right except you are not passing the JSON keys as strings.

It should have double or single quotes around it

{ "field1": "hello", "field2" : "hello2"}

      type: 'post',
      url: 'superman',
      data: { 
        "field1": "hello", // Quotes were missing
        "field2": "hello1" // Here also
      success: function (response) {
      error: function () {

Check, using jQuery, if an element is 'display:none' or block on click

There are two methods in jQuery to check for visibility:




You can also execute commands based on visibility in the selector;




How do I generate sourcemaps when using babel and webpack?

If optimizing for dev + production, you could try something like this in your config:

const dev = process.env.NODE_ENV !== 'production'

// in config

  devtool: dev ? 'eval-cheap-module-source-map' : 'source-map',

From the docs:

  • devtool: "eval-cheap-module-source-map" offers SourceMaps that only maps lines (no column mappings) and are much faster
  • devtool: "source-map" cannot cache SourceMaps for modules and need to regenerate complete SourceMap for the chunk. It’s something for production.

I am using webpack 2.1.0-beta.19

Find the 2nd largest element in an array with minimum number of comparisons

Assuming space is irrelevant, this is the smallest I could get it. It requires 2*n comparisons in worst case, and n comparisons in best case:

arr = [ 0, 12, 13, 4, 5, 32, 8 ]
max = [ -1, -1 ]

for i in range(len(arr)):
     if( arr[i] > max[0] ):
     elif( arr[i] > max[1] ):

print max[1]

What is the correct way to read a serial port using .NET framework?

Could you try something like this for example I think what you are wanting to utilize is the port.ReadExisting() Method

 using System;
 using System.IO.Ports;

 class SerialPortProgram 
  // Create the serial port with basic settings 
    private SerialPort port = new   SerialPort("COM1",
      9600, Parity.None, 8, StopBits.One); 
    static void Main(string[] args) 
      // Instatiate this 

    private static void SerialPortProgram() 
        Console.WriteLine("Incoming Data:");
         // Attach a method to be called when there
         // is data waiting in the port's buffer 
        port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived); 
        // Begin communications 
        // Enter an application loop to keep this thread alive 

    private void port_DataReceived(object sender, SerialDataReceivedEventArgs e) 
       // Show all the incoming data in the port's buffer

Or is you want to do it based on what you were trying to do , you can try this

public class MySerialReader : IDisposable
  private SerialPort serialPort;
  private Queue<byte> recievedData = new Queue<byte>();

  public MySerialReader()
    serialPort = new SerialPort();
    serialPort.DataReceived += serialPort_DataReceived;

  void serialPort_DataReceived(object s, SerialDataReceivedEventArgs e)
    byte[] data = new byte[serialPort.BytesToRead];
    serialPort.Read(data, 0, data.Length);
    data.ToList().ForEach(b => recievedData.Enqueue(b));

  void processData()
    // Determine if we have a "packet" in the queue
    if (recievedData.Count > 50)
        var packet = Enumerable.Range(0, 50).Select(i => recievedData.Dequeue());

  public void Dispose()
        if (serialPort != null)

Android scale animation on view

public void expand(final View v) {
        ScaleAnimation scaleAnimation = new ScaleAnimation(1, 1, 1, 0, 0, 0);
        scaleAnimation.setAnimationListener(new Animation.AnimationListener() {
            public void onAnimationStart(Animation animation) {


            public void onAnimationEnd(Animation animation) {

            public void onAnimationRepeat(Animation animation) {


    public void collapse(final View v) {
        ScaleAnimation scaleAnimation = new ScaleAnimation(1, 1, 0, 1, 0, 0);
        scaleAnimation.setAnimationListener(new Animation.AnimationListener() {
            public void onAnimationStart(Animation animation) {


            public void onAnimationEnd(Animation animation) {

            public void onAnimationRepeat(Animation animation) {


How to log Apache CXF Soap Request and Soap Response using Log4j?

You need to create a file named org.apache.cxf.Logger (that is: org.apache.cxf file with Logger extension) under /META-INF/cxf/ with the following contents:


Reference: Using Log4j Instead of java.util.logging.

Also if you replace standard:


with much more verbose:

<bean id="abstractLoggingInterceptor" abstract="true">
    <property name="prettyLogging" value="true"/>
<bean id="loggingInInterceptor" class="org.apache.cxf.interceptor.LoggingInInterceptor" parent="abstractLoggingInterceptor"/>
<bean id="loggingOutInterceptor" class="org.apache.cxf.interceptor.LoggingOutInterceptor" parent="abstractLoggingInterceptor"/>

        <ref bean="loggingInInterceptor"/>
        <ref bean="loggingOutInterceptor"/>
        <ref bean="loggingOutInterceptor"/>
        <ref bean="loggingInInterceptor"/>

Apache CXF will pretty print XML messages formatting them with proper indentation and line breaks. Very useful. More about it here.

Sending mail attachment using Java

Working code, I have used Java Mail 1.4.7 jar

import java.util.Properties;
import javax.activation.*;
import javax.mail.*;

public class MailProjectClass {

public static void main(String[] args) {

    final String username = "[email protected]";
    final String password = "your.password";

    Properties props = new Properties();
    props.put("mail.smtp.auth", true);
    props.put("mail.smtp.starttls.enable", true);
    props.put("", "");
    props.put("mail.smtp.port", "587");

    Session session = Session.getInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("[email protected]"));
                InternetAddress.parse("[email protected]"));
        message.setSubject("Testing Subject");

        MimeBodyPart messageBodyPart = new MimeBodyPart();

        Multipart multipart = new MimeMultipart();
        String file = "path of file to be attached";
        String fileName = "attachmentName";
        DataSource source = new FileDataSource(file);
        messageBodyPart.setDataHandler(new DataHandler(source));





    } catch (MessagingException e) {

How to implement if-else statement in XSLT?

You have to reimplement it using <xsl:choose> tag:

         <xsl:when test="$CreatedDate > $IDAppendedDate">
           <h2> mooooooooooooo </h2>
          <h2> dooooooooooooo </h2>

Saving results with headers in Sql Server Management Studio

At least in SQL Server 2012, you can right click in the query window and select Query Options. From there you can select Include Headers for grid and/or text and have the Save As work the way you want it without restarting SSMS.

You'll still need to change it in Tools->Options in the menu bar to have new query windows use those settings by default.

JQuery $.ajax() post - data in a java servlet

To get the value from the servlet from POST command, you can follow the approach as explained on this post by using request.getParameter(key) format which will return the value you want.

Access: Move to next record until EOF

To loop from current record to the end:

While Me.CurrentRecord < Me.Recordset.RecordCount
    ' ... do something to current record
    ' ...

    DoCmd.GoToRecord Record:=acNext

To check if it is possible to go to next record:

If Me.CurrentRecord < Me.Recordset.RecordCount Then
    ' ...
End If

How do I pass multiple parameter in URL?


url = new URL(""+lat+"&param2="+lon);

must work. For whatever strange reason1, you need ? before the first parameter and & before the following ones.

Using a compound parameter like

url = new URL(""+lat+"_"+lon);

would work, too, but is surely not nice. You can't use a space there as it's prohibited in an URL, but you could encode it as %20 or + (but this is even worse style).

1 Stating that ? separates the path and the parameters and that & separates parameters from each other does not explain anything about the reason. Some RFC says "use ? there and & there", but I can't see why they didn't choose the same character.

When should we use intern method of String on String literals

Learn Java String Intern - once for all

Strings in java are immutable objects by design. Therefore, two string objects even with same value will be different objects by default. However, if we wish to save memory, we could indicate to use same memory by a concept called string intern.

The below rules would help you understand the concept in clear terms:

  1. String class maintains an intern-pool which is initially empty. This pool must guarantee to contain string objects with only unique values.
  2. All string literals having same value must be considered same memory-location object because they have otherwise no notion of distinction. Therefore, all such literals with same value will make a single entry in the intern-pool and will refer to same memory location.
  3. Concatenation of two or more literals is also a literal. (Therefore rule #2 will be applicable for them)
  4. Each string created as object (i.e. by any other method except as literal) will have different memory locations and will not make any entry in the intern-pool
  5. Concatenation of literals with non-literals will make a non-literal. Thus, the resultant object will have a new memory location and will NOT make an entry in the intern-pool.
  6. Invoking intern method on a string object, either creates a new object that enters the intern-pool or return an existing object from the pool that has same value. The invocation on any object which is not in the intern-pool, does NOT move the object to the pool. It rather creates another object that enters the pool.


String s1=new String (“abc”);
String s2=new String (“abc”);
If (s1==s2)  //would return false  by rule #4
If (“abc” == “a”+”bc” )  //would return true by rules #2 and #3
If (“abc” == s1 )  //would return false  by rules #1,2 and #4
If (“abc” == s1.intern() )  //would return true  by rules #1,2,4 and #6
If ( s1 == s2.intern() )      //wound return false by rules #1,4, and #6

Note: The motivational cases for string intern are not discussed here. However, saving of memory will definitely be one of the primary objectives.

Split String by delimiter position using oracle SQL

Therefore, I would like to separate the string by the furthest delimiter.

I know this is an old question, but this is a simple requirement for which SUBSTR and INSTR would suffice. REGEXP are still slower and CPU intensive operations than the old subtsr and instr functions.

  2    ( SELECT 'F/P/O' str FROM dual
  3    )
  4  SELECT SUBSTR(str, 1, Instr(str, '/', -1, 1) -1) part1,
  5         SUBSTR(str, Instr(str, '/', -1, 1) +1) part2
  7  /

----- -----
F/P   O

As you said you want the furthest delimiter, it would mean the first delimiter from the reverse.

You approach was fine, but you were missing the start_position in INSTR. If the start_position is negative, the INSTR function counts back start_position number of characters from the end of string and then searches towards the beginning of string.

Center image in div horizontally

<div class="outer">
    <div class="inner">
        <img src="" alt="tall image" />
<hr />
<div class="outer">
    <div class="inner">
        <img src="" alt="wide image" />


    max-width: 100%;
    max-height: 100%;
    display: block;
    margin: auto auto;

    border: 1px solid #888;
    width: 100px;
    height: 100px;

    height: 100px;
    width: 100px;
    vertical-align: middle;

How to overcome "'aclocal-1.15' is missing on your system" warning?

Before running ./configure try running autoreconf -f -i. The autoreconf program automatically runs autoheader, aclocal, automake, autopoint and libtoolize as required.

Edit to add: This is usually caused by checking out code from Git instead of extracting it from a .zip or .tar.gz archive. In order to trigger rebuilds when files change, Git does not preserve files' timestamps, so the configure script might appear to be out of date. As others have mentioned, there are ways to get around this if you don't have a sufficiently recent version of autoreconf.

Another edit: This error can also be caused by copying the source folder extracted from an archive with scp to another machine. The timestamps can be updated, suggesting that a rebuild is necessary. To avoid this, copy the archive and extract it in place.

Where to put Gradle configuration (i.e. credentials) that should not be committed?

First answer is still valid, but the API has changed in the past. Since my edit there wasn't accepted I post it as separate answer.

The method authentication() is only used to provide the authentication method (e.g. Basic) but not any credentials.

You also shouldn't use it since it's printing the credentials plain on failure!

This his how it should look like in your build.gradle

    maven {
        credentials {
            username "$mavenUser"
            password "$mavenPassword"
        url ''

In in your userhome dir put:


Also ensure that the GRADLE_USER_HOME is set to ~/.gradle otherwise the properties file there won't be resolved.

See also:

and (

Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION]

This worked for me. Add sudo before python

curl |sudo python

How to loop through a directory recursively to delete files with certain extensions

The other answers provided will not include files or directories that start with a . the following worked for me:

  local fl1="$1"/*;
  local fl2="$1"/.[!.]*; 
  local fl3="$1"/..?*;
  for inpath in "$1"/* "$1"/.[!.]* "$1"/..?*; do
    if [ "$inpath" != "$fl1" -a "$inpath" != "$fl2" -a "$inpath" != "$fl3" ]; then 
      stat --printf="%F\0%n\0\n" -- "$inpath";
      if [ -d "$inpath" ]; then
        getAll "$inpath"
      #elif [ -f $inpath ]; then

How to get image height and width using java?

You can get width and height of image with BufferedImage object using java.

public void setWidthAndHeightImage(FileUploadEvent event){
    byte[] imageTest = event.getFile().getContents();
                baiStream = new ByteArrayInputStream(imageTest );
                BufferedImage bi =;
                //get width and height of image
                int imageWidth = bi.getWidth();
                int imageHeight = bi.getHeight();

List of IP addresses/hostnames from local network in Python

Here is a small tool scanip that will help you to get all ip addresses and their corresponding mac addresses in the network (Works on Linux).

top -c command in linux to filter processes listed based on processname

I ended up using a shell script with the following code:


while [ 1 == 1 ]
    ps auxf |grep -ve "grep" |grep -E "MSG[^\ ]*" --color=auto
    sleep 5

npm start error with create-react-app

Yes you should not install react-scripts globally, it will not work.

I think i didn't use the --save when i first created the project (on another machine), so for me this fixed the problem :

npm install --save react react-dom react-scripts

Angular 2 router no base href set

Angular 7,8 fix is in app.module.ts

import {APP_BASE_HREF} from '@angular/common';

inside @NgModule add

providers: [{provide: APP_BASE_HREF, useValue: '/'}]

Visual studio - getting error "Metadata file 'XYZ' could not be found" after edit continue

Make sure all your dependent projects are using the same .Net Framework version. I had the same issue caused by a dependent project using 4.5.1, while all others were using 4.5. Changing the project from 4.5.1 to 4.5 and rebuilding my solution fixed this issue for me.

WebSockets protocol vs HTTP

You seem to assume that WebSocket is a replacement for HTTP. It is not. It's an extension.

The main use-case of WebSockets are Javascript applications which run in the web browser and receive real-time data from a server. Games are a good example.

Before WebSockets, the only method for Javascript applications to interact with a server was through XmlHttpRequest. But these have a major disadvantage: The server can't send data unless the client has explicitly requested it.

But the new WebSocket feature allows the server to send data whenever it wants. This allows to implement browser-based games with a much lower latency and without having to use ugly hacks like AJAX long-polling or browser plugins.

So why not use normal HTTP with streamed requests and responses

In a comment to another answer you suggested to just stream the client request and response body asynchronously.

In fact, WebSockets are basically that. An attempt to open a WebSocket connection from the client looks like a HTTP request at first, but a special directive in the header (Upgrade: websocket) tells the server to start communicating in this asynchronous mode. First drafts of the WebSocket protocol weren't much more than that and some handshaking to ensure that the server actually understands that the client wants to communicate asynchronously. But then it was realized that proxy servers would be confused by that, because they are used to the usual request/response model of HTTP. A potential attack scenario against proxy servers was discovered. To prevent this it was necessary to make WebSocket traffic look unlike any normal HTTP traffic. That's why the masking keys were introduced in the final version of the protocol.

switch case statement error: case expressions must be constant expression*, since ADT 14 are not more declared as final static int so you can not use in switch case construct. You could use if else clause instead.

SVN checkout the contents of a folder, not the folder itself

Just add a . to it:

svn checkout file:///home/landonwinters/svn/waterproject/trunk .

That means: check out to current directory.

Is there a JavaScript strcmp()?

var strcmp = new Intl.Collator(undefined, {numeric:true, sensitivity:'base'}).compare;

Usage: strcmp(string1, string2)

Result: 1 means string1 is bigger, 0 means equal, -1 means string2 is bigger.

This has higher performance than String.prototype.localeCompare

Also, numeric:true makes it do logical number comparison

Hosting a Maven repository on github

If you have only aar or jar file itself, or just don't want to use plugins - I've created a simple shell script. You can achieve the same with it - publishing your artifacts to Github and use it as public Maven repo.

How can I list all tags for a Docker image on a remote registry?

I have done this thing when I have to implement a task in which if user somehow type the wrong tag then we have to give the list of all the tag present in the repo(Docker repo) present in the register. So I have code in batch Script.

<pre style="background-color:#bcbbbb;">
@echo off

docker login --username=xxxx --password=xxxx
docker pull %1:%2

echo "Specified Version is Not Found "
echo "Available Version for this image is :"
for /f %%i in (' curl -s -H "Content-Type:application/json" -X POST -d "{\"username\":\"user\",\"password\":\"password\"}" ^|jq -r .token ') do set TOKEN=%%i
curl -sH "Authorization: JWT %TOKEN%" "" | jq .results[].name

So in this we can give arguments to out batch file like:

Dockerfile java version7 

ToggleButton in C# WinForms

When my button's FlatStyle is set to system, it looks flat. And when it's set to popup, it only pops up when mouses over. Either is what I want. I want it to look sunken when checked and raised when unchecked and no change while mousing over (the button is really a checkbox but the checkbox's appearance property is set to button).

I end up setting the FlatStyle to flat and wrote a new Paint event handler.

 private void checkbox_paint(object sender, PaintEventArgs e)
            CheckBox myCheckbox = (CheckBox)sender;
            Rectangle borderRectangle = myCheckbox.ClientRectangle;
            if (myCheckbox.Checked)
                ControlPaint.DrawBorder3D(e.Graphics, borderRectangle,
                ControlPaint.DrawBorder3D(e.Graphics, borderRectangle,

I give a similar answer to this question: C# winforms button with solid border, like 3d Sorry for double posting.

How to check whether a variable is a class or not?

There are some working solutions here already, but here's another one:

>>> import types
>>> class Dummy: pass
>>> type(Dummy) is types.ClassType

Most efficient way to convert an HTMLCollection to an Array

To convert array-like to array in efficient way we can make use of the jQuery makeArray :

makeArray: Convert an array-like object into a true JavaScript array.


var domArray = jQuery.makeArray(htmlCollection);

A little extra:

If you do not want to keep reference to the array object (most of the time HTMLCollections are dynamically changes so its better to copy them into another array, This example pay close attention to performance:

var domDataLength = domData.length //Better performance, no need to calculate every iteration the domArray length
var resultArray = new Array(domDataLength) // Since we know the length its improves the performance to declare the result array from the beginning.

for (var i = 0 ; i < domDataLength ; i++) {
    resultArray[i] = domArray[i]; //Since we already declared the resultArray we can not make use of the more expensive push method.

What is array-like?

HTMLCollection is an "array-like" object, the array-like objects are similar to array's object but missing a lot of its functionally definition:

Array-like objects look like arrays. They have various numbered elements and a length property. But that’s where the similarity stops. Array-like objects do not have any of Array’s functions, and for-in loops don’t even work!

Automatically get loop index in foreach loop in Perl

Well, there is this way:

use List::Rubyish;

$list = List::Rubyish->new( [ qw<a b c> ] );
$list->each_index( sub { say "\$_=$_" } );

See List::Rubyish.

XML Document to String

First you need to get rid of all newline characters in all your text nodes. Then you can use an identity transform to output your DOM tree. Look at the javadoc for TransformerFactory#newTransformer().

nodejs module.js:340 error: cannot find module

Hi fellow Phonegap/Cordova/Ionic developers,

  I solved this issue by doing the following

  1. C: drive -> Users -> "username" eg. john -> AppData -> Roaming

  2. Inside the "Roaming" folder you need to delete both "npm" and "npm-cache" 

  3. Now build your project, and it should work

Happy coding!!!

How do you stash an untracked file?

If you want to stash untracked files, but keep indexed files (the ones you're about to commit for example), just add -k (keep index) option to the -u

git stash -u -k

How do I get a python program to do nothing?

You can use continue

if condition:
    #do something

How can I get the current page name in WordPress?

I believe that the Roots starter theme has a fantastic function to get the current page title. It is very hackable, covers all bases, and can be easily used with the wp_title hook.

 * Page titles
function roots_title() {
  if (is_home()) {
    if (get_option('page_for_posts', true)) {
      echo get_the_title(get_option('page_for_posts', true));
    } else {
      _e('Latest Posts', 'roots');
  } elseif (is_archive()) {
    $term = get_term_by('slug', get_query_var('term'), get_query_var('taxonomy'));
    if ($term) {
      echo $term->name;
    } elseif (is_post_type_archive()) {
      echo get_queried_object()->labels->name;
    } elseif (is_day()) {
      printf(__('Daily Archives: %s', 'roots'), get_the_date());
    } elseif (is_month()) {
      printf(__('Monthly Archives: %s', 'roots'), get_the_date('F Y'));
    } elseif (is_year()) {
      printf(__('Yearly Archives: %s', 'roots'), get_the_date('Y'));
    } elseif (is_author()) {
      $author = get_queried_object();
      printf(__('Author Archives: %s', 'roots'), $author->display_name);
    } else {
  } elseif (is_search()) {
    printf(__('Search Results for %s', 'roots'), get_search_query());
  } elseif (is_404()) {
    _e('Not Found', 'roots');
  } else {

how to check for special characters php

preg_match('/'.preg_quote('^\'£$%^&*()}{@#~?><,@|-=-_+-¬', '/').'/', $string);

Netbeans - class does not have a main method

Make sure it is

public static void main(String[] argv)

No other signature will do.

Calling a Function defined inside another function in Javascript

you can also just use return:

   function outer() { 
    function inner() {
return inner();


How do I execute a stored procedure in a SQL Agent job?

You just need to add this line to the window there:

exec (your stored proc name) (and possibly add parameters)

What is your stored proc called, and what parameters does it expect?

Iterating through array - java

Since atleast Java 1.5.0 (Java 5) the code can be cleaned up a bit. Arrays and anything that implements Iterator (e.g. Collections) can be looped as such:

public static boolean inArray(int[] array, int check) {
   for (int o : array){
      if (o == check) {
         return true;
   return false;

In Java 8 you can also do something like:

// import;

public static boolean inArray(int[] array, int check) {
   return IntStream.of(array).anyMatch(val -> val == check);

Although converting to a stream for this is probably overkill.

jQuery get specific option tag text

I wanted to get the selected label. This worked for me in jQuery 1.5.1.

$("#list :selected").text();

How to check String in response body with mockMvc

here a more elegant way

            .header("Authorization", "Bearer " + validToken))

Is calculating an MD5 hash less CPU intensive than SHA family functions?

On my 2012 MacBook Air (Intel Core i5-3427U, 2x 1.8 GHz, 2.8 GHz Turbo), SHA-1 is slightly faster than MD5 (using OpenSSL in 64-bit mode):

$ openssl speed md5 sha1
OpenSSL 0.9.8r 8 Feb 2011
The 'numbers' are in 1000s of bytes per second processed.
type             16 bytes     64 bytes    256 bytes   1024 bytes   8192 bytes
md5              30055.02k    94158.96k   219602.97k   329008.21k   384150.47k
sha1             31261.12k    95676.48k   224357.36k   332756.21k   396864.62k

Update: 10 months later with OS X 10.9, SHA-1 got slower on the same machine:

$ openssl speed md5 sha1
OpenSSL 0.9.8y 5 Feb 2013
The 'numbers' are in 1000s of bytes per second processed.
type             16 bytes     64 bytes    256 bytes   1024 bytes   8192 bytes
md5              36277.35k   106558.04k   234680.17k   334469.33k   381756.70k
sha1             35453.52k    99530.85k   206635.24k   281695.48k   313881.86k

Second update: On OS X 10.10, SHA-1 speed is back to the 10.8 level:

$ openssl speed md5 sha1
OpenSSL 0.9.8zc 15 Oct 2014
The 'numbers' are in 1000s of bytes per second processed.
type             16 bytes     64 bytes    256 bytes   1024 bytes   8192 bytes
md5              35391.50k   104905.27k   229872.93k   330506.91k   382791.75k
sha1             38054.09k   110332.44k   238198.72k   340007.12k   387137.77k

Third update: OS X 10.14 with LibreSSL is a lot faster (still on the same machine). SHA-1 still comes out on top:

$ openssl speed md5 sha1
LibreSSL 2.6.5
The 'numbers' are in 1000s of bytes per second processed.
type             16 bytes     64 bytes    256 bytes   1024 bytes   8192 bytes
md5              43128.00k   131797.91k   304661.16k   453120.00k   526789.29k
sha1             55598.35k   157916.03k   343214.08k   489092.34k   570668.37k

Is there a way of setting culture for a whole application? All current threads and new threads?

Here is the solution for c# MVC:

  1. First : Create a custom attribute and override method like this:

    public class CultureAttribute : ActionFilterAttribute
        public override void OnActionExecuting(ActionExecutingContext filterContext)
            // Retreive culture from GET
            string currentCulture = filterContext.HttpContext.Request.QueryString["culture"];
            // Also, you can retreive culture from Cookie like this :
            //string currentCulture = filterContext.HttpContext.Request.Cookies["cookie"].Value;
            // Set culture
            Thread.CurrentThread.CurrentCulture = new CultureInfo(currentCulture);
            Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(currentCulture);
  2. Second : In App_Start, find FilterConfig.cs, add this attribute. (this works for WHOLE application)

    public class FilterConfig
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
            // Add custom attribute here
            filters.Add(new CultureAttribute());

That's it !

If you want to define culture for each controller/action in stead of whole application, you can use this attribute like this:

public class StudentsController : Controller


public ActionResult Index()
    return View();

How to check list A contains any value from list B?

If you didn't care about performance, you could try:

a.Any(item => b.Contains(item))
// or, as in the column using a method group

But I would try this first:


How can I check for "undefined" in JavaScript?

// x has not been defined before
if (typeof x === 'undefined') { // Evaluates to true without errors.
   // These statements execute.

if (x === undefined) { // Throws a ReferenceError


Exit from app when click button in android phonegap?

Try this code.


        <script type="text/javascript" charset="utf-8" src="cordova-1.5.0.js"></script>      
        <script type="text/javascript" charset="utf-8">

            function onLoad()
                  document.addEventListener("deviceready", onDeviceReady, true);

            function exitFromApp()



    <body onload="onLoad();">
       <button name="buttonClick" onclick="exitFromApp()">Click Me!</button>

Replace src="cordova-1.5.0.js" with your phonegap js .

How to subtract/add days from/to a date?

Just subtract a number:

> as.Date("2009-10-01")
[1] "2009-10-01"
> as.Date("2009-10-01")-5
[1] "2009-09-26"

Since the Date class only has days, you can just do basic arithmetic on it.

If you want to use POSIXlt for some reason, then you can use it's slots:

> a <- as.POSIXlt("2009-10-04")
> names(unclass(as.POSIXlt("2009-10-04")))
[1] "sec"   "min"   "hour"  "mday"  "mon"   "year"  "wday"  "yday"  "isdst"
> a$mday <- a$mday - 6
> a
[1] "2009-09-28 EDT"

$(document).ready shorthand

These specific lines are the usual wrapper for jQuery plugins:

" make sure that your plugin doesn't collide with other libraries that might use the dollar sign, it's a best practice to pass jQuery to a self executing function (closure) that maps it to the dollar sign so it can't be overwritten by another library in the scope of its execution."

(function( $ ){
  $.fn.myPlugin = function() {
    // Do your awesome plugin stuff here
})( jQuery );


Find the number of columns in a table

Since all answers are using COUNT(), you can also use MAX() to get the number of columns in a specific table as

WHERE TABLE_CATALOG = 'YourDatabaseNameHere'
      TABLE_SCHEMA = 'YourSchemaNameHere'
      TABLE_NAME = 'YourTableNameHere';


How to delete a cookie using jQuery?

Try this

 $.cookie('_cookieName', null, { path: '/' });

The { path: '/' } do the job for you

Tool to generate JSON schema from JSON data

You might be looking for this:

It is an online tool that can automatically generate JSON schema from JSON string. And you can edit the schema easily.

Create a remote branch on GitHub

Git is supposed to understand what files already exist on the server, unless you somehow made a huge difference to your tree and the new changes need to be sent.

To create a new branch with a copy of your current state

git checkout -b new_branch #< create a new local branch with a copy of your code
git push origin new_branch #< pushes to the server

Can you please describe the steps you did to understand what might have made your repository need to send that much to the server.

How to initialize log4j properly?

Find a or log4j.xml online that has a root appender, and put it on your classpath.

### direct log messages to stdout ###
log4j.rootLogger=debug, stdout

will log to the console. I prefer logging to a file so you can investigate afterwards.

log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

although for verbose logging applications 100KB usually needs to be increased to 1MB or 10MB, especially for debug.

Personally I set up multiple loggers, and set the root logger to warn or error level instead of debug.

Run R script from command line

If you want the output to print to the terminal it is best to use Rscript

Rscript a.R

Note that when using R CMD BATCH a.R that instead of redirecting output to standard out and displaying on the terminal a new file called a.Rout will be created.

# Check the output
cat a.Rout

One other thing to note about using Rscript is that it doesn't load the methods package by default which can cause confusion. So if you're relying on anything that methods provides you'll want to load it explicitly in your script.

If you really want to use the ./a.R way of calling the script you could add an appropriate #! to the top of the script

#!/usr/bin/env Rscript
sayHello <- function(){


I will also note that if you're running on a *unix system there is the useful littler package which provides easy command line piping to R. It may be necessary to use littler to run shiny apps via a script? Further details can be found in this question.

How to test code dependent on environment variables using JUnit?

The usual solution is to create a class which manages the access to this environmental variable, which you can then mock in your test class.

public class Environment {
    public String getVariable() {
        return System.getenv(); // or whatever

public class ServiceTest {
    private static class MockEnvironment {
        public String getVariable() {
           return "foobar";

    @Test public void testService() {
        service.doSomething(new MockEnvironment());

The class under test then gets the environment variable using the Environment class, not directly from System.getenv().

How do I load a PHP file into a variable?

file_get_contents() will not work if your server has allow_url_fopen turned off. Most shared web hosts have it turned off by default due to security risks. Also, in PHP6, the allow_url_fopen option will no longer exist and all functions will act as if it is permenantly set to off. So this is a very bad method to use.

Your best option to use if you are accessing the file through http is cURL

How do I "shake" an Android device within the Android emulator to bring up the dev menu to debug my React Native app

on linux ctrl+m should work but it doesn't for solving the problem click on the (...) (its extended controls) and then close that you can open menu by ctrl+m. then:

  1. click on the (...) (its extended controls)

  2. close extended controls

  3. ctrl+m

Measuring the distance between two coordinates in PHP

Try this gives awesome results

function getDistance($point1_lat, $point1_long, $point2_lat, $point2_long, $unit = 'km', $decimals = 2) {
        // Calculate the distance in degrees
        $degrees = rad2deg(acos((sin(deg2rad($point1_lat))*sin(deg2rad($point2_lat))) + (cos(deg2rad($point1_lat))*cos(deg2rad($point2_lat))*cos(deg2rad($point1_long-$point2_long)))));

        // Convert the distance in degrees to the chosen unit (kilometres, miles or nautical miles)
        switch($unit) {
            case 'km':
                $distance = $degrees * 111.13384; // 1 degree = 111.13384 km, based on the average diameter of the Earth (12,735 km)
            case 'mi':
                $distance = $degrees * 69.05482; // 1 degree = 69.05482 miles, based on the average diameter of the Earth (7,913.1 miles)
            case 'nmi':
                $distance =  $degrees * 59.97662; // 1 degree = 59.97662 nautic miles, based on the average diameter of the Earth (6,876.3 nautical miles)
        return round($distance, $decimals);

/lib/ bad ELF interpreter: No such file or directory

You did not mention what the command was that you were trying to run that produced the error message. However, the bottom line problem is that you are trying to run and/or install 32-bit (i686) packages on a 64-bit (x86_64) system which is not a good idea. For example, if you were trying to run the 32-bit version of Perl on a 64-bit system, the result would be something like

perl: /lib/ bad ELF interpreter: No such file or directory

If you still want to use the rpm command to install the 32-bit versions of glibc and glibc-common on your system, then you need to know that you must install both of the packages at the same time and as a single command because they are dependencies of each other. The command to run in your case would be:

rpm -Uvh glibc-2.12-1.80.el6.i686.rpm glibc-common-2.12-1.80.el6.i686.rpm

Codeigniter how to create PDF

Create new pdf helper file in application\helpers folder and name it pdf_helper.php. Add below code in pdf_helper.php file:

        function tcpdf()

For more Please follow the below link:

How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

Because XMLHttpReponse synchronous operation is deprecated I came up with the following solution that wraps XMLHttpRequest. This allows ordered AJAX queries while still being asycnronous in nature, which is very useful for single use CSRF tokens.

It is also transparent so libraries such as jQuery will operate seamlessly.

/* wrap XMLHttpRequest for synchronous operation */
var XHRQueue = [];
var _XMLHttpRequest = XMLHttpRequest;
XMLHttpRequest = function()
  var xhr   = new _XMLHttpRequest();
  var _send = xhr.send;

  xhr.send = function()
    /* queue the request, and if it's the first, process it */
    XHRQueue.push([this, arguments]);
    if (XHRQueue.length == 1)

  xhr.processQueue = function()
    var call = XHRQueue[0];
    var xhr  = call[0];
    var args = call[1];

    /* you could also set a CSRF token header here */

    /* send the request */
    _send.apply(xhr, args);

  xhr.addEventListener('load', function(e)
    /* you could also retrieve a CSRF token header here */

    /* remove the completed request and if there is more, trigger the next */
    if (XHRQueue.length)

  return xhr;

How do you add CSS with Javascript?

This is my solution to add a css rule at the end of the last style sheet list:

var css = new function()
    function addStyleSheet()
        let head = document.head;
        let style = document.createElement("style");


    this.insert = function(rule)
        if(document.styleSheets.length == 0) { addStyleSheet(); }

        let sheet = document.styleSheets[document.styleSheets.length - 1];
        let rules = sheet.rules;

        sheet.insertRule(rule, rules.length);

css.insert("body { background-color: red }");

How to remove trailing whitespaces with sed?

It is best to also quote $1:

sed -i.bak 's/[[:blank:]]*$//' "$1"

Converting String Array to an Integer Array

For Java 8 and higher:

    String[] test = {"1", "2", "3", "4", "5"};
    int[] ints =;

"The operation is not valid for the state of the transaction" error and transaction scope

I've encountered this error when my Transaction is nested within another. Is it possible that the stored procedure declares its own transaction or that the calling function declares one?

How to check if a word is an English word with Python?

It won't work well with WordNet, because WordNet does not contain all english words. Another possibility based on NLTK without enchant is NLTK's words corpus

>>> from nltk.corpus import words
>>> "would" in words.words()
>>> "could" in words.words()
>>> "should" in words.words()
>>> "I" in words.words()
>>> "you" in words.words()

What is the difference between String and string in C#?

Both are the same.The difference is how you use it. Convention is,

string is for variables

String is for calling other String class methods


string fName = "John";
string lName = "Smith";

string fullName = String.Concat(fName,lName);

if (String.IsNullOrEmpty(fName))
  Console.WriteLine("Enter first name");

How do I write a compareTo method which compares objects?

Consider using the Comparator interface described here which uses generics so you can avoid casting Object to Student.

As Eugene Retunsky said, your first part is the correct way to compare Strings. Also if the lastNames are equal I think you meant to compare firstNames, in which case just use compareTo in the same way.

How to query SOLR for empty fields?

you can do it with filter query q=*:*&fq=-id:*

TokenMismatchException in VerifyCsrfToken.php Line 67

I also get this error, but I was solved the problem. If you using php artisan serve add this code {{ csrf_field() }} under {!! Form::open() !!}

  1. php artisan cache:clear
  2. Clear cache & cookies browser
  3. Using Private Browser (Mozilla) / Incognito Window (Chrome)
  4. Open your form/page and then submit again guys

I hope this is solve your problem.

Writing a VLOOKUP function in vba

As Tim Williams suggested, using Application.VLookup will not throw an error if the lookup value is not found (unlike Application.WorksheetFunction.VLookup).

If you want the lookup to return a default value when it fails to find a match, and to avoid hard-coding the column number -- an equivalent of IFERROR(VLOOKUP(what, where, COLUMNS(where), FALSE), default) in formulas, you could use the following function:

Private Function VLookupVBA(what As Variant, lookupRng As Range, defaultValue As Variant) As Variant
    Dim rv As Variant: rv = Application.VLookup(what, lookupRng, lookupRng.Columns.Count, False)
    If IsError(rv) Then
        VLookupVBA = defaultValue
        VLookupVBA = rv
    End If
End Function

Public Sub UsageExample()
    MsgBox VLookupVBA("ValueToFind", ThisWorkbook.Sheets("ReferenceSheet").Range("A:D"), "Not found!")
End Sub

How does a ArrayList's contains() method evaluate objects?

It uses the equals method on the objects. So unless Thing overrides equals and uses the variables stored in the objects for comparison, it will not return true on the contains() method.

How to change default text color using custom theme?

When you create an App, a file called styles.xml will be created in your res/values folder. If you change the styles, you can change the background, text color, etc for all your layouts. That way you don’t have to go into each individual layout and change the it manually.


<resources xmlns:android="">
<style name="Theme.AppBaseTheme" parent="@android:style/Theme.Light">
    <item name="android:editTextColor">#295055</item> 
    <item name="android:textColorPrimary">#295055</item>
    <item name="android:textColorSecondary">#295055</item>
    <item name="android:textColorTertiary">#295055</item>
    <item name="android:textColorPrimaryInverse">#295055</item>
    <item name="android:textColorSecondaryInverse">#295055</item>
    <item name="android:textColorTertiaryInverse">#295055</item>

     <item name="android:windowBackground">@drawable/custom_background</item>        

<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
    <!-- All customizations that are NOT specific to a particular API-level can go here. -->

parent="@android:style/Theme.Light" is Google’s native colors. Here is a reference of what the native styles are:

The default Android style is also called “Theme”. So you calling it Theme probably confused the program.

name="Theme.AppBaseTheme" means that you are creating a style that inherits all the styles from parent="@android:style/Theme.Light". This part you can ignore unless you want to inherit from AppBaseTheme again. = <style name="AppTheme" parent="AppBaseTheme">

@drawable/custom_background is a custom image I put in the drawable’s folder. It is a 300x300 png image.

#295055 is a dark blue color.

My code changes the background and text color. For Button text, please look through Google’s native stlyes (the link I gave u above).

Then in Android Manifest, remember to include the code:


Setting a PHP $_SESSION['var'] using jQuery

Might want to try putting the PHP function on another PHP page, and use an AJAX call to set the variable.

TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array

I get this error whenever I use np.concatenate the wrong way:

>>> a = np.eye(2)
>>> np.concatenate(a, a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<__array_function__ internals>", line 6, in concatenate
TypeError: only integer scalar arrays can be converted to a scalar index

The correct way is to input the two arrays as a tuple:

>>> np.concatenate((a, a))
array([[1., 0.],
       [0., 1.],
       [1., 0.],
       [0., 1.]])

dropping a global temporary table

Step 1. Figure out which errors you want to trap:

If the table does not exist:

SQL> drop table x;
drop table x
ERROR at line 1:
ORA-00942: table or view does not exist

If the table is in use:

SQL> create global temporary table t (data varchar2(4000));

Table created.

Use the table in another session. (Notice no commit or anything after the insert.)

SQL> insert into t values ('whatever');

1 row created.

Back in the first session, attempt to drop:

SQL> drop table t;
drop table t
ERROR at line 1:
ORA-14452: attempt to create, alter or drop an index on temporary table already in use

So the two errors to trap:

  1. ORA-00942: table or view does not exist
  2. ORA-14452: attempt to create, alter or drop an index on temporary table already in use

See if the errors are predefined. They aren't. So they need to be defined like so:

create or replace procedure p as
    table_or_view_not_exist exception;
    pragma exception_init(table_or_view_not_exist, -942);
    attempted_ddl_on_in_use_GTT exception;
    pragma exception_init(attempted_ddl_on_in_use_GTT, -14452);
    execute immediate 'drop table t';

        when table_or_view_not_exist then
            dbms_output.put_line('Table t did not exist at time of drop. Continuing....');

        when attempted_ddl_on_in_use_GTT then
            dbms_output.put_line('Help!!!! Someone is keeping from doing my job!');
            dbms_output.put_line('Please rescue me');
end p;

And results, first without t:

SQL> drop table t;

Table dropped.

SQL> exec p;
Table t did not exist at time of drop. Continuing....

PL/SQL procedure successfully completed.

And now, with t in use:

SQL> create global temporary table t (data varchar2(4000));

Table created.

In another session:

SQL> insert into t values (null);

1 row created.

And then in the first session:

SQL> exec p;
Help!!!! Someone is keeping from doing my job!
Please rescue me

ERROR at line 1:
ORA-14452: attempt to create, alter or drop an index on temporary table already in use
ORA-06512: at "SCHEMA_NAME.P", line 16
ORA-06512: at line 1

How can I implement a theme from bootswatch or wrapbootstrap in an MVC 5 project?

All what you have to do is to select and download the bootstrap.css and bootstrap.js files from Bootswatch website, and then replace the original files with them.

Of course you have to add the paths to your layout page after the jQuery path that is all.

Selecting data from two different servers in SQL Server

As @Super9 told about OPENDATASOURCE using SQL Server Authentication with data provider SQLOLEDB . I am just posting here a code snippet for one table is in the current sever database where the code is running and another in other server ''

SELECT top 2 * from dbo.tblHamdoonSoft  tbl1 inner JOIN  
OpenDataSource('SQLOLEDB','Data Source=;User ID=sa;Password=hamdoonsoft')
.[TestDatabase].[dbo].[tblHamdoonSoft1] tbl2 on =

Git push won't do anything (everything up-to-date)

Right now, it appears as you are on the develop branch. Do you have a develop branch on your origin? If not, try git push origin develop. git push will work once it knows about a develop branch on your origin.

As further reading, I'd have a look at the git-push man pages, in particular, the examples section.

Difference between decimal, float and double in .NET?

  1. Double and float can be divided by integer zero without an exception at both compilation and run time.
  2. Decimal cannot be divided by integer zero. Compilation will always fail if you do that.

How to redirect 'print' output to a file using python?

If you are using Linux I suggest you to use the tee command. The implementation goes like this:

python | tee any_file_name.txt

If you don't want to change anything in the code, I think this might be the best possible solution. You can also implement logger but you need do some changes in the code.

Sorting Characters Of A C++ String

std::sort(str.begin(), str.end());

See here

Escaping Strings in JavaScript

You can also try this for the double quotes:

JSON.stringify(sDemoString).slice(1, -1);
JSON.stringify('my string with "quotes"').slice(1, -1);

How do I find which application is using up my port?

On the command prompt, do:

netstat -nb

Compare given date with today

$toBeComparedDate = '2014-08-12';
$today = (new DateTime())->format('Y-m-d'); //use format whatever you are using
$expiry = (new DateTime($toBeComparedDate))->format('Y-m-d');

var_dump(strtotime($today) > strtotime($expiry)); //false or true

How do I assert equality on two classes without an equals method?

AssertJ assertions can be used to compare the values without #equals method properly overridden, e.g.:

import static org.assertj.core.api.Assertions.assertThat; 

// ...


How do I check if a given string is a legal/valid file name under Windows?

Regular expressions are overkill for this situation. You can use the String.IndexOfAny() method in combination with Path.GetInvalidPathChars() and Path.GetInvalidFileNameChars().

Also note that both Path.GetInvalidXXX() methods clone an internal array and return the clone. So if you're going to be doing this a lot (thousands and thousands of times) you can cache a copy of the invalid chars array for reuse.

How to convert Nonetype to int or string?

That TypeError only appears when you try to pass int() None (which is the only NoneType value, as far as I know). I would say that your real goal should not be to convert NoneType to int or str, but to figure out where/why you're getting None instead of a number as expected, and either fix it or handle the None properly.

Android get image from gallery into ImageView

i think your ImageView img is not instantiated its equal to null to the compiler; that's why an NullPointerException is raised

did you call in your activity

img = (ImageView) findViewById(;

where my_imageview is the id of your ImageView widget!!

What does the 'u' symbol mean in front of string values?

This is a feature, not a bug.

See, specifically the 'unicode type' section.

Create a date from day month and year with T-SQL

I personally Prefer Substring as it provide cleansing options and ability to split the string as needed. The assumption is that the data is of the format 'dd, mm, yyyy'.

--2012 and above
        RIGHT(REPLACE(@date, ' ', ''), 4)
        ,RIGHT(CONCAT('00',SUBSTRING(REPLACE(@date, ' ', ''), CHARINDEX(',', REPLACE(@date, ' ', '')) + 1, LEN(REPLACE(@date, ' ', '')) - CHARINDEX(',', REPLACE(@date, ' ', '')) - 5)),2)
        ,RIGHT(CONCAT('00',SUBSTRING(REPLACE(@date, ' ', ''), 1, CHARINDEX(',', REPLACE(@date, ' ', '')) - 1)),2)

--2008 and below
SELECT   RIGHT(REPLACE(@date, ' ', ''), 4)
        +RIGHT('00'+SUBSTRING(REPLACE(@date, ' ', ''), CHARINDEX(',', REPLACE(@date, ' ', '')) + 1, LEN(REPLACE(@date, ' ', '')) - CHARINDEX(',', REPLACE(@date, ' ', '')) - 5),2)
        +RIGHT('00'+SUBSTRING(REPLACE(@date, ' ', ''), 1, CHARINDEX(',', REPLACE(@date, ' ', '')) - 1),2)

Here is a demonstration of how it can be sued if the data is stored in a column. Needless to say, its ideal to check the result-set before applying to the column

DECLARE @Table TABLE (ID INT IDENTITY(1000,1), DateString VARCHAR(50), DateColumn DATE)

SELECT'12, 1, 2007',NULL
SELECT'15,3, 2007',NULL
SELECT'18, 11 , 2007',NULL
SELECT'22 , 11, 2007',NULL
SELECT'30, 12, 2007  ',NULL

SET DateColumn = CONCAT (
        RIGHT(REPLACE(DateString, ' ', ''), 4)
        ,RIGHT(CONCAT('00',SUBSTRING(REPLACE(DateString, ' ', ''), CHARINDEX(',', REPLACE(DateString, ' ', '')) + 1, LEN(REPLACE(DateString, ' ', '')) - CHARINDEX(',', REPLACE(DateString, ' ', '')) - 5)),2)
        ,RIGHT(CONCAT('00',SUBSTRING(REPLACE(DateString, ' ', ''), 1, CHARINDEX(',', REPLACE(DateString, ' ', '')) - 1)),2)

SELECT ID,DateString,DateColumn
FROM @Table

Is the sizeof(some pointer) always equal to four?

In addition to the 16/32/64 bit differences even odder things can occur.

There have been machines where sizeof(int *) will be one value, probably 4 but where sizeof(char *) is larger. Machines that naturally address words instead of bytes have to "augment" character pointers to specify what portion of the word you really want in order to properly implement the C/C++ standard.

This is now very unusual as hardware designers have learned the value of byte addressability.

How to insert pandas dataframe via mysqldb into database?

Andy Hayden mentioned the correct function (to_sql). In this answer, I'll give a complete example, which I tested with Python 3.5 but should also work for Python 2.7 (and Python 3.x):

First, let's create the dataframe:

# Create dataframe
import pandas as pd
import numpy as np

number_of_samples = 10
frame = pd.DataFrame({
    'feature1': np.random.random(number_of_samples),
    'feature2': np.random.random(number_of_samples),
    'class':    np.random.binomial(2, 0.1, size=number_of_samples),


Which gives:

   feature1  feature2  class
0  0.548814  0.791725      1
1  0.715189  0.528895      0
2  0.602763  0.568045      0
3  0.544883  0.925597      0
4  0.423655  0.071036      0
5  0.645894  0.087129      0
6  0.437587  0.020218      0
7  0.891773  0.832620      1
8  0.963663  0.778157      0
9  0.383442  0.870012      0

To import this dataframe into a MySQL table:

# Import dataframe into MySQL
import sqlalchemy
database_username = 'ENTER USERNAME'
database_password = 'ENTER USERNAME PASSWORD'
database_ip       = 'ENTER DATABASE IP'
database_name     = 'ENTER DATABASE NAME'
database_connection = sqlalchemy.create_engine('mysql+mysqlconnector://{0}:{1}@{2}/{3}'.
                                               format(database_username, database_password, 
                                                      database_ip, database_name))
frame.to_sql(con=database_connection, name='table_name_for_df', if_exists='replace')

One trick is that MySQLdb doesn't work with Python 3.x. So instead we use mysqlconnector, which may be installed as follows:

pip install mysql-connector==2.1.4  # version avoids Protobuf error


enter image description here

Note that to_sql creates the table as well as the columns if they do not already exist in the database.

How to upload files to server using JSP/Servlet?

Another source of this problem occurs if you are using Geronimo with its embedded Tomcat. In this case, after many iterations of testing commons-io and commons-fileupload, the problem arises from a parent classloader handling the commons-xxx jars. This has to be prevented. The crash always occurred at:

fileItems = uploader.parseRequest(request);

Note that the List type of fileItems has changed with the current version of commons-fileupload to be specifically List<FileItem> as opposed to prior versions where it was generic List.

I added the source code for commons-fileupload and commons-io into my Eclipse project to trace the actual error and finally got some insight. First, the exception thrown is of type Throwable not the stated FileIOException nor even Exception (these will not be trapped). Second, the error message is obfuscatory in that it stated class not found because axis2 could not find commons-io. Axis2 is not used in my project at all but exists as a folder in the Geronimo repository subdirectory as part of standard installation.

Finally, I found 1 place that posed a working solution which successfully solved my problem. You must hide the jars from parent loader in the deployment plan. This was put into geronimo-web.xml with my full file shown below.

Pasted from <> 

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<web:web-app xmlns:app="" xmlns:client="" xmlns:conn="" xmlns:dep="" xmlns:ejb="" xmlns:log="" xmlns:name="" xmlns:pers="" xmlns:pkgen="" xmlns:sec="" xmlns:web="">

<!--Don't load commons-io or fileupload from parent classloaders-->


How to customize <input type="file">?

first of all it's a container:

<div class="upload_file_container">
    Select file!
    <input type="file" name="photo" />

The second, it's a CSS style, if you want to real more customization, just keeping your eyes is open :)

   background(your img);

.upload_file_container input{

This example hasn't style for text inside the button, it depends on font-size, just correct the height and padding-top values for container

Unable to launch the IIS Express Web server

I ran in to this error today. Running Win 8.1 and VS 2013. Suddenly my projects could not run anymore and i got the message "Unable to launch the IIS Express Web server" and no further information.

After a while I found out that all the projects that the IIS Express could not start all were running .net 3.5. Projects running later versions did start ok.

The solution for me was to remove .net 3.5 (from control panel -> turn windows features on/off), restart windows and the add .net 3.5 again.

How can I solve "Non-static method xxx:xxx() should not be called statically in PHP 5.4?

You can either remove E_STRICT from error_reporting(), or you can simply make your method static, if you need to call it statically. As far as I know, there is no (strict) way to have a method that can be invoked both as static and non-static method. Also, which is more annoying, you cannot have two methods with the same name, one being static and the other non-static.

Boolean operators ( &&, -a, ||, -o ) in Bash

-a and -o are the older and/or operators for the test command. && and || are and/or operators for the shell. So (assuming an old shell) in your first case,

[ "$1" = 'yes' ] && [ -r $2.txt ]

The shell is evaluating the and condition. In your second case,

[ "$1" = 'yes' -a $2 -lt 3 ]

The test command (or builtin test) is evaluating the and condition.

Of course in all modern or semi-modern shells, the test command is built in to the shell, so there really isn't any or much difference. In modern shells, the if statement can be written:

[[ $1 == yes && -r $2.txt ]]

Which is more similar to modern programming languages and thus is more readable.

The APK file does not exist on disk

assemble[Variant] would generate the APK for you on disk although it should not be necessary to use it to debug the app.

Run the following command in the root directory of the project:

$ ./gradlew clean build assemble[Variant]


ImportError: DLL load failed: %1 is not a valid Win32 application. But the DLL's are there

I copied cv2.pyd file from /opencv/build/python/2.7/x86 folder instead of from /x64 folder to C:/Python27/Lib/site-packeges. I followed rest of the instructions provided here.

Added by someone else, not verified: I also copy file cv2.pyd to folder C:/Python27/Lib/site-packages/cv2. It works.

Group by & count function in sqlalchemy

You can also count on multiple groups and their intersection:

self.session.query(func.count(Table.column1),Table.column1, Table.column2).group_by(Table.column1, Table.column2).all()

The query above will return counts for all possible combinations of values from both columns.

UPDATE multiple tables in MySQL using LEFT JOIN

                DECLARE @cols VARCHAR(max),@colsUpd VARCHAR(max), @query VARCHAR(max),@queryUpd VARCHAR(max), @subQuery VARCHAR(max)
DECLARE @TableNameTest NVARCHAR(150)
SET @TableNameTest = @TableName+ '_Staging';
SELECT  @colsUpd = STUF  ((SELECT DISTINCT '], T1.[' + name,']=T2.['+name+'' FROM sys.columns
                 WHERE object_id = (
                                    SELECT top 1 object_id 
                                      FROM sys.objects
                                     WHERE name = ''+@TableNameTest+''
                and name not in ('Action','Record_ID')
                FOR XML PATH('')
            ), 1, 2, ''
        ) + ']'

  Select @queryUpd ='Update T1
SET '+@colsUpd+'
FROM '+@TableName+' T1
INNER JOIN '+@TableNameTest+' T2
ON T1.Record_ID = T2.Record_Id
WHERE T2.[Action] = ''Modify'''
EXEC (@queryUpd)

Activate tabpage of TabControl

There are two properties in a TabControl control that manages which tab page is selected.

SelectedIndex which offer the possibility to select it by index (an integer starting from 0 to the number of tabs you have minus one).

SelectedTab which offer the possibility to selected the tab object itself to select.

Setting either of these property will change the currently displayed tab.

Alternatively you can also use the Select method. It comes in three flavour, one where you pass the index of the tab, another the TabPage object itself and the last one a string representing the tab's name.

How to dynamically create CSS class in JavaScript and apply?

Here is Vishwanath's solution slightly rewritten with comments :

function setStyle(cssRules, aSelector, aStyle){
    for(var i = 0; i < cssRules.length; i++) {
        if(cssRules[i].selectorText && cssRules[i].selectorText.toLowerCase() == aSelector.toLowerCase()) {
            cssRules[i].style.cssText = aStyle;
            return true;
    return false;

function createCSSSelector(selector, style) {
    var doc = document;
    var allSS = doc.styleSheets;
    if(!allSS) return;

    var headElts = doc.getElementsByTagName("head");
    if(!headElts.length) return;

    var styleSheet, media, iSS = allSS.length; // scope is global in a function
    /* 1. search for media == "screen" */
    while(iSS){ --iSS;
        if(allSS[iSS].disabled) continue; /* dont take into account the disabled stylesheets */
        media = allSS[iSS].media;
        if(typeof media == "object")
            media = media.mediaText;
        if(media == "" || media=='all' || media.indexOf("screen") != -1){
            styleSheet = allSS[iSS];
            iSS = -1;   // indication that media=="screen" was found (if not, then iSS==0)

    /* 2. if not found, create one */
    if(iSS != -1) {
        var styleSheetElement = doc.createElement("style");
        styleSheetElement.type = "text/css";
        styleSheet = doc.styleSheets[allSS.length]; /* take the new stylesheet to add the selector and the style */

    /* 3. add the selector and style */
    switch (typeof {
    case "string":
        if(!setStyle(styleSheet.rules, selector, style));
            styleSheet.addRule(selector, style);
    case "object":
        if(!setStyle(styleSheet.cssRules, selector, style));
            styleSheet.insertRule(selector + "{" + style + "}", styleSheet.cssRules.length);

How to use a keypress event in AngularJS?

here's my directive:

mainApp.directive('number', function () {
    return {
        link: function (scope, el, attr) {
            el.bind("keydown keypress", function (event) {
                //ignore all characters that are not numbers, except backspace, delete, left arrow and right arrow
                if ((event.keyCode < 48 || event.keyCode > 57) && event.keyCode != 8 && event.keyCode != 46 && event.keyCode != 37 && event.keyCode != 39) {


<input number />

Add a column to existing table and uniquely number them on MS SQL Server

This will depend on the database but for SQL Server, this could be achieved as follows:

alter table Example
add NewColumn int identity(1,1)

Loading PictureBox Image from resource file with path (Part 3) first you need to import the image into your project.

1) Select the PictureBox in the Form Design View

2) Open PictureBox Tasks
(it's the little arrow printed to right on the edge of the PictureBox)

3) Click on "Choose image..."

4) Select the second option "Project resource file:"
(this option will create a folder called "Resources" which you can access with Properties.Resources)

5) Click on "Import..." and select your image from your computer
(now a copy of the image will be saved in "Resources" folder created at step 4)

6) Click on "OK"

Now the image is in your project and you can use it with the Properties command. Just type this code when you want to change the picture in the PictureBox:

pictureBox1.Image = Properties.Resources.MyImage;

MyImage represent the name of the image...
After typing "Properties.Resources.", all imported image files are displayed...

Could not load file or assembly 'EntityFramework' after downgrading EF -->

I had the same issue when updating an older project. Here's what I did to resolve it:

  • Converted all projects to .NET 4.5.
  • Uninstalled the NuGet package for Entity Framework 5.
  • Reinstalled the NuGet package for Entity Framework 5.
  • Cleaned the solution.
  • Rebuilt the solution.

The projects that used Entity Framework 5 and .NET 4 were installing the Entity Framework dll version 4.4. Once I switched the .NET version to 4.5 on the project, the dll version would be 5.

My problem came from older projects being on .NET 4 and a newer project running .NET 4.5 so there were 2 dll versions of EF in my solution.

Hope this helps someone...

How to deploy a war file in Tomcat 7

You just need to put your war file in webapps and then start your server.

it will get deployed.

otherwise you can also use tomcat manager a webfront to upload & deploy your war remotely.

Convert a String In C++ To Upper Case

Without using any libraries:

std::string YourClass::Uppercase(const std::string & Text)
    std::string UppperCaseString;
    for (std::string::const_iterator it=Text.begin(); it<Text.end(); ++it)
        UppperCaseString.push_back(((0x60 < *it) && (*it < 0x7B)) ? (*it - static_cast<char>(0x20)) : *it);
    return UppperCaseString;

How to access the elements of a 2D array?

If you have this :

a = [[1, 1], [2, 1],[3, 1]]

You can easily access this by using :

a[0][1] = 7

Using Bootstrap Modal window as PartialView

I do this with mustache.js and templates (you could use any JavaScript templating library).

In my view, I have something like this:

<script type="text/x-mustache-template" id="modalTemplate">

...which lets me keep my templates in a partial view called Modal.ascx:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
        <div class="modal-header">
            <a class="close" data-dismiss="modal">&times;</a>
        <div class="modal-body">
            <table class="table table-striped table-condensed">
        <div class="modal-footer">
            <a class="btn" data-dismiss="modal">Close</a>

I create placeholders for each modal in my view:

<%foreach (var item in Model) {%>
    <div data-id="<%=Html.Encode(item.Id)%>"
         class="modal hide fade">

...and make ajax calls with jQuery:

<script type="text/javascript">
    var modalTemplate = $("#modalTemplate").html()
    $(".modal[data-id]").each(function() {
        var $this = $(this)
        var id = $this.attr("data-id")
        $this.on("show", function() {
            if ($this.html()) return
                type: "POST",
                url: "<%=Url.Action("SomeAction")%>",
                data: { id: id },
                success: function(data) {
                    $this.append(Mustache.to_html(modalTemplate, data))

Then, you just need a trigger somewhere:

<%foreach (var item in Model) {%>
    <a data-toggle="modal" href="#modelModal<%=Html.Encode(item.Id)%>">

How do you easily create empty matrices javascript?

There is something about Array.fill I need to mention.

If you just use below method to create a 3x3 matrix.


You will find that the values in the matrix is a reference.

enter image description here

Optimized solution (prevent passing by reference):

If you want to pass by value rather than reference, you can leverage to create it.

Array(3).fill(null).map(() => Array(3).fill(0));

enter image description here

Why do I have ORA-00904 even when the column is present?

Write the column name in between DOUBLE quote as in "columnName".

If the error message shows a different character case than what you wrote, it is very likely that your sql client performed an automatic case conversion for you. Use double quote to bypass that. (This works on Squirrell Client 3.0).

When to use dynamic vs. static libraries

If the library is static, then at link time the code is linked in with your executable. This makes your executable larger (than if you went the dynamic route).

If the library is dynamic then at link time references to the required methods are built in to your executable. This means that you have to ship your executable and the dynamic library. You also ought to consider whether shared access to the code in the library is safe, preferred load address among other stuff.

If you can live with the static library, go with the static library.

How to format a JavaScript date

Requested format in one line - no libraries and no Date methods, just regex:

var d = (new Date()).toString().replace(/\S+\s(\S+)\s(\d+)\s(\d+)\s.*/,'$2-$1-$3');
// date will be formatted as "14-Oct-2015" (pass any date object in place of 'new Date()')

In my testing, this works reliably in the major browsers (Chrome, Safari, Firefox and IE.) As @RobG pointed out, the output of Date.prototype.toString() is implementation-dependent, so for international or non-browser implementations, just test the output to be sure it works right in your JavaScript engine. You can even add some code to test the string output and make sure it's matching what you expect before you do the regex replace.