Programs & Examples On #Jlayer

JLayer is a decorator for Java Swing components, often used for for painting over and catching events from subcomponents in the Swing framework.

Java Swing - how to show a panel on top of another panel?

I think LayeredPane is your best bet here. You would need a third panel though to contain A and B. This third panel would be the layeredPane and then panel A and B could still have a nice LayoutManagers. All you would have to do is center B over A and there is quite a lot of examples in the Swing trail on how to do this. Tutorial for positioning without a LayoutManager.

public class Main {
    private JFrame frame = new JFrame();
    private JLayeredPane lpane = new JLayeredPane();
    private JPanel panelBlue = new JPanel();
    private JPanel panelGreen = new JPanel();
    public Main()
    {
        frame.setPreferredSize(new Dimension(600, 400));
        frame.setLayout(new BorderLayout());
        frame.add(lpane, BorderLayout.CENTER);
        lpane.setBounds(0, 0, 600, 400);
        panelBlue.setBackground(Color.BLUE);
        panelBlue.setBounds(0, 0, 600, 400);
        panelBlue.setOpaque(true);
        panelGreen.setBackground(Color.GREEN);
        panelGreen.setBounds(200, 100, 100, 100);
        panelGreen.setOpaque(true);
        lpane.add(panelBlue, new Integer(0), 0);
        lpane.add(panelGreen, new Integer(1), 0);
        frame.pack();
        frame.setVisible(true);
    }


    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new Main();
    }

}

You use setBounds to position the panels inside the layered pane and also to set their sizes.

Edit to reflect changes to original post You will need to add component listeners that detect when the parent container is being resized and then dynamically change the bounds of panel A and B.

WampServer orange icon

After removing the innodb_additional_mem_pool_size=4M from my.ini and killing that process that used the port that Mysql wanted I managed it to go.

Suggested fix: 1) The quick solution: Comment the line innodb_additional_mem_pool_size=4M in the service's 'my.ini' file, 2) exclude the option from the 5.7.4 default config file or 3) un-unknow the variable to mysql ;)

link: http://bugs.mysql.com/bug.php?id=72533

Use number 1, remove the whole line. Save to my.ini. Kill the process if you have one running (look at them with resmon.exe and kill them with command taskkill /pid pid-of-process /f), then start wampmysql and your icon should turn green.

Regards SB

Reordering arrays

With ES6 you can do something like this:

const swapPositions = (array, a ,b) => {
  [array[a], array[b]] = [array[b], array[a]]
}

let array = [1,2,3,4,5];
swapPositions(array,0,1);

/// => [2, 1, 3, 4, 5]

What are Bearer Tokens and token_type in OAuth 2?

Anyone can define "token_type" as an OAuth 2.0 extension, but currently "bearer" token type is the most common one.

https://tools.ietf.org/html/rfc6750

Basically that's what Facebook is using. Their implementation is a bit behind from the latest spec though.

If you want to be more secure than Facebook (or as secure as OAuth 1.0 which has "signature"), you can use "mac" token type.

However, it will be hard way since the mac spec is still changing rapidly.

https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-05

How do I get the domain originating the request in express.js?

Instead of:

var host = req.get('host');
var origin = req.get('origin');

you can also use:

var host = req.headers.host;
var origin = req.headers.origin;

Syntax error near unexpected token 'fi'

Use Notepad ++ and use the option to Convert the file to UNIX format. That should solve this problem.

Save string to the NSUserDefaults?

Here's how to do the same with Swift;

var valueToSave = "someValue"
NSUserDefaults.standardUserDefaults().setObject(valueToSave, forKey: "preferenceName")

To get it back later;

if let savedValue = NSUserDefaults.standardUserDefaults().stringForKey("preferenceName") {
    // Do something with savedValue
}

In Swift 3.0

var valueToSave = "someValue"
UserDefaults.standard.set(valueToSave, forKey: "preferenceName")

if let savedValue = UserDefaults.standard.string(forKey: "preferenceName") {

}

Class Not Found: Empty Test Suite in IntelliJ

Same issue here using IDEA 15.0.6, and nothing helped except when I renamed the package the test class was in. Afterwards I renamed it back to its original name and it still worked, so the rename action might have cleared some cache.

Create Excel file in Java

You can use Apache POI for creating native binary xls files.

Or you can use JExcelApi which is another, and somewhat light-weight as far as I can remember, Java library for Excel.

How to include a sub-view in Blade templates?

As of Laravel 5.6, if you have this kind of structure and you want to include another blade file inside a subfolder,

|--- views

|------- parentFolder (Folder)

|---------- name.blade.php (Blade File)

|---------- childFolder (Folder)

|-------------- mypage.blade.php (Blade File)

name.blade.php

  <html>
      @include('parentFolder.childFolder.mypage')
  </html>

Merge trunk to branch in Subversion

Is there something that prevents you from merging all revisions on trunk since the last merge?

svn merge -rLastRevisionMergedFromTrunkToBranch:HEAD url/of/trunk path/to/branch/wc

should work just fine. At least if you want to merge all changes on trunk to your branch.

"Could not run curl-config: [Errno 2] No such file or directory" when installing pycurl

That solved my problem on Ubuntu 14.04:

apt-get install libcurl4-gnutls-dev

Why doesn't the Scanner class have a nextChar method?

The reason is that the Scanner class is designed for reading in whitespace-separated tokens. It's a convenience class that wraps an underlying input stream. Before scanner all you could do was read in single bytes, and that's a big pain if you want to read words or lines. With Scanner you pass in System.in, and it does a number of read() operations to tokenize the input for you. Reading a single character is a more basic operation. Source

You can use (char) System.in.read();.

How to multiply a BigDecimal by an integer in Java

First off, BigDecimal.multiply() returns a BigDecimal and you're trying to store that in an int.

Second, it takes another BigDecimal as the argument, not an int.

If you just use the BigDecimal for all variables involved in these calculations, it should work fine.

How to convert a 3D point into 2D perspective projection?

All of the answers address the question posed in the title. However, I would like to add a caveat that is implicit in the text. Bézier patches are used to represent the surface, but you cannot just transform the points of the patch and tessellate the patch into polygons, because this will result in distorted geometry. You can, however, tessellate the patch first into polygons using a transformed screen tolerance and then transform the polygons, or you can convert the Bézier patches to rational Bézier patches, then tessellate those using a screen-space tolerance. The former is easier, but the latter is better for a production system.

I suspect that you want the easier way. For this, you would scale the screen tolerance by the norm of the Jacobian of the inverse perspective transformation and use that to determine the amount of tessellation that you need in model space (it might be easier to compute the forward Jacobian, invert that, then take the norm). Note that this norm is position-dependent, and you may want to evaluate this at several locations, depending on the perspective. Also remember that since the projective transformation is rational, you need to apply the quotient rule to compute the derivatives.

How to calculate UILabel height dynamically?

Try this

// UILabel *myLabel;

CGSize labelSize = [myLabel.text sizeWithFont:myLabel.font 
                            constrainedToSize:myLabel.frame.size 
                                lineBreakMode:NSLineBreakByWordWrapping];

CGFloat labelHeight = labelSize.height;


int lines = [myLabel.text sizeWithFont:myLabel.font 
                     constrainedToSize:myLabel.frame.size 
                         lineBreakMode:NSLineBreakByWordWrapping].height/16; 
             // '16' is font size

or

int lines = labelHeight/16;

NSLog(@"lines count : %i \n\n",lines);  

or

int lines = [myLabel.text sizeWithFont:myLabel.font 
                     constrainedToSize:myLabel.frame.size 
                         lineBreakMode:UILineBreakModeWordWrap].height /myLabel.font.pointSize; //fetching font size from font

By Using Categories, Just Create the category class named as

UILabel+UILabelDynamicHeight.h

UILabel+UILabelDynamicHeight.m

No more tension about the height calculation. Please review the below implementation.

Updates for iOS7 & Above,iOS 7 below : Dynamically calculate the UILabel height

#define SYSTEM_VERSION_EQUAL_TO(v)                  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v)              ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v)     ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)
#define iOS7_0 @"7.0"

UILabel+UILabelDynamicHeight.h

#import <UIKit/UIKit.h>
@interface UILabel (UILabelDynamicHeight)

#pragma mark - Calculate the size the Multi line Label
/*====================================================================*/

    /* Calculate the size of the Multi line Label */

/*====================================================================*/
/**
 *  Returns the size of the Label
 *
 *  @param aLabel To be used to calculte the height
 *
 *  @return size of the Label
 */
 -(CGSize)sizeOfMultiLineLabel;

@end

UILabel+UILabelDynamicHeight.m

#import "UILabel+UILabelDynamicHeight.h"
@implementation UILabel (UILabelDynamicHeight)


#pragma mark - Calculate the size,bounds,frame of the Multi line Label
/*====================================================================*/

/* Calculate the size,bounds,frame of the Multi line Label */

/*====================================================================*/
/**
 *  Returns the size of the Label
 *
 *  @param aLabel To be used to calculte the height
 *
 *  @return size of the Label
 */
-(CGSize)sizeOfMultiLineLabel{

    //Label text
    NSString *aLabelTextString = [self text];

    //Label font
    UIFont *aLabelFont = [self font];

    //Width of the Label
    CGFloat aLabelSizeWidth = self.frame.size.width;


    if (SYSTEM_VERSION_LESS_THAN(iOS7_0)) {
        //version < 7.0

        return [aLabelTextString sizeWithFont:aLabelFont
                            constrainedToSize:CGSizeMake(aLabelSizeWidth, MAXFLOAT)
                                lineBreakMode:NSLineBreakByWordWrapping];
    }
    else if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(iOS7_0)) {
        //version >= 7.0

        //Return the calculated size of the Label
        return [aLabelTextString boundingRectWithSize:CGSizeMake(aLabelSizeWidth, MAXFLOAT)
                                              options:NSStringDrawingUsesLineFragmentOrigin
                                           attributes:@{
                                                        NSFontAttributeName : aLabelFont
                                                        }
                                              context:nil].size;

    }

    return [self bounds].size;

}
@end

How can I store JavaScript variable output into a PHP variable?

If this is related to a form submission, use a hidden inputinside the form and change the hidden input value to this variable value. Then you can get that hidden input value in the php page and assign it to your php variable after form submission.

Update:

According to your edit, it seems you don't understand how javascript and php works. Javascript is a client side language, and php is a serverside language. Therefore you cannot execute javascript logic and use that variable value to a php variable when you execute relevant page in the server. You can run the relevant javascript logic after client browser process the web page returned from the web server (which has already executed the php code for the relevant page). After the execution of the javascript code and after assigning the relevant value to the relevant javascript variable, you can use form submission or ajax to send that javascript variable value to use by another php page (or a request to process and get the same php page).

What is the "proper" way to cast Hibernate Query.list() to List<Type>?

List<Person> list = new ArrayList<Person>();
Criteria criteria = this.getSessionFactory().getCurrentSession().createCriteria(Person.class);
for (final Object o : criteria.list()) {
    list.add((Person) o);
}

Multiple Indexes vs Multi-Column Indexes

One item that seems to have been missed is star transformations. Index Intersection operators resolve the predicate by calculating the set of rows hit by each of the predicates before any I/O is done on the fact table. On a star schema you would index each individual dimension key and the query optimiser can resolve which rows to select by the index intersection computation. The indexes on individual columns give the best flexibility for this.

Scroll event listener javascript

I was looking a lot to find a solution for sticy menue with old school JS (without JQuery). So I build small test to play with it. I think it can be helpfull to those looking for solution in js. It needs improvments of unsticking the menue back, and making it more smooth. Also I find a nice solution with JQuery that clones the original div instead of position fixed, its better since the rest of page element dont need to be replaced after fixing. Anyone know how to that with JS ? Please remark, correct and improve.

<!DOCTYPE html>
<html>

<head>
<script>

// addEvent function by John Resig:
// http://ejohn.org/projects/flexible-javascript-events/

function addEvent( obj, type, fn ) {

    if ( obj.attachEvent ) {

        obj['e'+type+fn] = fn;
        obj[type+fn] = function(){obj['e'+type+fn]( window.event );};
        obj.attachEvent( 'on'+type, obj[type+fn] );
    } else {
        obj.addEventListener( type, fn, false );
    }
}
function getScrollY() {
    var  scrOfY = 0;
    if( typeof( window.pageYOffset ) == 'number' ) {
        //Netscape compliant
        scrOfY = window.pageYOffset;

    } else if( document.body && document.body.scrollTop )  {
        //DOM compliant
        scrOfY = document.body.scrollTop;
    } 
    return scrOfY;
}
</script>
<style>
#mydiv {
    height:100px;
    width:100%;
}
#fdiv {
    height:100px;
    width:100%;
}
</style>
</head>

<body>

<!-- HTML for example event goes here -->

<div id="fdiv" style="background-color:red;position:fix">
</div>
<div id="mydiv" style="background-color:yellow">
</div>
<div id="fdiv" style="background-color:green">
</div>

<script>

// Script for example event goes here

addEvent(window, 'scroll', function(event) {

    var x = document.getElementById("mydiv");

    var y = getScrollY();      
    if (y >= 100) {
        x.style.position = "fixed"; 
        x.style.top= "0";
    } 
});

</script>
</body>
</html>

What are pipe and tap methods in Angular tutorial?

You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:

  /**
   * Used to stitch together functional operators into a chain.
   * @method pipe
   * @return {Observable} the Observable result of all of the operators having
   * been called in the order they were passed in.
   *
   * @example
   *
   * import { map, filter, scan } from 'rxjs/operators';
   *
   * Rx.Observable.interval(1000)
   *   .pipe(
   *     filter(x => x % 2 === 0),
   *     map(x => x + x),
   *     scan((acc, x) => acc + x)
   *   )
   *   .subscribe(x => console.log(x))
   */

In brief:

Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan(), but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe() to make a chain of those operators (see example above).

Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do(). You can think of it as if observable was an array over time, then tap() would be an equivalent to Array.forEach().

