Programs & Examples On #Graph databases

A graph database uses graph structures with nodes, edges, and properties to represent and store information.

How to stop mysqld

To stop autostart of mysql on boot, the following worked for me with mysql 8.0.12 installed using Homebrew in macOS Mojave 10.14.1:

rm -rf ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist

Executing another application from Java

Here is an example of how to use ProcessBuilder to execute your remote application. Since you do not care about input/output and/or errors, you can do as follows:

List<String> args = new ArrayList<String>();
args.add ("script.bat"); // command name
args.add ("-option"); // optional args added as separate list items
ProcessBuilder pb = new ProcessBuilder (args);
Process p = pb.start();
p.waitFor();

the waitFor() method will wait until the process had ended before continuing. This method returns the error code of the process but, since you don't care about it, I didn't put it in the example.

Center button under form in bootstrap

It's working completely try this:

<div class="button pull-left" style="padding-left:40%;" >

Body set to overflow-y:hidden but page is still scrollable in Chrome

Find out the element which is larger than the body (element which is causing the page to scroll) and just set it's position to fixed. NOTE: I'm not talking to change the position of draggable elements. Draggable elements can be dragged out of body only when there's an element larger than body (mostly in width).

Copy a file in a sane, safe and efficient way

Too many!

The "ANSI C" way buffer is redundant, since a FILE is already buffered. (The size of this internal buffer is what BUFSIZ actually defines.)

The "OWN-BUFFER-C++-WAY" will be slow as it goes through fstream, which does a lot of virtual dispatching, and again maintains internal buffers or each stream object. (The "COPY-ALGORITHM-C++-WAY" does not suffer this, as the streambuf_iterator class bypasses the stream layer.)

I prefer the "COPY-ALGORITHM-C++-WAY", but without constructing an fstream, just create bare std::filebuf instances when no actual formatting is needed.

For raw performance, you can't beat POSIX file descriptors. It's ugly but portable and fast on any platform.

The Linux way appears to be incredibly fast — perhaps the OS let the function return before I/O was finished? In any case, that's not portable enough for many applications.

EDIT: Ah, "native Linux" may be improving performance by interleaving reads and writes with asynchronous I/O. Letting commands pile up can help the disk driver decide when is best to seek. You might try Boost Asio or pthreads for comparison. As for "can't beat POSIX file descriptors"… well that's true if you're doing anything with the data, not just blindly copying.

if else in a list comprehension

One way:

def change(f):
    if f is None:
        return unicode(f.strip())
    else:
        return ''

row = [change(x) for x in row]

Although then you have:

row = map(change, row)

Or you can use a lambda inline.

Is it possible to override / remove background: none!important with jQuery?

With a <script> right after the <style> that applies the !important things, you should be able to do something like this:

var lastStylesheet = document.styleSheets[document.styleSheets.length - 1];
lastStylesheet.disabled = true;

document.write('<style type="text/css">');
// Call fixBackground for each element that needs fixing
document.write('</style>');

lastStylesheet.disabled = false;

function fixBackground(el) {
    document.write('html #' + el.id + ' { background-image: ' +
        document.defaultView.getComputedStyle(el).backgroundImage +
        ' !important; }');
}

This probably depends on what kind of browser compatibility you need, though.

Delete newline in Vim

As other answers mentioned, (upper case) J and search + replace for \n can be used generally to strip newline characters and to concatenate lines.

But in order to get rid of the trailing newline character in the last line, you need to do this in Vim:

:set noendofline binary
:w

Easiest way to toggle 2 classes in jQuery

I've made a jQuery plugin for working DRY:

$.fn.toggle2classes = function(class1, class2){
  if( !class1 || !class2 )
    return this;

  return this.each(function(){
    var $elm = $(this);

    if( $elm.hasClass(class1) || $elm.hasClass(class2) )
      $elm.toggleClass(class1 +' '+ class2);

    else
      $elm.addClass(class1);
  });
};

You can just try it here, copy and run this in the console and then try:

$('body').toggle2classes('a', 'b');

Get cart item name, quantity all details woocommerce

Note on product price

The price of the product in the cart may be different from that of the product.

This can happen when you use some plugins that change the price of the product when it is added to the cart or if you have added a custom function in the functions.php of your active theme.

If you want to be sure you get the price of the product added to the cart you will have to get it like this:

foreach ( WC()->cart->get_cart() as $cart_item ) {
    // gets the cart item quantity
    $quantity           = $cart_item['quantity'];
    // gets the cart item subtotal
    $line_subtotal      = $cart_item['line_subtotal']; 
    $line_subtotal_tax  = $cart_item['line_subtotal_tax'];
    // gets the cart item total
    $line_total         = $cart_item['line_total'];
    $line_tax           = $cart_item['line_tax'];
    // unit price of the product
    $item_price         = $line_subtotal / $quantity;
    $item_tax           = $line_subtotal_tax / $quantity;

}

Instead of:

foreach ( WC()->cart->get_cart() as $cart_item ) {
    // gets the product object
    $product            = $cart_item['data'];
    // gets the product prices
    $regular_price      = $product->get_regular_price();
    $sale_price         = $product->get_sale_price();
    $price              = $product->get_price();
}

Other data you can get:

foreach ( WC()->cart->get_cart() as $cart_item ) {

    // get the data of the cart item
    $product_id         = $cart_item['product_id'];
    $variation_id       = $cart_item['variation_id'];

    // gets the cart item quantity
    $quantity           = $cart_item['quantity'];
    // gets the cart item subtotal
    $line_subtotal      = $cart_item['line_subtotal']; 
    $line_subtotal_tax  = $cart_item['line_subtotal_tax'];
    // gets the cart item total
    $line_total         = $cart_item['line_total'];
    $line_tax           = $cart_item['line_tax'];
    // unit price of the product
    $item_price         = $line_subtotal / $quantity;
    $item_tax           = $line_subtotal_tax / $quantity;

    // gets the product object
    $product            = $cart_item['data'];
    // get the data of the product
    $sku                = $product->get_sku();
    $name               = $product->get_name();
    $regular_price      = $product->get_regular_price();
    $sale_price         = $product->get_sale_price();
    $price              = $product->get_price();
    $stock_qty          = $product->get_stock_quantity();
    // attributes
    $attributes         = $product->get_attributes();
    $attribute          = $product->get_attribute( 'pa_attribute-name' ); // // specific attribute eg. "pa_color"
    // custom meta
    $custom_meta        = $product->get_meta( '_custom_meta_key', true );
    // product categories
    $categories         = wc_get_product_category_list(  $product->get_id() ); // returns a string with all product categories separated by a comma
}

How to use sed to replace only the first occurrence in a file?

You could use awk to do something similar..

awk '/#include/ && !done { print "#include \"newfile.h\""; done=1;}; 1;' file.c

Explanation:

/#include/ && !done

Runs the action statement between {} when the line matches "#include" and we haven't already processed it.

{print "#include \"newfile.h\""; done=1;}

This prints #include "newfile.h", we need to escape the quotes. Then we set the done variable to 1, so we don't add more includes.

1;

This means "print out the line" - an empty action defaults to print $0, which prints out the whole line. A one liner and easier to understand than sed IMO :-)

XAMPP Apache Webserver localhost not working on MAC OS

In my case, Web Sharing was running, which blocked XAMPP.

'Untick' Web Sharing in the Bluetooth Settings (or Network), which causes HTTPD to show in activity log.

Apache should now run and be available!

How do I get the current date in Cocoa

