Programs & Examples On #S60 3rd edition

How do I center floated elements?

Removing floats, and using inline-block may fix your problems:

 .pagination a {
-    display: block;
+    display: inline-block;
     width: 30px;
     height: 30px;
-    float: left;
     margin-left: 3px;
     background: url(/images/structure/pagination-button.png);
 }

(remove the lines starting with - and add the lines starting with +.)

_x000D_
_x000D_
.pagination {_x000D_
  text-align: center;_x000D_
}_x000D_
.pagination a {_x000D_
  + display: inline-block;_x000D_
  width: 30px;_x000D_
  height: 30px;_x000D_
  margin-left: 3px;_x000D_
  background: url(/images/structure/pagination-button.png);_x000D_
}_x000D_
.pagination a.last {_x000D_
  width: 90px;_x000D_
  background: url(/images/structure/pagination-button-last.png);_x000D_
}_x000D_
.pagination a.first {_x000D_
  width: 60px;_x000D_
  background: url(/images/structure/pagination-button-first.png);_x000D_
}
_x000D_
<div class='pagination'>_x000D_
  <a class='first' href='#'>First</a>_x000D_
  <a href='#'>1</a>_x000D_
  <a href='#'>2</a>_x000D_
  <a href='#'>3</a>_x000D_
  <a class='last' href='#'>Last</a>_x000D_
</div>_x000D_
<!-- end: .pagination -->
_x000D_
_x000D_
_x000D_

inline-block works cross-browser, even on IE6 as long as the element is originally an inline element.

Quote from quirksmode:

An inline block is placed inline (ie. on the same line as adjacent content), but it behaves as a block.

this often can effectively replace floats:

The real use of this value is when you want to give an inline element a width. In some circumstances some browsers don't allow a width on a real inline element, but if you switch to display: inline-block you are allowed to set a width.” ( http://www.quirksmode.org/css/display.html#inlineblock ).

From the W3C spec:

[inline-block] causes an element to generate an inline-level block container. The inside of an inline-block is formatted as a block box, and the element itself is formatted as an atomic inline-level box.

How to create a button programmatically?

Add this code in viewDidLoad
//add Button

            var button=UIButton(frame: CGRectMake(150, 240, 75, 30))
            button.setTitle("Next", forState: UIControlState.Normal)
            button.addTarget(self, action: "buttonTapAction:", forControlEvents: UIControlEvents.TouchUpInside)
            button.backgroundColor = UIColor.greenColor()
            self.view.addSubview(button)

Write this function outside it,this will call when you tap on the button

func buttonTapAction(sender:UIButton!)
{
    println("Button is working")
}

BSTR to std::string (std::wstring) and vice versa

There is a c++ class called _bstr_t. It has useful methods and a collection of overloaded operators.

For example, you can easily assign from a const wchar_t * or a const char * just doing _bstr_t bstr = L"My string"; Then you can convert it back doing const wchar_t * s = bstr.operator const wchar_t *();. You can even convert it back to a regular char const char * c = bstr.operator char *(); You can then just use the const wchar_t * or the const char * to initialize a new std::wstring oe std::string.

NodeJS: How to get the server's port?

Express 4.x answer:

Express 4.x (per Tien Do's answer below), now treats app.listen() as an asynchronous operation, so listener.address() will only return data inside of app.listen()'s callback:

var app = require('express')();

var listener = app.listen(8888, function(){
    console.log('Listening on port ' + listener.address().port); //Listening on port 8888
});

Express 3 answer:

I think you are looking for this(express specific?):

console.log("Express server listening on port %d", app.address().port)

You might have seen this(bottom line), when you create directory structure from express command:

alfred@alfred-laptop:~/node$ express test4
   create : test4
   create : test4/app.js
   create : test4/public/images
   create : test4/public/javascripts
   create : test4/logs
   create : test4/pids
   create : test4/public/stylesheets
   create : test4/public/stylesheets/style.less
   create : test4/views/partials
   create : test4/views/layout.jade
   create : test4/views/index.jade
   create : test4/test
   create : test4/test/app.test.js
alfred@alfred-laptop:~/node$ cat test4/app.js 

/**
 * Module dependencies.
 */

var express = require('express');

var app = module.exports = express.createServer();

// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.use(express.bodyDecoder());
  app.use(express.methodOverride());
  app.use(express.compiler({ src: __dirname + '/public', enable: ['less'] }));
  app.use(app.router);
  app.use(express.staticProvider(__dirname + '/public'));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); 
});

app.configure('production', function(){
  app.use(express.errorHandler()); 
});

// Routes

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

// Only listen on $ node app.js

if (!module.parent) {
  app.listen(3000);
  console.log("Express server listening on port %d", app.address().port)
}

Formatting Phone Numbers in PHP

Try something like:

preg_replace('/\d{3}/', '$0-', str_replace('.', null, trim($number)), 2);

this would take a $number of 8881112222 and convert to 888-111-2222. Hope this helps.

How to shrink/purge ibdata1 file in MySQL

If you use the InnoDB storage engine for (some of) your MySQL tables, you’ve probably already came across a problem with its default configuration. As you may have noticed in your MySQL’s data directory (in Debian/Ubuntu – /var/lib/mysql) lies a file called ‘ibdata1'. It holds almost all the InnoDB data (it’s not a transaction log) of the MySQL instance and could get quite big. By default this file has a initial size of 10Mb and it automatically extends. Unfortunately, by design InnoDB data files cannot be shrinked. That’s why DELETEs, TRUNCATEs, DROPs, etc. will not reclaim the space used by the file.

I think you can find good explanation and solution there :

http://vdachev.net/2007/02/22/mysql-reducing-ibdata1/

Resolve absolute path from relative path and/or file name

You can just concatenate them.

SET ABS_PATH=%~dp0 
SET REL_PATH=..\SomeFile.txt
SET COMBINED_PATH=%ABS_PATH%%REL_PATH%

it looks odd with \..\ in the middle of your path but it works. No need to do anything crazy :)

'Field required a bean of type that could not be found.' error spring restful API using mongodb

I had the same issue. My mistake was that I used @Service annotation on the Service Interface. The @Service annotation should be applied to the ServiceImpl class.

@UniqueConstraint and @Column(unique = true) in hibernate annotation

In addition to Boaz's answer ....

@UniqueConstraint allows you to name the constraint, while @Column(unique = true) generates a random name (e.g. UK_3u5h7y36qqa13y3mauc5xxayq).

Sometimes it can be helpful to know what table a constraint is associated with. E.g.:

@Table(
   name = "product_serial_group_mask", 
   uniqueConstraints = {
      @UniqueConstraint(
          columnNames = {"mask", "group"},
          name="uk_product_serial_group_mask"
      )
   }
)

Delete rows with blank values in one particular column

It is the same construct - simply test for empty strings rather than NA:

Try this:

df <- df[-which(df$start_pc == ""), ]

In fact, looking at your code, you don't need the which, but use the negation instead, so you can simplify it to:

df <- df[!(df$start_pc == ""), ]
df <- df[!is.na(df$start_pc), ]

And, of course, you can combine these two statements as follows:

df <- df[!(df$start_pc == "" | is.na(df$start_pc)), ]

And simplify it even further with with:

df <- with(df, df[!(start_pc == "" | is.na(start_pc)), ])

You can also test for non-zero string length using nzchar.

df <- with(df, df[!(nzchar(start_pc) | is.na(start_pc)), ])

Disclaimer: I didn't test any of this code. Please let me know if there are syntax errors anywhere

Converting of Uri to String

String to Uri

Uri myUri = Uri.parse("https://www.google.com");

Uri to String

Uri uri;
String stringUri = uri.toString();

Why are the Level.FINE logging messages not showing?

Loggers only log the message, i.e. they create the log records (or logging requests). They do not publish the messages to the destinations, which is taken care of by the Handlers. Setting the level of a logger, only causes it to create log records matching that level or higher.

You might be using a ConsoleHandler (I couldn't infer where your output is System.err or a file, but I would assume that it is the former), which defaults to publishing log records of the level Level.INFO. You will have to configure this handler, to publish log records of level Level.FINER and higher, for the desired outcome.

I would recommend reading the Java Logging Overview guide, in order to understand the underlying design. The guide covers the difference between the concept of a Logger and a Handler.

Editing the handler level

1. Using the Configuration file

The java.util.logging properties file (by default, this is the logging.properties file in JRE_HOME/lib) can be modified to change the default level of the ConsoleHandler:

java.util.logging.ConsoleHandler.level = FINER

2. Creating handlers at runtime

This is not recommended, for it would result in overriding the global configuration. Using this throughout your code base will result in a possibly unmanageable logger configuration.

Handler consoleHandler = new ConsoleHandler();
consoleHandler.setLevel(Level.FINER);
Logger.getAnonymousLogger().addHandler(consoleHandler);

How do you use Intent.FLAG_ACTIVITY_CLEAR_TOP to clear the Activity Stack?

@bitestar has the correct solution, but there is one more step:

It was hidden away in the docs, however you must change the launchMode of the Activity to anything other than standard. Otherwise it will be destroyed and recreated instead of being reset to the top.

sudo echo "something" >> /etc/privilegedFile doesn't work

How about:
echo text | sudo dd status=none of=privilegedfile
I want to change /proc/sys/net/ipv4/tcp_rmem.
I did:
sudo dd status=none of=/proc/sys/net/ipv4/tcp_rmem <<<"4096 131072 1024000"
eliminates the echo with a single line document

Convert HTML string to image

Thanks all for your responses. I used HtmlRenderer external dll (library) to achieve the same and found below code for the same.

Here is the code for this

public void ConvertHtmlToImage()
{
   Bitmap m_Bitmap = new Bitmap(400, 600);
   PointF point = new PointF(0, 0);
   SizeF maxSize = new System.Drawing.SizeF(500, 500);
   HtmlRenderer.HtmlRender.Render(Graphics.FromImage(m_Bitmap),
                                           "<html><body><p>This is some html code</p>"
                                           + "<p>This is another html line</p></body>",
                                            point, maxSize);

   m_Bitmap.Save(@"C:\Test.png", ImageFormat.Png);
}

Creating a REST API using PHP

In your example, it’s fine as it is: it’s simple and works. The only things I’d suggest are:

  1. validating the data POSTed
  2. make sure your API is sending the Content-Type header to tell the client to expect a JSON response:

    header('Content-Type: application/json');
    echo json_encode($response);
    

Other than that, an API is something that takes an input and provides an output. It’s possible to “over-engineer” things, in that you make things more complicated that need be.

If you wanted to go down the route of controllers and models, then read up on the MVC pattern and work out how your domain objects fit into it. Looking at the above example, I can see maybe a MathController with an add() action/method.

There are a few starting point projects for RESTful APIs on GitHub that are worth a look.

Exchange Powershell - How to invoke Exchange 2010 module from inside script?

import-module Microsoft.Exchange.Management.PowerShell.E2010aTry with some implementation like:

$exchangeser = "MTLServer01"
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionURI http://${exchangeserver}/powershell/ -Authentication kerberos
import-PSSession $session 

or

add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010

How to determine the version of Gradle?

Option 1- From Studio

In Android Studio, go to File > Project Structure. Then select the "project" tab on the left.

Your Gradle version will be displayed here.

Option 2- gradle-wrapper.properties

If you are using the Gradle wrapper, then your project will have a gradle/wrapper/gradle-wrapper.properties folder.

This file should contain a line like this:

distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip

This determines which version of Gradle you are using. In this case, gradle-2.2.1-all.zip means I am using Gradle 2.2.1.

Option 3- Local Gradle distribution

If you are using a version of Gradle installed on your system instead of the wrapper, you can run gradle --version to check.

How can I mimic the bottom sheet from the Maps app?

I don't know how exactly the bottom sheet of the new Maps app, responds to user interactions. But you can create a custom view that looks like the one in the screenshots and add it to the main view.

I assume you know how to:

1- create view controllers either by storyboards or using xib files.

2- use googleMaps or Apple's MapKit.

Example

1- Create 2 view controllers e.g, MapViewController and BottomSheetViewController. The first controller will host the map and the second is the bottom sheet itself.

Configure MapViewController

Create a method to add the bottom sheet view.

func addBottomSheetView() {
    // 1- Init bottomSheetVC
    let bottomSheetVC = BottomSheetViewController()

    // 2- Add bottomSheetVC as a child view 
    self.addChildViewController(bottomSheetVC)
    self.view.addSubview(bottomSheetVC.view)
    bottomSheetVC.didMoveToParentViewController(self)

    // 3- Adjust bottomSheet frame and initial position.
    let height = view.frame.height
    let width  = view.frame.width
    bottomSheetVC.view.frame = CGRectMake(0, self.view.frame.maxY, width, height)
}

And call it in viewDidAppear method:

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    addBottomSheetView()
}

Configure BottomSheetViewController

1) Prepare background

Create a method to add blur and vibrancy effects

func prepareBackgroundView(){
    let blurEffect = UIBlurEffect.init(style: .Dark)
    let visualEffect = UIVisualEffectView.init(effect: blurEffect)
    let bluredView = UIVisualEffectView.init(effect: blurEffect)
    bluredView.contentView.addSubview(visualEffect)

    visualEffect.frame = UIScreen.mainScreen().bounds
    bluredView.frame = UIScreen.mainScreen().bounds

    view.insertSubview(bluredView, atIndex: 0)
}

call this method in your viewWillAppear

override func viewWillAppear(animated: Bool) {
   super.viewWillAppear(animated)
   prepareBackgroundView()
}

Make sure that your controller's view background color is clearColor.

2) Animate bottomSheet appearance

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    UIView.animateWithDuration(0.3) { [weak self] in
        let frame = self?.view.frame
        let yComponent = UIScreen.mainScreen().bounds.height - 200
        self?.view.frame = CGRectMake(0, yComponent, frame!.width, frame!.height)
    }
}

3) Modify your xib as you want.

4) Add Pan Gesture Recognizer to your view.

In your viewDidLoad method add UIPanGestureRecognizer.

override func viewDidLoad() {
    super.viewDidLoad()

    let gesture = UIPanGestureRecognizer.init(target: self, action: #selector(BottomSheetViewController.panGesture))
    view.addGestureRecognizer(gesture)

}

And implement your gesture behaviour:

func panGesture(recognizer: UIPanGestureRecognizer) {
    let translation = recognizer.translationInView(self.view)
    let y = self.view.frame.minY
    self.view.frame = CGRectMake(0, y + translation.y, view.frame.width, view.frame.height)
     recognizer.setTranslation(CGPointZero, inView: self.view)
}

Scrollable Bottom Sheet:

If your custom view is a scroll view or any other view that inherits from, so you have two options:

First:

Design the view with a header view and add the panGesture to the header. (bad user experience).

Second:

1 - Add the panGesture to the bottom sheet view.

2 - Implement the UIGestureRecognizerDelegate and set the panGesture delegate to the controller.

3- Implement shouldRecognizeSimultaneouslyWith delegate function and disable the scrollView isScrollEnabled property in two case:

  • The view is partially visible.
  • The view is totally visible, the scrollView contentOffset property is 0 and the user is dragging the view downwards.

Otherwise enable scrolling.

  func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
      let gesture = (gestureRecognizer as! UIPanGestureRecognizer)
      let direction = gesture.velocity(in: view).y

      let y = view.frame.minY
      if (y == fullView && tableView.contentOffset.y == 0 && direction > 0) || (y == partialView) {
          tableView.isScrollEnabled = false
      } else {
        tableView.isScrollEnabled = true
      }

      return false
  }

NOTE

In case you set .allowUserInteraction as an animation option, like in the sample project, so you need to enable scrolling on the animation completion closure if the user is scrolling up.

