Programs & Examples On #External

This tag refers to something that is outside of a particular system. In other words, it is something that is not a part of the main system and therefore can be considered "extra".

How to style SVG with external CSS?

What works for me: style tag with @import rule

<defs>
    <style type="text/css">
        @import url("svg-common.css");
    </style>
</defs>

Eclipse: How to build an executable jar with external jar?

You can do this by writing a manifest for your jar. Have a look at the Class-Path header. Eclipse has an option for choosing your own manifest on export.

The alternative is to add the dependency to the classpath at the time you invoke the application:

win32: java.exe -cp app.jar;dependency.jar foo.MyMainClass
*nix:  java -cp app.jar:dependency.jar foo.MyMainClass

Android saving file to external storage

Make sure your app has the proper permissions to be allowed to write to external storage: http://developer.android.com/reference/android/Manifest.permission.html#WRITE_EXTERNAL_STORAGE

It should look something like this in your manifest file:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

How to call execl() in C with the proper arguments?

If you need just to execute your VLC playback process and only give control back to your application process when it is done and nothing more complex, then i suppose you can use just:

system("The same thing you type into console");

PHP ini file_get_contents external url

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.your_external_website.com");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);

is best for http url, But how to open https url help me

Find location of a removable SD card

You can try to use the support library function called of ContextCompat.getExternalFilesDirs() :

      final File[] appsDir=ContextCompat.getExternalFilesDirs(getActivity(),null);
      final ArrayList<File> extRootPaths=new ArrayList<>();
      for(final File file : appsDir)
        extRootPaths.add(file.getParentFile().getParentFile().getParentFile().getParentFile());

The first one is the primary external storage, and the rest are supposed to be real SD-cards paths.

The reason for the multiple ".getParentFile()" is to go up another folder, since the original path is

.../Android/data/YOUR_APP_PACKAGE_NAME/files/

EDIT: here's a more comprehensive way I've created, to get the sd-cards paths:

  /**
   * returns a list of all available sd cards paths, or null if not found.
   *
   * @param includePrimaryExternalStorage set to true if you wish to also include the path of the primary external storage
   */
  @TargetApi(Build.VERSION_CODES.HONEYCOMB)
  public static List<String> getSdCardPaths(final Context context, final boolean includePrimaryExternalStorage)
    {
    final File[] externalCacheDirs=ContextCompat.getExternalCacheDirs(context);
    if(externalCacheDirs==null||externalCacheDirs.length==0)
      return null;
    if(externalCacheDirs.length==1)
      {
      if(externalCacheDirs[0]==null)
        return null;
      final String storageState=EnvironmentCompat.getStorageState(externalCacheDirs[0]);
      if(!Environment.MEDIA_MOUNTED.equals(storageState))
        return null;
      if(!includePrimaryExternalStorage&&VERSION.SDK_INT>=VERSION_CODES.HONEYCOMB&&Environment.isExternalStorageEmulated())
        return null;
      }
    final List<String> result=new ArrayList<>();
    if(includePrimaryExternalStorage||externalCacheDirs.length==1)
      result.add(getRootOfInnerSdCardFolder(externalCacheDirs[0]));
    for(int i=1;i<externalCacheDirs.length;++i)
      {
      final File file=externalCacheDirs[i];
      if(file==null)
        continue;
      final String storageState=EnvironmentCompat.getStorageState(file);
      if(Environment.MEDIA_MOUNTED.equals(storageState))
        result.add(getRootOfInnerSdCardFolder(externalCacheDirs[i]));
      }
    if(result.isEmpty())
      return null;
    return result;
    }

  /** Given any file/folder inside an sd card, this will return the path of the sd card */
  private static String getRootOfInnerSdCardFolder(File file)
    {
    if(file==null)
      return null;
    final long totalSpace=file.getTotalSpace();
    while(true)
      {
      final File parentFile=file.getParentFile();
      if(parentFile==null||parentFile.getTotalSpace()!=totalSpace||!parentFile.canRead())
        return file.getAbsolutePath();
      file=parentFile;
      }
    }

Getting the 'external' IP address in Java

As @Donal Fellows wrote, you have to query the network interface instead of the machine. This code from the javadocs worked for me:

The following example program lists all the network interfaces and their addresses on a machine:

import java.io.*;
import java.net.*;
import java.util.*;
import static java.lang.System.out;

public class ListNets {

    public static void main(String args[]) throws SocketException {
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netint : Collections.list(nets))
            displayInterfaceInformation(netint);
    }

    static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
        out.printf("Display name: %s\n", netint.getDisplayName());
        out.printf("Name: %s\n", netint.getName());
        Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
        for (InetAddress inetAddress : Collections.list(inetAddresses)) {
            out.printf("InetAddress: %s\n", inetAddress);
        }
        out.printf("\n");
     }
} 

The following is sample output from the example program:

Display name: TCP Loopback interface
Name: lo
InetAddress: /127.0.0.1

Display name: Wireless Network Connection
Name: eth0
InetAddress: /192.0.2.0

From docs.oracle.com

How to invoke function from external .c file in C?

use #include "ClasseAusiliaria.c" [Dont use angle brackets (< >) ]

and I prefer save file with .h extension in the same Directory/folder.

#include "ClasseAusiliaria.h"

What are the differences between a HashMap and a Hashtable in Java?

Hashtable:

Hashtable is a data structure that retains values of key-value pair. It doesn’t allow null for both the keys and the values. You will get a NullPointerException if you add null value. It is synchronized. So it comes with its cost. Only one thread can access HashTable at a particular time.

Example :

import java.util.Map;
import java.util.Hashtable;

public class TestClass {

    public static void main(String args[ ]) {
    Map<Integer,String> states= new Hashtable<Integer,String>();
    states.put(1, "INDIA");
    states.put(2, "USA");

    states.put(3, null);    //will throw NullPointerEcxeption at runtime

    System.out.println(states.get(1));
    System.out.println(states.get(2));
//  System.out.println(states.get(3));

    }
}

HashMap:

HashMap is like Hashtable but it also accepts key value pair. It allows null for both the keys and the values. Its performance better is better than HashTable, because it is unsynchronized.

Example:

import java.util.HashMap;
import java.util.Map;

public class TestClass {

    public static void main(String args[ ]) {
    Map<Integer,String> states = new HashMap<Integer,String>();
    states.put(1, "INDIA");
    states.put(2, "USA");

    states.put(3, null);    // Okay
    states.put(null,"UK");

    System.out.println(states.get(1));
    System.out.println(states.get(2));
    System.out.println(states.get(3));

    }
}

JUnit assertEquals(double expected, double actual, double epsilon)

Epsilon is your "fuzz factor," since doubles may not be exactly equal. Epsilon lets you describe how close they have to be.

If you were expecting 3.14159 but would take anywhere from 3.14059 to 3.14259 (that is, within 0.001), then you should write something like

double myPi = 22.0d / 7.0d; //Don't use this in real life!
assertEquals(3.14159, myPi, 0.001);

(By the way, 22/7 comes out to 3.1428+, and would fail the assertion. This is a good thing.)

Recover sa password

best answer written by Dmitri Korotkevitch:

Speaking of the installation, SQL Server 2008 allows you to set authentication mode (Windows or SQL Server) during the installation process. You will be forced to choose the strong password for sa user in the case if you choose sql server authentication mode during setup.

If you install SQL Server with Windows Authentication mode and want to change it, you need to do 2 different things:

  1. Go to SQL Server Properties/Security tab and change the mode to SQL Server authentication mode

  2. Go to security/logins, open SA login properties

a. Uncheck "Enforce password policy" and "Enforce password expiration" check box there if you decide to use weak password

b. Assign password to SA user

c. Open "Status" tab and enable login.

I don't need to mention that every action from above would violate security best practices that recommend to use windows authentication mode, have sa login disabled and use strong passwords especially for sa login.

CSS performance relative to translateZ(0)

On mobile devices sending everything to the GPU will cause a memory overload and crash the application. I encountered this on an iPad app in Cordova. Best to only send the required items to the GPU, the divs that you're specifically moving around.

Better yet, use the 3d transitions transforms to do the animations like translateX(50px) as opposed to left:50px;

Pass Model To Controller using Jquery/Ajax

Use the following JS:

$(document).ready(function () {
    $("#btnsubmit").click(function () {

             $.ajax({
                 type: "POST",
                 url: '/Plan/PlanManage',     //your action
                 data: $('#PlanForm').serialize(),   //your form name.it takes all the values of model               
                 dataType: 'json',
                 success: function (result) {
                     console.log(result);
                 }
             })
        return false;
    });
});

and the following code on your controller:

[HttpPost]
public string PlanManage(Plan objplan)  //model plan
{
}

CSS Box Shadow - Top and Bottom Only

I've played around with it and I think I have a solution. The following example shows how to set Box-Shadow so that it will only show a shadow for the inset top and bottom of an element.

Legend: insetOption leftPosition topPosition blurStrength spreadStrength color

Description
The key to accomplishing this is to set the blur value to <= the negative of the spread value (ex. inset 0px 5px -?px 5px #000; the blur value should be -5 and lower) and to also keep the blur value > 0 when subtracted from the primary positioning value (ex. using the example from above, the blur value should be -9 and up, thus giving us an optimal value for the the blur to be between -5 and -9).

Solution

.styleName {   
/* for IE 8 and lower */
background-color:#888; filter: progid:DXImageTransform.Microsoft.dropShadow(color=#FFFFCC, offX=0, offY=0, positive=true);  

/* for IE 9 */ 
box-shadow: inset 0px 2px -2px 2px rgba(255,255,204,0.7), inset 0px -2px -2px 2px rgba(255,255,204,0.7); 

/* for webkit browsers */ 
-webkit-box-shadow: inset 0px 2px -2px 2px rgba(255,255,204,0.7), inset 0px -2px -2px 2px rgba(255,255,204,0.7); 

/* for firefox 3.6+ */
-moz-box-shadow: inset 0px 2px -2px 2px rgba(255,255,204,0.7), inset 0px -2px -2px 2px rgba(255,255,204,0.7);   
}

Psexec "run as (remote) admin"

Simply add a -h after adding your credentials using a -u -p, and it will run with elevated privileges.

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

For my situation this error was caused by having circular references in json sent from the server when using an ORM for parent/child relationships. So the quick and easy solution was

JsonConvert.SerializeObject(myObject, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore })

The better solution is to create DTOs that do not contain the references on both sides (parent/child).

Get JSF managed bean by name in any Servlet related class

I had same requirement.

I have used the below way to get it.

I had session scoped bean.

@ManagedBean(name="mb")
@SessionScopedpublic 
class ManagedBean {
     --------
}

I have used the below code in my servlet doPost() method.

ManagedBean mb = (ManagedBean) request.getSession().getAttribute("mb");

it solved my problem.

How to make div go behind another div?

http://jsfiddle.net/f2znvn4f/


HTML

<div class="box-left-mini">
    <div class="front"><span>this is in front</span></div>
    <div class="behind_container">
        <div class="behind">behind</div>        
    </div>
</div>

CSS

.box-left-mini{
    float:left;
    background-image:url(website-content/hotcampaign.png);
    width:292px;
    height:141px;
}

.box-left-mini .front {
    display: block;
    z-index: 5;
    position: relative;
}
.box-left-mini .front span {
    background: #fff
}

.box-left-mini .behind_container {
    background-color: #ff0;
    position: relative;
    top: -18px;
}
.box-left-mini .behind {
    display: block;
    z-index: 3;
}

The reason you're getting so many different answers is because you've not explained what you want to do exactly. All the answers you get with code will be programmatically correct, but it's all down to what you want to achieve

How to read appSettings section in the web.config file?

Since you're accessing a web.config you should probably use

using System.Web.Configuration;

WebConfigurationManager.AppSettings["configFile"]

What is Scala's yield?

Yield is similar to for loop which has a buffer that we cannot see and for each increment, it keeps adding next item to the buffer. When the for loop finishes running, it would return the collection of all the yielded values. Yield can be used as simple arithmetic operators or even in combination with arrays. Here are two simple examples for your better understanding

scala>for (i <- 1 to 5) yield i * 3

res: scala.collection.immutable.IndexedSeq[Int] = Vector(3, 6, 9, 12, 15)

scala> val nums = Seq(1,2,3)
nums: Seq[Int] = List(1, 2, 3)

scala> val letters = Seq('a', 'b', 'c')
letters: Seq[Char] = List(a, b, c)

scala> val res = for {
     |     n <- nums
     |     c <- letters
     | } yield (n, c)

res: Seq[(Int, Char)] = List((1,a), (1,b), (1,c), (2,a), (2,b), (2,c), (3,a), (3,b), (3,c))

Hope this helps!!

Class has no objects member

First install pylint-django using following command

$ pip install pylint-django

Then run the second command as follows:

$ pylint test_file.py --load-plugins pylint_django

--load-plugins pylint_django is necessary for correctly review a code of django

jQuery trigger file input

Based on Guillaume Bodi's answer I did this:

$('.fileinputbar-button').on('click', function() {
    $('article.project_files > header, article.upload').show();
    $('article.project_files > header, article.upload header').addClass('active');
    $('.file_content, article.upload .content').show();
    $('.fileinput-button input').focus().click();
    $('.fileinput-button').hide();
});

which means it's hidden to start with and then displayed for the trigger, then hidden again immediately.

What is the $$hashKey added to my JSON.stringify result

https://www.timcosta.io/angular-js-object-comparisons/

Angular is pretty magical the first time people see it. Automatic DOM updates when you update a variable in your JS, and the same variable will update in your JS file when someone updates its value in the DOM. This same functionality works across page elements, and across controllers.

The key to all of this is the $$hashKey Angular attaches to objects and arrays used in ng-repeats.

This $$hashKey causes a lot of confusion for people who are sending full objects to an API that doesn't strip extra data. The API will return a 400 for all of your requests, but that $$hashKey just wont go away from your objects.

Angular uses the $$hashKey to keep track of which elements in the DOM belong to which item in an array that is being looped through in an ng-repeat. Without the $$hashKey Angular would have no way to apply changes the occur in the JavaScript or DOM to their counterpart, which is one of the main uses for Angular.

Consider this array:

users = [  
    {
         first_name: "Tim"
         last_name: "Costa"
         email: "[email protected]"
    }
]

If we rendered that into a list using ng-repeat="user in users", each object in it would receive a $$hashKey for tracking purposes from Angular. Here are two ways to avoid this $$hashKey.

