Programs & Examples On #Sysdatabases

What is the maximum value for an int32?

2GB

(is there a minimum length for answers?)

Using an if statement to check if a div is empty

Try this:

$(document).ready(function() {
    if ($('#leftmenu').html() === "") {
        $('#menuTitleWrapper').remove();
        $('#middlemenu').css({'right' : '0', 'position' : 'absolute'});
        $('#PageContent').css({'top' : '30px', 'position' : 'relative'});
    }
});

It's not the prettiest, but it should work. It checks whether the innerHTML (the contents of #leftmenu) is an empty string (i.e. there's nothing inside of it).

Maintain image aspect ratio when changing height

For img tags if you define one side then other side is resized to keep aspect ratio and by default images expand to their original size.

Using this fact if you wrap each img tag into div tag and set its width to 100% of parent div then height will be according to aspect ratio as you wanted.

http://jsfiddle.net/0o5tpbxg/

* {
    margin: 0;
    padding: 0;
}
.slider {
    display: flex;
}
.slider .slide img {
    width: 100%;
}

How to change ViewPager's page?

slide to right

viewPager.arrowScroll(View.FOCUS_RIGHT);

slide to left

viewPager.arrowScroll(View.FOCUS_LEFT);

How to access SOAP services from iPhone

Have a look at here this link and their roadmap. They have RO|C on the way, and that can connect to their web services, which probably includes SOAP (I use the VCL version which definitely includes it).

Why should C++ programmers minimize use of 'new'?

I think the poster meant to say You do not have to allocate everything on theheap rather than the the stack.

Basically objects are allocated on the stack (if the object size allows, of course) because of the cheap cost of stack-allocation, rather than heap-based allocation which involves quite some work by the allocator, and adds verbosity because then you have to manage data allocated on the heap.

M_PI works with math.h but not with cmath in Visual Studio

Consider adding the switch /D_USE_MATH_DEFINES to your compilation command line, or to define the macro in the project settings. This will drag the symbol to all reachable dark corners of include and source files leaving your source clean for multiple platforms. If you set it globally for the whole project, you will not forget it later in a new file(s).

Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

Please note that adding the get_author function would slow the list_display in the admin, because showing each person would make a SQL query.

To avoid this, you need to modify get_queryset method in PersonAdmin, for example:

def get_queryset(self, request):
    return super(PersonAdmin,self).get_queryset(request).select_related('book')

Before: 73 queries in 36.02ms (67 duplicated queries in admin)

After: 6 queries in 10.81ms

Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata.`

In my case I was getting this error because the option (HttpActivation) was not enabled. Windows features dialog box showing HTTP Activation under WCF Services under .NET Framework 4.6 Advanced Services

React : difference between <Route exact path="/" /> and <Route path="/" />

In short, if you have multiple routes defined for your app's routing, enclosed with Switch component like this;

<Switch>

  <Route exact path="/" component={Home} />
  <Route path="/detail" component={Detail} />

  <Route exact path="/functions" component={Functions} />
  <Route path="/functions/:functionName" component={FunctionDetails} />

</Switch>

Then you have to put exact keyword to the Route which it's path is also included by another Route's path. For example home path / is included in all paths so it needs to have exact keyword to differentiate it from other paths which start with /. The reason is also similar to /functions path. If you want to use another route path like /functions-detail or /functions/open-door which includes /functions in it then you need to use exact for the /functions route.

top align in html table?

Some CSS :

table td, table td * {
    vertical-align: top;
}

HTML5 Video Stop onClose

Try this:

if ($.browser.msie)
{
   // Some other solution as applies to whatever IE compatible video player used.
}
else
{
   $('video')[0].pause();
}

But, consider that $.browser is deprecated, but I haven't found a comparable solution.

Comparison of C++ unit test frameworks

I've recently released xUnit++, specifically as an alternative to Google Test and the Boost Test Library (view the comparisons). If you're familiar with xUnit.Net, you're ready for xUnit++.

#include "xUnit++/xUnit++.h"

FACT("Foo and Blah should always return the same value")
{
    Check.Equal("0", Foo()) << "Calling Foo() with no parameters should always return \"0\".";
    Assert.Equal(Foo(), Blah());
}

THEORY("Foo should return the same value it was given, converted to string", (int input, std::string expected),
    std::make_tuple(0, "0"),
    std::make_tuple(1, "1"),
    std::make_tuple(2, "2"))
{
    Assert.Equal(expected, Foo(input));
}

Main features:

  • Incredibly fast: tests run concurrently.
  • Portable
  • Automatic test registration
  • Many assertion types (Boost has nothing on xUnit++)
  • Compares collections natively.
  • Assertions come in three levels:
    • fatal errors
    • non-fatal errors
    • warnings
  • Easy assert logging: Assert.Equal(-1, foo(i)) << "Failed with i = " << i;
  • Test logging: Log.Debug << "Starting test"; Log.Warn << "Here's a warning";
  • Fixtures
  • Data-driven tests (Theories)
  • Select which tests to run based on:
    • Attribute matching
    • Name substring matchin
    • Test Suites

How to align input forms in HTML

A simple solution for you if you're new to HTML, is just to use a table to line everything up.

<form>
  <table>
    <tr>
      <td align="right">First Name:</td>
      <td align="left"><input type="text" name="first" /></td>
    </tr>
    <tr>
      <td align="right">Last Name:</td>
      <td align="left"><input type="text" name="last" /></td>
    </tr>
    <tr>
      <td align="right">Email:</td>
      <td align="left"><input type="text" name="email" /></td>
    </tr>
  </table>
</form>

How to customise file type to syntax associations in Sublime Text?

I put my customized changes in the User package:

*nix: ~/.config/sublime-text-2/Packages/User/Scala.tmLanguage
*Windows: %APPDATA%\Sublime Text 2\Packages\User\Scala.tmLanguage

Which also means it's in JSON format:

{
  "extensions":
  [
    "sbt"
  ]
}

This is the same place the

View -> Syntax -> Open all with current extension as ...

menu item adds it (creating the file if it doesn't exist).

Bootstrap: Open Another Modal in Modal

Close the first Bootstrap modal and open the new modal dynamically.

$('#Modal_One').modal('hide');
setTimeout(function () {
  $('#Modal_New').modal({
    backdrop: 'dynamic',
    keyboard: true
  });
}, 500);

How do I use the includes method in lodash to check if an object is in the collection?

Supplementing the answer by p.s.w.g, here are three other ways of achieving this using lodash 4.17.5, without using _.includes():

Say you want to add object entry to an array of objects numbers, only if entry does not exist already.

let numbers = [
    { to: 1, from: 2 },
    { to: 3, from: 4 },
    { to: 5, from: 6 },
    { to: 7, from: 8 },
    { to: 1, from: 2 } // intentionally added duplicate
];

let entry = { to: 1, from: 2 };

/* 
 * 1. This will return the *index of the first* element that matches:
 */
_.findIndex(numbers, (o) => { return _.isMatch(o, entry) });
// output: 0


/* 
 * 2. This will return the entry that matches. Even if the entry exists
 *    multiple time, it is only returned once.
 */
_.find(numbers, (o) => { return _.isMatch(o, entry) });
// output: {to: 1, from: 2}


/* 
 * 3. This will return an array of objects containing all the matches.
 *    If an entry exists multiple times, if is returned multiple times.
 */
_.filter(numbers, _.matches(entry));
// output: [{to: 1, from: 2}, {to: 1, from: 2}]

If you want to return a Boolean, in the first case, you can check the index that is being returned:

_.findIndex(numbers, (o) => { return _.isMatch(o, entry) }) > -1;
// output: true

How do I print out the value of this boolean? (Java)

System.out.println(isLeapYear);

should work just fine.

Incidentally, in

else if ((year % 4 == 0) && (year % 100 == 0))
    isLeapYear = false;

else if ((year % 4 == 0) && (year % 100 == 0) && (year % 400 == 0))
    isLeapYear = true;

the year % 400 part will never be reached because if (year % 4 == 0) && (year % 100 == 0) && (year % 400 == 0) is true, then (year % 4 == 0) && (year % 100 == 0) must have succeeded.

Maybe swap those two conditions or refactor them:

else if ((year % 4 == 0) && (year % 100 == 0))
    isLeapYear = (year % 400 == 0);

Java - Check Not Null/Empty else assign default value

If using JDK 9 +, use Objects.requireNonNullElse(T obj, T defaultObj)

Removing header column from pandas dataframe

Haven't seen this solution yet so here's how I did it without using read_csv:

df.rename(columns={'A':'','B':''})

If you rename all your column names to empty strings your table will return without a header.

And if you have a lot of columns in your table you can just create a dictionary first instead of renaming manually:

df_dict = dict.fromkeys(df.columns, '')
df.rename(columns = df_dict)

Format an Integer using Java String Format

If you are using a third party library called apache commons-lang, the following solution can be useful:

Use StringUtils class of apache commons-lang :

int i = 5;
StringUtils.leftPad(String.valueOf(i), 3, "0"); // --> "005"

As StringUtils.leftPad() is faster than String.format()

Adding +1 to a variable inside a function

Move points into test:

def test():
    points = 0
    addpoint = raw_input ("type ""add"" to add a point")
    ...

or use global statement, but it is bad practice. But better way it move points to parameters:

def test(points=0):
    addpoint = raw_input ("type ""add"" to add a point")
    ...

How to check if an element is in an array

Array

let elements = [1, 2, 3, 4, 5, 5]

Check elements presence

elements.contains(5) // true

Get elements index

elements.firstIndex(of: 5) // 4
elements.firstIndex(of: 10) // nil

Get element count

let results = elements.filter { element in element == 5 }
results.count // 2

Passing ArrayList from servlet to JSP

request.getAttribute("servletName") method will return Object that you need to cast to ArrayList

ArrayList<Category> list =new ArrayList<Category>();
//storing passed value from jsp
list = (ArrayList<Category>)request.getAttribute("servletName");

Really killing a process in Windows

"End Process" on the Processes-Tab calls TerminateProcess which is the most ultimate way Windows knows to kill a process.

If it doesn't go away, it's currently locked waiting on some kernel resource (probably a buggy driver) and there is nothing (short of a reboot) you could do to make the process go away.

Have a look at this blog-entry from wayback when: http://blogs.technet.com/markrussinovich/archive/2005/08/17/unkillable-processes.aspx

Unix based systems like Linux also have that problem where processes could survive a kill -9 if they are in what's known as "Uninterruptible sleep" (shown by top and ps as state D) at which point the processes sleep so well that they can't process incoming signals (which is what kill does - sending signals).

Normally, Uninterruptible sleep should not last long, but as under Windows, broken drivers or broken userpace programs (vfork without exec) can end up sleeping in D forever.

R data formats: RData, Rda, Rds etc

In addition to @KenM's answer, another important distinction is that, when loading in a saved object, you can assign the contents of an Rds file. Not so for Rda

> x <- 1:5
> save(x, file="x.Rda")
> saveRDS(x, file="x.Rds")
> rm(x)

## ASSIGN USING readRDS
> new_x1 <- readRDS("x.Rds")
> new_x1
[1] 1 2 3 4 5

## 'ASSIGN' USING load -- note the result
> new_x2 <- load("x.Rda")
loading in to  <environment: R_GlobalEnv> 
> new_x2
[1] "x"
# NOTE: `load()` simply returns the name of the objects loaded. Not the values. 
> x
[1] 1 2 3 4 5

NameError: name 'datetime' is not defined

It can also be used as below:

from datetime import datetime
start_date = datetime(2016,3,1)
end_date = datetime(2016,3,10)

Putty: Getting Server refused our key Error

I was facing similar issue when trying to logon through Mobaxterm. The private key was generated through puttygen. Regenerating the key helped in my case.

linux/videodev.h : no such file or directory - OpenCV on ubuntu 11.04

The patch is here: https://code.ros.org/trac/opencv/attachment/ticket/862/OpenCV-2.2-nov4l1.patch

By adding #ifdef HAVE_CAMV4L around

#include <linux/videodev.h>

in OpenCV-2.2.0/modules/highgui/src/cap_v4l.cpp and removing || defined (HAVE_CAMV4L2) from line 174 allowed me to compile.

How to identify object types in java

You want instanceof:

if (value instanceof Integer)

This will be true even for subclasses, which is usually what you want, and it is also null-safe. If you really need the exact same class, you could do

if (value.getClass() == Integer.class)

or

if (Integer.class.equals(value.getClass())

Strange PostgreSQL "value too long for type character varying(500)"

Character varying is different than text. Try running

ALTER TABLE product_product ALTER COLUMN code TYPE text;

That will change the column type to text, which is limited to some very large amount of data (you would probably never actually hit it.)

Defining TypeScript callback type

I just found something in the TypeScript language specification, it's fairly easy. I was pretty close.

the syntax is the following:

public myCallback: (name: type) => returntype;

In my example, it would be

class CallbackTest
{
    public myCallback: () => void;

    public doWork(): void
    {
        //doing some work...
        this.myCallback(); //calling callback
    }
}

error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

int &z = 12;

On the right hand side, a temporary object of type int is created from the integral literal 12, but the temporary cannot be bound to non-const reference. Hence the error. It is same as:

int &z = int(12); //still same error

Why a temporary gets created? Because a reference has to refer to an object in the memory, and for an object to exist, it has to be created first. Since the object is unnamed, it is a temporary object. It has no name. From this explanation, it became pretty much clear why the second case is fine.

A temporary object can be bound to const reference, which means, you can do this:

const int &z = 12; //ok

C++11 and Rvalue Reference:

For the sake of the completeness, I would like to add that C++11 has introduced rvalue-reference, which can bind to temporary object. So in C++11, you can write this:

int && z = 12; //C+11 only 

Note that there is && intead of &. Also note that const is not needed anymore, even though the object which z binds to is a temporary object created out of integral-literal 12.

Since C++11 has introduced rvalue-reference, int& is now henceforth called lvalue-reference.

Setting table row height

You can remove some extra spacing as well if you place a border-collapse: collapse; CSS statement on your table.

iPhone App Development on Ubuntu

Probably not. While I can't log into the Apple Development site, according to this post you need an intel mac platform.

http://tinleyharrier.blogspot.com/2008/03/iphone-sdk-requirements.html

Reading rows from a CSV file in Python

import csv

with open('filepath/filename.csv', "rt", encoding='ascii') as infile:
    read = csv.reader(infile)
    for row in read :
        print (row)

This will solve your problem. Don't forget to give the encoding.

How to pass form input value to php function

You need to look into Ajax; Start here this is the best way to stay on the current page and be able to send inputs to php.

<!DOCTYPE html>
<html>
<head>
<script>
function showHint(str)
{
var xmlhttp;
if (str.length==0)
  { 
  document.getElementById("txtHint").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","gethint.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<h3>Start typing a name in the input field below:</h3>
<form action=""> 
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)" />
</form>
<p>Suggestions: <span id="txtHint"></span></p> 

</body>
</html>

This gets the users input on the textbox and opens the webpage gethint.php?q=ja from here the php script can do anything with $_GET['q'] and echo back to the page James, Jason....etc

What's the difference between process.cwd() vs __dirname?

process.cwd() returns the current working directory,

i.e. the directory from which you invoked the node command.

__dirname returns the directory name of the directory containing the JavaScript source code file

How to get file size in Java

Did a quick google. Seems that to find the file size you do this,

long size = f.length();

The differences between the three methods you posted can be found here

getFreeSpace() and getTotalSpace() are pretty self explanatory, getUsableSpace() seems to be the space that the JVM can use, which in most cases will be the same as the amount of free space.

Mocking methods of local scope objects with Mockito

The answer from @edutesoy points to the documentation of PowerMockito and mentions constructor mocking as a hint but doesn't mention how to apply that to the current problem in the question.

Here is a solution based on that. Taking the code from the question:

public class MyClass {
    void method1 {
        MyObject obj1 = new MyObject();
        obj1.method1();
    }
}

The following test will create a mock of the MyObject instance class via preparing the class that instantiates it (in this example I am calling it MyClass) with PowerMock and letting PowerMockito to stub the constructor of MyObject class, then letting you stub the MyObject instance method1() call:

@RunWith(PowerMockRunner.class)
@PrepareForTest(MyClass.class)
public class MyClassTest {
    @Test
    public void testMethod1() {      
        MyObject myObjectMock = mock(MyObject.class);
        when(myObjectMock.method1()).thenReturn(<whatever you want to return>);   
        PowerMockito.whenNew(MyObject.class).withNoArguments().thenReturn(myObjectMock);
        
        MyClass objectTested = new MyClass();
        objectTested.method1();
        
        ... // your assertions or verification here 
    }
}

With that your internal method1() call will return what you want.

If you like the one-liners you can make the code shorter by creating the mock and the stub inline:

MyObject myObjectMock = when(mock(MyObject.class).method1()).thenReturn(<whatever you want>).getMock();   

How to store arbitrary data for some HTML tags

Why not make use of the meaningful data already there, instead of adding arbitrary data?

i.e. use <a href="/articles/5/page-title" class="article-link">, and then you can programmatically get all article links on the page (via the classname) and the article ID (matching the regex /articles\/(\d+)/ against this.href).

How to get a list of column names

Using @Tarkus's answer, here are the regexes I used in R:

getColNames <- function(conn, tableName) {
    x <- dbGetQuery( conn, paste0("SELECT sql FROM sqlite_master WHERE tbl_name = '",tableName,"' AND type = 'table'") )[1,1]
    x <- str_split(x,"\\n")[[1]][-1]
    x <- sub("[()]","",x)
    res <- gsub( '"',"",str_extract( x[1], '".+"' ) )
    x <- x[-1]
    x <- x[-length(x)]
    res <- c( res, gsub( "\\t", "", str_extract( x, "\\t[0-9a-zA-Z_]+" ) ) )
    res
}

Code is somewhat sloppy, but it appears to work.

How to calculate UILabel width based on text length?

yourLabel.intrinsicContentSize.width for Objective-C / Swift

Get User Selected Range

Selection is its own object within VBA. It functions much like a Range object.

Selection and Range do not share all the same properties and methods, though, so for ease of use it might make sense just to create a range and set it equal to the Selection, then you can deal with it programmatically like any other range.

Dim myRange as Range
Set myRange = Selection

For further reading, check out the MSDN article.

Remove empty space before cells in UITableView

NONE of the above helped me. but doing this did help:

self.tableView.contentInset = UIEdgeInsetsMake(-64, 0, 0, 0)

instead of '-64' you can put any other number depending on the height of your navigation bar.

Best practices when running Node.js with port 80 (Ubuntu / Linode)

Give Safe User Permission To Use Port 80

Remember, we do NOT want to run your applications as the root user, but there is a hitch: your safe user does not have permission to use the default HTTP port (80). You goal is to be able to publish a website that visitors can use by navigating to an easy to use URL like http://ip:port/

Unfortunately, unless you sign on as root, you’ll normally have to use a URL like http://ip:port - where port number > 1024.

A lot of people get stuck here, but the solution is easy. There a few options but this is the one I like. Type the following commands:

sudo apt-get install libcap2-bin
sudo setcap cap_net_bind_service=+ep `readlink -f \`which node\``