No found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:

Look at the exception:

No qualifying bean of type [edu.java.spring.ws.dao.UserDao] found for dependency

This means that there's no bean available to fulfill that dependency. Yes, you have an implementation of the interface, but you haven't created a bean for that implementation. You have two options:

  • Annotate UserDaoImpl with @Component or @Repository, and let the component scan do the work for you, exactly as you have done with UserService.
  • Add the bean manually to your xml file, the same you have done with UserBoImpl.

Remember that if you create the bean explicitly you need to put the definition before the component scan. In this case the order is important.

CR LF notepad++ removal

View -> Show Symbol -> uncheck Show All characters

How do you automatically resize columns in a DataGridView control AND allow the user to resize the columns on that same grid?

A simple two lines of code works for me.

dataGridView.DataSource = dataTable;
dataGridView.AutoResizeColumns();

How to use doxygen to create UML class diagrams from C++ source

Quote from this post (it's written by the author of doxygen himself) :

run doxygen -g and change the following options of the generated Doxyfile:

    EXTRACT_ALL            = YES
    HAVE_DOT               = YES
    UML_LOOK               = YES

run doxygen again

How do I clear a C++ array?

Hey i think The fastest way to handle that kind of operation is to memset() the memory.

Example-

memset(&myPage.pageArray[0][0], 0, sizeof(myPage.pageArray));

A similar C++ way would be to use std::fill

char *begin = myPage.pageArray[0][0];
char *end = begin + sizeof(myPage.pageArray);
std::fill(begin, end, 0);

How to define a connection string to a SQL Server 2008 database?

You need to specify how you'll authenticate with the database. If you want to use integrated security (this means using Windows authentication using your local or domain Windows account), add this to the connection string:

Integrated Security = True;

If you want to use SQL Server authentication (meaning you specify a login and password rather than using a Windows account), add this:

User ID = "username"; Password = "password";

Interpreting segfault messages

Let's go to the source -- 2.6.32, for example. The message is printed by show_signal_msg() function in arch/x86/mm/fault.c if the show_unhandled_signals sysctl is set.

"error" is not an errno nor a signal number, it's a "page fault error code" -- see definition of enum x86_pf_error_code.

"[7fa44d2f8000+f6f000]" is starting address and size of virtual memory area where offending object was mapped at the time of crash. Value of "ip" should fit in this region. With this info in hand, it should be easy to find offending code in gdb.

Converting serial port data to TCP/IP in a Linux environment

Open a port in your server with netcat and start listening:

nc -lvp port number

And on the machine you are reading the serial port, send it with netcat as root:

nc <IP address> portnumber < /dev/ttyACM0

If you want to store the data on the server you can redirect the data to a text file.

First create a file where you are saving the data:

touch data.txt

And then start saving data

nc -lvp port number > data.txt

How to set environment variable or system property in spring tests?

The right way to do this, starting with Spring 4.1, is to use a @TestPropertySource annotation.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:whereever/context.xml")
@TestPropertySource(properties = {"myproperty = foo"})
public class TestWarSpringContext {
    ...    
}

See @TestPropertySource in the Spring docs and Javadocs.

TypeLoadException says 'no implementation', but it is implemented

Another possibility is a mixture of release and debug builds in the dependencies. For example, Assembly A depends on Assembly B, A was built in Debug mode while the copy of B in GAC was built in Release mode, or vice versa.

best practice to generate random token for forgot password

This may be helpful whenever you need a very very random token

<?php
   echo mb_strtoupper(strval(bin2hex(openssl_random_pseudo_bytes(16))));
?>

Android Overriding onBackPressed()

Just call the onBackPressed() method in the activity you want to show the dialog and inside it show your dialog.

Apache is not running from XAMPP Control Panel ( Error: Apache shutdown unexpectedly. This may be due to a blocked port)

Go in xampp/apache/conf/httpd.conf and open it. Then just chang 2 lines

Listen 80
to
Listen 81

And

ServerName localhost:80
to
ServerName localhost:81

Then start using admin privileges.

As I am working in a corporate environment where developers faces firewall issues, none of the other answers resolved my issue.

As the port is not used by Skype, but by some other internal applications, I followed the below steps to resolve the issue:

Step 1 - From the XAMPP Control Panel, under Apache, click the Config button, and select the Apache (httpd.conf).

Inside the httpd.conf file, somehow I found a line that says:

Listen 80 And change the 80 into any number / port you want. In my scenario I’m using port 8080.

Listen 8080 Still from the httpd.conf file,

You should also do this in the same process Still from the httpd-ssl.conf file, find another line that says

ServerName localhost:443 And change 443 to 4433.

ServerName localhost:4433 Remember to save the httpd.conf and httpd-ssl.conf files after performing some changes. Then restart the Apache service.

jQuery limit to 2 decimal places

Here is a working example in both Javascript and jQuery:

http://jsfiddle.net/GuLYN/312/

//In jQuery
$("#calculate").click(function() {
    var num = parseFloat($("#textbox").val());
    var new_num = $("#textbox").val(num.toFixed(2));
});


// In javascript
document.getElementById('calculate').onclick = function() {
    var num = parseFloat(document.getElementById('textbox').value);
    var new_num = num.toFixed(2);
    document.getElementById('textbox').value = new_num;
};
?

AngularJS is rendering <br> as text not as a newline

I've used like this

function chatSearchCtrl($scope, $http,$sce) {
 // some more my code

// take this 
data['message'] = $sce.trustAsHtml(data['message']);

$scope.searchresults = data;

and in html I did

<p class="clsPyType clsChatBoxPadding" ng-bind-html="searchresults.message"></p>

thats it I get my <br/> tag rendered

Using SSIS BIDS with Visual Studio 2012 / 2013

Welcome to Microsoft Marketing Speak hell. With the 2012 release of SQL Server, the BIDS, Business Intelligence Designer Studio, plugin for Visual Studio was renamed to SSDT, SQL Server Data Tools. SSDT is available for 2010 and 2012. The problem is, there are two different products called SSDT.

There is SSDT which replaces the database designer thing which was called Data Dude in VS 2008 and in 2010 became database projects. That a free install and if you snag the web installer, that's what you get when you install SSDT. It puts the correct project templates and such into Visual Studio.

There's also the SSDT which is the "BIDS" replacement for developing SSIS, SSRS and SSAS stuff. As of March 2013, it is now available for the 2012 release of Visual Studio. The download is labeled SSDTBI_VS2012_X86.msi Perhaps that's a signal on how the product is going to be referred to in marketing materials. Download links are

None the less, we have Business Intelligence projects available to us in Visual Studio 2012. And the people did rejoice and did feast upon the lambs and toads and tree-sloths and fruit-bats and orangutans and breakfast cereals

enter image description here

Changing plot scale by a factor in matplotlib

As you have noticed, xscale and yscale does not support a simple linear re-scaling (unfortunately). As an alternative to Hooked's answer, instead of messing with the data, you can trick the labels like so:

ticks = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x*scale))
ax.xaxis.set_major_formatter(ticks)

A complete example showing both x and y scaling:

import numpy as np
import pylab as plt
import matplotlib.ticker as ticker

# Generate data
x = np.linspace(0, 1e-9)
y = 1e3*np.sin(2*np.pi*x/1e-9) # one period, 1k amplitude

# setup figures
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
# plot two identical plots
ax1.plot(x, y)
ax2.plot(x, y)

# Change only ax2
scale_x = 1e-9
scale_y = 1e3
ticks_x = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_x))
ax2.xaxis.set_major_formatter(ticks_x)

ticks_y = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_y))
ax2.yaxis.set_major_formatter(ticks_y)

ax1.set_xlabel("meters")
ax1.set_ylabel('volt')
ax2.set_xlabel("nanometers")
ax2.set_ylabel('kilovolt')

plt.show() 

And finally I have the credits for a picture:

Left: ax1 no scaling, right: ax2 y axis scaled to kilo and x axis scaled to nano

Note that, if you have text.usetex: true as I have, you may want to enclose the labels in $, like so: '${0:g}$'.

How to set the Android progressbar's height?

Use this

style="@android:style/Widget.ProgressBar.Horizontal"

Failed to load resource under Chrome

There is a temporary work around in Reenable (temporary) showModalDialog support in Chrome (for Windows) 37+.

Basically, create a new string in the registry at

HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\EnableDeprecatedWebPlatformFeatures

Under the EnableDeprecatedWebPlatformFeatures key, create a string value with the name 1 and a value of ShowModalDialog_EffectiveUntil20150430. To verify that the policy is enabled, visit chrome://policy URL.

How to create a custom navigation drawer in android

You can easily customize the android Navigation drawer once you know how its implemented. here is a nice tutorial where you can set it up.

This will be the structure of your mainXML:

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- Framelayout to display Fragments -->
    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <!-- Listview to display slider menu -->
    <ListView
        android:id="@+id/list_slidermenu"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="right"
        android:choiceMode="singleChoice"
        android:divider="@color/list_divider"
        android:dividerHeight="1dp"        
        android:listSelector="@drawable/list_selector"
        android:background="@color/list_background"/>
</android.support.v4.widget.DrawerLayout>

You can customize this listview to your liking by adding the header. And radiobuttons.

When to use the !important property in CSS

This is the real life scenario

Imagine this scenario

  1. You have a global CSS file that sets visual aspects of your site globally.
  2. You (or others) use inline styles on elements themselves which is usually very bad practice.

In this case you could set certain styles in your global CSS file as important, thus overriding inline styles set directly on elements.

Actual real world example?

This kind of scenario usually happens when you don't have total control over your HTML. Think of solutions in SharePoint for instance. You'd like your part to be globally defined (styled), but some inline styles you can't control are present. !important makes such situations easier to deal with.

Other real life scenarios would also include some badly written jQuery plugins that also use inline styles...

I suppose you got the idea by now and can come up with some others as well.

When do you decide to use !important?

I suggest you don't use !important unless you can't do it any other way. Whenever it's possible to avoid it, avoid it. Using lots of !important styles will make maintenance a bit harder, because you break the natural cascading in your stylesheets.

How to get correlation of two vectors in python

The docs indicate that numpy.correlate is not what you are looking for:

numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
  Cross-correlation of two 1-dimensional sequences.
  This function computes the correlation as generally defined in signal processing texts:
     z[k] = sum_n a[n] * conj(v[n+k])
  with a and v sequences being zero-padded where necessary and conj being the conjugate.

Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:

from scipy.stats.stats import pearsonr   
a = [1,4,6]
b = [1,2,3]   
print pearsonr(a,b)

This gives

(0.99339926779878274, 0.073186395040328034)

You can also use numpy.corrcoef:

import numpy
print numpy.corrcoef(a,b)

This gives:

[[ 1.          0.99339927]
 [ 0.99339927  1.        ]]

How to get the width and height of an android.widget.ImageView?

I could get image width and height by its drawable;

int width = imgView.getDrawable().getIntrinsicWidth();
int height = imgView.getDrawable().getIntrinsicHeight();

Search for an item in a Lua list

Use the following representation instead:

local items = { apple=true, orange=true, pear=true, banana=true }
if items.apple then
    ...
end

What is the maximum number of edges in a directed graph with n nodes?

Can also be thought of as the number of ways of choosing pairs of nodes n choose 2 = n(n-1)/2. True if only any pair can have only one edge. Multiply by 2 otherwise

Batch file to split .csv file