Internet Explorer 11 detection

Edit 18 Nov 2016

This code also work (for those who prefer another solution , without using ActiveX)

var isIE11 = !!window.MSInputMethodContext && !!document.documentMode;
  // true on IE11
  // false on Edge and other IEs/browsers.

Original Answer

In order to check Ie11 , you can use this : ( tested)

(or run this)

!(window.ActiveXObject) && "ActiveXObject" in window

I have all VMS of IE :

enter image description here

enter image description here

enter image description here

enter image description here

Notice : this wont work for IE11 :

as you can see here , it returns true :

enter image description here

So what can we do :

Apparently , they added the machine bit space :

ie11 :

"Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729; rv:11.0) like Gecko"

ie12 :

"Mozilla/5.0 (Windows NT 6.3; Win64; x64; Trident/7.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729; rv:11.0) like Gecko"

so we can do:

/x64|x32/ig.test(window.navigator.userAgent)

this will return true only for ie11.

Get the filename of a fileupload in a document through JavaScript

Try

var fu1 = document.getElementById("FileUpload1").value;

Convert string to JSON array

If having following JSON from web service, Json Array as a response :

       [3]
 0:  {
 id: 2
 name: "a561137"
 password: "test"
 firstName: "abhishek"
 lastName: "ringsia"
 organization: "bbb"
    }-
1:  {
 id: 3
 name: "a561023"
 password: "hello"
 firstName: "hello"
  lastName: "hello"
  organization: "hello"
 }-
 2:  {
  id: 4
  name: "a541234"
  password: "hello"
  firstName: "hello"
  lastName: "hello"
  organization: "hello"
    }

have To Accept it first as a Json Array ,then while reading its Object have to use Object Mapper.readValue ,because Json Object Still in String .

      List<User> list = new ArrayList<User>();
      JSONArray jsonArr = new JSONArray(response);


      for (int i = 0; i < jsonArr.length(); i++) {
        JSONObject jsonObj = jsonArr.getJSONObject(i);
         ObjectMapper mapper = new ObjectMapper();
        User usr = mapper.readValue(jsonObj.toString(), User.class);      
        list.add(usr);

    }

mapper.read is correct function ,if u use mapper.convert(param,param) . It will give u error .

How to extract text from a PDF?

I was given a 400 page pdf file with a table of data that I had to import - luckily no images. Ghostscript worked for me:

gswin64c -sDEVICE=txtwrite -o output.txt input.pdf

The output file was split into pages with headers, etc., but it was then easy to write an app to strip out blank lines, etc, and suck in all 30,000 records. -dSIMPLE and -dCOMPLEX made no difference in this case.

How do I call a Django function on button click?

here is a pure-javascript, minimalistic approach. I use JQuery but you can use any library (or even no libraries at all).

<html>
    <head>
        <title>An example</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script>
            function call_counter(url, pk) {
                window.open(url);
                $.get('YOUR_VIEW_HERE/'+pk+'/', function (data) {
                    alert("counter updated!");
                });
            }
        </script>
    </head>
    <body>
        <button onclick="call_counter('http://www.google.com', 12345);">
            I update object 12345
        </button>
        <button onclick="call_counter('http://www.yahoo.com', 999);">
            I update object 999
        </button>
    </body>
</html>

Alternative approach

Instead of placing the JavaScript code, you can change your link in this way:

<a target="_blank" 
    class="btn btn-info pull-right" 
    href="{% url YOUR_VIEW column_3_item.pk %}/?next={{column_3_item.link_for_item|urlencode:''}}">
    Check It Out
</a>

and in your views.py:

def YOUR_VIEW_DEF(request, pk):
    YOUR_OBJECT.objects.filter(pk=pk).update(views=F('views')+1)
    return HttpResponseRedirect(request.GET.get('next')))

What does the question mark operator mean in Ruby?

It is a code style convention; it indicates that a method returns a boolean value.

The question mark is a valid character at the end of a method name.

How to compare two object variables in EL expression language?

In Expression Language you can just use the == or eq operator to compare object values. Behind the scenes they will actually use the Object#equals(). This way is done so, because until with the current EL 2.1 version you cannot invoke methods with other signatures than standard getter (and setter) methods (in the upcoming EL 2.2 it would be possible).

So the particular line

<c:when test="${lang}.equals(${pageLang})">

should be written as (note that the whole expression is inside the { and })

<c:when test="${lang == pageLang}">

or, equivalently

<c:when test="${lang eq pageLang}">

Both are behind the scenes roughly interpreted as

jspContext.findAttribute("lang").equals(jspContext.findAttribute("pageLang"))

If you want to compare constant String values, then you need to quote it

<c:when test="${lang == 'en'}">

or, equivalently

<c:when test="${lang eq 'en'}">

which is behind the scenes roughly interpreted as

jspContext.findAttribute("lang").equals("en")

Check if a string is html or not

Using jQuery in this case, the simplest form would be:

if ($(testString).length > 0)

If $(testString).length = 1, this means that there is one HTML tag inside textStging.

How to get css background color on <tr> tag to span entire row

tr.rowhighlight td, tr.rowhighlight th{
    background-color:#f0f8ff;
}

How do I use a custom Serializer with Jackson?

Use @JsonValue:

public class User {
    int id;
    String name;

    @JsonValue
    public int getId() {
        return id;
    }
}

@JsonValue only works on methods so you must add the getId method. You should be able to skip your custom serializer altogether.

How do you add an array to another array in Ruby and not end up with a multi-dimensional result?

Just another way of doing it.

[somearray, anotherarray].flatten
=> ["some", "thing", "another", "thing"]

Implode an array with JavaScript?

Array.join is what you need, but if you like, the friendly people at phpjs.org have created implode for you.

Then some slightly off topic ranting. As @jon_darkstar alreadt pointed out, jQuery is JavaScript and not vice versa. You don't need to know JavaScript to be able to understand how to use jQuery, but it certainly doesn't hurt and once you begin to appreciate reusability or start looking at the bigger picture you absolutely need to learn it.

Loop through a Map with JSTL

You can loop through a hash map like this

<%
ArrayList list = new ArrayList();
TreeMap itemList=new TreeMap();
itemList.put("test", "test");
list.add(itemList);
pageContext.setAttribute("itemList", list);                            
%>

  <c:forEach items="${itemList}" var="itemrow">
   <input  type="text"  value="<c:out value='${itemrow.test}'/>"/>
  </c:forEach>               

For more JSTL functionality look here

Getting current directory in .NET web application

The current directory is a system-level feature; it returns the directory that the server was launched from. It has nothing to do with the website.

You want HttpRuntime.AppDomainAppPath.

If you're in an HTTP request, you can also call Server.MapPath("~/Whatever").

How to access the elements of a 2D array?

a[1][1] does work as expected. Do you mean a11 as the first element of the first row? Cause that would be a[0][0].

using lodash .groupBy. how to add your own keys for grouped output?

In 2017 do so

_.chain(data)
  .groupBy("color")
  .toPairs()
  .map(item => _.zipObject(["color", "users"], item))
  .value();

How to remove trailing whitespaces with sed?

For those who look for efficiency (many files to process, or huge files), using the + repetition operator instead of * makes the command more than twice faster.

With GNU sed:

sed -Ei 's/[ \t]+$//' "$1"
sed -i 's/[ \t]\+$//' "$1"   # The same without extended regex

I also quickly benchmarked something else: using [ \t] instead of [[:space:]] also significantly speeds up the process (GNU sed v4.4):

sed -Ei 's/[ \t]+$//' "$1"

real    0m0,335s
user    0m0,133s
sys 0m0,193s

sed -Ei 's/[[:space:]]+$//' "$1"

real    0m0,838s
user    0m0,630s
sys 0m0,207s

sed -Ei 's/[ \t]*$//' "$1"

real    0m0,882s
user    0m0,657s
sys 0m0,227s

sed -Ei 's/[[:space:]]*$//' "$1"

real    0m1,711s
user    0m1,423s
sys 0m0,283s

CSS: How to remove pseudo elements (after, before,...)?

_x000D_
_x000D_
*::after {
   content: none !important;
}
*::before {
   content: none !important;
}
_x000D_
_x000D_
_x000D_

How to print from Flask @app.route to python console

It seems like you have it worked out, but for others looking for this answer, an easy way to do this is by printing to stderr. You can do that like this:

from __future__ import print_function # In python 2.7
import sys

@app.route('/button/')
def button_clicked():
    print('Hello world!', file=sys.stderr)
    return redirect('/')

Flask will display things printed to stderr in the console. For other ways of printing to stderr, see this stackoverflow post

How to find the maximum value in an array?

Iterate over the Array. First initialize the maximum value to the first element of the array and then for each element optimize it if the element under consideration is greater.

Count the number of Occurrences of a Word in a String

This should be a faster non-regex solution.
(note - Not a Java programmer)

 String str = "i have a male cat. the color of male cat is Black";
 int found  = 0;
 int oldndx = 0;
 int newndx = 0;

 while ( (newndx=str.indexOf("male cat", oldndx)) > -1 )
 {
     found++;
     oldndx = newndx+8;
 }

jQuery select element in parent window

I came across the same problem but, as stated above, the accepted solution did not work for me.

If you're inside a frame or iframe element, an alternative solution is to use

window.parent.$('#testdiv');

Here's a quick explanation of the differences between window.opener, window.parent and window.top:

  • window.opener refers to the window that called window.open( ... ) to open the window from which it's called
  • window.parent refers to the parent of a window in a frame or iframe element

Why is conversion from string constant to 'char*' valid in C but invalid in C++

You can declare like one of the below options:

char data[] = "Testing String";

or

const char* data = "Testing String";

or

char* data = (char*) "Testing String";

How can I format decimal property to currency?

Properties can return anything they want to, but it's going to need to return the correct type.

private decimal _amount;

public string FormattedAmount
{
    get { return string.Format("{0:C}", _amount); }
}

Question was asked... what if it was a nullable decimal.

private decimal? _amount;

public string FormattedAmount
{
    get
    {
         return _amount == null ? "null" : string.Format("{0:C}", _amount.Value);
    }
}  

Count character occurrences in a string in C++

Pseudocode:

count = 0
For each character c in string s
  Check if c equals '_'
    If yes, increase count

EDIT: C++ example code:

int count_underscores(string s) {
  int count = 0;

  for (int i = 0; i < s.size(); i++)
    if (s[i] == '_') count++;

  return count;
}

Note that this is code to use together with std::string, if you're using char*, replace s.size() with strlen(s).

Also note: I can understand you want something "as small as possible", but I'd suggest you to use this solution instead. As you see you can use a function to encapsulate the code for you so you won't have to write out the for loop everytime, but can just use count_underscores("my_string_") in the rest of your code. Using advanced C++ algorithms is certainly possible here, but I think it's overkill.

Syntax for async arrow function

Async arrow functions look like this:

const foo = async () => {
  // do something
}

Async arrow functions look like this for a single argument passed to it:

const foo = async evt => {
  // do something with evt
}

Async arrow functions look like this for multiple arguments passed to it:

const foo = async (evt, callback) => {
  // do something with evt
  // return response with callback
}

The anonymous form works as well:

const foo = async function() {
  // do something
}

An async function declaration looks like this:

async function foo() {
  // do something
}

Using async function in a callback:

const foo = event.onCall(async () => {
  // do something
})

Matplotlib 2 Subplots, 1 Colorbar

Shared colormap and colorbar

This is for the more complex case where the values are not just between 0 and 1; the cmap needs to be shared instead of just using the last one.

import numpy as np
from matplotlib.colors import Normalize
import matplotlib.pyplot as plt
import matplotlib.cm as cm
fig, axes = plt.subplots(nrows=2, ncols=2)
cmap=cm.get_cmap('viridis')
normalizer=Normalize(0,4)
im=cm.ScalarMappable(norm=normalizer)
for i,ax in enumerate(axes.flat):
    ax.imshow(i+np.random.random((10,10)),cmap=cmap,norm=normalizer)
    ax.set_title(str(i))
fig.colorbar(im, ax=axes.ravel().tolist())
plt.show()

How do I know which version of Javascript I'm using?

JavaScript 1.2 was introduced with Netscape Navigator 4 in 1997. That version number only ever had significance for Netscape browsers. For example, Microsoft's implementation (as used in Internet Explorer) is called JScript, and has its own version numbering which bears no relation to Netscape's numbering.

How to sort an array in descending order in Ruby

For those folks who like to measure speed in IPS ;)

require 'benchmark/ips'

ary = []
1000.times { 
  ary << {:bar => rand(1000)} 
}

Benchmark.ips do |x|
  x.report("sort")               { ary.sort{ |a,b| b[:bar] <=> a[:bar] } }
  x.report("sort reverse")       { ary.sort{ |a,b| a[:bar] <=> b[:bar] }.reverse }
  x.report("sort_by -a[:bar]")   { ary.sort_by{ |a| -a[:bar] } }
  x.report("sort_by a[:bar]*-1") { ary.sort_by{ |a| a[:bar]*-1 } }
  x.report("sort_by.reverse!")   { ary.sort_by{ |a| a[:bar] }.reverse }
  x.compare!
end

And results:

Warming up --------------------------------------
                sort    93.000  i/100ms
        sort reverse    91.000  i/100ms
    sort_by -a[:bar]   382.000  i/100ms
  sort_by a[:bar]*-1   398.000  i/100ms
    sort_by.reverse!   397.000  i/100ms
Calculating -------------------------------------
                sort    938.530  (± 1.8%) i/s -      4.743k in   5.055290s
        sort reverse    901.157  (± 6.1%) i/s -      4.550k in   5.075351s
    sort_by -a[:bar]      3.814k (± 4.4%) i/s -     19.100k in   5.019260s
  sort_by a[:bar]*-1      3.732k (± 4.3%) i/s -     18.706k in   5.021720s
    sort_by.reverse!      3.928k (± 3.6%) i/s -     19.850k in   5.060202s

Comparison:
    sort_by.reverse!:     3927.8 i/s
    sort_by -a[:bar]:     3813.9 i/s - same-ish: difference falls within error
  sort_by a[:bar]*-1:     3732.3 i/s - same-ish: difference falls within error
                sort:      938.5 i/s - 4.19x  slower
        sort reverse:      901.2 i/s - 4.36x  slower

ldap query for group members