Now, when you tell a Node application that you want it to run on port 80, it will not complain.

Check this reference link

How to check if all elements of a list matches a condition?

You could use itertools's takewhile like this, it will stop once a condition is met that fails your statement. The opposite method would be dropwhile

for x in itertools.takewhile(lambda x: x[2] == 0, list)
    print x

Color text in terminal applications in UNIX

Different solution that I find more elegant

Here's another way to do it. Some people will prefer this as the code is a bit cleaner. There are no %s and a RESET color to end the coloration.

#include <stdio.h>

#define RED   "\x1B[31m"
#define GRN   "\x1B[32m"
#define YEL   "\x1B[33m"
#define BLU   "\x1B[34m"
#define MAG   "\x1B[35m"
#define CYN   "\x1B[36m"
#define WHT   "\x1B[37m"
#define RESET "\x1B[0m"

int main() {
  printf(RED "red\n"     RESET);
  printf(GRN "green\n"   RESET);
  printf(YEL "yellow\n"  RESET);
  printf(BLU "blue\n"    RESET);
  printf(MAG "magenta\n" RESET);
  printf(CYN "cyan\n"    RESET);
  printf(WHT "white\n"   RESET);

  return 0;
}

This program gives the following output:

enter image description here


Simple example with multiple colors

This way, it's easy to do something like:

printf("This is " RED "red" RESET " and this is " BLU "blue" RESET "\n");

This line produces the following output:

execution's output

How do I get the name of the current executable in C#?

You can use Environment.GetCommandLineArgs() to obtain the arguments and Environment.CommandLine to obtain the actual command line as entered.

Also, you can use Assembly.GetEntryAssembly() or Process.GetCurrentProcess().

However, when debugging, you should be careful as this final example may give your debugger's executable name (depending on how you attach the debugger) rather than your executable, as may the other examples.

Why are C++ inline functions in the header?

There are two ways to look at it:

  1. Inline functions are defined in the header because, in order to inline a function call, the compiler must be able to see the function body. For a naive compiler to do that, the function body must be in the same translation unit as the call. (A modern compiler can optimize across translation units, and so a function call may be inlined even though the function definition is in a separate translation unit, but these optimizations are expensive, aren't always enabled, and weren't always supported by the compiler)

  2. functions defined in the header must be marked inline because otherwise, every translation unit which includes the header will contain a definition of the function, and the linker will complain about multiple definitions (a violation of the One Definition Rule). The inline keyword suppresses this, allowing multiple translation units to contain (identical) definitions.

The two explanations really boil down to the fact that the inline keyword doesn't exactly do what you'd expect.

A C++ compiler is free to apply the inlining optimization (replace a function call with the body of the called function, saving the call overhead) any time it likes, as long as it doesn't alter the observable behavior of the program.

The inline keyword makes it easier for the compiler to apply this optimization, by allowing the function definition to be visible in multiple translation units, but using the keyword doesn't mean the compiler has to inline the function, and not using the keyword doesn't forbid the compiler from inlining the function.

How to check if a json key exists?

You can check this way where 'HAS' - Returns true if this object has a mapping for name. The mapping may be NULL.

if (json.has("status")) {
   String status = json.getString("status"));
}

if (json.has("club")) {
   String club = json.getString("club"));
}

You can also check using 'isNull' - Returns true if this object has no mapping for name or if it has a mapping whose value is NULL.

if (!json.isNull("club"))
    String club = json.getString("club"));

Run Android studio emulator on AMD processor

I am using the AMD processor and had the same issue. To solve this go to control panel-> turn windows features on or off -> check the hyper-V checkbox and click Ok and restart your computer. Now you can create virtual device

How to create empty folder in java?

Looks file you use the .mkdirs() method on a File object: http://www.roseindia.net/java/beginners/java-create-directory.shtml

// Create a directory; all non-existent ancestor directories are
// automatically created
success = (new File("../potentially/long/pathname/without/all/dirs")).mkdirs();
if (!success) {
    // Directory creation failed
}

Go Back to Previous Page

Depends what it is that you're trying to do it with. You could use something like this:

echo "<a href=\"javascript:history.go(-1)\">GO BACK</a>";

That's the simplest option. The other poster is right about having a proper flow of history but this is an example for you.

Just edited, orig version wasn't indented and looked like nothing. ;)

Create a txt file using batch file in a specific folder

Changed the set to remove % as that will write to text file as Echo on or off

echo off
title Custom Text File
cls
set /p txt=What do you want it to say? ; 
echo %txt% > "D:\Testing\dblank.txt"
exit

PHP - define constant inside a class

See Class Constants:

class MyClass
{
    const MYCONSTANT = 'constant value';

    function showConstant() {
        echo  self::MYCONSTANT. "\n";
    }
}

echo MyClass::MYCONSTANT. "\n";

$classname = "MyClass";
echo $classname::MYCONSTANT. "\n"; // As of PHP 5.3.0

$class = new MyClass();
$class->showConstant();

echo $class::MYCONSTANT."\n"; // As of PHP 5.3.0

In this case echoing MYCONSTANT by itself would raise a notice about an undefined constant and output the constant name converted to a string: "MYCONSTANT".