Sample Project

I created a sample project with more options on this repo which may give you better insights about how to customise the flow.

In the demo, addBottomSheetView() function controls which view should be used as a bottom sheet.

Sample Project Screenshots

- Partial View

enter image description here

- FullView

enter image description here

- Scrollable View

enter image description here

Visual Studio keyboard shortcut to automatically add the needed 'using' statement

Alt + Shift + F10 will show the menu associated with the smart tag.

Casting a number to a string in TypeScript

const page_number = 3;

window.location.hash = page_number as string; // Error

"Conversion of type 'number' to type 'string' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first." -> You will get this error if you try to typecast number to string. So, first convert it to unknown and then to string.

window.location.hash = (page_number as unknown) as string; // Correct way

How to do while loops with multiple conditions

Have you noticed that in the code you posted, condition2 is never set to False? This way, your loop body is never executed.

Also, note that in Python, not condition is preferred to condition == False; likewise, condition is preferred to condition == True.

How can I hide an HTML table row <tr> so that it takes up no space?

You can use style display:none with tr to hide and it will work with all browsers.

Could not find method compile() for arguments Gradle

Hope Below steps will help

Add the dependency to your project-level build.gradle:

classpath 'com.google.gms:google-services:3.0.0'

Add the plugin to your app-level build.gradle:

apply plugin: 'com.google.gms.google-services'

app-level build.gradle:

dependencies {
        compile 'com.google.android.gms:play-services-auth:9.8.0'
}

Get css top value as number not as string?

You can use the parseInt() function to convert the string to a number, e.g:

parseInt($('#elem').css('top'));

Update: (as suggested by Ben): You should give the radix too:

parseInt($('#elem').css('top'), 10);

Forces it to be parsed as a decimal number, otherwise strings beginning with '0' might be parsed as an octal number (might depend on the browser used).

How do you upload a file to a document library in sharepoint?

You can upload documents to SharePoint libraries using the Object Model or SharePoint Webservices.

Upload using Object Model:

String fileToUpload = @"C:\YourFile.txt";
String sharePointSite = "http://yoursite.com/sites/Research/";
String documentLibraryName = "Shared Documents";

using (SPSite oSite = new SPSite(sharePointSite))
{
    using (SPWeb oWeb = oSite.OpenWeb())
    {
        if (!System.IO.File.Exists(fileToUpload))
            throw new FileNotFoundException("File not found.", fileToUpload);                    

        SPFolder myLibrary = oWeb.Folders[documentLibraryName];

        // Prepare to upload
        Boolean replaceExistingFiles = true;
        String fileName = System.IO.Path.GetFileName(fileToUpload);
        FileStream fileStream = File.OpenRead(fileToUpload);

        // Upload document
        SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);

        // Commit 
        myLibrary.Update();
    }
}

How to get the sign, mantissa and exponent of a floating point number

You're &ing the wrong bits. I think you want:

s = *ptr >> 31;
e = *ptr & 0x7f800000;
e >>= 23;
m = *ptr & 0x007fffff;

Remember, when you &, you are zeroing out bits that you don't set. So in this case, you want to zero out the sign bit when you get the exponent, and you want to zero out the sign bit and the exponent when you get the mantissa.

Note that the masks come directly from your picture. So, the exponent mask will look like:

0 11111111 00000000000000000000000

and the mantissa mask will look like:

0 00000000 11111111111111111111111

C# static class why use?

Static classes can be useful in certain situations, but there is a potential to abuse and/or overuse them, like most language features.

As Dylan Smith already mentioned, the most obvious case for using a static class is if you have a class with only static methods. There is no point in allowing developers to instantiate such a class.

The caveat is that an overabundance of static methods may itself indicate a flaw in your design strategy. I find that when you are creating a static function, its a good to ask yourself -- would it be better suited as either a) an instance method, or b) an extension method to an interface. The idea here is that object behaviors are usually associated with object state, meaning the behavior should belong to the object. By using a static function you are implying that the behavior shouldn't belong to any particular object.

Polymorphic and interface driven design are hindered by overusing static functions -- they cannot be overriden in derived classes nor can they be attached to an interface. Its usually better to have your 'helper' functions tied to an interface via an extension method such that all instances of the interface have access to that shared 'helper' functionality.

One situation where static functions are definitely useful, in my opinion, is in creating a .Create() or .New() method to implement logic for object creation, for instance when you want to proxy the object being created,

public class Foo
{
    public static Foo New(string fooString)
    {
        ProxyGenerator generator = new ProxyGenerator();

        return (Foo)generator.CreateClassProxy
             (typeof(Foo), new object[] { fooString }, new Interceptor()); 
    }

This can be used with a proxying framework (like Castle Dynamic Proxy) where you want to intercept / inject functionality into an object, based on say, certain attributes assigned to its methods. The overall idea is that you need a special constructor because technically you are creating a copy of the original instance with special added functionality.

How to uncheck checked radio button

This simple script allows you to uncheck an already checked radio button. Works on all javascript enabled browsers.

_x000D_
_x000D_
var allRadios = document.getElementsByName('re');_x000D_
var booRadio;_x000D_
var x = 0;_x000D_
for(x = 0; x < allRadios.length; x++){_x000D_
  allRadios[x].onclick = function() {_x000D_
    if(booRadio == this){_x000D_
      this.checked = false;_x000D_
      booRadio = null;_x000D_
    } else {_x000D_
      booRadio = this;_x000D_
    }_x000D_
  };_x000D_
}
_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>
_x000D_
_x000D_
_x000D_

How to pass multiple parameters in json format to a web service using jquery?

Found the solution:

It should be:

"{'Id1':'2','Id2':'2'}"

and not

"{'Id1':'2'},{'Id2':'2'}"

How do you detect the clearing of a "search" HTML5 input?

It made sense to me that clicking the X should count as a change event. I already had the onChange event all setup to do what I needed it to do. So for me, the fix was to simply do this jQuery line:

$('#search').click(function(){ $(this).change(); });

jQuery AJAX Character Encoding

If you are using CodeIgniter you can solve this by adding the following code to your Controller before loading any Views (assuming you have charsetproperly set on your config. If not, just put charset=whateveryouwant.

$this->output->set_header('Content-type: text/html; charset='.$this->config->item('charset'));

The way I did it was to add that line to the constructor of MY_Controller, my superclass for all Controllers, this way I make sure I will have no encoding problems anywhere.

By the way, this doesn't affect JSON returns (which are encoded in UTF-8).

Force HTML5 youtube video

If you're using the iframe embed api, you can put html5:1 as one of the playerVars arguments, like so:

player = new YT.Player('player', {
    height: '390',
    width: '640',
    videoId: '<VIDEO ID>',
    playerVars: {
        html5: 1
    },
});

Totally works.

Android emulator doesn't take keyboard input - SDK tools rev 20

Restarting the emulator helps sometimes when typing is unavailable - despite keyboard input being enabled for your Android Virtual Device.

Pass a PHP string to a JavaScript variable (and escape newlines)

function escapeJavaScriptText($string)
{
    return str_replace("\n", '\n', str_replace('"', '\"', addcslashes(str_replace("\r", '', (string)$string), "\0..\37'\\")));
}

Filter values only if not null using lambda in Java8

you can use this

List<Car> requiredCars = cars.stream()
    .filter (t->  t!= null && StringUtils.startsWith(t.getName(),"M"))
    .collect(Collectors.toList());

Get year, month or day from numpy datetime64

Anon's answer works great for me, but I just need to modify the statement for days

from:

days = dates - dates.astype('datetime64[M]') + 1

to:

days = dates.astype('datetime64[D]') - dates.astype('datetime64[M]') + 1

Opening a new tab to read a PDF file

You have to use target attribute

<a href="newsletter_01.pdf" target="_blank">

Why did a network-related or instance-specific error occur while establishing a connection to SQL Server?

check forthe followings :

Make sure your database engine is configured to accept remote connections

• Start > All Programs > SQL Server 2005 > Configuration Tools > SQL Server Surface Area Configuration • Click on Surface Area Configuration for Services and Connections • Select the instance that is having a problem > Database Engine > Remote Connections • Enable local and remote connections • Restart instance

  1. Check the SQL Server service account

• If you are not using a domain account as a service account (for example if you are using NETWORK SERVICE), you may want to switch this first before proceeding

  1. If you are using a named SQL Server instance, make sure you are using that instance name in your connection strings in your ASweb P.NET application

• Usually the format needed to specify the database server is machinename\instancename • Check your connection string as well

Update div with jQuery ajax response html

You are setting the html of #showresults of whatever data is, and then replacing it with itself, which doesn't make much sense ?
I'm guessing you where really trying to find #showresults in the returned data, and then update the #showresults element in the DOM with the html from the one from the ajax call :

$('#submitform').click(function () {
    $.ajax({
        url: "getinfo.asp",
        data: {
            txtsearch: $('#appendedInputButton').val()
        },
        type: "GET",
        dataType: "html",
        success: function (data) {
            var result = $('<div />').append(data).find('#showresults').html();
            $('#showresults').html(result);
        },
        error: function (xhr, status) {
            alert("Sorry, there was a problem!");
        },
        complete: function (xhr, status) {
            //$('#showresults').slideDown('slow')
        }
    });
});

Html5 Full screen video

You can use html5 video player which has full screen playback option. This is a very good html5 player to have a look.
http://sublimevideo.net/

Select from where field not equal to Mysql Php

select * from table where fiels1 NOT LIKE 'x' AND field2 NOT LIKE 'y'

//this work in case insensitive manner

What's the difference between nohup and ampersand

nohup catches the hangup signal (see man 7 signal) while the ampersand doesn't (except the shell is confgured that way or doesn't send SIGHUP at all).

Normally, when running a command using & and exiting the shell afterwards, the shell will terminate the sub-command with the hangup signal (kill -SIGHUP <pid>). This can be prevented using nohup, as it catches the signal and ignores it so that it never reaches the actual application.

In case you're using bash, you can use the command shopt | grep hupon to find out whether your shell sends SIGHUP to its child processes or not. If it is off, processes won't be terminated, as it seems to be the case for you. More information on how bash terminates applications can be found here.

There are cases where nohup does not work, for example when the process you start reconnects the SIGHUP signal, as it is the case here.

What does "Object reference not set to an instance of an object" mean?

Not to be blunt but it means exactly what it says. One of your object references is NULL. You'll see this when you try and access the property or method of a NULL'd object.

ASP.NET jQuery Ajax Calling Code-Behind Method

This hasn't solved my problem too, so I changed the parameters slightly.
This code worked for me:

var dataValue = "{ name: 'person', isGoing: 'true', returnAddress: 'returnEmail' }";

$.ajax({
    type: "POST",
    url: "Default.aspx/OnSubmit",
    data: dataValue,
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
    },
    success: function (result) {
        alert("We returned: " + result.d);
    }
});

How to get column values in one comma separated value

For Mysql:

SELECT t.user, 

(SELECT GROUP_CONCAT( t1.department ) FROM table_name t1 WHERE t1.user = t.user)department

FROM table_name t
GROUP BY t.user
LIMIT 0 , 30

Configuring angularjs with eclipse IDE

You'd first wanna make sure you have the JSDT installed.

Next thing is to install some dedicated tools for the job, so check out AngularJS Eclipse Tools. The AngularJS Eclipse Templates might be of help, too, and here's a visual guide written for it to get you started.

Also see the AngularJS Eclipse getting started page.


Since this answer had been posted, the AngularJS Eclipse plugin was released, as other answers stated. You might wanna check it out first.

push() a two-dimensional array

var r = 3; //start from rows 3
var c = 5; //start from col 5

var rows = 8;

var cols = 7;


for (var i = 0; i < rows; i++)

{

 for (var j = 0; j < cols; j++)

 {
    if(j <= c && i <= r) {
      myArray[i][j] = 1;
    } else {
      myArray[i][j] = 0;
    }
}

}

How can I refresh or reload the JFrame?

You should use this code

this.setVisible(false); //this will close frame i.e. NewJFrame

new NewJFrame().setVisible(true); // Now this will open NewJFrame for you again and will also get refreshed 

How to get text from EditText?

Put this in your MainActivity:

{
    public EditText bizname, storeno, rcpt, item, price, tax, total;
    public Button click, click2;
    int contentView;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.main_activity );
        bizname = (EditText) findViewById( R.id.editBizName );
        item = (EditText) findViewById( R.id.editItem );
        price = (EditText) findViewById( R.id.editPrice );
        tax = (EditText) findViewById( R.id.editTax );
        total = (EditText) findViewById( R.id.editTotal );
        click = (Button) findViewById( R.id.button );
    }
}

Put this under a button or something

public void clickBusiness(View view) {
    checkPermsOfStorage( this );

    bizname = (EditText) findViewById( R.id.editBizName );
    item = (EditText) findViewById( R.id.editItem );
    price = (EditText) findViewById( R.id.editPrice );
    tax = (EditText) findViewById( R.id.editTax );
    total = (EditText) findViewById( R.id.editTotal );
    String x = ("\nItem/Price: " + item.getText() + price.getText() + "\nTax/Total" + tax.getText() + total.getText());
    Toast.makeText( this, x, Toast.LENGTH_SHORT ).show();
    try {
        this.WriteBusiness(bizname,storeno,rcpt,item,price,tax,total);
        String vv = tax.getText().toString();
        System.console().printf( "%s", vv );
        //new XMLDivisionWriter(getString(R.string.SDDoc) + "/tax_div_business.xml");
    } catch (ReflectiveOperationException e) {
        e.printStackTrace();
    }
}

There! The debate is settled!

How do I get whole and fractional parts from double in JSP/Java?

double value = 3.25;
double fractionalPart = value % 1;
double integralPart = value - fractionalPart;

Find Nth occurrence of a character in a string

public int GetNthIndex(string s, char t, int n)
{
    int count = 0;
    for (int i = 0; i < s.Length; i++)
    {
        if (s[i] == t)
        {
            count++;
            if (count == n)
            {
                return i;
            }
        }
    }
    return -1;
}

That could be made a lot cleaner, and there are no checks on the input.

Adding one day to a date

Since you already have an answer to what's wrong with your code, I can bring another perspective on how you can play with datetimes generally, and solve your problem specifically.

Oftentimes you find yourself posing a problem in terms of solution. This is just one of the reasons you end up with an imperative code. It's great if it works though; there are just other, arguably more maintainable alternatives. One of them is a declarative code. The point is asking what you need, instead of how to get there.

In your particular case, this can look like the following. First, you need to find out what is it that you're looking for, that is, discover abstractions. In your case, it looks like you need a date. Not just any date, but the one having some standard representation. Say, ISO8601 date. There are at least two implementations: the first one is a date parsed from an ISO8601-formatted string (or a string in any other format actually), and the second is some future date which is a day later. Thus, the whole code could look like that:

(new Future(
    new DateTimeParsedFromISO8601('2009-09-30 20:24:00'),
    new OneDay()
))
    ->value();

For more examples with datetime juggling check out this one.

How to pass a form input value into a JavaScript function

There are several ways to approach this. Personally, I would avoid in-line scripting. Since you've tagged jQuery, let's use that.

HTML:

<form>
    <input type="text" id="formValueId" name="valueId"/>
    <input type="button" id="myButton" />
</form>

JavaScript:

$(document).ready(function() {
    $('#myButton').click(function() {
      foo($('#formValueId').val());
    });
});

Hadoop/Hive : Loading data from .csv on a local machine

You can load local CSV file to Hive only if:

  1. You are doing it from one of the Hive cluster nodes.
  2. You installed Hive client on non-cluster node and using hive or beeline for upload.

Remove Identity from a column in a table