Active Directory does not store the group membership on user objects. It only stores the Member list on the group. The tools show the group membership on user objects by doing queries for it.

How about:

(&(objectClass=group)(member=cn=my,ou=full,dc=domain))

(You forgot the (& ) bit in your example in the question as well).

What does the 'b' character do in front of a string literal?

Here's an example where the absence of b would throw a TypeError exception in Python 3.x

>>> f=open("new", "wb")
>>> f.write("Hello Python!")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' does not support the buffer interface

Adding a b prefix would fix the problem.

Display XML content in HTML page

You can use the old <xmp> tag. I don't know about browser support, but it should still work.

<HTML>

your code/tables

<xmp>
    <catalog>
        <cd>
            <title>Empire Burlesque</title>
            <artist>Bob Dylan</artist>
            <country>USA</country>
            <country>Columbia</country>
            <price>10.90</price>
            <year>1985</year>
        </cd>
    </catalog>
</xmp>

Output:

your code/tables
<catalog>
    <cd>
        <title>Empire Burlesque</title>
        <artist>Bob Dylan</artist>
        <country>USA</country>
        <country>Columbia</country>
        <price>10.90</price>
        <year>1985</year>
    </cd>
</catalog>

IntelliJ IDEA JDK configuration on Mac OS

Just tried this recently and when trying to select the JDK... /System/Library/Java/JavaVirtualMachines/ appears as empty when opening&selecting through IntelliJ. Therefore i couldn't select the JDK...

I've found that to workaround this, when the finder windows open (pressing [+] JDK) just use the shortcut Shift + CMD + G to specify the path. (/System/Library/Java/JavaVirtualMachines/1.6.0.jdk in my case)

And voila, IntelliJ can find everything from that point on.

How do you make sure email you send programmatically is not automatically marked as spam?

It sounds like you are depending on some feedback to determine what is getting stuck on the receiving end. You should be checking the outbound mail yourself for obvious "spaminess".

Buy any decent spam control system, and send your outbound mail through it. If you send any decent volume of mail, you should be doing this anyhow, because of the risk of sending outbound viruses, especially if you have desktop windows users.

Proofpoint had spam + anti-virus + some reputation services in a single deployment, for example. (I used to work there, so I happen to know this off the top of my head. I'm sure other vendors in this space have similar features.) But you get the idea. If you send your mail through a basic commerical spam control setup, and it doesn't pass, it shouldn't be going out of your network.

Also, there are some companies that can assist you with increasing delivery rates of non-spam, outbound email, like Habeas.

JavaScript: Class.method vs. Class.prototype.method

A. Static Method:

      Class.method = function () { /* code */ }
  1. method() here is a function property added to an another function (here Class).
  2. You can directly access the method() by the class / function name. Class.method();
  3. No need for creating any object/instance (new Class()) for accessing the method(). So you could call it as a static method.

B. Prototype Method (Shared across all the instances):

     Class.prototype.method = function () { /* code using this.values */ }
  1. method() here is a function property added to an another function protype (here Class.prototype).
  2. You can either directly access by class name or by an object/instance (new Class()).
  3. Added advantage - this way of method() definition will create only one copy of method() in the memory and will be shared across all the object's/instance's created from the Class

C. Class Method (Each instance has its own copy):

   function Class () {
      this.method = function () { /* do something with the private members */};
   }
  1. method() here is a method defined inside an another function (here Class).
  2. You can't directly access the method() by the class / function name. Class.method();
  3. You need to create an object/instance (new Class()) for the method() access.
  4. This way of method() definition will create a unique copy of the method() for each and every objects created using the constructor function (new Class()).
  5. Added advantage - Bcos of the method() scope it has the full right to access the local members(also called private members) declared inside the constructor function (here Class)

Example:

    function Class() {
        var str = "Constructor method"; // private variable
        this.method = function () { console.log(str); };
    }
    Class.prototype.method = function() { console.log("Prototype method"); };
    Class.method = function() { console.log("Static method"); };

    new Class().method();     // Constructor method
    // Bcos Constructor method() has more priority over the Prototype method()

    // Bcos of the existence of the Constructor method(), the Prototype method 
    // will not be looked up. But you call it by explicity, if you want.
    // Using instance
    new Class().constructor.prototype.method(); // Prototype method

    // Using class name
    Class.prototype.method(); // Prototype method

    // Access the static method by class name
    Class.method();           // Static method

disabling spring security in spring boot app

With this solution you can fully enable/disable the security by activating a specific profile by command line. I defined the profile in a file application-nosecurity.yaml

spring:
  autoconfigure:
    exclude: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration

Then I modified my custom WebSecurityConfigurerAdapter by adding the @Profile("!nosecurity") as follows:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@Profile("!nosecurity")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {...}

To fully disable the security it's enough to start the application up by specifying the nosecurity profile, i.e.:

java -jar  target/myApp.jar --spring.profiles.active=nosecurity

submitting a form when a checkbox is checked

Submit form when your checkbox is checked

$(document).ready(function () {   
$("#yoursubmitbuttonid").click(function(){           
                if( $(".yourcheckboxclass").is(":checked") )
                {
                    $("#yourformId").submit();

                }else{
                    alert("Please select !!!");
                    return false;
                }
                return false;
            }); 
});

How do I set path while saving a cookie value in JavaScript?

See https://developer.mozilla.org/en/DOM/document.cookie for more documentation:

 setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {  
     if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/.test(sKey)) { return; }  
     var sExpires = "";  
     if (vEnd) {  
       switch (typeof vEnd) {  
         case "number": sExpires = "; max-age=" + vEnd; break;  
         case "string": sExpires = "; expires=" + vEnd; break;  
         case "object": if (vEnd.hasOwnProperty("toGMTString")) { sExpires = "; expires=" + vEnd.toGMTString(); } break;  
       }  
     }  
     document.cookie = escape(sKey) + "=" + escape(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");  
   }

When is a C++ destructor called?

Others have already addressed the other issues, so I'll just look at one point: do you ever want to manually delete an object.

The answer is yes. @DavidSchwartz gave one example, but it's a fairly unusual one. I'll give an example that's under the hood of what a lot of C++ programmers use all the time: std::vector (and std::deque, though it's not used quite as much).

As most people know, std::vector will allocate a larger block of memory when/if you add more items than its current allocation can hold. When it does this, however, it has a block of memory that's capable of holding more objects than are currently in the vector.

To manage that, what vector does under the covers is allocate raw memory via the Allocator object (which, unless you specify otherwise, means it uses ::operator new). Then, when you use (for example) push_back to add an item to the vector, internally the vector uses a placement new to create an item in the (previously) unused part of its memory space.

Now, what happens when/if you erase an item from the vector? It can't just use delete -- that would release its entire block of memory; it needs to destroy one object in that memory without destroying any others, or releasing any of the block of memory it controls (for example, if you erase 5 items from a vector, then immediately push_back 5 more items, it's guaranteed that the vector will not reallocate memory when you do so.

To do that, the vector directly destroys the objects in the memory by explicitly calling the destructor, not by using delete.

If, perchance, somebody else were to write a container using contiguous storage roughly like a vector does (or some variant of that, like std::deque really does), you'd almost certainly want to use the same technique.

Just for example, let's consider how you might write code for a circular ring-buffer.

#ifndef CBUFFER_H_INC
#define CBUFFER_H_INC

template <class T>
class circular_buffer {
    T *data;
    unsigned read_pos;
    unsigned write_pos;
    unsigned in_use;
    const unsigned capacity;
public:
    circular_buffer(unsigned size) :
        data((T *)operator new(size * sizeof(T))),
        read_pos(0),
        write_pos(0),
        in_use(0),
        capacity(size)
    {}

    void push(T const &t) {
        // ensure there's room in buffer:
        if (in_use == capacity) 
            pop();

        // construct copy of object in-place into buffer
        new(&data[write_pos++]) T(t);
        // keep pointer in bounds.
        write_pos %= capacity;
        ++in_use;
    }

    // return oldest object in queue:
    T front() {
        return data[read_pos];
    }

    // remove oldest object from queue:
    void pop() { 
        // destroy the object:
        data[read_pos++].~T();

        // keep pointer in bounds.
        read_pos %= capacity;
        --in_use;
    }
  
~circular_buffer() {
    // first destroy any content
    while (in_use != 0)
        pop();

    // then release the buffer.
    operator delete(data); 
}

};

#endif

Unlike the standard containers, this uses operator new and operator delete directly. For real use, you probably do want to use an allocator class, but for the moment it would do more to distract than contribute (IMO, anyway).

REST / SOAP endpoints for a WCF service

MSDN seems to have an article for this now:

https://msdn.microsoft.com/en-us/library/bb412196(v=vs.110).aspx

Intro:

By default, Windows Communication Foundation (WCF) makes endpoints available only to SOAP clients. In How to: Create a Basic WCF Web HTTP Service, an endpoint is made available to non-SOAP clients. There may be times when you want to make the same contract available both ways, as a Web endpoint and as a SOAP endpoint. This topic shows an example of how to do this.

How to enter quotes in a Java string?

Just escape the quotes:

String value = "\"ROM\"";

How to check if the user can go back in browser history or not

the browser has back and forward button. I come up a solution on this question. but It will affect browser forward action and cause bug with some browsers.

It works like that: If the browser open a new url, that has never opened, the history.length will be grow.

so you can change hash like

  location.href = '#__transfer__' + new Date().getTime() 

to get a never shown url, then history.length will get the true length.

  var realHistoryLength = history.length - 1

but, It not always work well, and I don't known why ,especially the when url auto jump quickly.

Bundler: Command not found

My problem was that I did:

sudo gem install bundler

So I had installed as root rather than as myself. So I uninstalled as root, then installed as myself:

sudo gem uninstall bundler
gem install bundler
rbenv rehash

(last command for if you are using rbenv)

And it worked. The "correct" path was in .bashrc (or other shell profile), at least according to

$PATH
=> zsh: /Users/myself/.rbenv/shims:/Users/myself/.rbenv/bin: ... etc

but it was expecting it to be installed for myself - not for root. In my case, its rightful installation place is in ~/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/gems/bundler

How to make an embedded Youtube video automatically start playing?

This works perfectly for me try this just put ?rel=0&autoplay=1 in the end of link

<iframe width="631" height="466" src="https://www.youtube.com/embed/UUdMixCYeTA?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>

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

I do have an article on MSDN - Creating ASP.NET MVC with custom bootstrap theme / layout using VS 2012, VS 2013 and VS 2015, also have a demo code sample attached.. Please refer below link. https://code.msdn.microsoft.com/ASPNET-MVC-application-62ffc106

Android button font size

In XML file, the font size of ant text including the button, textView, editText and others can be changed by the adding

android:textSize="10sp"

List changes unexpectedly after assignment. How do I clone or copy it to prevent this?

A slight practical perspective to look into memory through id and gc.

>>> b = a = ['hell', 'word']
>>> c = ['hell', 'word']

>>> id(a), id(b), id(c)
(4424020872, 4424020872, 4423979272) 
     |           |
      -----------

>>> id(a[0]), id(b[0]), id(c[0])
(4424018328, 4424018328, 4424018328) # all referring to same 'hell'
     |           |           |
      -----------------------

>>> id(a[0][0]), id(b[0][0]), id(c[0][0])
(4422785208, 4422785208, 4422785208) # all referring to same 'h'
     |           |           |
      -----------------------

>>> a[0] += 'o'
>>> a,b,c
(['hello', 'word'], ['hello', 'word'], ['hell', 'word'])  # b changed too
>>> id(a[0]), id(b[0]), id(c[0])
(4424018384, 4424018384, 4424018328) # augmented assignment changed a[0],b[0]
     |           |
      -----------

>>> b = a = ['hell', 'word']
>>> id(a[0]), id(b[0]), id(c[0])
(4424018328, 4424018328, 4424018328) # the same hell
     |           |           |
      -----------------------

>>> import gc
>>> gc.get_referrers(a[0]) 
[['hell', 'word'], ['hell', 'word']]  # one copy belong to a,b, the another for c
>>> gc.get_referrers(('hell'))
[['hell', 'word'], ['hell', 'word'], ('hell', None)] # ('hello', None) 

Sourcetree - undo unpushed commits

If You are on another branch, You need first "check to this commit" for commit you want to delete, and only then "reset current branch to this commit" choosing previous wright commit, will work.

Making a button invisible by clicking another button in HTML

write this

To hide

{document.getElementById("p2").style.display="none";}

to show

{document.getElementById("p2").style.display="block";}

How to use Google fonts in React.js?

Had the same issue. Turns out I was using " instead of '.

use @import url('within single quotes'); like this

not @import url("within double quotes"); like this

Use Ant for running program with command line arguments

Extending Richard Cook's answer.

Here's the ant task to run any program (including, but not limited to Java programs):

<target name="run">
   <exec executable="name-of-executable">
      <arg value="${arg0}"/>
      <arg value="${arg1}"/>
   </exec>
</target>

Here's the task to run a Java program from a .jar file:

<target name="run-java">
   <java jar="path for jar">
      <arg value="${arg0}"/>
      <arg value="${arg1}"/>
   </java>
</target>

You can invoke either from the command line like this:

ant -Darg0=Hello -Darg1=World run

Make sure to use the -Darg syntax; if you ran this:

ant run arg0 arg1

then ant would try to run targets arg0 and arg1.

LaTeX: remove blank page after a \part or \chapter

Although I guess you do not need an answer any longer, I am giving the solution for those who will come to see this post.

Derived from book.cls

\def\@endpart{\vfil\newpage
              \if@twoside
                \null
                \thispagestyle{empty}%
                \newpage
              \fi
              \if@tempswa
                \twocolumn
              \fi}

It is "\newpage" at the first line of this fragment that adds a redundant blank page after the part header page. So you must redefine the command \@endpart. Add the following snippet to the beggining of your tex file.

\makeatletter
\renewcommand\@endpart{\vfil
              \if@twoside
                \null
                \thispagestyle{empty}%
                \newpage
              \fi
              \if@tempswa
                \twocolumn
              \fi}
\makeatother

How to check if a subclass is an instance of a class at runtime?

Class.isAssignableFrom() - works for interfaces as well. If you don't want that, you'll have to call getSuperclass() and test until you reach Object.

How to get first and last element in an array in java?

Check this

double[] myarray = ...;
System.out.println(myarray[myarray.length-1]); //last
System.out.println(myarray[0]); //first

Check if value is in select list with JQuery