If splitting very large files, the solution I found is an adaptation from this, with PowerShell "embedded" in a batch file. This works fast, as opposed to many other things I tried (I wouldn't know about other options posted here).

The way to use mysplit.bat below is

mysplit.bat <mysize> 'myfile'

Note: The script was intended to use the first argument as the split size. It is currently hardcoded at 100Mb. It should not be difficult to fix this.

Note 2: The filname should be enclosed in single quotes. Other alternatives for quoting apparently do not work.

Note 3: It splits the file at given number of bytes, not at given number of lines. For me this was good enough. Some lines of code could be probably added to complete each chunk read, up to the next CR/LF. This will split in full lines (not with a constant number of them), with no sacrifice in processing time.

Script mysplit.bat:

@REM Using https://stackoverflow.com/questions/19335004/how-to-run-a-powershell-script-from-a-batch-file
@REM and https://stackoverflow.com/questions/1001776/how-can-i-split-a-text-file-using-powershell
@PowerShell  ^
    $upperBound = 100MB;  ^
    $rootName = %2;  ^
    $from = $rootName;  ^
    $fromFile = [io.file]::OpenRead($from);  ^
    $buff = new-object byte[] $upperBound;  ^
    $count = $idx = 0;  ^
    try {  ^
        do {  ^
            'Reading ' + $upperBound;  ^
            $count = $fromFile.Read($buff, 0, $buff.Length);  ^
            if ($count -gt 0) {  ^
                $to = '{0}.{1}' -f ($rootName, $idx);  ^
                $toFile = [io.file]::OpenWrite($to);  ^
                try {  ^
                    'Writing ' + $count + ' to ' + $to;  ^
                    $tofile.Write($buff, 0, $count);  ^
                } finally {  ^
                    $tofile.Close();  ^
                }  ^
            }  ^
            $idx ++;  ^
        } while ($count -gt 0);  ^
    }  ^
    finally {  ^
        $fromFile.Close();  ^
    }  ^
%End PowerShell%

Reading JSON from a file?

Here is a copy of code which works fine for me

import json

with open("test.json") as json_file:
    json_data = json.load(json_file)
    print(json_data)

with the data

{
    "a": [1,3,"asdf",true],
    "b": {
        "Hello": "world"
    }
}

you may want to wrap your json.load line with a try catch because invalid JSON will cause a stacktrace error message.

syntax error when using command line in python

Come out of the "python interpreter."

  1. Check out your PATH variable c:\python27
  2. cd and your file location. 3.Now type Python yourfilename.py.

I hope this should work

Executing Javascript code "on the spot" in Chrome?

You can use bookmarklets if you want run bigger scripts in more convenient way and run them automatically by one click.

jquery.ajax Access-Control-Allow-Origin

http://encosia.com/using-cors-to-access-asp-net-services-across-domains/

refer the above link for more details on Cross domain resource sharing.

you can try using JSONP . If the API is not supporting jsonp, you have to create a service which acts as a middleman between the API and your client. In my case, i have created a asmx service.

sample below:

ajax call:

$(document).ready(function () {
        $.ajax({
            crossDomain: true,
            type:"GET",
            contentType: "application/json; charset=utf-8",
            async:false,
            url: "<your middle man service url here>/GetQuote?callback=?",
            data: { symbol: 'ctsh' },
            dataType: "jsonp",                
            jsonpCallback: 'fnsuccesscallback'
        });
    });

service (asmx) which will return jsonp:

[WebMethod]
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public void GetQuote(String symbol,string callback)
    {          

        WebProxy myProxy = new WebProxy("<proxy url here>", true);

        myProxy.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
        StockQuoteProxy.StockQuote SQ = new StockQuoteProxy.StockQuote();
        SQ.Proxy = myProxy;
        String result = SQ.GetQuote(symbol);
        StringBuilder sb = new StringBuilder();
        JavaScriptSerializer js = new JavaScriptSerializer();
        sb.Append(callback + "(");
        sb.Append(js.Serialize(result));
        sb.Append(");");
        Context.Response.Clear();
        Context.Response.ContentType = "application/json";
        Context.Response.Write(sb.ToString());
        Context.Response.End();         
    }

Is there a way to access the "previous row" value in a SELECT statement?

SQL has no built in notion of order, so you need to order by some column for this to be meaningful. Something like this:

select t1.value - t2.value from table t1, table t2 
where t1.primaryKey = t2.primaryKey - 1

If you know how to order things but not how to get the previous value given the current one (EG, you want to order alphabetically) then I don't know of a way to do that in standard SQL, but most SQL implementations will have extensions to do it.

Here is a way for SQL server that works if you can order rows such that each one is distinct:

select  rank() OVER (ORDER BY id) as 'Rank', value into temp1 from t

select t1.value - t2.value from temp1 t1, temp1 t2 
where t1.Rank = t2.Rank - 1

drop table temp1

If you need to break ties, you can add as many columns as necessary to the ORDER BY.

Problem in running .net framework 4.0 website on iis 7.0

Depending on the type of application, another thing to check is under the Advanced Settings for the Application Pool make sure "Enable 32-Bit Applications" is set to True.

I'd checked everything in this thread when I had this issue but all had already been setup correctly, I found this was the problem for me.

How to get full REST request body using Jersey?

It does seem you would have to use a MessageBodyReader here. Here's an example, using jdom:

import org.jdom.Document;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
import javax.ws.rs.ext.MediaType;
import javax.ws.rs.ext.MultivaluedMap;
import java.lang.reflect.Type;
import java.lang.annotation.Annotation;
import java.io.InputStream;

@Provider // this annotation is necessary!
@ConsumeMime("application/xml") // this is a hint to the system to only consume xml mime types
public class XMLMessageBodyReader implements MessageBodyReader<Document> {
  private SAXBuilder builder = new SAXBuilder();

  public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) {
    // check if we're requesting a jdom Document
    return Document.class.isAssignableFrom(type);
  }

  public Document readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) {
    try {
      return builder.build(entityStream);
    }
    catch (Exception e) {
      // handle error somehow
    }
  } 
}

Add this class to the list of resources your jersey deployment will process (usually configured via web.xml, I think). You can then use this reader in one of your regular resource classes like this:

@Path("/somepath") @POST
public void handleXMLData(Document doc) {
  // do something with the document
}

I haven't verified that this works exactly as typed, but that's the gist of it. More reading here:

How to send an email with Python?

Make sure you have granted permission for both Sender and Receiver to send email and receive email from Unknown sources(External Sources) in Email Account.

import smtplib

#Ports 465 and 587 are intended for email client to email server communication - sending email
server = smtplib.SMTP('smtp.gmail.com', 587)

#starttls() is a way to take an existing insecure connection and upgrade it to a secure connection using SSL/TLS.
server.starttls()

#Next, log in to the server
server.login("#email", "#password")

msg = "Hello! This Message was sent by the help of Python"

#Send the mail
server.sendmail("#Sender", "#Reciever", msg)

enter image description here

How to create a self-signed certificate with OpenSSL

I can't comment, so I will put this as a separate answer. I found a few issues with the accepted one-liner answer:

  • The one-liner includes a passphrase in the key.
  • The one-liner uses SHA-1 which in many browsers throws warnings in console.

Here is a simplified version that removes the passphrase, ups the security to suppress warnings and includes a suggestion in comments to pass in -subj to remove the full question list:

openssl genrsa -out server.key 2048
openssl rsa -in server.key -out server.key
openssl req -sha256 -new -key server.key -out server.csr -subj '/CN=localhost'
openssl x509 -req -sha256 -days 365 -in server.csr -signkey server.key -out server.crt

Replace 'localhost' with whatever domain you require. You will need to run the first two commands one by one as OpenSSL will prompt for a passphrase.

To combine the two into a .pem file:

cat server.crt server.key > cert.pem

System.Threading.Timer in C# it seems to be not working. It runs very fast every 3 second

Is using System.Threading.Timer mandatory?

If not, System.Timers.Timer has handy Start() and Stop() methods (and an AutoReset property you can set to false, so that the Stop() is not needed and you simply call Start() after executing).

Shrink a YouTube video to responsive width

Okay, looks like big solutions.

Why not to add width: 100%; directly in your iframe. ;)

So your code would looks something like <iframe style="width: 100%;" ...></iframe>

Try this it'll work as it worked in my case.

Enjoy! :)

Can't access Eclipse marketplace

in my case: i got a new pc and I had to download and install a brand new eclipse. by default the proxy was set to native. I was getting that error at first. I then changed it to active. And still it didn't work. And then i put it back to "native" and it worked.

How to stop "setInterval"

Store the return of setInterval in a variable, and use it later to clear the interval.

var timer = null;
$("textarea").blur(function(){
    timer = window.setInterval(function(){ ... whatever ... }, 2000);
}).focus(function(){
    if(timer){
       window.clearInterval(timer);
       timer = null
    }
});

How do you get/set media volume (not ringtone volume) in Android?

private AudioManager audio;

Inside onCreate:

audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

Override onKeyDown:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    switch (keyCode) {
    case KeyEvent.KEYCODE_VOLUME_UP:
        audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
                AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
        return true;
    case KeyEvent.KEYCODE_VOLUME_DOWN:
        audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
                AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
        return true;
    default:
        return false;
    }
}

How to remove item from a python list in a loop?

x = [i for i in x if len(i)==2]

Copy output of a JavaScript variable to the clipboard

For general purposes of copying any text to the clipboard, I wrote the following function:

function textToClipboard (text) {
    var dummy = document.createElement("textarea");
    document.body.appendChild(dummy);
    dummy.value = text;
    dummy.select();
    document.execCommand("copy");
    document.body.removeChild(dummy);
}

The value of the parameter is inserted into value of a newly created <textarea>, which is then selected, its value is copied to the clipboard and then it gets removed from the document.

Best way to Bulk Insert from a C# DataTable

Here's how I do it using a DataTable. This is a working piece of TEST code.