You must use the following:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [gregorian components:(NSHourCalendarUnit  | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:yourDateHere];
NSInteger hour = [dateComponents hour];
NSInteger minute = [dateComponents minute];
NSInteger second = [dateComponents second];
[gregorian release];

There is no difference between NSDate* now and NSDate *now, it's just a matter of preference. From the compiler perspective, nothing changes.

Datetime in C# add days

Why do you use Int64? AddDays demands a double-value to be added. Then you'll need to use the return-value of AddDays. See here.

Why is HttpContext.Current null?

Clearly HttpContext.Current is not null only if you access it in a thread that handles incoming requests. That's why it works "when i use this code in another class of a page".

It won't work in the scheduling related class because relevant code is not executed on a valid thread, but a background thread, which has no HTTP context associated with.

Overall, don't use Application["Setting"] to store global stuffs, as they are not global as you discovered.

If you need to pass certain information down to business logic layer, pass as arguments to the related methods. Don't let your business logic layer access things like HttpContext or Application["Settings"], as that violates the principles of isolation and decoupling.

Update: Due to the introduction of async/await it is more often that such issues happen, so you might consider the following tip,

In general, you should only call HttpContext.Current in only a few scenarios (within an HTTP module for example). In all other cases, you should use

instead of HttpContext.Current.

Setting public class variables

this is the way, but i would suggest to write a getter and setter for that variable.

class Testclass

{
    private $testvar = "default value";

    public function setTestvar($testvar) { 
        $this->testvar = $testvar; 
    }
    public function getTestvar() { 
        return $this->testvar; 
    }

    function dosomething()
    {
        echo $this->getTestvar();
    }
}

$Testclass = new Testclass();

$Testclass->setTestvar("another value");

$Testclass->dosomething();

Should we pass a shared_ptr by reference or by value?

It's known issue that passing shared_ptr by value has a cost and should be avoided if possible.

The cost of passing by shared_ptr

Most of the time passing shared_ptr by reference, and even better by const reference, would do.

The cpp core guideline has a specific rule for passing shared_ptr

R.34: Take a shared_ptr parameter to express that a function is part owner

void share(shared_ptr<widget>);            // share -- "will" retain refcount

An example of when passing shared_ptr by value is really necessary is when the caller passes a shared object to an asynchronous callee - ie the caller goes out of scope before the callee completes its job. The callee must "extend" the lifetime of the shared object by taking a share_ptr by value. In this case, passing a reference to shared_ptr won't do.

The same goes for passing a shared object to a work thread.

How do I tokenize a string in C++?

If you're willing to use C, you can use the strtok function. You should pay attention to multi-threading issues when using it.

ORA-01036: illegal variable name/number when running query through C#

You defined one oracleCommand but used it in 'for'. it means you are adding parameter with the same name to one OracleCommand. you should use cmd.Parameters.clear() to refresh your parameters.

for(int i=0;i<usersList.Count;i++)
        {
            if (!(selectedUsersArray[i].Equals("")) && !passwordArray[i].Equals(""))
            {
                cmd.Parameters.clear();//Add this line
                OracleParameter userName = new OracleParameter();
                userName.ParameterName = "user";
                userName.Value = selectedUsersArray[i];

                OracleParameter passwd = new OracleParameter();
                passwd.ParameterName = "password";
                passwd.Value = passwordArray[i];

                cmd.Parameters.Add(userName);
                cmd.Parameters.Add(passwd);

                cmd.Prepare();
                cmd.ExecuteNonQuery();                   


            }
        } 

Windows task scheduler error 101 launch failure code 2147943785

The user that is configured to run this scheduled task must have "Log on as a batch job" rights on the computer that hosts the exe you are launching. This can be configured on the local security policy of the computer that hosts the exe. You can change the policy (on the server hosting the exe) under

Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment -> Log On As Batch Job

Add your user to this list (you could also make the user account a local admin on the machine hosting the exe).

Finally, you could also simply copy your exe from the network location to your local computer and run it from there instead.

Note also that a domain policy could be restricting "Log on as a batch job" rights at your organization.

Python Array with String Indices

What you want is called an associative array. In python these are called dictionaries.

Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys.

myDict = {}
myDict["john"] = "johns value"
myDict["jeff"] = "jeffs value"

Alternative way to create the above dict:

myDict = {"john": "johns value", "jeff": "jeffs value"}

Accessing values:

print(myDict["jeff"]) # => "jeffs value"

Getting the keys (in Python v2):

print(myDict.keys()) # => ["john", "jeff"]

In Python 3, you'll get a dict_keys, which is a view and a bit more efficient (see views docs and PEP 3106 for details).

print(myDict.keys()) # => dict_keys(['john', 'jeff']) 

If you want to learn about python dictionary internals, I recommend this ~25 min video presentation: https://www.youtube.com/watch?v=C4Kc8xzcA68. It's called the "The Mighty Dictionary".

How to run test methods in specific order in JUnit4?

Its one of the main issue which I faced when I worked on Junit and I came up with following solution which works fine for me:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;

public class OrderedRunner extends BlockJUnit4ClassRunner {

    public OrderedRunner(Class<?> clazz) throws InitializationError {
        super(clazz);
    }

    @Override
    protected List<FrameworkMethod> computeTestMethods() {
        List<FrameworkMethod> list = super.computeTestMethods();
        List<FrameworkMethod> copy = new ArrayList<FrameworkMethod>(list);
        Collections.sort(copy, new Comparator<FrameworkMethod>() {

            @Override
            public int compare(FrameworkMethod f1, FrameworkMethod f2) {
                Order o1 = f1.getAnnotation(Order.class);
                Order o2 = f2.getAnnotation(Order.class);

                if (o1 == null || o2 == null) {
                    return -1;
                }

                return o1.order() - o2.order();
            }
        });
        return copy;
    }
}

also create a interface like below:

 @Retention(RetentionPolicy.RUNTIME)


@Target({ ElementType.METHOD})

public @interface Order {
public int order();
}

Now suppose you have class A where you have written several test cases like below:

(@runWith=OrderRunner.class)
Class A{
@Test
@Order(order = 1)

void method(){

//do something

}

}

So execution will start from method named "method()". Thanks!

How do I pass along variables with XMLHTTPRequest

Following is correct way:

xmlhttp.open("GET","getuser.php?fname="+abc ,true);

How to declare a vector of zeros in R

You can also use the matrix command, to create a matrix with n lines and m columns, filled with zeros.

matrix(0, n, m)

Highcharts - how to have a chart with dynamic height?

When using percentage, the height it relative to the width and will dynamically change along with it:

chart: {
    height: (9 / 16 * 100) + '%' // 16:9 ratio
},

JSFiddle Highcharts with percentage height

If else embedding inside html

<?php if ($foo) { ?>
    <div class="mydiv">Condition is true</div>
<?php } else { ?>
    <div class="myotherdiv">Condition is false</div>
<?php } ?>

Spring Boot application can't resolve the org.springframework.boot package

Maybe there is a problem with the JAR files in the local Maven repository. Try deleting the .m2/repository folder and hit Maven -> Update Project... another time to trigger Maven to download the dependencies again. I tried it and it worked for me.

The program can't start because MSVCR110.dll is missing from your computer

I was getting a similar issue from the Apache Lounge 32 bit version. After downloading the 64 bit version, the issue was resolved.

Here is an excellent video explain the steps involved: https://www.youtube.com/watch?v=17qhikHv5hY

git with IntelliJ IDEA: Could not read from remote repository

this helped me to fix current issue

If you're using macOS Sierra 10.12.2 or later, you will need to modify your ~/.ssh/config file to automatically load keys into the ssh-agent and store passphrases in your keychain.

Host *
 AddKeysToAgent yes
 UseKeychain yes
 IdentityFile ~/.ssh/id_rsa

source

Efficient Algorithm for Bit Reversal (from MSB->LSB to LSB->MSB) in C

I think the simplest method I know follows. MSB is input and LSB is 'reversed' output:

unsigned char rev(char MSB) {
    unsigned char LSB=0;  // for output
    _FOR(i,0,8) {
        LSB= LSB << 1;
        if(MSB&1) LSB = LSB | 1;
        MSB= MSB >> 1;
    }
    return LSB;
}

//    It works by rotating bytes in opposite directions. 
//    Just repeat for each byte.

How to get controls in WPF to fill available space?

Each control deriving from Panel implements distinct layout logic performed in Measure() and Arrange():

  • Measure() determines the size of the panel and each of its children
  • Arrange() determines the rectangle where each control renders

The last child of the DockPanel fills the remaining space. You can disable this behavior by setting the LastChild property to false.

The StackPanel asks each child for its desired size and then stacks them. The stack panel calls Measure() on each child, with an available size of Infinity and then uses the child's desired size.

A Grid occupies all available space, however, it will set each child to their desired size and then center them in the cell.

You can implement your own layout logic by deriving from Panel and then overriding MeasureOverride() and ArrangeOverride().

See this article for a simple example.

how to set auto increment column with sql developer

I found this post, which looks a bit old, but I figured I'd update everyone on my new findings.

I am using Oracle SQL Developer 4.0.2.15 on Windows. Our database is Oracle 10g (version 10.2.0.1) running on Windows.

To make a column auto-increment in Oracle -

  1. Open up the database connection in the Connections tab
  2. Expand the Tables section, and right click the table that has the column you want to change to auto-increment, and select Edit...
  3. Choose the Columns section, and select the column you want to auto-increment (Primary Key column)
  4. Next, click the "Identity Column" section below the list of columns, and change type from None to "Column Sequence"
  5. Leave the default settings (or change the names of the sequence and trigger if you'd prefer) and then click OK

Your id column (primary key) will now auto-increment, but the sequence will be starting at 1. If you need to increment the id to a certain point, you'll have to run a few alter statements against the sequence.
This post has some more details and how to overcome this.

I found the solution here

How to turn on line numbers in IDLE?

If you are trying to track down which line caused an error, if you right-click in the Python shell where the line error is displayed it will come up with a "Go to file/line" which takes you directly to the line in question.

Side-by-side list items as icons within a div (css)

add this line in your css file:

.classname ul li {
    float: left;
}

How to display alt text for an image in chrome

Here is a simple workaround in jQuery. You can implement it as a user script to apply it to every page you view.

$(function () {
  $('img').live('mouseover', function () {
    var img = $(this); // cache query
    if (img.title) {
      return;
    }
    img.attr('title', img.attr('alt'));
  });
});

I have also implemented this as a Chrome extension called alt. Because it uses jQuery.live, it works with dynamically loaded content, too. I have retired this extension and removed it from the Chrome store.

SAP Crystal Reports runtime for .Net 4.0 (64-bit)

SAP is notoriously bad at making these downloads available... or in an easily accessible location so hopefully this link still works by the time you read this answer.

< original link no longer active >

http://scn.sap.com/docs/DOC-7824 Updated Link 2/6/13:

https://wiki.scn.sap.com/wiki/display/BOBJ/Crystal+Reports%2C+Developer+for+Visual+Studio+Downloads - "Updated 10/31/2017"

http://www.crystalreports.com/crvs/confirm/ - "Updated 10/31/2017"

Is there any ASCII character for <br>?

& is a character; &amp; is a HTML character entity for that character.

<br> is an element. Elements don't get character entities.

In contrast to many answers here, \n or &#13; are not equivalent to <br>. The former denotes a line break in text documents. The latter is intended to denote a line break in HTML documents and is doing that by virtue of its default CSS:

br:before { content: "\A"; white-space: pre-line }

A textual line break can be rendered as an HTML line break or can be treated as whitespace, depending on the CSS white-space property.

How can I create an object and add attributes to it?

The mock module is basically made for that.

import mock
obj = mock.Mock()
obj.a = 5

What is content-type and datatype in an AJAX request?

contentType is the type of data you're sending, so application/json; charset=utf-8 is a common one, as is application/x-www-form-urlencoded; charset=UTF-8, which is the default.

dataType is what you're expecting back from the server: json, html, text, etc. jQuery will use this to figure out how to populate the success function's parameter.

If you're posting something like:

{"name":"John Doe"}

and expecting back:

{"success":true}

Then you should have:

var data = {"name":"John Doe"}
$.ajax({
    dataType : "json",
    contentType: "application/json; charset=utf-8",
    data : JSON.stringify(data),
    success : function(result) {
        alert(result.success); // result is an object which is created from the returned JSON
    },
});

If you're expecting the following:

<div>SUCCESS!!!</div>

Then you should do:

var data = {"name":"John Doe"}
$.ajax({
    dataType : "html",
    contentType: "application/json; charset=utf-8",
    data : JSON.stringify(data),
    success : function(result) {
        jQuery("#someContainer").html(result); // result is the HTML text
    },
});

One more - if you want to post:

name=John&age=34

Then don't stringify the data, and do:

var data = {"name":"John", "age": 34}
$.ajax({
    dataType : "html",
    contentType: "application/x-www-form-urlencoded; charset=UTF-8", // this is the default value, so it's optional
    data : data,
    success : function(result) {
        jQuery("#someContainer").html(result); // result is the HTML text
    },
});

how to get login option for phpmyadmin in xampp

Ya, it's working fine, but it can enter into localhost without entering password.

You can do it in another way by following these steps:

  1. In the browser, type: localhost/xampp/

  2. On the left side bar menu, click Security.

  3. Now you can see the subject table, and below the subject table you can see this link:
    http://localhost/security/xamppsecurity.php. Click this link.

  4. Now you can set the password as you want.

  5. Go to the xampp folder where you installed xampp. Open the xampp folder.

  6. Find and open the phpMyAdmin folder.

  7. Find and open the config.inc.php file with Notepad.

  8. Find the code below:

    $cfg['Servers'][$i]['auth_type'] = 'config';
    $cfg['Servers'][$i]['user'] = 'root';
    $cfg['Servers'][$i]['password'] = '';
    $cfg['Servers'][$i]['extension'] = 'mysqli';
    $cfg['Servers'][$i]['AllowNoPassword'] = true;
    
  9. Replace it with the code below:

    $cfg['Servers'][$i]['auth_type'] = 'cookie';
    $cfg['Servers'][$i]['user'] = 'root';
    $cfg['Servers'][$i]['password'] = '';
    $cfg['Servers'][$i]['extension'] = 'mysqli';
    $cfg['Servers'][$i]['AllowNoPassword'] = false;
    
  10. Save the file and run the localhost/phpmyadmin with the browser.

Right Align button in horizontal LinearLayout

You should use the Relativelayout instead of Linearlayout as main layout. If you use Relativelayout as main then easily handle the button on right side because relative layout provide us alignParent right, left,top and bottom.

Difference between parameter and argument

Arguments and parameters are different in that parameters are used to different values in the program and The arguments are passed the same value in the program so they are used in c++. But no difference in c. It is the same for arguments and parameters in c.

Combine two columns of text in pandas dataframe

more efficient is

def concat_df_str1(df):
    """ run time: 1.3416s """
    return pd.Series([''.join(row.astype(str)) for row in df.values], index=df.index)

and here is a time test:

import numpy as np
import pandas as pd

from time import time


def concat_df_str1(df):
    """ run time: 1.3416s """
    return pd.Series([''.join(row.astype(str)) for row in df.values], index=df.index)


def concat_df_str2(df):
    """ run time: 5.2758s """
    return df.astype(str).sum(axis=1)


def concat_df_str3(df):
    """ run time: 5.0076s """
    df = df.astype(str)
    return df[0] + df[1] + df[2] + df[3] + df[4] + \
           df[5] + df[6] + df[7] + df[8] + df[9]


def concat_df_str4(df):
    """ run time: 7.8624s """
    return df.astype(str).apply(lambda x: ''.join(x), axis=1)


def main():
    df = pd.DataFrame(np.zeros(1000000).reshape(100000, 10))
    df = df.astype(int)

    time1 = time()
    df_en = concat_df_str4(df)
    print('run time: %.4fs' % (time() - time1))
    print(df_en.head(10))


if __name__ == '__main__':
    main()

final, when sum(concat_df_str2) is used, the result is not simply concat, it will trans to integer.

ActiveModel::ForbiddenAttributesError when creating new user

If using ActiveAdmin don't forget that there is also a permit_params in the model register block:

ActiveAdmin.register Api::V1::Person do
  permit_params :name, :address, :etc
end

These need to be set along with those in the controller:

def api_v1_person_params
  params.require(:api_v1_person).permit(:name, :address, :etc)
end

Otherwise you will get the error:

ActiveModel::ForbiddenAttributesError

Node.js res.setHeader('content-type', 'text/javascript'); pushing the response javascript as file download

You can directly set the content type like below:

res.writeHead(200, {'Content-Type': 'text/plain'});

For reference go through the nodejs Docs link.

HTTP Error 500.22 - Internal Server Error (An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.)

Set Application pool to classic .NET appool and make sure that Classic .Net apppool working on Classic managed piple line .

Call int() function on every list element?

just a point,

numbers = [int(x) for x in numbers]

the list comprehension is more natural, while

numbers = map(int, numbers)

is faster.

Probably this will not matter in most cases

Useful read: LP vs map

Could not instantiate mail function. Why this error occurring

Just revisiting the old thread you can debug PHPMailer in depth by adding:

print_r(error_get_last());

this will print out the exact error for you which is causing the default php mail() to break.

Hope it helps somebody.

Tuple unpacking in for loops

The enumerate function returns a generator object which, at each iteration, yields a tuple containing the index of the element (i), numbered starting from 0 by default, coupled with the element itself (a), and the for loop conveniently allows you to access both fields of those generated tuples and assign variable names to them.

Input placeholders for Internet Explorer

I found a quite simple solution using this method:

http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html

it's a jquery hack, and it worked perfectly on my projects

How can I create a carriage return in my C# string

<br /> works for me

So...

String body = String.Format(@"New user: 
 <br /> Name: {0}
 <br /> Email: {1}
 <br /> Phone: {2}", Name, Email, Phone);

Produces...

New user:
Name: Name
Email: Email
Phone: Phone

How do you get the footer to stay at the bottom of a Web page?

Multiple people have put the answer to this simple problem up here, but I have one thing to add, considering how frustrated I was until I figured out what I was doing wrong.

As mentioned the most straightforward way to do this is like so..

html {
    position: relative;
    min-height: 100%;
}

body {
    background-color: transparent;
    position: static;
    height: 100%;
    margin-bottom: 30px;
}

.site-footer {
    position: absolute;
    height: 30px;
    bottom: 0px;
    left: 0px;
    right: 0px;
}

However the property not mentioned in posts, presumably because it is usually default, is the position: static on the body tag. Position relative will not work!

My wordpress theme had overridden the default body display and it confused me for an obnoxiously long time.

How to float a div over Google Maps?

#floating-panel {
  position: absolute;
  top: 10px;
  left: 25%;
  z-index: 5;
  background-color: #fff;
  padding: 5px;
  border: 1px solid #999;
  text-align: center;
  font-family: 'Roboto','sans-serif';
  line-height: 30px;
  padding-left: 10px;
}

Just need to move the map below this box. Work to me.

From Google

How to stop a PowerShell script on the first error?

Redirecting stderr to stdout seems to also do the trick without any other commands/scriptblock wrappers although I can't find an explanation why it works that way..

# test.ps1

$ErrorActionPreference = "Stop"

aws s3 ls s3://xxx
echo "==> pass"

aws s3 ls s3://xxx 2>&1
echo "shouldn't be here"

This will output the following as expected (the command aws s3 ... returns $LASTEXITCODE = 255)

PS> .\test.ps1

An error occurred (AccessDenied) when calling the ListObjectsV2 operation: Access Denied
==> pass

How to modify STYLE attribute of element with known ID using JQuery

$("span").mouseover(function () {
$(this).css({"background-color":"green","font-size":"20px","color":"red"});
});

<div>
Sachin Tendulkar has been the most complete batsman of his time, the most prolific     runmaker of all time, and arguably the biggest cricket icon the game has ever known. His batting is based on the purest principles: perfect balance, economy of movement, precision in stroke-making.
</div>

Set the intervals of x-axis using r

You can use axis:

> axis(side=1, at=c(0:23))

That is, something like this:

plot(0:23, d, type='b', axes=FALSE)
axis(side=1, at=c(0:23))
axis(side=2, at=seq(0, 600, by=100))
box()

Return only string message from Spring MVC 3 Controller

For outputing String as text/plain use:

@RequestMapping(value="/foo", method=RequestMethod.GET, produces="text/plain")
@ResponseBody
public String foo() {
    return "bar";
}

Default optional parameter in Swift function

in case you need to use a bool param, you need just to assign the default value.

func test(WithFlag flag: Bool = false){.....}

then you can use without or with the param:

test() //here flag automatically has the default value: false
test(WithFlag: true) //here flag has the value: true

Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug)

Xcode 8 and Swift 3.0

Using URLSession:

 let url = URL(string:"Download URL")!
 let req = NSMutableURLRequest(url:url)
 let config = URLSessionConfiguration.default
 let session = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue.main)

 let task : URLSessionDownloadTask = session.downloadTask(with: req as URLRequest)
task.resume()

URLSession Delegate call:

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {

}


func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, 
didWriteData bytesWritten: Int64, totalBytesWritten writ: Int64, totalBytesExpectedToWrite exp: Int64) {
                   print("downloaded \(100*writ/exp)" as AnyObject)

}

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL){

}