_x000D_
_x000D_
if(!$('#select-box').find("option:contains('" + thevalue  + "')").length){_x000D_
//do stuff_x000D_
}
_x000D_
_x000D_
_x000D_

Asynchronous Requests with Python requests

I have been using python requests for async calls against github's gist API for some time.

For an example, see the code here:

https://github.com/davidthewatson/flasgist/blob/master/views.py#L60-72

This style of python may not be the clearest example, but I can assure you that the code works. Let me know if this is confusing to you and I will document it.

How can I convert a zero-terminated byte array to string?

For example,

package main

import "fmt"

func CToGoString(c []byte) string {
    n := -1
    for i, b := range c {
        if b == 0 {
            break
        }
        n = i
    }
    return string(c[:n+1])
}

func main() {
    c := [100]byte{'a', 'b', 'c'}
    fmt.Println("C: ", len(c), c[:4])
    g := CToGoString(c[:])
    fmt.Println("Go:", len(g), g)
}

Output:

C:  100 [97 98 99 0]
Go: 3 abc

Select first and last row from grouped data

Just for completeness: You can pass slice a vector of indices:

df %>% arrange(stopSequence) %>% group_by(id) %>% slice(c(1,n()))

which gives

  id stopId stopSequence
1  1      a            1
2  1      c            3
3  2      b            1
4  2      c            4
5  3      b            1
6  3      a            3

Is it possible to ignore one single specific line with Pylint?

Checkout the files in https://github.com/PyCQA/pylint/tree/master/pylint/checkers. I haven't found a better way to obtain the error name from a message than either Ctrl + F-ing those files or using the GitHub search feature:

If the message is "No name ... in module ...", use the search:

No name %r in module %r repo:PyCQA/pylint/tree/master path:/pylint/checkers

Or, to get fewer results:

"No name %r in module %r" repo:PyCQA/pylint/tree/master path:/pylint/checkers

GitHub will show you:

"E0611": (
    "No name %r in module %r",
    "no-name-in-module",
    "Used when a name cannot be found in a module.",

You can then do:

from collections import Sequence # pylint: disable=no-name-in-module

Random numbers with Math.random() in Java

The first one generates numbers in the wrong range, while the second one is correct.

To show that the first one is incorrect, let's say min is 10 and max is 20. In other words, the result is expected to be greater than or equal to ten, and strictly less than twenty. If Math.random() returns 0.75, the result of the first formula is 25, which is outside the range.

can't multiply sequence by non-int of type 'float'

Because growthRates is a sequence (you're even iterating it!) and you multiply it by (1 + 0.01), which is obviously a float (1.01). I guess you mean for growthRate in growthRates: ... * growthrate?

Rounding Bigdecimal values with 2 Decimal Places

You can call setScale(newScale, roundingMode) method three times with changing the newScale value from 4 to 3 to 2 like

First case

    BigDecimal a = new BigDecimal("10.12345");

    a = a.setScale(4, BigDecimal.ROUND_HALF_UP); 
    System.out.println("" + a); //10.1235
    a = a.setScale(3, BigDecimal.ROUND_HALF_UP); 
    System.out.println("" + a); //10.124
    a = a.setScale(2, BigDecimal.ROUND_HALF_UP);
    System.out.println("" + a); //10.12

Second case

    BigDecimal a = new BigDecimal("10.12556");

    a = a.setScale(4, BigDecimal.ROUND_HALF_UP); 
    System.out.println("" + a); //10.1256
    a = a.setScale(3, BigDecimal.ROUND_HALF_UP); 
    System.out.println("" + a); //10.126
    a = a.setScale(2, BigDecimal.ROUND_HALF_UP);
    System.out.println("" + a); //10.13

Stop node.js program from command line

Ctrl+Z suspends it, which means it can still be running.

Ctrl+C will actually kill it.

you can also kill it manually like this:

ps aux | grep node

Find the process ID (second from the left):

kill -9 PROCESS_ID

This may also work

killall node

make script execution to unlimited

As @Peter Cullen answer mention, your script will meet browser timeout first. So its good idea to provide some log output, then flush(), but connection have buffer and you'll not see anything unless much output provided. Here are code snippet what helps provide reliable log:

set_time_limit(0);
...
print "log message";
print "<!--"; print str_repeat (' ', 4000); print "-->"; flush();
print "log message";
print "<!--"; print str_repeat (' ', 4000); print "-->"; flush();

How to add an item to an ArrayList in Kotlin?

If you have a MUTABLE collection:

val list = mutableListOf(1, 2, 3)
list += 4

If you have an IMMUTABLE collection:

var list = listOf(1, 2, 3)
list += 4

note that I use val for the mutable list to emphasize that the object is always the same, but its content changes.

In case of the immutable list, you have to make it var. A new object is created by the += operator with the additional value.

What's a good way to extend Error in JavaScript?

To avoid the boilerplate for every different type of error, I combined the wisdom of some of the solutions into a createErrorType function:

function createErrorType(name, init) {
  function E(message) {
    if (!Error.captureStackTrace)
      this.stack = (new Error()).stack;
    else
      Error.captureStackTrace(this, this.constructor);
    this.message = message;
    init && init.apply(this, arguments);
  }
  E.prototype = new Error();
  E.prototype.name = name;
  E.prototype.constructor = E;
  return E;
}

Then you can define new error types easily as follows:

var NameError = createErrorType('NameError', function (name, invalidChar) {
  this.message = 'The name ' + name + ' may not contain ' + invalidChar;
});

var UnboundError = createErrorType('UnboundError', function (variableName) {
  this.message = 'Variable ' + variableName + ' is not bound';
});

How to get height of entire document with JavaScript?

This is a really old question, and thus, has many outdated answers. As of 2020 all major browsers have adhered to the standard.

Answer for 2020:

document.body.scrollHeight

Edit: the above doesn't take margins on the <body> tag into account. If your body has margins, use:

document.documentElement.scrollHeight

How to read if a checkbox is checked in PHP?

You can do it with the short if:

$check_value = isset($_POST['my_checkbox_name']) ? 1 : 0;

or with the new PHP7 Null coalescing operator

$check_value = $_POST['my_checkbox_name'] ?? 0;

Extract source code from .jar file

Do the following on your linux box where java works (if u like the terminal way of doing things)

cd ~
mkdir decompiled_code && cd decompiled_code
wget https://bitbucket.org/mstrobel/procyon/downloads/procyon-decompiler-0.5.36.jar
java -jar procyon-decompiler-0.5.36.jar /Path/to/your/jar -o .

NOTE : as @Richard commented "this may be illegal depending on whether you own the copyright to the jar, the country you live in and your purpose for doing it."

Regular cast vs. static_cast vs. dynamic_cast

FYI, I believe Bjarne Stroustrup is quoted as saying that C-style casts are to be avoided and that you should use static_cast or dynamic_cast if at all possible.

Barne Stroustrup's C++ style FAQ

Take that advice for what you will. I'm far from being a C++ guru.

Call javascript from MVC controller action

The usual/standard way in MVC is that you should put/call your all display, UI, CSS and Javascript in View, however there is no rule to it, you can call it in the Controller as well if you manage to do so (something i don't see the possibility of).

Android: Clear the back stack

Advanced, Reuseable Kotlin:

You can set the flag directly using setter method. In Kotlin or is the replacement for the Java bitwise or |.

intent.flags = FLAG_ACTIVITY_NEW_TASK or FLAG_ACTIVITY_CLEAR_TASK

If use this more than once, create an Intent extension function

fun Intent.clearStack() {
    flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}

You can then directly call this function before starting the intent

intent.clearStack()

If you need the option to add additional flags in other situations, add an optional param to the extension function.

fun Intent.clearStack(additionalFlags: Int = 0) {
    flags = additionalFlags or Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}

How to get all selected values from <select multiple=multiple>?

Actually, I found the best, most-succinct, fastest, and most-compatible way using pure JavaScript (assuming you don't need to fully support IE lte 8) is the following:

var values = Array.prototype.slice.call(document.querySelectorAll('#select-meal-type option:checked'),0).map(function(v,i,a) { 
    return v.value; 
});

UPDATE (2017-02-14):

An even more succinct way using ES6/ES2015 (for the browsers that support it):

const selected = document.querySelectorAll('#select-meal-type option:checked');
const values = Array.from(selected).map(el => el.value);

Does not contain a definition for and no extension method accepting a first argument of type could be found

placeBets(betList, stakeAmt) is an instance method not a static method. You need to create an instance of CBetfairAPI first:

MyBetfair api = new MyBetfair();
ArrayList bets = api.placeBets(betList, stakeAmt);

python: how to get information about a function?

In python: help(my_list.append) for example, will give you the docstring of the function.

>>> my_list = []
>>> help(my_list.append)

    Help on built-in function append:

    append(...)
        L.append(object) -- append object to end

Difference between Mutable objects and Immutable objects

They are not different from the point of view of JVM. Immutable objects don't have methods that can change the instance variables. And the instance variables are private; therefore you can't change it after you create it. A famous example would be String. You don't have methods like setString, or setCharAt. And s1 = s1 + "w" will create a new string, with the original one abandoned. That's my understanding.

Globally catch exceptions in a WPF application?

AppDomain.UnhandledException Event

This event provides notification of uncaught exceptions. It allows the application to log information about the exception before the system default handler reports the exception to the user and terminates the application.

   public App()
   {
      AppDomain currentDomain = AppDomain.CurrentDomain;
      currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);    
   }

   static void MyHandler(object sender, UnhandledExceptionEventArgs args) 
   {
      Exception e = (Exception) args.ExceptionObject;
      Console.WriteLine("MyHandler caught : " + e.Message);
      Console.WriteLine("Runtime terminating: {0}", args.IsTerminating);
   }

If the UnhandledException event is handled in the default application domain, it is raised there for any unhandled exception in any thread, no matter what application domain the thread started in. If the thread started in an application domain that has an event handler for UnhandledException, the event is raised in that application domain. If that application domain is not the default application domain, and there is also an event handler in the default application domain, the event is raised in both application domains.

For example, suppose a thread starts in application domain "AD1", calls a method in application domain "AD2", and from there calls a method in application domain "AD3", where it throws an exception. The first application domain in which the UnhandledException event can be raised is "AD1". If that application domain is not the default application domain, the event can also be raised in the default application domain.

Which version of CodeIgniter am I currently using?

You should try :

<?php
echo CI_VERSION;
?>

Or check the file system/core/CodeIgniter.php

How can I check if a program exists from a Bash script?

If you guys/gals can't get the things in answers here to work and are pulling hair out of your back, try to run the same command using bash -c. Just look at this somnambular delirium. This is what really happening when you run $(sub-command):

First. It can give you completely different output.

$ command -v ls
alias ls='ls --color=auto'
$ bash -c "command -v ls"
/bin/ls

Second. It can give you no output at all.

$ command -v nvm
nvm
$ bash -c "command -v nvm"
$ bash -c "nvm --help"
bash: nvm: command not found

How to get error message when ifstream open fails

Following on @Arne Mertz's answer, as of C++11 std::ios_base::failure inherits from system_error (see http://www.cplusplus.com/reference/ios/ios_base/failure/), which contains both the error code and message that strerror(errno) would return.

std::ifstream f;

// Set exceptions to be thrown on failure
f.exceptions(std::ifstream::failbit | std::ifstream::badbit);

try {
    f.open(fileName);
} catch (std::system_error& e) {
    std::cerr << e.code().message() << std::endl;
}

This prints No such file or directory. if fileName doesn't exist.

What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?

I have tried to make note about these and have collected and written examples from a java perspective.

HTTP for Java Developers

Reverse Ajax - Old style

Async Handling on server side

Reverse Ajax - New style

Server Sent Events

Putting it here for any java developer who is looking into the same subject.

Java random numbers using a seed

You shouldn't be creating a new Random in method scope. Make it a class member:

public class Foo {
   private Random random 

   public Foo() {
       this(System.currentTimeMillis());
   }

   public Foo(long seed) {
       this.random = new Random(seed);
   }

   public synchronized double getNext() {
        return generator.nextDouble();
   }
}

This is only an example. I don't think wrapping Random this way adds any value. Put it in a class of yours that is using it.

Adding whitespace in Java

Use the StringUtils class, it also includes null check

StringUtils.leftPad(String str, int size)
StringUtils.rightPad(String str, int size)

json.dumps vs flask.jsonify

The jsonify() function in flask returns a flask.Response() object that already has the appropriate content-type header 'application/json' for use with json responses. Whereas, the json.dumps() method will just return an encoded string, which would require manually adding the MIME type header.

See more about the jsonify() function here for full reference.

Edit: Also, I've noticed that jsonify() handles kwargs or dictionaries, while json.dumps() additionally supports lists and others.

How to provide a file download from a JSF backing bean?

Introduction

You can get everything through ExternalContext. In JSF 1.x, you can get the raw HttpServletResponse object by ExternalContext#getResponse(). In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream() without the need to grab the HttpServletResponse from under the JSF hoods.

On the response, you should set the Content-Type header so that the client knows which application to associate with the provided file. And, you should set the Content-Length header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition header to attachment if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.

Most important part is to call FacesContext#responseComplete() to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException with a message like getoutputstream() has already been called for this response when the JSF implementation calls getWriter() to render HTML.

Turn off ajax / don't use remote command!

You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink> and <h:commandButton>. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.

In case you're using e.g. PrimeFaces <p:commandXxx>, then you need to make sure that you explicitly turn off ajax via ajax="false" attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" /> in the command component.

Generic JSF 2.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();

    ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
    ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = ec.getResponseOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Generic JSF 1.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

    response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
    response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = response.getOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Common static file example

In case you need to stream a static file from the local disk file system, substitute the code as below:

File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();

// ...

Files.copy(file.toPath(), output);

Common dynamic file example

In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output there where the API being used expects an OutputStream.

E.g. iText PDF:

String fileName = "dynamic.pdf";
String contentType = "application/pdf";

// ...

Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();

E.g. Apache POI HSSF:

String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";

// ...

HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();

Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.

Utility method

If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile() methods taking either a File, or an InputStream, or a byte[], and specifying whether the file should be downloaded as an attachment (true) or inline (false).

public void download() throws IOException {
    Faces.sendFile(file, true);
}

Yes, this code is complete as-is. You don't need to invoke responseComplete() and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.

Remove Sub String by using Python

>>> import re
>>> st = " i think mabe 124 + <font color=\"black\"><font face=\"Times New Roman\">but I don't have a big experience it just how I see it in my eyes <font color=\"green\"><font face=\"Arial\">fun stuff"
>>> re.sub("<.*?>","",st)
" i think mabe 124 + but I don't have a big experience it just how I see it in my eyes fun stuff"
>>> 

git push to specific branch

If your Local branch and remote branch is the same name then you can just do it:

git push origin branchName

When your local and remote branch name is different then you can just do it:

git push origin localBranchName:remoteBranchName

How do I change the value of a global variable inside of a function

var a = 10;

myFunction(a);

function myFunction(a){
   window['a'] = 20; // or window.a
}

alert("Value of 'a' outside the function " + a); //outputs 20

With window['variableName'] or window.variableName you can modify the value of a global variable inside a function.

ArrayIndexOutOfBoundsException when using the ArrayList's iterator

While I agree that the accepted answer is usually the best solution and definitely easier to use, I noticed no one displayed the proper usage of the iterator. So here is a quick example:

Iterator<Object> it = arrayList.iterator();
while(it.hasNext())
{
    Object obj = it.next();
    //Do something with obj
}

How to access model hasMany Relation with where condition?

//lower for v4 some version

public function videos() {
    $instance =$this->hasMany('Video');
    $instance->getQuery()->where('available','=', 1);
    return $instance
}

//v5

public function videos() {
    return $this->hasMany('Video')->where('available','=', 1);
}

Launching an application (.EXE) from C#?

System.Diagnostics.Process.Start( @"C:\Windows\System32\Notepad.exe" );

get original element from ng-click

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

How to print binary tree diagram?

Adapted from Vasya Novikov's answer to make it more binary, and use a StringBuilder for efficiency (concatenating String objects together in Java is generally inefficient).

public StringBuilder toString(StringBuilder prefix, boolean isTail, StringBuilder sb) {
    if(right!=null) {
        right.toString(new StringBuilder().append(prefix).append(isTail ? "¦   " : "    "), false, sb);
    }
    sb.append(prefix).append(isTail ? "+-- " : "+-- ").append(value.toString()).append("\n");
    if(left!=null) {
        left.toString(new StringBuilder().append(prefix).append(isTail ? "    " : "¦   "), true, sb);
    }
    return sb;
}

@Override
public String toString() {
    return this.toString(new StringBuilder(), true, new StringBuilder()).toString();
}

Output:

¦       +-- 7
¦   +-- 6
¦   ¦   +-- 5
+-- 4
    ¦   +-- 3
    +-- 2
        +-- 1
            +-- 0

How to subtract hours from a date in Oracle so it affects the day also

Try this:

SELECT to_char(sysdate - (2 / 24), 'MM-DD-YYYY HH24') FROM DUAL

To test it using a new date instance:

SELECT to_char(TO_DATE('11/06/2015 00:00','dd/mm/yyyy HH24:MI') - (2 / 24), 'MM-DD-YYYY HH24:MI') FROM DUAL

Output is: 06-10-2015 22:00, which is the previous day.

Retrieve only the queried element in an object array in MongoDB collection

Likewise you can find for the multiple

db.getCollection('localData').aggregate([
    // Get just the docs that contain a shapes element where color is 'red'
  {$match: {'shapes.color': {$in : ['red','yellow'] } }},
  {$project: {
     shapes: {$filter: {
        input: '$shapes',
        as: 'shape',
        cond: {$in: ['$$shape.color', ['red', 'yellow']]}
     }}
  }}
])

open link of google play store in mobile version android

You'll want to use the specified market protocol:

final String appPackageName = "com.example"; // Can also use getPackageName(), as below
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));

Keep in mind, this will crash on any device that does not have the Market installed (the emulator, for example). Hence, I would suggest something like:

final String appPackageName = getPackageName(); // getPackageName() from Context or Activity object
try {
    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
} catch (android.content.ActivityNotFoundException anfe) {
    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + appPackageName)));
}