using (SqlConnection con = new SqlConnection(connStr))
{
    con.Open();

    // Create a table with some rows. 
    DataTable table = MakeTable();

    // Get a reference to a single row in the table. 
    DataRow[] rowArray = table.Select();

    using (SqlBulkCopy bulkCopy = new SqlBulkCopy(con))
    {
        bulkCopy.DestinationTableName = "dbo.CarlosBulkTestTable";

        try
        {
            // Write the array of rows to the destination.
            bulkCopy.WriteToServer(rowArray);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

    }

}//using

How do I remove duplicates from a C# array?

This might depend on how much you want to engineer the solution - if the array is never going to be that big and you don't care about sorting the list you might want to try something similar to the following:

    public string[] RemoveDuplicates(string[] myList) {
        System.Collections.ArrayList newList = new System.Collections.ArrayList();

        foreach (string str in myList)
            if (!newList.Contains(str))
                newList.Add(str);
        return (string[])newList.ToArray(typeof(string));
    }

Parse JSON in C#

I tried to use the code above but didn't work. The JSON structure returned by Google is so different and there is a very important miss in the helper function: a call to DataContractJsonSerializer.ReadObject() that actually deserializes the JSON data into the object.

Here is the code that WORKS in 2011:

using System;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
using System.Collections.Generic;

namespace <YOUR_NAMESPACE>
{
    public class JSONHelper
    {
        public static T Deserialise<T>(string json)
        {
            T obj = Activator.CreateInstance<T>();
            MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
            DataContractJsonSerializer serialiser = new DataContractJsonSerializer(obj.GetType());
            obj = (T)serialiser.ReadObject(ms);
            ms.Close();
            return obj;
        }
    }

    public class Result
    {
        public string GsearchResultClass { get; set; }
        public string unescapedUrl { get; set; }
        public string url { get; set; }
        public string visibleUrl { get; set; }
        public string cacheUrl { get; set; }
        public string title { get; set; }
        public string titleNoFormatting { get; set; }
        public string content { get; set; }
    }

    public class Page
    {
        public string start { get; set; }
        public int label { get; set; }
    }

    public class Cursor
    {
        public string resultCount { get; set; }
        public Page[] pages { get; set; }
        public string estimatedResultCount { get; set; }
        public int currentPageIndex { get; set; }
        public string moreResultsUrl { get; set; }
        public string searchResultTime { get; set; }
    }

    public class ResponseData
    {
        public Result[] results { get; set; }
        public Cursor cursor { get; set; }
    }

    public class GoogleSearchResults
    {
        public ResponseData responseData { get; set; }
        public object responseDetails { get; set; }
        public int responseStatus { get; set; }
    }
}

To get the content of the first result, do:

GoogleSearchResults googleResults = new GoogleSearchResults();
googleResults = JSONHelper.Deserialise<GoogleSearchResults>(jsonData);
string contentOfFirstResult = googleResults.responseData.results[0].content;

How can I run PowerShell with the .NET 4 runtime?

If you're still stuck on PowerShell v1.0 or v2.0, here is my variation on Jason Stangroome's excellent answer.

Create a powershell4.cmd somewhere on your path with the following contents:

@echo off
:: http://stackoverflow.com/questions/7308586/using-batch-echo-with-special-characters
if exist %~dp0powershell.exe.activation_config goto :run
echo.^<?xml version="1.0" encoding="utf-8" ?^>                 > %~dp0powershell.exe.activation_config
echo.^<configuration^>                                        >> %~dp0powershell.exe.activation_config
echo.  ^<startup useLegacyV2RuntimeActivationPolicy="true"^>  >> %~dp0powershell.exe.activation_config
echo.    ^<supportedRuntime version="v4.0"/^>                 >> %~dp0powershell.exe.activation_config
echo.  ^</startup^>                                           >> %~dp0powershell.exe.activation_config
echo.^</configuration^>                                       >> %~dp0powershell.exe.activation_config
:run
:: point COMPLUS_ApplicationMigrationRuntimeActivationConfigPath to the directory that this cmd file lives in
:: and the directory contains a powershell.exe.activation_config file which matches the executable name powershell.exe
set COMPLUS_ApplicationMigrationRuntimeActivationConfigPath=%~dp0
%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe %*
set COMPLUS_ApplicationMigrationRuntimeActivationConfigPath=

This will allow you to launch an instance of the powershell console running under .NET 4.0.

You can see the difference on my system where I have PowerShell 2.0 by examining the output of the following two commands run from cmd.

C:\>powershell -ExecutionPolicy ByPass -Command $PSVersionTable

Name                           Value
----                           -----
CLRVersion                     2.0.50727.5485
BuildVersion                   6.1.7601.17514
PSVersion                      2.0
WSManStackVersion              2.0
PSCompatibleVersions           {1.0, 2.0}
SerializationVersion           1.1.0.1
PSRemotingProtocolVersion      2.1


C:\>powershell4.cmd -ExecutionPolicy ByPass -Command $PSVersionTable

Name                           Value
----                           -----
PSVersion                      2.0
PSCompatibleVersions           {1.0, 2.0}
BuildVersion                   6.1.7601.17514
CLRVersion                     4.0.30319.18408
WSManStackVersion              2.0
PSRemotingProtocolVersion      2.1
SerializationVersion           1.1.0.1

Is there a way to run Bash scripts on Windows?

Install Cygwin, which includes Bash among many other GNU and Unix utilities (without whom its unlikely that bash will be very useful anyway).

Another option is MinGW's MSYS which includes bash and a smaller set of the more important utilities such as awk. Personally I would have preferred Cygwin because it includes such heavy lifting tools as Perl and Python which I find I cannot live without, while MSYS skimps on these and assumes you are going to install them yourself.

Updated: If anyone is interested in this answer and is running MS-Windows 10, please note that MS-Windows 10 has a "Windows Subsystem For Linux" feature which - once enabled - allows you to install a user-mode image of Ubuntu and then run Bash on that. This provides 100% compatibility with Ubuntu for debugging and running Bash scripts, but this setup is completely standalone from Windows and you cannot use Bash scripts to interact with Windows features (such as processes and APIs) except for limited access to files through the DrvFS feature.

How to handle Pop-up in Selenium WebDriver using Java

Do not make the situation complex. Use ID if they are available.

driver.get("http://www.rediff.com");
WebElement sign = driver.findElement(By.linkText("Sign in"));
sign.click();
WebElement email_id= driver.findElement(By.id("c_uname"));
email_id.sendKeys("hi");

How to debug an apache virtual host configuration?

If you are trying to debug your virtual host configuration, you may find the Apache -S command line switch useful. That is, type the following command:

httpd -S

This command will dump out a description of how Apache parsed the configuration file. Careful examination of the IP addresses and server names may help uncover configuration mistakes. (See the docs for the httpd program for other command line options).

How to open Atom editor from command line in OS X?

I am on mingw bash, so I have created ~.profile file with following: alias atom='~/AppData/Local/atom/bin/atom'

checking if number entered is a digit in jquery

Value validation wouldn't be a responsibility of jQuery. You can use pure JavaScript for this. Two ways that come to my mind are:

/^\d+$/.match(value)
Number(value) == value

Select where count of one field is greater than one

It should also be mentioned that the "pk" should be a key field. The self-join

SELECT t1.* FROM db.table t1
JOIN db.table t2 ON t1.someField = t2.someField AND t1.pk != t2.pk 

by Bill Karwin give you all the records that are duplicates which is what I wanted. Because some have more than two, you can get the same record more than once. I wrote all to another table with the same fields to get rid of the same records by key fields suppression. I tried

SELECT * FROM db.table HAVING COUNT(someField) > 1

above first. The data returned from it give only one of the duplicates, less than 1/2 of what this gives you but the count is good if that is all you want.

Cannot execute RUN mkdir in a Dockerfile

The problem is that /var/www doesn't exist either, and mkdir isn't recursive by default -- it expects the immediate parent directory to exist.

Use:

mkdir -p /var/www/app

...or install a package that creates a /var/www prior to reaching this point in your Dockerfile.

How do I find the MySQL my.cnf location

If you're on a Mac with Homebrew, use

brew info mysql

You'll see something like

$ brew info mysql
mysql: stable 5.6.13 (bottled)
http://dev.mysql.com/doc/refman/5.6/en/
Conflicts with: mariadb, mysql-cluster, percona-server
/usr/local/Cellar/mysql/5.6.13 (9381 files, 354M) *

That last line is the INSTALLERDIR per the MySQL docs

How do I get the path and name of the file that is currently executing?

I think it's just __file__ Sounds like you may also want to checkout the inspect module.

How do you get assembler output from C/C++ source in gcc?

From: http://www.delorie.com/djgpp/v2faq/faq8_20.html

gcc -c -g -Wa,-a,-ad [other GCC options] foo.c > foo.lst

in alternative to PhirePhly's answer Or just use -S as everyone said.

Proper way to concatenate variable strings

Since strings are lists of characters in Python, we can concatenate strings the same way we concatenate lists (with the + sign):

{{ var1 + '-' + var2 + '-' + var3 }}

If you want to pipe the resulting string to some filter, make sure you enclose the bits in parentheses:

e.g. To concatenate our 3 vars, and get a sha512 hash:

{{ (var1 + var2 + var3) | hash('sha512') }}

Note: this works on Ansible 2.3. I haven't tested it on earlier versions.

WordPress path url in js script file

For users working with the Genesis framework.

Add the following to your child theme functions.php

add_action( 'genesis_before', 'script_urls' );

function script_urls() {
?>
    <script type="text/javascript">
     var stylesheetDir = '<?= get_bloginfo("stylesheet_directory"); ?>';
    </script>
<?php
}

And use that variable to set the relative url in your script. For example:

Reset.style.background = " url('"+stylesheetDir+"/images/searchfield_clear.png') ";

numpy: most efficient frequency counts for unique values in an array

from collections import Counter
x = array( [1,1,1,2,2,2,5,25,1,1] )
mode = counter.most_common(1)[0][0]

Remove end of line characters from Java string

Given a String str:

str = str.replaceAll("\\\\r","")
str = str.replaceAll("\\\\n","")

When should the xlsm or xlsb formats be used?

They're all similar in that they're essentially zip files containing the actual file components. You can see the contents just by replacing the extension with .zip and opening them up. The difference with xlsb seems to be that the components are not XML-based but are in a binary format: supposedly this is beneficial when working with large files.

https://blogs.msdn.microsoft.com/dmahugh/2006/08/22/new-binary-file-format-for-spreadsheets/

Add to integers in a list

If you try appending the number like, say listName.append(4) , this will append 4 at last. But if you are trying to take <int> and then append it as, num = 4 followed by listName.append(num), this will give you an error as 'num' is of <int> type and listName is of type <list>. So do type cast int(num) before appending it.

How can I uninstall Ruby on ubuntu?

Run the following command from your terminal:

sudo apt-get purge ruby

Usually works well for me.

iOS Safari – How to disable overscroll but allow scrollable divs to scroll normally?

This solves the issue when you scroll past the beginning or end of the div

var selScrollable = '.scrollable';
// Uses document because document will be topmost level in bubbling
$(document).on('touchmove',function(e){
  e.preventDefault();
});
// Uses body because jQuery on events are called off of the element they are
// added to, so bubbling would not work if we used document instead.
$('body').on('touchstart', selScrollable, function(e) {
  if (e.currentTarget.scrollTop === 0) {
    e.currentTarget.scrollTop = 1;
  } else if (e.currentTarget.scrollHeight === e.currentTarget.scrollTop + e.currentTarget.offsetHeight) {
    e.currentTarget.scrollTop -= 1;
  }
});
// Stops preventDefault from being called on document if it sees a scrollable div
$('body').on('touchmove', selScrollable, function(e) {
  e.stopPropagation();
});

Note that this won't work if you want to block whole page scrolling when a div does not have overflow. To block that, use the following event handler instead of the one immediately above (adapted from this question):

$('body').on('touchmove', selScrollable, function(e) {
    // Only block default if internal div contents are large enough to scroll
    // Warning: scrollHeight support is not universal. (https://stackoverflow.com/a/15033226/40352)
    if($(this)[0].scrollHeight > $(this).innerHeight()) {
        e.stopPropagation();
    }
});

how to align img inside the div to the right?

<style type="text/css">
>> .imgTop {
>>  display: block;
>>  text-align: right;
>>  }
>> </style>

<img class="imgTop" src="imgName.gif" alt="image description" height="100" width="100">

How to get the changes on a branch in Git

git log --cherry-mark --oneline from_branch...to_branch

(3dots) but sometimes it shows '+' instead of '='

How can I remove all text after a character in bash?

An example might have been useful, but if I understood you correctly, this would work:

echo "Hello: world" | cut -f1 -d":"

This will convert Hello: world into Hello.

Removing all empty elements from a hash / YAML?

class Hash   
  def compact
    def _empty?(val)
      case val
      when Hash     then val.compact.empty?
      when Array    then val.all? { |v| _empty?(v) }
      when String   then val.empty?
      when NilClass then true
      # ... custom checking 
      end
    end

    delete_if { |_key, val| _empty?(val) }   
  end 
end

How do I output an ISO 8601 formatted string in JavaScript?

See the last example on page https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference:Global_Objects:Date:

/* Use a function for the exact format desired... */
function ISODateString(d) {
    function pad(n) {return n<10 ? '0'+n : n}
    return d.getUTCFullYear()+'-'
         + pad(d.getUTCMonth()+1)+'-'
         + pad(d.getUTCDate())+'T'
         + pad(d.getUTCHours())+':'
         + pad(d.getUTCMinutes())+':'
         + pad(d.getUTCSeconds())+'Z'
}

var d = new Date();
console.log(ISODateString(d)); // Prints something like 2009-09-28T19:03:12Z

How to parse json string in Android?

Use JSON classes for parsing e.g

JSONObject mainObject = new JSONObject(Your_Sring_data);
JSONObject uniObject = mainObject.getJSONObject("university");
String  uniName = uniObject.getString("name");
String uniURL = uniObject.getString("url");

JSONObject oneObject = mainObject.getJSONObject("1");
String id = oneObject.getString("id");
....

'uint32_t' does not name a type

You need to include iostream

#include <iostream>
using namespace std;

Execution failed app:processDebugResources Android Studio

I stumbled upon this error while updating my Android studio to 3.0.1 from 2.3. After trying all the solutions above, i found that the issue was with the Build tools version. I was using an unsupported version of build tools. I changed mine as below and it worked.

buildToolsVersion '26.0.2'

As a rule of thumb always try to use the latest version of Build tools supported by your Gradle version. From version 3.0.0 of Gradle, you don't need to specify the build tools version as this is picked up automatically.

3.0.0 (October 2017) : Android plugin for Gradle 3.0.0

With this update, you no longer need to specify a version for the build tools—the plugin uses the minimum required version by default. So, you can now remove the android.buildToolsVersion property.

https://developer.android.com/studio/releases/gradle-plugin.html#3-0-0

Make Bootstrap's Carousel both center AND responsive?

By using this on bootstrap 3:

#carousel-example-generic{
    margin:auto;
}

Difference between IISRESET and IIS Stop-Start command

I know this is quite an old post, but I would like to point out the following for people who will read it in the future: As per MS:

Do not use the IISReset.exe tool to restart the IIS services. Instead, use the NET STOP and NET START commands. For example, to stop and start the World Wide Web Publishing Service, run the following commands:

  • NET STOP iisadmin /y
  • NET START w3svc

There are two benefits to using the NET STOP/NET START commands to restart the IIS Services as opposed to using the IISReset.exe tool. First, it is possible for IIS configuration changes that are in the process of being saved when the IISReset.exe command is run to be lost. Second, using IISReset.exe can make it difficult to identify which dependent service or services failed to stop when this problem occurs. Using the NET STOP commands to stop each individual dependent service will allow you to identify which service fails to stop, so you can then troubleshoot its failure accordingly.

KB:https://support.microsoft.com/en-ca/help/969864/using-iisreset-exe-to-restart-internet-information-services-iis-result

Why do we need middleware for async flow in Redux?

The short answer: seems like a totally reasonable approach to the asynchrony problem to me. With a couple caveats.

I had a very similar line of thought when working on a new project we just started at my job. I was a big fan of vanilla Redux's elegant system for updating the store and rerendering components in a way that stays out of the guts of a React component tree. It seemed weird to me to hook into that elegant dispatch mechanism to handle asynchrony.

I ended up going with a really similar approach to what you have there in a library I factored out of our project, which we called react-redux-controller.

I ended up not going with the exact approach you have above for a couple reasons:

  1. The way you have it written, those dispatching functions don't have access to the store. You can somewhat get around that by having your UI components pass in all of the info the dispatching function needs. But I'd argue that this couples those UI components to the dispatching logic unnecessarily. And more problematically, there's no obvious way for the dispatching function to access updated state in async continuations.
  2. The dispatching functions have access to dispatch itself via lexical scope. This limits the options for refactoring once that connect statement gets out of hand -- and it's looking pretty unwieldy with just that one update method. So you need some system for letting you compose those dispatcher functions if you break them up into separate modules.

Take together, you have to rig up some system to allow dispatch and the store to be injected into your dispatching functions, along with the parameters of the event. I know of three reasonable approaches to this dependency injection:

  • redux-thunk does this in a functional way, by passing them into your thunks (making them not exactly thunks at all, by dome definitions). I haven't worked with the other dispatch middleware approaches, but I assume they're basically the same.
  • react-redux-controller does this with a coroutine. As a bonus, it also gives you access to the "selectors", which are the functions you may have passed in as the first argument to connect, rather than having to work directly with the raw, normalized store.
  • You could also do it the object-oriented way by injecting them into the this context, through a variety of possible mechanisms.

Update

It occurs to me that part of this conundrum is a limitation of react-redux. The first argument to connect gets a state snapshot, but not dispatch. The second argument gets dispatch but not the state. Neither argument gets a thunk that closes over the current state, for being able to see updated state at the time of a continuation/callback.

Java integer to byte array

BigInteger.valueOf(1695609641).toByteArray()

Getting all file names from a folder using C#

http://msdn.microsoft.com/en-us/library/system.io.directory.getfiles.aspx

The System.IO namespace has loads of methods to help you with file operations. The

Directory.GetFiles() 

method returns an array of strings which represent the files in the target directory.

How to force open links in Chrome not download them?

Just found your question whilst trying to solve another problem I'm having, you will find that currently Google isn't able to perform a temporary download so therefore you have to download instead.

See: http://productforums.google.com/forum/#!topic/chrome/Drge_Zrwg-c

How would you implement an LRU cache in Java?

I would consider using java.util.concurrent.PriorityBlockingQueue, with priority determined by a "numberOfUses" counter in each element. I would be very, very careful to get all my synchronisation correct, as the "numberOfUses" counter implies that the element can't be immutable.

The element object would be a wrapper for the objects in the cache:

class CacheElement {
    private final Object obj;
    private int numberOfUsers = 0;

    CacheElement(Object obj) {
        this.obj = obj;
    }

    ... etc.
}

What REST PUT/POST/DELETE calls should return by a convention?

Forgive the flippancy, but if you are doing REST over HTTP then RFC7231 describes exactly what behaviour is expected from GET, PUT, POST and DELETE.

Update (Jul 3 '14):
The HTTP spec intentionally does not define what is returned from POST or DELETE. The spec only defines what needs to be defined. The rest is left up to the implementer to choose.

How can I style an Android Switch?

You can define the drawables that are used for the background, and the switcher part like this:

<Switch
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:thumb="@drawable/switch_thumb"
    android:track="@drawable/switch_bg" />

Now you need to create a selector that defines the different states for the switcher drawable. Here the copies from the Android sources:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:drawable="@drawable/switch_thumb_disabled_holo_light" />
    <item android:state_pressed="true"  android:drawable="@drawable/switch_thumb_pressed_holo_light" />
    <item android:state_checked="true"  android:drawable="@drawable/switch_thumb_activated_holo_light" />
    <item                               android:drawable="@drawable/switch_thumb_holo_light" />
</selector>

This defines the thumb drawable, the image that is moved over the background. There are four ninepatch images used for the slider:

The deactivated version (xhdpi version that Android is using)The deactivated version
The pressed slider: The pressed slider
The activated slider (on state):The activated slider
The default version (off state): enter image description here

There are also three different states for the background that are defined in the following selector:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:drawable="@drawable/switch_bg_disabled_holo_dark" />
    <item android:state_focused="true"  android:drawable="@drawable/switch_bg_focused_holo_dark" />
    <item                               android:drawable="@drawable/switch_bg_holo_dark" />
</selector>

The deactivated version: The deactivated version
The focused version: The focused version
And the default version:the default version

To have a styled switch just create this two selectors, set them to your Switch View and then change the seven images to your desired style.

Why does Java's hashCode() in String use 31 as a multiplier?

Goodrich and Tamassia computed from over 50,000 English words (formed as the union of the word lists provided in two variants of Unix) that using the constants 31, 33, 37, 39, and 41 will produce fewer than 7 collisions in each case. This may be the reason that so many Java implementations choose such constants.

See section 9.2 Hash Tables (page 522) of Data Structures and Algorithms in Java.

How to Select Every Row Where Column Value is NOT Distinct

How about

SELECT EmailAddress, CustomerName FROM Customers a
WHERE Exists ( SELECT emailAddress FROM customers c WHERE a.customerName != c.customerName AND a.EmailAddress = c.EmailAddress)

Show whitespace characters in Visual Studio Code

Hit the F1 button, then type "Toggle Render Whitespace" or the parts of it you can remember :)