Using Block GET/POST/PUT/DELETE:

 let request = NSMutableURLRequest(url: URL(string: "Your API URL here" ,param: param))!,
        cachePolicy: .useProtocolCachePolicy,
        timeoutInterval:"Your request timeout time in Seconds")
    request.httpMethod = "GET"
    request.allHTTPHeaderFields = headers as? [String : String] 

    let session = URLSession.shared

    let dataTask = session.dataTask(with: request as URLRequest) {data,response,error in
        let httpResponse = response as? HTTPURLResponse

        if (error != nil) {
         print(error)
         } else {
         print(httpResponse)
         }

        DispatchQueue.main.async {
           //Update your UI here
        }

    }
    dataTask.resume()

Working fine for me.. try it 100% result guarantee

Free XML Formatting tool

Notepad++ dit it well only if you're in ANSI. If you do it in something like "ANSI AS UTF8", tidy dirty the doc :/.

How do I REALLY reset the Visual Studio window layout?

If you have an old backup copy of CurrentSettings.vssettings, you can try restoring it.

I had a completely corrupted Visual Studio layout. When I tried to enter debug, I was told that VS had become unstable. When I restarted, my window layout would then be totally screwed. I tried restoring the VS current user settings in the registry from a backup, but that didn't help. However, restoring CurrentSettings.vssettings seems to have cured it.

There seems to be a bunch of binary stuff in there and I can imagine it gets irretrievably corrupted sometimes.

Pad a string with leading zeros so it's 3 characters long in SQL Server 2008

Here's a more general technique for left-padding to any desired width:

declare @x     int     = 123 -- value to be padded
declare @width int     = 25  -- desired width
declare @pad   char(1) = '0' -- pad character

select right_justified = replicate(
                           @pad ,
                           @width-len(convert(varchar(100),@x))
                           )
                       + convert(varchar(100),@x)

However, if you're dealing with negative values, and padding with leading zeroes, neither this, nor other suggested technique will work. You'll get something that looks like this:

00-123

[Probably not what you wanted]

So … you'll have to jump through some additional hoops Here's one approach that will properly format negative numbers:

declare @x     float   = -1.234
declare @width int     = 20
declare @pad   char(1) = '0'

select right_justified = stuff(
         convert(varchar(99),@x) ,                            -- source string (converted from numeric value)
         case when @x < 0 then 2 else 1 end ,                 -- insert position
         0 ,                                                  -- count of characters to remove from source string
         replicate(@pad,@width-len(convert(varchar(99),@x)) ) -- text to be inserted
         )

One should note that the convert() calls should specify an [n]varchar of sufficient length to hold the converted result with truncation.

NuGet Package Restore Not Working

If anything else didn't work, try:

  1. Close Project.
  2. Delete packages folder in your solution folder.
  3. Open Project again and restore Nugget Packages again.

Worked for me and it's easy to try.

Any reason to prefer getClass() over instanceof when generating .equals()?

This is something of a religious debate. Both approaches have their problems.

  • Use instanceof and you can never add significant members to subclasses.
  • Use getClass and you violate the Liskov substitution principle.

Bloch has another relevant piece of advice in Effective Java Second Edition:

  • Item 17: Design and document for inheritance or prohibit it

Rails select helper - Default selected value, how?

I couldn't get this to work and found that I needed to add the "selected" html attribute not only to the correct <option> tag but also to the <select> tag. MDN's docs on the selected attribute of the select tag say:

selected - Boolean attribute indicates that a specific option can be initially selected.

That means the code should look like:

f.select :project_id, options_for_select(@project_select, default_val), html: {selected: true}

PHP: Update multiple MySQL fields in single query

Add your multiple columns with comma separations:

UPDATE settings SET postsPerPage = $postsPerPage, style= $style WHERE id = '1'

However, you're not sanitizing your inputs?? This would mean any random hacker could destroy your database. See this question: What's the best method for sanitizing user input with PHP?

Also, is style a number or a string? I'm assuming a string, so it would need to be quoted.

How to use if - else structure in a batch file?

I believe you can use something such as

if ___ (

do this

) else if ___ (

do this

)

How can I wait In Node.js (JavaScript)? l need to pause for a period of time

On Node 7.6.0 or higher

Node supports waiting natively:

const sleep = (waitTimeInMs) => new Promise(resolve => setTimeout(resolve, waitTimeInMs));

then if you can use async functions:

await sleep(10000); // sleep for 10 seconds

or:

sleep(10000).then(() => {
  // This will execute 10 seconds from now
});

On older Node versions (original answer)

I wanted an asynchronous sleep that worked in Windows & Linux, without hogging my CPU with a long while loop. I tried the sleep package but it wouldn't install on my Windows box. I ended up using:

https://www.npmjs.com/package/system-sleep

To install it, type:

npm install system-sleep

In your code,

var sleep = require('system-sleep');
sleep(10*1000); // sleep for 10 seconds

Works like a charm.

Div side by side without float

I am currently working on this, and i have already a number of solutions. It is nice to have a high quality site, that i can use also for my convenience. Because if you do not write these things down, you will eventually forget some parts. And i can also recommend writing some basic's down if you are starting any kind of new programming/design.

So if the float functions are causing problems there is a couple of options you can try.

One is modify the div alignment in the div tag it self like so <div class="kosher" align=left> If this does not suit you then there is another option with margin like so.

.leftdiv {
    display: inline-block;
    width: 40%;
    float: left;
}
.rightdiv {
    display: block;
    margin-right: 20px;
    margin-left: 45%;
}

Don't forget to remove the <div align=left>.

whitespaces in the path of windows filepath

Try putting double quotes in your filepath variable

"\"E:/ABC/SEM 2/testfiles/all.txt\""

Check the permissions of the file or in any case consider renaming the folder to remove the space

How to draw interactive Polyline on route google maps v2 android

Instead of creating too many short Polylines just create one like here:

PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
for (int z = 0; z < list.size(); z++) {
    LatLng point = list.get(z);
    options.add(point);
}
line = myMap.addPolyline(options);

I'm also not sure you should use geodesic when your points are so close to each other.

ADB Shell Input Events

To send a reload call to a React-Native app running in a android device: adb shell input keyboard text "rr"

How to fix "could not find a base address that matches schema http"... in WCF

The solution is to define a custom binding inside your Web.Config file and set the security mode to "Transport". Then you just need to use the bindingConfiguration property inside your endpoint definition to point to your custom binding.

See here: Scott's Blog: WCF Bindings Needed For HTTPS

How to hide element label by element id in CSS?

Despite other answers here, you should not use display:none to hide the label element.

The accessible way to hide a label visually is to use an 'off-left' or 'clip' rule in your CSS. Using display:none will prevent people who use screen-readers from having access to the content of the label element. Using display:none hides content from all users, and that includes screen-reader users (who benefit most from label elements).

label[for="foo"] { 
    border: 0;
    clip: rect(0 0 0 0);
    height: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: 1px;
}

The W3C and WAI offer more guidance on this topic, including CSS for the 'clip' technique.

Toggle display:none style with JavaScript

you can do this easily by using jquery using .css property... try this one: http://api.jquery.com/css/

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

What the error is telling, is that you can't convert an entire list into an integer. You could get an index from the list and convert that into an integer:

x = ["0", "1", "2"] 
y = int(x[0]) #accessing the zeroth element

If you're trying to convert a whole list into an integer, you are going to have to convert the list into a string first:

x = ["0", "1", "2"]
y = ''.join(x) # converting list into string
z = int(y)

If your list elements are not strings, you'll have to convert them to strings before using str.join:

x = [0, 1, 2]
y = ''.join(map(str, x))
z = int(y)

Also, as stated above, make sure that you're not returning a nested list.

With CSS, how do I make an image span the full width of the page as a background image?

You set the CSS to :

#elementID {
    background: black url(http://www.electrictoolbox.com/images/rangitoto-3072x200.jpg) center no-repeat;
    height: 200px;
}

It centers the image, but does not scale it.

FIDDLE

In newer browsers you can use the background-size property and do:

#elementID {
    height: 200px; 
    width: 100%;
    background: black url(http://www.electrictoolbox.com/images/rangitoto-3072x200.jpg) no-repeat;
    background-size: 100% 100%;
}

FIDDLE

Other than that, a regular image is one way to do it, but then it's not really a background image.

?

How to compare only Date without Time in DateTime types in Linq to SQL with Entity Framework?

DateTime dt1 = DateTime.Now.Date;
DateTime dt2 = Convert.ToDateTime(TextBox4.Text.Trim()).Date;
if (dt1 >= dt2)
{
    MessageBox.Show("Valid Date");
}
else
{
    MessageBox.Show("Invalid Date... Please Give Correct Date....");
}

jQuery checkbox event handling

Acknowledging the fact that the asker specifically requested jQuery and that the answer selected is correct, it should be noted that this problem doesn't actually need jQuery per say. If one desires to solve this problem without it, one can simply set the onClick attribute of the checkboxes that he or she wants to add additional functionality to, like so:

HTML:

<form id="myform">
  <input type="checkbox" name="check1" value="check1" onClick="cbChanged(this);">
  <input type="checkbox" name="check2" value="check2" onClick="cbChanged(this);">
</form>

javascript:

function cbChanged(checkboxElem) {
  if (checkboxElem.checked) {
    // Do something special
  } else {
    // Do something else
  }
}

Fiddle: http://jsfiddle.net/Y9f66/1/

How to open warning/information/error dialog in Swing?

import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class ErrorDialog {

  public static void main(String argv[]) {
    String message = "\"The Comedy of Errors\"\n"
        + "is considered by many scholars to be\n"
        + "the first play Shakespeare wrote";
    JOptionPane.showMessageDialog(new JFrame(), message, "Dialog",
        JOptionPane.ERROR_MESSAGE);
  }
}

JS Client-Side Exif Orientation: Rotate and Mirror JPEG Images

WunderBart's answer was the best for me. Note that you can speed it up a lot if your images are often the right way around, simply by testing the orientation first and bypassing the rest of the code if no rotation is required.

Putting all of the info from wunderbart together, something like this;

var handleTakePhoto = function () {
    let fileInput: HTMLInputElement = <HTMLInputElement>document.getElementById('photoInput');
    fileInput.addEventListener('change', (e: any) => handleInputUpdated(fileInput, e.target.files));
    fileInput.click();
}

var handleInputUpdated = function (fileInput: HTMLInputElement, fileList) {
    let file = null;

    if (fileList.length > 0 && fileList[0].type.match(/^image\//)) {
        isLoading(true);
        file = fileList[0];
        getOrientation(file, function (orientation) {
            if (orientation == 1) {
                imageBinary(URL.createObjectURL(file));
                isLoading(false);
            }
            else 
            {
                resetOrientation(URL.createObjectURL(file), orientation, function (resetBase64Image) {
                    imageBinary(resetBase64Image);
                    isLoading(false);
                });
            }
        });
    }

    fileInput.removeEventListener('change');
}


// from http://stackoverflow.com/a/32490603
export function getOrientation(file, callback) {
    var reader = new FileReader();

    reader.onload = function (event: any) {
        var view = new DataView(event.target.result);

        if (view.getUint16(0, false) != 0xFFD8) return callback(-2);

        var length = view.byteLength,
            offset = 2;

        while (offset < length) {
            var marker = view.getUint16(offset, false);
            offset += 2;

            if (marker == 0xFFE1) {
                if (view.getUint32(offset += 2, false) != 0x45786966) {
                    return callback(-1);
                }
                var little = view.getUint16(offset += 6, false) == 0x4949;
                offset += view.getUint32(offset + 4, little);
                var tags = view.getUint16(offset, little);
                offset += 2;

                for (var i = 0; i < tags; i++)
                    if (view.getUint16(offset + (i * 12), little) == 0x0112)
                        return callback(view.getUint16(offset + (i * 12) + 8, little));
            }
            else if ((marker & 0xFF00) != 0xFF00) break;
            else offset += view.getUint16(offset, false);
        }
        return callback(-1);
    };

    reader.readAsArrayBuffer(file.slice(0, 64 * 1024));
};

export function resetOrientation(srcBase64, srcOrientation, callback) {
    var img = new Image();

    img.onload = function () {
        var width = img.width,
            height = img.height,
            canvas = document.createElement('canvas'),
            ctx = canvas.getContext("2d");

        // set proper canvas dimensions before transform & export
        if (4 < srcOrientation && srcOrientation < 9) {
            canvas.width = height;
            canvas.height = width;
        } else {
            canvas.width = width;
            canvas.height = height;
        }

        // transform context before drawing image
        switch (srcOrientation) {
            case 2: ctx.transform(-1, 0, 0, 1, width, 0); break;
            case 3: ctx.transform(-1, 0, 0, -1, width, height); break;
            case 4: ctx.transform(1, 0, 0, -1, 0, height); break;
            case 5: ctx.transform(0, 1, 1, 0, 0, 0); break;
            case 6: ctx.transform(0, 1, -1, 0, height, 0); break;
            case 7: ctx.transform(0, -1, -1, 0, height, width); break;
            case 8: ctx.transform(0, -1, 1, 0, 0, width); break;
            default: break;
        }

        // draw image
        ctx.drawImage(img, 0, 0);

        // export base64
        callback(canvas.toDataURL());
    };

    img.src = srcBase64;
}

aspx page to redirect to a new page

<%@ Page Language="C#" %>
<script runat="server">
  protected override void OnLoad(EventArgs e)
  {
      Response.Redirect("new.aspx");
  }
</script>

Error With Port 8080 already in use

if you are running from inside eclipse with wtp, you should be able to change the port from the "servers" view (window -> show view -> servers)

In Android, how do I set margins in dp programmatically?

You can use this method and put static dimen like 20 it converts according your device

 public static int dpToPx(int dp) 
      {
          float scale = context.getResources().getDisplayMetrics().density;
       return (int) (dp * scale + 0.5f);
  }

What is /dev/null 2>&1?

/dev/null is a standard file that discards all you write to it, but reports that the write operation succeeded.

1 is standard output and 2 is standard error.

2>&1 redirects standard error to standard output. &1 indicates file descriptor (standard output), otherwise (if you use just 1) you will redirect standard error to a file named 1. [any command] >>/dev/null 2>&1 redirects all standard error to standard output, and writes all of that to /dev/null.

Polymorphism: Why use "List list = new ArrayList" instead of "ArrayList list = new ArrayList"?

This enables you to write something like:

void doSomething() {
    List<String>list = new ArrayList<String>();
    //do something
}

Later on, you might want to change it to:

void doSomething() {
    List<String>list = new LinkedList<String>();
    //do something
}

without having to change the rest of the method.

However, if you want to use a CopyOnWriteArrayList for example, you would need to declare it as such, and not as a List if you wanted to use its extra methods (addIfAbsent for example):

void doSomething() {
    CopyOnWriteArrayList<String>list = new CopyOnWriteArrayList<String>();
    //do something, for example:
    list.addIfAbsent("abc");
}

PHP: Split string

to explode with '.' use

explode('\\.','a.b');

Calculate time difference in minutes in SQL Server

Please try as below to get the time difference in hh:mm:ss format

Select StartTime, EndTime, CAST((EndTime - StartTime) as time(0)) 'TotalTime' from [TableName]

jQuery .ajax() POST Request throws 405 (Method Not Allowed) on RESTful WCF

Your code is actually attempting to make a Cross-domain (CORS) request, not an ordinary POST.

That is: Modern browsers will only allow Ajax calls to services in the same domain as the HTML page.

Example: A page in http://www.example.com/myPage.html can only directly request services that are in http://www.example.com, like http://www.example.com/testservice/etc. If the service is in other domain, the browser won't make the direct call (as you'd expect). Instead, it will try to make a CORS request.

To put it shortly, to perform a CORS request, your browser:

  • Will first send an OPTION request to the target URL
  • And then only if the server response to that OPTION contains the adequate headers (Access-Control-Allow-Origin is one of them) to allow the CORS request, the browse will perform the call (almost exactly the way it would if the HTML page was at the same domain).
    • If the expected headers don't come, the browser simply gives up (like it did to you).

How to solve it? The simplest way is to enable CORS (enable the necessary headers) on the server.

If you don't have server-side access to it, you can mirror the web service from somewhere else, and then enable CORS there.

How can I change the default Mysql connection timeout when connecting through python?

You change default value in MySQL configuration file (option connect_timeout in mysqld section) -

[mysqld]
connect_timeout=100

If this file is not accessible for you, then you can set this value using this statement -

SET GLOBAL connect_timeout=100;

linking problem: fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

Since the problem is due to the difference in compilation and target machine specifications (x86 & x64) Follow the steps below:

  1. Open the C++ project that you want to configure.
  2. Choose the Configuration Manager button to open the Configuration Manager dialog box.
  3. In the Active Solution Platform drop-down list, select the option to open the New Solution Platform dialog box.
  4. In the Type or select the new platform drop-down list, select a 64-bit platform.

This solved my problem.

iOS - UIImageView - how to handle UIImage image orientation

here is a workable sample cod, considering the image orientation:

#define rad(angle) ((angle) / 180.0 * M_PI)
- (CGAffineTransform)orientationTransformedRectOfImage:(UIImage *)img
{
    CGAffineTransform rectTransform;
    switch (img.imageOrientation)
    {
        case UIImageOrientationLeft:
            rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(90)), 0, -img.size.height);
            break;
        case UIImageOrientationRight:
            rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-90)), -img.size.width, 0);
            break;
        case UIImageOrientationDown:
            rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-180)), -img.size.width, -img.size.height);
            break;
        default:
            rectTransform = CGAffineTransformIdentity;
    };

    return CGAffineTransformScale(rectTransform, img.scale, img.scale);
}


