Programs & Examples On #Dynamic columns

How to run console application from Windows Service?

I have a Windows service, and I added the following line to the constructor for my service:

using System.Diagnostics;
try {
    Process p = Process.Start(@"C:\Windows\system32\calc.exe");
} catch {
    Debugger.Break();
}

When I tried to run this, the Process.Start() call was made, and no exception occurred. However, the calc.exe application did not show up. In order to make it work, I had edit the properties for my service in the Service Control Manager to enable interaction with the desktop. After doing that, the Process.Start() opened calc.exe as expected.

But as others have said, interaction with the desktop is frowned upon by Microsoft and has essentially been disabled in Vista. So even if you can get it to work in XP, I don't know that you'll be able to make it work in Vista.

Catch browser's "zoom" event in JavaScript

Here is a native way (major frameworks cannot zoom in Chrome, because they dont supports passive event behaviour)


//For Google Chrome
document.addEventListener("mousewheel", event => {
  console.log(`wheel`);
  if(event.ctrlKey == true)
  {
    event.preventDefault();
    if(event.deltaY > 0) {
      console.log('Down');
    }else {
      console.log('Up');
    }
  }
}, { passive: false });

// For Mozilla Firefox
document.addEventListener("DOMMouseScroll", event => {
  console.log(`wheel`);
  if(event.ctrlKey == true)
  {
    event.preventDefault();
    if(event.detail > 0) {
      console.log('Down');
    }else {
      console.log('Up');
    }
  }
}, { passive: false });

SVN remains in conflict?

If you have trouble resolving (like me) and you cannot delete and update the resources because you have made many changes on them, plus you are using eclipse subversive instead of native client, follow these steps:

  1. make a copy of your entire project dir
  2. perform team>disconnect within eclipse, and choose to delete the svn metadata
  3. then choose team>share project, and point to the very same folder that your project resides in
  4. choose yes, and commit everything (you may want to exclude some very local resources, like configuration files)
  5. if you have deleted or moved some resources prior to your first commit trial, delete those old resources (they should have doubled up, one in old location, one in new) and commit those deletions.

You're done.

sed edit file in place

One thing to note, sed cannot write files on its own as the sole purpose of sed is to act as an editor on the "stream" (ie pipelines of stdin, stdout, stderr, and other >&n buffers, sockets and the like). With this in mind you can use another command tee to write the output back to the file. Another option is to create a patch from piping the content into diff.

Tee method

sed '/regex/' <file> | tee <file>

Patch method

sed '/regex/' <file> | diff -p <file> /dev/stdin | patch

UPDATE:

Also, note that patch will get the file to change from line 1 of the diff output:

Patch does not need to know which file to access as this is found in the first line of the output from diff:

$ echo foobar | tee fubar

$ sed 's/oo/u/' fubar | diff -p fubar /dev/stdin
*** fubar   2014-03-15 18:06:09.000000000 -0500
--- /dev/stdin  2014-03-15 18:06:41.000000000 -0500
***************
*** 1 ****
! foobar
--- 1 ----
! fubar

$ sed 's/oo/u/' fubar | diff -p fubar /dev/stdin | patch
patching file fubar

Inject service in app.config

** Explicitly request services from other modules using angular.injector **

Just to elaborate on kim3er's answer, you can provide services, factories, etc without changing them to providers, as long as they are included in other modules...

However, I'm not sure if the *Provider (which is made internally by angular after it processes a service, or factory) will always be available (it may depend on what else loaded first), as angular lazily loads modules.

Note that if you want to re-inject the values that they should be treated as constants.

Here's a more explicit, and probably more reliable way to do it + a working plunker

var base = angular.module('myAppBaseModule', [])
base.factory('Foo', function() { 
  console.log("Foo");
  var Foo = function(name) { this.name = name; };
  Foo.prototype.hello = function() {
    return "Hello from factory instance " + this.name;
  }
  return Foo;
})
base.service('serviceFoo', function() {
  this.hello = function() {
    return "Service says hello";
  }
  return this;
});

var app = angular.module('appModule', []);
app.config(function($provide) {
  var base = angular.injector(['myAppBaseModule']);
  $provide.constant('Foo', base.get('Foo'));
  $provide.constant('serviceFoo', base.get('serviceFoo'));
});
app.controller('appCtrl', function($scope, Foo, serviceFoo) {
  $scope.appHello = (new Foo("app")).hello();
  $scope.serviceHello = serviceFoo.hello();
});

Mockito matcher and array of primitives

What works for me was org.mockito.ArgumentMatchers.isA

for example:

isA(long[].class)

that works fine.

the implementation difference of each other is:

public static <T> T any(Class<T> type) {
    reportMatcher(new VarArgAware(type, "<any " + type.getCanonicalName() + ">"));
    return Primitives.defaultValue(type);
}

public static <T> T isA(Class<T> type) {
    reportMatcher(new InstanceOf(type));
    return Primitives.defaultValue(type);
}

Can I run a 64-bit VMware image on a 32-bit machine?

You can if your processor is 64-bit and Virtualization Technology (VT) extension is enabled (it can be switched off in BIOS). You can't do it on 32-bit processor.

To check this under Linux you just need to look into /proc/cpuinfo file. Just look for the appropriate flag (vmx for Intel processor or svm for AMD processor)

egrep '(vmx|svm)' /proc/cpuinfo

To check this under Windows you need to use a program like CPU-Z which will display your processor architecture and supported extensions.

How can I check if the current date/time is past a set date/time?

Since PHP >= 5.2.2 you can use the DateTime class as such:

if (new DateTime() > new DateTime("2010-05-15 16:00:00")) {
    # current time is greater than 2010-05-15 16:00:00
    # in other words, 2010-05-15 16:00:00 has passed
}

The string passed to the DateTime constructor is parsed according to these rules.


Note that it is also possible to use time and strtotime functions. See original answer.

How to convert a multipart file to File?

The answer by Alex78191 has worked for me.

public File getTempFile(MultipartFile multipartFile)
{

CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartFile;
FileItem fileItem = commonsMultipartFile.getFileItem();
DiskFileItem diskFileItem = (DiskFileItem) fileItem;
String absPath = diskFileItem.getStoreLocation().getAbsolutePath();
File file = new File(absPath);

//trick to implicitly save on disk small files (<10240 bytes by default)

if (!file.exists()) {
    file.createNewFile();
    multipartFile.transferTo(file);
}

return file;
}

For uploading files having size greater than 10240 bytes please change the maxInMemorySize in multipartResolver to 1MB.

<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- setting maximum upload size t 20MB -->
<property name="maxUploadSize" value="20971520" />
<!-- max size of file in memory (in bytes) -->
<property name="maxInMemorySize" value="1048576" />
<!-- 1MB --> </bean>

PhpMyAdmin not working on localhost

when I started xampp on my windows 10 there were many options available, unfortunately every one of them failed. I ll list them so that you don't go through all of them again.

THINGS THAT DIDN'T WORK

1) i installed xampp initially in a different drive and not c because of UAC issues so i uninstalled Xampp and installed it again in c (didn't work) 2) while reinstalling i deactivated the antivirus as setup said that some installing might not end up properly(realized it doesn't matter :) lmao) 3) i tried to change ports several times of xampp from 80 to some different number like 8080 etc. still nothing happened 4) i then tried using firefox as it is believed that internet explorer or internet edge is not a good browser for xampp 5) after that i went to config file i.e config.inc inside phpmyadmin folder and did some crap as were given in the instructions. Failure it was 6) then i closed laptop and went to sleep(XD srry leave this point) 7) then i tried searching for windows web services in the services.msc to disable it. i couldn't find it

WHAT WORKED

On eighth time i got success.This is what i did 8)In control panel, where you have actions , modules PIDs, Ports you will see Services under which you will see gray boxes which are actually checkboxes but are empty initially. i checked it so that xampp services start and apache services start. now you will see them ticked. After that just change the port of xampp and apache to 80.

I hope it helps. cheers ;)

JUnit tests pass in Eclipse but fail in Maven Surefire

I had this problem today testing a method that converted an object that contained a Map to a JSON string. I assume Eclipse and the Maven surefire plugin were using different JREs which had different implementations of HashMap ordering or something, which caused the tests run through Eclipse to pass and the tests run through surefire to fail (assertEquals failed). The easiest solution was to use an implementation of Map that had reliable ordering.

Setting up maven dependency for SQL Server

<dependency>
  <groupId>com.hynnet</groupId>
  <artifactId>sqljdbc4-chs</artifactId>
  <version>4.0.2206.100</version>
</dependency>

This worked for me(if you use maven)

https://search.maven.org/artifact/com.hynnet/sqljdbc4-chs/4.0.2206.100/jar

Place API key in Headers or URL

It is better to use API Key in header, not in URL.

URLs are saved in browser's history if it is tried from browser. It is very rare scenario. But problem comes when the backend server logs all URLs. It might expose the API key.

In two ways, you can use API Key in header

Basic Authorization:

Example from stripe:

curl https://api.stripe.com/v1/charges -u sk_test_BQokikJOvBiI2HlWgH4olfQ2:

curl uses the -u flag to pass basic auth credentials (adding a colon after your API key will prevent it from asking you for a password).

Custom Header

curl -H "X-API-KEY: 6fa741de1bdd1d91830ba" https://api.mydomain.com/v1/users

Getting "Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?" when installing lxml through pip

Install lxml from http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml for your python version. It's a precompiled WHL with required modules/dependencies.

The site lists several packages, when e.g. using Win32 Python 3.9, use lxml-4.5.2-cp39-cp39-win32.whl.

Download the file, and then install with:

pip install C:\path\to\downloaded\file\lxml-4.5.2-cp39-cp39-win32.whl

What are the best use cases for Akka framework

I've recently implemented the canonical map-reduce example in Akka: Word count. So it's one use case of Akka: better performance. It was more of a experiment of JRuby and Akka's actors than anything else, but it also shows that Akka is not Scala or Java only: it works on all languages on top of JVM.

Twig ternary operator, Shorthand if-then-else

You can use shorthand syntax as of Twig 1.12.0

{{ foo ?: 'no' }} is the same as {{ foo ? foo : 'no' }}
{{ foo ? 'yes' }} is the same as {{ foo ? 'yes' : '' }}

How can I have two fixed width columns with one flexible column in the center?

Instead of using width (which is a suggestion when using flexbox), you could use flex: 0 0 230px; which means:

  • 0 = don't grow (shorthand for flex-grow)
  • 0 = don't shrink (shorthand for flex-shrink)
  • 230px = start at 230px (shorthand for flex-basis)

which means: always be 230px.

See fiddle, thanks @TylerH

Oh, and you don't need the justify-content and align-items here.

img {
    max-width: 100%;
}
#container {
    display: flex;
    x-justify-content: space-around;
    x-align-items: stretch;
    max-width: 1200px;
}
.column.left {
    width: 230px;
    flex: 0 0 230px;
}
.column.right {
    width: 230px;
    flex: 0 0 230px;
    border-left: 1px solid #eee;
}
.column.center {
    border-left: 1px solid #eee;
}

How do I install Python libraries in wheel format?

To install wheel packages in python 2.7x:

  1. Install python 2.7x (i would recommend python 2.78) - download the appropriate python binary for your version of windows . You can download python 2.78 at this site https://www.python.org/download/releases/2.7.8/ -I would recommend installing the graphical Tk module, and including python 2.78 in the windows path (environment variables) during installation.

  2. Install get-pip.py and setuptools Download the installer at https://bootstrap.pypa.io/get-pip.py Double click the above file to run it. It will install pip and setuptools [or update them, if you have an earlier version of either]

-Double click the above file and wait - it will open a black window and print will scroll across the screen as it downloads and installs [or updates] pip and setuptools --->when it finishes the window will close.

  1. Open an elevated command prompt - click on windows start icon, enter cmd in the search field (but do not press enter), then press ctrl+shift+. Click 'yes' when the uac box appears.

A-type cd c:\python27\scripts [or cd \scripts ]

B-type pip install -u Eg to install pyside, type pip install -u pyside

Wait - it will state 'downloading PySide or -->it will download and install the appropriate version of the python package [the one that corresponds to your version of python and windows.]

Note - if you have downloaded the .whl file and saved it locally on your hard drive, type in
pip install --no-index --find-links=localpathtowheelfile packagename

**to install a previously downloaded wheel package you need to type in the following command pip install --no-index --find-links=localpathtowheelfile packagename

In jQuery, what's the best way of formatting a number to 2 decimal places?

We modify a Meouw function to be used with keyup, because when you are using an input it can be more helpful.

Check this:

Hey there!, @heridev and I created a small function in jQuery.

You can try next:

HTML

<input type="text" name="one" class="two-digits"><br>
<input type="text" name="two" class="two-digits">?

jQuery

// apply the two-digits behaviour to elements with 'two-digits' as their class
$( function() {
    $('.two-digits').keyup(function(){
        if($(this).val().indexOf('.')!=-1){         
            if($(this).val().split(".")[1].length > 2){                
                if( isNaN( parseFloat( this.value ) ) ) return;
                this.value = parseFloat(this.value).toFixed(2);
            }  
         }            
         return this; //for chaining
    });
});

? DEMO ONLINE:

http://jsfiddle.net/c4Wqn/

(@heridev, @vicmaster)

Spark SQL: apply aggregate functions to a list of columns

Current answers are perfectly correct on how to create the aggregations, but none actually address the column alias/renaming that is also requested in the question.

Typically, this is how I handle this case:

val dimensionFields = List("col1")
val metrics = List("col2", "col3", "col4")
val columnOfInterests = dimensions ++ metrics

val df = spark.read.table("some_table"). 
    .select(columnOfInterests.map(c => col(c)):_*)
    .groupBy(dimensions.map(d => col(d)): _*)
    .agg(metrics.map( m => m -> "sum").toMap)
    .toDF(columnOfInterests:_*)    // that's the interesting part

The last line essentially renames every columns of the aggregated dataframe to the original fields, essentially changing sum(col2) and sum(col3) to simply col2 and col3.