While using getPackageName() from Context or subclass thereof for consistency (thanks @cprcrack!). You can find more on Market Intents here: link.

"FATAL: Module not found error" using modprobe

Insert this in your Makefile

 $(MAKE) -C $(KDIR) M=$(PWD) modules_install                      

 it will install the module in the directory /lib/modules/<var>/extra/
 After make , insert module with modprobe module_name (without .ko extension)

OR

After your normal make, you copy module module_name.ko into   directory  /lib/modules/<var>/extra/

then do modprobe module_name (without .ko extension)

How to delete a stash created with git stash create?

From git doc: http://git-scm.com/docs/git-stash

drop [-q|--quiet] []

Remove a single stashed state from the stash list. When no is given, it removes the latest one. i.e. stash@{0}, otherwise must be a valid stash log reference of the form stash@{}.

example:

git stash drop stash@{5}

This would delete the stash entry 5. To see all the list of stashes:

git stash list

How can I take a screenshot with Selenium WebDriver?

Java

Seems to be missing here - taking screenshot of a specific element in Java:

public void takeScreenshotElement(WebElement element) throws IOException {
    WrapsDriver wrapsDriver = (WrapsDriver) element;
    File screenshot = ((TakesScreenshot) wrapsDriver.getWrappedDriver()).getScreenshotAs(OutputType.FILE);
    Rectangle rectangle = new Rectangle(element.getSize().width, element.getSize().height);
    Point location = element.getLocation();
    BufferedImage bufferedImage = ImageIO.read(screenshot);
    BufferedImage destImage = bufferedImage.getSubimage(location.x, location.y, rectangle.width, rectangle.height);
    ImageIO.write(destImage, "png", screenshot);
    File file = new File("//path//to");
    FileUtils.copyFile(screenshot, file);
}

How to parse a query string into a NameValueCollection in .NET

HttpUtility.ParseQueryString will work as long as you are in a web app or don't mind including a dependency on System.Web. Another way to do this is:

NameValueCollection queryParameters = new NameValueCollection();
string[] querySegments = queryString.Split('&');
foreach(string segment in querySegments)
{
   string[] parts = segment.Split('=');
   if (parts.Length > 0)
   {
      string key = parts[0].Trim(new char[] { '?', ' ' });
      string val = parts[1].Trim();

      queryParameters.Add(key, val);
   }
}

get the latest fragment in backstack

Or you may just add a tag when adding fragments corresponding to their content and use simple static String field (also you may save it in activity instance bundle in onSaveInstanceState(Bundle) method) to hold last added fragment tag and get this fragment byTag() at any time you need...

Expected block end YAML error

This error also occurs if you use four-space instead of two-space indentation.

e.g., the following would throw the error:

fields:
    - metadata: {}
        name: colName
        nullable: true

whereas changing indentation to two-spaces would fix it:

fields:
  - metadata: {}
    name: colName
    nullable: true

Different color for each bar in a bar chart; ChartJS

After looking into the Chart.Bar.js file I've managed to find the solution. I've used this function to generate a random color:

function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

I've added it to the end of the file and i called this function right inside the "fillColor:" under

helpers.each(dataset.data,function(dataPoint,index){
                    //Add a new point for each piece of data, passing any required data to draw.

so now it looks like this:

helpers.each(dataset.data,function(dataPoint,index){
                    //Add a new point for each piece of data, passing any required data to draw.

                    datasetObject.bars.push(new this.BarClass({
                        value : dataPoint,
                        label : data.labels[index],
                        datasetLabel: dataset.label,
                        strokeColor : dataset.strokeColor,
                        fillColor : getRandomColor(),
                        highlightFill : dataset.highlightFill || dataset.fillColor,
                        highlightStroke : dataset.highlightStroke || dataset.strokeColor
                    }));
                },this);

and it works I get different color for each bar.

Unicode characters in URLs

Use percent encoding. Modern browsers will take care of display & paste issues and make it human-readable. E. g. http://ko.wikipedia.org/wiki/????:??

Edit: when you copy such an url in Firefox, the clipboard will hold the percent-encoded form (which is usually a good thing), but if you copy only a part of it, it will remain unencoded.

Usage of unicode() and encode() functions in Python

Make sure you've set your locale settings right before running the script from the shell, e.g.

$ locale -a | grep "^en_.\+UTF-8"
en_GB.UTF-8
en_US.UTF-8
$ export LC_ALL=en_GB.UTF-8
$ export LANG=en_GB.UTF-8

Docs: man locale, man setlocale.

MySQL integer field is returned as string in PHP

Use the mysqlnd (native driver) for php.

If you're on Ubuntu:

sudo apt-get install php5-mysqlnd
sudo service apache2 restart

If you're on Centos:

sudo yum install php-mysqlnd
sudo service httpd restart

The native driver returns integer types appropriately.

Edit:

As @Jeroen has pointed out, this method will only work out-of-the-box for PDO.
As @LarsMoelleken has pointed out, this method will work with mysqli if you also set the MYSQLI_OPT_INT_AND_FLOAT_NATIVE option to true.

Example:

$mysqli = mysqli_init();
$mysqli->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, TRUE);

Check div is hidden using jquery

Try:

if(!$('#car2').is(':visible'))
{  
    alert('car 2 is hidden');       
}

Why does intellisense and code suggestion stop working when Visual Studio is open?

MS Visual Studio 2017 Pro, C++ projects

Too many good answers for this question. This worked for me:


IntelliSense works only when i load the project by double clicking the solution file.

I tried all the above answers with unfortunately no luck. Dll's, setting, dependencies...you name it. It sucks that you have to go through all that for an autocomplete....miss my Vim config....

How do I generate a random number between two variables that I have stored?

rand() % ((highestNumber - lowestNumber) + 1) + lowestNumber

how to get GET and POST variables with JQuery?

If your $_GET is multidimensional, this might be what you're wanting:

var $_GET = {};
document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
    function decode(s) {
            return decodeURIComponent(s.split("+").join(" "));
    }

    //handling for multidimensional arrays
    if(decode(arguments[1]).indexOf("[]") > 0){
        var newName = decode(arguments[1]).substring(0, decode(arguments[1]).length - 2);
        if(typeof $_GET[newName] == 'undefined'){
            $_GET[newName] = new Array();
        }
        $_GET[newName].push(decode(arguments[2]));
    }else{
        $_GET[decode(arguments[1])] = decode(arguments[2]);
    }
});

Abstract Class:-Real Time Example

Here, Something about abstract class...

  1. Abstract class is an incomplete class so we can't instantiate it.
  2. If methods are abstract, class must be abstract.
  3. In abstract class, we use abstract and concrete method both.
  4. It is illegal to define a class abstract and final both.

Real time example--

If you want to make a new car(WagonX) in which all the another car's properties are included like color,size, engine etc.and you want to add some another features like model,baseEngine in your car.Then simply you create a abstract class WagonX where you use all the predefined functionality as abstract and another functionalities are concrete, which is is defined by you.
Another sub class which extend the abstract class WagonX,By default it also access the abstract methods which is instantiated in abstract class.SubClasses also access the concrete methods by creating the subclass's object.
For reusability the code, the developers use abstract class mostly.

abstract class WagonX
{
   public abstract void model();
   public abstract void color();
   public static void baseEngine()
    {
     // your logic here
    }
   public static void size()
   {
   // logic here
   }
}
class Car extends WagonX
{
public void model()
{
// logic here
}
public void color()
{
// logic here
}
}

Using jQuery to center a DIV on the screen

I like adding functions to jQuery so this function would help:

jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) + 
                                                $(window).scrollTop()) + "px");
    this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) + 
                                                $(window).scrollLeft()) + "px");
    return this;
}

Now we can just write:

$(element).center();

Demo: Fiddle (with added parameter)

How to make a great R reproducible example

Here are some of my suggestions:

  • Try to use default R datasets
  • If you have your own dataset, include them with dput, so others can help you more easily
  • Do not use install.package() unless it is really necessary, people will understand if you just use require or library
  • Try to be concise,

    • Have some dataset
    • Try to describe the output you need as simply as possible
    • Do it yourself before you ask the question
  • It is easy to upload an image, so upload plots if you have
  • Also include any errors you may have

All these are part of a reproducible example.

Center a H1 tag inside a DIV

You can use display: table-cell in order to render the div as a table cell and then use vertical-align like you would do in a normal table cell.

#AlertDiv {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

You can try it here: http://jsfiddle.net/KaXY5/424/

Controller 'ngModel', required by directive '...', can't be found

One possible solution to this issue is ng-model attribute is required to use that directive.

Hence adding in the 'ng-model' attribute can resolve the issue.

<input submit-required="true" ng-model="user.Name"></input>

Error: Could not create the Java Virtual Machine Mac OSX Mavericks

So try uninstalling all other versions other than the one you need, then set the JAVA_HOMEpath variable for that JDK remaining, and you're done.

That's worked for me, I have two JDK (version 8 & 11) installed on my local mac, that causes the issue, for uninstalling, I followed these two steps:

  • cd /Library/Java/JavaVirtualMachines
  • rm -rf openjdk-11.0.1.jdk

C++ IDE for Macs

Xcode is free and good, which is lucky because it's pretty much the only option on the Mac.

Spool Command: Do not output SQL statement to file

Exec the query in TOAD or SQL DEVELOPER

---select /*csv*/ username, user_id, created from all_users;

Save in .SQL format in "C" drive

--- x.sql

execute command

---- set serveroutput on
     spool y.csv
     @c:\x.sql
     spool off;

What is the 'instanceof' operator used for in Java?

public class Animal{ float age; }

public class Lion extends Animal { int claws;}

public class Jungle {
    public static void main(String args[]) {

        Animal animal = new Animal(); 
        Animal animal2 = new Lion(); 
        Lion lion = new Lion(); 
        Animal animal3 = new Animal(); 
        Lion lion2 = new Animal();   //won't compile (can't reference super class object with sub class reference variable) 

        if(animal instanceof Lion)  //false

        if(animal2 instanceof Lion)  //true

        if(lion insanceof Lion) //true

        if(animal3 instanceof Animal) //true 

    }
}

How store a range from excel into a Range variable?

What is currentWorksheet? It works if you use the built-in ActiveSheet.

dataStartRow=1
dataStartCol=1
dataEndRow=4
dataEndCol=4
Set currentWorksheet=ActiveSheet
dataTable = currentWorksheet.Range(currentWorksheet.Cells(dataStartRow, dataStartCol), currentWorksheet.Cells(dataEndRow, dataEndCol))

Numpy: find index of the elements within range