- (UIImage *)croppedImage:(UIImage*)orignialImage InRect:(CGRect)visibleRect{
    //transform visible rect to image orientation
    CGAffineTransform rectTransform = [self orientationTransformedRectOfImage:orignialImage];
    visibleRect = CGRectApplyAffineTransform(visibleRect, rectTransform);

    //crop image
    CGImageRef imageRef = CGImageCreateWithImageInRect([orignialImage CGImage], visibleRect);
    UIImage *result = [UIImage imageWithCGImage:imageRef scale:orignialImage.scale orientation:orignialImage.imageOrientation];
    CGImageRelease(imageRef);
    return result;
}

How to Detect if I'm Compiling Code with a particular Visual Studio version?

_MSC_VER should be defined to a specific version number. You can either #ifdef on it, or you can use the actual define and do a runtime test. (If for some reason you wanted to run different code based on what compiler it was compiled with? Yeah, probably you were looking for the #ifdef. :))

How to merge two json string in Python?

As of Python 3.5, you can merge two dicts with:

merged = {**dictA, **dictB}

(https://www.python.org/dev/peps/pep-0448/)

So:

jsonMerged = {**json.loads(jsonStringA), **json.loads(jsonStringB)}
asString = json.dumps(jsonMerged)

etc.

java.util.Date to XMLGregorianCalendar

A one line example using Joda-Time library:

XMLGregorianCalendar xgc = DatatypeFactory.newInstance().newXMLGregorianCalendar(new DateTime().toGregorianCalendar());

Credit to Nicolas Mommaerts from his comment in the accepted answer.

Mockito, JUnit and Spring

Honestly I am not sure if I really understand your question :P I will try to clarify as much as I can, from what I get from your original question:

First, in most case, you should NOT have any concern on Spring. You rarely need to have spring involved in writing your unit test. In normal case, you only need to instantiate the system under test (SUT, the target to be tested) in your unit test, and inject dependencies of SUT in the test too. The dependencies are usually a mock/stub.

Your original suggested way, and example 2, 3 is precisely doing what I am describing above.

In some rare case (like, integration tests, or some special unit tests), you need to create a Spring app context, and get your SUT from the app context. In such case, I believe you can:

1) Create your SUT in spring app ctx, get reference to it, and inject mocks to it

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("test-app-ctx.xml")
public class FooTest {

    @Autowired
    @InjectMocks
    TestTarget sut;

    @Mock
    Foo mockFoo;

    @Before
    /* Initialized mocks */
    public void setup() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void someTest() {
         // ....
    }
}

or

2) follow the way described in your link Spring Integration Tests, Creating Mock Objects. This approach is to create mocks in Spring's app context, and you can get the mock object from the app ctx to do your stubbing/verification:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("test-app-ctx.xml")
public class FooTest {

    @Autowired
    TestTarget sut;

    @Autowired
    Foo mockFoo;

    @Test
    public void someTest() {
         // ....
    }
}

Both ways should work. The main difference is the former case will have the dependencies injected after going through spring's lifecycle etc. (e.g. bean initialization), while the latter case is injected beforehands. For example, if your SUT implements spring's InitializingBean, and the initialization routine involves the dependencies, you will see the difference between these two approach. I believe there is no right or wrong for these 2 approaches, as long as you know what you are doing.

Just a supplement, @Mock, @Inject, MocktoJunitRunner etc are all unnecessary in using Mockito. They are just utilities to save you typing the Mockito.mock(Foo.class) and bunch of setter invocations.

How to detect if JavaScript is disabled?

just a bit tough but (hairbo gave me the idea)

CSS:

.pagecontainer {
  display: none;
}

JS:

function load() {
  document.getElementById('noscriptmsg').style.display = "none";
  document.getElementById('load').style.display = "block";
  /* rest of js*/
}

HTML:

<body onload="load();">

  <div class="pagecontainer" id="load">
    Page loading....
  </div>
  <div id="noscriptmsg">
    You don't have javascript enabled. Good luck with that.
  </div>

</body>

would work in any case right? even if the noscript tag is unsupported (only some css required) any one knows a non css solution?

Resize Google Maps marker icon image

So I just had this same issue, but a little different. I already had the icon as an object as Philippe Boissonneault suggests, but I was using an SVG image.

What solved it for me was:
Switch from an SVG image to a PNG and following Catherine Nyo on having an image that is double the size of what you will use.

DataGrid get selected rows' column values

I believe the reason there's no straightforward property to access the selected row of a WPF DataGrid is because a DataGrid's selection mode can be set to either the row-level or the cell-level. Therefore, the selection-related properties and events are all written against cell-level selection - you'll always have selected cells regardless of the grid's selection mode, but you aren't guaranteed to have a selected row.

I don't know precisely what you're trying to achieve by handling the CellEditEnding event, but to get the values of all selected cells when you select a row, take a look at handling the SelectedCellsChanged event, instead. Especially note the remarks in that article:

You can handle the SelectedCellsChanged event to be notified when the collection of selected cells is changed. If the selection includes full rows, the Selector.SelectionChanged event is also raised.

You can retrieve the AddedCells and RemovedCells from the SelectedCellsChangedEventArgs in the event handler.

Hope that helps put you on the right track. :)

Convert timestamp to readable date/time PHP

If you are using PHP date(), you can use this code to get the date, time, second, etc.

$time = time();               // you have 1299446702 in time
$year = $time/31556926 % 12;  // to get year
$week = $time / 604800 % 52;  // to get weeks
$hour = $time / 3600 % 24;    // to get hours
$minute = $time / 60 % 60;    // to get minutes
$second = $time % 60;         // to get seconds

How to add a named sheet at the end of all Excel sheets?

This will give you the option to:

  1. Overwrite or Preserve a tab that has the same name.
  2. Place the sheet at End of all tabs or Next to the current tab.
  3. Select your New sheet or the Active one.

Call CreateWorksheet("New", False, False, False)


Sub CreateWorksheet(sheetName, preserveOldSheet, isLastSheet, selectActiveSheet)
  activeSheetNumber = Sheets(ActiveSheet.Name).Index

  If (Evaluate("ISREF('" & sheetName & "'!A1)")) Then 'Does sheet exist?
    If (preserveOldSheet) Then
      MsgBox ("Can not create sheet " + sheetName + ". This sheet exist.")
      Exit Sub
    End If
      Application.DisplayAlerts = False
      Worksheets(sheetName).Delete
    End If

    If (isLastSheet) Then
      Sheets.Add(After:=Sheets(Sheets.Count)).Name = sheetName 'Place sheet at the end.
    Else 'Place sheet after the active sheet.
      Sheets.Add(After:=Sheets(activeSheetNumber)).Name = sheetName
    End If

    If (selectActiveSheet) Then
      Sheets(activeSheetNumber).Activate
    End If

End Sub

Catch error if iframe src fails to load . Error :-"Refused to display 'http://www.google.co.in/' in a frame.."

I think that you can bind the load event of the iframe, the event fires when the iframe content is fully loaded.

At the same time you can start a setTimeout, if the iFrame is loaded clear the timeout alternatively let the timeout fire.

Code:

var iframeError;

function change() {
    var url = $("#addr").val();
    $("#browse").attr("src", url);
    iframeError = setTimeout(error, 5000);
}

function load(e) {
    alert(e);
}

function error() {
    alert('error');
}

$(document).ready(function () {
    $('#browse').on('load', (function () {
        load('ok');
        clearTimeout(iframeError);
    }));

});

Demo: http://jsfiddle.net/IrvinDominin/QXc6P/

Second problem

It is because you miss the parens in the inline function call; try change this:

<iframe id="browse" style="width:100%;height:100%" onload="load" onerror="error"></iframe>

into this:

<iframe id="browse" style="width:100%;height:100%" onload="load('Done func');" onerror="error('failed function');"></iframe>

Demo: http://jsfiddle.net/IrvinDominin/ALBXR/4/

How do I set the proxy to be used by the JVM

As is pointed out in other answers, if you need to use Authenticated proxies, there's no reliable way to do this purely using command-line variables - which is annoying if you're using someone else's application and don't want to mess with the source code.

Will Iverson makes the helpful suggestion over at Using HttpProxy to connect to a host with preemtive authentication to use a Proxy-management tool such as Proxifier ( http://www.proxifier.com/ for Mac OS X and Windows) to handle this.

For example with Proxifier you can set it up to only intercept java commands to be managed and redirected through its (authenticated) proxy. You're going to want to set the proxyHost and proxyPort values to blank in this case though, e.g. pass in -Dhttp.proxyHost= -Dhttp.proxyPort= to your java commands.

Remove a parameter to the URL with JavaScript

function removeParam(parameter)
{
  var url=document.location.href;
  var urlparts= url.split('?');

 if (urlparts.length>=2)
 {
  var urlBase=urlparts.shift(); 
  var queryString=urlparts.join("?"); 

  var prefix = encodeURIComponent(parameter)+'=';
  var pars = queryString.split(/[&;]/g);
  for (var i= pars.length; i-->0;)               
      if (pars[i].lastIndexOf(prefix, 0)!==-1)   
          pars.splice(i, 1);
  url = urlBase+'?'+pars.join('&');
  window.history.pushState('',document.title,url); // added this line to push the new url directly to url bar .

}
return url;
}

This will resolve your problem

How to run specific test cases in GoogleTest

Summarising @Rasmi Ranjan Nayak and @nogard answers and adding another option:

On the console

You should use the flag --gtest_filter, like

--gtest_filter=Test_Cases1*

(You can also do this in Properties|Configuration Properties|Debugging|Command Arguments)

On the environment

You should set the variable GTEST_FILTER like

export GTEST_FILTER = "Test_Cases1*"

On the code

You should set a flag filter, like

::testing::GTEST_FLAG(filter) = "Test_Cases1*";

such that your main function becomes something like

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    ::testing::GTEST_FLAG(filter) = "Test_Cases1*";
    return RUN_ALL_TESTS();
}

See section Running a Subset of the Tests for more info on the syntax of the string you can use.

docker: executable file not found in $PATH

For some reason, I get that error unless I add the "bash" clarifier. Even adding "#!/bin/bash" to the top of my entrypoint file didn't help.

ENTRYPOINT [ "bash", "entrypoint.sh" ]

What do the terms "CPU bound" and "I/O bound" mean?

CPU Bound means the rate at which process progresses is limited by the speed of the CPU. A task that performs calculations on a small set of numbers, for example multiplying small matrices, is likely to be CPU bound.

I/O Bound means the rate at which a process progresses is limited by the speed of the I/O subsystem. A task that processes data from disk, for example, counting the number of lines in a file is likely to be I/O bound.

Memory bound means the rate at which a process progresses is limited by the amount memory available and the speed of that memory access. A task that processes large amounts of in memory data, for example multiplying large matrices, is likely to be Memory Bound.

Cache bound means the rate at which a process progress is limited by the amount and speed of the cache available. A task that simply processes more data than fits in the cache will be cache bound.

I/O Bound would be slower than Memory Bound would be slower than Cache Bound would be slower than CPU Bound.

The solution to being I/O bound isn't necessarily to get more Memory. In some situations, the access algorithm could be designed around the I/O, Memory or Cache limitations. See Cache Oblivious Algorithms.