Removing empty rows of a data file in R

This is similar to some of the above answers, but with this, you can specify if you want to remove rows with a percentage of missing values greater-than or equal-to a given percent (with the argument pct)

drop_rows_all_na <- function(x, pct=1) x[!rowSums(is.na(x)) >= ncol(x)*pct,]

Where x is a dataframe and pct is the threshold of NA-filled data you want to get rid of.

pct = 1 means remove rows that have 100% of its values NA. pct = .5 means remome rows that have at least half its values NA

Javascript to check whether a checkbox is being checked or unchecked

function CHeck(){
    var ChkBox = document.getElementById("CheckBox1");
    alert(ChkBox.Checked);
}

<asp:CheckBox ID="CheckBox1" runat="server" onclick="CHeck()" />

How can I get all a form's values that would be submitted without submitting

In straight Javascript you could do something similar to the following:

var kvpairs = [];
var form = // get the form somehow
for ( var i = 0; i < form.elements.length; i++ ) {
   var e = form.elements[i];
   kvpairs.push(encodeURIComponent(e.name) + "=" + encodeURIComponent(e.value));
}
var queryString = kvpairs.join("&");

In short, this creates a list of key-value pairs (name=value) which is then joined together using "&" as a delimiter.

Python syntax for "if a or b or c but not all of them"

This is basically a "some (but not all)" functionality (when contrasted with the any() and all() builtin functions).

This implies that there should be Falses and Trues among the results. Therefore, you can do the following:

some = lambda ii: frozenset(bool(i) for i in ii).issuperset((True, False))

# one way to test this is...
test = lambda iterable: (any(iterable) and (not all(iterable))) # see also http://stackoverflow.com/a/16522290/541412

# Some test cases...
assert(some(()) == False)       # all() is true, and any() is false
assert(some((False,)) == False) # any() is false
assert(some((True,)) == False)  # any() and all() are true

assert(some((False,False)) == False)
assert(some((True,True)) == False)
assert(some((True,False)) == True)
assert(some((False,True)) == True)

One advantage of this code is that you only need to iterate once through the resulting (booleans) items.

One disadvantage is that all these truth-expressions are always evaluated, and do not do short-circuiting like the or/and operators.

When should you use a class vs a struct in C++?

I use struct only when I need to hold some data without any member functions associated to it (to operate on the member data) and to access the data variables directly.

Eg: Reading/Writing data from files and socket streams etc. Passing function arguments in a structure where the function arguments are too many and function syntax looks too lengthy.

Technically there is no big difference between class and struture except default accessibility. More over it depends on programming style how you use it.

Add rows to CSV File in powershell

Simple to me is like this:

$Time = Get-Date -Format "yyyy-MM-dd HH:mm K"
$Description = "Done on time"

"$Time,$Description"|Add-Content -Path $File # Keep no space between content variables

If you have a lot of columns, then create a variable like $NewRow like:

$Time = Get-Date -Format "yyyy-MM-dd HH:mm K"
$Description = "Done on time"
$NewRow = "$Time,$Description" # No space between variables, just use comma(,).

$NewRow | Add-Content -Path $File # Keep no space between content variables

Please note the difference between Set-Content (overwrites the existing contents) and Add-Content (appends to the existing contents) of the file.

Arrays with different datatypes i.e. strings and integers. (Objectorientend)

Notice the repetition of Book in Booknumber (int), Booktitle (string), Booklanguage (string), Bookprice (int)- it screams for a class type.

class Book {
  int number;
  String title;
  String language;
  int price;
}

Now you can simply have:

Book[] books = new Books[3];

If you want arrays, you can declare it as object array an insert Integer and String into it:

Object books[3][4]

'Must Override a Superclass Method' Errors after importing a project into Eclipse

The answer by Paul worked for me partially. I still had one error then. So, in addition to that, I also had to go to Properties-> Project Facets and there set the Java version from 1.5 to 1.6.

Maybe that helps.

How to create an array of object literals in a loop?

var arr = [];
var len = oFullResponse.results.length;
for (var i = 0; i < len; i++) {
    arr.push({
        key: oFullResponse.results[i].label,
        sortable: true,
        resizeable: true
    });
}

Convert date to another timezone in JavaScript

You can also use https://www.npmjs.com/package/ctoc_timezone

It has got much simple implementation and format customisation.

Changing format in toTimeZone:

CtoC.toTimeZone(new Date(),"EST","Do MMM YYYY hh:mm:ss #{EST}");

Output :

28th Feb 2013 19:00:00 EST

You can explore multiple functionalities in the doc.

When is layoutSubviews called?

A rather obscure, yet potentially important case when layoutSubviews never gets called is:

import UIKit

class View: UIView {

    override class var layerClass: AnyClass { return Layer.self }

    class Layer: CALayer {
        override func layoutSublayers() {
            // if we don't call super.layoutSublayers()...
            print(type(of: self), #function)
        }
    }