EDIT - Perhaps what you're looking for is this static properties / variables:

class MyClass
{
    private static $staticVariable = null;

    public static function showStaticVariable($value = null)
    {
        if ((is_null(self::$staticVariable) === true) && (isset($value) === true))
        {
            self::$staticVariable = $value;
        }

        return self::$staticVariable;
    }
}

MyClass::showStaticVariable(); // null
MyClass::showStaticVariable('constant value'); // "constant value"
MyClass::showStaticVariable('other constant value?'); // "constant value"
MyClass::showStaticVariable(); // "constant value"

Compile Views in ASP.NET MVC

The answer given here works for some MVC versions but not for others.

The simple solution worked for MVC1 but on upgrading to MVC2 the views were no longer being compliled. This was due to a bug in the website project files. See this Haacked article.

See this: http://haacked.com/archive/2011/05/09/compiling-mvc-views-in-a-build-environment.aspx

What REALLY happens when you don't free after malloc?

It is completely fine to leave memory unfreed when you exit; malloc() allocates the memory from the memory area called "the heap", and the complete heap of a process is freed when the process exits.

That being said, one reason why people still insist that it is good to free everything before exiting is that memory debuggers (e.g. valgrind on Linux) detect the unfreed blocks as memory leaks, and if you have also "real" memory leaks, it becomes more difficult to spot them if you also get "fake" results at the end.

Test if executable exists in Python?

So basically you want to find a file in mounted filesystem (not necessarily in PATH directories only) and check if it is executable. This translates to following plan:

  • enumerate all files in locally mounted filesystems
  • match results with name pattern
  • for each file found check if it is executable

I'd say, doing this in a portable way will require lots of computing power and time. Is it really what you need?

How to get first object out from List<Object> using Linq

var firstObjectsOfValues = (from d in dic select d.Value[0].ComponentValue("Dep"));

Converting year and month ("yyyy-mm" format) to a date?

Indeed, as has been mentioned above (and elsewhere on SO), in order to convert the string to a date, you need a specific date of the month. From the as.Date() manual page:

If the date string does not specify the date completely, the returned answer may be system-specific. The most common behaviour is to assume that a missing year, month or day is the current one. If it specifies a date incorrectly, reliable implementations will give an error and the date is reported as NA. Unfortunately some common implementations (such as glibc) are unreliable and guess at the intended meaning.

A simple solution would be to paste the date "01" to each date and use strptime() to indicate it as the first day of that month.


For those seeking a little more background on processing dates and times in R:

In R, times use POSIXct and POSIXlt classes and dates use the Date class.

Dates are stored as the number of days since January 1st, 1970 and times are stored as the number of seconds since January 1st, 1970.

So, for example:

d <- as.Date("1971-01-01")
unclass(d)  # one year after 1970-01-01
# [1] 365

pct <- Sys.time()  # in POSIXct
unclass(pct)  # number of seconds since 1970-01-01
# [1] 1450276559
plt <- as.POSIXlt(pct)
up <- unclass(plt)  # up is now a list containing the components of time
names(up)
# [1] "sec"    "min"    "hour"   "mday"   "mon"    "year"   "wday"   "yday"   "isdst"  "zone"  
# [11] "gmtoff"
up$hour
# [1] 9

To perform operations on dates and times:

plt - as.POSIXlt(d)
# Time difference of 16420.61 days

And to process dates, you can use strptime() (borrowing these examples from the manual page):

strptime("20/2/06 11:16:16.683", "%d/%m/%y %H:%M:%OS")
# [1] "2006-02-20 11:16:16 EST"

# And in vectorized form:
dates <- c("1jan1960", "2jan1960", "31mar1960", "30jul1960")
strptime(dates, "%d%b%Y")
# [1] "1960-01-01 EST" "1960-01-02 EST" "1960-03-31 EST" "1960-07-30 EDT"

Nullable type as a generic parameter possible?

Multiple generic constraints can't be combined in an OR fashion (less restrictive), only in an AND fashion (more restrictive). Meaning that one method can't handle both scenarios. The generic constraints also cannot be used to make a unique signature for the method, so you'd have to use 2 separate method names.

However, you can use the generic constraints to make sure that the methods are used correctly.

In my case, I specifically wanted null to be returned, and never the default value of any possible value types. GetValueOrDefault = bad. GetValueOrNull = good.

I used the words "Null" and "Nullable" to distinguish between reference types and value types. And here is an example of a couple extension methods I wrote that compliments the FirstOrDefault method in System.Linq.Enumerable class.

    public static TSource FirstOrNull<TSource>(this IEnumerable<TSource> source)
        where TSource: class
    {
        if (source == null) return null;
        var result = source.FirstOrDefault();   // Default for a class is null
        return result;
    }

    public static TSource? FirstOrNullable<TSource>(this IEnumerable<TSource?> source)
        where TSource : struct
    {
        if (source == null) return null;
        var result = source.FirstOrDefault();   // Default for a nullable is null
        return result;
    }

DataGridView - Focus a specific cell

You can try this for DataGrid:

DataGridCellInfo cellInfo = new DataGridCellInfo(myDataGrid.Items[colRow], myDataGrid.Columns[colNum]);
DataGridCell cellToFocus = (DataGridCell)cellInfo.Column.GetCellContent(cellInfo.Item).Parent;
ViewControlHelper.SetFocus(cellToFocus, e);

Error while waiting for device: Time out after 300seconds waiting for emulator to come online

Restarting ADB server works for me, but no need to go for it from command line.
Ctrl + Maj + A -> Troubleshoot Device Connections -> Next -> Next -> Restart ADB Server

enter image description here

How to copy a file from remote server to local machine?

For example, your remote host is example.com and remote login name is user1:

scp [email protected]:/path/to/file /path/to/store/file

Pie chart with jQuery

There is a new player in the field, offering advanced Navigation Charts that are using Canvas for super-smooth animations and performance:

https://zoomcharts.com/

Example of charts:

interactive pie chart

Documentation: https://zoomcharts.com/en/javascript-charts-library/charts-packages/pie-chart/

What is cool about this lib:

  • Others slice can be expanded
  • Pie offers drill down for hierarchical structures (see example)
  • write your own data source controller easily, or provide simple json file
  • export high res images out of box
  • full touch support, works smoothly on iPad, iPhone, android, etc.

enter image description here

Charts are free for non-commercial use, commercial licenses and technical support available as well.

Also interactive Time charts and Net Charts are there for you to use. enter image description here

enter image description here

Charts come with extensive API and Settings, so you can control every aspect of the charts.

How to extract Month from date in R

Without the need of an external package:

if your date is in the following format:

myDate = as.POSIXct("2013-01-01")

Then to get the month number:

format(myDate,"%m")

And to get the month string:

format(myDate,"%B")

How do you synchronise projects to GitHub with Android Studio?

Now you can do it like so (you do not need to go to github or open new directory from git):

enter image description here

How to check for DLL dependency?

In the past (i.e. WinXP days), I used to depend/rely on DLL Dependency Walker (depends.exe) but there are times when I am still not able to determine the DLL issue(s). Ideally, we'd like to find out before runtime by inspections but if that does not resolve it (or taking too much time), you can try enabling the "loader snap" as described on http://blogs.msdn.com/b/junfeng/archive/2006/11/20/debugging-loadlibrary-failures.aspx and https://msdn.microsoft.com/en-us/library/windows/hardware/ff556886(v=vs.85).aspx and briefly mentioned LoadLibrary fails; GetLastError no help

WARNING: I've messed up my Windows in the past fooling around with gflag making it crawl to its knees, you have been forewarned.

enter image description here

Note: "Loader snap" is per-process so the UI enable won't stay checked (use cdb or glfags -i)

Django, creating a custom 500/404 error page

From the page you referenced:

When you raise Http404 from within a view, Django will load a special view devoted to handling 404 errors. It finds it by looking for the variable handler404 in your root URLconf (and only in your root URLconf; setting handler404 anywhere else will have no effect), which is a string in Python dotted syntax – the same format the normal URLconf callbacks use. A 404 view itself has nothing special: It’s just a normal view.

So I believe you need to add something like this to your urls.py:

handler404 = 'views.my_404_view'

and similar for handler500.

Xcode Error: "The app ID cannot be registered to your development team."

Meet same Issue on one mac, but ok on another mac. I'm sure bundle ID is fine and unique.

I know it is provisioning profile issue, so Try refreshing the provisioning profile on your Local computer. Then It Works!

  1. cd ~/Library/MobileDevice/Provisioning\ Profiles
  2. rm *
  3. Xcode > Preferences... > Accounts > click your Account and Team name > click Download Manual Profiles
  4. Run app again

CSS /JS to prevent dragging of ghost image?

The be-all-end-all, for no selecting or dragging, with all browser prefixes:

-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-o-user-select: none;
-ms-user-select: none;
user-select: none;

-webkit-user-drag: none;
-khtml-user-drag: none;
-moz-user-drag: none;
-o-user-drag: none;
-ms-user-drag: none;
user-drag: none;

You can also set the draggable attribute to false. You can do this with inline HTML: draggable="false", with Javascript: elm.draggable = false, or with jQuery: elm.attr('draggable', false).

You can also handle the onmousedown function to return false. You can do this with inline HTML: onmousedown="return false", with Javascript: elm.onmousedown=()=>return false;, or with jQuery: elm.mousedown(()=>return false)

How do I insert datetime value into a SQLite database?

The way to store dates in SQLite is:

 yyyy-mm-dd hh:mm:ss.xxxxxx

SQLite also has some date and time functions you can use. See SQL As Understood By SQLite, Date And Time Functions.

select dept names who have more than 2 employees whose salary is greater than 1000

select D.DeptName from [Department] D where D.DeptID in 
( 
    select E.DeptId from [Employee] E
    where E.Salary > 1000
    group by E.DeptId
    having count(*) > 2
)

How to get Rails.logger printing to the console/stdout when running rspec?

You can define a method in spec_helper.rb that sends a message both to Rails.logger.info and to puts and use that for debugging:

def log_test(message)
    Rails.logger.info(message)
    puts message
end

What is the most efficient/elegant way to parse a flat table into a tree?

Assuming that you know that the root elements are zero, here's the pseudocode to output to text:

function PrintLevel (int curr, int level)
    //print the indents
    for (i=1; i<=level; i++)
        print a tab
    print curr \n;
    for each child in the table with a parent of curr
        PrintLevel (child, level+1)


for each elementID where the parentid is zero
    PrintLevel(elementID, 0)

How to set the size of a column in a Bootstrap responsive table

You could use inline styles and define the width in the <th> tag. Make it so that the sum of the widths = 100%.

    <tr>
        <th style="width:10%">Size</th>
        <th style="width:30%">Bust</th>
        <th style="width:50%">Waist</th>
        <th style="width:10%">Hips</th>
    </tr>

Bootply demo

Typically using inline styles is not ideal, however this does provide flexibility because you can get very specific and granular with exact widths.

Have log4net use application config file for configuration data

Have you tried adding a configsection handler to your app.config? e.g.

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>

How to remove the querystring and get only the url?

If you want to get request path (more info):

echo parse_url($_SERVER["REQUEST_URI"])['path']

If you want to remove the query and (and maybe fragment also):

function strposa($haystack, $needles=array(), $offset=0) {
        $chr = array();
        foreach($needles as $needle) {
                $res = strpos($haystack, $needle, $offset);
                if ($res !== false) $chr[$needle] = $res;
        }
        if(empty($chr)) return false;
        return min($chr);
}
$i = strposa($_SERVER["REQUEST_URI"], ['#', '?']);
echo strrpos($_SERVER["REQUEST_URI"], 0, $i);

Email & Phone Validation in Swift

Swift 4+

You can use simplified regex "^[6-9]\\d{9}$"

^     #Match the beginning of the string
[6-9] #Match a 6, 7, 8 or 9
\\d   #Match a digit (0-9 and anything else that is a "digit" in the regex engine)
{9}   #Repeat the previous "\d" 9 times (9 digits)
$     #Match the end of the string

From Reference

Indian 10 Digit Mobile validation(can start with 6,7,8,9) -