Convert DateTime to String PHP

Shorter way using list. And you can do what you want with each date component.

list($day,$month,$year,$hour,$min,$sec) = explode("/",date('d/m/Y/h/i/s'));
echo $month.'/'.$day.'/'.$year.' '.$hour.':'.$min.':'.$sec;

Oracle SQL, concatenate multiple columns + add text

The Oracle/PLSQL CONCAT function allows to concatenate two strings together.

CONCAT( string1, string2 )

string1

The first string to concatenate.

string2

The second string to concatenate.

E.g.

SELECT 'I like ' || type_column_name || ' cake with ' || 
icing_column_name || ' and a ' fruit_column_name || '.' 
AS Cake FROM table;

Python matplotlib multiple bars

import matplotlib.pyplot as plt
from matplotlib.dates import date2num
import datetime

x = [
    datetime.datetime(2011, 1, 4, 0, 0),
    datetime.datetime(2011, 1, 5, 0, 0),
    datetime.datetime(2011, 1, 6, 0, 0)
]
x = date2num(x)

y = [4, 9, 2]
z = [1, 2, 3]
k = [11, 12, 13]

ax = plt.subplot(111)
ax.bar(x-0.2, y, width=0.2, color='b', align='center')
ax.bar(x, z, width=0.2, color='g', align='center')
ax.bar(x+0.2, k, width=0.2, color='r', align='center')
ax.xaxis_date()

plt.show()

enter image description here

I don't know what's the "y values are also overlapping" means, does the following code solve your problem?

ax = plt.subplot(111)
w = 0.3
ax.bar(x-w, y, width=w, color='b', align='center')
ax.bar(x, z, width=w, color='g', align='center')
ax.bar(x+w, k, width=w, color='r', align='center')
ax.xaxis_date()
ax.autoscale(tight=True)

plt.show()

enter image description here

Scheduling recurring task in Android

I realize this is an old question and has been answered but this could help someone. In your activity

private ScheduledExecutorService scheduleTaskExecutor;

In onCreate

  scheduleTaskExecutor = Executors.newScheduledThreadPool(5);

    //Schedule a task to run every 5 seconds (or however long you want)
    scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            // Do stuff here!

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // Do stuff to update UI here!
                    Toast.makeText(MainActivity.this, "Its been 5 seconds", Toast.LENGTH_SHORT).show();
                }
            });

        }
    }, 0, 5, TimeUnit.SECONDS); // or .MINUTES, .HOURS etc.

Converting string into datetime

Something that isn't mentioned here and is useful: adding a suffix to the day. I decoupled the suffix logic so you can use it for any number you like, not just dates.

import time

def num_suffix(n):
    '''
    Returns the suffix for any given int
    '''
    suf = ('th','st', 'nd', 'rd')
    n = abs(n) # wise guy
    tens = int(str(n)[-2:])
    units = n % 10
    if tens > 10 and tens < 20:
        return suf[0] # teens with 'th'
    elif units <= 3:
        return suf[units]
    else:
        return suf[0] # 'th'

def day_suffix(t):
    '''
    Returns the suffix of the given struct_time day
    '''
    return num_suffix(t.tm_mday)

# Examples
print num_suffix(123)
print num_suffix(3431)
print num_suffix(1234)
print ''
print day_suffix(time.strptime("1 Dec 00", "%d %b %y"))
print day_suffix(time.strptime("2 Nov 01", "%d %b %y"))
print day_suffix(time.strptime("3 Oct 02", "%d %b %y"))
print day_suffix(time.strptime("4 Sep 03", "%d %b %y"))
print day_suffix(time.strptime("13 Nov 90", "%d %b %y"))
print day_suffix(time.strptime("14 Oct 10", "%d %b %y"))???????

Why is textarea filled with mysterious white spaces?

keep textarea code with no additional white spaces inside

moreover if you see extra blank lines there is solution in meta language:

<textarea>
for line in lines:
echo line.replace('\n','\r')
endfor
</textarea>

it will print lines without additional blank lines of course it depends if your lines ending with '\n', '\r\n' or '' - please adapt

Better way to Format Currency Input editText?

After looking at most of the StackOverflow posts on different ways to achieve this using a TextWatcher, InputFilter, or library like CurrencyEditText I've settled on this simple solution using an OnFocusChangeListener.

The logic is to parse the EditText to a number when it is focused and to format it back when it loses focus.

amount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean hasFocus) {
            Number numberAmount = 0f;
            try {
                numberAmount = Float.valueOf(amount.getText().toString());
            } catch (NumberFormatException e1) {
                e1.printStackTrace();
                try {
                    numberAmount = NumberFormat.getCurrencyInstance().parse(amount.getText().toString());
                } catch (ParseException e2) {
                    e2.printStackTrace();
                }
            }
            if (hasFocus) {
                amount.setText(numberAmount.toString());
            } else {
                amount.setText(NumberFormat.getCurrencyInstance().format(numberAmount));
            }
        }
    });

Why doesn't Java offer operator overloading?

There are a lot of posts complaining about operator overloading.

I felt I had to clarify the "operator overloading" concepts, offering an alternative viewpoint on this concept.

#Code obfuscating?

This argument is a fallacy.

##Obfuscating is possible in all languages...

It is as easy to obfuscate code in C or Java through functions/methods as it is in C++ through operator overloads:

// C++
T operator + (const T & a, const T & b) // add ?
{
   T c ;
   c.value = a.value - b.value ; // subtract !!!
   return c ;
}

// Java
static T add (T a, T b) // add ?
{
   T c = new T() ;
   c.value = a.value - b.value ; // subtract !!!
   return c ;
}

/* C */
T add (T a, T b) /* add ? */
{
   T c ;
   c.value = a.value - b.value ; /* subtract !!! */
   return c ;
}

##...Even in Java's standard interfaces

For another example, let's see the Cloneable interface in Java:

You are supposed to clone the object implementing this interface. But you could lie. And create a different object. In fact, this interface is so weak you could return another type of object altogether, just for the fun of it:

class MySincereHandShake implements Cloneable
{
    public Object clone()
    {
       return new MyVengefulKickInYourHead() ;
    }
}

As the Cloneable interface can be abused/obfuscated, should it be banned on the same grounds C++ operator overloading is supposed to be?

We could overload the toString() method of a MyComplexNumber class to have it return the stringified hour of the day. Should the toString() overloading be banned, too? We could sabotage MyComplexNumber.equals to have it return a random value, modify the operands... etc. etc. etc..

In Java, as in C++, or whatever language, the programmer must respect a minimum of semantics when writing code. This means implementing a add function that adds, and Cloneable implementation method that clones, and a ++ operator than increments.

#What's obfuscating anyway?

Now that we know that code can be sabotaged even through the pristine Java methods, we can ask ourselves about the real use of operator overloading in C++?

##Clear and natural notation: methods vs. operator overloading?

We'll compare below, for different cases, the "same" code in Java and C++, to have an idea of which kind of coding style is clearer.

###Natural comparisons:

// C++ comparison for built-ins and user-defined types
bool    isEqual          = A == B ;
bool    isNotEqual       = A != B ;
bool    isLesser         = A <  B ;
bool    isLesserOrEqual  = A <= B ;

// Java comparison for user-defined types
boolean isEqual          = A.equals(B) ;
boolean isNotEqual       = ! A.equals(B) ;
boolean isLesser         = A.comparesTo(B) < 0 ;
boolean isLesserOrEqual  = A.comparesTo(B) <= 0 ;

Please note that A and B could be of any type in C++, as long as the operator overloads are provided. In Java, when A and B are not primitives, the code can become very confusing, even for primitive-like objects (BigInteger, etc.)...

###Natural array/container accessors and subscripting:

// C++ container accessors, more natural
value        = myArray[25] ;         // subscript operator
value        = myVector[25] ;        // subscript operator
value        = myString[25] ;        // subscript operator
value        = myMap["25"] ;         // subscript operator
myArray[25]  = value ;               // subscript operator
myVector[25] = value ;               // subscript operator
myString[25] = value ;               // subscript operator
myMap["25"]  = value ;               // subscript operator

// Java container accessors, each one has its special notation
value        = myArray[25] ;         // subscript operator
value        = myVector.get(25) ;    // method get
value        = myString.charAt(25) ; // method charAt
value        = myMap.get("25") ;     // method get
myArray[25]  = value ;               // subscript operator
myVector.set(25, value) ;            // method set
myMap.put("25", value) ;             // method put

In Java, we see that for each container to do the same thing (access its content through an index or identifier), we have a different way to do it, which is confusing.

In C++, each container uses the same way to access its content, thanks to operator overloading.

###Natural advanced types manipulation

The examples below use a Matrix object, found using the first links found on Google for "Java Matrix object" and "C++ Matrix object":

// C++ YMatrix matrix implementation on CodeProject
// http://www.codeproject.com/KB/architecture/ymatrix.aspx
// A, B, C, D, E, F are Matrix objects;
E =  A * (B / 2) ;
E += (A - B) * (C + D) ;
F =  E ;                  // deep copy of the matrix

// Java JAMA matrix implementation (seriously...)
// http://math.nist.gov/javanumerics/jama/doc/
// A, B, C, D, E, F are Matrix objects;
E = A.times(B.times(0.5)) ;
E.plusEquals(A.minus(B).times(C.plus(D))) ;
F = E.copy() ;            // deep copy of the matrix

And this is not limited to matrices. The BigInteger and BigDecimal classes of Java suffer from the same confusing verbosity, whereas their equivalents in C++ are as clear as built-in types.

###Natural iterators:

// C++ Random Access iterators
++it ;                  // move to the next item
--it ;                  // move to the previous item
it += 5 ;               // move to the next 5th item (random access)
value = *it ;           // gets the value of the current item
*it = 3.1415 ;          // sets the value 3.1415 to the current item
(*it).foo() ;           // call method foo() of the current item

// Java ListIterator<E> "bi-directional" iterators
value = it.next() ;     // move to the next item & return the value
value = it.previous() ; // move to the previous item & return the value
it.set(3.1415) ;        // sets the value 3.1415 to the current item

###Natural functors:

// C++ Functors
myFunctorObject("Hello World", 42) ;

// Java Functors ???
myFunctorObject.execute("Hello World", 42) ;

###Text concatenation:

// C++ stream handling (with the << operator)
                    stringStream   << "Hello " << 25 << " World" ;
                    fileStream     << "Hello " << 25 << " World" ;
                    outputStream   << "Hello " << 25 << " World" ;
                    networkStream  << "Hello " << 25 << " World" ;
anythingThatOverloadsShiftOperator << "Hello " << 25 << " World" ;

// Java concatenation
myStringBuffer.append("Hello ").append(25).append(" World") ;

Ok, in Java you can use MyString = "Hello " + 25 + " World" ; too... But, wait a second: This is operator overloading, isn't it? Isn't it cheating???

:-D

##Generic code?

The same generic code modifying operands should be usable both for built-ins/primitives (which have no interfaces in Java), standard objects (which could not have the right interface), and user-defined objects.

For example, calculating the average value of two values of arbitrary types:

// C++ primitive/advanced types
template<typename T>
T getAverage(const T & p_lhs, const T & p_rhs)
{
   return (p_lhs + p_rhs) / 2 ;
}

int     intValue     = getAverage(25, 42) ;
double  doubleValue  = getAverage(25.25, 42.42) ;
complex complexValue = getAverage(cA, cB) ; // cA, cB are complex
Matrix  matrixValue  = getAverage(mA, mB) ; // mA, mB are Matrix

// Java primitive/advanced types
// It won't really work in Java, even with generics. Sorry.

#Discussing operator overloading

Now that we have seen fair comparisons between C++ code using operator overloading, and the same code in Java, we can now discuss "operator overloading" as a concept.

##Operator overloading existed since before computers

Even outside of computer science, there is operator overloading: For example, in mathematics, operators like +, -, *, etc. are overloaded.

Indeed, the signification of +, -, *, etc. changes depending on the types of the operands (numerics, vectors, quantum wave functions, matrices, etc.).

Most of us, as part of our science courses, learned multiple significations for operators, depending on the types of the operands. Did we find them confusing, them?

##Operator overloading depends on its operands

This is the most important part of operator overloading: Like in mathematics, or in physics, the operation depends on its operands' types.

So, know the type of the operand, and you will know the effect of the operation.

##Even C and Java have (hard-coded) operator overloading

In C, the real behavior of an operator will change according to its operands. For example, adding two integers is different than adding two doubles, or even one integer and one double. There is even the whole pointer arithmetic domain (without casting, you can add to a pointer an integer, but you cannot add two pointers...).

In Java, there is no pointer arithmetic, but someone still found string concatenation without the + operator would be ridiculous enough to justify an exception in the "operator overloading is evil" creed.

It's just that you, as a C (for historical reasons) or Java (for personal reasons, see below) coder, you can't provide your own.

##In C++, operator overloading is not optional...

In C++, operator overloading for built-in types is not possible (and this is a good thing), but user-defined types can have user-defined operator overloads.

As already said earlier, in C++, and to the contrary to Java, user-types are not considered second-class citizens of the language, when compared to built-in types. So, if built-in types have operators, user types should be able to have them, too.

The truth is that, like the toString(), clone(), equals() methods are for Java (i.e. quasi-standard-like), C++ operator overloading is so much part of C++ that it becomes as natural as the original C operators, or the before mentioned Java methods.

Combined with template programming, operator overloading becomes a well known design pattern. In fact, you cannot go very far in STL without using overloaded operators, and overloading operators for your own class.

##...but it should not be abused

Operator overloading should strive to respect the semantics of the operator. Do not subtract in a + operator (as in "do not subtract in a add function", or "return crap in a clone method").

Cast overloading can be very dangerous because they can lead to ambiguities. So they should really be reserved for well defined cases. As for && and ||, do not ever overload them unless you really know what you're doing, as you'll lose the the short circuit evaluation that the native operators && and || enjoy.

#So... Ok... Then why it is not possible in Java?

Because James Gosling said so:

I left out operator overloading as a fairly personal choice because I had seen too many people abuse it in C++.

James Gosling. Source: http://www.gotw.ca/publications/c_family_interview.htm

Please compare Gosling's text above with Stroustrup's below:

Many C++ design decisions have their roots in my dislike for forcing people to do things in some particular way [...] Often, I was tempted to outlaw a feature I personally disliked, I refrained from doing so because I did not think I had the right to force my views on others.