I just had this same problem. 4 statements in SSMS instead of using the GUI and it was very fast.

  • Make a new column

    alter table users add newusernum int;

  • Copy values over

    update users set newusernum=usernum;

  • Drop the old column

    alter table users drop column usernum;

  • Rename the new column to the old column name

    EXEC sp_RENAME 'users.newusernum' , 'usernum', 'COLUMN';

How can I remove the last character of a string in python?

No need to use expensive regex, if barely needed then try- Use r'(/)(?=$)' pattern that is capture last / and replace with r'' i.e. blank character.

>>>re.sub(r'(/)(?=$)',r'','/home/ro/A_Python_Scripts/flask-auto/myDirectory/scarlett Johanson/1448543562.17.jpg/')
>>>'/home/ro/A_Python_Scripts/flask-auto/myDirectory/scarlett Johanson/1448543562.17.jpg'

run program in Python shell

From the same folder, you can do:

import test

Block direct access to a file over http but allow php script access

That is how I prevented direct access from URL to my ini files. Paste the following code in .htaccess file on root. (no need to create extra folder)

<Files ~ "\.ini$">
  Order allow,deny
  Deny from all
</Files>

my settings.ini file is on the root, and without this code is accessible www.mydomain.com/settings.ini

How to get a path to the desktop for current user in C#?

// Environment.GetFolderPath
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); // Current User's Application Data
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); // All User's Application Data
Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles); // Program Files
Environment.GetFolderPath(Environment.SpecialFolder.Cookies); // Internet Cookie
Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // Logical Desktop
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); // Physical Desktop
Environment.GetFolderPath(Environment.SpecialFolder.Favorites); // Favorites
Environment.GetFolderPath(Environment.SpecialFolder.History); // Internet History
Environment.GetFolderPath(Environment.SpecialFolder.InternetCache); // Internet Cache
Environment.GetFolderPath(Environment.SpecialFolder.MyComputer); // "My Computer" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // "My Documents" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyMusic); // "My Music" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); // "My Pictures" Folder
Environment.GetFolderPath(Environment.SpecialFolder.Personal); // "My Document" Folder
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); // Program files Folder
Environment.GetFolderPath(Environment.SpecialFolder.Programs); // Programs Folder
Environment.GetFolderPath(Environment.SpecialFolder.Recent); // Recent Folder
Environment.GetFolderPath(Environment.SpecialFolder.SendTo); // "Sent to" Folder
Environment.GetFolderPath(Environment.SpecialFolder.StartMenu); // Start Menu
Environment.GetFolderPath(Environment.SpecialFolder.Startup); // Startup
Environment.GetFolderPath(Environment.SpecialFolder.System); // System Folder
Environment.GetFolderPath(Environment.SpecialFolder.Templates); // Document Templates

Cannot install NodeJs: /usr/bin/env: node: No such file or directory

For me the accepted answer did not yet work. I started off as suggested here:

ln -s /usr/bin/nodejs /usr/bin/node

After doing this I was getting the following error:

/usr/local/lib/node_modules/npm/bin/npm-cli.js:85 let notifier = require('update-notifier')({pkg}) ^^^

SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode at exports.runInThisContext (vm.js:53:16) at Module._compile (module.js:374:25) at Object.Module._extensions..js (module.js:417:10) at Module.load (module.js:344:32) at Function.Module._load (module.js:301:12) at Function.Module.runMain (module.js:442:10) at startup (node.js:136:18) at node.js:966:3

The solution was to download the most recent version of node from https://nodejs.org/en/download/ .

Then I did:

sudo tar -xf node-v10.15.0-linux-x64.tar.xz --directory /usr/local --strip-components 1

Now the update was finally successful: npm -v changed from 3.2.1 to 6.4.1

Do I need <class> elements in persistence.xml?

It's not a solution but a hint for those using Spring:

I tried to use org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean with setting persistenceXmlLocation but with this I had to provide the <class> elements (even if the persistenceXmlLocation just pointed to META-INF/persistence.xml).

When not using persistenceXmlLocation I could omit these <class> elements.

Scatter plot and Color mapping in Python

To add to wflynny's answer above, you can find the available colormaps here

Example:

import matplotlib.cm as cm
plt.scatter(x, y, c=t, cmap=cm.jet)

or alternatively,

plt.scatter(x, y, c=t, cmap='jet')

oracle varchar to number

If you want formated number then use

SELECT TO_CHAR(number, 'fmt')
   FROM DUAL;

SELECT TO_CHAR('123', 999.99)
   FROM DUAL;

Result 123.00

Whats the CSS to make something go to the next line in the page?

Have the element display as a block:

display: block;

How can I erase all inline styles with javascript and leave only the styles specified in the css style sheet?

$('div').attr('style', '');

or

$('div').removeAttr('style'); (From Andres's Answer)

To make this a little smaller, try this:

$('div[style]').removeAttr('style');

This should speed it up a little because it checks that the divs have the style attribute.

Either way, this might take a little while to process if you have a large amount of divs, so you might want to consider other methods than javascript.

How to retrieve all keys (or values) from a std::map and put them into a vector?

Here's a nice function template using C++11 magic, working for both std::map, std::unordered_map:

template<template <typename...> class MAP, class KEY, class VALUE>
std::vector<KEY>
keys(const MAP<KEY, VALUE>& map)
{
    std::vector<KEY> result;
    result.reserve(map.size());
    for(const auto& it : map){
        result.emplace_back(it.first);
    }
    return result;
}

Check it out here: http://ideone.com/lYBzpL

Scroll to the top of the page using JavaScript?

You can use javascript's built in function scrollTo:

_x000D_
_x000D_
function scroll() {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  });
}
_x000D_
<button onclick="scroll">Scroll</button>
_x000D_
_x000D_
_x000D_

Hidden Columns in jqGrid

I just want to expand on queen3's suggestion, applying the following does the trick:

editoptions: { 
              dataInit: function(element) { 
                          $(element).attr("readonly", "readonly"); 
                        } 
             }

Scenario #1:

  • Field must be visible in the grid
  • Field must be visible in the form
  • Field must be read-only

Solution:

colModel:[
        {  name:'providerUserId',
               index:'providerUserId', 
               width:100,editable:true, 
               editrules:{required:true}, 
               editoptions:{ 
                            dataInit: function(element) { 
                                  jq(element).attr("readonly", "readonly"); 
                             } 
                           }
            },
],

The providerUserId is visible in the grid and visible when editing the form. But you cannot edit the contents.


Scenario #2:

  • Field must not be visible in the grid
  • Field must be visible in the form
  • Field must be read-only

Solution:

colModel:[
           {name:'providerUserId',
            index:'providerUserId', 
            width:100,editable:true, 
            editrules:{
                         required:true, 
                         edithidden:true
                      },
            hidden:true, 
            editoptions:{ 
                  dataInit: function(element) {                     
                             jq(element).attr("readonly", "readonly"); 
                          } 
                     }
         },
        ]

Notice in both instances I'm using jq to reference jquery, instead of the usual $. In my HTML I have the following script to modify the variable used by jQuery:

<script type="text/javascript">
    var jq = jQuery.noConflict();
</script>

Getting started with Haskell

I'm going to order this guide by the level of skill you have in Haskell, going from an absolute beginner right up to an expert. Note that this process will take many months (years?), so it is rather long.

Absolute Beginner

Firstly, Haskell is capable of anything, with enough skill. It is very fast (behind only C and C++ in my experience), and can be used for anything from simulations to servers, guis and web applications.

However there are some problems that are easier to write for a beginner in Haskell than others. Mathematical problems and list process programs are good candidates for this, as they only require the most basic of Haskell knowledge to be able to write.

Some good guides to learning the very basics of Haskell are the Happy Learn Haskell Tutorial and the first 6 chapters of Learn You a Haskell for Great Good (or its JupyterLab adaptation). While reading these, it is a very good idea to also be solving simple problems with what you know.

Another two good resources are Haskell Programming from first principles, and Programming in Haskell. They both come with exercises for each chapter, so you have small simple problems matching what you learned on the last few pages.

A good list of problems to try is the haskell 99 problems page. These start off very basic, and get more difficult as you go on. It is very good practice doing a lot of those, as they let you practice your skills in recursion and higher order functions. I would recommend skipping any problems that require randomness as that is a bit more difficult in Haskell. Check this SO question in case you want to test your solutions with QuickCheck (see Intermediate below).

Once you have done a few of those, you could move on to doing a few of the Project Euler problems. These are sorted by how many people have completed them, which is a fairly good indication of difficulty. These test your logic and Haskell more than the previous problems, but you should still be able to do the first few. A big advantage Haskell has with these problems is Integers aren't limited in size. To complete some of these problems, it will be useful to have read chapters 7 and 8 of learn you a Haskell as well.

Beginner

After that you should have a fairly good handle on recursion and higher order functions, so it would be a good time to start doing some more real world problems. A very good place to start is Real World Haskell (online book, you can also purchase a hard copy). I found the first few chapters introduced too much too quickly for someone who has never done functional programming/used recursion before. However with the practice you would have had from doing the previous problems you should find it perfectly understandable.

Working through the problems in the book is a great way of learning how to manage abstractions and building reusable components in Haskell. This is vital for people used to object-orientated (oo) programming, as the normal oo abstraction methods (oo classes) don't appear in Haskell (Haskell has type classes, but they are very different to oo classes, more like oo interfaces). I don't think it is a good idea to skip chapters, as each introduces a lot new ideas that are used in later chapters.

After a while you will get to chapter 14, the dreaded monads chapter (dum dum dummmm). Almost everyone who learns Haskell has trouble understanding monads, due to how abstract the concept is. I can't think of any concept in another language that is as abstract as monads are in functional programming. Monads allows many ideas (such as IO operations, computations that might fail, parsing,...) to be unified under one idea. So don't feel discouraged if after reading the monads chapter you don't really understand them. I found it useful to read many different explanations of monads; each one gives a new perspective on the problem. Here is a very good list of monad tutorials. I highly recommend the All About Monads, but the others are also good.

Also, it takes a while for the concepts to truly sink in. This comes through use, but also through time. I find that sometimes sleeping on a problem helps more than anything else! Eventually, the idea will click, and you will wonder why you struggled to understand a concept that in reality is incredibly simple. It is awesome when this happens, and when it does, you might find Haskell to be your favorite imperative programming language :)

To make sure that you are understanding Haskell type system perfectly, you should try to solve 20 intermediate haskell exercises. Those exercises using fun names of functions like "furry" and "banana" and helps you to have a good understanding of some basic functional programming concepts if you don't have them already. Nice way to spend your evening with a bunch of papers covered with arrows, unicorns, sausages and furry bananas.

Intermediate