extension String {
    var isValidContact: Bool {
        let phoneNumberRegex = "^[6-9]\\d{9}$"
        let phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneNumberRegex)
        let isValidPhone = phoneTest.evaluate(with: self)
        return isValidPhone
    }
} 

Usage:-

print("9292929292".isValidContact)//true
print("5454545454".isValidContact)//false

For email validation you can check this

Node.js Generate html

You can use jade + express:

app.get('/', function (req, res) { res.render('index', { title : 'Home' } ) });

above you see 'index' and an object {title : 'Home'}, 'index' is your html and the object is your data that will be rendered in your html.

What determines the monitor my app runs on?

Here's what I've found. If you want an app to open on your secondary monitor by default do the following:

1. Open the application.
2. Re-size the window so that it is not maximized or minimized.
3. Move the window to the monitor you want it to open on by default.
4. Close the application.  Do not re-size prior to closing.
5. Open the application.
   It should open on the monitor you just moved it to and closed it on.
6. Maximize the window.

The application will now open on this monitor by default. If you want to change it to another monitor, just follow steps 1-6 again.

How to set default value to all keys of a dict object in python?

You can use the following class. Just change zero to any default value you like. The solution was tested in Python 2.7.

class cDefaultDict(dict):
    # dictionary that returns zero for missing keys
    # keys with zero values are not stored

    def __missing__(self,key):
        return 0

    def __setitem__(self, key, value):
        if value==0:
            if key in self:  # returns zero anyway, so no need to store it
                del self[key]
        else:
            dict.__setitem__(self, key, value)

How to make android listview scrollable?

I know this question is 4-5 years old, but still, this might be useful:

Sometimes, if you have only a few elements that "exit the screen", the list might not scroll. That's because the operating system doesn't view it as actually exceeding the screen.

I'm saying this because I ran into this problem today - I only had 2 or 3 elements that were exceeding the screen limits, and my list wasn't scrollable. And it was a real mystery. As soon as I added a few more, it started to scroll.

So you have to make sure it's not a design problem at first, like the list appearing to go beyond the borders of the screen but in reality, "it doesn't", and adjust its dimensions and margin values and see if it's starting to "become scrollable". It did, for me.

Oracle - Why does the leading zero of a number disappear when converting it TO_CHAR

It's the default formatting that Oracle provides. If you want leading zeros on output, you'll need to explicitly provide the format. Use:

SELECT TO_CHAR(0.56,'0.99') FROM DUAL;

or even:

SELECT TO_CHAR(.56,'0.99') FROM DUAL;

The same is true for trailing zeros:

SQL> SELECT TO_CHAR(.56,'0.990') val FROM DUAL;

VAL
------
 0.560

The general form of the TO_CHAR conversion function is:

TO_CHAR(number, format)

Reset select2 value and show placeholder

One [very] hacky way to do it (I saw it work for version 4.0.3):

var selection = $("#DelegateId").data("select2").selection;
var evt = document.createEvent("UIEvents");
selection._handleClear(evt);
selection.trigger("toggle", {});
  • allowClear must be set to true
  • an empty option must exist in the select element

Best JavaScript compressor

If you use Packer, just go far the 'shrink variables' option and gzip the resulting code. The base62 option is only for if your server cannot send gzipped files. Packer with 'shrink vars' achieves better compression the YUI, but can introduce bugs if you've skipped a semicolon somewhere.

base62 is basically a poor man's gzip, which is why gzipping base62-ed code gives you bigger files than gzipping shrink-var-ed code.

Jquery ajax call click event submit button

You did not add # before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.

See documentation: http://api.jquery.com/category/selectors/
its your friend.

Try this:

It seems that id: $("#Shareitem").val() is wrong if you want to pass the value of

<input type="hidden" name="id" value="" id="id">

you need to change this line:

id: $("#Shareitem").val()

by

id: $("#id").val()

All together:

 <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script>
    $(document).ready(function(){
      $("#Shareitem").click(function(e){
          e.preventDefault();
        $.ajax({type: "POST",
                url: "/imball-reagens/public/shareitem",
                data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },
                success:function(result){
          $("#sharelink").html(result);
        }});
      });
    });
    </script>

Which header file do you include to use bool type in c in linux?

bool is just a macro that expands to _Bool. You can use _Bool with no #include very much like you can use int or double; it is a C99 keyword.

The macro is defined in <stdbool.h> along with 3 other macros.

The macros defined are

  • bool: macro expands to _Bool
  • false: macro expands to 0
  • true: macro expands to 1
  • __bool_true_false_are_defined: macro expands to 1

'module' object is not callable - calling method in another file

  • from a directory_of_modules, you can import a specific_module.py
  • this specific_module.py, can contain a Class with some_methods() or just functions()
  • from a specific_module.py, you can instantiate a Class or call functions()
  • from this Class, you can execute some_method()

Example:

#!/usr/bin/python3
from directory_of_modules import specific_module
instance = specific_module.DbConnect("username","password")
instance.login()

Excerpts from PEP 8 - Style Guide for Python Code:

Modules should have short and all-lowercase names.

Notice: Underscores can be used in the module name if it improves readability.

A Python module is simply a source file(*.py), which can expose:

  • Class: names using the "CapWords" convention.

  • Function: names in lowercase, words separated by underscores.

  • Global Variables: the conventions are about the same as those for Functions.

Convert the values in a column into row names in an existing data frame

You can execute this in 2 simple statements:

row.names(samp) <- samp$names
samp[1] <- NULL

How to check if a specific key is present in a hash or not?

While Hash#has_key? gets the job done, as Matz notes here, it has been deprecated in favour of Hash#key?.

hash.key?(some_key)

Loop through an array php

You can use also this without creating additional variables nor copying the data in the memory like foreach() does.

while (false !== (list($item, $values) = each($array)))
{
    ...
}

MVC3 DropDownListFor - a simple example?

     @Html.DropDownListFor(m => m.SelectedValue,Your List,"ID","Values")

Here Value is that object of model where you want to save your Selected Value

What is the difference between "::" "." and "->" in c++

Put very simple :: is the scoping operator, . is the access operator (I forget what the actual name is?), and -> is the dereference arrow.

:: - Scopes a function. That is, it lets the compiler know what class the function lives in and, thus, how to call it. If you are using this operator to call a function, the function is a static function.

. - This allows access to a member function on an already created object. For instance, Foo x; x.bar() calls the method bar() on instantiated object x which has type Foo. You can also use this to access public class variables.

-> - Essentially the same thing as . except this works on pointer types. In essence it dereferences the pointer, than calls .. Using this is equivalent to (*ptr).method()

How to make type="number" to positive numbers only

With text type of input you can use this for a better validation,

return (event.keyCode? (event.keyCode == 69 ? false : event.keyCode >= 48 && event.keyCode <= 57) : (event.charCode >= 48 && event.charCode <= 57))? true : event.preventDefault();

How do I use select with date condition?

select sysdate from dual
30-MAR-17