Bjarne Stroustrup. Source: The Design and Evolution of C++ (1.3 General Background)

##Would operator overloading benefit Java?

Some objects would greatly benefit from operator overloading (concrete or numerical types, like BigDecimal, complex numbers, matrices, containers, iterators, comparators, parsers etc.).

In C++, you can profit from this benefit because of Stroustrup's humility. In Java, you're simply screwed because of Gosling's personal choice.

##Could it be added to Java?

The reasons for not adding operator overloading now in Java could be a mix of internal politics, allergy to the feature, distrust of developers (you know, the saboteur ones that seem to haunt Java teams...), compatibility with the previous JVMs, time to write a correct specification, etc..

So don't hold your breath waiting for this feature...

##But they do it in C#!!!

Yeah...

While this is far from being the only difference between the two languages, this one never fails to amuse me.

Apparently, the C# folks, with their "every primitive is a struct, and a struct derives from Object", got it right at first try.

##And they do it in other languages!!!

Despite all the FUD against used defined operator overloading, the following languages support it: Kotlin, Scala, Dart, Python, F#, C#, D, Algol 68, Smalltalk, Groovy, Perl 6, C++, Ruby, Haskell, MATLAB, Eiffel, Lua, Clojure, Fortran 90, Swift, Ada, Delphi 2005...

So many languages, with so many different (and sometimes opposing) philosophies, and yet they all agree on that point.

Food for thought...

Spring Boot @Value Properties

You haven't included package declarations in the OP but it is possible that neither @SpringBootApplication nor @ComponentScan are scanning for your @Component.

The @ComponentScan Javadoc states:

Either basePackageClasses or basePackages (or its alias value) may be specified to define specific packages to scan. If specific packages are not defined, scanning will occur from the package of the class that declares this annotation.

ISTR wasting a lot of time on this before and found it easiest to simply move my application class to the highest package in my app's package tree.

More recently I encountered a gotcha were the property was being read before the value insertion had been done. Jesse's answer helped as @PostConstruct seems to be the earliest you can read the inserted values, and of course you should let Spring call this.

Batch file to restart a service. Windows

net stop <your service> && net start <your service>

No net restart, unfortunately.

How to set selected value from Combobox?

cmbEmployeeStatus.Text = "text"

PowerShell Remoting giving "Access is Denied" error

Running the command prompt or Powershell ISE as an administrator fixed this for me.

Most efficient way to see if an ArrayList contains an object in Java

There are three basic options:

1) If retrieval performance is paramount and it is practical to do so, use a form of hash table built once (and altered as/if the List changes).

2) If the List is conveniently sorted or it is practical to sort it and O(log n) retrieval is sufficient, sort and search.

3) If O(n) retrieval is fast enough or if it is impractical to manipulate/maintain the data structure or an alternate, iterate over the List.

Before writing code more complex than a simple iteration over the List, it is worth thinking through some questions.

  • Why is something different needed? (Time) performance? Elegance? Maintainability? Reuse? All of these are okay reasons, apart or together, but they influence the solution.

  • How much control do you have over the data structure in question? Can you influence how it is built? Managed later?

  • What is the life cycle of the data structure (and underlying objects)? Is it built up all at once and never changed, or highly dynamic? Can your code monitor (or even alter) its life cycle?

  • Are there other important constraints, such as memory footprint? Does information about duplicates matter? Etc.

Regex for Mobile Number Validation

This regex is very short and sweet for working.

/^([+]\d{2})?\d{10}$/

Ex: +910123456789 or 0123456789

-> /^ and $/ is for starting and ending
-> The ? mark is used for conditional formatting where before question mark is available or not it will work
-> ([+]\d{2}) this indicates that the + sign with two digits '\d{2}' here you can place digit as per country
-> after the ? mark '\d{10}' this says that the digits must be 10 of length change as per your country mobile number length

This is how this regex for mobile number is working.
+ sign is used for world wide matching of number.

if you want to add the space between than you can use the

[ ]

here the square bracket represents the character sequence and a space is character for searching in regex.
for the space separated digit you can use this regex

/^([+]\d{2}[ ])?\d{10}$/

Ex: +91 0123456789

Thanks ask any question if you have.

What's the difference between django OneToOneField and ForeignKey?

Also OneToOneField is useful to be used as primary key to avoid key duplication. One may do not have implicit / explicit autofield

models.AutoField(primary_key=True)

but use OneToOneField as primary key instead (imagine UserProfile model for example):

user = models.OneToOneField(
    User, null=False, primary_key=True, verbose_name='Member profile')

SVN: Folder already under version control but not comitting?

For me doing a svn update, followed by svn commit worked. There were no .svn folders present in folder which was failing to add.

Set Culture in an ASP.Net MVC app

If using Subdomains, for example like "pt.mydomain.com" to set portuguese for example, using Application_AcquireRequestState won't work, because it's not called on subsequent cache requests.

To solve this, I suggest an implementation like this:

  1. Add the VaryByCustom parameter to the OutPutCache like this:

    [OutputCache(Duration = 10000, VaryByCustom = "lang")]
    public ActionResult Contact()
    {
        return View("Contact");
    }
    
  2. In global.asax.cs, get the culture from the host using a function call:

    protected void Application_AcquireRequestState(object sender, EventArgs e)
    {
        System.Threading.Thread.CurrentThread.CurrentUICulture = GetCultureFromHost();
    }
    
  3. Add the GetCultureFromHost function to global.asax.cs:

    private CultureInfo GetCultureFromHost()
    {
        CultureInfo ci = new CultureInfo("en-US"); // en-US
        string host = Request.Url.Host.ToLower();
        if (host.Equals("mydomain.com"))
        {
            ci = new CultureInfo("en-US");
        }
        else if (host.StartsWith("pt."))
        {
            ci = new CultureInfo("pt");
        }
        else if (host.StartsWith("de."))
        {
            ci = new CultureInfo("de");
        }
        else if (host.StartsWith("da."))
        {
            ci = new CultureInfo("da");
        }
    
        return ci;
    }
    
  4. And finally override the GetVaryByCustomString(...) to also use this function:

    public override string GetVaryByCustomString(HttpContext context, string value)
    {
        if (value.ToLower() == "lang")
        {
            CultureInfo ci = GetCultureFromHost();
            return ci.Name;
        }
        return base.GetVaryByCustomString(context, value);
    }
    

The function Application_AcquireRequestState is called on non-cached calls, which allows the content to get generated and cached. GetVaryByCustomString is called on cached calls to check if the content is available in cache, and in this case we examine the incoming host domain value, again, instead of relying on just the current culture info, which could have changed for the new request (because we are using subdomains).

Understanding the difference between Object.create() and new SomeFunction()

This:

var foo = new Foo();

and

var foo = Object.create(Foo.prototype);

are quite similar. One important difference is that new Foo actually runs constructor code, whereas Object.create will not execute code such as

function Foo() {
    alert("This constructor does not run with Object.create");
}

Note that if you use the two-parameter version of Object.create() then you can do much more powerful things.

iPhone Debugging: How to resolve 'failed to get the task for process'?

Go to Edit Schemes and under Run -> Info -> Build Configuration, change from Ad-Hoc to Debug. Click OK to save.

Optimal way to concatenate/aggregate strings

For those of us who found this and are not using Azure SQL Database:

STRING_AGG() in PostgreSQL, SQL Server 2017 and Azure SQL
https://www.postgresql.org/docs/current/static/functions-aggregate.html
https://docs.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql

GROUP_CONCAT() in MySQL
http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat

(Thanks to @Brianjorden and @milanio for Azure update)

Example Code:

select Id
, STRING_AGG(Name, ', ') Names 
from Demo
group by Id

SQL Fiddle: http://sqlfiddle.com/#!18/89251/1

Concatenate two slices in Go

I would like to emphasize @icza answer and simplify it a bit since it is a crucial concept. I assume that reader is familiar with slices.

c := append(a, b...)

This is a valid answer to the question. BUT if you need to use slices 'a' and 'c' later in code in different context, this is not the safe way to concatenate slices.

To explain, lets read the expression not in terms of slices, but in terms of underlying arrays:

"Take (underlying) array of 'a' and append elements from array 'b' to it. If array 'a' has enough capacity to include all elements from 'b' - underlying array of 'c' will not be a new array, it will actually be array 'a'. Basically, slice 'a' will show len(a) elements of underlying array 'a', and slice 'c' will show len(c) of array 'a'."

append() does not necessarily create a new array! This can lead to unexpected results. See Go Playground example.

Always use make() function if you want to make sure that new array is allocated for the slice. For example here are few ugly but efficient enough options for the task.

la := len(a)
c := make([]int, la, la + len(b))
_ = copy(c, a)
c = append(c, b...)

la := len(a)
c := make([]int, la + len(b))
_ = copy(c, a)
_ = copy(c[la:], b)

How to check if a stored procedure exists before creating it

As of SQL SERVER 2016 you can use the new DROP PROCEDURE IF EXISTS.
DROP { PROC | PROCEDURE } [ IF EXISTS ] { [ schema_name. ] procedure } [ ,...n ]

Reference : https://msdn.microsoft.com/en-us/library/ms174969.aspx

How to check if a radiobutton is checked in a radiogroup in Android?

If you want to check on just one RadioButton you can use the isChecked function

if(radioButton.isChecked())
{
  // is checked    
}
else
{
  // not checked
}

and if you have a RadioGroup you can use

if (radioGroup.getCheckedRadioButtonId() == -1)
{
  // no radio buttons are checked
}
else
{
  // one of the radio buttons is checked
}

git pull fails "unable to resolve reference" "unable to update local ref"

I had this issue while using SourceTree. I tried to pull again and it worked. I think I Was witching branches (checkout) too fast :).

My situation is a bit different from the poster's because my repository has been relatively cooperative, without any apparent corruption.

LAST_INSERT_ID() MySQL

For no InnoDB solution: you can use a procedure don't forgot to set the delimiter for storing the procedure with ;

CREATE PROCEDURE myproc(OUT id INT, IN otherid INT, IN title VARCHAR(255))
BEGIN
LOCK TABLES `table1` WRITE;
INSERT INTO `table1` ( `title` ) VALUES ( @title ); 
SET @id = LAST_INSERT_ID();
UNLOCK TABLES;
INSERT INTO `table2` ( `parentid`, `otherid`, `userid` ) VALUES (@id, @otherid, 1); 
END

And you can use it...

SET @myid;
CALL myproc( @myid, 1, "my title" );
SELECT @myid;

C# : Passing a Generic Object

You cannot access var with the generic.

Try something like

Console.WriteLine("Generic : {0}", test);

And override ToString method [1]

[1] http://msdn.microsoft.com/en-us/library/system.object.tostring.aspx

Android Studio Rendering Problems : The following classes could not be found

You have to do two things:

  • be sure to have imported right appcompat-v7 library in your project structure -> dependencies
  • change the theme in the preview window to not an AppCompat theme. Try with Holo.light or Holo.dark for example.

#1130 - Host ‘localhost’ is not allowed to connect to this MySQL server

Find the file "config.inc.php" under your phpMyAdmin directory and edit the following lines:

$cfg['Servers'][$i]['auth_type'] = 'config'; // config, http, cookie

$cfg['Servers'][$i]['user'] = 'root'; // MySQL user

$cfg['Servers'][$i]['password'] = 'TYPE_YOUR_PASSWORD_HERE'; // MySQL password

Note that the password used in the 'password' field must be the same for the MySQL root password. Also, you should check if root login is allowed in this line:

$cfg['Servers'][$i]['AllowRoot']     = TRUE;        // true = allow root login

This way you have your root password set.

store return value of a Python script in a bash script

read it in the docs. If you return anything but an int or None it will be printed to stderr.

To get just stderr while discarding stdout do:

output=$(python foo.py 2>&1 >/dev/null)

Computational complexity of Fibonacci Sequence

Just ask yourself how many statements need to execute for F(n) to complete.

For F(1), the answer is 1 (the first part of the conditional).

For F(n), the answer is F(n-1) + F(n-2).

So what function satisfies these rules? Try an (a > 1):

an == a(n-1) + a(n-2)

Divide through by a(n-2):

a2 == a + 1

Solve for a and you get (1+sqrt(5))/2 = 1.6180339887, otherwise known as the golden ratio.

So it takes exponential time.

"Unicode Error "unicodeescape" codec can't decode bytes... Cannot open text files in Python 3

Typical error on Windows because the default user directory is C:\user\<your_user>, so when you want to use this path as an string parameter into a Python function, you get a Unicode error, just because the \u is a Unicode escape. Any character not numeric after this produces an error.

To solve it, just double the backslashes: C:\\user\\<\your_user>...

How to convert string to Date in Angular2 \ Typescript?

You can use date filter to convert in date and display in specific format.

In .ts file (typescript):

let dateString = '1968-11-16T00:00:00' 
let newDate = new Date(dateString);

In HTML:

{{dateString |  date:'MM/dd/yyyy'}}

Below are some formats which you can implement :

Backend:

public todayDate = new Date();

HTML :

<select>
<option value=""></option>
<option value="MM/dd/yyyy">[{{todayDate | date:'MM/dd/yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy">[{{todayDate | date:'EEEE, MMMM d, yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm a'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm:ss a'}}]</option>
<option value="MM/dd/yyyy h:mm a">[{{todayDate | date:'MM/dd/yyyy h:mm a'}}]</option>
<option value="MM/dd/yyyy h:mm:ss a">[{{todayDate | date:'MM/dd/yyyy h:mm:ss a'}}]</option>
<option value="MMMM d">[{{todayDate | date:'MMMM d'}}]</option>   
<option value="yyyy-MM-ddTHH:mm:ss">[{{todayDate | date:'yyyy-MM-ddTHH:mm:ss'}}]</option>
<option value="h:mm a">[{{todayDate | date:'h:mm a'}}]</option>
<option value="h:mm:ss a">[{{todayDate | date:'h:mm:ss a'}}]</option>      
<option value="EEEE, MMMM d, yyyy hh:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy hh:mm:ss a'}}]</option>
<option value="MMMM yyyy">[{{todayDate | date:'MMMM yyyy'}}]</option> 
</select>

Cannot start GlassFish 4.1 from within Netbeans 8.0.1 Service area

If you are using netbeans 7 and greater with oracle xe do the following on netbeans :

  1. go to services tab
  2. under servers, remove glassfish
  3. add back glassfish server
  4. input port number 9090 for http access

Glassfish can use that one if available or some random port number is created