Once you understand Monads, I think you have made the transition from a beginner Haskell programmer to an intermediate haskeller. So where to go from here? The first thing I would recommend (if you haven't already learnt them from learning monads) is the various types of monads, such as Reader, Writer and State. Again, Real world Haskell and All about monads gives great coverage of this. To complete your monad training learning about monad transformers is a must. These let you combine different types of Monads (such as a Reader and State monad) into one. This may seem useless to begin with, but after using them for a while you will wonder how you lived without them.

Now you can finish the real world Haskell book if you want. Skipping chapters now doesn't really matter, as long as you have monads down pat. Just choose what you are interested in.

With the knowledge you would have now, you should be able to use most of the packages on cabal (well the documented ones at least...), as well as most of the libraries that come with Haskell. A list of interesting libraries to try would be:

  • Parsec: for parsing programs and text. Much better than using regexps. Excellent documentation, also has a real world Haskell chapter.

  • QuickCheck: A very cool testing program. What you do is write a predicate that should always be true (eg length (reverse lst) == length lst). You then pass the predicate the QuickCheck, and it will generate a lot of random values (in this case lists) and test that the predicate is true for all results. See also the online manual.

  • HUnit: Unit testing in Haskell.

  • gtk2hs: The most popular gui framework for Haskell, lets you write gtk applications.

  • happstack: A web development framework for Haskell. Doesn't use databases, instead a data type store. Pretty good docs (other popular frameworks would be snap and yesod).

Also, there are many concepts (like the Monad concept) that you should eventually learn. This will be easier than learning Monads the first time, as your brain will be used to dealing with the level of abstraction involved. A very good overview for learning about these high level concepts and how they fit together is the Typeclassopedia.

  • Applicative: An interface like Monads, but less powerful. Every Monad is Applicative, but not vice versa. This is useful as there are some types that are Applicative but are not Monads. Also, code written using the Applicative functions is often more composable than writing the equivalent code using the Monad functions. See Functors, Applicative Functors and Monoids from the learn you a haskell guide.

  • Foldable,Traversable: Typeclasses that abstract many of the operations of lists, so that the same functions can be applied to other container types. See also the haskell wiki explanation.

  • Monoid: A Monoid is a type that has a zero (or mempty) value, and an operation, notated <> that joins two Monoids together, such that x <> mempty = mempty <> x = x and x <> (y <> z) = (x <> y) <> z. These are called identity and associativity laws. Many types are Monoids, such as numbers, with mempty = 0 and <> = +. This is useful in many situations.

  • Arrows: Arrows are a way of representing computations that take an input and return an output. A function is the most basic type of arrow, but there are many other types. The library also has many very useful functions for manipulating arrows - they are very useful even if only used with plain old Haskell functions.

  • Arrays: the various mutable/immutable arrays in Haskell.

  • ST Monad: lets you write code with a mutable state that runs very quickly, while still remaining pure outside the monad. See the link for more details.

  • FRP: Functional Reactive Programming, a new, experimental way of writing code that handles events, triggers, inputs and outputs (such as a gui). I don't know much about this though. Paul Hudak's talk about yampa is a good start.

There are a lot of new language features you should have a look at. I'll just list them, you can find lots of info about them from google, the haskell wikibook, the haskellwiki.org site and ghc documentation.

  • Multiparameter type classes/functional dependencies
  • Type families
  • Existentially quantified types
  • Phantom types
  • GADTS
  • others...

A lot of Haskell is based around category theory, so you may want to look into that. A good starting point is Category Theory for Computer Scientist. If you don't want to buy the book, the author's related article is also excellent.

Finally you will want to learn more about the various Haskell tools. These include:

  • ghc (and all its features)
  • cabal: the Haskell package system
  • darcs: a distributed version control system written in Haskell, very popular for Haskell programs.
  • haddock: a Haskell automatic documentation generator

While learning all these new libraries and concepts, it is very useful to be writing a moderate-sized project in Haskell. It can be anything (e.g. a small game, data analyser, website, compiler). Working on this will allow you to apply many of the things you are now learning. You stay at this level for ages (this is where I'm at).

Expert

It will take you years to get to this stage (hello from 2009!), but from here I'm guessing you start writing phd papers, new ghc extensions, and coming up with new abstractions.

Getting Help

Finally, while at any stage of learning, there are multiple places for getting information. These are:

  • the #haskell irc channel
  • the mailing lists. These are worth signing up for just to read the discussions that take place - some are very interesting.
  • other places listed on the haskell.org home page

Conclusion

Well this turned out longer than I expected... Anyway, I think it is a very good idea to become proficient in Haskell. It takes a long time, but that is mainly because you are learning a completely new way of thinking by doing so. It is not like learning Ruby after learning Java, but like learning Java after learning C. Also, I am finding that my object-orientated programming skills have improved as a result of learning Haskell, as I am seeing many new ways of abstracting ideas.

Java 8 - Difference between Optional.flatMap and Optional.map

  • Optional.map():

Takes every element and if the value exists, it is passed to the function:

Optional<T> optionalValue = ...;
Optional<Boolean> added = optionalValue.map(results::add);

Now added has one of three values: true or false wrapped into an Optional , if optionalValue was present, or an empty Optional otherwise.

If you don't need to process the result you can simply use ifPresent(), it doesn't have return value:

optionalValue.ifPresent(results::add); 
  • Optional.flatMap():

Works similar to the same method of streams. Flattens out the stream of streams. With the difference that if the value is presented it is applied to function. Otherwise, an empty optional is returned.

You can use it for composing optional value functions calls.

Suppose we have methods:

public static Optional<Double> inverse(Double x) {
    return x == 0 ? Optional.empty() : Optional.of(1 / x);
}

public static Optional<Double> squareRoot(Double x) {
    return x < 0 ? Optional.empty() : Optional.of(Math.sqrt(x));
}

Then you can compute the square root of the inverse, like:

Optional<Double> result = inverse(-4.0).flatMap(MyMath::squareRoot);

or, if you prefer:

Optional<Double> result = Optional.of(-4.0).flatMap(MyMath::inverse).flatMap(MyMath::squareRoot);

If either the inverse() or the squareRoot() returns Optional.empty(), the result is empty.

PHP: How to generate a random, unique, alphanumeric string for use in a secret link?

<?php
function generateRandomString($length = 11) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;

}

?>

above function will generate you a random string which is length of 11 characters.

Catching exceptions from Guzzle

Depending on your project, disabling exceptions for guzzle might be necessary. Sometimes coding rules disallow exceptions for flow control. You can disable exceptions for Guzzle 3 like this:

$client = new \Guzzle\Http\Client($httpBase, array(
  'request.options' => array(
     'exceptions' => false,
   )
));

This does not disable curl exceptions for something like timeouts, but now you can get every status code easily:

$request = $client->get($uri);
$response = $request->send();
$statuscode = $response->getStatusCode();

To check, if you got a valid code, you can use something like this:

if ($statuscode > 300) {
  // Do some error handling
}

... or better handle all expected codes:

if (200 === $statuscode) {
  // Do something
}
elseif (304 === $statuscode) {
  // Nothing to do
}
elseif (404 === $statuscode) {
  // Clean up DB or something like this
}
else {
  throw new MyException("Invalid response from api...");
}

For Guzzle 5.3

$client = new \GuzzleHttp\Client(['defaults' => [ 'exceptions' => false ]] );

Thanks to @mika

For Guzzle 6

$client = new \GuzzleHttp\Client(['http_errors' => false]);

Error creating bean with name 'entityManagerFactory

This sounds like a ClassLoader conflict. I'd bet you have the javax.persistence api 1.x on the classpath somewhere, whereas Spring is trying to access ValidationMode, which was only introduced in JPA 2.0.

Since you use Maven, do mvn dependency:tree, find the artifact:

<dependency>
    <groupId>javax.persistence</groupId>
    <artifactId>persistence-api</artifactId>
    <version>1.0</version>
</dependency>

And remove it from your setup. (See Excluding Dependencies)

AFAIK there is no such general distribution for JPA 2, but you can use this Hibernate-specific version:

<dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.0-api</artifactId>
    <version>1.0.1.Final</version>
</dependency>

OK, since that doesn't work, you still seem to have some JPA-1 version in there somewhere. In a test method, add this code:

System.out.println(EntityManager.class.getProtectionDomain()
                                      .getCodeSource()
                                      .getLocation());

See where that points you and get rid of that artifact.


Ahh, now I finally see the problem. Get rid of this:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jpa</artifactId>
    <version>2.0.8</version>
</dependency>

and replace it with

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>3.2.5.RELEASE</version>
</dependency>

On a different note, you should set all test libraries (spring-test, easymock etc.) to

<scope>test</scope>

"No X11 DISPLAY variable" - what does it mean?

For those who are trying to get an X Window application working from Windows from Linux:

What worked for me was to setup xming server on my windows machine, set X11 forwarding option in putty when I connect to the linux host and put in my windows ip address with the display port and then the display variable with my windows IP address:0.0

Dont forget to add the linux hosts IP address to the X0.hosts file to ensure that the xming server accepts traffic from that host. Took me a while to figure that out.

Onclick CSS button effect

JS provides the tools to do this the right way. Try the demo snippet.

enter image description here

_x000D_
_x000D_
var doc = document;_x000D_
var buttons = doc.getElementsByTagName('button');_x000D_
var button = buttons[0];_x000D_
_x000D_
button.addEventListener("mouseover", function(){_x000D_
  this.classList.add('mouse-over');_x000D_
});_x000D_
_x000D_
button.addEventListener("mouseout", function(){_x000D_
  this.classList.remove('mouse-over');_x000D_
});_x000D_
_x000D_
button.addEventListener("mousedown", function(){_x000D_
  this.classList.add('mouse-down');_x000D_
});_x000D_
_x000D_
button.addEventListener("mouseup", function(){_x000D_
  this.classList.remove('mouse-down');_x000D_
  alert('Button Clicked!');_x000D_
});_x000D_
_x000D_
//this is unrelated to button styling.  It centers the button._x000D_
var box = doc.getElementById('box');_x000D_
var boxHeight = window.innerHeight;_x000D_
box.style.height = boxHeight + 'px'; 
_x000D_
button{_x000D_
  text-transform: uppercase;_x000D_
  background-color:rgba(66, 66, 66,0.3);_x000D_
  border:none;_x000D_
  font-size:4em;_x000D_
  color:white;_x000D_
  -webkit-box-shadow: 0px 10px 5px -4px rgba(0,0,0,0.33);_x000D_
  -moz-box-shadow: 0px 10px 5px -4px rgba(0,0,0,0.33);_x000D_
  box-shadow: 0px 10px 5px -4px rgba(0,0,0,0.33);_x000D_
}_x000D_
button:focus {_x000D_
  outline:0;_x000D_
}_x000D_
.mouse-over{_x000D_
  background-color:rgba(66, 66, 66,0.34);_x000D_
}_x000D_
.mouse-down{_x000D_
  -webkit-box-shadow: 0px 6px 5px -4px rgba(0,0,0,0.52);_x000D_
  -moz-box-shadow: 0px 6px 5px -4px rgba(0,0,0,0.52);_x000D_
  box-shadow: 0px 6px 5px -4px rgba(0,0,0,0.52);                 _x000D_
}_x000D_
_x000D_
/* unrelated to button styling */_x000D_
#box {_x000D_
  display: flex;_x000D_
  flex-flow: row nowrap ;_x000D_
  justify-content: center;_x000D_
  align-content: center;_x000D_
  align-items: center;_x000D_
  width:100%;_x000D_
}_x000D_
_x000D_
button {_x000D_
  order:1;_x000D_
  flex: 0 1 auto;_x000D_
  align-self: auto;_x000D_
  min-width: 0;_x000D_
  min-height: auto;_x000D_
}            _x000D_
_x000D_
_x000D_
    
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
  <head>_x000D_
    <meta charset=utf-8 />_x000D_
    <meta name="description" content="3d Button Configuration" />_x000D_
  </head>_x000D_
_x000D_
  <body>_x000D_
    <section id="box">_x000D_
      <button>_x000D_
        Submit_x000D_
      </button>_x000D_
    </section>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Getting DOM element value using pure JavaScript

Pass the object:

doSomething(this)

You can get all data from object:

function(obj){
    var value = obj.value;
    var id = obj.id;
}

Or pass the id only:

doSomething(this.id)

Get the object and after that value:

function(id){
    var value = document.getElementById(id).value;  
}

IllegalStateException: Can not perform this action after onSaveInstanceState with ViewPager

Starting from support library version 24.0.0 you can call FragmentTransaction.commitNow() method which commits this transaction synchronously instead of calling commit() followed by executePendingTransactions(). As documentation says this approach even better:

Calling commitNow is preferable to calling commit() followed by executePendingTransactions() as the latter will have the side effect of attempting to commit all currently pending transactions whether that is the desired behavior or not.

Laravel 5 - artisan seed [ReflectionException] Class SongsTableSeeder does not exist

If you have copied the seeders files from any other project then you need to run the artisan command php artisan db:seed otherwise it is fine.

How can I read a text file in Android?

Try this code