    override func layoutSubviews() {
        // ... this method never gets called by the OS!
        print(type(of: self), #function)
    }
}

let view = View(frame: CGRect(x: 0, y: 0, width: 100, height: 100))

Heatmap in matplotlib with pcolor?

This is late, but here is my python implementation of the flowingdata NBA heatmap.

updated:1/4/2014: thanks everyone

# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>

# ------------------------------------------------------------------------
# Filename   : heatmap.py
# Date       : 2013-04-19
# Updated    : 2014-01-04
# Author     : @LotzJoe >> Joe Lotz
# Description: My attempt at reproducing the FlowingData graphic in Python
# Source     : http://flowingdata.com/2010/01/21/how-to-make-a-heatmap-a-quick-and-easy-solution/
#
# Other Links:
#     http://stackoverflow.com/questions/14391959/heatmap-in-matplotlib-with-pcolor
#
# ------------------------------------------------------------------------

import matplotlib.pyplot as plt
import pandas as pd
from urllib2 import urlopen
import numpy as np
%pylab inline

page = urlopen("http://datasets.flowingdata.com/ppg2008.csv")
nba = pd.read_csv(page, index_col=0)

# Normalize data columns
nba_norm = (nba - nba.mean()) / (nba.max() - nba.min())

# Sort data according to Points, lowest to highest
# This was just a design choice made by Yau
# inplace=False (default) ->thanks SO user d1337
nba_sort = nba_norm.sort('PTS', ascending=True)

nba_sort['PTS'].head(10)

# Plot it out
fig, ax = plt.subplots()
heatmap = ax.pcolor(nba_sort, cmap=plt.cm.Blues, alpha=0.8)

# Format
fig = plt.gcf()
fig.set_size_inches(8, 11)

# turn off the frame
ax.set_frame_on(False)

# put the major ticks at the middle of each cell
ax.set_yticks(np.arange(nba_sort.shape[0]) + 0.5, minor=False)
ax.set_xticks(np.arange(nba_sort.shape[1]) + 0.5, minor=False)

# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.tick_top()

# Set the labels

# label source:https://en.wikipedia.org/wiki/Basketball_statistics
labels = [
    'Games', 'Minutes', 'Points', 'Field goals made', 'Field goal attempts', 'Field goal percentage', 'Free throws made', 'Free throws attempts', 'Free throws percentage',
    'Three-pointers made', 'Three-point attempt', 'Three-point percentage', 'Offensive rebounds', 'Defensive rebounds', 'Total rebounds', 'Assists', 'Steals', 'Blocks', 'Turnover', 'Personal foul']

# note I could have used nba_sort.columns but made "labels" instead
ax.set_xticklabels(labels, minor=False)
ax.set_yticklabels(nba_sort.index, minor=False)

# rotate the
plt.xticks(rotation=90)

ax.grid(False)

# Turn off all the ticks
ax = plt.gca()

for t in ax.xaxis.get_major_ticks():
    t.tick1On = False
    t.tick2On = False
for t in ax.yaxis.get_major_ticks():
    t.tick1On = False
    t.tick2On = False

The output looks like this: flowingdata-like nba heatmap

There's an ipython notebook with all this code here. I've learned a lot from 'overflow so hopefully someone will find this useful.

Command to collapse all sections of code?

In Visual Studio 2019:

Go to Tools > Options > Keyboard.

Search for Edit.ToggleAllOutlining

Use the shortcut listed there, or assign it the shortcut of choice.

Converting from signed char to unsigned char and back again?

This is one of the reasons why C++ introduced the new cast style, which includes static_cast and reinterpret_cast

There's two things you can mean by saying conversion from signed to unsigned, you might mean that you wish the unsigned variable to contain the value of the signed variable modulo the maximum value of your unsigned type + 1. That is if your signed char has a value of -128 then CHAR_MAX+1 is added for a value of 128 and if it has a value of -1, then CHAR_MAX+1 is added for a value of 255, this is what is done by static_cast. On the other hand you might mean to interpret the bit value of the memory referenced by some variable to be interpreted as an unsigned byte, regardless of the signed integer representation used on the system, i.e. if it has bit value 0b10000000 it should evaluate to value 128, and 255 for bit value 0b11111111, this is accomplished with reinterpret_cast.

Now, for the two's complement representation this happens to be exactly the same thing, since -128 is represented as 0b10000000 and -1 is represented as 0b11111111 and likewise for all in between. However other computers (usually older architectures) may use different signed representation such as sign-and-magnitude or ones' complement. In ones' complement the 0b10000000 bitvalue would not be -128, but -127, so a static cast to unsigned char would make this 129, while a reinterpret_cast would make this 128. Additionally in ones' complement the 0b11111111 bitvalue would not be -1, but -0, (yes this value exists in ones' complement,) and would be converted to a value of 0 with a static_cast, but a value of 255 with a reinterpret_cast. Note that in the case of ones' complement the unsigned value of 128 can actually not be represented in a signed char, since it ranges from -127 to 127, due to the -0 value.

I have to say that the vast majority of computers will be using two's complement making the whole issue moot for just about anywhere your code will ever run. You will likely only ever see systems with anything other than two's complement in very old architectures, think '60s timeframe.

The syntax boils down to the following:

signed char x = -100;
unsigned char y;

y = (unsigned char)x;                    // C static
y = *(unsigned char*)(&x);               // C reinterpret
y = static_cast<unsigned char>(x);       // C++ static
y = reinterpret_cast<unsigned char&>(x); // C++ reinterpret

To do this in a nice C++ way with arrays:

jbyte memory_buffer[nr_pixels];
unsigned char* pixels = reinterpret_cast<unsigned char*>(memory_buffer);

or the C way:

unsigned char* pixels = (unsigned char*)memory_buffer;

How do you check whether a number is divisible by another number (Python)?

You can use % operator to check divisiblity of a given number

The code to check whether given no. is divisible by 3 or 5 when no. less than 1000 is given below:

n=0
while n<1000:
    if n%3==0 or n%5==0:
        print n,'is multiple of 3 or 5'
    n=n+1

How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift?

Without some manual String masks or TimeFormatters

import Foundation

struct DateISO: Codable {
    var date: Date
}

extension Date{
    var isoString: String {
        let encoder = JSONEncoder()
        encoder.dateEncodingStrategy = .iso8601
        guard let data = try? encoder.encode(DateISO(date: self)),
        let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as?  [String: String]
            else { return "" }
        return json?.first?.value ?? ""
    }
}

let dateString = Date().isoString

Spring get current ApplicationContext

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring-servlet.xml");

Then you can retrieve the bean:

MyClass myClass = (MyClass) context.getBean("myClass");

Reference: springbyexample.org

Counting Line Numbers in Eclipse

You could use former Instantiations product CodePro AnalytiX. This eclipse plugin provides you suchlike statistics in code metrics view. This is provided by Google free of charge.

How to achieve function overloading in C?

If your compiler is gcc and you don't mind doing hand updates every time you add a new overload you can do some macro magic and get the result you want in terms of callers, it's not as nice to write... but it's possible

look at __builtin_types_compatible_p, then use it to define a macro that does something like

#define foo(a) \
((__builtin_types_compatible_p(int, a)?foo(a):(__builtin_types_compatible_p(float, a)?foo(a):)

but yea nasty, just don't

EDIT: C1X will be getting support for type generic expressions they look like this:

#define cbrt(X) _Generic((X), long double: cbrtl, \
                              default: cbrt, \
                              float: cbrtf)(X)

What are naming conventions for MongoDB?

Until we get SERVER-863 keeping the field names as short as possible is advisable especially where you have a lot of records.

Depending on your use case, field names can have a huge impact on storage. Cant understand why this is not a higher priority for MongoDb, as this will have a positive impact on all users. If nothing else, we can start being more descriptive with our field names, without thinking twice about bandwidth & storage costs.

Please do vote.

How to use callback with useState hook in react

we can write customise function which will call the callBack function if any changes in the state

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const useStateCallbackWrapper = (initilValue, callBack) => {
  const [state, setState] = useState(initilValue);
  useEffect(() => callBack(state), [state]);
  return [state, setState];
};

const callBack = state => {
  console.log("---------------", state);
};
function App() {
  const [count, setCount] = useStateCallbackWrapper(0, callBack);
  return (
    <div className="App">
      <h1>{count}</h1>
      <button onClick={() => setCount(count + 1)}>+</button>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

`

Prevent PDF file from downloading and printing

I suggest to modify pdf.js: remove the download button, convert pdf (at backend part) to some intermediate format of pdf.js and put watermark also at server side.

How to get all child inputs of a div element (jQuery)

here is my approach:

You can use it in other event.

_x000D_
_x000D_
var id;_x000D_
$("#panel :input").each(function(e){ _x000D_
  id = this.id;_x000D_
  // show id _x000D_
  console.log("#"+id);_x000D_
  // show input value _x000D_
  console.log(this.value);_x000D_
  // disable input if you want_x000D_
  //$("#"+id).prop('disabled', true);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="panel">_x000D_
  <table>_x000D_
    <tr>_x000D_
       <td><input id="Search_NazovProjektu" type="text" value="Naz Val" /></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
       <td><input id="Search_Popis" type="text" value="Po Val" /></td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to concatenate strings of a string field in a PostgreSQL 'group by' query?

Following up on Kev's answer, using the Postgres docs:

First, create an array of the elements, then use the built-in array_to_string function.

CREATE AGGREGATE array_accum (anyelement)
(
 sfunc = array_append,
 stype = anyarray,
 initcond = '{}'
);

select array_to_string(array_accum(name),'|') from table group by id;

How do I generate a random int number?

Use one instance of Random repeatedly

// Somewhat better code...
Random rng = new Random();
for (int i = 0; i < 100; i++)
{
    Console.WriteLine(GenerateDigit(rng));
}
...
static int GenerateDigit(Random rng)
{
    // Assume there'd be more logic here really
    return rng.Next(10);
}

This article takes a look at why randomness causes so many problems, and how to address them. http://csharpindepth.com/Articles/Chapter12/Random.aspx

What is the difference between Integrated Security = True and Integrated Security = SSPI?

True is only valid if you're using the .NET SqlClient library. It isn't valid when using OLEDB. Where SSPI is bvaid in both either you are using .net SqlClient library or OLEDB.

How is using OnClickListener interface different via XML and Java code?

These are exactly the same. android:onClick was added in API level 4 to make it easier, more Javascript-web-like, and drive everything from the XML. What it does internally is add an OnClickListener on the Button, which calls your DoIt method.

Here is what using a android:onClick="DoIt" does internally:

Button button= (Button) findViewById(R.id.buttonId);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        DoIt(v);
    }
});

The only thing you trade off by using android:onClick, as usual with XML configuration, is that it becomes a bit more difficult to add dynamic content (programatically, you could decide to add one listener or another depending on your variables). But this is easily defeated by adding your test within the DoIt method.

Convert char* to string C++

There seems to be a few details left out of your explanation, but I will do my best...

If these are NUL-terminated strings or the memory is pre-zeroed, you can just iterate down the length of the memory segment until you hit a NUL (0) character or the maximum length (whichever comes first). Use the string constructor, passing the buffer and the size determined in the previous step.

string retrieveString( char* buf, int max ) {

    size_t len = 0;
    while( (len < max) && (buf[ len ] != '\0') ) {
        len++;
    }

    return string( buf, len );

}

If the above is not the case, I'm not sure how you determine where a string ends.

Unexpected 'else' in "else" error

You need to rearrange your curly brackets. Your first statement is complete, so R interprets it as such and produces syntax errors on the other lines. Your code should look like:

if (dsnt<0.05) {
  wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else if (dst<0.05) {
  wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else {
  t.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)       
} 

To put it more simply, if you have:

if(condition == TRUE) x <- TRUE
else x <- FALSE

Then R reads the first line and because it is complete, runs that in its entirety. When it gets to the next line, it goes "Else? Else what?" because it is a completely new statement. To have R interpret the else as part of the preceding if statement, you must have curly brackets to tell R that you aren't yet finished:

if(condition == TRUE) {x <- TRUE
 } else {x <- FALSE}

Shortcut to comment out a block of code with sublime text

In mac I did this

  • type your comment and press command + D to select the text
  • and then press Alt + Command + / to comment out the selected text.

How to determine whether a given Linux is 32 bit or 64 bit?

That system is 32bit. iX86 in uname means it is a 32-bit architecture. If it was 64 bit, it would return

Linux mars 2.6.9-67.0.15.ELsmp #1 SMP Tue Apr 22 13:50:33 EDT 2008 x86_64 i686 x86_64 x86_64 GNU/Linux

How to send Request payload to REST API in java?

I tried with a rest client.

Headers :

  • POST /r/gerrit/rpc/ChangeDetailService HTTP/1.1
  • Host: git.eclipse.org
  • User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:18.0) Gecko/20100101 Firefox/18.0
  • Accept: application/json
  • Accept-Language: null
  • Accept-Encoding: gzip,deflate,sdch
  • accept-charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
  • Content-Type: application/json; charset=UTF-8
  • Content-Length: 73
  • Connection: keep-alive

it works fine. I retrieve 200 OK with a good body.

Why do you set a status code in your request? and multiple declaration "Accept" with Accept:application/json,application/json,application/jsonrequest. just a statement is enough.

BeautifulSoup Grab Visible Webpage Text

The simplest way to handle this case is by using getattr(). You can adapt this example to your needs:

from bs4 import BeautifulSoup

source_html = """
<span class="ratingsDisplay">
    <a class="ratingNumber" href="https://www.youtube.com/watch?v=oHg5SJYRHA0" target="_blank" rel="noopener">
        <span class="ratingsContent">3.7</span>
    </a>
</span>
"""

soup = BeautifulSoup(source_html, "lxml")
my_ratings = getattr(soup.find('span', {"class": "ratingsContent"}), "text", None)
print(my_ratings)

This will find the text element,"3.7", within the tag object <span class="ratingsContent">3.7</span> when it exists, however, default to NoneType when it does not.

getattr(object, name[, default])

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise, AttributeError is raised.

Get list of a class' instance methods

$ irb --simple-prompt

class TestClass
  def method1
  end

  def method2
  end

  def method3
  end
end

tc_list = TestClass.instance_methods(false)
#[:method1, :method2, :method3]
puts tc_list
#method1
#method2
#method3

Cross compile Go on OSX?

The process of creating executables for many platforms can be a little tedious, so I suggest to use a script:

#!/usr/bin/env bash

package=$1
if [[ -z "$package" ]]; then
  echo "usage: $0 <package-name>"
  exit 1
fi
package_name=$package

#the full list of the platforms: https://golang.org/doc/install/source#environment
platforms=(
"darwin/386"
"dragonfly/amd64"
"freebsd/386"
"freebsd/amd64"
"freebsd/arm"
"linux/386"
"linux/amd64"
"linux/arm"
"linux/arm64"
"netbsd/386"
"netbsd/amd64"
"netbsd/arm"
"openbsd/386"
"openbsd/amd64"
"openbsd/arm"
"plan9/386"
"plan9/amd64"
"solaris/amd64"
"windows/amd64"
"windows/386" )

for platform in "${platforms[@]}"
do
    platform_split=(${platform//\// })
    GOOS=${platform_split[0]}
    GOARCH=${platform_split[1]}
    output_name=$package_name'-'$GOOS'-'$GOARCH
    if [ $GOOS = "windows" ]; then
        output_name+='.exe'
    fi

    env GOOS=$GOOS GOARCH=$GOARCH go build -o $output_name $package
    if [ $? -ne 0 ]; then
        echo 'An error has occurred! Aborting the script execution...'
        exit 1
    fi
done

I checked this script on OSX only

gist - go-executable-build.sh

how to read xml file from url using php

It is working for me. I think you probably need to use urlencode() on each of the components of $map_url.

How to measure height, width and distance of object using camera?

For measuring distances with a single camera, you need to know some numbers. To measure height of something, say a chair, the only thing you have is the the size of it in the camera (which is in pixels, and can be converted to inches using screen size), that is all. The chance of measuring the height and width is using a reference, say a 6 foot tall person standing next to the chair.

This way you can work out in reverse using say a 10 foot tall object, using its size as appearing in the camera, you can work out the size of things at the same distance, on a surface that is not flat, even ensuring that they are at the same distance is a challenge.

So using the camera and just the camera, it is not possible. You need to know distance somehow, or need a reference.

If you are using the application to measure height of items you know the location of, then using GPS, you can find distance, and rest is math.

I have found some links using Google, they may help.

  1. http://forestjohnson.blogspot.com/2010/01/how-to-measure-size-of-object-using.html
  2. http://gigaom.com/mobile/how_to_measure_/
  3. http://www.iphonelife.com/blog/5/cameasure-use-your-camera-measure-size-or-distance

They may help you to find out what other information is needed other than what the camera can provide, so that you can think about your application as well regarding what can be done and what are the limitations.

One way is using multiple cameras, and that can be compensated using multiple pictures taken a known distance away. So the application can ask the user to take multiple images, track the distance using GPS, and probably it can work.

See these links as well:

  1. http://iopscience.iop.org/1742-6596/48/1/074/pdf/1742-6596_48_1_074.pdf
  2. http://www.optical-metrology-centre.com/Downloads/Papers/Photogrammetric%20Record%201994%20Automated%203-D%20measurement.pdf

How to get Url Hash (#) from server side

We had a situation where we needed to persist the URL hash across ASP.Net post backs. As the browser does not send the hash to the server by default, the only way to do it is to use some Javascript:

  1. When the form submits, grab the hash (window.location.hash) and store it in a server-side hidden input field Put this in a DIV with an id of "urlhash" so we can find it easily later.

  2. On the server you can use this value if you need to do something with it. You can even change it if you need to.

  3. On page load on the client, check the value of this this hidden field. You will want to find it by the DIV it is contained in as the auto-generated ID won't be known. Yes, you could do some trickery here with .ClientID but we found it simpler to just use the wrapper DIV as it allows all this Javascript to live in an external file and be used in a generic fashion.

  4. If the hidden input field has a valid value, set that as the URL hash (window.location.hash again) and/or perform other actions.

We used jQuery to simplify the selecting of the field, etc ... all in all it ends up being a few jQuery calls, one to save the value, and another to restore it.

Before submit:

$("form").submit(function() {
  $("input", "#urlhash").val(window.location.hash);
});

On page load:

var hashVal = $("input", "#urlhash").val();
if (IsHashValid(hashVal)) {
  window.location.hash = hashVal;
}

IsHashValid() can check for "undefined" or other things you don't want to handle.

Also, make sure you use $(document).ready() appropriately, of course.

Why does javascript replace only first instance when using replace?

Unlike the C#/.NET class library (and most other sensible languages), when you pass a String in as the string-to-match argument to the string.replace method, it doesn't do a string replace. It converts the string to a RegExp and does a regex substitution. As Gumbo explains, a regex substitution requires the g?lobal flag, which is not on by default, to replace all matches in one go.

If you want a real string-based replace — for example because the match-string is dynamic and might contain characters that have a special meaning in regexen — the JavaScript idiom for that is:

var id= 'c_'+date.split('/').join('');

Display image as grayscale using matplotlib

import matplotlib.pyplot as plt

You can also run once in your code

plt.gray()

This will show the images in grayscale as default

im = array(Image.open('I_am_batman.jpg').convert('L'))
plt.imshow(im)
plt.show()

Directory-tree listing in Python

I know this is an old question. This is a neat way I came across if you are on a liunx machine.

import subprocess
print(subprocess.check_output(["ls", "/"]).decode("utf8"))

Uncaught TypeError: Cannot assign to read only property

When you use Object.defineProperties, by default writable is set to false, so _year and edition are actually read only properties.

Explicitly set them to writable: true:

_year: {
    value: 2004,
    writable: true
},

edition: {
    value: 1,
    writable: true
},

Check out MDN for this method.

writable
true if and only if the value associated with the property may be changed with an assignment operator.
Defaults to false.

How to access property of anonymous type in C#?

If you want a strongly typed list of anonymous types, you'll need to make the list an anonymous type too. The easiest way to do this is to project a sequence such as an array into a list, e.g.

var nodes = (new[] { new { Checked = false, /* etc */ } }).ToList();

Then you'll be able to access it like:

nodes.Any(n => n.Checked);

Because of the way the compiler works, the following then should also work once you have created the list, because the anonymous types have the same structure so they are also the same type. I don't have a compiler to hand to verify this though.

nodes.Add(new { Checked = false, /* etc */ });

Facebook page automatic "like" URL (for QR Code)

For a hyperlink just use www.facebook.com/++page ID++/like

Eg: www.facebook.com/MYPAGEISAWESOME/like

To make it work with m.facebook.com here's what you do:

Open the Facebook page you're looking for then change the URL to the mobile URL ( which is www.m.facebook.com/MYPAGEISAWESOME ).

Now you should see a big version of the mobile Facebook page. Copy the target URL of the like button.

Pop that URL into the QR generator to make a "scan to like" barcode. This will open the m.Facebook page in the browser of most mobiles directly from the QR reader. If they are not logged into Facebook then they will be prompted to log in and then click 'like'. If logged in, it will auto like.

Hope this helps!

Also, definitely include something with a "click here/scan here to like us on Facebook"

How can I export tables to Excel from a webpage

   function normalexport() {

       try {
           var i;
           var j;
           var mycell;
           var tableID = "tblInnerHTML";
           var drop = document.getElementById('<%= ddl_sections.ClientID %>');
           var objXL = new ActiveXObject("Excel.Application");
           var objWB = objXL.Workbooks.Add();
           var objWS = objWB.ActiveSheet;
           var str = filterNum(drop.options[drop.selectedIndex].text);
           objWB.worksheets("Sheet1").activate; //activate dirst worksheet
           var XlSheet = objWB.activeSheet; //activate sheet
           XlSheet.Name = str; //rename


           for (i = 0; i < document.getElementById("ctl00_ContentPlaceHolder1_1").rows.length - 1; i++) {
               for (j = 0; j < document.getElementById("ctl00_ContentPlaceHolder1_1").rows(i).cells.length; j++) {
                   mycell = document.getElementById("ctl00_ContentPlaceHolder1_1").rows(i).cells(j);

                   objWS.Cells(i + 1, j + 1).Value = mycell.innerText;

                   //                                                objWS.Cells(i + 1, j + 1).style.backgroundColor = mycell.style.backgroundColor;
               }
           }

           objWS.Range("A1", "L1").Font.Bold = true;
           //                objWS.Range("A1", "L1").Font.ColorIndex = 2;
           //                 objWS.Range("A1", "Z1").Interior.ColorIndex = 47;

           objWS.Range("A1", "Z1").EntireColumn.AutoFit();

           //objWS.Range("C1", "C1").ColumnWidth = 50;

           objXL.Visible = true;

       } catch (err) {
           alert("Error. Scripting for ActiveX might be disabled")
           return
       }
       idTmr = window.setInterval("Cleanup();", 1);

   }


   function filterNum(str) {

       return str.replace(/[ / ]/g, '');
   }

Uncaught TypeError: data.push is not a function

one things to remember push work only with array[] not object{}.

if you want to add Like object o inside inside n


_x000D_
_x000D_
a={ b:"c",
D:"e",
F: {g:"h",
I:"j",
k:{ l:"m"
}}
}

a.F.k.n = { o: "p" };
a.F.k.n = { o: "p" };
console.log(a);
_x000D_
_x000D_
_x000D_

Parenthesis/Brackets Matching using Stack algorithm

public String checkString(String value) {
    Stack<Character> stack = new Stack<>();
    char topStackChar = 0;
    for (int i = 0; i < value.length(); i++) {
        if (!stack.isEmpty()) {
            topStackChar = stack.peek();
        }
        stack.push(value.charAt(i));
        if (!stack.isEmpty() && stack.size() > 1) {
            if ((topStackChar == '[' && stack.peek() == ']') ||
                    (topStackChar == '{' && stack.peek() == '}') ||
                    (topStackChar == '(' && stack.peek() == ')')) {
                stack.pop();
                stack.pop();
            }
        }
    }
    return stack.isEmpty() ? "YES" : "NO";
}

multi line comment vb.net in Visual studio 2010

The only way I could do it in VS 2010 IDE was to highlight the block of code and hit ctrl-E and then C

Firebase cloud messaging notification not received by device

In my case, I manually killed some google play services and forgot about it.

Later, I have to restart the device, after that I can receive notification without any problem.

Passing arguments forward to another javascript function

The explanation that none of the other answers supplies is that the original arguments are still available, but not in the original position in the arguments object.

The arguments object contains one element for each actual parameter provided to the function. When you call a you supply three arguments: the numbers 1, 2, and, 3. So, arguments contains [1, 2, 3].

function a(args){
    console.log(arguments) // [1, 2, 3]
    b(arguments);
}

When you call b, however, you pass exactly one argument: a's arguments object. So arguments contains [[1, 2, 3]] (i.e. one element, which is a's arguments object, which has properties containing the original arguments to a).

function b(args){
    // arguments are lost?
    console.log(arguments) // [[1, 2, 3]]
}

a(1,2,3);

As @Nick demonstrated, you can use apply to provide a set arguments object in the call.

The following achieves the same result:

function a(args){
    b(arguments[0], arguments[1], arguments[2]); // three arguments
}

But apply is the correct solution in the general case.

Make child div stretch across width of page

you can pull it out of the flow by setting position:absolute on it, but you'll have different display issues to deal with. Or you can explicitly set the width to > 960.

Error: Cannot access file bin/Debug/... because it is being used by another process

i found Cody Gray 's answer partially helpful, in that it did direct me to the real source of my problem which some of you may also be experiencing: visual studio's test execution stays open by default and maintains a lock on the files.

To stop that predominantly useless behaviour, follow the instructions from https://connect.microsoft.com/VisualStudio/feedback/details/771994/vstest-executionengine-x86-exe-32-bit-not-closing-vs2012-11-0-50727-1-rtmrel

Uncheck Test menu -> Test Settings -> "Keep Test Execution Engine Running"

CSS - center two images in css side by side

I've just done this for a project, and achieved it by using the h6 tag which I wasn't using for anything else:

in html code:

<h6><img alt="small drawing" src="../Images/image1.jpg" width="50%"/> <img alt="small drawing" src="../Images/image2.jpg" width="50%"/><br/>Optional caption text</h6>

The space between the image tags puts a vertical gap between the images. The width argument in each img tag is optional, but it neatly sizes the images to fill the width of the page. Notice that each image must be set to take up only 50% of the width. (Or 33% if you're using 3 images.) The width argument must come after the alt and src arguments or it won't work.

in css code:

/* h6: set presentation of images */
h6
  {
  font-family: "Franklin Gothic Demi", serif;
  font-size: 1.0em;
  font-weight: normal;
  line-height: 1.25em;
  text-align: center;
  }

The text items set the look of the caption text, and the text-align property centers both the images and the caption text.

Bootstrap 4: Multilevel Dropdown Inside Navigation

This one works on Bootstrap 4.3.1.

Jsfiddle: https://jsfiddle.net/ko6L31w4/1/

The HTML code might be a little bit messy because I create a slightly complex dropdown menu for comprehensive test, otherwise everything is pretty straight forward.

Js includes fewer ways to collapse opened dropdowns and CSS only includes minimal styles for full functionalities.

_x000D_
_x000D_
$(function() {_x000D_
  $("ul.dropdown-menu [data-toggle='dropdown']").on("click", function(event) {_x000D_
    event.preventDefault();_x000D_
    event.stopPropagation();_x000D_
    _x000D_
    //method 1: remove show from sibilings and their children under your first parent_x000D_
    _x000D_
/*   if (!$(this).next().hasClass('show')) {_x000D_
        _x000D_
          $(this).parents('.dropdown-menu').first().find('.show').removeClass('show');_x000D_
       }  */     _x000D_
     _x000D_
     _x000D_
    //method 2: remove show from all siblings of all your parents_x000D_
    $(this).parents('.dropdown-submenu').siblings().find('.show').removeClass("show");_x000D_
    _x000D_
    $(this).siblings().toggleClass("show");_x000D_
    _x000D_
    _x000D_
    //collapse all after nav is closed_x000D_
    $(this).parents('li.nav-item.dropdown.show').on('hidden.bs.dropdown', function(e) {_x000D_
      $('.dropdown-submenu .show').removeClass("show");_x000D_
    });_x000D_
_x000D_
  });_x000D_
});
_x000D_
.dropdown-submenu {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.dropdown-submenu>.dropdown-menu {_x000D_
  top: 0;_x000D_
  left: 100%;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>_x000D_
_x000D_
_x000D_
<nav class="navbar navbar-expand-md navbar-light bg-white py-3 shadow-sm">_x000D_
  <div class="container-fluid">_x000D_
    <a href="#" class="navbar-brand font-weight-bold">Multilevel Dropdown</a>_x000D_
    _x000D_
  <button type="button" data-toggle="collapse" data-target="#navbarContent" aria-controls="navbars" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler">_x000D_
    <span class="navbar-toggler-icon"></span>_x000D_
  </button>_x000D_
_x000D_
_x000D_
  <div id="navbarContent" class="collapse navbar-collapse">_x000D_
      <ul class="navbar-nav mr-auto">_x000D_
      _x000D_
        <!-- nav dropdown -->_x000D_
        <li class="nav-item dropdown">_x000D_
        _x000D_
          <a href="#" data-toggle="dropdown" class="nav-link dropdown-toggle">Dropdown</a>_x000D_
          <ul class="dropdown-menu">_x000D_
            _x000D_
            <li><a href="#" class="dropdown-item">Some action</a></li>_x000D_
            _x000D_
            <!-- lvl 1 dropdown -->_x000D_
            <li class="dropdown-submenu">_x000D_
              <a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 1</a>_x000D_
              <ul class="dropdown-menu">_x000D_
                <li><a href="#" class="dropdown-item">level 2</a></li>_x000D_
                _x000D_
                <!-- lvl 2 dropdown -->_x000D_
                <li class="dropdown-submenu">_x000D_
                  <a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 2</a>_x000D_
                  <ul class="dropdown-menu">_x000D_
                    <li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
                    _x000D_
                    <!-- lvl 3 dropdown --> _x000D_
                    <li class="dropdown-submenu">_x000D_
                      <a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 3</a>_x000D_
                      <ul class="dropdown-menu">_x000D_
                        <li><a href="#" class="dropdown-item">level 4</a></li>_x000D_
                      </ul>_x000D_
                    </li>_x000D_
                    _x000D_
                  </ul>_x000D_
                </li>_x000D_
_x000D_
                <li><a href="#" class="dropdown-item">level 2</a></li>_x000D_
                <li><a href="#" class="dropdown-item">level 2</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
            _x000D_
            <li><a href="#" class="dropdown-item">Some other action</a></li>_x000D_
            _x000D_
            <li class="dropdown-submenu">_x000D_
              <a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 1</a>_x000D_
              <ul class="dropdown-menu">_x000D_
                _x000D_
                <li class="dropdown-submenu">_x000D_
                  <a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 2</a>_x000D_
                  <ul class="dropdown-menu">_x000D_
                    <li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
                    <li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
                  </ul>_x000D_
                </li>_x000D_
                _x000D_
                <li class="dropdown-submenu">_x000D_
                  <a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 2</a>_x000D_
                  <ul class="dropdown-menu">_x000D_
                    <li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
                    <li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
                  </ul>_x000D_
                </li>_x000D_
_x000D_
                <li><a href="#" class="dropdown-item">level 2</a></li>_x000D_
                _x000D_
                                <li class="dropdown-submenu">_x000D_
                  <a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 2</a>_x000D_
                  <ul class="dropdown-menu">_x000D_
                    <li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
                    <li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
                  </ul>_x000D_
                </li>_x000D_
                _x000D_
                <li><a href="#" class="dropdown-item">level 2</a></li>_x000D_
              </ul>_x000D_
            </li>  _x000D_
          </ul>_x000D_
        </li>_x000D_
_x000D_
        <li class="nav-item"><a href="#" class="nav-link">About</a></li>_x000D_
        <li class="nav-item"><a href="#" class="nav-link">Services</a></li>_x000D_
        <li class="nav-item"><a href="#" class="nav-link">Contact</a></li>_x000D_
      </ul>_x000D_
    </div>_x000D_
  </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

What are queues in jQuery?

To understand queue method, you have to understand how jQuery does animation. If you write multiple animate method calls one after the other, jQuery creates an 'internal' queue and adds these method calls to it. Then it runs those animate calls one by one.

Consider following code.

function nonStopAnimation()
{
    //These multiple animate calls are queued to run one after
    //the other by jQuery.
    //This is the reason that nonStopAnimation method will return immeidately
    //after queuing these calls. 
    $('#box').animate({ left: '+=500'}, 4000);
    $('#box').animate({ top: '+=500'}, 4000);
    $('#box').animate({ left: '-=500'}, 4000);

    //By calling the same function at the end of last animation, we can
    //create non stop animation. 
    $('#box').animate({ top: '-=500'}, 4000 , nonStopAnimation);
}

The 'queue'/'dequeue' method gives you control over this 'animation queue'.

By default the animation queue is named 'fx'. I have created a sample page here which has various examples which will illustrate how the queue method could be used.

http://jsbin.com/zoluge/1/edit?html,output

Code for above sample page:

$(document).ready(function() {
    $('#nonStopAnimation').click(nonStopAnimation);

    $('#stopAnimationQueue').click(function() {
        //By default all animation for particular 'selector'
        //are queued in queue named 'fx'.
        //By clearning that queue, you can stop the animation.
        $('#box').queue('fx', []);
    });

    $('#addAnimation').click(function() {
        $('#box').queue(function() {
            $(this).animate({ height : '-=25'}, 2000);
            //De-queue our newly queued function so that queues
            //can keep running.
            $(this).dequeue();
        });
    });

    $('#stopAnimation').click(function() {
        $('#box').stop();
    });

    setInterval(function() {
        $('#currentQueueLength').html(
         'Current Animation Queue Length for #box ' + 
          $('#box').queue('fx').length
        );
    }, 2000);
});

function nonStopAnimation()
{
    //These multiple animate calls are queued to run one after
    //the other by jQuery.
    $('#box').animate({ left: '+=500'}, 4000);
    $('#box').animate({ top: '+=500'}, 4000);
    $('#box').animate({ left: '-=500'}, 4000);
    $('#box').animate({ top: '-=500'}, 4000, nonStopAnimation);
}

Now you may ask, why should I bother with this queue? Normally, you wont. But if you have a complicated animation sequence which you want to control, then queue/dequeue methods are your friend.

Also see this interesting conversation on jQuery group about creating a complicated animation sequence.

http://groups.google.com/group/jquery-en/browse_thread/thread/b398ad505a9b0512/f4f3e841eab5f5a2?lnk=gst

Demo of the animation:

http://www.exfer.net/test/jquery/tabslide/

Let me know if you still have questions.

How to get response as String using retrofit without using GSON or any other library in android

** Update ** A scalars converter has been added to retrofit that allows for a String response with less ceremony than my original answer below.

Example interface --

public interface GitHubService {
    @GET("/users/{user}")
    Call<String> listRepos(@Path("user") String user);
}

Add the ScalarsConverterFactory to your retrofit builder. Note: If using ScalarsConverterFactory and another factory, add the scalars factory first.

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(ScalarsConverterFactory.create())
    // add other factories here, if needed.
    .build();

You will also need to include the scalars converter in your gradle file --

implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'

--- Original Answer (still works, just more code) ---

I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject land. I suspect your specific problem might be better solved using a custom gson TypeAdapter or a retrofit Converter if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -

First, if you are using Retrofit 2, you should start using the Call API. Instead of sending an object to convert as the type parameter, use ResponseBody from okhttp --

public interface GitHubService {
    @GET("/users/{user}")
    Call<ResponseBody> listRepos(@Path("user") String user);
}

then you can create and execute your call --

GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Response<ResponseBody> response) {
        try {
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(Throwable t) {
        e.printStackTrace();
    }
});

Note The code above calls string() on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream() instead. See the ResponseBody docs.

Django CharField vs TextField

CharField has max_length of 255 characters while TextField can hold more than 255 characters. Use TextField when you have a large string as input. It is good to know that when the max_length parameter is passed into a TextField it passes the length validation to the TextArea widget.

How to set custom location for local installation of npm package?

On Windows 7 for example, the following set of commands/operations could be used.

Create an personal environment variable, double backslashes are mandatory:

  • Variable name: %NPM_HOME%
  • Variable value: C:\\SomeFolder\\SubFolder\\

Now, set the config values to the new folders (examplary file names):

  • Set the npm folder

npm config set prefix "%NPM_HOME%\\npm"

  • Set the npm-cache folder

npm config set cache "%NPM_HOME%\\npm-cache"

  • Set the npm temporary folder

npm config set tmp "%NPM_HOME%\\temp"

Optionally, you can purge the contents of the original folders before the config is changed.

  • Delete the npm-cache npm cache clear

  • List the npm modules npm -g ls

  • Delete the npm modules npm -g rm name_of_package1 name_of_package2

Required attribute on multiple checkboxes with the same name?

You can make it with jQuery a less lines:

$(function(){

    var requiredCheckboxes = $(':checkbox[required]');

    requiredCheckboxes.change(function(){

        if(requiredCheckboxes.is(':checked')) {
            requiredCheckboxes.removeAttr('required');
        }

        else {
            requiredCheckboxes.attr('required', 'required');
        }
    });

});

With $(':checkbox[required]') you select all checkboxes with the attribute required, then, with the .change method applied to this group of checkboxes, you can execute the function you want when any item of this group changes. In this case, if any of the checkboxes is checked, I remove the required attribute for all of the checkboxes that are part of the selected group.

I hope this helps.

Farewell.

Convert IQueryable<> type object to List<T> type?

Add the following:

using System.Linq

...and call ToList() on the IQueryable<>.

How can I access and process nested objects, arrays or JSON?

My stringdata is coming from PHP file but still, I indicate here in var. When i directly take my json into obj it will nothing show thats why i put my json file as

var obj=JSON.parse(stringdata); so after that i get message obj and show in alert box then I get data which is json array and store in one varible ArrObj then i read first object of that array with key value like this ArrObj[0].id

     var stringdata={
        "success": true,
        "message": "working",
        "data": [{
                  "id": 1,
                  "name": "foo"
         }]
      };

                var obj=JSON.parse(stringdata);
                var key = "message";
                alert(obj[key]);
                var keyobj = "data";
                var ArrObj =obj[keyobj];

                alert(ArrObj[0].id);

Android: upgrading DB version and adding new table

Your code looks correct. My suggestion is that the database already thinks it's upgraded. If you executed the project after incrementing the version number, but before adding the execSQL call, the database on your test device/emulator may already believe it's at version 2.

A quick way to verify this would be to change the version number to 3 -- if it upgrades after that, you know it was just because your device believed it was already upgraded.

There was no endpoint listening at (url) that could accept the message

I changed my website and app bindings to a new port and it worked for me. This error might occur because the port the website uses is not available. Hence sometimes the problem is solved by simply restarting the machine

-Edit-

Alternative (and easier) solution:reference

  1. Get PID of process which is using the port CMD command- netstat -aon | findstr 0.0:80

Command 1

  1. Use the PID to get process name -

tasklist /FI "PID eq "

Command2

  1. Open task manager, find this process and stop it.

(Note- Make sure you do not stop Net.tcp services)

Laravel Carbon subtract days from current date

You can always use strtotime to minus the number of days from the current date:

$users = Users::where('status_id', 'active')
           ->where( 'created_at', '>', date('Y-m-d', strtotime("-30 days"))
           ->get();

What is the string length of a GUID?

Binary strings store raw-byte data, whilst character strings store text. Use binary data when storing hexi-decimal values such as SID, GUID and so on. The uniqueidentifier data type contains a globally unique identifier, or GUID. This value is derived by using the NEWID() function to return a value that is unique to all objects. It's stored as a binary value but it is displayed as a character string.

Here is an example.

USE AdventureWorks2008R2;
GO
CREATE TABLE MyCcustomerTable
(
    user_login   varbinary(85) DEFAULT SUSER_SID()
    ,data_value   varbinary(1)
);
GO

INSERT MyCustomerTable (data_value)
    VALUES (0x4F);
GO

Applies to: SQL Server The following example creates the cust table with a uniqueidentifier data type, and uses NEWID to fill the table with a default value. In assigning the default value of NEWID(), each new and existing row has a unique value for the CustomerID column.

-- Creating a table using NEWID for uniqueidentifier data type.  
CREATE TABLE cust  
(  
 CustomerID uniqueidentifier NOT NULL  
   DEFAULT newid(),  
 Company varchar(30) NOT NULL,  
 ContactName varchar(60) NOT NULL,   
 Address varchar(30) NOT NULL,   
 City varchar(30) NOT NULL,  
 StateProvince varchar(10) NULL,  
 PostalCode varchar(10) NOT NULL,   
 CountryRegion varchar(20) NOT NULL,   
 Telephone varchar(15) NOT NULL,  
 Fax varchar(15) NULL  
);  
GO  
-- Inserting 5 rows into cust table.  
INSERT cust  
(CustomerID, Company, ContactName, Address, City, StateProvince,   
 PostalCode, CountryRegion, Telephone, Fax)  
VALUES  
 (NEWID(), 'Wartian Herkku', 'Pirkko Koskitalo', 'Torikatu 38', 'Oulu', NULL,  
 '90110', 'Finland', '981-443655', '981-443655')  
,(NEWID(), 'Wellington Importadora', 'Paula Parente', 'Rua do Mercado, 12', 'Resende', 'SP',  
 '08737-363', 'Brasil', '(14) 555-8122', '')  
,(NEWID(), 'Cactus Comidas para Ilevar', 'Patricio Simpson', 'Cerrito 333', 'Buenos Aires', NULL,   
 '1010', 'Argentina', '(1) 135-5555', '(1) 135-4892')  
,(NEWID(), 'Ernst Handel', 'Roland Mendel', 'Kirchgasse 6', 'Graz', NULL,  
 '8010', 'Austria', '7675-3425', '7675-3426')  
,(NEWID(), 'Maison Dewey', 'Catherine Dewey', 'Rue Joseph-Bens 532', 'Bruxelles', NULL,  
 'B-1180', 'Belgium', '(02) 201 24 67', '(02) 201 24 68');  
GO

Windows XP or later Windows: How can I run a batch file in the background with no window displayed?

In the other question I suggested autoexnt. That is also possible in this situation. Just set the service to run manually (ie not automatic at startup). When you want to run your batch, modify the autoexnt.bat file to call the batch file you want, and start the autoexnt service.

The batchfile to start this, can look like this (untested):

echo call c:\path\to\batch.cmd %* > c:\windows\system32\autoexnt.bat
net start autoexnt

Note that batch files started this way run as the system user, which means you do not have access to network shares automatically. But you can use net use to connect to a remote server.

You have to download the Windows 2003 Resource Kit to get it. The Resource Kit can also be installed on other versions of windows, like Windows XP.

App.Config file in console application C#

use this

System.Configuration.ConfigurationSettings.AppSettings.Get("Keyname")

Getting a list item by index

You can use the ElementAt extension method on the list.

For example:

// Get the first item from the list

using System.Linq;

var myList = new List<string>{ "Yes", "No", "Maybe"};
var firstItem = myList.ElementAt(0);

// Do something with firstItem

How can I access global variable inside class in Python

By declaring it global inside the function that accesses it:

g_c = 0

class TestClass():
    def run(self):
        global g_c
        for i in range(10):
            g_c = 1
            print(g_c)

The Python documentation says this, about the global statement:

The global statement is a declaration which holds for the entire current code block.

Using 'sudo apt-get install build-essentials'

Try 'build-essential' instead.

What are Covering Indexes and Covered Queries in SQL Server?

a covering index is the one which gives every required column and in which SQL server don't have hop back to the clustered index to find any column. This is achieved using non-clustered index and using INCLUDE option to cover columns. Non-key columns can be included only in non-clustered indexes. Columns can’t be defined in both the key column and the INCLUDE list. Column names can’t be repeated in the INCLUDE list. Non-key columns can be dropped from a table only after the non-key index is dropped first. Please see details here

Resize UIImage by keeping Aspect ratio and width

If somebody needs this solution in Swift 5:

private func resizeImage(image: UIImage, newHeight: CGFloat) -> UIImage {
    
    let scale = newHeight / image.size.height
    let newWidth = image.size.width * scale
    UIGraphicsBeginImageContext(CGSize(width:newWidth, height:newHeight))
    image.draw(in:CGRect(x:0, y:0, width:newWidth, height:newHeight))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage
}

Find difference between timestamps in seconds in PostgreSQL

select age(timestamp_A, timestamp_B)

Answering to Igor's comment:

select age('2013-02-28 11:01:28'::timestamp, '2011-12-31 11:00'::timestamp);
              age              
-------------------------------
 1 year 1 mon 28 days 00:01:28

python and sys.argv

BTW you can pass the error message directly to sys.exit:

if len(sys.argv) < 2:
    sys.exit('Usage: %s database-name' % sys.argv[0])

if not os.path.exists(sys.argv[1]):
    sys.exit('ERROR: Database %s was not found!' % sys.argv[1])

Session 'app': Error Launching activity

I got the same error. This issue was caused by uninstalling the app from the device (uninstalled from only 1 user)

Solved by logging into the other user and uninstall the app from there.

and it solved.

What is the difference between substr and substring?

substring(startIndex, endIndex(not included))

substr(startIndex, how many characters)

const string = 'JavaScript';

console.log('substring(1,2)', string.substring(1,2)); // a
console.log('substr(1,2)', string.substr(1,2)); // av

How to remove the first character of string in PHP?

The code works well for me.

$str = substr($str ,-(strlen($str)-1));

Maybe, contribute with answers too.

Enums in Javascript with ES6

Update 11.05.2020:
Modified to include static fields and methods to closer replicate "true" enum behavior.

If you're planning on updating I would recommend trying to use what I call an "Enum Class" (barring any browser or runtime env limitations you can't accept). It's basically a very simple and clean class that uses private fields and limited accessors to simulate the behavior of an enum. This is something I sometimes do in C# when I want to build more functionality into an enum.

I realize private class fields are still experimental at this point but it seems to work for the purposes of creating a class with immutable fields/properties. Browser support is decent as well. The only "major" browsers that don't support it are Firefox (which I'm sure they will soon) and IE (who cares).

DISCLAIMER:
I am not a developer. I just put this together to solve the limitations of nonexistent enums in JS when I was working on a personal project.

Sample Class

class Colors {
    // Private Fields
    static #_RED = 0;
    static #_GREEN = 1;
    static #_BLUE = 2;

    // Accessors for "get" functions only (no "set" functions)
    static get RED() { return this.#_RED; }
    static get GREEN() { return this.#_GREEN; }
    static get BLUE() { return this.#_BLUE; }
}

You should now be able to call your enums directly.

Colors.RED; // 0
Colors.GREEN; // 1
Colors.BLUE; // 2

The combination of using private fields and limited accessors means that the existing enum values are well protected (they're essentially constants now).

Colors.RED = 10 // Colors.RED is still 0
Colors._RED = 10 // Colors.RED is still 0
Colors.#_RED = 10 // Colors.RED is still 0

How do I add a simple jQuery script to WordPress?

**#Method 1:**Try to put your jquery code in a separate js file.

Now register that script in functions.php file.

function add_my_script() {
    wp_enqueue_script(
      'custom-script', get_template_directory_uri() . '/js/your-script-name.js', 
        array('jquery') 
    );
}
add_action( 'wp_enqueue_scripts', 'add_my_script' );

Now you are done.

Registering script in functions has it benefits as it comes in <head> section when page loads thus it is a part of header.php always. So you don't have to repeat your code each time you write a new html content.

#Method 2: put the script code inside the page body under <script> tag. Then you don't have to register it in functions.

What is the difference between HTTP_HOST and SERVER_NAME in PHP?

Please note that if you want to use IPv6, you probably want to use HTTP_HOST rather than SERVER_NAME . If you enter http://[::1]/ the environment variables will be the following:

HTTP_HOST = [::1]
SERVER_NAME = ::1

This means, that if you do a mod_rewrite for example, you might get a nasty result. Example for a SSL redirect:

# SERVER_NAME will NOT work - Redirection to https://::1/
RewriteRule .* https://%{SERVER_NAME}/

# HTTP_HOST will work - Redirection to https://[::1]/
RewriteRule .* https://%{HTTP_HOST}/

This applies ONLY if you access the server without an hostname.

How to get the category title in a post in Wordpress?

You can use

<?php the_category(', '); ?>

which would output them in a comma separated list.

You can also do the same for tags as well:

<?php the_tags('<em>:</em>', ', ', ''); ?>

How to set MimeBodyPart ContentType to "text/html"?

Try with this:

msg.setContent(email.getBody(), "text/html; charset=ISO-8859-1");

Using OpenGl with C#?

I would also recommend the Tao Framework. But one additional note:

Take a look at these tutorials: http://www.taumuon.co.uk/jabuka/

How to disable submit button once it has been clicked?

In my case this was needed.

Disable submit button on form submit

It works fine in Internet Explorer and Firefox without it, but it did not work in Google Chrome.

The problem is that you are disabling the button before it can actually trigger the submit event.

How to use code to open a modal in Angular 2?

Simply, npm install --save @types/bootstrap try to match typing version with your bootstrap version. E.g. you have Bootstrap 4.3.1 then npm install --save @types/[email protected]

How do I reset the scale/zoom of a web app on an orientation change on the iPhone?

If you have the width set in the viewport :

<meta name = "viewport" content = "width=device-width; initial-scale=1.0;
 maximum-scale=1.0;" />

And then change the orientation it will randomly zoom in sometimes (especially if you are dragging on the screen) to fix this don't set a width here I used :

<meta id="viewport" name="viewport" content="initial-scale=1.0; user-scalable=0;
minimum-scale=1.0; maximum-scale=1.0" />

This fixes the zoom whatever happens then you can use either window.onorientationchange event or if you want it to be platform independant (handy for testing) the window.innerWidth method.

TypeScript function overloading

As a heads up to others, I've oberserved that at least as manifested by TypeScript compiled by WebPack for Angular 2, you quietly get overWRITTEN instead of overLOADED methods.

myComponent {
  method(): { console.info("no args"); },
  method(arg): { console.info("with arg"); }
}

Calling:

myComponent.method()

seems to execute the method with arguments, silently ignoring the no-arg version, with output:

with arg

Cannot read property 'push' of undefined when combining arrays

In most cases you have to initialize the array,

let list: number[] = [];

How does lock work exactly?

The performance impact depends on the way you lock. You can find a good list of optimizations here: http://www.thinkingparallel.com/2007/07/31/10-ways-to-reduce-lock-contention-in-threaded-programs/

Basically you should try to lock as little as possible, since it puts your waiting code to sleep. If you have some heavy calculations or long lasting code (e.g. file upload) in a lock it results in a huge performance loss.

Variable might not have been initialized error

You declared them, but you didn't initialize them with a value. Add something like this:

int a = 0;

Chrome extension: accessing localStorage in content script

Update 2016:

Google Chrome released the storage API: http://developer.chrome.com/extensions/storage.html

It is pretty easy to use like the other Chrome APIs and you can use it from any page context within Chrome.

    // Save it using the Chrome extension storage API.
    chrome.storage.sync.set({'foo': 'hello', 'bar': 'hi'}, function() {
      console.log('Settings saved');
    });

    // Read it using the storage API
    chrome.storage.sync.get(['foo', 'bar'], function(items) {
      message('Settings retrieved', items);
    });

To use it, make sure you define it in the manifest:

    "permissions": [
      "storage"
    ],

There are methods to "remove", "clear", "getBytesInUse", and an event listener to listen for changed storage "onChanged"

Using native localStorage (old reply from 2011)

Content scripts run in the context of webpages, not extension pages. Therefore, if you're accessing localStorage from your contentscript, it will be the storage from that webpage, not the extension page storage.

Now, to let your content script to read your extension storage (where you set them from your options page), you need to use extension message passing.

The first thing you do is tell your content script to send a request to your extension to fetch some data, and that data can be your extension localStorage:

contentscript.js

chrome.runtime.sendMessage({method: "getStatus"}, function(response) {
  console.log(response.status);
});

background.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getStatus")
      sendResponse({status: localStorage['status']});
    else
      sendResponse({}); // snub them.
});

You can do an API around that to get generic localStorage data to your content script, or perhaps, get the whole localStorage array.

I hope that helped solve your problem.

To be fancy and generic ...

contentscript.js

chrome.runtime.sendMessage({method: "getLocalStorage", key: "status"}, function(response) {
  console.log(response.data);
});

background.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getLocalStorage")
      sendResponse({data: localStorage[request.key]});
    else
      sendResponse({}); // snub them.
});

How to select last two characters of a string

You can pass a negative index to .slice(). That will indicate an offset from the end of the set.

var member = "my name is Mate";

var last2 = member.slice(-2);

alert(last2); // "te"

Bulk Insert Correctly Quoted CSV File in SQL Server

You could also look at using OpenRowSet with the CSV text file data provider.

This should be possible with any version of SQL Server >= 2005 although you need to enable the feature.

http://social.msdn.microsoft.com/forums/en-US/sqldataaccess/thread/5869d247-f0a0-4224-80b3-ff2e414be402

How to calculate the time interval between two time strings

Take a look at the datetime module and the timedelta objects. You should end up constructing a datetime object for the start and stop times, and when you subtract them, you get a timedelta.

String.Replace ignoring case

(Edited: wasn't aware of the `naked link' problem, sorry about that)

Taken from here:

string myString = "find Me and replace ME";
string strReplace = "me";
myString = Regex.Replace(myString, "me", strReplace, RegexOptions.IgnoreCase);

Seems you are not the first to complain of the lack of case insensitive string.Replace.

How to convert a Drawable to a Bitmap?

Maybe this will help someone...

From PictureDrawable to Bitmap, use:

private Bitmap pictureDrawableToBitmap(PictureDrawable pictureDrawable){ 
    Bitmap bmp = Bitmap.createBitmap(pictureDrawable.getIntrinsicWidth(), pictureDrawable.getIntrinsicHeight(), Config.ARGB_8888); 
    Canvas canvas = new Canvas(bmp); 
    canvas.drawPicture(pictureDrawable.getPicture()); 
    return bmp; 
}

... implemented as such:

Bitmap bmp = pictureDrawableToBitmap((PictureDrawable) drawable);

How to fix the "java.security.cert.CertificateException: No subject alternative names present" error?

This is an old question, yet I had the same problem when moving from JDK 1.8.0_144 to jdk 1.8.0_191

We found a hint in the changelog:

Changelog

we added the following additional system property, which helped in our case to solve this issue:

-Dcom.sun.jndi.ldap.object.disableEndpointIdentification=true

Android Studio - Auto complete and other features not working

If nothing works (like happened with me ) go to your user profile in windows at %userprofile% . You will find folders there (hidden) named with the version of the android studio you are using and prefixed with a dot.

like .AndroidStudio3.1. Just delete that .

download and install visual studio 2008

Try this one: http://www.asp.net/downloads/essential This has web developer and VS2008 express

CSS values using HTML5 data attribute

As of today, you can read some values from HTML5 data attributes in CSS3 declarations. In CaioToOn's fiddle the CSS code can use the data properties for setting the content.

Unfortunately it is not working for the width and height (tested in Google Chrome 35, Mozilla Firefox 30 & Internet Explorer 11).

But there is a CSS3 attr() Polyfill from Fabrice Weinberg which provides support for data-width and data-height. You can find the GitHub repo to it here: cssattr.js.

Convert double to Int, rounded down

Another option either using Double or double is use Double.valueOf(double d).intValue();. Simple and clean

XPath - Selecting elements that equal a value

The XPath spec. defines the string value of an element as the concatenation (in document order) of all of its text-node descendents.

This explains the "strange results".

"Better" results can be obtained using the expressions below:

//*[text() = 'qwerty']

The above selects every element in the document that has at least one text-node child with value 'qwerty'.

//*[text() = 'qwerty' and not(text()[2])]

The above selects every element in the document that has only one text-node child and its value is: 'qwerty'.

App.settings - the Angular way?

I find this Angular How-to: Editable Config Files from Microsoft Dev blogs being the best solution. You can configure dev build settings or prod build settings.

How to find whether a ResultSet is empty or not in Java?

if (rs == null || !rs.first()) {
    //empty
} else {
    //not empty
}

Note that after this method call, if the resultset is not empty, it is at the beginning.

Nested routes with react router v4 / v5

I succeeded in defining nested routes by wrapping with Switch and define nested route before than root route.

<BrowserRouter>
  <Switch>
    <Route path="/staffs/:id/edit" component={StaffEdit} />
    <Route path="/staffs/:id" component={StaffShow} />
    <Route path="/staffs" component={StaffIndex} />
  </Switch>
</BrowserRouter>

Reference: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Switch.md

Get the client IP address using PHP

It also works fine for internal IP addresses:

 function get_client_ip()
 {
      $ipaddress = '';
      if (getenv('HTTP_CLIENT_IP'))
          $ipaddress = getenv('HTTP_CLIENT_IP');
      else if(getenv('HTTP_X_FORWARDED_FOR'))
          $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
      else if(getenv('HTTP_X_FORWARDED'))
          $ipaddress = getenv('HTTP_X_FORWARDED');
      else if(getenv('HTTP_FORWARDED_FOR'))
          $ipaddress = getenv('HTTP_FORWARDED_FOR');
      else if(getenv('HTTP_FORWARDED'))
          $ipaddress = getenv('HTTP_FORWARDED');
      else if(getenv('REMOTE_ADDR'))
          $ipaddress = getenv('REMOTE_ADDR');
      else
          $ipaddress = 'UNKNOWN';

      return $ipaddress;
 }

Prevent flicker on webkit-transition of webkit-transform

I found that applying the -webkit-backface-visibility: hidden; to the translating element and -webkit-transform: translate3d(0,0,0); to all its children, the flicker then disappears

PHP mail function doesn't complete sending of e-mail

Maybe the problem is the configuration of the mail server. To avoid this type of problems or you do not have to worry about the mail server problem, I recommend you use PHPMailer.

It is a plugin that has everything necessary to send mail, and the only thing you have to take into account is to have the SMTP port (Port: 25 and 465), enabled.

require_once 'PHPMailer/PHPMailer.php';
require_once '/servicios/PHPMailer/SMTP.php';
require_once '/servicios/PHPMailer/Exception.php';

$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
try {
    //Server settings
    $mail->SMTPDebug = 0;
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = '[email protected]';
    $mail->Password = 'contrasenia';
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 465;

    // Recipients
    $mail->setFrom('[email protected]', 'my name');
    $mail->addAddress('[email protected]');

    // Attachments
    $mail->addAttachment('optional file');         // Add files, is optional

    // Content
    $mail->isHTML(true);// Set email format to HTML
    $mail->Subject = utf8_decode("subject");
    $mail->Body    = utf8_decode("mail content");
    $mail->AltBody = '';
    $mail->send();
}
catch (Exception $e) {
    $error = $mail->ErrorInfo;
}

Exit/save edit to sudoers file? Putty SSH

#UBUNTU20

if you are opening this file as root, then type

root# visudo

the file will be opened, go to the line where you want to add/modifiy anything simply without any insert or i button pressed.

press ctrl + O
press ctrl + x
press enter

Laravel 5 How to switch from Production mode

What you could also have a look at is the exposed method Application->loadEnvironmentFrom($file)

I needed one application to run on multiple subdomains. So in bootstrap/app.php I added something like:

$envFile = '.env';
// change $envFile conditionally here
$app->loadEnvironmentFrom($envFile);

get all keys set in memcached

If you have PHP & PHP-memcached installed, you can run

$ php -r '$c = new Memcached(); $c->addServer("localhost", 11211); var_dump( $c->getAllKeys() );'

unbound method f() must be called with fibo_ instance as first argument (got classobj instance instead)

fibo = f.fibo references the class itself. You probably wanted fibo = f.fibo() (note the parentheses) to make an instance of the class, after which fibo.f() should succeed correctly.

f.fibo.f() fails because you are essentially calling f(self, a=0) without supplying self; self is "bound" automatically when you have an instance of the class.

How to check if a file exists in the Documents directory in Swift?

Swift 4.x version

    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
    let url = NSURL(fileURLWithPath: path)
    if let pathComponent = url.appendingPathComponent("nameOfFileHere") {
        let filePath = pathComponent.path
        let fileManager = FileManager.default
        if fileManager.fileExists(atPath: filePath) {
            print("FILE AVAILABLE")
        } else {
            print("FILE NOT AVAILABLE")
        }
    } else {
        print("FILE PATH NOT AVAILABLE")
    }

Swift 3.x version

    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
    let url = URL(fileURLWithPath: path)

    let filePath = url.appendingPathComponent("nameOfFileHere").path
    let fileManager = FileManager.default
    if fileManager.fileExists(atPath: filePath) {
        print("FILE AVAILABLE")
    } else {
        print("FILE NOT AVAILABLE")
    }

Swift 2.x version, need to use URLByAppendingPathComponent

    let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
    let url = NSURL(fileURLWithPath: path)
    let filePath = url.URLByAppendingPathComponent("nameOfFileHere").path!
    let fileManager = NSFileManager.defaultManager()
    if fileManager.fileExistsAtPath(filePath) {
        print("FILE AVAILABLE")
    } else {
        print("FILE NOT AVAILABLE")
    }

How to loop through a HashMap in JSP?

Depending on what you want to accomplish within the loop, iterate over one of these instead:

  • countries.keySet()
  • countries.entrySet()
  • countries.values()

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined

By reading your exception , It's sure that you forgot to autowire customerService

You should autowire your customerservice .

make following changes in your controller class

@Controller
public class CustomerController{

    @Autowired
    private Customerservice customerservice;
......other code......

}

Again your service implementation class

write

@Service
public class CustomerServiceImpl implements CustomerService {
    @Autowired
    private CustomerDAO customerDAO;
......other code......

.....add transactional methods
}

If you are using hibernate make necessary changes in your applicationcontext xml file(configuration of session factory is needed).

you should autowire sessionFactory set method in your DAO mplementation

please find samle application context :

<?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:annotation-config />
    <context:component-scan base-package="com.sparkle" />
    <!-- Configures the @Controller programming model -->
    <mvc:annotation-driven />

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" 
            p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" p:order="0" />

    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>
    <!-- <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
        p:location="/WEB-INF/jdbc.properties" /> -->

     <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">         
        <list>
            <value>/WEB-INF/jdbc.properties</value>          

        </list>    
    </property>     
    </bean>




    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource"
        p:driverClassName="${jdbc.driverClassName}"
        p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
        p:password="${jdbc.password}" />


    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${jdbc.dialect}</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <tx:annotation-driven />


   <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
          p:sessionFactory-ref="sessionFactory"/>


</beans>

note that i am using jdbc.properties file for jdbc url and driver specification

Git push: "fatal 'origin' does not appear to be a git repository - fatal Could not read from remote repository."

As Matt Clark stated above

However, origin might not be set, so skip the deleting step and simply attempting to add can clear this up.

git remote add origin <"clone">

Where "clone" is simply going into your GitHub repo and copying the "HTTPS clone URL" and pasting into GitBash

React js onClick can't pass value to method

Making alternate attempt to answer OP's question including e.preventDefault() calls:

Rendered link (ES6)

<a href="#link" onClick={(e) => this.handleSort(e, 'myParam')}>

Component Function

handleSort = (e, param) => {
  e.preventDefault();
  console.log('Sorting by: ' + param)
}

Babel command not found

You will need to add quotes around the path to your babel file as below

"./node_modules/.bin/babel" --help

ffmpeg - Converting MOV files to MP4

The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:

ffmpeg -i input.mov -qscale 0 output.mp4

Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0):

ffmpeg -i input.mov -q:v 0 output.mp4

Set Canvas size using javascript

You can also use this script , just change the height and width

<canvas id="Canvas01" width="500" height="400" style="border:2px solid #FF9933; margin-left:10px; margin-top:10px;"></canvas>

   <script>
      var canvas = document.getElementById("Canvas01");
      var ctx = canvas.getContext("2d");

How to resolve this JNI error when trying to run LWJGL "Hello World"?

A CLASSPATH entry is either a directory at the head of a package hierarchy of .class files, or a .jar file. If you're expecting ./lib to include all the .jar files in that directory, it won't. You have to name them explicitly.

Http Get using Android HttpURLConnection

If you just need a very simple call, you can use URL directly:

import java.net.URL;

    new URL("http://wheredatapp.com").openStream();

How do I initialise all entries of a matrix with a specific value?

The ones method is much faster than using repmat:

>> tic; for i = 1:1e6, x=5*ones(10,1); end; toc
Elapsed time is 3.426347 seconds.
>> tic; for i = 1:1e6, y=repmat(5,10,1); end; toc
Elapsed time is 20.603680 seconds. 

And, in my opinion, makes for much more readable code.

DOUBLE vs DECIMAL in MySQL

Actually it's quite different. DOUBLE causes rounding issues. And if you do something like 0.1 + 0.2 it gives you something like 0.30000000000000004. I personally would not trust financial data that uses floating point math. The impact may be small, but who knows. I would rather have what I know is reliable data than data that were approximated, especially when you are dealing with money values.

How to detect orientation change in layout in Android?

Use the onConfigurationChanged method of Activity. See the following code:

@Override
public void onConfigurationChanged(@NotNull Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
    }
}

You also have to edit the appropriate element in your manifest file to include the android:configChanges Just see the code below:

<activity android:name=".MyActivity"
          android:configChanges="orientation|keyboardHidden"
          android:label="@string/app_name">

NOTE: with Android 3.2 (API level 13) or higher, the "screen size" also changes when the device switches between portrait and landscape orientation. Thus, if you want to prevent runtime restarts due to orientation change when developing for API level 13 or higher, you must declare android:configChanges="orientation|screenSize" for API level 13 or higher.

Hope this will help you... :)

..The underlying connection was closed: An unexpected error occurred on a receive

I was working also on web scraping project and same issue found, below code applied and it worked nicely. If you are not aware about TLS versions then you can apply all below otherwise you can apply specific.

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;

End-line characters from lines read from text file, using Python

What's wrong with your code? I find it to be quite elegant and simple. The only problem is that if the file doesn't end in a newline, the last line returned won't have a '\n' as the last character, and therefore doing line = line[:-1] would incorrectly strip off the last character of the line.

The most elegant way to solve this problem would be to define a generator which took the lines of the file and removed the last character from each line only if that character is a newline:

def strip_trailing_newlines(file):
    for line in file:
        if line[-1] == '\n':
            yield line[:-1]
        else:
            yield line

f = open("myFile.txt", "r")
for line in strip_trailing_newlines(f):
    # do something with line

What is a None value?

This is what the Python documentation has got to say about None:

The sole value of types.NoneType. None is frequently used to represent the absence of a value, as when default arguments are not passed to a function.

Changed in version 2.4: Assignments to None are illegal and raise a SyntaxError.

Note The names None and debug cannot be reassigned (assignments to them, even as an attribute name, raise SyntaxError), so they can be considered “true” constants.

  1. Let's confirm the type of None first

    print type(None)
    print None.__class__
    

    Output

    <type 'NoneType'>
    <type 'NoneType'>
    

Basically, NoneType is a data type just like int, float, etc. You can check out the list of default types available in Python in 8.15. types — Names for built-in types.

  1. And, None is an instance of NoneType class. So we might want to create instances of None ourselves. Let's try that

    print types.IntType()
    print types.NoneType()
    

    Output

    0
    TypeError: cannot create 'NoneType' instances
    

So clearly, cannot create NoneType instances. We don't have to worry about the uniqueness of the value None.

  1. Let's check how we have implemented None internally.

    print dir(None)
    

    Output

    ['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', 
     '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__',
     '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
    

Except __setattr__, all others are read-only attributes. So, there is no way we can alter the attributes of None.

  1. Let's try and add new attributes to None

    setattr(types.NoneType, 'somefield', 'somevalue')
    setattr(None, 'somefield', 'somevalue')
    None.somefield = 'somevalue'
    

    Output

    TypeError: can't set attributes of built-in/extension type 'NoneType'
    AttributeError: 'NoneType' object has no attribute 'somefield'
    AttributeError: 'NoneType' object has no attribute 'somefield'
    

The above seen statements produce these error messages, respectively. It means that, we cannot create attributes dynamically on a None instance.

  1. Let us check what happens when we assign something None. As per the documentation, it should throw a SyntaxError. It means, if we assign something to None, the program will not be executed at all.

    None = 1
    

    Output

    SyntaxError: cannot assign to None
    

We have established that

  1. None is an instance of NoneType
  2. None cannot have new attributes
  3. Existing attributes of None cannot be changed.
  4. We cannot create other instances of NoneType
  5. We cannot even change the reference to None by assigning values to it.

So, as mentioned in the documentation, None can really be considered as a true constant.

Happy knowing None :)

Refused to load the font 'data:font/woff.....'it violates the following Content Security Policy directive: "default-src 'self'". Note that 'font-src'

In my case, I deleted src/registerServiceWorker file from create-react-app generated app. I added it and now it's all working.

How to get the caller class in Java

Since I currently have the same problem here is what I do:

  1. I prefer com.sun.Reflection instead of stackTrace since a stack trace is only producing the name not the class (including the classloader) itself.

  2. The method is deprecated but still around in Java 8 SDK.

// Method descriptor #124 (I)Ljava/lang/Class; (deprecated) // Signature: (I)Ljava/lang/Class<*>; @java.lang.Deprecated public static native java.lang.Class getCallerClass(int arg0);

  1. The method without int argument is not deprecated

// Method descriptor #122 ()Ljava/lang/Class; // Signature: ()Ljava/lang/Class<*>; @sun.reflect.CallerSensitive public static native java.lang.Class getCallerClass();

Since I have to be platform independent bla bla including Security Restrictions, I just create a flexible method:

  1. Check if com.sun.Reflection is available (security exceptions disable this mechanism)

  2. If 1 is yes then get the method with int or no int argument.

  3. If 2 is yes call it.

If 3. was never reached, I use the stack trace to return the name. I use a special result object that contains either the class or the string and this object tells exactly what it is and why.

[Summary] I use stacktrace for backup and to bypass eclipse compiler warnings I use reflections. Works very good. Keeps the code clean, works like a charm and also states the problems involved correctly.

I use this for quite a long time and today I searched a related question so

Print a file, skipping the first X lines, in Bash

If you want to see the first 10 lines you can use sed as below:

sed -n '1,10 p' myFile.txt

Or if you want to see lines from 20 to 30 you can use:

sed -n '20,30 p' myFile.txt

What are the most useful Intellij IDEA keyboard shortcuts?

Ctrl + F11 invokes a dialog with all alphanumeric keys on the keyboard. Selecting one empty will add the current line to bookmarks and mark the line with selected key.

Shift + F11 invokes a list of bookmarks. Pressing a key takes to associated bookmark.

Laravel 5 - redirect to HTTPS

I'm adding this alternative as I suffered a lot with this issue. I tried all different ways and nothing worked. So, I came up with a workaround for it. It might not be the best solution but it does work -

FYI, I am using Laravel 5.6

if (App::environment('production')) {
    URL::forceScheme('https');
}

production <- It should be replaced with the APP_ENV value in your .env file

How to redirect to Login page when Session is expired in Java web application?

You need to implement the HttpSessionListener interface, server will notify session time outs.

like this;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class ApplicationSessionListener implements HttpSessionListener {

public void sessionCreated(HttpSessionEvent event) {
   System.out.println("Session Created");
 }

public void sessionDestroyed(HttpSessionEvent event) {
   //write your logic
   System.out.println("Session Destroyed");
  }
 }

Check this example for better understanding

http://www.myjavarecipes.com/how-to-catch-session-timeouts/

JavaScript replace \n with <br />

Use a regular expression for .replace().:

messagetoSend = messagetoSend.replace(/\n/g, "<br />");

If those linebreaks were made by windows-encoding, you will also have to replace the carriage return.

messagetoSend = messagetoSend.replace(/\r\n/g, "<br />");

How to convert char to integer in C?

In the old days, when we could assume that most computers used ASCII, we would just do

int i = c[0] - '0';

But in these days of Unicode, it's not a good idea. It was never a good idea if your code had to run on a non-ASCII computer.

Edit: Although it looks hackish, evidently it is guaranteed by the standard to work. Thanks @Earwicker.

How to set a value of a variable inside a template code?

There are tricks like the one described by John; however, Django's template language by design does not support setting a variable (see the "Philosophy" box in Django documentation for templates).
Because of this, the recommended way to change any variable is via touching the Python code.

Regular expression for number with length of 4, 5 or 6

[0-9]{4,6} can be shortened to \d{4,6}

Entity Framework - Linq query with order by and group by

You can try to cast the result of GroupBy and Take into an Enumerable first then process the rest (building on the solution provided by NinjaNye

var groupByReference = (from m in context.Measurements
                              .GroupBy(m => m.Reference)
                              .Take(numOfEntries).AsEnumerable()
                               .Select(g => new {Creation = g.FirstOrDefault().CreationTime, 
                                             Avg = g.Average(m => m.CreationTime.Ticks),
                                                Items = g })
                              .OrderBy(x => x.Creation)
                              .ThenBy(x => x.Avg)
                              .ToList() select m);

Your sql query would look similar (depending on your input) this

SELECT TOP (3) [t1].[Reference] AS [Key]
FROM (
    SELECT [t0].[Reference]
    FROM [Measurements] AS [t0]
    GROUP BY [t0].[Reference]
    ) AS [t1]
GO

-- Region Parameters
DECLARE @x1 NVarChar(1000) = 'Ref1'
-- EndRegion
SELECT [t0].[CreationTime], [t0].[Id], [t0].[Reference]
FROM [Measurements] AS [t0]
WHERE @x1 = [t0].[Reference]
GO

-- Region Parameters
DECLARE @x1 NVarChar(1000) = 'Ref2'
-- EndRegion
SELECT [t0].[CreationTime], [t0].[Id], [t0].[Reference]
FROM [Measurements] AS [t0]
WHERE @x1 = [t0].[Reference]

Set cookies for cross origin requests

Note for Chrome Browser released in 2020.

A future release of Chrome will only deliver cookies with cross-site requests if they are set with SameSite=None and Secure.

So if your backend server does not set SameSite=None, Chrome will use SameSite=Lax by default and will not use this cookie with { withCredentials: true } requests.

More info https://www.chromium.org/updates/same-site.

Firefox and Edge developers also want to release this feature in the future.

Spec found here: https://tools.ietf.org/html/draft-west-cookie-incrementalism-01#page-8

Pass command parameter to method in ViewModel in WPF?

If you are that particular to pass elements to viewmodel You can use

 CommandParameter="{Binding ElementName=ManualParcelScanScreen}"

Is it possible to create a 'link to a folder' in a SharePoint document library?

The simplest way is to use the following pattern:

http://[server]/[site]/[ListName]/[Folder]/[SubFolder]

To place a shortcut to a document library:

  1. Upload it as *.url file. However, by default, this file type is not allowed.
  2. Go to you Document Library settings > Advanced Settings > Allow management of content types. Add the "Link to document" content type to a document library and paste the link

Regex to test if string begins with http:// or https://

(http|https)?:\/\/(\S+)

This works for me

Not a regex specialist, but i will try to explain the awnser.

(http|https) : Parenthesis indicates a capture group, "I" a OR statement.

\/\/ : "\" allows special characters, such as "/"

(\S+) : Anything that is not whitespace until the next whitespace

Set Value of Input Using Javascript Function

I'm not using YUI, but in case it helps anyone else - my issue was that I had duplicate ID's on the page (was working inside a dialog and forgot about the page underneath).

Changing the ID so it was unique allowed me to use the methods listed in Sangeet's answer.

Javascript - How to show escape characters in a string?

You have to escape the backslash, so try this:

str = "Hello\\nWorld";

Here are more escaped characters in Javascript.

C++ for each, pulling from vector elements

For next examples assumed that you use C++11. Example with ranged-based for loops:

for (auto &attack : m_attack) // access by reference to avoid copying
{  
    if (attack->m_num == input)
    {
        attack->makeDamage();
    }
}

You should use const auto &attack depending on the behavior of makeDamage().

You can use std::for_each from standard library + lambdas:

std::for_each(m_attack.begin(), m_attack.end(),
        [](Attack * attack)
        {
            if (attack->m_num == input)
            {
                attack->makeDamage();
            }
        }
);

If you are uncomfortable using std::for_each, you can loop over m_attack using iterators:

for (auto attack = m_attack.begin(); attack != m_attack.end(); ++attack)
{  
    if (attack->m_num == input)
    {
        attack->makeDamage();
    }
}

Use m_attack.cbegin() and m_attack.cend() to get const iterators.

initializing strings as null vs. empty string

The default constructor initializes the string to the empty string. This is the more economic way of saying the same thing.

However, the comparison to NULL stinks. That is an older syntax still in common use that means something else; a null pointer. It means that there is no string around.

If you want to check whether a string (that does exist) is empty, use the empty method instead:

if (myStr.empty()) ...

PANIC: Broken AVD system path. Check your ANDROID_SDK_ROOT value

It means that your path to tools is incorrect. This is what it looks like on a mac using brew. Mind the version.

export ANDROID_SDK_ROOT='/usr/local/Cellar/android-sdk/24.4.1_1'

In your case it looks like you should run this:

export ANDROID_SDK_ROOT='/Users/username/Library/Android/sdk'

How to request Google to re-crawl my website?

There are two options. The first (and better) one is using the Fetch as Google option in Webmaster Tools that Mike Flynn commented about. Here are detailed instructions:

  1. Go to: https://www.google.com/webmasters/tools/ and log in
  2. If you haven't already, add and verify the site with the "Add a Site" button
  3. Click on the site name for the one you want to manage
  4. Click Crawl -> Fetch as Google
  5. Optional: if you want to do a specific page only, type in the URL
  6. Click Fetch
  7. Click Submit to Index
  8. Select either "URL" or "URL and its direct links"
  9. Click OK and you're done.

With the option above, as long as every page can be reached from some link on the initial page or a page that it links to, Google should recrawl the whole thing. If you want to explicitly tell it a list of pages to crawl on the domain, you can follow the directions to submit a sitemap.

Your second (and generally slower) option is, as seanbreeden pointed out, submitting here: http://www.google.com/addurl/

Update 2019:

  1. Login to - Google Search Console
  2. Add a site and verify it with the available methods.
  3. After verification from the console, click on URL Inspection.
  4. In the Search bar on top, enter your website URL or custom URLs for inspection and enter.
  5. After Inspection, it'll show an option to Request Indexing
  6. Click on it and GoogleBot will add your website in a Queue for crawling.

SQLException: No suitable driver found for jdbc:derby://localhost:1527

Notice: you can download it from here.

If you can't find it, then

  1. Find your project in projects selection tab

  2. Right click "Libraries"

  3. Click "Add JAR/Folder..."

  4. Choose "derbyclient.jar"

  5. Click "Open", then you will see "derbyclient.jar" under your "Libraries"

Make sure your URL, user name, password is correct, and run your code:)

android: how to use getApplication and getApplicationContext from non activity / service class

Either pass in a Context (so you can access resources), or make the helper methods static.

Ansible: get current target host's IP address

Plain ansible_default_ipv4.address might not be what you think in some cases, use:

ansible_default_ipv4.address|default(ansible_all_ipv4_addresses[0])

Find out how much memory is being used by an object in Python

I haven't any personal experience with either of the following, but a simple search for a "Python [memory] profiler" yield:

  • PySizer, "a memory profiler for Python," found at http://pysizer.8325.org/. However the page seems to indicate that the project hasn't been updated for a while, and refers to...

  • Heapy, "support[ing] debugging and optimization regarding memory related issues in Python programs," found at http://guppy-pe.sourceforge.net/#Heapy.

Hope that helps.

scp from Linux to Windows

Try this, it really works.

$ scp username@from_host_ip:/home/ubuntu/myfile /cygdrive/c/Users/Anshul/Desktop

And for copying all files

$ scp -r username@from_host_ip:/home/ubuntu/ *. * /cygdrive/c/Users/Anshul/Desktop

Link a photo with the cell in excel

Hold down the Alt key and drag the pictures to snap to the upper left corner of the cell.

Format the picture and in the Properties tab select "Move but don't size with cells"

Now you can sort the data table by any column and the pictures will stay with the respective data.

This post at SuperUser has a bit more background and screenshots: https://superuser.com/questions/712622/put-an-equation-object-in-an-excel-cell/712627#712627

Table 'performance_schema.session_variables' doesn't exist

For my system the problem ended up being that I still had Mysql 5.6 installed and so the mysql_upgrade.exe from that installation was being called instead of the one for 5.7. Navigate to C:\Program Files\MySQL\MySQL Server 5.7\bin and run .\mysql_upgrade.exe -u root

Stop executing further code in Java

You can just use return to end the method's execution

How can I protect my .NET assemblies from decompilation?

I know you don't want to obfuscate, but maybe you should check out dotfuscator, it will take your compiled assemblies and obfuscate them for you. I think it can even encrypt them.

Adobe Acrobat Pro make all pages the same dimension

With Mac OS X and the more recent versions of Acrobat Pro, the PDF printer option does not work. What does work is doing basically the same thing in Preview App. Open the multi page file in Preview, select File>Print. In the Print dialog set your sheet size as if you are using a printer. You may want to select "Auto Rotate", "Scale to Fit" and "Print Entire Image". Then in the lower left corner is the drop button "PDF" and in that menu select "Save as PDF". Give it a new file name, click Save and then you can open the resulting file in whatever PDF app you want and the sheet sizes are the same.

Why are only final variables accessible in anonymous class?

An anonymous class is an inner class and the strict rule applies to inner classes (JLS 8.1.3):

Any local variable, formal method parameter or exception handler parameter used but not declared in an inner class must be declared final. Any local variable, used but not declared in an inner class must be definitely assigned before the body of the inner class.

I haven't found a reason or an explanation on the jls or jvms yet, but we do know, that the compiler creates a separate class file for each inner class and it has to make sure, that the methods declared on this class file (on byte code level) at least have access to the values of local variables.

(Jon has the complete answer - I keep this one undeleted because one might interested in the JLS rule)

How to remove jar file from local maven repository which was added with install:install-file?

  1. cd ~/.m2
  2. git init
  3. git commit -am "some comments"
  4. cd /path/to/your/project
  5. mvn install
  6. cd ~/.m2
  7. git reset --hard

Check if event exists on element

You may use:

$("#foo").unbind('click');

to make sure all click events are unbinded, then attach your event

Error:Execution failed for task ':app:processDebugResources'. > java.io.IOException: Could not delete folder "" in android studio

I found another handy solution, which avoids rebuilding all components again and again, in this article: http://bitstopixels.blogspot.ca/2017/04/react-native-windows-10-eperm-operation.html

  1. Execute react-native run-android
  2. As soon as React Packager window opens, close it
  3. Wait for react-native run-android to complete giving you the BUILD SUCCESSFUL message. (The app will be launched with a red error screen complaining connecting to server failed. Don't panic.)
  4. Then run react-native start to start the React Packager, this is the server indicated in the error message of the previous step
  5. Reload the app in emulator or device (Double tap the R key)

Insert using LEFT JOIN and INNER JOIN

You have to be specific about the columns you are selecting. If your user table had four columns id, name, username, opted_in you must select exactly those four columns from the query. The syntax looks like:

INSERT INTO user (id, name, username, opted_in)
  SELECT id, name, username, opted_in 
  FROM user LEFT JOIN user_permission AS userPerm ON user.id = userPerm.user_id

However, there does not appear to be any reason to join against user_permission here, since none of the columns from that table would be inserted into user. In fact, this INSERT seems bound to fail with primary key uniqueness violations.

MySQL does not support inserts into multiple tables at the same time. You either need to perform two INSERT statements in your code, using the last insert id from the first query, or create an AFTER INSERT trigger on the primary table.

INSERT INTO user (name, username, email, opted_in) VALUES ('a','b','c',0);
/* Gets the id of the new row and inserts into the other table */
INSERT INTO user_permission (user_id, permission_id) VALUES (LAST_INSERT_ID(), 4)

Or using a trigger:

CREATE TRIGGER creat_perms AFTER INSERT ON `user`
FOR EACH ROW
BEGIN
  INSERT INTO user_permission (user_id, permission_id) VALUES (NEW.id, 4)
END

Mockito: Mock private field initialization

I already found the solution to this problem which I forgot to post here.

@RunWith(PowerMockRunner.class)
@PrepareForTest({ Test.class })
public class SampleTest {

@Mock
Person person;

@Test
public void testPrintName() throws Exception {
    PowerMockito.whenNew(Person.class).withNoArguments().thenReturn(person);
    Test test= new Test();
    test.testMethod();
    }
}

Key points to this solution are:

  1. Running my test cases with PowerMockRunner: @RunWith(PowerMockRunner.class)

  2. Instruct Powermock to prepare Test.class for manipulation of private fields: @PrepareForTest({ Test.class })

  3. And finally mock the constructor for Person class:

    PowerMockito.mockStatic(Person.class); PowerMockito.whenNew(Person.class).withNoArguments().thenReturn(person);

Decreasing for loops in Python impossible?

for n in range(6,0,-1):
    print n

Can't use method return value in write context

The issue is this, you want to know if the error is not empty.

public function getError() {
    return $this->error;
}

Adding a method isErrorSet() will solve the problem.

public function isErrorSet() {
    if (isset($this->error) && !empty($this->error)) {
        return true;
    } else {
        return false;
    }
}

Now this will work fine with this code with no notice.

if (!($x->isErrorSet())) {
    echo $x->getError();
}

Simple way to change the position of UIView?

Here is the Swift 3 answer for anyone looking since Swift 3 does not accept "Make".

aView.center = CGPoint(x: 200, Y: 200)

JavaScript OOP in NodeJS: how?

This is the best video about Object-Oriented JavaScript on the internet:

The Definitive Guide to Object-Oriented JavaScript

Watch from beginning to end!!

Basically, Javascript is a Prototype-based language which is quite different than the classes in Java, C++, C#, and other popular friends. The video explains the core concepts far better than any answer here.

With ES6 (released 2015) we got a "class" keyword which allows us to use Javascript "classes" like we would with Java, C++, C#, Swift, etc.

Screenshot from the video showing how to write and instantiate a Javascript class/subclass: enter image description here

Setting font on NSAttributedString on UITextView disregards line spacing

Attributed String Programming Guide:

UIFont *font = [UIFont fontWithName:@"Palatino-Roman" size:14.0];
NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObject:font
                                forKey:NSFontAttributeName];
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"strigil" attributes:attrsDictionary];

Update: I tried to use addAttribute: method in my own app, but it seemed to be not working on the iOS 6 Simulator:

NSLog(@"%@", textView.attributedText);

The log seems to show correctly added attributes, but the view on iOS simulator was not display with attributes.

Twitter Bootstrap Modal Form Submit

Updated 2018

Do you want to close the modal after submit? Whether the form in inside the modal or external to it you should be able to use jQuery ajax to submit the form.

Here is an example with the form inside the modal:

<a href="#myModal" role="button" class="btn" data-toggle="modal">Launch demo modal</a>

<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
            <h3 id="myModalLabel">Modal header</h3>
    </div>
    <div class="modal-body">
        <form id="myForm" method="post">
          <input type="hidden" value="hello" id="myField">
            <button id="myFormSubmit" type="submit">Submit</button>
        </form>
    </div>
    <div class="modal-footer">
        <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
        <button class="btn btn-primary">Save changes</button>
    </div>
</div>

And the jQuery ajax to get the form fields and submit it..

$('#myFormSubmit').click(function(e){
      e.preventDefault();
      alert($('#myField').val());
      /*
      $.post('http://path/to/post', 
         $('#myForm').serialize(), 
         function(data, status, xhr){
           // do something here with response;
         });
      */
});

Bootstrap 3 example


Bootstrap 4 example

Unable to simultaneously satisfy constraints, will attempt to recover by breaking constraint

I am getting this same error, but only on a specific view, when I touch the first textfield, and then the next textfield down.

I am writing in SwiftUI for iOS 13.4