Android Preventing Double Click On A Button

final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {

    private final AtomicBoolean onClickEnabled = new AtomicBoolean(true);

    @Override
    public void onClick(View v) {
        Log.i("TAG", "onClick begin");
        if (!onClickEnabled.compareAndSet(true, false)) {
            Log.i("TAG", "onClick not enabled");
            return;
        }

        button.setEnabled(false);

        // your action here

        button.setEnabled(true);
        onClickEnabled.set(true);
        Log.i("TAG", "onClick end");
    }
});

Convert NSDate to NSString

swift 4 answer

static let dateformat: String = "yyyy-MM-dd'T'HH:mm:ss"
public static func stringTodate(strDate : String) -> Date
{

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = dateformat
    let date = dateFormatter.date(from: strDate)
    return date!
}
public static func dateToString(inputdate : Date) -> String
{

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = dateformat
    return formatter.string(from: inputdate)

}

AngularJs: How to check for changes in file input fields?

I made a small directive to listen for file input changes.

View JSFiddle

view.html:

<input type="file" custom-on-change="uploadFile">

controller.js:

app.controller('myCtrl', function($scope){
    $scope.uploadFile = function(event){
        var files = event.target.files;
    };
});     

directive.js:

app.directive('customOnChange', function() {
  return {
    restrict: 'A',
    link: function (scope, element, attrs) {
      var onChangeHandler = scope.$eval(attrs.customOnChange);
      element.on('change', onChangeHandler);
      element.on('$destroy', function() {
        element.off();
      });

    }
  };
});

ORA-30926: unable to get a stable set of rows in the source tables

Had the error today on a 12c and none of the existing answers fit (no duplicates, no non-deterministic expressions in the WHERE clause). My case was related to that other possible cause of the error, according to Oracle's message text (emphasis below):

ORA-30926: unable to get a stable set of rows in the source tables
Cause: A stable set of rows could not be got because of large dml activity or a non-deterministic where clause.

The merge was part of a larger batch, and was executed on a live database with many concurrent users. There was no need to change the statement. I just committed the transaction before the merge, then ran the merge separately, and committed again. So the solution was found in the suggested action of the message:

Action: Remove any non-deterministic where clauses and reissue the dml.

What are CN, OU, DC in an LDAP search?

  • CN = Common Name
  • OU = Organizational Unit
  • DC = Domain Component

These are all parts of the X.500 Directory Specification, which defines nodes in a LDAP directory.

You can also read up on LDAP data Interchange Format (LDIF), which is an alternate format.

You read it from right to left, the right-most component is the root of the tree, and the left most component is the node (or leaf) you want to reach.

Each = pair is a search criteria.

With your example query

("CN=Dev-India,OU=Distribution Groups,DC=gp,DC=gl,DC=google,DC=com");

In effect the query is:

From the com Domain Component, find the google Domain Component, and then inside it the gl Domain Component and then inside it the gp Domain Component.

In the gp Domain Component, find the Organizational Unit called Distribution Groups and then find the the object that has a common name of Dev-India.

Saving utf-8 texts with json.dumps as UTF8, not as \u escape sequence

Thanks for the original answer here. With python 3 the following line of code:

print(json.dumps(result_dict,ensure_ascii=False))

was ok. Consider trying not writing too much text in the code if it's not imperative.

This might be good enough for the python console. However, to satisfy a server you might need to set the locale as explained here (if it is on apache2) http://blog.dscpl.com.au/2014/09/setting-lang-and-lcall-when-using.html

basically install he_IL or whatever language locale on ubuntu check it is not installed

locale -a 

install it where XX is your language

sudo apt-get install language-pack-XX

For example:

sudo apt-get install language-pack-he

add the following text to /etc/apache2/envvrs

export LANG='he_IL.UTF-8'
export LC_ALL='he_IL.UTF-8'

Than you would hopefully not get python errors on from apache like:

print (js) UnicodeEncodeError: 'ascii' codec can't encode characters in position 41-45: ordinal not in range(128)

Also in apache try to make utf the default encoding as explained here:
How to change the default encoding to UTF-8 for Apache?

Do it early because apache errors can be pain to debug and you can mistakenly think it's from python which possibly isn't the case in that situation

Convert a String of Hex into ASCII in Java

Easiest way to do it with javax.xml.bind.DatatypeConverter:

    String hex = "75546f7272656e745c436f6d706c657465645c6e667375635f6f73745f62795f6d757374616e675c50656e64756c756d2d392c303030204d696c65732e6d7033006d7033006d7033004472756d202620426173730050656e64756c756d00496e2053696c69636f00496e2053696c69636f2a3b2a0050656e64756c756d0050656e64756c756d496e2053696c69636f303038004472756d2026204261737350656e64756c756d496e2053696c69636f30303800392c303030204d696c6573203c4d757374616e673e50656e64756c756d496e2053696c69636f3030380050656e64756c756d50656e64756c756d496e2053696c69636f303038004d50330000";
    byte[] s = DatatypeConverter.parseHexBinary(hex);
    System.out.println(new String(s));

How to leave/exit/deactivate a Python virtualenv

To activate a Python virtual environment:

$cd ~/python-venv/
$./bin/activate

To deactivate:

$deactivate

How to get label text value form a html page?

The best way to get the text value from a <label> element is as follows.

if you will be getting element ids frequently it's best to have a function to return the ids:

function id(e){return document.getElementById(e)}

Assume the following structure: <label for='phone'>Phone number</label> <input type='text' id='phone' placeholder='Mobile or landline numbers...'>

This code will extract the text value 'Phone number' from the<label>: var text = id('phone').previousElementSibling.innerHTML;

This code works on all browsers, and you don't have to give each<label>element a unique id.

Make a URL-encoded POST request using `http.NewRequest(...)`

URL-encoded payload must be provided on the body parameter of the http.NewRequest(method, urlStr string, body io.Reader) method, as a type that implements io.Reader interface.

Based on the sample code:

package main

import (
    "fmt"
    "net/http"
    "net/url"
    "strconv"
    "strings"
)

func main() {
    apiUrl := "https://api.com"
    resource := "/user/"
    data := url.Values{}
    data.Set("name", "foo")
    data.Set("surname", "bar")

    u, _ := url.ParseRequestURI(apiUrl)
    u.Path = resource
    urlStr := u.String() // "https://api.com/user/"

    client := &http.Client{}
    r, _ := http.NewRequest(http.MethodPost, urlStr, strings.NewReader(data.Encode())) // URL-encoded payload
    r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
    r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))

    resp, _ := client.Do(r)
    fmt.Println(resp.Status)
}

resp.Status is 200 OK this way.

Oracle: Call stored procedure inside the package

You're nearly there, just take out the EXECUTE:

DECLARE
  procId NUMBER;

BEGIN
  PKG1.INIT(1143824, 0, procId);
  DBMS_OUTPUT.PUT_LINE(procId);
END;

python numpy/scipy curve fitting

You'll first need to separate your numpy array into two separate arrays containing x and y values.

x = [1, 2, 3, 9]
y = [1, 4, 1, 3]

curve_fit also requires a function that provides the type of fit you would like. For instance, a linear fit would use a function like

def func(x, a, b):
    return a*x + b

scipy.optimize.curve_fit(func, x, y) will return a numpy array containing two arrays: the first will contain values for a and b that best fit your data, and the second will be the covariance of the optimal fit parameters.

Here's an example for a linear fit with the data you provided.

import numpy as np
from scipy.optimize import curve_fit

x = np.array([1, 2, 3, 9])
y = np.array([1, 4, 1, 3])

def fit_func(x, a, b):
    return a*x + b

params = curve_fit(fit_func, x, y)

[a, b] = params[0]

This code will return a = 0.135483870968 and b = 1.74193548387

Here's a plot with your points and the linear fit... which is clearly a bad one, but you can change the fitting function to obtain whatever type of fit you would like.

enter image description here

PHP multidimensional array search by value

Building off Jakub's excellent answer, here is a more generalized search that will allow the key to specified (not just for uid):

function searcharray($value, $key, $array) {
   foreach ($array as $k => $val) {
       if ($val[$key] == $value) {
           return $k;
       }
   }
   return null;
}

Usage: $results = searcharray('searchvalue', searchkey, $array);

How to detect lowercase letters in Python?

To check if a character is lower case, use the islower method of str. This simple imperative program prints all the lowercase letters in your string:

for c in s:
    if c.islower():
         print c

Note that in Python 3 you should use print(c) instead of print c.


Possibly ending up with assigning those letters to a different variable.

To do this I would suggest using a list comprehension, though you may not have covered this yet in your course:

>>> s = 'abCd'
>>> lowercase_letters = [c for c in s if c.islower()]
>>> print lowercase_letters
['a', 'b', 'd']

Or to get a string you can use ''.join with a generator:

>>> lowercase_letters = ''.join(c for c in s if c.islower())
>>> print lowercase_letters
'abd'

How to print jquery object/array

Your result is currently in string format, you need to parse it as json.

var obj = $.parseJSON(result);
alert(obj[0].category);

Additionally, if you set the dataType of the ajax call you are making to json, you can skip the $.parseJSON() step.

PHP function overloading

PHP does not support overloading for now. Hope this will be implemented in the other versions like other programming languages.

Checkout this library, This will allow you to use PHP Overloading in terms of closures. https://github.com/Sahil-Gulati/Overloading

Apache VirtualHost 403 Forbidden

The problem was that the file access permission was wrong.

I changed the permissions of the directory and it worked.

How to align texts inside of an input?

If you want to get it aligned to the right after the text looses focus you can try to use the direction modifier. This will show the right part of the text after loosing focus. e.g. useful if you want to show the file name in a large path.

_x000D_
_x000D_
input.rightAligned {_x000D_
  direction:ltr;_x000D_
  overflow:hidden;_x000D_
}_x000D_
input.rightAligned:not(:focus) {_x000D_
  direction:rtl;_x000D_
  text-align: left;_x000D_
  unicode-bidi: plaintext;_x000D_
  text-overflow: ellipsis;_x000D_
}
_x000D_
<form>_x000D_
    <input type="text" class="rightAligned" name="name" value="">_x000D_
</form>
_x000D_
_x000D_
_x000D_

The not selector is currently well supported : Browser support

When do I use path params vs. query params in a RESTful API?

Example URL: /rest/{keyword}

This URL is an example for path parameters. We can get this URL data by using @PathParam.

Example URL: /rest?keyword=java&limit=10

This URL is an example for query parameters. We can get this URL data by using @Queryparam.

How do I resize a Google Map with JavaScript after it has loaded?

This is best it will do the Job done. It will re-size your Map. No need to inspect element anymore to re-size your Map. What it does it will automatically trigger re-size event .

    google.maps.event.addListener(map, "idle", function()
        {
            google.maps.event.trigger(map, 'resize');
        });

        map_array[Next].setZoom( map.getZoom() - 1 );
    map_array[Next].setZoom( map.getZoom() + 1 );

React fetch data in server before render

What you're looking for is componentWillMount.

From the documentation:

Invoked once, both on the client and server, immediately before the initial rendering occurs. If you call setState within this method, render() will see the updated state and will be executed only once despite the state change.

So you would do something like this:

componentWillMount : function () {
    var data = this.getData();
    this.setState({data : data});
},

This way, render() will only be called once, and you'll have the data you're looking for in the initial render.

How does database indexing work?

Simple Description!

The index is nothing but a data structure that stores the values for a specific column in a table. An index is created on a column of a table.

Example: We have a database table called User with three columns – Name, Age and Address. Assume that the User table has thousands of rows.

Now, let’s say that we want to run a query to find all the details of any users who are named 'John'. If we run the following query:

SELECT * FROM User 
WHERE Name = 'John'

The database software would literally have to look at every single row in the User table to see if the Name for that row is ‘John’. This will take a long time.

This is where index helps us: index is used to speed up search queries by essentially cutting down the number of records/rows in a table that needs to be examined.

How to create an index:

CREATE INDEX name_index
ON User (Name)

An index consists of column values(Eg: John) from one table, and those values are stored in a data structure.

So now the database will use the index to find employees named John because the index will presumably be sorted alphabetically by the Users name. And, because it is sorted, it means searching for a name is a lot faster because all names starting with a “J” will be right next to each other in the index!

How do I import the javax.servlet API in my Eclipse project?

I was getting a null pointer exception during project creation related to "Dynamic Web Module".

To get the project to compile (that is, to javax.servlet to import successfully) I had to go to project's Properties, pick Project Facets in the sidebar, tick Dynamic Web Module and click Apply.

Surprisingly, this time "Dynamic Web Module" facet installed correctly, and import started to work.

Regular expression for floating point numbers

For those who searching a regex which would validate an entire input that should be a signed float point number on every single character typed by a user.

I.e. a sign goes first (should match and be valid), then all the digits (still match and valid) and its optional decimal part.

In JS, we use onkeydown/oninput event to do that + the following regex:

^[+-]?[0-9]*([\.][0-9]*)?$

Getting the first character of a string with $str[0]

Yes. Strings can be seen as character arrays, and the way to access a position of an array is to use the [] operator. Usually there's no problem at all in using $str[0] (and I'm pretty sure is much faster than the substr() method).

There is only one caveat with both methods: they will get the first byte, rather than the first character. This is important if you're using multibyte encodings (such as UTF-8). If you want to support that, use mb_substr(). Arguably, you should always assume multibyte input these days, so this is the best option, but it will be slightly slower.

"insufficient memory for the Java Runtime Environment " message in eclipse

How to diagnose this error even when running the simple command:

java -version
#
# There is insufficient memory for the Java Runtime Environment to continue.
# Cannot create GC thread. Out of system resources.
# An error report file with more information is saved as:
# /home2/ericlesc/code/java/c2/hs_err_pid23944.log

Check the amount of free memory you have:

free -m
             total       used       free     shared    buffers     cached
Mem:         28119      26643       1475        189       2391      15368
-/+ buffers/cache:       8884      19235
Swap:         5117         34       5083

Check the max number of user processes, make sure you are not over limit:

ulimit -a

ps -ef | wc -l