public static String pathRoot = "/sdcard/system/temp/";
public static String readFromFile(Context contect, String nameFile) {
    String aBuffer = "";
    try {
        File myFile = new File(pathRoot + nameFile);
        FileInputStream fIn = new FileInputStream(myFile);
        BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
        String aDataRow = "";
        while ((aDataRow = myReader.readLine()) != null) {
            aBuffer += aDataRow;
        }
        myReader.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return aBuffer;
}

Changing EditText bottom line color with appcompat v7

You can set background of edittext to a rectangle with minus padding on left, right and top to achieve this. Here is the xml example:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:top="-1dp"
        android:left="-1dp"
        android:right="-1dp"
        android:bottom="1dp"
        >
        <shape android:shape="rectangle">
            <stroke android:width="1dp" android:color="#6A9A3A"/>
        </shape>
    </item>
</layer-list>

Replace the shape with a selector if you want to provide different width and color for focused edittext.

How to query first 10 rows and next time query other 10 rows from table

LIMIT limit OFFSET offset will work.

But you need a stable ORDER BY clause, or the values may be ordered differently for the next call (after any write on the table for instance).

SELECT *
FROM   msgtable
WHERE  cdate = '2012-07-18'
ORDER  BY msgtable_id  -- or whatever is stable 
LIMIT  10
OFFSET 50;  -- to skip to page 6

Use standard-conforming date style (ISO 8601 in my example), which works irregardless of your locale settings.

Paging will still shift if involved rows are inserted or deleted or changed in relevant columns. It has to.

To avoid that shift or for better performance with big tables use smarter paging strategies:

Adjusting the Xcode iPhone simulator scale and size

Specific to XCode 9.1:
You can refere to @Krunal's answer above or follow below steps

its bit tricky to adjust Simulator size.

If you want to zoom your simulator screen follow below steps :

  • Goto Window->Uncheck Show Device Bezels

refer screenshot 1

  • Goto Window->select zoom

refere screenshot 2

after doing this you can resize your simulator by dragging edges of simulator.

Pixel Accurate : Its to display your simulator in same size as Physical device pixels, if your screen size doesn't have enough resolution to cover dimension it would not enable Pixel Accurate option.

Alternate is change simulator to landscape mode by clicking ? + ? ,then you could click ? + 2 to select Pixel Accurate option (make sure you have disable Show Device Bezels to reduce size.

Capture Video of Android's Screen

Android 4.4 (KitKat) and higher devices have a shell utility for recording the Android device screen. Connect a device in developer/debug mode running KitKat with the adb utility over USB and then type the following:

adb shell screenrecord /sdcard/movie.mp4
(Press Ctrl-C to stop)
adb pull /sdcard/movie.mp4

Screen recording is limited to a maximum of 3 minutes.

Reference: https://developer.android.com/studio/command-line/adb.html#screenrecord

Maven: The packaging for this project did not assign a file to the build artifact

I have seen this error occur when the plugins that are needed are not specifically mentioned in the pom. So

mvn clean install

will give the exception if this is not added:

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-install-plugin</artifactId>
        <version>2.5.2</version>
 </plugin>

Likewise,

mvn clean install deploy

will fail on the same exception if something like this is not added:

<plugin>
   <artifactId>maven-deploy-plugin</artifactId>
   <version>2.8.1</version>
   <executions>
      <execution>
         <id>default-deploy</id>
         <phase>deploy</phase>
         <goals>
            <goal>deploy</goal>
         </goals>
      </execution>
   </executions>
</plugin>

It makes sense, but a clearer error message would be welcome

How to iterate over a std::map full of strings in C++

Use:

std::map<std::string, std::string>::const_iterator

instead:

std::map<std::string, std::string>::iterator

How to make phpstorm display line numbers by default?

Simplest solution for line numbers in php storm..There are many other solutions but i think A big picture a good from 1000 words.

Simplest solution for line numbers in php storm..There are many other solutions but i think A big picture a good from 1000 words.

Get counts of all tables in a schema

select owner, table_name, num_rows, sample_size, last_analyzed from all_tables;

This is the fastest way to retrieve the row counts but there are a few important caveats:

  1. NUM_ROWS is only 100% accurate if statistics were gathered in 11g and above with ESTIMATE_PERCENT => DBMS_STATS.AUTO_SAMPLE_SIZE (the default), or in earlier versions with ESTIMATE_PERCENT => 100. See this post for an explanation of how the AUTO_SAMPLE_SIZE algorithm works in 11g.
  2. Results were generated as of LAST_ANALYZED, the current results may be different.

Python and JSON - TypeError list indices must be integers not str

First of all, you should be using json.loads, not json.dumps. loads converts JSON source text to a Python value, while dumps goes the other way.

After you fix that, based on the JSON snippet at the top of your question, readable_json will be a list, and so readable_json['firstName'] is meaningless. The correct way to get the 'firstName' field of every element of a list is to eliminate the playerstuff = readable_json['firstName'] line and change for i in playerstuff: to for i in readable_json:.

Warning: push.default is unset; its implicit value is changing in Git 2.0

It's explained in great detail in the docs, but I'll try to summarize:

  • matching means git push will push all your local branches to the ones with the same name on the remote. This makes it easy to accidentally push a branch you didn't intend to.

  • simple means git push will push only the current branch to the one that git pull would pull from, and also checks that their names match. This is a more intuitive behavior, which is why the default is getting changed to this.

This setting only affects the behavior of your local client, and can be overridden by explicitly specifying which branches you want to push on the command line. Other clients can have different settings, it only affects what happens when you don't specify which branches you want to push.

Change table header color using bootstrap

//use css
.blue {
    background-color:blue !important;
}
.blue th {
    color:white !important;
}

//html
<table class="table blue">.....</table>

Python json.loads shows ValueError: Extra data

Well , it might help someone. i just got the same error while my json file is like this

{"id":"1101010","city_id":"1101","name":"TEUPAH SELATAN"}
{"id":"1101020","city_id":"1101","name":"SIMEULUE TIMUR"}

and i found it malformed, so i changed it into somekind of

{
  "datas":[
    {"id":"1101010","city_id":"1101","name":"TEUPAH SELATAN"},
    {"id":"1101020","city_id":"1101","name":"SIMEULUE TIMUR"}
  ]
}

Android: failed to convert @drawable/picture into a drawable

I think I found a way to have it work without restarting Eclipse, or without closing project (it worked for me):

  • rename image file name under res/ in Eclipse -> choose file and press F2 (for me it res/drawable-mdpi/bush-landscape.jpg -> changed to bush.jpg)

  • Build Project (it will still show error)

  • change image where you used it (I changed in Graphical Layout. For me the place was LinearLayout/Background/bush-landscape -> changed "bush-landscape" to "bush")

  • Build Project

Allowed memory size of X bytes exhausted

The memory must be configured in several places.
Set memory_limit to 512M:

sudo vi /etc/php5/cgi/php.ini
sudo vi /etc/php5/cli/php.ini
sudo vi /etc/php5/apache2/php.ini Or /etc/php5/fpm/php.ini

Restart service:

sudo service service php5-fpm restart
sudo service service nginx restart

or

sudo service apache2 restart

Finally it should solve the problem of the memory_limit

Another git process seems to be running in this repository

Delete index.lock in here:

<path to your repo>/.git/index.lock

Also, if your repository has submodules, delete all index.lock in here as well:

<path to your repo>/.git/modules/<path to your submodule>/index.lock

how to automatically scroll down a html page?

Use document.scrollTop to change the position of the document. Set the scrollTop of the document equal to the bottom of the featured section of your site

pandas groupby sort descending order

Similar to one of the answers above, but try adding .sort_values() to your .groupby() will allow you to change the sort order. If you need to sort on a single column, it would look like this:

df.groupby('group')['id'].count().sort_values(ascending=False)

ascending=False will sort from high to low, the default is to sort from low to high.

*Careful with some of these aggregations. For example .size() and .count() return different values since .size() counts NaNs.

What is the difference between size and count in pandas?

How to discard all changes made to a branch?

When you want to discard changes in your local branch, you can stash these changes using git stash command.

git stash save "some_name"

Your changes will be saved and you can retrieve those later,if you want or you can delete it. After doing this, your branch will not have any uncommitted code and you can pull the latest code from your main branch using git pull.

How to check if mod_rewrite is enabled in php?

Use this function:

function apache_module_exists($module)
{
    return in_array($module, apache_get_modules());
}

Show popup after page load

When the DOM is finished loading you can add your code in the $(document).ready() function.

Remove the onclick from here:

<input type="submit" name="submit" value="Submit" onClick="PopUp()" />

Try this:

$(document).ready(function(){
   setTimeout(function(){
      PopUp();
   },5000); // 5000 to load it after 5 seconds from page load
});

how to hide <li> bullets in navigation menu and footer links BUT show them for listing items

You need to define a class for the bullets you want to hide. For examples

.no-bullets {
    list-style-type: none;
}

Then apply it to the list you want hidden bullets:

<ul class="no-bullets">

All other lists (without a specific class) will show the bulltets as usual.

What is the maximum length of a URL in different browsers?

It seems that Chrome at least has raised this limit. I pasted 20,000 characters into the bookmarklet and it took it.

Disabled form inputs do not appear in the request

Using Jquery and sending the data with ajax, you can solve your problem:

<script>

$('#form_id').submit(function() {
    $("#input_disabled_id").prop('disabled', false);

    //Rest of code
    })
</script>

I am not able launch JNLP applications using "Java Web Start"?

I believe this is a security problem. If I download the jnpl file and execute it after a clean java 8 installation via javaws myfile.jnpl everything is working fine (I get multiple windows where I have to confirm some security problems).

chrome : how to turn off user agent stylesheet settings?

https://developers.google.com/chrome-developer-tools/docs/settings

  1. Open Chrome dev tools
  2. Click gear icon on bottom right
  3. In General section, check or uncheck "Show user agent styles".

How can I generate a unique ID in Python?

You might want Python's UUID functions:

21.15. uuid — UUID objects according to RFC 4122

eg:

import uuid
print uuid.uuid4()

7d529dd4-548b-4258-aa8e-23e34dc8d43d

Escape text for HTML

there are some special quotes characters which are not removed by HtmlEncode and will not be displayed in Edge or IE correctly like ” and “ . you can extent replacing these characters with something like below function.

private string RemoveJunkChars(string input)
{
    return HttpUtility.HtmlEncode(input.Replace("”", "\"").Replace("“", "\""));
}

python, sort descending dataframe with pandas

For pandas 0.17 and above, use this :

test = df.sort_values('one', ascending=False)

Since 'one' is a series in the pandas data frame, hence pandas will not accept the arguments in the form of a list.

jQuery: Change button text on click

In HTML:

<button type="button" id="AddButton" onclick="AddButtonClick()" class="btn btn-success btn-block ">Add</button> 

In Jquery write this function:

    function AddButtonClick(){ 
      //change text from add to Update
      $("#AddButton").text('Update');
    }

Git: cannot checkout branch - error: pathspec '...' did not match any file(s) known to git

This worked for me. It discards all local changes and resets it to the last commit.

git reset --hard

Is background-color:none valid CSS?

CSS Level 3 specifies the unset property value. From MDN:

The unset CSS keyword is the combination of the initial and inherit keywords. Like these two other CSS-wide keywords, it can be applied to any CSS property, including the CSS shorthand all. This keyword resets the property to its inherited value if it inherits from its parent or to its initial value if not. In other words, it behaves like the inherit keyword in the first case and like the initial keyword in the second case.

Unfortunately this value is currently not supported in all browsers, including IE, Safari and Opera. I suggest using transparent for the time being.

How do I make a composite key with SQL Server Management Studio?

Open up the table designer in SQL Server Management Studio (right-click table and select 'Design')

Holding down the Ctrl key highlight two or more columns in the left hand table margin

Hit the little 'Key' on the standard menu bar at the top

You're done..

:-)

How to prevent a background process from being stopped after closing SSH client in Linux

When the session is closed the process receives the SIGHUP signal which it is apparently not catching. You can use the nohup command when launching the process or the bash built-in command disown -h after starting the process to prevent this from happening:

> help disown
disown: disown [-h] [-ar] [jobspec ...]
     By default, removes each JOBSPEC argument from the table of active jobs.
    If the -h option is given, the job is not removed from the table, but is
    marked so that SIGHUP is not sent to the job if the shell receives a
    SIGHUP.  The -a option, when JOBSPEC is not supplied, means to remove all
    jobs from the job table; the -r option means to remove only running jobs.

How to fast-forward a branch to head?

In your case, to fast-forward, run:

$ git merge --ff-only origin/master

This uses the --ff-only option of git merge, as the question specifically asks for "fast-forward".

Here is an excerpt from git-merge(1) that shows more fast-forward options:

--ff, --no-ff, --ff-only
    Specifies how a merge is handled when the merged-in history is already a descendant of the current history.  --ff is the default unless merging an annotated
    (and possibly signed) tag that is not stored in its natural place in the refs/tags/ hierarchy, in which case --no-ff is assumed.

    With --ff, when possible resolve the merge as a fast-forward (only update the branch pointer to match the merged branch; do not create a merge commit). When
    not possible (when the merged-in history is not a descendant of the current history), create a merge commit.

    With --no-ff, create a merge commit in all cases, even when the merge could instead be resolved as a fast-forward.

    With --ff-only, resolve the merge as a fast-forward when possible. When not possible, refuse to merge and exit with a non-zero status.

I fast-forward often enough that it warranted an alias:

$ git config --global alias.ff 'merge --ff-only @{upstream}'

Now I can run this to fast-forward:

$ git ff

Use of PUT vs PATCH methods in REST API real life scenarios

Though Dan Lowe's excellent answer very thoroughly answered the OP's question about the difference between PUT and PATCH, its answer to the question of why PATCH is not idempotent is not quite correct.

To show why PATCH isn't idempotent, it helps to start with the definition of idempotence (from Wikipedia):

The term idempotent is used more comprehensively to describe an operation that will produce the same results if executed once or multiple times [...] An idempotent function is one that has the property f(f(x)) = f(x) for any value x.

In more accessible language, an idempotent PATCH could be defined as: After PATCHing a resource with a patch document, all subsequent PATCH calls to the same resource with the same patch document will not change the resource.

Conversely, a non-idempotent operation is one where f(f(x)) != f(x), which for PATCH could be stated as: After PATCHing a resource with a patch document, subsequent PATCH calls to the same resource with the same patch document do change the resource.

To illustrate a non-idempotent PATCH, suppose there is a /users resource, and suppose that calling GET /users returns a list of users, currently:

[{ "id": 1, "username": "firstuser", "email": "[email protected]" }]

Rather than PATCHing /users/{id}, as in the OP's example, suppose the server allows PATCHing /users. Let's issue this PATCH request:

PATCH /users
[{ "op": "add", "username": "newuser", "email": "[email protected]" }]

Our patch document instructs the server to add a new user called newuser to the list of users. After calling this the first time, GET /users would return:

[{ "id": 1, "username": "firstuser", "email": "[email protected]" },
 { "id": 2, "username": "newuser", "email": "[email protected]" }]

Now, if we issue the exact same PATCH request as above, what happens? (For the sake of this example, let's assume that the /users resource allows duplicate usernames.) The "op" is "add", so a new user is added to the list, and a subsequent GET /users returns:

[{ "id": 1, "username": "firstuser", "email": "[email protected]" },
 { "id": 2, "username": "newuser", "email": "[email protected]" },
 { "id": 3, "username": "newuser", "email": "[email protected]" }]

The /users resource has changed again, even though we issued the exact same PATCH against the exact same endpoint. If our PATCH is f(x), f(f(x)) is not the same as f(x), and therefore, this particular PATCH is not idempotent.

Although PATCH isn't guaranteed to be idempotent, there's nothing in the PATCH specification to prevent you from making all PATCH operations on your particular server idempotent. RFC 5789 even anticipates advantages from idempotent PATCH requests:

A PATCH request can be issued in such a way as to be idempotent, which also helps prevent bad outcomes from collisions between two PATCH requests on the same resource in a similar time frame.

In Dan's example, his PATCH operation is, in fact, idempotent. In that example, the /users/1 entity changed between our PATCH requests, but not because of our PATCH requests; it was actually the Post Office's different patch document that caused the zip code to change. The Post Office's different PATCH is a different operation; if our PATCH is f(x), the Post Office's PATCH is g(x). Idempotence states that f(f(f(x))) = f(x), but makes no guarantes about f(g(f(x))).

R dplyr: Drop multiple columns

You can try

iris %>% select(-!!drop.cols)

How can I edit a .jar file?

Here's what I did:

  • Extracted the files using WinRAR
  • Made my changes to the extracted files
  • Opened the original JAR file with WinRAR
  • Used the ADD button to replace the files that I modified

That's it. I have tested it with my Nokia and it's working for me.

How do I display an alert dialog on Android?

Make this static method and use it where ever you want.

public static void showAlertDialog(Context context, String title, String message, String posBtnMsg, String negBtnMsg) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle(title);
            builder.setMessage(message);
            builder.setPositiveButton(posBtnMsg, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            builder.setNegativeButton(negBtnMsg, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            AlertDialog dialog = builder.create();
            dialog.show();

        }

how to use LIKE with column name

ORACLE DATABASE example:

select * 
from table1 t1, table2 t2
WHERE t1.a like ('%' || t2.b || '%')

Changing SQL Server collation to case insensitive from case sensitive?

You can do that but the changes will affect for new data that is inserted on the database. On the long run follow as suggested above.

Also there are certain tricks you can override the collation, such as parameters for stored procedures or functions, alias data types, and variables are assigned the default collation of the database. To change the collation of an alias type, you must drop the alias and re-create it.

You can override the default collation of a literal string by using the COLLATE clause. If you do not specify a collation, the literal is assigned the database default collation. You can use DATABASEPROPERTYEX to find the current collation of the database.

You can override the server, database, or column collation by specifying a collation in the ORDER BY clause of a SELECT statement.

How can I download a specific Maven artifact in one command line?

Here's what worked for me to download the latest version of an artifact called "component.jar" with Maven 3.1.1 in the end (other suggestions did not, mostly due to maven version changes I believe)

This actually downloads the file and copies it into the local working directory

From bash:

mvn dependency:get \
    -DrepoUrl=http://.../ \
        -Dartifact=com.foo.something:component:LATEST:jar \
        -Dtransitive=false \
        -Ddest=component.jar \

How do I compare strings in Java?

.equals() compares the data in a class (assuming the function is implemented). == compares pointer locations (location of the object in memory).

== returns true if both objects (NOT TALKING ABOUT PRIMITIVES) point to the SAME object instance. .equals() returns true if the two objects contain the same data equals() Versus == in Java

That may help you.

Iterating through a list in reverse order in java

Guava offers Lists#reverse(List) and ImmutableList#reverse(). As in most cases for Guava, the former delegates to the latter if the argument is an ImmutableList, so you can use the former in all cases. These do not create new copies of the list but just "reversed views" of it.

Example

List reversed = ImmutableList.copyOf(myList).reverse();

String replacement in batch file

You can use !, but you must have the ENABLEDELAYEDEXPANSION switch set.

setlocal ENABLEDELAYEDEXPANSION
set word=table
set str="jump over the chair"
set str=%str:chair=!word!%

Find closing HTML tag in Sublime Text

Under the "Goto" menu, Control + M is Jump to Matching Bracket. Works for parentheses as well.

Spring Boot - Cannot determine embedded database driver class for database type NONE

I'd the same problem and excluding the DataSourceAutoConfiguration solved the problem.

@SpringBootApplication
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class RecommendationEngineWithCassandraApplication {

    public static void main(String[] args) {
        SpringApplication.run(RecommendationEngineWithCassandraApplication.class, args);
    }
}

Eclipse - no Java (JRE) / (JDK) ... no virtual machine

Eclipse will by default try to launch with the default "java.exe" (the first one referenced by your PATH)

Three things to remember:

  • "Installing" a JRE or a JDK can be as simple as unzipping or copying it from another computer: there is no special installation steps, and you can have as many different JVM versions (1.4, 5.0, 6.0...) as you want, "installed" (copied) almost anywhere on your disk.
  • I would recommend to always run Eclipse with the lastest JRE possible (to benefit from the latest hotspot evolutions). You can:
  • The JVM you will reference within your Eclipse session is not always the one used for launching Eclipse because:
    • You only need a JRE to launch Eclipse, but once Eclipse launched, you should register a JDK for your projects (especially for Java sources and debugging purposes, also in theory for compilation but Eclipse has its own Java compiler) Note: You could register just a JRE within Eclipse because it is enough to run your program, but again a JDK will allow for more operations.
    • Even though the default registered Java in Eclipse is the one used to launch the session, you can want to register an older SDK (including a non-Sun one) in order to run/debug your programs with a JRE similar to the one which will actually be used in production.

Installed JREs


June 2012, jmbertucci comments:

I'm running Windows 7 64-bit and I had the 32-bit JRE installed. I downloaded Eclipse 64-bit which looks for a 64-bit JRE. Because I didn't have the 64-bit JRE it threw the error, which makes sense.

I went to the Java manual install page (which was not as directly accessible as you'd like) and installed the 64-bit version. See "Java Downloads for All Operating Systems". That was all I needed.


April 2016: Steve Mayne adds in the comments:

I had to edit the eclipse.ini file to reference the correct Java path - Eclipse doesn't use the environment PATH at all when there is a value in eclipse.ini.

How to see tomcat is running or not

open your browser,check whether Tomcat homepage is visible by below command.

http://ipaddress:portnumber

also check this

How to pass text in a textbox to JavaScript function?

This is what I have done. (Adapt from all of your answers)

<input name="textbox1" type="text" id="txt1"/>
<input name="buttonExecute" onclick="execute(document.getElementById('txt1').value)" type="button" value="Execute" />

It works. Thanks to all of you. :)

Resize image in the wiki of GitHub using Markdown

Updated:

Markdown syntax for images (external/internal):

![test](https://github.com/favicon.ico)

HTML code for sizing images (internal/external):

<img src="https://github.com/favicon.ico" width="48">

Example:

test


Old Answer:

This should work:

[[ http://url.to/image.png | height = 100px ]]

Source: https://guides.github.com/features/mastering-markdown/

Passing a URL with brackets to curl

Never mind, I found it in the docs:

-g/--globoff
              This  option  switches  off  the "URL globbing parser". When you set this option, you can
              specify URLs that contain the letters {}[] without having them being interpreted by  curl
              itself.  Note  that  these  letters  are not normal legal URL contents but they should be
              encoded according to the URI standard.

How to initialize a static array?

If you are creating an array then there is no difference, however, the following is neater:

String[] suit = {
  "spades", 
  "hearts", 
  "diamonds", 
  "clubs"  
};

But, if you want to pass an array into a method you have to call it like this:

myMethod(new String[] {"spades", "hearts"});

myMethod({"spades", "hearts"}); //won't compile!

How to pass a variable to the SelectCommand of a SqlDataSource?

Just add a custom property to the page which will return the variable of your choice. You can then use the built-in "control" parameter type.

In the code behind, add:

Dim MyVariable as Long


ReadOnly Property MyCustomProperty As Long
    Get
        Return MyVariable
    End Get
End Property

In the select parameters section add:

<asp:ControlParameter ControlID="__Page" Name="MyParameter" 
PropertyName="MyCustomProperty" Type="Int32" />

Angular no provider for NameService

Angular 2 has changed, here is what the top of your code should look like:

import {
  ComponentAnnotation as Component,
  ViewAnnotation as View, bootstrap
} from 'angular2/angular2';
import {NameService} from "./services/NameService";

@Component({
  selector: 'app',
  appInjector: [NameService]
})

Also, you may want to use getters and setters in your service:

export class NameService {
    _names: Array<string>;
    constructor() {
        this._names = ["Alice", "Aarav", "Martín", "Shannon", "Ariana", "Kai"];
    }
    get names() {
        return this._names;
    }
}

Then in your app you can simply do:

this.names = nameService.names;

I suggest you go to plnkr.co and create a new Angular 2 (ES6) plunk and get it to work in there first. It will set everything up for you. Once it's working there, copy it over to your other environment and triage any issues with that environment.

How to delete a cookie using jQuery?

Worked for me only when path was set, i.e.:

$.cookie('name', null, {path:'/'})

Return value using String result=Command.ExecuteScalar() error occurs when result returns null

There is a advance feature of c#, use that '?.' . string getValue = cmd.ExecuteScalar()?.ToString(); thants all.

non static method cannot be referenced from a static context

In Java, static methods belong to the class rather than the instance. This means that you cannot call other instance methods from static methods unless they are called in an instance that you have initialized in that method.

Here's something you might want to do:

public class Foo
{
  public void fee()
  {
     //do stuff  
  }

  public static void main (String[]arg) 
  { 
     Foo foo = new Foo();
     foo.fee();
  } 
}

Notice that you are running an instance method from an instance that you've instantiated. You can't just call call a class instance method directly from a static method because there is no instance related to that static method.

C# "must declare a body because it is not marked abstract, extern, or partial"

You DO NOT have to provide a body for getters and setters IF you'd like the automated compiler to provide a basic implementation.

This DOES however require you to make sure you're using the v3.5 compiler by updating your web.config to something like

 <compilers>
   <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CSharp.CSharpCodeProvider,System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="4">
    <providerOption name="CompilerVersion" value="v3.5"/>
    <providerOption name="WarnAsError" value="false"/>
  </compiler>
</compilers>

Static Final Variable in Java

In first statement you define variable, which common for all of the objects (class static field).

In the second statement you define variable, which belongs to each created object (a lot of copies).

In your case you should use the first one.

React Router Pass Param to Component

If you want to pass props to a component inside a route, the simplest way is by utilizing the render, like this:

<Route exact path="/details/:id" render={(props) => <DetailsPage globalStore={globalStore} {...props} /> } />

You can access the props inside the DetailPage using:

this.props.match
this.props.globalStore

The {...props} is needed to pass the original Route's props, otherwise you will only get this.props.globalStore inside the DetailPage.

Pass Hidden parameters using response.sendRedirect()

To send a variable value through URL in response.sendRedirect(). I have used it for one variable, you can also use it for two variable by proper concatenation.

String value="xyz";

response.sendRedirect("/content/test.jsp?var="+value);

What are Runtime.getRuntime().totalMemory() and freeMemory()?

Codified version of all other answers (at the time of writing):

import java.io.*;

/**
 * This class is based on <a href="http://stackoverflow.com/users/2478930/cheneym">cheneym</a>'s
 * <a href="http://stackoverflow.com/a/18375641/253468">awesome interpretation</a>
 * of the Java {@link Runtime}'s memory query methods, which reflects intuitive thinking.
 * Also includes comments and observations from others on the same question, and my own experience.
 * <p>
 * <img src="https://i.stack.imgur.com/GjuwM.png" alt="Runtime's memory interpretation">
 * <p>
 * <b>JVM memory management crash course</b>:
 * Java virtual machine process' heap size is bounded by the maximum memory allowed.
 * The startup and maximum size can be configured by JVM arguments.
 * JVMs don't allocate the maximum memory on startup as the program running may never require that.
 * This is to be a good player and not waste system resources unnecessarily.
 * Instead they allocate some memory and then grow when new allocations require it.
 * The garbage collector will be run at times to clean up unused objects to prevent this growing.
 * Many parameters of this management such as when to grow/shrink or which GC to use
 * can be tuned via advanced configuration parameters on JVM startup.
 *
 * @see <a href="http://stackoverflow.com/a/42567450/253468">
 *     What are Runtime.getRuntime().totalMemory() and freeMemory()?</a>
 * @see <a href="http://www.oracle.com/technetwork/java/javase/memorymanagement-whitepaper-150215.pdf">
 *     Memory Management in the Sun Java HotSpot™ Virtual Machine</a>
 * @see <a href="http://docs.oracle.com/javase/8/docs/technotes/tools/windows/java.html">
 *     Full VM options reference for Windows</a>
 * @see <a href="http://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html">
 *     Full VM options reference for Linux, Mac OS X and Solaris</a>
 * @see <a href="http://www.oracle.com/technetwork/articles/java/vmoptions-jsp-140102.html">
 *     Java HotSpot VM Options quick reference</a>
 */
public class SystemMemory {

    // can be white-box mocked for testing
    private final Runtime runtime = Runtime.getRuntime();

    /**
     * <b>Total allocated memory</b>: space currently reserved for the JVM heap within the process.
     * <p>
     * <i>Caution</i>: this is not the total memory, the JVM may grow the heap for new allocations.
     */
    public long getAllocatedTotal() {
        return runtime.totalMemory();
    }

    /**
     * <b>Current allocated free memory</b>: space immediately ready for new objects.
     * <p>
     * <i>Caution</i>: this is not the total free available memory,
     * the JVM may grow the heap for new allocations.
     */
    public long getAllocatedFree() {
        return runtime.freeMemory();
    }

    /**
     * <b>Used memory</b>:
     * Java heap currently used by instantiated objects. 
     * <p>
     * <i>Caution</i>: May include no longer referenced objects, soft references, etc.
     * that will be swept away by the next garbage collection.
     */
    public long getUsed() {
        return getAllocatedTotal() - getAllocatedFree();
    }

    /**
     * <b>Maximum allocation</b>: the process' allocated memory will not grow any further.
     * <p>
     * <i>Caution</i>: This may change over time, do not cache it!
     * There are some JVMs / garbage collectors that can shrink the allocated process memory.
     * <p>
     * <i>Caution</i>: If this is true, the JVM will likely run GC more often.
     */
    public boolean isAtMaximumAllocation() {
        return getAllocatedTotal() == getTotal();
        // = return getUnallocated() == 0;
    }

    /**
     * <b>Unallocated memory</b>: amount of space the process' heap can grow.
     */
    public long getUnallocated() {
        return getTotal() - getAllocatedTotal();
    }

    /**
     * <b>Total designated memory</b>: this will equal the configured {@code -Xmx} value.
     * <p>
     * <i>Caution</i>: You can never allocate more memory than this, unless you use native code.
     */
    public long getTotal() {
        return runtime.maxMemory();
    }

    /**
     * <b>Total free memory</b>: memory available for new Objects,
     * even at the cost of growing the allocated memory of the process.
     */
    public long getFree() {
        return getTotal() - getUsed();
        // = return getAllocatedFree() + getUnallocated();
    }

    /**
     * <b>Unbounded memory</b>: there is no inherent limit on free memory.
     */
    public boolean isBounded() {
        return getTotal() != Long.MAX_VALUE;
    }

    /**
     * Dump of the current state for debugging or understanding the memory divisions.
     * <p>
     * <i>Caution</i>: Numbers may not match up exactly as state may change during the call.
     */
    public String getCurrentStats() {
        StringWriter backing = new StringWriter();
        PrintWriter out = new PrintWriter(backing, false);
        out.printf("Total: allocated %,d (%.1f%%) out of possible %,d; %s, %s %,d%n",
                getAllocatedTotal(),
                (float)getAllocatedTotal() / (float)getTotal() * 100,
                getTotal(),
                isBounded()? "bounded" : "unbounded",
                isAtMaximumAllocation()? "maxed out" : "can grow",
                getUnallocated()
        );
        out.printf("Used: %,d; %.1f%% of total (%,d); %.1f%% of allocated (%,d)%n",
                getUsed(),
                (float)getUsed() / (float)getTotal() * 100,
                getTotal(),
                (float)getUsed() / (float)getAllocatedTotal() * 100,
                getAllocatedTotal()
        );
        out.printf("Free: %,d (%.1f%%) out of %,d total; %,d (%.1f%%) out of %,d allocated%n",
                getFree(),
                (float)getFree() / (float)getTotal() * 100,
                getTotal(),
                getAllocatedFree(),
                (float)getAllocatedFree() / (float)getAllocatedTotal() * 100,
                getAllocatedTotal()
        );
        out.flush();
        return backing.toString();
    }

    public static void main(String... args) {
        SystemMemory memory = new SystemMemory();
        System.out.println(memory.getCurrentStats());
    }
}

Convert number to varchar in SQL with formatting

Correción: 3-LEN

declare @t  TINYINT 
set @t =233
SELECT ISNULL(REPLICATE('0',3-LEN(@t)),'') + CAST(@t AS VARCHAR) 

Can you style html form buttons with css?

You can directly create your own style in this way:

 input[type=button]
 { 
//Change the style as you like
 }

Change color of Back button in navigation bar

Use this code in AppDelegate class, inside of didFinishLaunchingWithOptions.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

UINavigationBar.appearance().tintColor = .white

}

java, get set methods

your panel class don't have a constructor that accepts a string

try change

RLS_strid_panel p = new RLS_strid_panel(namn1);

to

RLS_strid_panel p = new RLS_strid_panel();
p.setName1(name1);

How do I protect javascript files?

Forget it, this is not doable.

No matter what you try it will not work. All a user needs to do to discover your code and it's location is to look in the net tab in firebug or use fiddler to see what requests are being made.

Get position/offset of element relative to a parent container?

Example

So, if we had a child element with an id of "child-element" and we wanted to get it's left/top position relative to a parent element, say a div that had a class of "item-parent", we'd use this code.

var position = $("#child-element").offsetRelative("div.item-parent");
alert('left: '+position.left+', top: '+position.top);

Plugin Finally, for the actual plugin (with a few notes expalaining what's going on):

// offsetRelative (or, if you prefer, positionRelative)
(function($){
    $.fn.offsetRelative = function(top){
        var $this = $(this);
        var $parent = $this.offsetParent();
        var offset = $this.position();
        if(!top) return offset; // Didn't pass a 'top' element 
        else if($parent.get(0).tagName == "BODY") return offset; // Reached top of document
        else if($(top,$parent).length) return offset; // Parent element contains the 'top' element we want the offset to be relative to 
        else if($parent[0] == $(top)[0]) return offset; // Reached the 'top' element we want the offset to be relative to 
        else { // Get parent's relative offset
            var parent_offset = $parent.offsetRelative(top);
            offset.top += parent_offset.top;
            offset.left += parent_offset.left;
            return offset;
        }
    };
    $.fn.positionRelative = function(top){
        return $(this).offsetRelative(top);
    };
}(jQuery));

Note : You can Use this on mouseClick or mouseover Event

$(this).offsetRelative("div.item-parent");

Android Fragment onAttach() deprecated

This is another great change from Google ... The suggested modification: replace onAttach(Activity activity) with onAttach(Context context) crashed my apps on older APIs since onAttach(Context context) will not be called on native fragments.

I am using the native fragments (android.app.Fragment) so I had to do the following to make it work again on older APIs (< 23).

Here is what I did:

@Override
public void onAttach(Context context) {
    super.onAttach(context);

    // Code here
}

@SuppressWarnings("deprecation")
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        // Code here
    }
}

Convert NSNumber to int in Objective-C

You should stick to the NSInteger data types when possible. So you'd create the number like that:

NSInteger myValue = 1;
NSNumber *number = [NSNumber numberWithInteger: myValue];

Decoding works with the integerValue method then:

NSInteger value = [number integerValue];

Iterating through map in template

As Herman pointed out, you can get the index and element from each iteration.

{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}

Working example:

package main

import (
    "html/template"
    "os"
)

type EntetiesClass struct {
    Name string
    Value int32
}

// In the template, we use rangeStruct to turn our struct values
// into a slice we can iterate over
var htmlTemplate = `{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}`

func main() {
    data := map[string][]EntetiesClass{
        "Yoga": {{"Yoga", 15}, {"Yoga", 51}},
        "Pilates": {{"Pilates", 3}, {"Pilates", 6}, {"Pilates", 9}},
    }

    t := template.New("t")
    t, err := t.Parse(htmlTemplate)
    if err != nil {
        panic(err)
    }

    err = t.Execute(os.Stdout, data)
    if err != nil {
        panic(err)
    }

}

Output:

Pilates
3
6
9

Yoga
15
51

Playground: http://play.golang.org/p/4ISxcFKG7v

how to extract only the year from the date in sql server 2008?

year(@date)
year(getdate())
year('20120101')

update table
set column = year(date_column)
whre ....

or if you need it in another table

 update t
   set column = year(t1.date_column)
     from table_source t1
     join table_target t on (join condition)
    where ....

Using HTML5 file uploads with AJAX and jQuery

With jQuery (and without FormData API) you can use something like this:

function readFile(file){
   var loader = new FileReader();
   var def = $.Deferred(), promise = def.promise();

   //--- provide classic deferred interface
   loader.onload = function (e) { def.resolve(e.target.result); };
   loader.onprogress = loader.onloadstart = function (e) { def.notify(e); };
   loader.onerror = loader.onabort = function (e) { def.reject(e); };
   promise.abort = function () { return loader.abort.apply(loader, arguments); };

   loader.readAsBinaryString(file);

   return promise;
}

function upload(url, data){
    var def = $.Deferred(), promise = def.promise();
    var mul = buildMultipart(data);
    var req = $.ajax({
        url: url,
        data: mul.data,
        processData: false,
        type: "post",
        async: true,
        contentType: "multipart/form-data; boundary="+mul.bound,
        xhr: function() {
            var xhr = jQuery.ajaxSettings.xhr();
            if (xhr.upload) {

                xhr.upload.addEventListener('progress', function(event) {
                    var percent = 0;
                    var position = event.loaded || event.position; /*event.position is deprecated*/
                    var total = event.total;
                    if (event.lengthComputable) {
                        percent = Math.ceil(position / total * 100);
                        def.notify(percent);
                    }                    
                }, false);
            }
            return xhr;
        }
    });
    req.done(function(){ def.resolve.apply(def, arguments); })
       .fail(function(){ def.reject.apply(def, arguments); });

    promise.abort = function(){ return req.abort.apply(req, arguments); }

    return promise;
}

var buildMultipart = function(data){
    var key, crunks = [], bound = false;
    while (!bound) {
        bound = $.md5 ? $.md5(new Date().valueOf()) : (new Date().valueOf());
        for (key in data) if (~data[key].indexOf(bound)) { bound = false; continue; }
    }

    for (var key = 0, l = data.length; key < l; key++){
        if (typeof(data[key].value) !== "string") {
            crunks.push("--"+bound+"\r\n"+
                "Content-Disposition: form-data; name=\""+data[key].name+"\"; filename=\""+data[key].value[1]+"\"\r\n"+
                "Content-Type: application/octet-stream\r\n"+
                "Content-Transfer-Encoding: binary\r\n\r\n"+
                data[key].value[0]);
        }else{
            crunks.push("--"+bound+"\r\n"+
                "Content-Disposition: form-data; name=\""+data[key].name+"\"\r\n\r\n"+
                data[key].value);
        }
    }

    return {
        bound: bound,
        data: crunks.join("\r\n")+"\r\n--"+bound+"--"
    };
};

//----------
//---------- On submit form:
var form = $("form");
var $file = form.find("#file");
readFile($file[0].files[0]).done(function(fileData){
   var formData = form.find(":input:not('#file')").serializeArray();
   formData.file = [fileData, $file[0].files[0].name];
   upload(form.attr("action"), formData).done(function(){ alert("successfully uploaded!"); });
});

With FormData API you just have to add all fields of your form to FormData object and send it via $.ajax({ url: url, data: formData, processData: false, contentType: false, type:"POST"})

What does /p mean in set /p?

The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.

Two ways I've used it... first:

SET /P variable=

When batch file reaches this point (when left blank) it will halt and wait for user input. Input then becomes variable.

And second:

SET /P variable=<%temp%\filename.txt

Will set variable to contents (the first line) of the txt file. This method won't work unless the /P is included. Both tested on Windows 8.1 Pro, but it's the same on 7 and 10.

How to get ELMAH to work with ASP.NET MVC [HandleError] attribute?

You can take the code above and go one step further by introducing a custom controller factory that injects the HandleErrorWithElmah attribute into every controller.

For more infomation check out my blog series on logging in MVC. The first article covers getting Elmah set up and running for MVC.

There is a link to downloadable code at the end of the article. Hope that helps.

http://dotnetdarren.wordpress.com/

What is the difference between user and kernel modes in operating systems?

A processor in a computer running Windows has two different modes: user mode and kernel mode. The processor switches between the two modes depending on what type of code is running on the processor. Applications run in user mode, and core operating system components run in kernel mode. While many drivers run in kernel mode, some drivers may run in user mode.

When you start a user-mode application, Windows creates a process for the application. The process provides the application with a private virtual address space and a private handle table. Because an application's virtual address space is private, one application cannot alter data that belongs to another application. Each application runs in isolation, and if an application crashes, the crash is limited to that one application. Other applications and the operating system are not affected by the crash.

In addition to being private, the virtual address space of a user-mode application is limited. A processor running in user mode cannot access virtual addresses that are reserved for the operating system. Limiting the virtual address space of a user-mode application prevents the application from altering, and possibly damaging, critical operating system data.

All code that runs in kernel mode shares a single virtual address space. This means that a kernel-mode driver is not isolated from other drivers and the operating system itself. If a kernel-mode driver accidentally writes to the wrong virtual address, data that belongs to the operating system or another driver could be compromised. If a kernel-mode driver crashes, the entire operating system crashes.

If you are a Windows user once go through this link you will get more.

Communication between user mode and kernel mode

If conditions in a Makefile, inside a target

You can simply use shell commands. If you want to suppress echoing the output, use the "@" sign. For example:

clean:
    @if [ "test" = "test" ]; then\
        echo "Hello world";\
    fi

Note that the closing ";" and "\" are necessary.

getting error HTTP Status 405 - HTTP method GET is not supported by this URL but not used `get` ever?

I think your issue may be in the url pattern. Changing

<servlet-mapping>
    <servlet-name>Register</servlet-name>
    <url-pattern>/Register</url-pattern>
</servlet-mapping>

and

<form action="/Register" method="post">

may fix your problem

java.lang.NoClassDefFoundError: org/json/JSONObject

Please add the following dependency http://mvnrepository.com/artifact/org.json/json/20080701

<dependency>
   <groupId>org.json</groupId>
   <artifactId>json</artifactId>
   <version>20080701</version>
</dependency>

SQL UPDATE SET one column to be equal to a value in a related table referenced by a different column?

 select p.post_title,m.meta_value sale_price ,n.meta_value   regular_price
    from  wp_postmeta m 
    inner join wp_postmeta n
      on m.post_id  = n.post_id
    inner join wp_posts p
      ON m.post_id=p.id 
    and m.meta_key = '_sale_price'
    and  n.meta_key = '_regular_price'
     AND p.post_type = 'product';



 update  wp_postmeta m 
inner join wp_postmeta n
  on m.post_id  = n.post_id
inner join wp_posts p
  ON m.post_id=p.id 
and m.meta_key = '_sale_price'
and  n.meta_key = '_regular_price'
 AND p.post_type = 'product'
 set m.meta_value = n.meta_value;

Bundler: Command not found

I did this (Ubuntu latest as of March 2013 [ I think :) ]):

sudo gem install bundler

Credit goes to Ray Baxter.

If you need gem, I installed Ruby this way (though this is chronically taxing):

mkdir /tmp/ruby && cd /tmp/ruby
wget http://ftp.ruby-lang.org/pub/ruby/1.9/ruby-1.9.3-p327.tar.gz
tar xfvz ruby-1.9.3-p327.tar.gz
cd ruby-1.9.3-p327
./configure
make
sudo make install

Open Source Alternatives to Reflector?

Actually, I'm pretty sure Reflector is considered a disassembler with some decompiler functionality. Disassembler because it reads the bytes out of an assembly's file and converts it to an assembly language (ILasm in this case). The Decompiler functionality it provides by parsing the IL into well known patterns (like expressions and statements) which then get translated into higher level languages like C#, VB.Net, etc. The addin api for Reflector allows you to write your own language translator if you wish ... however the magic of how it parses the IL into the expression trees is a closely guarded secret.

I would recommend looking at any of the three things mentioned above if you want to understand how IL disassemblers work: Dile, CCI and Mono are all good sources for this stuff.

I also highly recommend getting the Ecma 335 spec and Serge Lidin's book too.

What is sr-only in Bootstrap 3?

I found this in the navbar example, and simplified it.

<ul class="nav">
  <li><a>Default</a></li>
  <li><a>Static top</a></li>
  <li><b><a>Fixed top <span class="sr-only">(current)</span></a></b></li>
</ul>

You see which one is selected (sr-only part is hidden):

  • Default
  • Static top
  • Fixed top

You hear which one is selected if you use screen reader:

  • Default
  • Static top
  • Fixed top (current)

As a result of this technique blind people supposed to navigate easier on your website.

Splitting dataframe into multiple dataframes

Groupby can helps you:

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

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

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

l_grouped = list(grouped)

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

Android - SMS Broadcast receiver

Your broadcast receiver must specify android:exported="true" to receive broadcasts created outside your own application. My broadcast receiver is defined in the manifest as follows:

<receiver
    android:name=".IncomingSmsBroadcastReceiver"
    android:enabled="true"
    android:exported="true" >
    <intent-filter>
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

As noted below, exported="true" is the default, so you can omit this line. I've left it in so that the discussion comments make sense.

ApiNotActivatedMapError for simple html page using google-places-api

as of Jan 2017, unfortunately @Adi's answer, while it seems like it should work, does not. (Google's API key process is buggy)

you'll need to click "get a key" from this link: https://developers.google.com/maps/documentation/javascript/get-api-key

also I strongly recommend you don't ever choose "secure key" until you are ready to switch to production. I did http referrer restrictions on a key and afterwards was unable to get it working with localhost, even after disabling security for the key. I had to create a new key for it to work again.

JavaScript function to add X months to a date

As demonstrated by many of the complicated, ugly answers presented, Dates and Times can be a nightmare for programmers using any language. My approach is to convert dates and 'delta t' values into Epoch Time (in ms), perform any arithmetic, then convert back to "human time."

// Given a number of days, return a Date object
//   that many days in the future. 
function getFutureDate( days ) {

    // Convert 'days' to milliseconds
    var millies = 1000 * 60 * 60 * 24 * days;

    // Get the current date/time
    var todaysDate = new Date();

    // Get 'todaysDate' as Epoch Time, then add 'days' number of mSecs to it
    var futureMillies = todaysDate.getTime() + millies;

    // Use the Epoch time of the targeted future date to create
    //   a new Date object, and then return it.
    return new Date( futureMillies );
}

// Use case: get a Date that's 60 days from now.
var twoMonthsOut = getFutureDate( 60 );

This was written for a slightly different use case, but you should be able to easily adapt it for related tasks.

EDIT: Full source here!

Base64 length calculation?

For reference, the Base64 encoder's length formula is as follows:

Base64 encoder's length formula

As you said, a Base64 encoder given n bytes of data will produce a string of 4n/3 Base64 characters. Put another way, every 3 bytes of data will result in 4 Base64 characters. EDIT: A comment correctly points out that my previous graphic did not account for padding; the correct formula is Ceiling(4n/3).

The Wikipedia article shows exactly how the ASCII string Man encoded into the Base64 string TWFu in its example. The input string is 3 bytes, or 24 bits, in size, so the formula correctly predicts the output will be 4 bytes (or 32 bits) long: TWFu. The process encodes every 6 bits of data into one of the 64 Base64 characters, so the 24-bit input divided by 6 results in 4 Base64 characters.

You ask in a comment what the size of encoding 123456 would be. Keeping in mind that every every character of that string is 1 byte, or 8 bits, in size (assuming ASCII/UTF8 encoding), we are encoding 6 bytes, or 48 bits, of data. According to the equation, we expect the output length to be (6 bytes / 3 bytes) * 4 characters = 8 characters.

Putting 123456 into a Base64 encoder creates MTIzNDU2, which is 8 characters long, just as we expected.

How do you uninstall all dependencies listed in package.json (NPM)?

If using Bash, just switch into the folder that has your package.json file and run the following:

for package in `ls node_modules`; do npm uninstall $package; done;

In the case of globally-installed packages, switch into your %appdata%/npm folder (if on Windows) and run the same command.

EDIT: This command breaks with npm 3.3.6 (Node 5.0). I'm now using the following Bash command, which I've mapped to npm_uninstall_all in my .bashrc file:

npm uninstall `ls -1 node_modules | tr '/\n' ' '`

Added bonus? it's way faster!

https://github.com/npm/npm/issues/10187

Verifying a specific parameter with Moq

I've been verifying calls in the same manner - I believe it is the right way to do it.

mockSomething.Verify(ms => ms.Method(
    It.IsAny<int>(), 
    It.Is<MyObject>(mo => mo.Id == 5 && mo.description == "test")
  ), Times.Once());

If your lambda expression becomes unwieldy, you could create a function that takes MyObject as input and outputs true/false...

mockSomething.Verify(ms => ms.Method(
    It.IsAny<int>(), 
    It.Is<MyObject>(mo => MyObjectFunc(mo))
  ), Times.Once());

private bool MyObjectFunc(MyObject myObject)
{
  return myObject.Id == 5 && myObject.description == "test";
}

Also, be aware of a bug with Mock where the error message states that the method was called multiple times when it wasn't called at all. They might have fixed it by now - but if you see that message you might consider verifying that the method was actually called.

EDIT: Here is an example of calling verify multiple times for those scenarios where you want to verify that you call a function for each object in a list (for example).

foreach (var item in myList)
  mockRepository.Verify(mr => mr.Update(
    It.Is<MyObject>(i => i.Id == item.Id && i.LastUpdated == item.LastUpdated),
    Times.Once());

Same approach for setup...

foreach (var item in myList) {
  var stuff = ... // some result specific to the item
  this.mockRepository
    .Setup(mr => mr.GetStuff(item.itemId))
    .Returns(stuff);
}

So each time GetStuff is called for that itemId, it will return stuff specific to that item. Alternatively, you could use a function that takes itemId as input and returns stuff.

this.mockRepository
    .Setup(mr => mr.GetStuff(It.IsAny<int>()))
    .Returns((int id) => SomeFunctionThatReturnsStuff(id));

One other method I saw on a blog some time back (Phil Haack perhaps?) had setup returning from some kind of dequeue object - each time the function was called it would pull an item from a queue.

How to create a toggle button in Bootstrap

I've been trying to activate 'active' class manually with javascript. It's not as usable as a complete library, but for easy cases seems to be enough:

var button = $('#myToggleButton');
button.on('click', function () {
  $(this).toggleClass('active');
});

If you think carefully, 'active' class is used by bootstrap when the button is being pressed, not before or after that (our case), so there's no conflict in reuse the same class.

Try this example and tell me if it fails: http://jsbin.com/oYoSALI/1/edit?html,js,output

Exception in thread "main" java.lang.UnsupportedClassVersionError: a (Unsupported major.minor version 51.0)

Copy the contents of the PATH settings to a notepad and check if the location for the 1.4.2 comes before that of the 7. If so, remove the path to 1.4.2 in the PATH setting and save it.

After saving and applying "Environment Variables" close and reopen the cmd line. In XP the path does no get reflected in already running programs.

Jquery submit form

Use the following jquery to submit a selectbox with out a submit button. Use "change" instead of click as shown above.

$("selectbox").change(function() { 
   document.forms["form"].submit();
});

Cheers!

How to find indices of all occurrences of one string in another in JavaScript?

function countInString(searchFor,searchIn){

 var results=0;
 var a=searchIn.indexOf(searchFor)

 while(a!=-1){
   searchIn=searchIn.slice(a*1+searchFor.length);
   results++;
   a=searchIn.indexOf(searchFor);
 }

return results;

}

Embedding Windows Media Player for all browsers

I found a good article about using the WMP with Firefox on MSDN.

Based on MSDN's article and after doing some trials and errors, I found using JavaScript is better than using conditional comments or nested "EMBED/OBJECT" tags.

I made a JS function that generate WMP object based on given arguments:

<script type="text/javascript">
    function generateWindowsMediaPlayer(
        holderId,   // String
        height,     // Number
        width,      // Number
        videoUrl    // String
        // you can declare more arguments for more flexibility
        ) {
        var holder = document.getElementById(holderId);

        var player = '<object ';
        player += 'height="' + height.toString() + '" ';
        player += 'width="' + width.toString() + '" ';

        videoUrl = encodeURI(videoUrl); // Encode for special characters

        if (navigator.userAgent.indexOf("MSIE") < 0) {
            // Chrome, Firefox, Opera, Safari
            //player += 'type="application/x-ms-wmp" '; //Old Edition
            player += 'type="video/x-ms-wmp" '; //New Edition, suggested by MNRSullivan (Read Comments)
            player += 'data="' + videoUrl + '" >';
        }
        else {
            // Internet Explorer
            player += 'classid="clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6" >';
            player += '<param name="url" value="' + videoUrl + '" />';
        }

        player += '<param name="autoStart" value="false" />';
        player += '<param name="playCount" value="1" />';
        player += '</object>';

        holder.innerHTML = player;
    }
</script>

Then I used that function by writing some markups and inline JS like these:

<div id='wmpHolder'></div>

<script type="text/javascript">        
    window.addEventListener('load', generateWindowsMediaPlayer('wmpHolder', 240, 320, 'http://mysite.com/path/video.ext'));
</script>

You can use jQuery.ready instead of window load event to making the codes more backward-compatible and cross-browser.

I tested the codes over IE 9-10, Chrome 27, Firefox 21, Opera 12 and Safari 5, on Windows 7/8.

When and why to 'return false' in JavaScript?

Also, this short and interesting link to read through https://www.w3schools.com/jsref/event_preventdefault.asp

Definition and Usage

The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.

For example, this can be useful when:

Clicking on a "Submit" button, prevent it from submitting a form
Clicking on a link, prevent the link from following the URL

Note: Not all events are cancelable. Use the cancelable property to find out if an event is cancelable.

Note: The preventDefault() method does not prevent further propagation of an event through the DOM. Use the stopPropagation() method to handle this.

Phonegap + jQuery Mobile, real world sample or tutorial

This is a nice 5-part tutorial that covers a lot of useful material: http://mobile.tutsplus.com/tutorials/phonegap/phonegap-from-scratch/
(Anyone else noticing a trend forming here??? hehehee )

And this will definitely be of use to all developers:
http://blip.tv/mobiletuts/weinre-demonstration-5922038
=)
Todd

Edit I just finished a nice four part tutorial building an app to write, save, edit, & delete notes using jQuery mobile (only), it was very practical & useful, but it was also only for jQM. So, I looked to see what else they had on DZone.

I'm now going to start sorting through these search results. At a glance, it looks really promising. I remembered this post; so I thought I'd steer people to it. ?

What is the correct JSON content type?

Of course, the correct MIME media type for JSON is application/json, but it's necessary to realize what type of data is expected in your application.

For example, I use Ext GWT and the server response must go as text/html but contains JSON data.

Client side, Ext GWT form listener

uploadForm.getForm().addListener(new FormListenerAdapter()
{
    @Override
    public void onActionFailed(Form form, int httpStatus, String responseText) 
    {
        MessageBox.alert("Error");
    }

    @Override
    public void onActionComplete(Form form, int httpStatus, String responseText) 
    {
        MessageBox.alert("Success");
    }
});

In case of using application/json response type, the browser suggests me to save the file.

Server side source code snippet using Spring MVC

return new AbstractUrlBasedView() 
{
    @SuppressWarnings("unchecked")
    @Override
    protected void renderMergedOutputModel(Map model, HttpServletRequest request,
                                           HttpServletResponse response) throws Exception 
    {
        response.setContentType("text/html");
        response.getWriter().write(json);
    }
};

Jquery: how to trigger click event on pressing enter key

_x000D_
_x000D_
     $('#Search').keyup(function(e)_x000D_
        {_x000D_
            if (event.keyCode === 13) {_x000D_
            e.preventDefault();_x000D_
            var searchtext = $('#Search').val();_x000D_
            window.location.href = "searchData.php?Search=" + searchtext + '&bit=1';_x000D_
            }_x000D_
        });
_x000D_
_x000D_
_x000D_

App installation failed due to application-identifier entitlement

You will get this error when your AppID prefix does not match the prefix of the previously installed app. If your app is already in the App Store, you will not be able to submit updates without restoring the original AppID prefix or contacting Apple.

Apple's instructions for handling this problem: https://developer.apple.com/library/content/technotes/tn2319/_index.html#//apple_ref/doc/uid/DTS40013778-CH1-ERRORMESSAGES-UPGRADE_S_APPLICATION_IDENTIFIER_DOES_NOT_MATCH_THE_INSTALLED_APP

If you did not intend to change the AppID prefix then Xcode is signing your app with the wrong provisioning profile.

If you do intend to change the AppID prefix (because the app was transferred to a new developer, or you are migrating from an old pre-2011 AppID) you must contact Apple to migrate an existing AppID to a new prefix.

You must also add the previous-application-identifiers entitlement to your app, listing all previous AppIDs (with old prefixes). And you must ask Apple to generate a provisioning profile for you that includes the previous-application-identifiers entitlement.

Get column from a two dimensional array

_x000D_
_x000D_
function arrayColumn(arr, n) {_x000D_
  return arr.map(x=> x[n]);_x000D_
}_x000D_
_x000D_
var twoDimensionalArray = [_x000D_
  [1, 2, 3],_x000D_
  [4, 5, 6],_x000D_
  [7, 8, 9]_x000D_
];_x000D_
_x000D_
console.log(arrayColumn(twoDimensionalArray, 1));
_x000D_
_x000D_
_x000D_

Squash the first two commits in Git?

You could use rebase interactive to modify the last two commits before they've been pushed to a remote

git rebase HEAD^^ -i

SQL Server ORDER BY date and nulls last

According to Itzik Ben-Gan, author of T-SQL Fundamentals for MS SQL Server 2012, "By default, SQL Server sorts NULL marks before non-NULL values. To get NULL marks to sort last, you can use a CASE expression that returns 1 when the" Next_Contact_Date column is NULL, "and 0 when it is not NULL. Non-NULL marks get 0 back from the expression; therefore, they sort before NULL marks (which get 1). This CASE expression is used as the first sort column." The Next_Contact_Date column "should be specified as the second sort column. This way, non-NULL marks sort correctly among themselves." Here is the solution query for your example for MS SQL Server 2012 (and SQL Server 2014):

ORDER BY 
   CASE 
        WHEN Next_Contact_Date IS NULL THEN 1
        ELSE 0
   END, Next_Contact_Date;

Equivalent code using IIF syntax:

ORDER BY 
   IIF(Next_Contact_Date IS NULL, 1, 0),
   Next_Contact_Date;

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

Just about every modern operating system will recover all the allocated memory space after a program exits. The only exception I can think of might be something like Palm OS where the program's static storage and runtime memory are pretty much the same thing, so not freeing might cause the program to take up more storage. (I'm only speculating here.)

So generally, there's no harm in it, except the runtime cost of having more storage than you need. Certainly in the example you give, you want to keep the memory for a variable that might be used until it's cleared.

However, it's considered good style to free memory as soon as you don't need it any more, and to free anything you still have around on program exit. It's more of an exercise in knowing what memory you're using, and thinking about whether you still need it. If you don't keep track, you might have memory leaks.

On the other hand, the similar admonition to close your files on exit has a much more concrete result - if you don't, the data you wrote to them might not get flushed, or if they're a temp file, they might not get deleted when you're done. Also, database handles should have their transactions committed and then closed when you're done with them. Similarly, if you're using an object oriented language like C++ or Objective C, not freeing an object when you're done with it will mean the destructor will never get called, and any resources the class is responsible might not get cleaned up.

How do I perform a Perl substitution on a string while keeping the original?

If you write Perl with use strict;, then you'll find that the one line syntax isn't valid, even when declared.

With:

my ($newstring = $oldstring) =~ s/foo/bar/;

You get:

Can't declare scalar assignment in "my" at script.pl line 7, near ") =~"
Execution of script.pl aborted due to compilation errors.

Instead, the syntax that you have been using, while a line longer, is the syntactically correct way to do it with use strict;. For me, using use strict; is just a habit now. I do it automatically. Everyone should.

#!/usr/bin/env perl -wT

use strict;

my $oldstring = "foo one foo two foo three";
my $newstring = $oldstring;
$newstring =~ s/foo/bar/g;

print "$oldstring","\n";
print "$newstring","\n";

Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed

Whoever still having the same issue. Please add the following line in application.properties

# The SQL dialect makes Hibernate generate better SQL for the chosen database
## I am using Mysql8 so I have declared MySQL8Dialect if you have other versions just add ## that version number
spring.jpa.properties.hibernate.dialect =  org.hibernate.dialect.MySQL8Dialect

How do you get a directory listing in C?

There is no standard C (or C++) way to enumerate files in a directory.

Under Windows you can use the FindFirstFile/FindNextFile functions to enumerate all entries in a directory. Under Linux/OSX use the opendir/readdir/closedir functions.

How to increase size of DOSBox window?

Here's how to change the dosbox.conf file in Linux to increase the size of the window. I actually DID what follows, so I can say it works (in 32-bit PCLinuxOS fullmontyKDE, anyway). The question's answer is in the .conf file itself.

You find this file in Linux at /home/(username)/.dosbox . In Konqueror or Dolphin, you must first check 'Hidden files' or you won't see the folder. Open it with KWrite superuser or your fav editor.

  1. Save the file with another name like 'dosbox-0.74original.conf' to preserve the original file in case you need to restore it.
  2. Search on 'resolution' and carefully read what the conf file says about changing it. There are essentially two variables: resolution and output. You want to leave fullresolution alone for now. Your question was about WINDOW, not full. So look for windowresolution, see what the comments in conf file say you can do. The best suggestion is to use a bigger-window resolution like 900x800 (which is what I used on a 1366x768 screen), but NOT the actual resolution of your machine (which would make the window fullscreen, and you said you didn't want that). Be specific, replacing the 'windowresolution=original' with 'windowresolution=900x800' or other dimensions. On my screen, that doubled the window size just as it does with the max Font tab in Windows Properties (for the exe file; as you'll see below the ==== marks, 32-bit Windows doesn't need Dosbox).

Then, search on 'output', and as the instruction in the conf file warns, if and only if you have 'hardware scaling', change the default 'output=surface' to something else; he then lists the optional other settings. I changed it to 'output=overlay'. There's one other setting to test: aspect. Search the file for 'aspect', and change the 'false' to 'true' if you want an even bigger window. When I did this, the window took up over half of the screen. With 'false' left alone, I had a somewhat smaller window (I use widescreen monitors, whether laptop or desktop, maybe that's why).

So after you've made the changes, save the file with the original name of dosbox-0.74.conf . Then, type dosbox at the command line or create a Launcher (in KDE, this is a right click on the desktop) with the command dosbox. You still have to go through the mount command (i.e., mount c~ c:\123 if that's the location and file you'll execute). I'm sure there's a way to make a script, but haven't yet learned how to do that.

Loop through each row of a range in Excel

In Loops, I always prefer to use the Cells class, using the R1C1 reference method, like this:

Cells(rr, col).Formula = ...

This allows me to quickly and easily loop over a Range of cells easily:

Dim r As Long
Dim c As Long

c = GetTargetColumn() ' Or you could just set this manually, like: c = 1

With Sheet1 ' <-- You should always qualify a range with a sheet!

    For r = 1 To 10 ' Or 1 To (Ubound(MyListOfStuff) + 1)

        ' Here we're looping over all the cells in rows 1 to 10, in Column "c"
        .Cells(r, c).Value = MyListOfStuff(r)

        '---- or ----

        '...to easily copy from one place to another (even with an offset of rows and columns)
        .Cells(r, c).Value = Sheet2.Cells(r + 3, 17).Value


    Next r

End With

What is the use of "assert"?

As written in other answers, assert statements are used to check the state of the program at a given point.

I won't repeat what was said about associated message, parentheses, or -O option and __debug__ constant. Check also the doc for first hand information. I will focus on your question: what is the use of assert? More precisely, when (and when not) should one use assert?

The assert statements are useful to debug a program, but discouraged to check user input. I use the following rule of thumb: keep assertions to detect a this should not happen situation. A user input may be incorrect, e.g. a password too short, but this is not a this should not happen case. If the diameter of a circle is not twice as large as its radius, you are in a this should not happen case.

The most interesting, in my mind, use of assert is inspired by the programming by contract as described by B. Meyer in [Object-Oriented Software Construction]( https://www.eiffel.org/doc/eiffel/Object-Oriented_Software_Construction%2C_2nd_Edition ) and implemented in the [Eiffel programming language]( https://en.wikipedia.org/wiki/Eiffel_(programming_language)). You can't fully emulate programming by contract using the assert statement, but it's interesting to keep the intent.

Here's an example. Imagine you have to write a head function (like the [head function in Haskell]( http://www.zvon.org/other/haskell/Outputprelude/head_f.html)). The specification you are given is: "if the list is not empty, return the first item of a list". Look at the following implementations:

>>> def head1(xs): return xs[0]

And

>>> def head2(xs):
...     if len(xs) > 0:
...         return xs[0]
...     else:
...         return None

(Yes, this can be written as return xs[0] if xs else None, but that's not the point).

If the list is not empty, both functions have the same result and this result is correct:

>>> head1([1, 2, 3]) == head2([1, 2, 3]) == 1
True

Hence, both implementations are (I hope) correct. They differ when you try to take the head item of an empty list:

>>> head1([])
Traceback (most recent call last):
...
IndexError: list index out of range

But:

>>> head2([]) is None
True

Again, both implementations are correct, because no one should pass an empty list to these functions (we are out of the specification). That's an incorrect call, but if you do such a call, anything can happen. One function raises an exception, the other returns a special value. The most important is: we can't rely on this behavior. If xs is empty, this will work:

print(head2(xs))

But this will crash the program:

print(head1(xs))

To avoid some surprises, I would like to know when I'm passing some unexpected argument to a function. In other words: I would like to know when the observable behavior is not reliable, because it depends on the implementation, not on the specification. Of course, I can read the specification, but programmers do not always read carefully the docs.

Imagine if I had a way to insert the specification into the code to get the following effect: when I violate the specification, e.g by passing an empty list to head, I get a warning. That would be a great help to write a correct (i.e. compliant with the specification) program. And that's where assert enters on the scene:

>>> def head1(xs):
...     assert len(xs) > 0, "The list must not be empty"
...     return xs[0]

And

>>> def head2(xs):
...     assert len(xs) > 0, "The list must not be empty"
...     if len(xs) > 0:
...         return xs[0]
...     else:
...         return None

Now, we have:

>>> head1([])
Traceback (most recent call last):
...
AssertionError: The list must not be empty

And:

>>> head2([])
Traceback (most recent call last):
...
AssertionError: The list must not be empty

Note that head1 throws an AssertionError, not an IndexError. That's important because an AssertionError is not any runtime error: it signals a violation of the specification. I wanted a warning, but I get an error. Fortunately, I can disable the check (using the -O option), but at my own risks. I will do it a crash is really expensive, and hope for the best. Imagine my program is embedded in a spaceship that travels through a black hole. I will disable assertions and hope the program is robust enough to not crash as long as possible.

This example was only about preconditions, be you can use assert to check postconditions (the return value and/or the state) and invariants (state of a class). Note that checking postconditions and invariants with assert can be cumbersome:

  • for postconditions, you need to assign the return value to a variable, and maybe to store the iniial state of the object if you are dealing with a method;
  • for invariants, you have to check the state before and after a method call.

You won't have something as sophisticated as Eiffel, but you can however improve the overall quality of a program.


To summarize, the assert statement is a convenient way to detect a this should not happen situation. Violations of the specification (e.g. passing an empty list to head) are first class this should not happen situations. Hence, while the assert statement may be used to detect any unexpected situation, it is a privilegied way to ensure that the specification is fulfilled. Once you have inserted assert statements into the code to represent the specification, we can hope you have improved the quality of the program because incorrect arguments, incorrect return values, incorrect states of a class..., will be reported.

sys.path different in Jupyter and Python - how to import own modules in Jupyter?

Here is what I do on my projects in jupyter notebook,

import sys
sys.path.append("../") # go to parent dir
from customFunctions import *

Then, to affect changes in customFunctions.py,

%load_ext autoreload
%autoreload 2

git ignore exception

If you're working with Visual Studio and your .dll happens to be in a bin folder, then you'll need to add an exception for the particular bin folder itself, before you can add the exception for the .dll file. E.g.

!SourceCode/Solution/Project/bin
!SourceCode/Solution/Project/bin/My.dll

This is because the default Visual Studio .gitignore file includes an ignore pattern for [Bbin]/

This pattern is zapping all bin folders (and consequently their contents), which makes any attempt to include the contents redundant (since the folder itself is already ignored).

I was able to find why my file wasn't being excepted by running

git check-ignore -v -- SourceCode/Solution/Project/bin/My.dll

from a Git Bash window. This returned the [Bbin]/ pattern.

Is it a good idea to index datetime field in mysql?

MySQL recommends using indexes for a variety of reasons including elimination of rows between conditions: http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html

This makes your datetime column an excellent candidate for an index if you are going to be using it in conditions frequently in queries. If your only condition is BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY) and you have no other index in the condition, MySQL will have to do a full table scan on every query. I'm not sure how many rows are generated in 30 days, but as long as it's less than about 1/3 of the total rows it will be more efficient to use an index on the column.

Your question about creating an efficient database is very broad. I'd say to just make sure that it's normalized and all appropriate columns are indexed (i.e. ones used in joins and where clauses).

Sublime Text 2 multiple line edit

ctrl + shift + right-click it works better that way

Angularjs - ng-cloak/ng-show elements blink

I personally decided to use the ng-class attribute rather than the ng-show. I've had a lot more success going this route especially for pop-up windows that are always not shown by default.

What used to be <div class="options-modal" ng-show="showOptions"></div>

is now: <div class="options-modal" ng-class="{'show': isPrintModalShown}">

with the CSS for the options-modal class being display: none by default. The show class contains the display:block CSS.