 Unable to simultaneously satisfy constraints.
        Probably at least one of the constraints in the following list is one you don't want. 
        Try this: 
            (1) look at each constraint and try to figure out which you don't expect; 
            (2) find the code that added the unwanted constraint or constraints and fix it. 
    (
        "<NSLayoutConstraint:0x2809b6760 'assistantHeight' TUISystemInputAssistantView:0x105710da0.height == 44   (active)>",
        "<NSLayoutConstraint:0x2809ccff0 'assistantView.bottom' TUISystemInputAssistantView:0x105710da0.bottom == _UIKBCompatInputView:0x10525ae10.top   (active)>",
        "<NSLayoutConstraint:0x2809cccd0 'assistantView.top' V:|-(0)-[TUISystemInputAssistantView:0x105710da0]   (active, names: '|':UIInputSetHostView:0x105215010 )>",
        "<NSLayoutConstraint:0x2809ca300 'inputView.top' V:|-(0)-[_UIKBCompatInputView:0x10525ae10]   (active, names: '|':UIInputSetHostView:0x105215010 )>"
    )

    Will attempt to recover by breaking constraint 
    <NSLayoutConstraint:0x2809ccff0 'assistantView.bottom' TUISystemInputAssistantView:0x105710da0.bottom == _UIKBCompatInputView:0x10525ae10.top   (active)>

    Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
    The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.

How do you rename a Git tag?

In addition to the other answers:

First you need to build an alias of the old tag name, pointing to the original commit:

git tag new old^{}

Then you need to delete the old one locally:

git tag -d old

Then delete the tag on you remote location(s):

# Check your remote sources:
git remote -v
# The argument (3rd) is your remote location,
# the one you can see with `git remote`. In this example: `origin`
git push origin :refs/tags/old

Finally you need to add your new tag to the remote location. Until you have done this, the new tag(s) will not be added:

git push origin --tags

Iterate this for every remote location.

Be aware, of the implications that a Git Tag change has to consumers of a package!

Find what 2 numbers add to something and multiply to something

With the multiplication, I recommend using the modulo operator (%) to determine which numbers divide evenly into the target number like:

$factors = array();
for($i = 0; $i < $target; $i++){
    if($target % $i == 0){
        $temp = array()
        $a = $i;
        $b = $target / $i;
        $temp["a"] = $a;
        $temp["b"] = $b;
        $temp["index"] = $i;
        array_push($factors, $temp);
    }
}

This would leave you with an array of factors of the target number.

How to empty the content of a div

An alternative way to do it is:

var div = document.getElementById('myDiv');
while(div.firstChild)
    div.removeChild(div.firstChild);

However, using document.getElementById('myDiv').innerHTML = ""; is faster.

See: Benchmark test

N.B.

Both methods preserve the div.

Excel CSV - Number cell format

Put a single quote before the field. Excel will treat it as text, even if it looks like a number.

...,`005,...

EDIT: This is wrong. The apostrophe trick only works when entering data directly into Excel. When you use it in a CSV file, the apostrophe appears in the field, which you don't want.

http://support.microsoft.com/kb/214233

Flutter command not found

Use the following steps for setup

  1. Download from Flutter SDK for Mac https://flutter.dev/docs/get-started/install/macos

  2. Extract the Flutter SDK zip (saved in Downloads) file using terminal. If you want to extract the Flutter SDK in fluttrerDevelopment folder

    $ cd ~/fluttrerDevelopment

    $ unzip ~/Downloads/flutter_macos_1.20.1-stable.zip

  3. Add the flutter tool to your path:

    $ export PATH=“$PATH:pwd/flutter/bin"

  4. If you have only Xcode setup in your machine then run

    $ flutter create my_first_flutter_app

    $ cd my_first_flutter_app

    $ flutter run