I use vscode version 1.22.2 so this could be a feature that did not exist back in 2015.

How to get bitmap from a url in android?

Okay so you are trying to get a bitmap from a file? Title says URL. Anyways, when you are getting files from external storage in Android you should never use a direct path. Instead call getExternalStorageDirectory() like so:

File bitmapFile = new File(Environment.getExternalStorageDirectory() + "/" + PATH_TO_IMAGE);
Bitmap bitmap = BitmapFactory.decodeFile(bitmapFile);

getExternalStorageDirectory() gives you the path to the SD card. Also you need to declare the WRITE_EXTERNAL_STORAGE permission in the Manifest.

How to combine paths in Java?

The main answer is to use File objects. However Commons IO does have a class FilenameUtils that can do this kind of thing, such as the concat() method.

Get list of passed arguments in Windows batch script (.bat)

dancavallaro has it right, %* for all command line parameters (excluding the script name itself). You might also find these useful:

%0 - the command used to call the batch file (could be foo, ..\foo, c:\bats\foo.bat, etc.)
%1 is the first command line parameter,
%2 is the second command line parameter,
and so on till %9 (and SHIFT can be used for those after the 9th).

%~nx0 - the actual name of the batch file, regardless of calling method (some-batch.bat)
%~dp0 - drive and path to the script (d:\scripts)
%~dpnx0 - is the fully qualified path name of the script (d:\scripts\some-batch.bat)

More info examples at https://www.ss64.com/nt/syntax-args.html and https://www.robvanderwoude.com/parameters.html

How to get label text value form a html page?

Use innerText/textContent:

  var el = document.getElementById('*spaM4');
  console.log(el.innerText || el.textContent);

Fiddle: http://jsfiddle.net/NeTgC/2/

How to convert an image to base64 encoding?

Easy:

$imagedata = file_get_contents("/path/to/image.jpg");
             // alternatively specify an URL, if PHP settings allow
$base64 = base64_encode($imagedata);

bear in mind that this will enlarge the data by 33%, and you'll have problems with files whose size exceed your memory_limit.

Load image from url

URL url = new URL("http://image10.bizrate-images.com/resize?sq=60&uid=2216744464");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bmp);

Android and Facebook share intent

Here is something I did which open Facebook App with Link

shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setComponent(new ComponentName("com.facebook.katana",
                    "com.facebook.katana.activity.composer.ImplicitShareIntentHandler"));

shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT,  videoUrl);

if (select count(column) from table) > 0 then

You cannot directly use a SQL statement in a PL/SQL expression:

SQL> begin
  2     if (select count(*) from dual) >= 1 then
  3        null;
  4     end if;
  5  end;
  6  /
        if (select count(*) from dual) >= 1 then
            *
ERROR at line 2:
ORA-06550: line 2, column 6:
PLS-00103: Encountered the symbol "SELECT" when expecting one of the following:
...
...

You must use a variable instead:

SQL> set serveroutput on
SQL>
SQL> declare
  2     v_count number;
  3  begin
  4     select count(*) into v_count from dual;
  5
  6     if v_count >= 1 then
  7             dbms_output.put_line('Pass');
  8     end if;
  9  end;
 10  /
Pass

PL/SQL procedure successfully completed.

Of course, you may be able to do the whole thing in SQL:

update my_table
set x = y
where (select count(*) from other_table) >= 1;

It's difficult to prove that something is not possible. Other than the simple test case above, you can look at the syntax diagram for the IF statement; you won't see a SELECT statement in any of the branches.

Eclipse Generate Javadoc Wizard: what is "Javadoc Command"?

There are already useful answers to this question above, however there is one more possibility which I don't see being addressed here.

We should consider that the java is installed correctly (that's why eclipse could have been launched in the first place), and the JDK is also added correctly to the eclipse. So the issue might be for some reason (e.g. migration of eclipse to another OS) the path for javadoc is not right which you can easily check and modify in the javadoc wizard page. Here is detailed instructions:

  1. Open the javadoc wizard by Project->Generate Javadoc...
  2. In the javadoc wizard window make sure the javadoc command path is correct as illustrated in below screenshot:

EclipseJavadocWizard

Media Queries: How to target desktop, tablet, and mobile?

Nowadays the most common thing is to see retina-screen devices, in other words: devices with high resolutions and a very high pixel density (but usually smaller than 6 inches physical size). That's why you will need retina display specialized media-queries on your CSS. This is the most complete example I could find:

@media only screen and (min-width: 320px) {

  /* Small screen, non-retina */

}

@media
only screen and (-webkit-min-device-pixel-ratio: 2)      and (min-width: 320px),
only screen and (   min--moz-device-pixel-ratio: 2)      and (min-width: 320px),
only screen and (     -o-min-device-pixel-ratio: 2/1)    and (min-width: 320px),
only screen and (        min-device-pixel-ratio: 2)      and (min-width: 320px),
only screen and (                min-resolution: 192dpi) and (min-width: 320px),
only screen and (                min-resolution: 2dppx)  and (min-width: 320px) { 

  /* Small screen, retina, stuff to override above media query */

}

@media only screen and (min-width: 700px) {

  /* Medium screen, non-retina */

}

@media
only screen and (-webkit-min-device-pixel-ratio: 2)      and (min-width: 700px),
only screen and (   min--moz-device-pixel-ratio: 2)      and (min-width: 700px),
only screen and (     -o-min-device-pixel-ratio: 2/1)    and (min-width: 700px),
only screen and (        min-device-pixel-ratio: 2)      and (min-width: 700px),
only screen and (                min-resolution: 192dpi) and (min-width: 700px),
only screen and (                min-resolution: 2dppx)  and (min-width: 700px) { 

  /* Medium screen, retina, stuff to override above media query */

}

@media only screen and (min-width: 1300px) {

  /* Large screen, non-retina */

}

@media
only screen and (-webkit-min-device-pixel-ratio: 2)      and (min-width: 1300px),
only screen and (   min--moz-device-pixel-ratio: 2)      and (min-width: 1300px),
only screen and (     -o-min-device-pixel-ratio: 2/1)    and (min-width: 1300px),
only screen and (        min-device-pixel-ratio: 2)      and (min-width: 1300px),
only screen and (                min-resolution: 192dpi) and (min-width: 1300px),
only screen and (                min-resolution: 2dppx)  and (min-width: 1300px) { 

  /* Large screen, retina, stuff to override above media query */

}

Source: CSS-Tricks Website

Capturing image from webcam in java?

You can try Marvin Framework. It provides an interface to work with cameras. Moreover, it also provides a set of real-time video processing features, like object tracking and filtering.

Take a look!

Real-time Video Processing Demo:
http://www.youtube.com/watch?v=D5mBt0kRYvk

You can use the source below. Just save a frame using MarvinImageIO.saveImage() every 5 second.

Webcam video demo:

public class SimpleVideoTest extends JFrame implements Runnable{

    private MarvinVideoInterface    videoAdapter;
    private MarvinImage             image;
    private MarvinImagePanel        videoPanel;

    public SimpleVideoTest(){
        super("Simple Video Test");
        videoAdapter = new MarvinJavaCVAdapter();
        videoAdapter.connect(0);
        videoPanel = new MarvinImagePanel();
        add(videoPanel);
        new Thread(this).start();
        setSize(800,600);
        setVisible(true);
    }
    @Override
    public void run() {
        while(true){
            // Request a video frame and set into the VideoPanel
            image = videoAdapter.getFrame();
            videoPanel.setImage(image);
        }
    }
    public static void main(String[] args) {
        SimpleVideoTest t = new SimpleVideoTest();
        t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

For those who just want to take a single picture:

WebcamPicture.java

public class WebcamPicture {
    public static void main(String[] args) {
        try{
            MarvinVideoInterface videoAdapter = new MarvinJavaCVAdapter();
            videoAdapter.connect(0);
            MarvinImage image = videoAdapter.getFrame();
            MarvinImageIO.saveImage(image, "./res/webcam_picture.jpg");
        } catch(MarvinVideoInterfaceException e){
            e.printStackTrace();
        }
    }
}

Insert Picture into SQL Server 2005 Image Field using only SQL

For updating a record:

 UPDATE Employees SET [Photo] = (SELECT
 MyImage.* from Openrowset(Bulk
 'C:\photo.bmp', Single_Blob) MyImage)
 where Id = 10

Notes:

  • Make sure to add the 'BULKADMIN' Role Permissions for the login you are using.
  • Paths are not pointing to your computer when using SQL Server Management Studio. If you start SSMS on your local machine and connect to a SQL Server instance on server X, the file C:\photo.bmp will point to hard drive C: on server X, not your machine!

What is the equivalent of bigint in C#?

Int64 maps directly to BigInt.

Source

Find duplicate values in R

Here, I summarize a few ways which may return different results to your question, so be careful:

# First assign your "id"s to an R object.
# Here's a hypothetical example:
id <- c("a","b","b","c","c","c","d","d","d","d")

#To return ALL MINUS ONE duplicated values:
id[duplicated(id)]
## [1] "b" "c" "c" "d" "d" "d"

#To return ALL duplicated values by specifying fromLast argument:
id[duplicated(id) | duplicated(id, fromLast=TRUE)]
## [1] "b" "b" "c" "c" "c" "d" "d" "d" "d"

#Yet another way to return ALL duplicated values, using %in% operator:
id[ id %in% id[duplicated(id)] ]
## [1] "b" "b" "c" "c" "c" "d" "d" "d" "d"

Hope these help. Good luck.

Self-references in object literals / initializers

Simply instantiate an anonymous function:

var foo = new function () {
    this.a = 5;
    this.b = 6;
    this.c = this.a + this.b;
};

Why can't a text column have a default value in MySQL?

I normally run sites on Linux, but I also develop on a local Windows machine. I've run into this problem many times and just fixed the tables when I encountered the problems. I installed an app yesterday to help someone out and of course ran into the problem again. So, I decided it was time to figure out what was going on - and found this thread. I really don't like the idea of changing the sql_mode of the server to an earlier mode (by default), so I came up with a simple (me thinks) solution.

This solution would of course require developers to wrap their table creation scripts to compensate for the MySQL issue running on Windows. You'll see similar concepts in dump files. One BIG caveat is that this could/will cause problems if partitioning is used.

// Store the current sql_mode
mysql_query("set @orig_mode = @@global.sql_mode");

// Set sql_mode to one that won't trigger errors...
mysql_query('set @@global.sql_mode = "MYSQL40"');

/**
 * Do table creations here...
 */

// Change it back to original sql_mode
mysql_query('set @@global.sql_mode = @orig_mode');

That's about it.

Android getActivity() is undefined

This is because you're using getActivity() inside an inner class. Try using:

SherlockFragmentActivity.this.getActivity()

instead, though there's really no need for the getActivity() part. In your case, SherlockFragmentActivity .this should suffice.

Select first 10 distinct rows in mysql

SELECT * 
FROM people 
WHERE names ='SMITH'
ORDER BY names asc
limit 10

If you need add group by clause. If you search Smith you would have to sort on something else.

Scrollbar without fixed height/Dynamic height with scrollbar

 <div id="scroll">
    <p>Try to add more text</p>
 </div>

here's the css code

#scroll {
   overflow-y:auto;
   height:auto;
   max-height:200px;
   border:1px solid black;
   width:300px;
 }

here's the demo JSFIDDLE

How to read from input until newline is found using scanf()?

Sounds like a homework problem. scanf() is the wrong function to use for the problem. I'd recommend getchar() or getch().

Note: I'm purposefully not solving the problem since this seems like homework, instead just pointing you in the right direction.

Convert string to nullable type (int, double, etc...)

There is a generic solution (for any type). Usability is good, but implementation should be improved: http://cleansharp.de/wordpress/2011/05/generischer-typeconverter/

This allows you to write very clean code like this:

string value = null;
int? x = value.ConvertOrDefault<int?>();

and also:

object obj = 1;  

string value = null;
int x = 5;
if (value.TryConvert(out x))
    Console.WriteLine("TryConvert example: " + x); 

bool boolean = "false".ConvertOrDefault<bool>();
bool? nullableBoolean = "".ConvertOrDefault<bool?>();
int integer = obj.ConvertOrDefault<int>();
int negativeInteger = "-12123".ConvertOrDefault<int>();
int? nullableInteger = value.ConvertOrDefault<int?>();
MyEnum enumValue = "SecondValue".ConvertOrDefault<MyEnum>();

MyObjectBase myObject = new MyObjectClassA();
MyObjectClassA myObjectClassA = myObject.ConvertOrDefault<MyObjectClassA>();

How do I find an element that contains specific text in Selenium WebDriver (Python)?

Similar problem: Find <button>Advanced...</button>

Maybe this will give you some ideas (please transfer the concept from Java to Python):

wait.until(ExpectedConditions.elementToBeClickable(//
    driver.findElements(By.tagName("button")).stream().filter(i -> i.getText().equals("Advanced...")).findFirst().get())).click();

How to get the full url in Express?

async function (request, response, next) {
  const url = request.rawHeaders[9] + request.originalUrl;
  //or
  const url = request.headers.host + request.originalUrl;
}

What are best practices that you use when writing Objective-C and Cocoa?

Don't use unknown strings as format strings

When methods or functions take a format string argument, you should make sure that you have control over the content of the format string.

For example, when logging strings, it is tempting to pass the string variable as the sole argument to NSLog:

    NSString *aString = // get a string from somewhere;
    NSLog(aString);

The problem with this is that the string may contain characters that are interpreted as format strings. This can lead to erroneous output, crashes, and security problems. Instead, you should substitute the string variable into a format string:

    NSLog(@"%@", aString);

SQL Server after update trigger

Try this script to create a temporary table TESTTEST and watch the order of precedence as the triggers are called in this order: 1) INSTEAD OF, 2) FOR, 3) AFTER