For me, the reason this happened was because PHP had consumed too much memory allocated to me on bluehost, and the way I was able to fix it, without restarting PHP or the server ( I can't ) was to take the public_html directory and rename it. And give it a minute for PHP to see the change, then rename it back.

A bug in the php engine itself. I found a clever way to give the PHP engine a swift kick.

(update Feb 2016) (I'm getting a spike of up-votes on this because Bluehost instance PHP engines are reserving all the memory and leaving none for the JVM. In their defense, PHP is evolving into an unholy rube Goldberg machine. Bluehost as a service is on the decline.

Comparing strings in Java

[EDIT] I made a mistake earlier, because, to get the text, you need to use .getText().toString().

Here is a full working example:

package com.psegina.passwordTest01;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

public class Main extends Activity implements OnClickListener {
    LinearLayout l;
    EditText user;
    EditText pwd;
    Button btn;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        l = new LinearLayout(this);
        user = new EditText(this);
        pwd = new EditText(this);
        btn = new Button(this);

        l.addView(user);
        l.addView(pwd);
        l.addView(btn);
        btn.setOnClickListener(this);

        setContentView(l);
    }

    public void onClick(View v){
        String u = user.getText().toString();
        String p = pwd.getText().toString();
        if( u.equals( p ) )
            Toast.makeText(getApplicationContext(), "Matches", Toast.LENGTH_SHORT).show();
        else
            Toast.makeText(getApplicationContext(), user.getText()+" != "+pwd.getText(), Toast.LENGTH_SHORT).show();
    }
}

Original answer (Will not work because of the lack of toString())

Try using .getText() instead of .toString().

if( passw1.getText() == passw2.getText() )
#do something

.toString() returns a String representation of the whole object, meaning it won't return the text you entered in the field (see for yourself by adding a Toast which will show the output of .toString())

isset in jQuery?

You can simply use this:

if ($("#one")){
   alert('yes');
}

if ($("#two")){
   alert('yes');
}

if ($("#three")){
   alert('yes');
}

if ($("#four")){
   alert('no');
}

Sorry, my mistake, it does not work.

HTTP Status 405 - Method Not Allowed Error for Rest API

@Produces({"text/plain","application/xml","application/json"}) change this to @Produces("text/plain") and try,

VIM Disable Automatic Newline At End Of File

Try to add in .vimrc

set binary

How to overlay image with color in CSS?

You should use rgba for overlaying your element with photos.rgba is a way to declare a color in CSS that includes alpha transparency support. you can use .row as an overlayer like this:

#header {
    background: url(../img/bg.jpg) 0 0 no-repeat fixed;
    height: 100%;
    overflow: hidden;
    color: #FFFFFF
 }

.row{
    background: rgba(39,62,84,0.82);
    overflow: hidden;
    height: 100%;
    z-index: 2;
}

How to use adb pull command?

I don't think adb pull handles wildcards for multiple files. I ran into the same problem and did this by moving the files to a folder and then pulling the folder.

I found a link doing the same thing. Try following these steps.

How to copy selected files from Android with adb pull

Is it possible to get all arguments of a function as single object inside that function?

As many other pointed out, arguments contains all the arguments passed to a function.

If you want to call another function with the same args, use apply

Example:

var is_debug = true;
var debug = function() {
  if (is_debug) {
    console.log.apply(console, arguments);
  }
}

debug("message", "another argument")

Creating an IFRAME using JavaScript

It is better to process HTML as a template than to build nodes via JavaScript (HTML is not XML after all.) You can keep your IFRAME's HTML syntax clean by using a template and then appending the template's contents into another DIV.

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

<script id="iframeTemplate" type="text/html">
    <iframe src="...">
        <!-- replace this line with alternate content -->
    </iframe>
</script>

<script type="text/javascript">
var element,
    html,
    template;

element = document.getElementById("placeholder");
template = document.getElementById("iframeTemplate");
html = template.innerHTML;

element.innerHTML = html;
</script>

Edit a specific Line of a Text File in C#

You need to Open the output file for write access rather than using a new StreamReader, which always overwrites the output file.

StreamWriter stm = null;
fi = new FileInfo(@"C:\target.xml");
if (fi.Exists)
   stm = fi.OpenWrite();

Of course, you will still have to seek to the correct line in the output file, which will be hard since you can't read from it, so unless you already KNOW the byte offset to seek to, you probably really want read/write access.

FileStream stm = fi.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);

with this stream, you can read until you get to the point where you want to make changes, then write. Keep in mind that you are writing bytes, not lines, so to overwrite a line you will need to write the same number of characters as the line you want to change.

Set position / size of UI element as percentage of screen size

For TextView and it's descendants (e.g., Button) you can get the display size from the WindowManager and then set the TextView height to be some fraction of it:

Button btn = new Button (this);
android.view.Display display = ((android.view.WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); 
btn.setHeight((int)(display.getHeight()*0.68));

Is JVM ARGS '-Xms1024m -Xmx2048m' still useful in Java 8?

What I know is one reason when “GC overhead limit exceeded” error is thrown when 2% of the memory is freed after several GC cycles

By this error your JVM is signalling that your application is spending too much time in garbage collection. so the little amount GC was able to clean will be quickly filled again thus forcing GC to restart the cleaning process again.

You should try changing the value of -Xmx and -Xms.

Map enum in JPA with fixed values?

The problem is, I think, that JPA was never incepted with the idea in mind that we could have a complex preexisting Schema already in place.

I think there are two main shortcomings resulting from this, specific to Enum:

  1. The limitation of using name() and ordinal(). Why not just mark a getter with @Id, the way we do with @Entity?
  2. Enum's have usually representation in the database to allow association with all sorts of metadata, including a proper name, a descriptive name, maybe something with localization etc. We need the easy of use of an Enum combined with the flexibility of an Entity.

Help my cause and vote on JPA_SPEC-47

Would this not be more elegant than using a @Converter to solve the problem?

// Note: this code won't work!!
// it is just a sample of how I *would* want it to work!
@Enumerated
public enum Language {
  ENGLISH_US("en-US"),
  ENGLISH_BRITISH("en-BR"),
  FRENCH("fr"),
  FRENCH_CANADIAN("fr-CA");
  @ID
  private String code;
  @Column(name="DESCRIPTION")
  private String description;

  Language(String code) {
    this.code = code;
  }

  public String getCode() {
    return code;
  }

  public String getDescription() {
    return description;
  }
}

Font.createFont(..) set color and size (java.awt.Font)

Well, once you have your font, you can invoke deriveFont. For example,

helvetica = helvetica.deriveFont(Font.BOLD, 12f);

Changes the font's style to bold and its size to 12 points.

ImageButton in Android

you are setting the image with the property "src"

android:src="@drawable/eye">

use "background" property instead "src" property:

android:background="@drawable/eye"

like:

<ImageButton
  android:id="@+id/Button01"
  android:scaleType="fitXY" 
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:cropToPadding="false"
  android:paddingLeft="10dp"
  android:background="@drawable/eye"> // this is the image(eye)
</ImageButton>

jQuery class within class selector

For this html:

<div class="outer">
     <div class="inner"></div>
</div>

This selector should work:

$('.outer > .inner')

How to make overlay control above all other controls?

Controls in the same cell of a Grid are rendered back-to-front. So a simple way to put one control on top of another is to put it in the same cell.

Here's a useful example, which pops up a panel that disables everything in the view (i.e. the user control) with a busy message while a long-running task is executed (i.e. while the BusyMessage bound property isn't null):

<Grid>

    <local:MyUserControl DataContext="{Binding}"/>

    <Grid>
        <Grid.Style>
            <Style TargetType="Grid">
                <Setter Property="Visibility"
                        Value="Visible" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding BusyMessage}"
                                 Value="{x:Null}">
                        <Setter Property="Visibility"
                                Value="Collapsed" />
                    </DataTrigger>

                </Style.Triggers>
            </Style>
        </Grid.Style>
        <Border HorizontalAlignment="Stretch"
                VerticalAlignment="Stretch"
                Background="DarkGray"
                Opacity=".7" />
        <Border HorizontalAlignment="Center"
                VerticalAlignment="Center"
                Background="White"
                Padding="20"
                BorderBrush="Orange"
                BorderThickness="4">
            <TextBlock Text="{Binding BusyMessage}" />
        </Border>
    </Grid>
</Grid>

Developing C# on Linux

You can also install it using conda (tested on Ubuntu):

conda create --name csharp
conda activate csharp
conda install -c conda-forge mono

Convert a String In C++ To Upper Case

struct convert {
   void operator()(char& c) { c = toupper((unsigned char)c); }
};

// ... 
string uc_str;
for_each(uc_str.begin(), uc_str.end(), convert());

Note: A couple of problems with the top solution:

21.5 Null-terminated sequence utilities

The contents of these headers shall be the same as the Standard C Library headers <ctype.h>, <wctype.h>, <string.h>, <wchar.h>, and <stdlib.h> [...]

  • Which means that the cctype members may well be macros not suitable for direct consumption in standard algorithms.

  • Another problem with the same example is that it does not cast the argument or verify that this is non-negative; this is especially dangerous for systems where plain char is signed. (The reason being: if this is implemented as a macro it will probably use a lookup table and your argument indexes into that table. A negative index will give you UB.)

How do I reverse a commit in git?

Or you can try using git revert http://www.kernel.org/pub/software/scm/git/docs/git-revert.html. I think something like git revert HEAD~1 -m 1 will revert your last commit (if it's still the last commit).

ios simulator: how to close an app

For iOS 7 & above:

  • shift+command+H twice to simulate the double tap of home button
  • swipe your app's screenshot upward to close it

You'll see screenshots representing the apps suspended on your device - those screenshots respond to touch events. Swiping is the gesture you'll make to "fling" the screenshot off of the screen. Note that on machines where your mouse is intended to represent your finger, you'll click and swipe as if it is your finger tapping and making the gesture.

Get Cell Value from a DataTable in C#

You can iterate DataTable like this:

private void button1_Click(object sender, EventArgs e)
{
    for(int i = 0; i< dt.Rows.Count;i++)
        for (int j = 0; j <dt.Columns.Count ; j++)
        {
            object o = dt.Rows[i].ItemArray[j];
            //if you want to get the string
            //string s = o = dt.Rows[i].ItemArray[j].ToString();
        }
}

Depending on the type of the data in the DataTable cell, you can cast the object to whatever you want.

Psql list all tables

In SQL Query, you can write this code:

select table_name from information_schema.tables where table_schema='YOUR_TABLE_SCHEME';

Replace your table scheme with YOUR_TABLE_SCHEME;

Example:

select table_name from information_schema.tables where table_schema='eLearningProject';

To see all scheme and all tables, there is no need of where clause:

select table_name from information_schema.tables

Cast from VARCHAR to INT - MySQL

As described in Cast Functions and Operators:

The type for the result can be one of the following values:

  • BINARY[(N)]
  • CHAR[(N)]
  • DATE
  • DATETIME
  • DECIMAL[(M[,D])]
  • SIGNED [INTEGER]
  • TIME
  • UNSIGNED [INTEGER]

Therefore, you should use:

SELECT CAST(PROD_CODE AS UNSIGNED) FROM PRODUCT

Laravel - Forbidden You don't have permission to access / on this server

You might be facing the file permissions issue. Verify your htacces file, did it change from yesterday ? Also, if you were doing any "composer update" or "artisan optimize" stuff, try chowning your laravel project folder for your username.

chown -R yourusername yourlaravelappfolder 

EDIT: the problem is possibly due to your local file permissions concerning Vagrant. Try to

set the permissions to the Vagrantfile containing folder to 777

How to use underscore.js as a template engine?

In it's simplest form you would use it like:

var html = _.template('<li><%= name %></li>', { name: 'John Smith' });
//html is now '<li>John Smith</li>'   

If you're going to be using a template a few times you'll want to compile it so it's faster:

var template = _.template('<li><%= name %></li>');

var html = [];
for (var key in names) {
    html += template({ name: names[i] });
}

console.log(html.join('')); //Outputs a string of <li> items

I personally prefer the Mustache style syntax. You can adjust the template token markers to use double curly braces:

_.templateSettings.interpolate = /\{\{(.+?)\}\}/g;

var template = _.template('<li>{{ name }}</li>');

Assigning a variable NaN in python without numpy

Use float("nan"):

>>> float("nan")
nan

How to HTML encode/escape a string? Is there a built-in?

The h helper method:

<%=h "<p> will be preserved" %>

How to parse JSON string in Typescript

TS has a JavaScript runtime

Typescript has a JavaScript runtime because it gets compiled to JS. This means JS objects which are built in as part of the language such as JSON, Object, and Math are also available in TS. Therefore we can just use the JSON.parse method to parse the JSON string.

Example:

const JSONStr = '{"name": "Bob", "error": false}'

// The JSON object is part of the runtime
const parsedObj = JSON.parse(JSONStr);

console.log(parsedObj);
// [LOG]: {
//   "name": "Bob",
//   "error": false
// } 

// The Object object is also part of the runtime so we can use it in TS
const objKeys = Object.keys(parsedObj);

console.log(objKeys);
// [LOG]: ["name", "error"] 

The only thing now is that parsedObj is type any which is generally a bad practice in TS. We can type the object if we are using type guards. Here is an example:

const JSONStr = '{"name": "Bob", "error": false}'
const parsedObj = JSON.parse(JSONStr);

interface nameErr {
  name: string;
  error: boolean;
}

function isNameErr(arg: any): arg is nameErr {
  if (typeof arg.name === 'string' && typeof arg.error === 'boolean') {
    return true;
  } else {
    return false;
  }
}

if (isNameErr(parsedObj)) {
  // Within this if statement parsedObj is type nameErr;
  parsedObj
}

What is "string[] args" in Main class for?

This is an array of the command line switches pass to the program. E.g. if you start the program with the command "myapp.exe -c -d" then string[] args[] will contain the strings "-c" and "-d".

Write a number with two decimal places SQL Server

This is how the kids are doing it today:

DECLARE @test DECIMAL(18,6) = 123.456789
SELECT FORMAT(@test, '##.##')

123.46

Unsupported operation :not writeable python

file = open('ValidEmails.txt','wb')
file.write(email.encode('utf-8', 'ignore'))

This is solve your encode error also.

Getting Raw XML From SOAPMessage in Java

if you have the client code then you just need to add the following two lines to get the XML request/response. Here _call is org.apache.axis.client.Call

String request = _call.getMessageContext().getRequestMessage().getSOAPPartAsString();
String response = _call.getMessageContext().getResponseMessage().getSOAPPartAsString();

else & elif statements not working in Python

 if guess == number:
     print ("Good")
 elif guess == 2:
     print ("Bad")
 else:
     print ("Also bad")

Make sure you have your identation right. The syntax is ok.