select count(1) from masterdata where to_date(inactive_from_date,'DD-MON-YY'
between '01-JAN-16' to '31-DEC-16'

12998 rows

How to add/subtract dates with JavaScript?

//In order to get yesterday's date in mm/dd/yyyy.


function gimmeYesterday(toAdd) {
            if (!toAdd || toAdd == '' || isNaN(toAdd)) return;
            var d = new Date();
            d.setDate(d.getDate() - parseInt(toAdd));
var yesterDAY = (d.getMonth() +1) + "/" + d.getDate() + "/" + d.getFullYear();
$("#endDate").html(yesterDAY);
        }
$(document).ready(function() {
gimmeYesterday(1);
});

you can try here: http://jsfiddle.net/ZQAHE/

Concatenating two std::vectors

Add this one to your header file:

template <typename T> vector<T> concat(vector<T> &a, vector<T> &b) {
    vector<T> ret = vector<T>();
    copy(a.begin(), a.end(), back_inserter(ret));
    copy(b.begin(), b.end(), back_inserter(ret));
    return ret;
}

and use it this way:

vector<int> a = vector<int>();
vector<int> b = vector<int>();

a.push_back(1);
a.push_back(2);
b.push_back(62);

vector<int> r = concat(a, b);

r will contain [1,2,62]

How do you format code in Visual Studio Code (VSCode)

  1. Right click somewhere in the content area (text) for the file
  2. Select Format Document from the menu:
    • Windows: Alt Shift F
    • Linux: Alt Shift I
    • macOS: ? ? F

Enter image description here

Algorithm to randomly generate an aesthetically-pleasing color palette

Use distinct-colors.

Written in javascript.

It generates a palette of visually distinct colors.

distinct-colors is highly configurable:

  • Choose how many colors are in the palette
  • Restrict the hue to a specific range
  • Restrict the chroma (saturation) to a specific range
  • Restrict the lightness to a specific range
  • Configure general quality of the palette

Convert an int to ASCII character

          A PROGRAM TO CONVERT INT INTO ASCII.




          #include<stdio.h>
          #include<string.h>
          #include<conio.h>

           char data[1000]= {' '};           /*thing in the bracket is optional*/
           char data1[1000]={' '};
           int val, a;
           char varray [9];

           void binary (int digit)
          {
              if(digit==0)
               val=48;
              if(digit==1)
               val=49;
              if(digit==2)
               val=50;
              if(digit==3)
               val=51;
              if(digit==4)
               val=52;
              if(digit==5)
               val=53;
              if(digit==6)
               val=54;
              if(digit==7)
               val=55;
              if(digit==8)
               val=56;
              if(digit==9)
                val=57;
                a=0;

           while(val!=0)
           {
              if(val%2==0)
               {
                varray[a]= '0';
               }

               else
               varray[a]='1';
               val=val/2;
               a++;
           }


           while(a!=7)
          {
            varray[a]='0';
            a++;
           }


          varray [8] = NULL;
          strrev (varray);
          strcpy (data1,varray);
          strcat (data1,data);
          strcpy (data,data1);

         }


          void main()
         {
           int num;
           clrscr();
           printf("enter number\n");
           scanf("%d",&num);
           if(num==0)
           binary(0);
           else
           while(num>0)
           {
           binary(num%10);
           num=num/10;
           }
           puts(data);
           getch();

           }

I check my coding and its working good.let me know if its helpful.thanks.

setState() inside of componentDidUpdate()

You can use setStateinside componentDidUpdate. The problem is that somehow you are creating an infinite loop because there's no break condition.

Based on the fact that you need values that are provided by the browser once the component is rendered, I think your approach about using componentDidUpdate is correct, it just needs better handling of the condition that triggers the setState.

Get max and min value from array in JavaScript

if you have "scattered" (not inside an array) values you can use:

var max_value = Math.max(val1, val2, val3, val4, val5);

Shell script to set environment variables

Run the script as source= to run in debug mode as well.

source= ./myscript.sh

One line if/else condition in linux shell scripting

It's not a direct answer to the question but you could just use the OR-operator

( grep "#SystemMaxUse=" journald.conf > /dev/null && sed -i 's/\#SystemMaxUse=/SystemMaxUse=50M/g' journald.conf ) || echo "This file has been edited. You'll need to do it manually."

Splitting dataframe into multiple dataframes

Groupby can helps you:

grouped = data.groupby(['name'])

Then you can work with each group like with a dataframe for each participant. And DataFrameGroupBy object methods such as (apply, transform, aggregate, head, first, last) return a DataFrame object.

Or you can make list from grouped and get all DataFrame's by index:

l_grouped = list(grouped)

l_grouped[0][1] - DataFrame for first group with first name.

run main class of Maven project

Try the maven-exec-plugin. From there:

mvn exec:java -Dexec.mainClass="com.example.Main"

This will run your class in the JVM. You can use -Dexec.args="arg0 arg1" to pass arguments.

If you're on Windows, apply quotes for exec.mainClass and exec.args:

mvn exec:java -D"exec.mainClass"="com.example.Main"

If you're doing this regularly, you can add the parameters into the pom.xml as well:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>exec-maven-plugin</artifactId>
  <version>1.2.1</version>
  <executions>
    <execution>
      <goals>
        <goal>java</goal>
      </goals>
    </execution>
  </executions>
  <configuration>
    <mainClass>com.example.Main</mainClass>
    <arguments>
      <argument>foo</argument>
      <argument>bar</argument>
    </arguments>
  </configuration>
</plugin>

Angular directives - when and how to use compile, controller, pre-link and post-link

In which order the directive functions are executed?

For a single directive

Based on the following plunk, consider the following HTML markup:

<body>
    <div log='some-div'></div>
</body>

With the following directive declaration:

myApp.directive('log', function() {
  
    return {
        controller: function( $scope, $element, $attrs, $transclude ) {
            console.log( $attrs.log + ' (controller)' );
        },
        compile: function compile( tElement, tAttributes ) {
            console.log( tAttributes.log + ' (compile)'  );
            return {
                pre: function preLink( scope, element, attributes ) {
                    console.log( attributes.log + ' (pre-link)'  );
                },
                post: function postLink( scope, element, attributes ) {
                    console.log( attributes.log + ' (post-link)'  );
                }
            };
         }
     };  
     
});

The console output will be:

some-div (compile)
some-div (controller)
some-div (pre-link)
some-div (post-link)

We can see that compile is executed first, then controller, then pre-link and last is post-link.

For nested directives

Note: The following does not apply to directives that render their children in their link function. Quite a few Angular directives do so (like ngIf, ngRepeat, or any directive with transclude). These directives will natively have their link function called before their child directives compile is called.

The original HTML markup is often made of nested elements, each with its own directive. Like in the following markup (see plunk):

<body>
    <div log='parent'>
        <div log='..first-child'></div>
        <div log='..second-child'></div>
    </div>
</body>

The console output will look like this:

// The compile phase
parent (compile)
..first-child (compile)
..second-child (compile)

// The link phase   
parent (controller)
parent (pre-link)
..first-child (controller)
..first-child (pre-link)
..first-child (post-link)
..second-child (controller)
..second-child (pre-link)
..second-child (post-link)
parent (post-link)

We can distinguish two phases here - the compile phase and the link phase.

The compile phase

When the DOM is loaded Angular starts the compile phase, where it traverses the markup top-down, and calls compile on all directives. Graphically, we could express it like so:

An image illustrating the compilation loop for children

It is perhaps important to mention that at this stage, the templates the compile function gets are the source templates (not instance template).

The link phase

DOM instances are often simply the result of a source template being rendered to the DOM, but they may be created by ng-repeat, or introduced on the fly.

Whenever a new instance of an element with a directive is rendered to the DOM, the link phase starts.

In this phase, Angular calls controller, pre-link, iterates children, and call post-link on all directives, like so:

An illustration demonstrating the link phase steps

how to detect search engine bots with php?

I'm using this code, pretty good. You will very easy to know user-agents visitted your site. This code is opening a file and write the user_agent down the file. You can check each day this file by go to yourdomain.com/useragent.txt and know about new user_agents and put them in your condition of if clause.

$user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
if(!preg_match("/Googlebot|MJ12bot|yandexbot/i", $user_agent)){
    // if not meet the conditions then
    // do what you need

    // here open a file and write the user_agent down the file. You can check each day this file useragent.txt and know about new user_agents and put them in your condition of if clause
    if($user_agent!=""){
        $myfile = fopen("useragent.txt", "a") or die("Unable to open file useragent.txt!");
        fwrite($myfile, $user_agent);
        $user_agent = "\n";
        fwrite($myfile, $user_agent);
        fclose($myfile);
    }
}

This is the content of useragent.txt

Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)
Mozilla/5.0 (compatible; MJ12bot/v1.4.6; http://mj12bot.com/)Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)
Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.96 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)mozilla/5.0 (compatible; yandexbot/3.0; +http://yandex.com/bots)
mozilla/5.0 (compatible; yandexbot/3.0; +http://yandex.com/bots)
mozilla/5.0 (compatible; yandexbot/3.0; +http://yandex.com/bots)
mozilla/5.0 (compatible; yandexbot/3.0; +http://yandex.com/bots)
mozilla/5.0 (compatible; yandexbot/3.0; +http://yandex.com/bots)
mozilla/5.0 (iphone; cpu iphone os 9_3 like mac os x) applewebkit/601.1.46 (khtml, like gecko) version/9.0 mobile/13e198 safari/601.1
mozilla/5.0 (windows nt 6.1; wow64) applewebkit/537.36 (khtml, like gecko) chrome/53.0.2785.143 safari/537.36
mozilla/5.0 (compatible; linkdexbot/2.2; +http://www.linkdex.com/bots/)
mozilla/5.0 (windows nt 6.1; wow64; rv:49.0) gecko/20100101 firefox/49.0
mozilla/5.0 (windows nt 6.1; wow64; rv:33.0) gecko/20100101 firefox/33.0
mozilla/5.0 (windows nt 6.1; wow64; rv:49.0) gecko/20100101 firefox/49.0
mozilla/5.0 (windows nt 6.1; wow64; rv:33.0) gecko/20100101 firefox/33.0
mozilla/5.0 (windows nt 6.1; wow64; rv:49.0) gecko/20100101 firefox/49.0
mozilla/5.0 (windows nt 6.1; wow64; rv:33.0) gecko/20100101 firefox/33.0
mozilla/5.0 (windows nt 6.1; wow64; rv:49.0) gecko/20100101 firefox/49.0
mozilla/5.0 (windows nt 6.1; wow64; rv:33.0) gecko/20100101 firefox/33.0
mozilla/5.0 (windows nt 6.1; wow64) applewebkit/537.36 (khtml, like gecko) chrome/53.0.2785.143 safari/537.36
mozilla/5.0 (windows nt 6.1; wow64) applewebkit/537.36 (khtml, like gecko) chrome/53.0.2785.143 safari/537.36
mozilla/5.0 (compatible; baiduspider/2.0; +http://www.baidu.com/search/spider.html)
zoombot (linkbot 1.0 http://suite.seozoom.it/bot.html)
mozilla/5.0 (windows nt 10.0; wow64) applewebkit/537.36 (khtml, like gecko) chrome/44.0.2403.155 safari/537.36 opr/31.0.1889.174
mozilla/5.0 (windows nt 10.0; wow64) applewebkit/537.36 (khtml, like gecko) chrome/44.0.2403.155 safari/537.36 opr/31.0.1889.174
sogou web spider/4.0(+http://www.sogou.com/docs/help/webmasters.htm#07)
mozilla/5.0 (windows nt 10.0; wow64) applewebkit/537.36 (khtml, like gecko) chrome/44.0.2403.155 safari/537.36 opr/31.0.1889.174

How can I select all children of an element except the last child?

How to select all children of an element except the last child using CSS?

Answer: this code will work

<style>
.parent *:not(:last-child) { 
  color:red;
}
</style>

<div class='parent'>
  <p>this is paragraph</p>
  <h1>this is heading</h1>
  <b>text is bold</b>
</div>

How to get a list of images on docker registry v2

We wrote a CLI tool for this purpose: docker-ls It allows you to browse a docker registry and supports authentication via token or basic auth.

javascript change background color on click

I'm suggest that you learn about Jquery, most popular JS library. With jquery it's simple to acomplish what you want.Simle example below:

$(“#DIV_YOU_WANT_CHANGE”).click(function() {
    $(this).addClass(“.your_class_with_new_color”);
}); 

Checking for NULL pointer in C/C++

I use if (ptr), but this is completely not worth arguing about.

I like my way because it's concise, though others say == NULL makes it easier to read and more explicit. I see where they're coming from, I just disagree the extra stuff makes it any easier. (I hate the macro, so I'm biased.) Up to you.

I disagree with your argument. If you're not getting warnings for assignments in a conditional, you need to turn your warning levels up. Simple as that. (And for the love of all that is good, don't switch them around.)

Note in C++0x, we can do if (ptr == nullptr), which to me does read nicer. (Again, I hate the macro. But nullptr is nice.) I still do if (ptr), though, just because it's what I'm used to.

Eclipse count lines of code

I created a Eclipse plugin, which can count the lines of source code. It support Kotlin, Java, Java Script, JSP, XML, C/C++, C#, and many other file types.

Please take a look at it. Any feedback would be appreciated!

the git-hub repository is here

How can I use JavaScript in Java?

You can use ScriptEngine, example:


public class Main {
    public static void main(String[] args) {
        StringBuffer javascript = null;
        ScriptEngine runtime = null;

        try {
            runtime = new ScriptEngineManager().getEngineByName("javascript");
            javascript = new StringBuffer();

            javascript.append("1 + 1");

            double result = (Double) runtime.eval(javascript.toString());

            System.out.println("Result: " + result);
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
}

How can I disable inherited css styles?

The cleanest solution is probably to specify your divs as exact children.

Try changing this:

div.rounded div div {
    background: url('bl.gif') no-repeat bottom left;
}

To this:

div.rounded > div > div {
    background: url('bl.gif') no-repeat bottom left;
}

How to print the values of slices

You can try the %v, %+v or %#v verbs of go fmt:

fmt.Printf("%v", projects)

If your array (or here slice) contains struct (like Project), you will see their details.
For more precision, you can use %#v to print the object using Go-syntax, as for a literal:

%v  the value in a default format.
    when printing structs, the plus flag (%+v) adds field names
%#v a Go-syntax representation of the value

For basic types, fmt.Println(projects) is enough.


Note: for a slice of pointers, that is []*Project (instead of []Project), you are better off defining a String() method in order to display exactly what you want to see (or you will see only pointer address).
See this play.golang example.

How to print something when running Puppet client?

Here is the puppet script with all the available puppet log functions.

log_levels.pp

node default {
  notice("try to run this script with -v and -d to see difference between log levels")
  notice("function documentation is available here: http://docs.puppetlabs.com/references/latest/function.html")
  notice("--------------------------------------------------------------------------")

  debug("this is debug. visible only with -d or --debug")
  info("this is info. visible only with -v or --verbose or -d or --debug")
  alert("this is alert. always visible")
  crit("this is crit. always visible")
  emerg("this is emerg. always visible")
  err("this is err. always visible")
  warning("and this is warning. always visible")
  notice("this is notice. always visible")
  #fail will break execution
  fail("this is fail. always visible. fail will break execution process")

}

Script output (on puppet 2.7): different log levels colors

NB: puppet 3.x colours may alter (all the errors will be printed in red)!

Transform hexadecimal information to binary using a Linux command

As @user786653 suggested, use the xxd(1) program:

xxd -r -p input.txt output.bin

Append key/value pair to hash with << in Ruby

Since hashes aren't inherently ordered, there isn't a notion of appending. Ruby hashes since 1.9 maintain insertion order, however. Here are the ways to add new key/value pairs.

The simplest solution is

h[:key] = "bar"

If you want a method, use store:

h.store(:key, "bar")

If you really, really want to use a "shovel" operator (<<), it is actually appending to the value of the hash as an array, and you must specify the key:

h[:key] << "bar"

The above only works when the key exists. To append a new key, you have to initialize the hash with a default value, which you can do like this:

h = Hash.new {|h, k| h[k] = ''}
h[:key] << "bar"

You may be tempted to monkey patch Hash to include a shovel operator that works in the way you've written:

class Hash
  def <<(k,v)
    self.store(k,v)
  end
end

However, this doesn't inherit the "syntactic sugar" applied to the shovel operator in other contexts:

h << :key, "bar" #doesn't work
h.<< :key, "bar" #works

How to force garbage collection in Java?

Your best option is to call System.gc() which simply is a hint to the garbage collector that you want it to do a collection. There is no way to force and immediate collection though as the garbage collector is non-deterministic.

Associating enums with strings in C#

Taken from @EvenMien and added in some of the comments. (Also for my own use case)

public struct AgentAction
{
    private AgentAction(string value) { Value = value; }

    public string Value { get; private set; }

    public override string ToString()
    {
        return this.Value;
    }

    public static AgentAction Login = new AgentAction("Logout");
    public static AgentAction Logout = new AgentAction("Logout");

    public static implicit operator string(AgentAction action) { return action.ToString(); }
}

working with negative numbers in python

Try this on your TA:

# Simulate multiplying two N-bit two's-complement numbers
# into a 2N-bit accumulator
# Use shift-add so that it's O(base_2_log(N)) not O(N)

for numa, numb in ((3, 5), (-3, 5), (3, -5), (-3, -5), (-127, -127)):
    print numa, numb,
    accum = 0
    negate = False
    if numa < 0:
        negate = True
        numa = -numa
    while numa:
        if numa & 1:
            accum += numb
        numa >>= 1
        numb <<= 1
    if negate:
        accum = -accum
    print accum

output:

3 5 15
-3 5 -15
3 -5 -15
-3 -5 15
-127 -127 16129

How to reverse an std::string?

Try

string reversed(temp.rbegin(), temp.rend());

EDIT: Elaborating as requested.

string::rbegin() and string::rend(), which stand for "reverse begin" and "reverse end" respectively, return reverse iterators into the string. These are objects supporting the standard iterator interface (operator* to dereference to an element, i.e. a character of the string, and operator++ to advance to the "next" element), such that rbegin() points to the last character of the string, rend() points to the first one, and advancing the iterator moves it to the previous character (this is what makes it a reverse iterator).

Finally, the constructor we are passing these iterators into is a string constructor of the form:

template <typename Iterator>
string(Iterator first, Iterator last);

which accepts a pair of iterators of any type denoting a range of characters, and initializes the string to that range of characters.

C# error: "An object reference is required for the non-static field, method, or property"

The Main method is Static. You can not invoke a non-static method from a static method.

GetRandomBits()

is not a static method. Either you have to create an instance of Program

Program p = new Program();
p.GetRandomBits();

or make

GetRandomBits() static.

Cannot import XSSF in Apache POI

You did not described the environment, anyway, you should download apache poi libraries. If you are using eclipse , right click on your root project , so properties and in java build path add external jar and import in your project those libraries :

xmlbeans-2.6.0 ; poi-ooxml-schemas- ... ; poi-ooxml- ... ; poi- .... ;

Find out if string ends with another string in C++

Use this function:

inline bool ends_with(std::string const & value, std::string const & ending)
{
    if (ending.size() > value.size()) return false;
    return std::equal(ending.rbegin(), ending.rend(), value.rbegin());
}

Make Frequency Histogram for Factor Variables

It seems like you want barplot(prop.table(table(animals))):

enter image description here

However, this is not a histogram.

In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?

Only using Session.Clear() when a user logs out can pose a security hole. As the session is still valid as far as the Web Server is concerned. It is then a reasonably trivial matter to sniff, and grab the session Id, and hijack that session.

For this reason, when logging a user out it would be safer and more sensible to use Session.Abandon() so that the session is destroyed, and a new session created (even though the logout UI page would be part of the new session, the new session would not have any of the users details in it and hijacking the new session would be equivalent to having a fresh session, hence it would be mute).

How to iterate through XML in Powershell?

PowerShell has built-in XML and XPath functions. You can use the Select-Xml cmdlet with an XPath query to select nodes from XML object and then .Node.'#text' to access node value.

[xml]$xml = Get-Content $serviceStatePath
$nodes = Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml
$nodes | ForEach-Object {$_.Node.'#text'}

Or shorter

[xml]$xml = Get-Content $serviceStatePath
Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml |
  % {$_.Node.'#text'}

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

Maybe something like this, where you could select more than one element if you'd like?

$("#number").each(function(){
    $(this).val(parseFloat($(this).val()).toFixed(2));
});

Using Axios GET with Authorization Header in React-Native App

For anyone else that comes across this post and might find it useful... There is actually nothing wrong with my code. I made the mistake of requesting client_credentials type access code instead of password access code (#facepalms). FYI I am using urlencoded post hence the use of querystring.. So for those that may be looking for some example code.. here is my full request

Big thanks to @swapnil for trying to help me debug this.

   const data = {
      grant_type: USER_GRANT_TYPE,
      client_id: CLIENT_ID,
      client_secret: CLIENT_SECRET,
      scope: SCOPE_INT,
      username: DEMO_EMAIL,
      password: DEMO_PASSWORD
    };



  axios.post(TOKEN_URL, Querystring.stringify(data))   
   .then(response => {
      console.log(response.data);
      USER_TOKEN = response.data.access_token;
      console.log('userresponse ' + response.data.access_token); 
    })   
   .catch((error) => {
      console.log('error ' + error);   
   });



const AuthStr = 'Bearer '.concat(USER_TOKEN); 
axios.get(URL, { headers: { Authorization: AuthStr } })
 .then(response => {
     // If request is good...
     console.log(response.data);
  })
 .catch((error) => {
     console.log('error ' + error);
  });

How to list the size of each file and directory and sort by descending size in Bash?

you can use the below to list files by size du -h | sort -hr | more or du -h --max-depth=0 * | sort -hr | more

How to fix Ora-01427 single-row subquery returns more than one row in select?

Use the following query:

SELECT E.I_EmpID AS EMPID,
       E.I_EMPCODE AS EMPCODE,
       E.I_EmpName AS EMPNAME,
       REPLACE(TO_CHAR(A.I_REQDATE, 'DD-Mon-YYYY'), ' ', '') AS FROMDATE,
       REPLACE(TO_CHAR(A.I_ENDDATE, 'DD-Mon-YYYY'), ' ', '') AS TODATE,
       TO_CHAR(NOD) AS NOD,
       DECODE(A.I_DURATION,
              'FD',
              'FullDay',
              'FN',
              'ForeNoon',
              'AN',
              'AfterNoon') AS DURATION,
       L.I_LeaveType AS LEAVETYPE,
       REPLACE(TO_CHAR((SELECT max(C.I_WORKDATE)
                         FROM T_COMPENSATION C
                        WHERE C.I_COMPENSATEDDATE = A.I_REQDATE
                          AND C.I_EMPID = A.I_EMPID),
                       'DD-Mon-YYYY'),
               ' ',
               '') AS WORKDATE,
       A.I_REASON AS REASON,
       AP.I_REJECTREASON AS REJECTREASON
  FROM T_LEAVEAPPLY A
 INNER JOIN T_EMPLOYEE_MS E
    ON A.I_EMPID = E.I_EmpID
   AND UPPER(E.I_IsActive) = 'YES'
   AND A.I_STATUS = '1'
 INNER JOIN T_LeaveType_MS L
    ON A.I_LEAVETYPEID = L.I_LEAVETYPEID
  LEFT OUTER JOIN T_APPROVAL AP
    ON A.I_REQDATE = AP.I_REQDATE
   AND A.I_EMPID = AP.I_EMPID
   AND AP.I_APPROVALSTATUS = '1'
 WHERE E.I_EMPID <> '22'
 ORDER BY A.I_REQDATE DESC

The trick is to force the inner query return only one record by adding an aggregate function (I have used max() here). This will work perfectly as far as the query is concerned, but, honestly, OP should investigate why the inner query is returning multiple records by examining the data. Are these multiple records really relevant business wise?

How to check not in array element

Simply

$os = array("Mac", "NT", "Irix", "Linux");
if (!in_array("BB", $os)) {
    echo "BB is not found";
}

How to write specific CSS for mozilla, chrome and IE

you can use this code in your css file:

 -webkit-top:9px;  
-moz-top:7px; 
top:5px;      

the code -webkit-top:9px; is for chrome, -moz-top:7px is for mozilla and the last one is for IE. Have Fun!!!

What is the difference between Views and Materialized Views in Oracle?

Views

They evaluate the data in the tables underlying the view definition at the time the view is queried. It is a logical view of your tables, with no data stored anywhere else.

The upside of a view is that it will always return the latest data to you. The downside of a view is that its performance depends on how good a select statement the view is based on. If the select statement used by the view joins many tables, or uses joins based on non-indexed columns, the view could perform poorly.

Materialized views

They are similar to regular views, in that they are a logical view of your data (based on a select statement), however, the underlying query result set has been saved to a table. The upside of this is that when you query a materialized view, you are querying a table, which may also be indexed.

In addition, because all the joins have been resolved at materialized view refresh time, you pay the price of the join once (or as often as you refresh your materialized view), rather than each time you select from the materialized view. In addition, with query rewrite enabled, Oracle can optimize a query that selects from the source of your materialized view in such a way that it instead reads from your materialized view. In situations where you create materialized views as forms of aggregate tables, or as copies of frequently executed queries, this can greatly speed up the response time of your end user application. The downside though is that the data you get back from the materialized view is only as up to date as the last time the materialized view has been refreshed.


Materialized views can be set to refresh manually, on a set schedule, or based on the database detecting a change in data from one of the underlying tables. Materialized views can be incrementally updated by combining them with materialized view logs, which act as change data capture sources on the underlying tables.

Materialized views are most often used in data warehousing / business intelligence applications where querying large fact tables with thousands of millions of rows would result in query response times that resulted in an unusable application.


Materialized views also help to guarantee a consistent moment in time, similar to snapshot isolation.

What is Express.js?

Express.js created by TJ Holowaychuk and now managed by the community. It is one of the most popular frameworks in the node.js. Express can also be used to develop various products such as web applications or RESTful API.For more information please read on the expressjs.com official site.

How to Free Inode Usage?

eaccelerator could be causing the problem since it compiles PHP into blocks...I've had this problem with an Amazon AWS server on a site with heavy load. Free up Inodes by deleting the eaccelerator cache in /var/cache/eaccelerator if you continue to have issues.

rm -rf /var/cache/eaccelerator/*

(or whatever your cache dir)

Determine the type of an object?

You can use type() or isinstance().

>>> type([]) is list
True

Be warned that you can clobber list or any other type by assigning a variable in the current scope of the same name.

>>> the_d = {}
>>> t = lambda x: "aight" if type(x) is dict else "NOPE"
>>> t(the_d) 'aight'
>>> dict = "dude."
>>> t(the_d) 'NOPE'

Above we see that dict gets reassigned to a string, therefore the test:

type({}) is dict

...fails.

To get around this and use type() more cautiously:

>>> import __builtin__
>>> the_d = {}
>>> type({}) is dict
True
>>> dict =""
>>> type({}) is dict
False
>>> type({}) is __builtin__.dict
True

How to convert dataframe into time series?

R has multiple ways of represeting time series. Since you're working with daily prices of stocks, you may wish to consider that financial markets are closed on weekends and business holidays so that trading days and calendar days are not the same. However, you may need to work with your times series in terms of both trading days and calendar days. For example, daily returns are calculated from sequential daily closing prices regardless of whether a weekend intervenes. But you may also want to do calendar-based reporting such as weekly price summaries. For these reasons the xts package, an extension of zoo, is commonly used with financial data in R. An example of how it could be used with your data follows.

Assuming the data shown in your example is in the dataframe df

  library(xts)
  stocks <- xts(df[,-1], order.by=as.Date(df[,1], "%m/%d/%Y"))
#
#  daily returns
#
   returns <- diff(stocks, arithmetic=FALSE ) - 1
#
#  weekly open, high, low, close reports
#
   to.weekly(stocks$Hero_close, name="Hero")

which gives the output

           Hero.Open Hero.High Hero.Low Hero.Close
2013-03-15    1669.1   1684.45   1669.1    1684.45
2013-03-22    1690.5   1690.50   1623.3    1659.60
2013-03-28    1617.7   1617.70   1542.0    1542.00

Can't open config file: /usr/local/ssl/openssl.cnf on Windows

SOLUTION!

just set -config parameter location correctly, i.e :

openssl ....................  -config C:\bin\apache\apache2.4.9\conf\openssl.cnf

Viewing root access files/folders of android on windows

Obviously, you'll need a rooted android device. Then set up an FTP server and transfer the files.

jQuery get html of container including the container itself

Firefox doesn't support outerHTML, so you need to define a function to help support it:

function outerHTML(node) {
    return node.outerHTML || (
        function(n) {
            var div = document.createElement('div');
            div.appendChild( n.cloneNode(true) );
            var h = div.innerHTML;
            div = null;
            return h;
        }
    )(node);
}

Then, you can use outerHTML:

var x = outerHTML($('#container').get(0));
$('#save').val(x);

Check whether number is even or odd

Every even number is divisible by two, regardless of if it's a decimal (but the decimal, if present, must also be even). So you can use the % (modulo) operator, which divides the number on the left by the number on the right and returns the remainder...

boolean isEven(double num) { return ((num % 2) == 0); }

final keyword in method parameters

Consider this implementation of foo():

public void foo(final String a) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            System.out.print(a);
        }
    }); 
}

Because the Runnable instance would outlive the method, this wouldn't compile without the final keyword -- final tells the compiler that it's safe to take a copy of the reference (to refer to it later). Thus, it's the reference that's considered final, not the value. In other words: As a caller, you can't mess anything up...

How does Tomcat find the HOME PAGE of my Web App?

In any web application, there will be a web.xml in the WEB-INF/ folder.

If you dont have one in your web app, as it seems to be the case in your folder structure, the default Tomcat web.xml is under TOMCAT_HOME/conf/web.xml

Either way, the relevant lines of the web.xml are

<welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

so any file matching this pattern when found will be shown as the home page.

In Tomcat, a web.xml setting within your web app will override the default, if present.

Further Reading

How do I override the default home page loaded by Tomcat?

Link vs compile vs controller

Also, a good reason to use a controller vs. link function (since they both have access to the scope, element, and attrs) is because you can pass in any available service or dependency into a controller (and in any order), whereas you cannot do that with the link function. Notice the different signatures:

controller: function($scope, $exceptionHandler, $attr, $element, $parse, $myOtherService, someCrazyDependency) {...

vs.

link: function(scope, element, attrs) {... //no services allowed

Create a user with all privileges in Oracle

There are 2 differences:

2 methods creating a user and granting some privileges to him

create user userName identified by password;
grant connect to userName;

and

grant connect to userName identified by password;

do exactly the same. It creates a user and grants him the connect role.

different outcome

resource is a role in oracle, which gives you the right to create objects (tables, procedures, some more but no views!). ALL PRIVILEGES grants a lot more of system privileges.

To grant a user all privileges run you first snippet or

grant all privileges to userName identified by password;

'cannot open git-upload-pack' error in Eclipse when cloning or pushing git repository

Might also be bad SSL cert, fix the server

If you have a GIT server with an outdated or self-signed SSL cert fix the server, afterwards everything should run fine.

Insecure Hotfix: Let the client accept any certificate

The following solution is just a mere hotfix on client side and should be avoided as it compromises security of your credentials and content. There is a detailed explanation for this in "How can I make git accept a self signed certificate?" which offers more complex and more secure solutions you can try out if the following works in general.

In my case it was Eclipse using a different storage for the git config as the command line does and thus not having the option

git config http.sslVerify false

set (which I set using command line for the repo for working with invalid/untrusted SSL cert).

Adding the option insides Eclipse immediately resolves the issue. To add the option

  1. open preferences via application menu Window => Preferences (or on OSX Eclipse => Settings).
  2. Navigate to Team => Git => Configuration
  3. click Add entry..., then put http.sslVerify in the key box and false in the value box.

Seems to be a valid solution for Eclipse 4.4 (Luna), 4.5.x (Mars) and 4.6.x (Neon) on different Operating systems.

Way to create multiline comments in Bash?

I tried the chosen answer, but found when I ran a shell script having it, the whole thing was getting printed to screen (similar to how jupyter notebooks print out everything in '''xx''' quotes) and there was an error message at end. It wasn't doing anything, but: scary. Then I realised while editing it that single-quotes can span multiple lines. So.. lets just assign the block to a variable.

x='
echo "these lines will all become comments."
echo "just make sure you don_t use single-quotes!"

ls -l
date

'

HTML input textbox with a width of 100% overflows table cells

I usually set the width of my inputs to 99% to fix this:

input {
    width: 99%;
}

You can also remove the default styles, but that will make it less obvious that it is a text box. However, I will show the code for that anyway:

input {
    width: 100%;
    border-width: 0;
    margin: 0;
    padding: 0;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
}

Ad@m

Saving lists to txt file

Framework 4: no need to use StreamWriter:

System.IO.File.WriteAllLines("SavedLists.txt", Lists.verbList);

Extract elements of list at odd positions

I like List comprehensions because of their Math (Set) syntax. So how about this:

L = [1, 2, 3, 4, 5, 6, 7]
odd_numbers = [y for x,y in enumerate(L) if x%2 != 0]
even_numbers = [y for x,y in enumerate(L) if x%2 == 0]

Basically, if you enumerate over a list, you'll get the index x and the value y. What I'm doing here is putting the value y into the output list (even or odd) and using the index x to find out if that point is odd (x%2 != 0).

How to add a Hint in spinner in XML

You can set the spinner prompt:

spinner.setPrompt("Select gender...");

How do I download the Android SDK without downloading Android Studio?

I downloaded Android Studio and installed it. The installer said:-

Android Studio => ( 500 MB )

Android SDK => ( 2.3 GB )

Android Studio installer is actually an "Android SDK Installer" along with a sometimes useful tool called "Android Studio".

Most importantly:- Android Studio Installer will not just install the SDK. It will also:-

  • Install the latest build-tools.
  • Install the latest platform-tools.
  • Install the latest AVD Manager which you cannot do without.

Things which you will have to do manually if you install the SDK from its zip file.

Just take it easy. Install the Android Studio.

****************************** Edit ******************************

So, being inspired by the responses in the comments I would like to update my answer.

The update is that only (and only) if 500MB of hard disk space does not matter much to you than you should go for Android Studio otherwise other answers would be better for you.

Android Studio worked for me as I had a 1TB hard disk which is 2000 times 500MB.

Also, note: that RAM sizse should not a restriction for you as you would not even be running Android Studio.

I came to this solution as I was myself stuck in this problem. I tried other answers but for some reason (maybe my in-competencies) they did not work for me. I decided to go for Android Studio and realized that it was merely 18% of the total installation and SDK was 82% of it. While I used to think otherwise. I am not deleting the answers inspite of negative rating as the answer worked for me. I might work for someone elese with a 1 TB hard disk (which is pretty common these days).

How to change SmartGit's licensing option after 30 days of commercial use on ubuntu?

on Mac:

  • First goto ~/Library/Preferences/SmartGit/19.1
  • Second goto preferences.yml file and just comment listx line
  • Third open smart git

React-Native Button style not work

Instead of using button . you can use Text in react native and then make in touchable

<TouchableOpacity onPress={this._onPressButton}> 
   <Text style = {'your custome style'}>
       button name
   </Text>
</TouchableOpacity >

Distinct by property of class with LINQ

You can't effectively use Distinct on a collection of objects (without additional work). I will explain why.

The documentation says:

It uses the default equality comparer, Default, to compare values.

For objects that means it uses the default equation method to compare objects (source). That is on their hash code. And since your objects don't implement the GetHashCode() and Equals methods, it will check on the reference of the object, which are not distinct.

SQL set values of one column equal to values of another column in the same table

UPDATE YourTable
SET ColumnB=ColumnA
WHERE
ColumnB IS NULL 
AND ColumnA IS NOT NULL

Stretch background image css?

.style1 {
  background: url(images/bg.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

Works in:

  • Safari 3+
  • Chrome Whatever+
  • IE 9+
  • Opera 10+ (Opera 9.5 supported background-size but not the keywords)
  • Firefox 3.6+ (Firefox 4 supports non-vendor prefixed version)

In addition you can try this for an IE solution

filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.myBackground.jpg', sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='myBackground.jpg', sizingMethod='scale')";
zoom: 1;

Credit to this article by Chris Coyier http://css-tricks.com/perfect-full-page-background-image/

What is the difference between the | and || or operators?

A single pipe (|) is the bitwise OR operator.

Two pipes (||) is the logical OR operator.

They are not interchangeable.

Procedure expects parameter which was not supplied

In addition to the other answers here, if you've forgotten to put:

cmd.CommandType = CommandType.StoredProcedure;

Then you will also get this error.

How can I make my flexbox layout take 100% vertical space?

You should set height of html, body, .wrapper to 100% (in order to inherit full height) and then just set a flex value greater than 1 to .row3 and not on the others.

_x000D_
_x000D_
.wrapper, html, body {
    height: 100%;
    margin: 0;
}
.wrapper {
    display: flex;
    flex-direction: column;
}
#row1 {
    background-color: red;
}
#row2 {
    background-color: blue;
}
#row3 {
    background-color: green;
    flex:2;
    display: flex;
}
#col1 {
    background-color: yellow;
    flex: 0 0 240px;
    min-height: 100%;/* chrome needed it a question time , not anymore */
}
#col2 {
    background-color: orange;
    flex: 1 1;
    min-height: 100%;/* chrome needed it a question time , not anymore */
}
#col3 {
    background-color: purple;
    flex: 0 0 240px;
    min-height: 100%;/* chrome needed it a question time , not anymore */
}
_x000D_
<div class="wrapper">
    <div id="row1">this is the header</div>
    <div id="row2">this is the second line</div>
    <div id="row3">
        <div id="col1">col1</div>
        <div id="col2">col2</div>
        <div id="col3">col3</div>
    </div>
</div>
_x000D_
_x000D_
_x000D_

DEMO

How to refresh an IFrame using Javascript?

Here is the HTML snippet:

<td><iframe name="idFrame" id="idFrame" src="chat.txt" width="468" height="300"></iframe></td>

And my Javascript code:

window.onload = function(){
setInterval(function(){
    parent.frames['idFrame'].location.href = "chat.txt";
},1000);}

How do I write outputs to the Log in Android?

Look into android.util.Log. It lets you write to the log with various log levels, and you can specify different tags to group the output. For example

Log.w("myApp", "no network");

will output a warning with the tag myApp and the message no network.

How to install Cmake C compiler and CXX compiler

Those errors :

"CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage

CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage"

means you haven't installed mingw32-base.

Go to http://sourceforge.net/projects/mingw/files/latest/download?source=files

and then make sure you select "mingw32-base"

Make sure you set up environment variables correctly in PATH section. "C:\MinGW\bin"

After that open CMake and Select Installation --> Delete Cache.

And click configure button again. I solved the problem this way, hope you solve the problem.

Can't install any package with node npm

There is a possibility that your package.json is causing this.

Parse your package.json to find the unexpected token

or

Delete your package.json file and create one through

npm install 

CSS3 transition events

Just for fun, don't do this!

$.fn.transitiondone = function () {
  return this.each(function () {
    var $this = $(this);
    setTimeout(function () {
      $this.trigger('transitiondone');
    }, (parseFloat($this.css('transitionDelay')) + parseFloat($this.css('transitionDuration'))) * 1000);
  });
};


$('div').on('mousedown', function (e) {
  $(this).addClass('bounce').transitiondone();
});

$('div').on('transitiondone', function () {
  $(this).removeClass('bounce');
});

Adding HTML entities using CSS content

Here are two ways:

  • In HTML:

    <div class="ics">&#9969;</div>

This will result into ⛱

  • In Css:

    .ics::before {content: "\9969;"}

with HTML code <div class="ics"></div>

This also results in ⛱

Delete all local git branches

git branch -d [branch name] for local delete

git branch -D [branch name] also for local delete but forces it

Converting a double to an int in C#

In the provided example your decimal is 8.6. Had it been 8.5 or 9.5, the statement i1 == i2 might have been true. Infact it would have been true for 8.5, and false for 9.5.

Explanation:

Regardless of the decimal part, the second statement, int i2 = (int)score will discard the decimal part and simply return you the integer part. Quite dangerous thing to do, as data loss might occur.

Now, for the first statement, two things can happen. If the decimal part is 5, that is, it is half way through, a decision is to be made. Do we round up or down? In C#, the Convert class implements banker's rounding. See this answer for deeper explanation. Simply put, if the number is even, round down, if the number is odd, round up.

E.g. Consider:

        double score = 8.5;
        int i1 = Convert.ToInt32(score); // 8
        int i2 = (int)score;             // 8

        score += 1;
        i1 = Convert.ToInt32(score);     // 10
        i2 = (int)score;                 // 9

Can "git pull --all" update all my local branches?

The script from @larsmans, a bit improved:

#!/bin/sh

set -x
CURRENT=`git rev-parse --abbrev-ref HEAD`
git fetch --all
for branch in "$@"; do
  if ["$branch" -ne "$CURRENT"]; then
    git checkout "$branch" || exit 1
    git rebase "origin/$branch" || exit 1
  fi
done
git checkout "$CURRENT" || exit 1
git rebase "origin/$CURRENT" || exit 1

This, after it finishes, leaves working copy checked out from the same branch as it was before the script was called.

The git pull version:

#!/bin/sh

set -x
CURRENT=`git rev-parse --abbrev-ref HEAD`
git fetch --all
for branch in "$@"; do
  if ["$branch" -ne "$CURRENT"]; then
    git checkout "$branch" || exit 1
    git pull || exit 1
  fi
done
git checkout "$CURRENT" || exit 1
git pull || exit 1

Find and replace with a newline in Visual Studio Code

  • Control F for search, or Control Shift F for global search
  • Replace >< by >\n< with Regular Expressions enabled

enter image description here

What is the meaning of prepended double colon "::"?

:: is used to link something ( a variable, a function, a class, a typedef etc...) to a namespace, or to a class.

if there is no left hand side before ::, then it underlines the fact you are using the global namespace.

e.g.:

::doMyGlobalFunction();

How to swap two variables in JavaScript

Use a third variable like this:

var a = 1,
    b = 2,
    c = a;

a = b; // must be first or a and b end up being both 1
b = c;

DEMO - Using a third variable


Gradle - Error Could not find method implementation() for arguments [com.android.support:appcompat-v7:26.0.0]

So ridiculous, but I still wanna share my experience in case of that someone falls into the situation like me.

Please check if you changed: compileSdkVersion --> implementationSdkVersion by mistake

How can I set the default timezone in node.js?

I know this thread is very old, but i think this would help anyone that landed here from google like me.

In GAE Flex (NodeJs), you could set the enviroment variable TZ (the one that manages all date timezones in the app) in the app.yaml file, i leave you here an example:

app.yaml

# [START env]
env_variables:
  # Timezone
  TZ: America/Argentina/Buenos_Aires

Is there a JSON equivalent of XQuery/XPath?

Is there some kind of query language ...

jq defines a JSON query language that is very similar to JSONPath -- see https://github.com/stedolan/jq/wiki/For-JSONPath-users

... [which] I can used to find an item in [0].objects where id = 3?

I'll assume this means: find all JSON objects under the specified key with id == 3, no matter where the object may be. A corresponding jq query would be:

.[0].objects | .. | objects | select(.id==3)

where "|" is the pipe-operator (as in command shell pipes), and where the segment ".. | objects" corresponds to "no matter where the object may be".

The basics of jq are largely obvious or intuitive or at least quite simple, and most of the rest is easy to pick up if you're at all familiar with command-shell pipes. The jq FAQ has pointers to tutorials and the like.

jq is also like SQL in that it supports CRUD operations, though the jq processor never overwrites its input. jq can also handle streams of JSON entities.

Two other criteria you might wish to consider in assessing a JSON-oriented query language are:

  • does it support regular expressions? (jq 1.5 has comprehensive support for PCRE regex)
  • is it Turing-complete? (yep)

Permission denied (publickey). fatal: The remote end hung up unexpectedly while pushing back to git repository

Googled "Permission denied (publickey). fatal: The remote end hung up unexpectedly", first result an exact SO dupe:

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly which links here in the accepted answer (from the original poster, no less): http://help.github.com/linux-set-up-git/

SCRIPT7002: XMLHttpRequest: Network Error 0x2ef3, Could not complete the operation due to error 00002ef3

[SOLVED]

I only observed this error today, for me the Error code was different though.

SCRIPT7002: XMLHttpRequest: Network Error 0x2efd, Could not complete the operation due to error 00002efd.

It was occurring randomly and not all the time. but what it noticed is, if it comes for subsequent ajax calls. so i put some delay of 5 seconds between the ajax calls and it resolved.

The I/O operation has been aborted because of either a thread exit or an application request

What I do when it happens is Disable the COM port into the Device Manager and Enable it again.

It stop the communications with another program or thread and become free for you.

I hope this works for you. Regards.

Get Hard disk serial Number

Use "vol" shell command and parse serial from it's output, like this. Works at least in Win7

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CheckHD
{
        class HDSerial
        {
            const string MY_SERIAL = "F845-BB23";
            public static bool CheckSerial()
            {
                string res = ExecuteCommandSync("vol");
                const string search = "Number is";
                int startI = res.IndexOf(search, StringComparison.InvariantCultureIgnoreCase);

                if (startI > 0)
                {
                    string currentDiskID = res.Substring(startI + search.Length).Trim();
                    if (currentDiskID.Equals(MY_SERIAL))
                        return true;
                }
                return false;
            }

            public static string ExecuteCommandSync(object command)
            {
                try
                {
                    // create the ProcessStartInfo using "cmd" as the program to be run,
                    // and "/c " as the parameters.
                    // Incidentally, /c tells cmd that we want it to execute the command that follows,
                    // and then exit.
                    System.Diagnostics.ProcessStartInfo procStartInfo =
                        new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);

                    // The following commands are needed to redirect the standard output.
                    // This means that it will be redirected to the Process.StandardOutput StreamReader.
                    procStartInfo.RedirectStandardOutput = true;
                    procStartInfo.UseShellExecute = false;
                    // Do not create the black window.
                    procStartInfo.CreateNoWindow = true;
                    // Now we create a process, assign its ProcessStartInfo and start it
                    System.Diagnostics.Process proc = new System.Diagnostics.Process();
                    proc.StartInfo = procStartInfo;
                    proc.Start();
                    // Get the output into a string
                    string result = proc.StandardOutput.ReadToEnd();
                    // Display the command output.
                    return result;
                }
                catch (Exception)
                {
                    // Log the exception
                    return null;
                }
            }
        }
    }

Redis: How to access Redis log file

Found it with:

sudo tail /var/log/redis/redis-server.log -n 100

So if the setup was more standard that should be:

sudo tail /var/log/redis_6379.log -n 100

This outputs the last 100 lines of the file.

Where your log file is located is in your configs that you can access with:

redis-cli CONFIG GET *

The log file may not always be shown using the above. In that case use

tail -f `less  /etc/redis/redis.conf | grep logfile|cut -d\  -f2`

Regex - Should hyphens be escaped?

Typically you would always put the hyphen first in the [] match section. EG, to match any alphanumeric character including hyphens (written the long way), you would use [-a-zA-Z0-9]

What is the difference between server side cookie and client side cookie?

All cookies are client and server

There is no difference. A regular cookie can be set server side or client side. The 'classic' cookie will be sent back with each request. A cookie that is set by the server, will be sent to the client in a response. The server only sends the cookie when it is explicitly set or changed, while the client sends the cookie on each request.

But essentially it's the same cookie.

But, behavior can change

A cookie is basically a name=value pair, but after the value can be a bunch of semi-colon separated attributes that affect the behavior of the cookie if it is so implemented by the client (or server). Those attributes can be about lifetime, context and various security settings.

HTTP-only (is not server-only)

One of those attributes can be set by a server to indicate that it's an HTTP-only cookie. This means that the cookie is still sent back and forth, but it won't be available in JavaScript. Do note, though, that the cookie is still there! It's only a built in protection in the browser, but if somebody would use a ridiculously old browser like IE5, or some custom client, they can actually read the cookie!

So it seems like there are 'server cookies', but there are actually not. Those cookies are still sent to the client. On the client there is no way to prevent a cookie from being sent to the server.

Alternatives to achieve 'only-ness'

If you want to store a value only on the server, or only on the client, then you'd need some other kind of storage, like a file or database on the server, or Local Storage on the client.

get keys of json-object in JavaScript

[What you have is just an object, not a "json-object". JSON is a textual notation. What you've quoted is JavaScript code using an array initializer and an object initializer (aka, "object literal syntax").]

If you can rely on having ECMAScript5 features available, you can use the Object.keys function to get an array of the keys (property names) in an object. All modern browsers have Object.keys (including IE9+).

Object.keys(jsonData).forEach(function(key) {
    var value = jsonData[key];
    // ...
});

The rest of this answer was written in 2011. In today's world, A) You don't need to polyfill this unless you need to support IE8 or earlier (!), and B) If you did, you wouldn't do it with a one-off you wrote yourself or grabbed from an SO answer (and probably shouldn't have in 2011, either). You'd use a curated polyfill, possibly from es5-shim or via a transpiler like Babel that can be configured to include polyfills (which may come from es5-shim).

Here's the rest of the answer from 2011:

Note that older browsers won't have it. If not, this is one of the ones you can supply yourself:

if (typeof Object.keys !== "function") {
    (function() {
        var hasOwn = Object.prototype.hasOwnProperty;
        Object.keys = Object_keys;
        function Object_keys(obj) {
            var keys = [], name;
            for (name in obj) {
                if (hasOwn.call(obj, name)) {
                    keys.push(name);
                }
            }
            return keys;
        }
    })();
}

That uses a for..in loop (more info here) to loop through all of the property names the object has, and uses Object.prototype.hasOwnProperty to check that the property is owned directly by the object rather than being inherited.

(I could have done it without the self-executing function, but I prefer my functions to have names, and to be compatible with IE you can't use named function expressions [well, not without great care]. So the self-executing function is there to avoid having the function declaration create a global symbol.)

jQuery Ajax POST example with PHP

HTML:

    <form name="foo" action="form.php" method="POST" id="foo">
        <label for="bar">A bar</label>
        <input id="bar" class="inputs" name="bar" type="text" value="" />
        <input type="submit" value="Send" onclick="submitform(); return false;" />
    </form>

JavaScript:

   function submitform()
   {
       var inputs = document.getElementsByClassName("inputs");
       var formdata = new FormData();
       for(var i=0; i<inputs.length; i++)
       {
           formdata.append(inputs[i].name, inputs[i].value);
       }
       var xmlhttp;
       if(window.XMLHttpRequest)
       {
           xmlhttp = new XMLHttpRequest;
       }
       else
       {
           xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
       }
       xmlhttp.onreadystatechange = function()
       {
          if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
          {

          }
       }
       xmlhttp.open("POST", "insert.php");
       xmlhttp.send(formdata);
   }

How to verify a method is called two times with mockito verify()

build gradle:

testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0"

code:

interface MyCallback {
  fun someMethod(value: String)
}

class MyTestableManager(private val callback: MyCallback){
  fun perform(){
    callback.someMethod("first")
    callback.someMethod("second")
    callback.someMethod("third")
  }
}

test:

import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.mock
...
val callback: MyCallback = mock()
val manager = MyTestableManager(callback)
manager.perform()

val captor: KArgumentCaptor<String> = com.nhaarman.mockitokotlin2.argumentCaptor<String>()

verify(callback, times(3)).someMethod(captor.capture())

assertTrue(captor.allValues[0] == "first")
assertTrue(captor.allValues[1] == "second")
assertTrue(captor.allValues[2] == "third")

How to loop through all the files in a directory in c # .net?

You can have a look at this page showing Deep Folder Copy, it uses recursive means to iterate throught the files and has some really nice tips, like filtering techniques etc.

http://www.codeproject.com/Tips/512208/Folder-Directory-Deep-Copy-including-sub-directori

Best way to encode text data for XML in Java?

Very simply: use an XML library. That way it will actually be right instead of requiring detailed knowledge of bits of the XML spec.

Error in setting JAVA_HOME

You are pointing your JAVA_HOME to the JRE which is the Java Runtime Environment. The runtime environment doesn't have a java compiler in its bin folder. You should download the JDK which is the Java Development Kit. Once you've installed that, you can see in your bin folder that there's a file called javac.exe. That's your compiler.

If strings starts with in PowerShell

$Group is an object, but you will actually need to check if $Group.samaccountname.StartsWith("string").

Change $Group.StartsWith("S_G_") to $Group.samaccountname.StartsWith("S_G_").

Run a .bat file using python code

So I do in Windows 10 and Python 3.7.1 (tested):

import subprocess
Quellpfad = r"C:\Users\MeMySelfAndI\Desktop"
Quelldatei = r"\a.bat"
Quelle = Quellpfad + Quelldatei
print(Quelle)
subprocess.call(Quelle)

Eclipse: Frustration with Java 1.7 (unbound library)

1)Go to configure build path . 2)Remove unbound JRE library . 3)Add library --> JRE System library .

Then project compile and done ..

Format number to 2 decimal places

Just use format(number, qtyDecimals) sample: format(1000, 2) result 1000.00