a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
np.argwhere((a>=6) & (a<=10))

Convert NSArray to NSString in Objective-C

NSString * str = [componentsJoinedByString:@""];

and you have dic or multiple array then used bellow

NSString * result = [[array valueForKey:@"description"] componentsJoinedByString:@""];   

Calendar date to yyyy-MM-dd format in java

public static String ThisWeekStartDate(WebDriver driver) {
        Calendar c = Calendar.getInstance();
        //ensure the method works within current month
        c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        System.out.println("Before Start Date " + c.getTime());
        Date date = c.getTime();

          SimpleDateFormat dfDate = new SimpleDateFormat("dd MMM yyyy hh.mm a");

          String CurrentDate = dfDate.format(date);
          System.out.println("Start Date " + CurrentDate);
          return CurrentDate;

    }
    public static String ThisWeekEndDate(WebDriver driver) {

        Calendar c = Calendar.getInstance();
        //ensure the method works within current month
        c.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
        System.out.println("Before End Date " + c.getTime());
        Date date = c.getTime();

          SimpleDateFormat dfDate = new SimpleDateFormat("dd MMM yyyy hh.mm a");

          String CurrentDate = dfDate.format(date);
          System.out.println("End Date " + CurrentDate);
          return CurrentDate;
    }

How do you develop Java Servlets using Eclipse?

I use Eclipse Java EE edition

Create a "Dynamic Web Project"

Install a local server in the server view, for the version of Tomcat I'm using. Then debug, and run on that server for testing.

When I deploy I export the project to a war file.

How can I wait for a thread to finish with .NET?

If using from .NET 4 this sample can help you:

class Program
{
    static void Main(string[] args)
    {
        Task task1 = Task.Factory.StartNew(() => doStuff());
        Task task2 = Task.Factory.StartNew(() => doStuff());
        Task task3 = Task.Factory.StartNew(() => doStuff());
        Task.WaitAll(task1, task2, task3);
        Console.WriteLine("All threads complete");
    }

    static void doStuff()
    {
        // Do stuff here
    }
}

From: Create multiple threads and wait all of them to complete

What does the error "JSX element type '...' does not have any construct or call signatures" mean?

If you are using material-ui, go to type definition of the component, which is being underlined by TypeScript. Most likely you will see something like this

export { default } from './ComponentName';

You have 2 options to resolve the error:

1.Add .default when using the component in JSX:

import ComponentName from './ComponentName'

const Component = () => <ComponentName.default />

2.Rename the component, which is being exported as "default", when importing:

import { default as ComponentName } from './ComponentName'

const Component = () => <ComponentName />

This way you don't need to specify .default every time you use the component.

Fatal error: Call to a member function fetch_assoc() on a non-object

I happen to miss spaces in my query and this error comes.

Ex: $sql= "SELECT * FROM";
$sql .= "table1";

Though the example might look simple, when coding complex queries, the probability for this error is high. I was missing space before word "table1".

Does Enter key trigger a click event?

@Component({
  selector: 'key-up3',
  template: `
    <input #box (keyup.enter)="doSomething($event)">
    <p>{{values}}</p>
  `
})
export class KeyUpComponent_v3 {
  doSomething(e) {
    alert(e);
  }
}

This works for me!

Accessing member of base class

Working example. Notes below.

class Animal {
    constructor(public name) {
    }

    move(meters) {
        alert(this.name + " moved " + meters + "m.");
    }
}

class Snake extends Animal {
    move() {
        alert(this.name + " is Slithering...");
        super.move(5);
    }
}

class Horse extends Animal {
    move() {
        alert(this.name + " is Galloping...");
        super.move(45);
    }
}

var sam = new Snake("Sammy the Python");
var tom: Animal = new Horse("Tommy the Palomino");

sam.move();
tom.move(34);
  1. You don't need to manually assign the name to a public variable. Using public name in the constructor definition does this for you.

  2. You don't need to call super(name) from the specialised classes.

  3. Using this.name works.

Notes on use of super.

This is covered in more detail in section 4.9.2 of the language specification.

The behaviour of the classes inheriting from Animal is not dissimilar to the behaviour in other languages. You need to specify the super keyword in order to avoid confusion between a specialised function and the base class function. For example, if you called move() or this.move() you would be dealing with the specialised Snake or Horse function, so using super.move() explicitly calls the base class function.

There is no confusion of properties, as they are the properties of the instance. There is no difference between super.name and this.name - there is simply this.name. Otherwise you could create a Horse that had different names depending on whether you were in the specialized class or the base class.

Safari 3rd party cookie iframe trick no longer working?

I tricked Safari with a .htaccess:

#http://www.w3.org/P3P/validator.html
<IfModule mod_headers.c>
Header set P3P "policyref=\"/w3c/p3p.xml\", CP=\"NOI DSP COR NID CUR ADM DEV OUR BUS\""
Header set Set-Cookie "test_cookie=1"
</IfModule>

And it stopped working for me too. All my apps are losing the session in Safari and are redirecting out of Facebook. As I'm in a hurry to fix those apps, I'm currently searching for a solution. I'll keep you posted.

Edit (2012-04-06): Apparently Apple "fixed" it with 5.1.4. I'm sure this is the reaction to the Google-thing: "An issue existed in the enforcement of its cookie policy. Third-party websites could set cookies if the "Block Cookies" preference in Safari was set to the default setting of "From third parties and advertisers". http://support.apple.com/kb/HT5190

How to Convert a Text File into a List in Python

Maybe:

crimefile = open(fileName, 'r')
yourResult = [line.split(',') for line in crimefile.readlines()]

How to layout multiple panels on a jFrame? (java)

The JPanel is actually only a container where you can put different elements in it (even other JPanels). So in your case I would suggest one big JPanel as some sort of main container for your window. That main panel you assign a Layout that suits your needs ( here is an introduction to the layouts).

After you set the layout to your main panel you can add the paint panel and the other JPanels you want (like those with the text in it..).

  JPanel mainPanel = new JPanel();
  mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

  JPanel paintPanel = new JPanel();
  JPanel textPanel = new JPanel();

  mainPanel.add(paintPanel);
  mainPanel.add(textPanel);

This is just an example that sorts all sub panels vertically (Y-Axis). So if you want some other stuff at the bottom of your mainPanel (maybe some icons or buttons) that should be organized with another layout (like a horizontal layout), just create again a new JPanel as a container for all the other stuff and set setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS).

As you will find out, the layouts are quite rigid and it may be difficult to find the best layout for your panels. So don't give up, read the introduction (the link above) and look at the pictures – this is how I do it :)

Or you can just use NetBeans to write your program. There you have a pretty easy visual editor (drag and drop) to create all sorts of Windows and Frames. (only understanding the code afterwards is ... tricky sometimes.)

EDIT

Since there are some many people interested in this question, I wanted to provide a complete example of how to layout a JFrame to make it look like OP wants it to.

The class is called MyFrame and extends swings JFrame

public class MyFrame extends javax.swing.JFrame{

    // these are the components we need.
    private final JSplitPane splitPane;  // split the window in top and bottom
    private final JPanel topPanel;       // container panel for the top
    private final JPanel bottomPanel;    // container panel for the bottom
    private final JScrollPane scrollPane; // makes the text scrollable
    private final JTextArea textArea;     // the text
    private final JPanel inputPanel;      // under the text a container for all the input elements
    private final JTextField textField;   // a textField for the text the user inputs
    private final JButton button;         // and a "send" button

    public MyFrame(){

        // first, lets create the containers:
        // the splitPane devides the window in two components (here: top and bottom)
        // users can then move the devider and decide how much of the top component
        // and how much of the bottom component they want to see.
        splitPane = new JSplitPane();

        topPanel = new JPanel();         // our top component
        bottomPanel = new JPanel();      // our bottom component

        // in our bottom panel we want the text area and the input components
        scrollPane = new JScrollPane();  // this scrollPane is used to make the text area scrollable
        textArea = new JTextArea();      // this text area will be put inside the scrollPane

        // the input components will be put in a separate panel
        inputPanel = new JPanel();
        textField = new JTextField();    // first the input field where the user can type his text
        button = new JButton("send");    // and a button at the right, to send the text

        // now lets define the default size of our window and its layout:
        setPreferredSize(new Dimension(400, 400));     // let's open the window with a default size of 400x400 pixels
        // the contentPane is the container that holds all our components
        getContentPane().setLayout(new GridLayout());  // the default GridLayout is like a grid with 1 column and 1 row,
        // we only add one element to the window itself
        getContentPane().add(splitPane);               // due to the GridLayout, our splitPane will now fill the whole window

        // let's configure our splitPane:
        splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);  // we want it to split the window verticaly
        splitPane.setDividerLocation(200);                    // the initial position of the divider is 200 (our window is 400 pixels high)
        splitPane.setTopComponent(topPanel);                  // at the top we want our "topPanel"
        splitPane.setBottomComponent(bottomPanel);            // and at the bottom we want our "bottomPanel"

        // our topPanel doesn't need anymore for this example. Whatever you want it to contain, you can add it here
        bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.Y_AXIS)); // BoxLayout.Y_AXIS will arrange the content vertically

        bottomPanel.add(scrollPane);                // first we add the scrollPane to the bottomPanel, so it is at the top
        scrollPane.setViewportView(textArea);       // the scrollPane should make the textArea scrollable, so we define the viewport
        bottomPanel.add(inputPanel);                // then we add the inputPanel to the bottomPanel, so it under the scrollPane / textArea

        // let's set the maximum size of the inputPanel, so it doesn't get too big when the user resizes the window
        inputPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, 75));     // we set the max height to 75 and the max width to (almost) unlimited
        inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.X_AXIS));   // X_Axis will arrange the content horizontally

        inputPanel.add(textField);        // left will be the textField
        inputPanel.add(button);           // and right the "send" button

        pack();   // calling pack() at the end, will ensure that every layout and size we just defined gets applied before the stuff becomes visible
    }

    public static void main(String args[]){
        EventQueue.invokeLater(new Runnable(){
            @Override
            public void run(){
                new MyFrame().setVisible(true);
            }
        });
    }
}

Please be aware that this is only an example and there are multiple approaches to layout a window. It all depends on your needs and if you want the content to be resizable / responsive. Another really good approach would be the GridBagLayout which can handle quite complex layouting, but which is also quite complex to learn.

How to return a complex JSON response with Node.js?

On express 3 you can use directly res.json({foo:bar})

res.json({ msgId: msg.fileName })

See the documentation

What is Python used for?

Python is a dynamic, strongly typed, object oriented, multipurpose programming language, designed to be quick (to learn, to use, and to understand), and to enforce a clean and uniform syntax.

  1. Python is dynamically typed: it means that you don't declare a type (e.g. 'integer') for a variable name, and then assign something of that type (and only that type). Instead, you have variable names, and you bind them to entities whose type stays with the entity itself. a = 5 makes the variable name a to refer to the integer 5. Later, a = "hello" makes the variable name a to refer to a string containing "hello". Static typed languages would have you declare int a and then a = 5, but assigning a = "hello" would have been a compile time error. On one hand, this makes everything more unpredictable (you don't know what a refers to). On the other hand, it makes very easy to achieve some results a static typed languages makes very difficult.
  2. Python is strongly typed. It means that if a = "5" (the string whose value is '5') will remain a string, and never coerced to a number if the context requires so. Every type conversion in python must be done explicitly. This is different from, for example, Perl or Javascript, where you have weak typing, and can write things like "hello" + 5 to get "hello5".
  3. Python is object oriented, with class-based inheritance. Everything is an object (including classes, functions, modules, etc), in the sense that they can be passed around as arguments, have methods and attributes, and so on.
  4. Python is multipurpose: it is not specialised to a specific target of users (like R for statistics, or PHP for web programming). It is extended through modules and libraries, that hook very easily into the C programming language.
  5. Python enforces correct indentation of the code by making the indentation part of the syntax. There are no control braces in Python. Blocks of code are identified by the level of indentation. Although a big turn off for many programmers not used to this, it is precious as it gives a very uniform style and results in code that is visually pleasant to read.
  6. The code is compiled into byte code and then executed in a virtual machine. This means that precompiled code is portable between platforms.

Python can be used for any programming task, from GUI programming to web programming with everything else in between. It's quite efficient, as much of its activity is done at the C level. Python is just a layer on top of C. There are libraries for everything you can think of: game programming and openGL, GUI interfaces, web frameworks, semantic web, scientific computing...

What is pipe() function in Angular

Don't get confused with the concepts of Angular and RxJS

We have pipes concept in Angular and pipe() function in RxJS.

1) Pipes in Angular: A pipe takes in data as input and transforms it to the desired output
https://angular.io/guide/pipes

2) pipe() function in RxJS: You can use pipes to link operators together. Pipes let you combine multiple functions into a single function.

The pipe() function takes as its arguments the functions you want to combine, and returns a new function that, when executed, runs the composed functions in sequence.
https://angular.io/guide/rx-library (search for pipes in this URL, you can find the same)

So according to your question, you are referring pipe() function in RxJS

chrome undo the action of "prevent this page from creating additional dialogs"

No. But you should really use console.log() instead of alert() for debugging.

In Chrome it even has the advantage of being able to print out entire objects (not just toString()).

How to set time zone of a java.util.Date?