All of the logic is placed in INSTEAD OF trigger and I have 2 examples of how you might code some scenarios...

Good luck...

CREATE TABLE TESTTEST
(
    ID  INT,
    Modified0 DATETIME,
    Modified1 DATETIME
)
GO
CREATE TRIGGER [dbo].[tr_TESTTEST_0] ON [dbo].TESTTEST
INSTEAD OF INSERT,UPDATE,DELETE
AS
BEGIN
    SELECT 'INSTEAD OF'
    SELECT 'TT0.0'
    SELECT * FROM TESTTEST

    SELECT *, 'I' Mode
    INTO #work
    FROM INSERTED

    UPDATE #work SET Mode='U' WHERE ID IN (SELECT ID FROM DELETED)
    INSERT INTO #work (ID, Modified0, Modified1, Mode)
    SELECT ID, Modified0, Modified1, 'D'
    FROM DELETED WHERE ID NOT IN (SELECT ID FROM INSERTED)

    --Check Security or any other logic to add and remove from #work before processing
    DELETE FROM #work WHERE ID=9 -- because you don't want anyone to edit this id?!?!
    DELETE FROM #work WHERE Mode='D' -- because you don't want anyone to delete any records

    SELECT 'EV'
    SELECT * FROM #work

    IF(EXISTS(SELECT TOP 1 * FROM #work WHERE Mode='I'))
    BEGIN
        SELECT 'I0.0'
        INSERT INTO dbo.TESTTEST (ID, Modified0, Modified1)
        SELECT ID, Modified0, Modified1
        FROM #work
        WHERE Mode='I'
        SELECT 'Cool stuff would happen here if you had FOR INSERT or AFTER INSERT triggers.'
        SELECT 'I0.1'
    END

    IF(EXISTS(SELECT TOP 1 * FROM #work WHERE Mode='D'))
    BEGIN
        SELECT 'D0.0'
        DELETE FROM TESTTEST WHERE ID IN (SELECT ID FROM #work WHERE Mode='D')
        SELECT 'Cool stuff would happen here if you had FOR DELETE or AFTER DELETE triggers.'
        SELECT 'D0.1'
    END

    IF(EXISTS(SELECT TOP 1 * FROM #work WHERE Mode='U'))
    BEGIN
        SELECT 'U0.0'
        UPDATE t SET t.Modified0=e.Modified0, t.Modified1=e.Modified1
        FROM dbo.TESTTEST t
        INNER JOIN #work e ON e.ID = t.ID
        WHERE e.Mode='U'
        SELECT 'U0.1'
    END
    DROP TABLE #work

    SELECT 'TT0.1'
    SELECT * FROM TESTTEST
END
GO
CREATE TRIGGER [dbo].[tr_TESTTEST_1] ON [dbo].TESTTEST
FOR UPDATE
AS
BEGIN
    SELECT 'FOR UPDATE'

    SELECT 'TT1.0'
    SELECT * FROM TESTTEST

    SELECT 'I1'
    SELECT * FROM INSERTED

    SELECT 'D1'
    SELECT * FROM DELETED

    SELECT 'TT1.1'
    SELECT * FROM TESTTEST
END
GO
CREATE TRIGGER [dbo].[tr_TESTTEST_2] ON [dbo].TESTTEST
AFTER UPDATE
AS
BEGIN
    SELECT 'AFTER UPDATE'

    SELECT 'TT2.0'
    SELECT * FROM TESTTEST

    SELECT 'I2'
    SELECT * FROM INSERTED

    SELECT 'D2'
    SELECT * FROM DELETED

    SELECT 'TT2.1'
    SELECT * FROM TESTTEST
END
GO

SELECT 'Start'
INSERT INTO TESTTEST (ID, Modified0) VALUES (9, GETDATE())-- not going to insert
SELECT 'RESTART'
INSERT INTO TESTTEST (ID, Modified0) VALUES (10, GETDATE())--going to insert
SELECT 'RESTART'
UPDATE TESTTEST SET Modified1=GETDATE() WHERE ID=10-- gointo to update
SELECT 'RESTART'
DELETE FROM TESTTEST WHERE ID=10-- not going to DELETE
SELECT 'FINISHED'

SELECT * FROM TESTTEST
DROP TABLE TESTTEST

Which equals operator (== vs ===) should be used in JavaScript comparisons?

Simply

== means comparison between operands with type conversion

&

=== means comparison between operands without type conversion

Type conversion in javaScript means javaScript automatically convert any other data types to string data types.

For example:

123=='123'   //will return true, because JS convert integer 123 to string '123'
             //as we used '==' operator 

123==='123' //will return false, because JS do not convert integer 123 to string 
            //'123' as we used '===' operator 

Why does SSL handshake give 'Could not generate DH keypair' exception?

You can disable DHE completely in your jdk, edit jre/lib/security/java.security and make sure DHE is disabled, eg. like

jdk.tls.disabledAlgorithms=SSLv3, DHE.

sqlplus: error while loading shared libraries: libsqlplus.so: cannot open shared object file: No such file or directory

PERMISSIONS: I want to stress the importance of permissions for "sqlplus".

  1. For any "Other" UNIX user other than the Owner/Group to be able to run sqlplus and access an ORACLE database , read/execute permissions are required (rx) for these 4 directories :

    $ORACLE_HOME/bin , $ORACLE_HOME/lib, $ORACLE_HOME/oracore, $ORACLE_HOME/sqlplus

  2. Environment. Set those properly:

    A. ORACLE_HOME (example: ORACLE_HOME=/u01/app/oranpgm/product/12.1.0/PRMNRDEV/)

    B. LD_LIBRARY_PATH (example: ORACLE_HOME=/u01/app/oranpgm/product/12.1.0/PRMNRDEV/lib)

    C. ORACLE_SID

    D. PATH

     export PATH="$ORACLE_HOME/bin:$PATH"
    

What is Ad Hoc Query?

In Sql Server "Ad Hoc Query" is also used for Ad Hoc Distributed Queries. These are ad hoc queries on an other server via OpenRowset or OpenDatasource. Ad Hoc Distributed Queries are only allowed after configuring so. This is a Server configuration option.

Simulating Button click in javascript

The reason your code isn't working the way you would expect is because this line:

<button type="button" value="submit" onClick="document.getElementById("datepicker").click()">submit </button>

should be changed to:

<button type="button" value="submit" onClick="document.getElementById('datepicker').focus()">submit </button>

There are two things to notice here:

1: The "s around datepicker have been changed to 's so that they do not interfere with the quotes surrounding the onclick event.

2: The click() has been changed to focus() to activate the datepicker calendar. When the button is pressed.

Now, this fixes your issue...but I do agree with the other posts that using jQuery to access the DOM element and trigger the event is the better way to go. Since you're already doing this for the jQuery datapicker plugin via <script src="http://code.jquery.com/jquery-1.8.3.js"></script>, this should not be a problem.

Inline events are not recommended.

Why I cannot cout a string?

You need to reference the cout's namespace std somehow. For instance, insert

using std::cout;
using std::endl;

on top of your function definition, or the file.

Adding a stylesheet to asp.net (using Visual Studio 2010)

The only thing you have to do is to add in the cshtml file, in the head, the following line:

        @Styles.Render("~/Content/Main.css")

The entire head will look somethink like that:

    <head>
         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
         <title>HTML Page</title>
         @Styles.Render("~/Content/main.css")
    </head>

Hope it helps!!

Putting GridView data in a DataTable

Copying Grid to datatable

        if (GridView.Rows.Count != 0)
        {
            //Forloop for header
            for (int i = 0; i < GridView.HeaderRow.Cells.Count; i++)
            {
                dt.Columns.Add(GridView.HeaderRow.Cells[i].Text);
            }
            //foreach for datarow
            foreach (GridViewRow row in GridView.Rows)
            {
                DataRow dr = dt.NewRow();
                for (int j = 0; j < row.Cells.Count; j++)
                {
                    dr[GridView.HeaderRow.Cells[j].Text] = row.Cells[j].Text;
                }
                dt.Rows.Add(dr);
            }
            //Loop for footer
            if (GridView.FooterRow.Cells.Count != 0)
            {
                DataRow dr = dt.NewRow();
                for (int i = 0; i < GridView.FooterRow.Cells.Count; i++)
                {
                    //You have to re-do the work if you did anything in databound for footer.  
                }
                dt.Rows.Add(dr);
            }
            dt.TableName = "tb";
        }

How to debug Javascript with IE 8

I discovered today that we can now debug Javascript With the developer tool bar plugins integreted in IE 8.

  • Click ? Tools on the toolbar, to the right of the tabs.
  • Select Developer Tools. The Developer Tools dialogue should open.
  • Click the Script tab in the dialogue.
  • Click the Start Debugging button.

You can use watch, breakpoint, see the call stack etc, similarly to debuggers in professional browsers.

You can also use the statement debugger; in your JavaScript code the set a breakpoint.

Replace whitespace with a comma in a text file in Linux

Here's a Perl script which will edit the files in-place:

perl -i.bak -lpe 's/\s+/,/g' files*

Consecutive whitespace is converted to a single comma.
Each input file is moved to .bak

These command-line options are used:

  • -i.bak edit in-place and make .bak copies

  • -p loop around every line of the input file, automatically print the line

  • -l removes newlines before processing, and adds them back in afterwards

  • -e execute the perl code

Android change SDK version in Eclipse? Unable to resolve target android-x

This Problem is because of Path so you need to build the path using following Steps

Goto project ----->Right Click on Project Name ---->properties ---->click on Than Java Build Path option than ---> click Android 4.2.2---->Ok

Deleting rows from parent and child tables

If the children have FKs linking them to the parent, then you can use DELETE CASCADE on the parent.

e.g.

CREATE TABLE supplier 
( supplier_id numeric(10) not null, 
 supplier_name varchar2(50) not null, 
 contact_name varchar2(50),  
 CONSTRAINT supplier_pk PRIMARY KEY (supplier_id) 
); 



CREATE TABLE products 
( product_id numeric(10) not null, 
 supplier_id numeric(10) not null, 
 CONSTRAINT fk_supplier 
   FOREIGN KEY (supplier_id) 
  REFERENCES supplier(supplier_id) 
  ON DELETE CASCADE 
); 

Delete the supplier, and it will delate all products for that supplier

When should a class be Comparable and/or Comparator?

Implementing Comparable means "I can compare myself with another object." This is typically useful when there's a single natural default comparison.

Implementing Comparator means "I can compare two other objects." This is typically useful when there are multiple ways of comparing two instances of a type - e.g. you could compare people by age, name etc.

View the change history of a file using Git versioning

SmartGit:

  1. In the menu enable to display unchanged files: View / Show unchanged files
  2. Right click the file and select 'Log' or press 'Ctrl-L'

JavaScript alert box with timer

If you are looking for an alert that dissapears after an interval you could try the jQuery UI Dialog widget.

Rails params explained?

Params contains the following three groups of parameters:

  1. User supplied parameters
    • GET (http://domain.com/url?param1=value1&param2=value2 will set params[:param1] and params[:param2])
    • POST (e.g. JSON, XML will automatically be parsed and stored in params)
    • Note: By default, Rails duplicates the user supplied parameters and stores them in params[:user] if in UsersController, can be changed with wrap_parameters setting
  2. Routing parameters
    • match '/user/:id' in routes.rb will set params[:id]
  3. Default parameters
    • params[:controller] and params[:action] is always available and contains the current controller and action

How to avoid Python/Pandas creating an index in a saved csv?

Another solution if you want to keep this column as index.

pd.read_csv('filename.csv', index_col='Unnamed: 0')

Deserializing JSON Object Array with Json.net

Slight modification to what was stated above. My Json format, which validates was

{
    mycollection:{[
           {   
               property0:value,
               property1:value,
             },
             {   
               property0:value,
               property1:value,
             }
           ]

         }
       }

Using AlexDev's response, I did this Looping each child, creating reader from it

 public partial class myModel
{
    public static List<myModel> FromJson(string json) => JsonConvert.DeserializeObject<myModelList>(json, Converter.Settings).model;
}

 public class myModelList {
    [JsonConverter(typeof(myModelConverter))]
    public List<myModel> model { get; set; }

}

class myModelConverter : JsonConverter
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var token = JToken.Load(reader);
        var list = Activator.CreateInstance(objectType) as System.Collections.IList;
        var itemType = objectType.GenericTypeArguments[0];
        foreach (var child in token.Children())  //mod here
        {
            var newObject = Activator.CreateInstance(itemType);
            serializer.Populate(child.CreateReader(), newObject); //mod here
            list.Add(newObject);
        }
        return list;
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType.IsGenericType && (objectType.GetGenericTypeDefinition() == typeof(List<>));
    }
    public override bool CanWrite => false;
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException();

}

How to disable a link using only CSS?

Thanks to everyone that posted solutions, I combined multiple approaches to provide some more advanced disabled functionality. Here is a gist, and the code is below.

This provides for multiple levels of defense so that Anchors marked as disable actually behave as such.
Using this approach, you get an anchor that you cannot:
  - click
  - tab to and hit return
  - tabbing to it will move focus to the next focusable element
  - it is aware if the anchor is subsequently enabled


1.  Include this css, as it is the first line of defense.  This assumes the selector you use is 'a.disabled'
    a.disabled {
      pointer-events: none;
      cursor: default;
    }

 2. Next, instantiate this class such as (with optional selector):
    $ ->
      new AnchorDisabler()

Here is the coffescript class:

class AnchorDisabler
  constructor: (selector = 'a.disabled') ->
    $(selector).click(@onClick).keyup(@onKeyup).focus(@onFocus)

  isStillDisabled: (ev) =>
    ### since disabled can be a class or an attribute, and it can be dynamically removed, always recheck on a watched event ###
    target = $(ev.target)
    return true if target.hasClass('disabled')
    return true if target.attr('disabled') is 'disabled'
    return false

  onFocus: (ev) =>
    ### if an attempt is made to focus on a disabled element, just move it along to the next focusable one. ###
    return unless @isStillDisabled(ev)

    focusables = $(':focusable')
    return unless focusables

    current = focusables.index(ev.target)
    next = (if focusables.eq(current + 1).length then focusables.eq(current + 1) else focusables.eq(0))

    next.focus() if next


  onClick: (ev) =>
    # disabled could be dynamically removed
    return unless @isStillDisabled(ev)

    ev.preventDefault()
    return false

  onKeyup: (ev) =>

    # 13 is the js key code for Enter, we are only interested in disabling that so get out fast
    code = ev.keyCode or ev.which
    return unless code is 13

    # disabled could be dynamically removed
    return unless @isStillDisabled(ev)

    ev.preventDefault()
    return false

Click outside menu to close in jquery

what about this?

    $(this).mouseleave(function(){  
        var thisUI = $(this);
        $('html').click(function(){
                thisUI.hide();
            $('html').unbind('click');
         });
     });

Swift Modal View Controller with transparent background

You can do it like this:

In your main view controller:

func showModal() {
    let modalViewController = ModalViewController()
    modalViewController.modalPresentationStyle = .overCurrentContext
    presentViewController(modalViewController, animated: true, completion: nil)
}

In your modal view controller:

class ModalViewController: UIViewController {
    override func viewDidLoad() {
        view.backgroundColor = UIColor.clearColor()
        view.opaque = false
    }
}

If you are working with a storyboard:

Just add a Storyboard Segue with Kind set to Present Modally to your modal view controller and on this view controller set the following values:

  • Background = Clear Color
  • Drawing = Uncheck the Opaque checkbox
  • Presentation = Over Current Context

As Crashalot pointed out in his comment: Make sure the segue only uses Default for both Presentation and Transition. Using Current Context for Presentation makes the modal turn black instead of remaining transparent.

How do I copy a 2 Dimensional array in Java?

I am using this function:

public static int[][] copy(final int[][] array) {
    if (array != null) {
        final int[][] copy = new int[array.length][];

        for (int i = 0; i < array.length; i++) {
            final int[] row = array[i];

            copy[i] = new int[row.length];
            System.arraycopy(row, 0, copy[i], 0, row.length);
        }

        return copy;
    }

    return null;
}

The big advantage of this approach is that it can also copy arrays that don't have the same row count such as:

final int[][] array = new int[][] { { 5, 3, 6 }, { 1 } };

how to add the missing RANDR extension

I am seeing this error message when I run Firefox headless through selenium using xvfb. It turns out that the message was a red herring for me. The message is only a warning, not an error. It is not why Firefox was not starting correctly.

The reason that Firefox was not starting for me was that it had been updated to a version that was no longer compatible with the Selenium drivers that I was using. I upgraded the selenium drivers to the latest and Firefox starts up fine again (even with this warning message about RANDR).

New releases of Firefox are often only compatible with one or two versions of Selenium. Occasionally Firefox is released with NO compatible version of Selenium. When that happens, it may take a week or two for a new version of Selenium to get released. Because of this, I now keep a version of Firefox that is known to work with the version of Selenium that I have installed. In addition to the version of Firefox that is kept up to date by my package manager, I have a version installed in /opt/ (eg /opt/firefox31/). The Selenium Java API takes an argument for the location of the Firefox binary to be used. The downside is that older versions of Firefox have known security vulnerabilities and shouldn't be used with untrusted content.

How can I display an image from a file in Jupyter Notebook?

Courtesy of this page, I found this worked when the suggestions above didn't:

import PIL.Image
from cStringIO import StringIO
import IPython.display
import numpy as np
def showarray(a, fmt='png'):
    a = np.uint8(a)
    f = StringIO()
    PIL.Image.fromarray(a).save(f, fmt)
    IPython.display.display(IPython.display.Image(data=f.getvalue()))

Return background color of selected cell

Maybe you can use this properties:

ActiveCell.Interior.ColorIndex - one of 56 preset colors

and

ActiveCell.Interior.Color - RGB color, used like that:

ActiveCell.Interior.Color = RGB(255,255,255)

Using logging in multiple modules

Throwing in another solution.

In my module's init.py I have something like:

# mymodule/__init__.py
import logging

def get_module_logger(mod_name):
  logger = logging.getLogger(mod_name)
  handler = logging.StreamHandler()
  formatter = logging.Formatter(
        '%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
  handler.setFormatter(formatter)
  logger.addHandler(handler)
  logger.setLevel(logging.DEBUG)
  return logger

Then in each module I need a logger, I do:

# mymodule/foo.py
from [modname] import get_module_logger
logger = get_module_logger(__name__)

When the logs are missed, you can differentiate their source by the module they came from.

$.ajax - dataType

as per docs:

  • "json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
  • "text": A plain text string.

How to install a specific version of Node on Ubuntu?

FYI the available version for raring in Chris Lea's repo is currently 0.8.25

sudo apt-get install nodejs=0.8.25-2chl1~raring1

How do the post increment (i++) and pre increment (++i) operators work in Java?

I believe however if you combine all of your statements and run it in Java 8.1 you will get a different answer, at least that's what my experience says.

The code will work like this:

int a=5,i;

i=++a + ++a + a++;            /*a = 5;
                                i=++a + ++a + a++; =>
                                i=6 + 7 + 7; (a=8); i=20;*/

i=a++ + ++a + ++a;           /*a = 5;
                                i=a++ + ++a + ++a; =>
                                i=8 + 10 + 11; (a=11); i=29;*/

a=++a + ++a + a++;            /*a=5;
                                a=++a + ++a + a++; =>
                                a=12 + 13 + 13;  a=38;*/

System.out.println(a);        //output: 38
System.out.println(i);         //output: 29

Auto refresh code in HTML using meta tags

The quotes you use are the issue:

<meta http-equiv=”refresh” content=”5" >

You should use the "

<meta http-equiv="refresh" content="5">

"Permission Denied" trying to run Python on Windows 10

This issue is far too common to still be persistent. And most answers and instructions fail to address it. Here's what to do on Windows 10:

  1. Type environment variables in the start search bar, and open Edit the System Environment Variables.

  2. Click Environment Variables...

  3. In the System Variables section, locate the variable with the key Path and double click it.

  4. Look for paths pointing to python files. Likely there are none. If there are, select and delete them.

  5. Create a new variable set to the path to your python executable. Normally this is C:\Users\[YOUR USERNAME HERE]\AppData\Local\Programs\Python\Python38. Ensure this by checking via your File Explorer.

    Note: If you can't see AppData, it's because you've not enabled viewing of hidden items: click the View tab and tick the Hidden Items checkbox.

  6. Create another variable pointing to the Scripts directory. Typically it is C:\Users\[YOUR USERNAME HERE]\AppData\Local\Programs\Python\Scripts.

  7. Restart your terminal and try typing py, python, python3, or python.exe.

Use NSInteger as array index

According to the error message, you declared myLoc as a pointer to an NSInteger (NSInteger *myLoc) rather than an actual NSInteger (NSInteger myLoc). It needs to be the latter.

What's the difference between a 302 and a 307 redirect?

Originally there was just 302

Response What browsers should do
302 Found Redo request with new url

The idea is that:

  • if you were doing a GET at some location, you would redo your GET to the new URL
  • if you were doing a POST at some location, you would redo your POST to the new URL
  • if you were doing a PUT at some location, you would redo your PUT to the new URL
  • if you were doing a DELETE at some location, you would redo your DELETE to the new URL
  • etc

Unfortunately every browser did it wrong. When getting a 302, they would always switch to GET at the new URL, rather than retrying the request with the same verb (e.g., POST):

  • Mosaic did it wrong
  • Netscape copied the bugs in Mosaic; so they got it wrong
  • Internet Explorer copied the bugs in Netscape; so they got it wrong

It became de-facto wrong.

All browsers got 302 wrong. So 303 and 307 were created.

Response What browsers should do What browsers actually do
302 Found Redo request with new url GET with new url
303 See Other GET with new url GET with new url
307 Temporary Redirect Redo request with new url Redo request with new url

In chart form

The 5 different kinds of redirects:

+------------------------------------------------------------+
¦           ¦                Switch to GET?                  ¦
¦           ¦------------------------------------------------¦
¦ Temporary ¦          No            ¦         Yes           ¦
¦-----------+------------------------+-----------------------¦
¦ No        ¦ 308 Permanent Redirect ¦ 301 Moved Permanently ¦
¦-----------+------------------------+-----------------------¦
¦ Yes       ¦ 307 Temporary Redirect ¦ 303 See Other         ¦
¦           ¦ 302 Found (intended)   ¦ 302 Found (actual)    ¦
+------------------------------------------------------------+

Alternatively:

Response Switch to get? Temporary?
301 Moved Permanently No No
302 Found (intended) No Yes
302 Found (actual) Yes Yes
303 See Other Yes Yes
307 Temporary Redirect No Yes
308 Permanent Redirect No No

How can I add numbers in a Bash script?

For integers:

  • Use arithmetic expansion: $((EXPR))

    num=$((num1 + num2))
    num=$(($num1 + $num2))       # Also works
    num=$((num1 + 2 + 3))        # ...
    num=$[num1+num2]             # Old, deprecated arithmetic expression syntax
    
  • Using the external expr utility. Note that this is only needed for really old systems.

    num=`expr $num1 + $num2`     # Whitespace for expr is important
    

For floating point:

Bash doesn't directly support this, but there are a couple of external tools you can use:

num=$(awk "BEGIN {print $num1+$num2; exit}")
num=$(python -c "print $num1+$num2")
num=$(perl -e "print $num1+$num2")
num=$(echo $num1 + $num2 | bc)   # Whitespace for echo is important

You can also use scientific notation (for example, 2.5e+2).


Common pitfalls:

  • When setting a variable, you cannot have whitespace on either side of =, otherwise it will force the shell to interpret the first word as the name of the application to run (for example, num= or num)

    num= 1 num =2

  • bc and expr expect each number and operator as a separate argument, so whitespace is important. They cannot process arguments like 3+ +4.

    num=`expr $num1+ $num2`

rsync: how can I configure it to create target directory on server?

The -R, --relative option will do this.

For example: if you want to backup /var/named/chroot and create the same directory structure on the remote server then -R will do just that.

Android Studio Gradle DSL method not found: 'android()' -- Error(17,0)

Correcting gradle settings is quite difficult. If you don't know much about Gradle it requires you to learn alot. Instead you can do the following:

1) Start a new project in a new folder. Choose the same settings with your project with gradle problem but keep it simple: Choose an empty main activity. 2) Delete all the files in ...\NewProjectName\app\src\main folder 3) Copy all the files in ...\ProjectWithGradleProblem\app\src\main folder to ...\NewProjectName\app\src\main folder. 4) If you are using the Test project (\ProjectWithGradleProblem\app\src\AndroidTest) you can do the same for that too.

this method works fine if your Gradle installation is healthy. If you just installed Android studio and did not modify it, the Gradle installation should be fine.

Removing pip's cache?

Since pip 20.1b1, which was released on 21 April 2020 and "added pip cache command for inspecting/managing pip’s wheel cache", it is possible to issue this command:

pip cache purge

The reference guide is here:
https://pip.pypa.io/en/stable/reference/pip_cache/
The corresponding pull request is here.

How can I make one python file run another?

from subprocess import Popen

Popen('python filename.py')

or how-can-i-make-one-python-file-run-another-file

Edit line thickness of CSS 'underline' attribute

Very easy ... outside "span" element with small font and underline, and inside "font" element with bigger font size.

_x000D_
_x000D_
<span style="font-size:1em;text-decoration:underline;">_x000D_
 <span style="font-size:1.5em;">_x000D_
   Text with big font size and thin underline_x000D_
 </span>_x000D_
</span>
_x000D_
_x000D_
_x000D_

How to hide Bootstrap previous modal when you opening new one?

The best that I've been able to do is

$(this).closest('.modal').modal('toggle');

This gets the modal holding the DOM object you triggered the event on (guessing you're clicking a button). Gets the closest parent '.modal' and toggles it. Obviously only works because it's inside the modal you clicked.

You can however do this:

$(".modal:visible").modal('toggle');

This gets the modal that is displaying (since you can only have one open at a time), and triggers the 'toggle' This would not work without ":visible"

Standard way to embed version into python package?

Lots of work toward uniform versioning and in support of conventions has been completed since this question was first asked. Palatable options are now detailed in the Python Packaging User Guide. Also noteworthy is that version number schemes are relatively strict in Python per PEP 440, and so keeping things sane is critical if your package will be released to the Cheese Shop.

Here's a shortened breakdown of versioning options:

  1. Read the file in setup.py (setuptools) and get the version.
  2. Use an external build tool (to update both __init__.py as well as source control), e.g. bump2version, changes or zest.releaser.
  3. Set the value to a __version__ global variable in a specific module.
  4. Place the value in a simple VERSION text file for both setup.py and code to read.
  5. Set the value via a setup.py release, and use importlib.metadata to pick it up at runtime. (Warning, there are pre-3.8 and post-3.8 versions.)
  6. Set the value to __version__ in sample/__init__.py and import sample in setup.py.
  7. Use setuptools_scm to extract versioning from source control so that it's the canonical reference, not code.

NOTE that (7) might be the most modern approach (build metadata is independent of code, published by automation). Also NOTE that if setup is used for package release that a simple python3 setup.py --version will report the version directly.

SQL Server Output Clause into a scalar variable

Way later but still worth mentioning is that you can also use variables to output values in the SET clause of an UPDATE or in the fields of a SELECT;

DECLARE @val1 int;
DECLARE @val2 int;
UPDATE [dbo].[PortalCounters_TEST]
SET @val1 = NextNum, @val2 = NextNum = NextNum + 1
WHERE [Condition] = 'unique value'
SELECT @val1, @val2

In the example above @val1 has the before value and @val2 has the after value although I suspect any changes from a trigger would not be in val2 so you'd have to go with the output table in that case. For anything but the simplest case, I think the output table will be more readable in your code as well.

One place this is very helpful is if you want to turn a column into a comma-separated list;

DECLARE @list varchar(max) = '';
DECLARE @comma varchar(2) = '';
SELECT @list = @list + @comma + County, @comma = ', ' FROM County
print @list

Using jQuery to see if a div has a child with a certain class

Simple Way

if ($('#text-field > p.filled-text').length != 0)

Find maximum value of a column and return the corresponding row values using Pandas

You can use:

print(df[df['Value']==df['Value'].max()])

Understanding the Linux oom-killer's logs

Memory management in Linux is a bit tricky to understand, and I can't say I fully understand it yet, but I'll try to share a little bit of my experience and knowledge.

Short answer to your question: Yes there are other stuff included than whats in the list.

What's being shown in your list is applications run in userspace. The kernel uses memory for itself and modules, on top of that it also has a lower limit of free memory that you can't go under. When you've reached that level it will try to free up resources, and when it can't do that anymore, you end up with an OOM problem.

From the last line of your list you can read that the kernel reports a total-vm usage of: 1498536kB (1,5GB), where the total-vm includes both your physical RAM and swap space. You stated you don't have any swap but the kernel seems to think otherwise since your swap space is reported to be full (Total swap = 524284kB, Free swap = 0kB) and it reports a total vmem size of 1,5GB.

Another thing that can complicate things further is memory fragmentation. You can hit the OOM killer when the kernel tries to allocate lets say 4096kB of continous memory, but there are no free ones availible.

Now that alone probably won't help you solve the actual problem. I don't know if it's normal for your program to require that amount of memory, but I would recommend to try a static code analyzer like cppcheck to check for memory leaks or file descriptor leaks. You could also try to run it through Valgrind to get a bit more information out about memory usage.

What version of JBoss I am running?

Use the following command from Linux

find $JBOSS_HOME -name run.sh -exec {} -V \; | grep '^JBoss'

Convert base class to derived class

No, there's no built-in way to convert a class like you say. The simplest way to do this would be to do what you suggested: create a DerivedClass(BaseClass) constructor. Other options would basically come out to automate the copying of properties from the base to the derived instance, e.g. using reflection.

The code you posted using as will compile, as I'm sure you've seen, but will throw a null reference exception when you run it, because myBaseObject as DerivedClass will evaluate to null, since it's not an instance of DerivedClass.

Numpy: find index of the elements within range

You can use np.where to get indices and np.logical_and to set two conditions:

import numpy as np
a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])

np.where(np.logical_and(a>=6, a<=10))
# returns (array([3, 4, 5]),)

Structs data type in php?

Closest you'd get to a struct is an object with all members public.

class MyStruct {
    public $foo;
    public $bar;
}

$obj = new MyStruct();
$obj->foo = 'Hello';
$obj->bar = 'World';

I'd say looking at the PHP Class Documentation would be worth it. If you need a one-off struct, use the StdObject as mentioned in alex's answer.

What is $@ in Bash?

Yes. Please see the man page of bash ( the first thing you go to ) under Special Parameters

Special Parameters

The shell treats several parameters specially. These parameters may only be referenced; assignment to them is not allowed.

* Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is, "$*" is equivalent to "$1c$2c...", where c is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators.

@ Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "$1" "$2" ... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, "$@" and $@ expand to nothing (i.e., they are removed).

Why does Boolean.ToString output "True" and not "true"

This probably harks from the old VB NOT .Net days when bool.ToString produced True or False.

ASP.NET MVC3 Razor - Html.ActionLink style

Here's the signature.

public static string ActionLink(this HtmlHelper htmlHelper, 
                                string linkText,
                                string actionName,
                                string controllerName,
                                object values, 
                                object htmlAttributes)

What you are doing is mixing the values and the htmlAttributes together. values are for URL routing.

You might want to do this.

@Html.ActionLink(Context.User.Identity.Name, "Index", "Account", null, 
     new { @style="text-transform:capitalize;" });

What's the best way to limit text length of EditText in Android

XML

android:maxLength="10"

Programmatically:

int maxLength = 10;
InputFilter[] filters = new InputFilter[1];
filters[0] = new InputFilter.LengthFilter(maxLength);
yourEditText.setFilters(filters);

Note: internally, EditText & TextView parse the value of android:maxLength in XML and use InputFilter.LengthFilter() to apply it.

See: TextView.java#L1564

How to redirect to Index from another controller?

Tag helpers:

<a asp-controller="OtherController" asp-action="Index" class="btn btn-primary"> Back to Other Controller View </a>

In the controller.cs have a method:

public async Task<IActionResult> Index()
{
    ViewBag.Title = "Titles";
    return View(await Your_Model or Service method);
}

SQL Server: Difference between PARTITION BY and GROUP BY

partition by doesn't actually roll up the data. It allows you to reset something on a per group basis. For example, you can get an ordinal column within a group by partitioning on the grouping field and using rownum() over the rows within that group. This gives you something that behaves a bit like an identity column that resets at the beginning of each group.

Twitter Bootstrap Tabs: Go to Specific Tab on Page Reload or Hyperlink

I just had this issue, but needed to handle multiple tab levels. The code is rather ugly (see comments), but does its job: https://gist.github.com/JensRantil/4721860 Hopefully someone else will find it useful (and feel free to propose better solutions!).

How does the bitwise complement operator (~ tilde) work?

Simply ...........

As 2's complement of any number we can calculate by inverting all 1s to 0's and vice-versa than we add 1 to it..

Here N= ~N produce results -(N+1) always. Because system store data in form of 2's complement which means it stores ~N like this.

  ~N = -(~(~N)+1) =-(N+1). 

For example::

  N = 10  = 1010
  Than ~N  = 0101
  so ~(~N) = 1010
  so ~(~N) +1 = 1011 

Now point is from where Minus comes. My opinion is suppose we have 32 bit register which means 2^31 -1 bit involved in operation and to rest one bit which change in earlier computation(complement) stored as sign bit which is 1 usually. And we get result as ~10 = -11.

~(-11) =10 ;

The above is true if printf("%d",~0); we get result: -1;

But printf("%u",~0) than result: 4294967295 on 32 bit machine.

How to verify a Text present in the loaded page through WebDriver

Note: Not in boolean

WebDriver driver=new FirefoxDriver();
driver.get("http://www.gmail.com");

if(driver.getPageSource().contains("Ur message"))
  {
    System.out.println("Pass");
  }
else
  {
    System.out.println("Fail");
  }

Shortcut key for commenting out lines of Python code in Spyder

  • Unblock multi-line comment

    Ctrl+5

  • Multi-line comment

    Ctrl+4

NOTE: For my version of Spyder (3.1.4) if I highlighted the entire multi-line comment and used Ctrl+5 the block remained commented out. Only after highlighting a small portion of the multi-line comment did Ctrl+5 work.

Java - Writing strings to a CSV file

Answer for this question is good if you want to overwrite your file everytime you rerun your program, but if you want your records to not be lost at rerunning your program, you may want to try this

public void writeAudit(String actionName) {
    String whereWrite = "./csvFiles/audit.csv";

    try {
        FileWriter fw = new FileWriter(whereWrite, true);
        BufferedWriter bw = new BufferedWriter(fw);
        PrintWriter pw = new PrintWriter(bw);

        Date date = new Date();

        pw.println(actionName + "," + date.toString());
        pw.flush();
        pw.close();

    } catch (FileNotFoundException e) {
        System.out.println(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

What throws an IOException in Java?

Java documentation is helpful to know the root cause of a particular IOException.

Just have a look at the direct known sub-interfaces of IOException from the documentation page:

ChangedCharSetException, CharacterCodingException, CharConversionException, ClosedChannelException, EOFException, FileLockInterruptionException, FileNotFoundException, FilerException, FileSystemException, HttpRetryException, IIOException, InterruptedByTimeoutException, InterruptedIOException, InvalidPropertiesFormatException, JMXProviderException, JMXServerErrorException, MalformedURLException, ObjectStreamException, ProtocolException, RemoteException, SaslException, SocketException, SSLException, SyncFailedException, UnknownHostException, UnknownServiceException, UnsupportedDataTypeException, UnsupportedEncodingException, UserPrincipalNotFoundException, UTFDataFormatException, ZipException

Most of these exceptions are self-explanatory.

A few IOExceptions with root causes:

EOFException: Signals that an end of file or end of stream has been reached unexpectedly during input. This exception is mainly used by data input streams to signal the end of the stream.

SocketException: Thrown to indicate that there is an error creating or accessing a Socket.

RemoteException: A RemoteException is the common superclass for a number of communication-related exceptions that may occur during the execution of a remote method call. Each method of a remote interface, an interface that extends java.rmi.Remote, must list RemoteException in its throws clause.

UnknownHostException: Thrown to indicate that the IP address of a host could not be determined (you may not be connected to Internet).

MalformedURLException: Thrown to indicate that a malformed URL has occurred. Either no legal protocol could be found in a specification string or the string could not be parsed.

How to check whether a string contains a substring in Ruby

You can use the include? method:

my_string = "abcdefg"
if my_string.include? "cde"
   puts "String includes 'cde'"
end

Python loop to run for certain amount of seconds

For those using asyncio, an easy way is to use asyncio.wait_for():

async def my_loop():
    res = False
    while not res:
        res = await do_something()

await asyncio.wait_for(my_loop(), 10)

Django download a file

I use this method:

{% if quote.myfile %}
    <div class="">
        <a role="button" 
            href="{{ quote.myfile.url }}"
            download="{{ quote.myfile.url }}"
            class="btn btn-light text-dark ml-0">
            Download attachment
        </a>
    </div>
{% endif %}

org.hibernate.NonUniqueResultException: query did not return a unique result: 2?

Thought this might help to someone, it happens because "When the number of data queries is greater than 1".reference

When is the init() function run?

The init func runs first and then main. It's used for setting something first before your program runs, for example:

Accessing a template, Running the program using all cores, Checking the Goos and arch etc...

top align in html table?

<TABLE COLS="3" border="0" cellspacing="0" cellpadding="0">
    <TR style="vertical-align:top">
        <TD>
            <!-- The log text-box -->
            <div style="height:800px; width:240px; border:1px solid #ccc; font:16px/26px Georgia, Garamond, Serif; overflow:auto;">
                Log:
            </div>
        </TD>
        <TD>
            <!-- The 2nd column -->
        </TD>
        <TD>
            <!-- The 3rd column -->
        </TD>
    </TR>
</TABLE>

Dynamically load a function from a DLL

LoadLibrary does not do what you think it does. It loads the DLL into the memory of the current process, but it does not magically import functions defined in it! This wouldn't be possible, as function calls are resolved by the linker at compile time while LoadLibrary is called at runtime (remember that C++ is a statically typed language).

You need a separate WinAPI function to get the address of dynamically loaded functions: GetProcAddress.

Example

#include <windows.h>
#include <iostream>

/* Define a function pointer for our imported
 * function.
 * This reads as "introduce the new type f_funci as the type: 
 *                pointer to a function returning an int and 
 *                taking no arguments.
 *
 * Make sure to use matching calling convention (__cdecl, __stdcall, ...)
 * with the exported function. __stdcall is the convention used by the WinAPI
 */
typedef int (__stdcall *f_funci)();

int main()
{
  HINSTANCE hGetProcIDDLL = LoadLibrary("C:\\Documents and Settings\\User\\Desktop\\test.dll");

  if (!hGetProcIDDLL) {
    std::cout << "could not load the dynamic library" << std::endl;
    return EXIT_FAILURE;
  }

  // resolve function address here
  f_funci funci = (f_funci)GetProcAddress(hGetProcIDDLL, "funci");
  if (!funci) {
    std::cout << "could not locate the function" << std::endl;
    return EXIT_FAILURE;
  }

  std::cout << "funci() returned " << funci() << std::endl;

  return EXIT_SUCCESS;
}

Also, you should export your function from the DLL correctly. This can be done like this:

int __declspec(dllexport) __stdcall funci() {
   // ...
}

As Lundin notes, it's good practice to free the handle to the library if you don't need them it longer. This will cause it to get unloaded if no other process still holds a handle to the same DLL.

What's the difference between Docker Compose vs. Dockerfile

Dockerfile is a file that contains text commands to assemble an image.

Docker compose is used to run a multi-container environment.

In your specific scenario, if you have multiple services for each technology you mentioned (service 1 using reddis, service 2 using rabbit mq etc), then you can have a Dockerfile for each of the services and a common docker-compose.yml to run all the "Dockerfile" as containers.

If you want them all in a single service, docker-compose will be a viable option.

remove attribute display:none; so the item will be visible

If you are planning to hide show some span based on click event which is initially hidden with style="display:none" then .toggle() is best option to go with.

$("span").toggle();

Reasons : Each time you don't need to check whether the style is already there or not. .toggle() will take care of that automatically and hide/show span based on current state.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="button" value="Toggle" onclick="$('#hiddenSpan').toggle();"/>_x000D_
<br/>_x000D_
<br/>_x000D_
<span id="hiddenSpan" style="display:none">Just toggle me</span>
_x000D_
_x000D_
_x000D_