java.util.Calendar is the usual way to handle time zones using just JDK classes. Apache Commons has some further alternatives/utilities that may be helpful. Edit Spong's note reminded me that I've heard really good things about Joda-Time (though I haven't used it myself).

How to disable button in React.js

very simple solution for this is by using useRef hook

const buttonRef = useRef();

const disableButton = () =>{
  buttonRef.current.disabled = true; // this disables the button
 }

<button
className="btn btn-primary mt-2"
ref={buttonRef}
onClick={disableButton}
>
    Add
</button>

Similarly you can enable the button by using buttonRef.current.disabled = false

How can I strip HTML tags from a string in ASP.NET?

For the second parameter,i.e. keep some tags, you may need some code like this by using HTMLagilityPack:

public string StripTags(HtmlNode documentNode, IList keepTags)
{
    var result = new StringBuilder();
        foreach (var childNode in documentNode.ChildNodes)
        {
            if (childNode.Name.ToLower() == "#text")
            {
                result.Append(childNode.InnerText);
            }
            else
            {
                if (!keepTags.Contains(childNode.Name.ToLower()))
                {
                    result.Append(StripTags(childNode, keepTags));
                }
                else
                {
                    result.Append(childNode.OuterHtml.Replace(childNode.InnerHtml, StripTags(childNode, keepTags)));
                }
            }
        }
        return result.ToString();
    }

More explanation on this page: http://nalgorithm.com/2015/11/20/strip-html-tags-of-an-html-in-c-strip_html-php-equivalent/

How should I have explained the difference between an Interface and an Abstract class?

Many junior developers make the mistake of thinking of interfaces, abstract and concrete classes as slight variations of the same thing, and choose one of them purely on technical grounds: Do I need multiple inheritance? Do I need some place to put common methods? Do I need to bother with something other than just a concrete class? This is wrong, and hidden in these questions is the main problem: "I". When you write code for yourself, by yourself, you rarely think of other present or future developers working on or with your code.

Interfaces and abstract classes, although apparently similar from a technical point of view, have completely different meanings and purposes.

Summary

  1. An interface defines a contract that some implementation will fulfill for you.

  2. An abstract class provides a default behavior that your implementation can reuse.

These two points above is what I'm looking for when interviewing, and is a compact enough summary. Read on for more details.

Alternative summary

  1. An interface is for defining public APIs
  2. An abstract class is for internal use, and for defining SPIs

By example

To put it differently: A concrete class does the actual work, in a very specific way. For example, an ArrayList uses a contiguous area of memory to store a list of objects in a compact manner which offers fast random access, iteration, and in-place changes, but is terrible at insertions, deletions, and occasionally even additions; meanwhile, a LinkedList uses double-linked nodes to store a list of objects, which instead offers fast iteration, in-place changes, and insertion/deletion/addition, but is terrible at random access. These two types of lists are optimized for different use cases, and it matters a lot how you're going to use them. When you're trying to squeeze performance out of a list that you're heavily interacting with, and when picking the type of list is up to you, you should carefully pick which one you're instantiating.

On the other hand, high level users of a list don't really care how it is actually implemented, and they should be insulated from these details. Let's imagine that Java didn't expose the List interface, but only had a concrete List class that's actually what LinkedList is right now. All Java developers would have tailored their code to fit the implementation details: avoid random access, add a cache to speed up access, or just reimplement ArrayList on their own, although it would be incompatible with all the other code that actually works with List only. That would be terrible... But now imagine that the Java masters actually realize that a linked list is terrible for most actual use cases, and decided to switch over to an array list for their only List class available. This would affect the performance of every Java program in the world, and people wouldn't be happy about it. And the main culprit is that implementation details were available, and the developers assumed that those details are a permanent contract that they can rely on. This is why it's important to hide implementation details, and only define an abstract contract. This is the purpose of an interface: define what kind of input a method accepts, and what kind of output is expected, without exposing all the guts that would tempt programmers to tweak their code to fit the internal details that might change with any future update.

An abstract class is in the middle between interfaces and concrete classes. It is supposed to help implementations share common or boring code. For example, AbstractCollection provides basic implementations for isEmpty based on size is 0, contains as iterate and compare, addAll as repeated add, and so on. This lets implementations focus on the crucial parts that differentiate between them: how to actually store and retrieve data.

Another perspective: APIs versus SPIs

Interfaces are low-cohesion gateways between different parts of code. They allow libraries to exist and evolve without breaking every library user when something changes internally. It's called Application Programming Interface, not Application Programming Classes. On a smaller scale, they also allow multiple developers to collaborate successfully on large scale projects, by separating different modules through well documented interfaces.

Abstract classes are high-cohesion helpers to be used when implementing an interface, assuming some level of implementation details. Alternatively, abstract classes are used for defining SPIs, Service Provider Interfaces.

The difference between an API and an SPI is subtle, but important: for an API, the focus is on who uses it, and for an SPI the focus is on who implements it.

Adding methods to an API is easy, all existing users of the API will still compile. Adding methods to an SPI is hard, since every service provider (concrete implementation) will have to implement the new methods. If interfaces are used to define an SPI, a provider will have to release a new version whenever the SPI contract changes. If abstract classes are used instead, new methods could either be defined in terms of existing abstract methods, or as empty throw not implemented exception stubs, which will at least allow an older version of a service implementation to still compile and run.

A note on Java 8 and default methods

Although Java 8 introduced default methods for interfaces, which makes the line between interfaces and abstract classes even blurrier, this wasn't so that implementations can reuse code, but to make it easier to change interfaces that serve both as an API and as an SPI (or are wrongly used for defining SPIs instead of abstract classes).

"Book knowledge"

The technical details provided in the OP's answer are considered "book knowledge" because this is usually the approach used in school and in most technology books about a language: what a thing is, not how to use it in practice, especially in large scale applications.

Here's an analogy: supposed the question was:

What is better to rent for prom night, a car or a hotel room?

The technical answer sounds like:

Well, in a car you can do it sooner, but in a hotel room you can do it more comfortably. On the other hand, the hotel room is in only one place, while in the car you can do it in more places, like, let's say you can go to the vista point for a nice view, or in a drive-in theater, or many other places, or even in more than one place. Also, the hotel room has a shower.

That is all true, but completely misses the points that they are two completely different things, and both can be used at the same time for different purposes, and the "doing it" aspect is not the most important thing about either of the two options. The answer lacks perspective, it shows an immature way of thinking, while correctly presenting true "facts".

Getting the inputstream from a classpath resource (XML file)

That depends on where exactly the XML file is. Is it in the sources folder (in the "default package" or the "root") or in the same folder as the class?

In for former case, you must use "/file.xml" (note the leading slash) to find the file and it doesn't matter which class you use to try to locate it.

If the XML file is next to some class, SomeClass.class.getResourceAsStream() with just the filename is the way to go.

Passing parameters in Javascript onClick event

It is probably better to create a dedicated function to create the link so you can avoid creating two anonymous functions. Thus:

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

<script>
  function getLink(id)
  {
    var link = document.createElement('a');
    link.setAttribute('href', '#');
    link.innerHTML = id;
    link.onclick = function()
    {
      onClickLink(id);
    };
    link.style.display = 'block';
    return link;
  }
  var div = document.getElementById('div');
  for (var i = 0; i < 10; i += 1)
  {
    div.appendChild(getLink(i.toString()));
  }
</script>

Although in both cases you end up with two functions, I just think it is better to wrap it in a function that is semantically easier to comprehend.

Search all of Git history for a string?

Git can search diffs with the -S option (it's called pickaxe in the docs)

git log -S password

This will find any commit that added or removed the string password. Here a few options:

  • -p: will show the diffs. If you provide a file (-p file), it will generate a patch for you.
  • -G: looks for differences whose added or removed line matches the given regexp, as opposed to -S, which "looks for differences that introduce or remove an instance of string".
  • --all: searches over all branches and tags; alternatively, use --branches[=<pattern>] or --tags[=<pattern>]

Angular2 disable button

May be below code can help:

<button [attr.disabled]="!isValid ? true : null">Submit</button>

undefined reference to `WinMain@16'

I was encountering this error while compiling my application with SDL. This was caused by SDL defining it's own main function in SDL_main.h. To prevent SDL define the main function an SDL_MAIN_HANDLED macro has to be defined before the SDL.h header is included.

Update div with jQuery ajax response html

It's also possible to use jQuery's .load()

$('#submitform').click(function() {
  $('#showresults').load('getinfo.asp #showresults', {
    txtsearch: $('#appendedInputButton').val()
  }, function() {
    // alert('Load was performed.')
    // $('#showresults').slideDown('slow')
  });
});

unlike $.get(), allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.

We could modify the example above to use only part of the document that is fetched:

$( "#result" ).load( "ajax/test.html #container" );

When this method executes, it retrieves the content of ajax/test.html, but then jQuery parses the returned document to find the element with an ID of container. This element, along with its contents, is inserted into the element with an ID of result, and the rest of the retrieved document is discarded.

Convert dictionary to bytes and back again python?

If you need to convert the dictionary to binary, you need to convert it to a string (JSON) as described in the previous answer, then you can convert it to binary.

For example:

my_dict = {'key' : [1,2,3]}

import json
def dict_to_binary(the_dict):
    str = json.dumps(the_dict)
    binary = ' '.join(format(ord(letter), 'b') for letter in str)
    return binary


def binary_to_dict(the_binary):
    jsn = ''.join(chr(int(x, 2)) for x in the_binary.split())
    d = json.loads(jsn)  
    return d

bin = dict_to_binary(my_dict)
print bin

dct = binary_to_dict(bin)
print dct

will give the output

1111011 100010 1101011 100010 111010 100000 1011011 110001 101100 100000 110010 101100 100000 110011 1011101 1111101

{u'key': [1, 2, 3]}

How to store an output of shell script to a variable in Unix?

Two simple examples to capture output the pwd command:

$ b=$(pwd)
$ echo $b
/home/user1

or

$ a=`pwd`
$ echo $a
/home/user1

The first way is preferred. Note that there can't be any spaces after the = for this to work.

Example using a short script:

#!/bin/bash

echo "hi there"

then:

$ ./so.sh
hi there
$ a=$(so.sh)
$ echo $a
hi there

In general a more flexible approach would be to return an exit value from the command and use it for further processing, though sometimes we just may want to capture the simple output from a command.

Ignore files that have already been committed to a Git repository

On my server linux server (not true on my local dev mac), directories are ignored as long as I don't add an asterisk:

www/archives/*

I don't know why but it made me loose a couple of hours, so I wanted to share...

How to execute only one test spec with angular-cli

I solved this problem for myself using grunt. I have the grunt script below. What the script does is takes the command line parameter of the specific test to run and creates a copy of test.ts and puts this specific test name in there.

To run this, first install grunt-cli using:

npm install -g grunt-cli

Put the below grunt dependencies in your package.json:

"grunt": "^1.0.1",
"grunt-contrib-clean": "^1.0.0",
"grunt-contrib-copy": "^1.0.0",
"grunt-exec": "^2.0.0",
"grunt-string-replace": "^1.3.1"

To run it save the below grunt file as Gruntfile.js in your root folder. Then from command line run it as:

grunt --target=app.component

This will run app.component.spec.ts.

Grunt file is as below:

/*
This gruntfile is used to run a specific test in watch mode. Example: To run app.component.spec.ts , the Command is: 
grunt --target=app.component
Do not specific .spec.ts. If no target is specified it will run all tests.
*/
module.exports = function(grunt) {
var target = grunt.option('target') || '';
  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    clean: ['temp.conf.js','src/temp-test.ts'],
    copy: {
      main: {
        files: [
             {expand: false, cwd: '.', src: ['karma.conf.js'], dest: 'temp.conf.js'},
             {expand: false, cwd: '.', src: ['src/test.ts'], dest: 'src/temp-test.ts'}
             ],
      }
    },
    'string-replace': {
          dist: {
            files: {
              'temp.conf.js': 'temp.conf.js',
              'src/temp-test.ts': 'src/temp-test.ts'
            },
            options: {
              replacements: [{
                pattern: /test.ts/ig,
                replacement: 'temp-test.ts'
              },
              {
                pattern: /const context =.*/ig,
                replacement: 'const context = require.context(\'./\', true, /'+target+'\\\.spec\\\.ts$/);'
              }]
            }
        }
    },
    'exec': {
        sleep: {
          //The sleep command is needed here, else webpack compile fails since it seems like the files in the previous step were touched too recently
          command: 'ping 127.0.0.1 -n 4 > nul',
          stdout: true,
          stderr: true
        },
        ng_test: {
          command: 'ng test --config=temp.conf.js',
          stdout: true,
          stderr: true
        }
    }
  });

  // Load the plugin that provides the "uglify" task.
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-string-replace');
    grunt.loadNpmTasks('grunt-exec');
  // Default task(s).
  grunt.registerTask('default', ['clean','copy','string-replace','exec']);

};

Check if any ancestor has a class using jQuery

if ($elem.parents('.left').length) {

}

How to style a clicked button in CSS

button:hover is just when you move the cursor over the button.
Try button:active instead...will work for other elements as well

_x000D_
_x000D_
button:active{_x000D_
  color: red;_x000D_
}
_x000D_
_x000D_
_x000D_

How do I detach objects in Entity Framework Code First?

If you want to detach existing object follow @Slauma's advice. If you want to load objects without tracking changes use:

var data = context.MyEntities.AsNoTracking().Where(...).ToList();

As mentioned in comment this will not completely detach entities. They are still attached and lazy loading works but entities are not tracked. This should be used for example if you want to load entity only to read data and you don't plan to modify them.

How to control the width and height of the default Alert Dialog in Android?

Ok , I can control the width and height using Builder class. I used

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(layout);
builder.setTitle("Title");
AlertDialog alertDialog = builder.create();
alertDialog.getWindow().setLayout(600, 400); //Controlling width and height.
alertDialog.show();

How to check if curl is enabled or disabled

you can check by putting these code in php file.

<?php
if(in_array  ('curl', get_loaded_extensions())) {
    echo "CURL is available on your web server";
}
else{
    echo "CURL is not available on your web server";
}

OR

var_dump(extension_loaded('curl'));

Angular: How to download a file from HttpClient?

I ended up here when searching for ”rxjs download file using post”.

This was my final product. It uses the file name and type given in the server response.

import { ajax, AjaxResponse } from 'rxjs/ajax';
import { map } from 'rxjs/operators';

downloadPost(url: string, data: any) {
    return ajax({
        url: url,
        method: 'POST',
        responseType: 'blob',
        body: data,
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'text/plain, */*',
            'Cache-Control': 'no-cache',
        }
    }).pipe(
        map(handleDownloadSuccess),
    );
}


handleDownloadSuccess(response: AjaxResponse) {
    const downloadLink = document.createElement('a');
    downloadLink.href = window.URL.createObjectURL(response.response);

    const disposition = response.xhr.getResponseHeader('Content-Disposition');
    if (disposition) {
        const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
        const matches = filenameRegex.exec(disposition);
        if (matches != null && matches[1]) {
            const filename = matches[1].replace(/['"]/g, '');
            downloadLink.setAttribute('download', filename);
        }
    }

    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
}

concatenate char array in C

in rare cases when you can't use strncat, strcat or strcpy. And you don't have access to <string.h> so you can't use strlen. Also you maybe don't even know the size of the char arrays and you still want to concatenate because you got only pointers. Well, you can do old school malloc and count characters yourself like..

char *combineStrings(char* inputA, char* inputB) {
    size_t len = 0, lenB = 0;
    while(inputA[len] != '\0') len++;
    while(inputB[lenB] != '\0') lenB++;
    char* output = malloc(len+lenB);
    sprintf((char*)output,"%s%s",inputA,inputB);
    return output;
}

It just needs #include <stdio.h> which you will have most likely included already

OSError - Errno 13 Permission denied

You need to change the directory permission so that web server process can change the directory.

  • To change ownership of the directory, use chown:

    chown -R user-id:group-id /path/to/the/directory
    
  • To see which user own the web server process (change httpd accordingly):

    ps aux | grep httpd | grep -v grep
    

    OR

    ps -efl | grep httpd | grep -v grep
    

Where does R store packages?

You do not want the '='

Use .libPaths("C:/R/library") in you Rprofile.site file

And make sure you have correct " symbol (Shift-2)

Can I change the fill color of an svg path with CSS?

if you want to change color by hovering in the element, try this:

path:hover{
  fill:red;
}

Javascript date.getYear() returns 111 in 2011?

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getYear

getYear is no longer used and has been replaced by the getFullYear method.

The getYear method returns the year minus 1900; thus:

  • For years greater than or equal to 2000, the value returned by getYear is 100 or greater. For example, if the year is 2026, getYear returns 126.
  • For years between and including 1900 and 1999, the value returned by getYear is between 0 and 99. For example, if the year is 1976, getYear returns 76.
  • For years less than 1900, the value returned by getYear is less than 0. For example, if the year is 1800, getYear returns -100.
  • To take into account years before and after 2000, you should use getFullYear instead of getYear so that the year is specified in full.

Load an image from a url into a PictureBox

Here's the solution I use. I can't remember why I couldn't just use the PictureBox.Load methods. I'm pretty sure it's because I wanted to properly scale & center the downloaded image into the PictureBox control. If I recall, all the scaling options on PictureBox either stretch the image, or will resize the PictureBox to fit the image. I wanted a properly scaled and centered image in the size I set for PictureBox.

Now, I just need to make a async version...

Here's my methods:

   #region Image Utilities

    /// <summary>
    /// Loads an image from a URL into a Bitmap object.
    /// Currently as written if there is an error during downloading of the image, no exception is thrown.
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    public static Bitmap LoadPicture(string url)
    {
        System.Net.HttpWebRequest wreq;
        System.Net.HttpWebResponse wresp;
        Stream mystream;
        Bitmap bmp;

        bmp = null;
        mystream = null;
        wresp = null;
        try
        {
            wreq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
            wreq.AllowWriteStreamBuffering = true;

            wresp = (System.Net.HttpWebResponse)wreq.GetResponse();

            if ((mystream = wresp.GetResponseStream()) != null)
                bmp = new Bitmap(mystream);
        }
        catch
        {
            // Do nothing... 
        }
        finally
        {
            if (mystream != null)
                mystream.Close();

            if (wresp != null)
                wresp.Close();
        }

        return (bmp);
    }

    /// <summary>
    /// Takes in an image, scales it maintaining the proper aspect ratio of the image such it fits in the PictureBox's canvas size and loads the image into picture box.
    /// Has an optional param to center the image in the picture box if it's smaller then canvas size.
    /// </summary>
    /// <param name="image">The Image you want to load, see LoadPicture</param>
    /// <param name="canvas">The canvas you want the picture to load into</param>
    /// <param name="centerImage"></param>
    /// <returns></returns>

    public static Image ResizeImage(Image image, PictureBox canvas, bool centerImage ) 
    {
        if (image == null || canvas == null)
        {
            return null;
        }

        int canvasWidth = canvas.Size.Width;
        int canvasHeight = canvas.Size.Height;
        int originalWidth = image.Size.Width;
        int originalHeight = image.Size.Height;

        System.Drawing.Image thumbnail =
            new Bitmap(canvasWidth, canvasHeight); // changed parm names
        System.Drawing.Graphics graphic =
                     System.Drawing.Graphics.FromImage(thumbnail);

        graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphic.SmoothingMode = SmoothingMode.HighQuality;
        graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
        graphic.CompositingQuality = CompositingQuality.HighQuality;

        /* ------------------ new code --------------- */

        // Figure out the ratio
        double ratioX = (double)canvasWidth / (double)originalWidth;
        double ratioY = (double)canvasHeight / (double)originalHeight;
        double ratio = ratioX < ratioY ? ratioX : ratioY; // use whichever multiplier is smaller

        // now we can get the new height and width
        int newHeight = Convert.ToInt32(originalHeight * ratio);
        int newWidth = Convert.ToInt32(originalWidth * ratio);

        // Now calculate the X,Y position of the upper-left corner 
        // (one of these will always be zero)
        int posX = Convert.ToInt32((canvasWidth - (image.Width * ratio)) / 2);
        int posY = Convert.ToInt32((canvasHeight - (image.Height * ratio)) / 2);

        if (!centerImage)
        {
            posX = 0;
            posY = 0;
        }
        graphic.Clear(Color.White); // white padding
        graphic.DrawImage(image, posX, posY, newWidth, newHeight);

        /* ------------- end new code ---------------- */

        System.Drawing.Imaging.ImageCodecInfo[] info =
                         ImageCodecInfo.GetImageEncoders();
        EncoderParameters encoderParameters;
        encoderParameters = new EncoderParameters(1);
        encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality,
                         100L);

        Stream s = new System.IO.MemoryStream();
        thumbnail.Save(s, info[1],
                          encoderParameters);

        return Image.FromStream(s);
    }

    #endregion

Here's the required includes. (Some might be needed by other code, but including all to be safe)

using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.IO;
using System.Drawing.Imaging;
using System.Text.RegularExpressions;
using System.Drawing;

How I generally use it:

 ImageUtil.ResizeImage(ImageUtil.LoadPicture( "http://someurl/img.jpg", pictureBox1, true);

PHP If Statement with Multiple Conditions

if($var == "abc" || $var == "def" || ...)
{
    echo "true";
}

Using "Or" instead of "And" would help here, i think

String concatenation in Ruby

You can also use % as follows:

source = "#{ROOT_DIR}/%s/App.config" % project

This approach works with ' (single) quotation mark as well.

Initializing a member array in constructor initializer

  1. No, unfortunately.
  2. You just can't in the way you want, as it's not allowed by the grammar (more below). You can only use ctor-like initialization, and, as you know, that's not available for initializing each item in arrays.
  3. I believe so, as they generalize initialization across the board in many useful ways. But I'm not sure on the details.

In C++03, aggregate initialization only applies with syntax similar as below, which must be a separate statement and doesn't fit in a ctor initializer.

T var = {...};

How to sort an object array by date property?

@Phrogz answers are both great, but here is a great, more concise answer:

array.sort(function(a,b){return a.getTime() - b.getTime()});

Using the arrow function way

array.sort((a,b)=>a.getTime()-b.getTime());

found here: Sort date in Javascript

How to uncheck checkbox using jQuery Uniform library

A simpler solution is to do this rather than using uniform:

$('#check1').prop('checked', true); // will check the checkbox with id check1
$('#check1').prop('checked', false); // will uncheck the checkbox with id check1

This will not trigger any click action defined.

You can also use:

$('#check1').click(); // 

This will toggle the check/uncheck for the checkbox but this will also trigger any click action you have defined. So be careful.

EDIT: jQuery 1.6+ uses prop() not attr() for checkboxes checked value

How to scroll UITableView to specific position

Use [tableView scrollToRowAtIndexPath:indexPath atScrollPosition:scrollPosition animated:YES]; Scrolls the receiver until a row identified by index path is at a particular location on the screen.

And

scrollToNearestSelectedRowAtScrollPosition:animated:

Scrolls the table view so that the selected row nearest to a specified position in the table view is at that position.

How do I pass data to Angular routed components?

By default i won't use a guard for this one for me it is more can i enter the route or can i leave it. It is not to share data betweenn them.

If you want to load data before we entered a route just add an resolver to this one this is also part of the Router.

As very basic example:

Resolver

import { Resolve, ActivatedRoute } from "@angular/router";
import { Observable } from "rxjs";
import { Injectable } from "@angular/core";
import { take } from "rxjs/operators";

@Injectable()
export class UserResolver implements Resolve<User> {

    constructor(
        private userService: UserService,
        private route: ActivatedRoute
    ) {}

    resolve(): Observable<firebase.User> {
        return this.route.params.pipe(
            switchMap((params) => this.userService.fetchUser(params.user_id)),
            take(1)
        );
    }
}

put to the router:

RouterModule.forChild([
{
    path: "user/:user_id",
    component: MyUserDetailPage,
    resolve: {
        user: UserResolver
    }
  }
}]

get the data in our component

ngOnInit() {
    const user: firebase.User = this.activatedRoute.snapshot.data.user;
}

The downside on this approach is, he will enter the route first if he get the user data not before, this ensures the data for the user has been loaded and is ready on start of the component, but you will stay on the old page as long the data has been loaded (Loading Animation)

Remove certain characters from a string

UPDATE yourtable 
SET field_or_column =REPLACE ('current string','findpattern', 'replacepattern') 
WHERE 1

Javascript : Send JSON Object with Ajax?

I struggled for a couple of days to find anything that would work for me as was passing multiple arrays of ids and returning a blob. Turns out if using .NET CORE I'm using 2.1, you need to use [FromBody] and as can only use once you need to create a viewmodel to hold the data.

Wrap up content like below,

var params = {
            "IDs": IDs,
            "ID2s": IDs2,
            "id": 1
        };

In my case I had already json'd the arrays and passed the result to the function

var IDs = JsonConvert.SerializeObject(Model.Select(s => s.ID).ToArray());

Then call the XMLHttpRequest POST and stringify the object

var ajax = new XMLHttpRequest();
ajax.open("POST", '@Url.Action("MyAction", "MyController")', true);
ajax.responseType = "blob";
ajax.setRequestHeader("Content-Type", "application/json;charset=UTF-8");           
ajax.onreadystatechange = function () {
    if (this.readyState == 4) {
       var blob = new Blob([this.response], { type: "application/octet-stream" });
       saveAs(blob, "filename.zip");
    }
};

ajax.send(JSON.stringify(params));

Then have a model like this

public class MyModel
{
    public int[] IDs { get; set; }
    public int[] ID2s { get; set; }
    public int id { get; set; }
}

Then pass in Action like

public async Task<IActionResult> MyAction([FromBody] MyModel model)

Use this add-on if your returning a file

<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.3/FileSaver.min.js"></script>

How can I initialize an ArrayList with all zeroes in Java?

Java 8 implementation (List initialized with 60 zeroes):

List<Integer> list = IntStream.of(new int[60])
                    .boxed()
                    .collect(Collectors.toList());
  • new int[N] - creates an array filled with zeroes & length N
  • boxed() - each element boxed to an Integer
  • collect(Collectors.toList()) - collects elements of stream

How to make flutter app responsive according to different screen size?

Place dependency in pubspec.yaml

flutter_responsive_screen: ^1.0.0

Function hp = Screen(MediaQuery.of(context).size).hp;
Function wp = Screen(MediaQuery.of(context).size).wp;

Example :
return Container(height: hp(27),weight: wp(27));

How to round to 2 decimals with Python?

If you need avoid floating point problem on rounding numbers for accounting, you can use numpy round.

You need install numpy :

pip install numpy

and the code :

import numpy as np

print(round(2.675, 2))
print(float(np.round(2.675, 2)))

prints

2.67
2.68

You should use that if you manage money with legal rounding.

UTF-8: General? Bin? Unicode?

  • utf8_bin compares the bits blindly. No case folding, no accent stripping.
  • utf8_general_ci compares one byte with one byte. It does case folding and accent stripping, but no 2-character comparisions: ij is not equal ? in this collation.
  • utf8_*_ci is a set of language-specific rules, but otherwise like unicode_ci. Some special cases: Ç, C, ch, ll
  • utf8_unicode_ci follows an old Unicode standard for comparisons. ij=?, but ae != æ
  • utf8_unicode_520_ci follows an newer Unicode standard. ae = æ

See collation chart for details on what is equal to what in various utf8 collations.

utf8, as defined by MySQL is limited to the 1- to 3-byte utf8 codes. This leaves out Emoji and some of Chinese. So you should really switch to utf8mb4 if you want to go much beyond Europe.

The above points apply to utf8mb4, after suitable spelling change. Going forward, utf8mb4 and utf8mb4_unicode_520_ci are preferred.

  • utf16 and utf32 are variants on utf8; there is virtually no use for them.
  • ucs2 is closer to "Unicode" than "utf8"; there is virtually no use for it.

Counting Line Numbers in Eclipse

Search > File Search

Check the Regular expression box.

Use this expression:

\n[\s]*

Select whatever file types (*.java, *.xml, etc..) and working sets are appropriate for you.

How to grep and replace

Be very careful when using find and sed in a git repo! If you don't exclude the binary files you can end up with this error:

error: bad index file sha1 signature 
fatal: index file corrupt

To solve this error you need to revert the sed by replacing your new_string with your old_string. This will revert your replaced strings, so you will be back to the beginning of the problem.

The correct way to search for a string and replace it is to skip find and use grep instead in order to ignore the binary files:

sed -ri -e "s/old_string/new_string/g" $(grep -Elr --binary-files=without-match "old_string" "/files_dir")

Credits for @hobs

yii2 redirect in controller action does not work?

If you are trying to do redirect in beforeAction() you should use send() method

 return $this->redirect('/some/url',302)->send();

How to assign an exec result to a sql variable?

I always use the return value to pass back error status. If you need to pass back one value I'd use an output parameter.

sample stored procedure, with an OUTPUT parameter:

CREATE PROCEDURE YourStoredProcedure 
(
    @Param1    int
   ,@Param2    varchar(5)
   ,@Param3    datetime OUTPUT
)
AS
IF ISNULL(@Param1,0)>5
BEGIN
    SET @Param3=GETDATE()
END
ELSE
BEGIN
    SET @Param3='1/1/2010'
END
RETURN 0
GO

call to the stored procedure, with an OUTPUT parameter:

DECLARE @OutputParameter  datetime
       ,@ReturnValue      int

EXEC @ReturnValue=YourStoredProcedure 1,null, @OutputParameter OUTPUT
PRINT @ReturnValue
PRINT CONVERT(char(23),@OutputParameter ,121)

OUTPUT:

0
2010-01-01 00:00:00.000