Programs & Examples On #Intraweb

IntraWeb is a tool for creating web forms applications emitted in HTML and Javascript, written in Delphi or C++ (from Embarcadero) and built on the Visual Component Library.

How to present UIAlertController when not in a view controller?

I posted a similar question a couple months ago and think I've finally solved the problem. Follow the link at the bottom of my post if you just want to see the code.

The solution is to use an additional UIWindow.

When you want to display your UIAlertController:

  1. Make your window the key and visible window (window.makeKeyAndVisible())
  2. Just use a plain UIViewController instance as the rootViewController of the new window. (window.rootViewController = UIViewController())
  3. Present your UIAlertController on your window's rootViewController

A couple things to note:

  • Your UIWindow must be strongly referenced. If it's not strongly referenced it will never appear (because it is released). I recommend using a property, but I've also had success with an associated object.
  • To ensure that the window appears above everything else (including system UIAlertControllers), I set the windowLevel. (window.windowLevel = UIWindowLevelAlert + 1)

Lastly, I have a completed implementation if you just want to look at that.

https://github.com/dbettermann/DBAlertController

Unable to read repository at http://download.eclipse.org/releases/indigo

I had the same problem and resolved it by

  • Deleting the cache directory \eclipse\p2\org.eclipse.equinox.p2.repository\cache
  • Refreshing the repositories.
    • Preferences -> Install Update -> Available Software Sites => select the entry
    • Click the "Reload"

Focus Input Box On Load

A portable way of doing this is using a custom function (to handle browser differences) like this one.

Then setup a handler for the onload at the end of your <body> tag, as jessegavin wrote:

window.onload = function() {
  document.getElementById("myinputbox").focus();
}

Setting an HTML text input box's "default" value. Revert the value when clicking ESC

See the defaultValue property of a text input, it's also used when you reset the form by clicking an <input type="reset"/> button (http://www.w3schools.com/jsref/prop_text_defaultvalue.asp )

btw, defaultValue and placeholder text are different concepts, you need to see which one better fits your needs

Algorithm to find Largest prime factor of a number

JavaScript code:

'option strict';

function largestPrimeFactor(val, divisor = 2) { 
    let square = (val) => Math.pow(val, 2);

    while ((val % divisor) != 0 && square(divisor) <= val) {
        divisor++;
    }

    return square(divisor) <= val
        ? largestPrimeFactor(val / divisor, divisor)
        : val;
}

Usage Example:

let result = largestPrimeFactor(600851475143);

Here is an example of the code:

WAMP Server doesn't load localhost

Solution(s) for this, found in the official wampserver.com forums:

SOLUTION #1:

This problem is caused by Windows (7) in combination with any software that also uses port 80 (like Skype or IIS (which is installed on most developer machines)). A video solution can be found here (34.500+ views, damn, this seems to be a big thing ! EDIT: The video now has ~60.000 views ;) )

To make it short: open command line tool, type "netstat -aon" and look for any lines that end of ":80". Note thatPID on the right side. This is the process id of the software which currently usesport 80. Press AltGr + Ctrl + Del to get into the Taskmanager. Switch to the tab where you can see all services currently running, ordered by PID. Search for that PID you just notices and stop that thing (right click). To prevent this in future, you should config the software's port settings (skype can do that).

SOLUTION #2:

left click the wamp icon in the taskbar, go to apache > httpd.conf and edit this file: change "listen to port .... 80" to 8080. Restart. Done !

SOLUTION #3:

Port 80 blocked by "Microsoft Web Deployment Service", simply deinstall this, more info here

By the way, it's not Microsoft's fault, it's a stupid usage of ports by most WAMP stacks.

IMPORTANT: you have to use localhost or 127.0.0.1 now with port 8080, this means 127.0.0.1:8080 or localhost:8080.

There isn't anything to compare. Nothing to compare, branches are entirely different commit histories

Top guy is probably right that you downloaded instead of cloning the repo at start. Here is a easy solution without getting too technical.

  • In a new editor window, clone your repo in another directory.
  • Make a new branch.
  • Then copy from your your edited editor window into your new repo by copy paste.

Make sure that all your edits are copied over by looking at your older github branch.

How to make child process die after parent exits?

As other people have pointed out, relying on the parent pid to become 1 when the parent exits is non-portable. Instead of waiting for a specific parent process ID, just wait for the ID to change:

pit_t pid = getpid();
switch (fork())
{
    case -1:
    {
        abort(); /* or whatever... */
    }
    default:
    {
        /* parent */
        exit(0);
    }
    case 0:
    {
        /* child */
        /* ... */
    }
}

/* Wait for parent to exit */
while (getppid() != pid)
    ;

Add a micro-sleep as desired if you don't want to poll at full speed.

This option seems simpler to me than using a pipe or relying on signals.

Fetch API with Cookie

Fetch does not use cookie by default. To enable cookie, do this:

fetch(url, {
  credentials: "same-origin"
}).then(...).catch(...);

PHP Warning: PHP Startup: ????????: Unable to initialize module

This happened to me when I tried to install a newer version of PHP. After finding that I also would need to reconfigure Apache for that I switched back to the old PHP version. Here the solution which worked for me:

change the httpd.conf to the correct versions:

 PHPIniDir ...
 LoadModule php5_module ...

Changed the

PATH - Environment Variable

When that does not take any effect

rename or delete the new PHP(-Version)-Folder

For some reason the last step did the trick for me. Even after a restart it did not have an effect before doing this.

Recreating a Dictionary from an IEnumerable<KeyValuePair<>>

If you're using .NET 3.5 or .NET 4, it's easy to create the dictionary using LINQ:

Dictionary<string, ArrayList> result = target.GetComponents()
                                      .ToDictionary(x => x.Key, x => x.Value);

There's no such thing as an IEnumerable<T1, T2> but a KeyValuePair<TKey, TValue> is fine.

SQL Server - stop or break execution of a SQL script

you could wrap your SQL statement in a WHILE loop and use BREAK if needed

WHILE 1 = 1
BEGIN
   -- Do work here
   -- If you need to stop execution then use a BREAK


    BREAK; --Make sure to have this break at the end to prevent infinite loop
END

How to remove specific value from array using jQuery

/** SUBTRACT ARRAYS **/

function subtractarrays(array1, array2){
    var difference = [];
    for( var i = 0; i < array1.length; i++ ) {
        if( $.inArray( array1[i], array2 ) == -1 ) {
                difference.push(array1[i]);
        }
    }
return difference;
}  

You can then call the function anywhere in your code.

var I_like    = ["love", "sex", "food"];
var she_likes = ["love", "food"];

alert( "what I like and she does't like is: " + subtractarrays( I_like, she_likes ) ); //returns "Naughty :P"!

This works in all cases and avoids the problems in the methods above. Hope that helps!

Why is my Button text forced to ALL CAPS on Lollipop?

In Android Studio IDE, you have to click the Filter icon to show expert properties. Then you will see the textAllCaps property. Check it, then uncheck it.

how do I initialize a float to its max/min value?

May I suggest that you initialize your "max and min so far" variables not to infinity, but to the first number in the array?

SQL Server Operating system error 5: "5(Access is denied.)"

Yes,It's right.The first you should find out your service account of sqlserver,you can see it in Task Manager when you press ctrl+alt+delete at the same time;Then,you must give the read/write privilege of "C:\Murach\SQL Server 2008\Databases" to the service account.

Should I mix AngularJS with a PHP framework?

It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.

It is indeed possible to have PHP render partials and whole views, but I would not recommend it.

To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.

I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.

Using PHP to render the view:

/user/account

if($loggedIn)
{
    echo "<p>Logged in as ".$user."</p>";
}
else
{
    echo "Please log in.";
}

How the same problem can be solved with an API centric approach by outputting JSON like this:

api/auth/

{
  authorized:true,
  user: {
      username: 'Joe', 
      securityToken: 'secret'
  }
}

and in Angular you could do a get, and handle the response client side.

$http.post("http://example.com/api/auth", {})
.success(function(data) {
    $scope.isLoggedIn = data.authorized;
});

To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.

Get Country of IP Address with PHP

Install and use PHP's GeoIP extension if you can. On debian lenny:

sudo wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
sudo gunzip GeoLiteCity.dat.gz
sudo mkdir -v /usr/share/GeoIP
sudo mv -v GeoLiteCity.dat /usr/share/GeoIP/GeoIPCity.dat

sudo apt-get install php5-geoip
# or sudo apt-get install php-geoip for PHP7

and then try it in PHP:

$ip = $_SERVER['REMOTE_ADDR'];
$country = geoip_country_name_by_name($ip);
echo 'The current user is located in: ' . $country;

returns:

The current user is located in: Cameroon

How do I set a column value to NULL in SQL Server Management Studio?

Use This:

Update Table Set Column = CAST(NULL As Column Type) where Condition

Like This:

Update News Set Title = CAST(NULL As nvarchar(100)) Where ID = 50

How to drop rows from pandas data frame that contains a particular string in a particular column?

This will only work if you want to compare exact strings. It will not work in case you want to check if the column string contains any of the strings in the list.

The right way to compare with a list would be :

searchfor = ['john', 'doe']
df = df[~df.col.str.contains('|'.join(searchfor))]

How to find SQL Server running port?

Try to enable the protocol by: Configuration Manger > SQL server Network Configuration > Protocols for MSSQLSERVER > properties of TCP/IP

parsing JSONP $http.jsonp() response in angular.js

This was very helpful. Angular doesn't work exactly like JQuery. It has its own jsonp() method, which indeed requires "&callback=JSON_CALLBACK" at the end of the query string. Here's an example:

var librivoxSearch = angular.module('librivoxSearch', []);
librivoxSearch.controller('librivoxSearchController', function ($scope, $http) {
    $http.jsonp('http://librivox.org/api/feed/audiobooks/author/Melville?format=jsonp&callback=JSON_CALLBACK').success(function (data) {
        $scope.data = data;
    });
});

Then display or manipulate {{ data }} in your Angular template.

What is the meaning of CTOR?

To expand a little more, there are two kinds of constructors: instance initializers (.ctor), type initializers (.cctor). Build the code below, and explore the IL code in ildasm.exe. You will notice that the static field 'b' will be initialized through .cctor() whereas the instance field will be initialized through .ctor()

internal sealed class CtorExplorer
{
   protected int a = 0;
   protected static int b = 0;
}

Sublime Text 3, convert spaces to tabs

As you might already know, you can customize your indention settings in Preferences.sublime-settings, for example:

"detect_indentation": true,
"tab_size": 4,
"translate_tabs_to_spaces": false

This will set your editor to use tabs that are 4 spaces wide and will override the default behavior that causes Sublime to match the indention of whatever file you're editing. With these settings, re-indenting the file will cause any spaces to be replaced with tabs.

As far as automatically re-indenting when opening a file, that's not quite as easy (but probably isn't a great idea since whitespace changes wreak havoc on file diffs). What might be a better course of action: you can map a shortcut for re-indention and just trigger that when you open a new file that needs fixing.

Should I initialize variable within constructor or outside constructor

It can depend on what your are initialising, for example you cannot just use field initialisation if a checked exception is involved. For example, the following:

public class Foo {
    FileInputStream fis = new FileInputStream("/tmp"); // throws FileNotFoundException
}

Will cause a compile-time error unless you also include a constructor declaring that checked exception, or extend a superclass which does, e.g.:

public Foo() throws FileNotFoundException {} 

Change Primary Key

You will need to drop and re-create the primary key like this:

alter table my_table drop constraint my_pk;
alter table my_table add constraint my_pk primary key (city_id, buildtime, time);

However, if there are other tables with foreign keys that reference this primary key, then you will need to drop those first, do the above, and then re-create the foreign keys with the new column list.

An alternative syntax to drop the existing primary key (e.g. if you don't know the constraint name):

alter table my_table drop primary key;

Copy all files with a certain extension from all subdirectories

I also had to do this myself. I did it via the --parents argument for cp:

find SOURCEPATH -name filename*.txt -exec cp --parents {} DESTPATH \;

Hide Signs that Meteor.js was Used

The amount of hacks you would need to go through to completely hide the fact your site is built by Meteor.js is absolutely ridiculous. You would have to strip essentially all core functionality and just serve straight up html, completely defeating the purpose of using the framework anyway.

That being said, I suggest looking at buildwith.com

You enter a url, and it reveals a ton of information about a site. If you only need to "fool" engines like this, there may be simple solutions.

Giving multiple URL patterns to Servlet Filter

If an URL pattern starts with /, then it's relative to the context root. The /Admin/* URL pattern would only match pages on http://localhost:8080/EMS2/Admin/* (assuming that /EMS2 is the context path), but you have them actually on http://localhost:8080/EMS2/faces/Html/Admin/*, so your URL pattern never matches.

You need to prefix your URL patterns with /faces/Html as well like so:

<url-pattern>/faces/Html/Admin/*</url-pattern>

You can alternatively also just reconfigure your web project structure/configuration so that you can get rid of the /faces/Html path in the URLs so that you can just open the page by for example http://localhost:8080/EMS2/Admin/Upload.xhtml.

Your filter mapping syntax is all fine. However, a simpler way to specify multiple URL patterns is to just use only one <filter-mapping> with multiple <url-pattern> entries:

<filter-mapping>
    <filter-name>LoginFilter</filter-name>
    <url-pattern>/faces/Html/Employee/*</url-pattern>
    <url-pattern>/faces/Html/Admin/*</url-pattern>
    <url-pattern>/faces/Html/Supervisor/*</url-pattern>
</filter-mapping>

Centering controls within a form in .NET (Winforms)?

In addition, if you want to align it to the center of another control:

//The "ctrlParent" is the one on which you want to align "ctrlToCenter".
//"ctrlParent" can be your "form name" or any other control such as "grid name" and etc.
ctrlToCenter.Parent = ctrlParent;

ctrlToCenter.Left = (ctrlToCenter.Parent.Width - ctrlToCenter.Width) / 2;
ctrlToCenter.Top = (ctrlToCenter.Parent.Height - ctrlToCenter.Height) / 2;

Pass a simple string from controller to a view MVC3

To pass a string to the view as the Model, you can do:

public ActionResult Index()
{
    string myString = "This is my string";
    return View((object)myString);
}

You must cast it to an object so that MVC doesn't try to load the string as the view name, but instead pass it as the model. You could also write:

return View("Index", myString);

.. which is a bit more verbose.

Then in your view, just type it as a string:

@model string

<p>Value: @Model</p>

Then you can manipulate Model how you want.

For accessing it from a Layout page, it might be better to create an HtmlExtension for this:

public static string GetThemePath(this HtmlHelper helper)
{
    return "/path-to-theme";
}

Then inside your layout page:

<p>Value: @Html.GetThemePath()</p>

Hopefully you can apply this to your own scenario.

Edit: explicit HtmlHelper code:

namespace <root app namespace>
{
    public static class Helpers
    {
        public static string GetThemePath(this HtmlHelper helper)
        {
            return System.Web.Hosting.HostingEnvironment.MapPath("~") + "/path-to-theme";
        }
    }
}

Then in your view:

@{
    var path = Html.GetThemePath();
    // .. do stuff
}

Or: <p>Path: @Html.GetThemePath()</p>

Edit 2:

As discussed, the Helper will work if you add a @using statement to the top of your view, with the namespace pointing to the one that your helper is in.

Text-align class for inside a table

The following lines of code are working properly. You can assign the classes like text-center, left or right, The text will align accordingly.

<p class="text-center">Day 1</p> 
<p class="text-left">Day 2</p> 
<p class="text-right">Day 3</p>

Here there isn't any need to create any external class. These are the Bootstrap classes and have their own property.

$ is not a function - jQuery error

As RPM1984 refers to, this is mostly likely caused by the fact that your script is loading before jQuery is loaded.

How to modify a text file?

Python's mmap module will allow you to insert into a file. The following sample shows how it can be done in Unix (Windows mmap may be different). Note that this does not handle all error conditions and you might corrupt or lose the original file. Also, this won't handle unicode strings.

import os
from mmap import mmap

def insert(filename, str, pos):
    if len(str) < 1:
        # nothing to insert
        return

    f = open(filename, 'r+')
    m = mmap(f.fileno(), os.path.getsize(filename))
    origSize = m.size()

    # or this could be an error
    if pos > origSize:
        pos = origSize
    elif pos < 0:
        pos = 0

    m.resize(origSize + len(str))
    m[pos+len(str):] = m[pos:origSize]
    m[pos:pos+len(str)] = str
    m.close()
    f.close()

It is also possible to do this without mmap with files opened in 'r+' mode, but it is less convenient and less efficient as you'd have to read and temporarily store the contents of the file from the insertion position to EOF - which might be huge.

Bootstrap button - remove outline on Chrome OS X

Here's the solution:

_x000D_
_x000D_
#sec-one{padding: 15px 0;}_x000D_
p{text-align: center;}_x000D_
/*_x000D_
* Change the color to any color you want;_x000D_
* or set to none if you don't any outline at all._x000D_
*/_x000D_
*:focus:not(a){_x000D_
    outline: 2px solid #f90d0e !important;_x000D_
    box-shadow: none !important;_x000D_
}
_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
  <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
</head>_x000D_
<body>_x000D_
<section id="sec-one">_x000D_
<div class="container">_x000D_
    <div class="row">_x000D_
      <div class="col">_x000D_
        <form>_x000D_
          <fieldset class="form-group">_x000D_
            <input type="text" class="form-control" placeholder="Full Name" required>_x000D_
          </fieldset>_x000D_
           <fieldset class="form-group">_x000D_
            <input type="email" class="form-control" placeholder="Email Address" required>_x000D_
          </fieldset>_x000D_
          <fieldset class="form-group">_x000D_
            <input type="submit" class="btn btn-default" value="Sign Up">_x000D_
          </fieldset>_x000D_
          </form>_x000D_
      </div>_x000D_
    </div>_x000D_
</div>_x000D_
</section>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

This works 100% hope it helps you.

How to parse month full form string using DateFormat in Java?

LocalDate from java.time

Use LocalDate from java.time, the modern Java date and time API, for a date

    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MMMM d, u", Locale.ENGLISH);
    LocalDate date = LocalDate.parse("June 27, 2007", dateFormatter);
    System.out.println(date);

Output:

2007-06-27

As others have said already, remember to specify an English-speaking locale when your string is in English. A LocalDate is a date without time of day, so a lot better suitable for the date from your string than the old Date class. Despite its name a Date does not represent a date but a point in time that falls on at least two different dates in different time zones of the world.

Only if you need an old-fashioned Date for an API that you cannot afford to upgrade to java.time just now, convert like this:

    Instant startOfDay = date.atStartOfDay(ZoneId.systemDefault()).toInstant();
    Date oldfashionedDate = Date.from(startOfDay);
    System.out.println(oldfashionedDate);

Output in my time zone:

Wed Jun 27 00:00:00 CEST 2007

Link

Oracle tutorial: Date Time explaining how to use java.time.

Error: [ng:areq] from angular controller

I got this same error when I included the entire controller file name in the Routes like this:

app.config(function($routeProvider) {
    $routeProvider 
    .when('/', { 
        templateUrl: 'home.html',
        controller: 'mainController.js'
    })

    .when('/portfolio', { 
        templateUrl: 'portfolio.html',
        controller: 'mainController.js'
    })
});

When it should be

app.config(function($routeProvider) {
    $routeProvider 
    .when('/', { 
        templateUrl: 'home.html',
        controller: 'mainController'
    })

    .when('/portfolio', { 
        templateUrl: 'portfolio.html',
        controller: 'mainController'
    })
});

Angular takes certain things you name like the app and controller and expounds on them in directives and across your app, take care to name everything consistently and check for this when debugging

Convert file: Uri to File in Android

File imageToUpload = new File(new URI(androidURI.toString())); works if this is a file u have created in the external storage.

For example file:///storage/emulated/0/(some directory and file name)

Importing from a relative path in Python

The default import method is already "relative", from the PYTHONPATH. The PYTHONPATH is by default, to some system libraries along with the folder of the original source file. If you run with -m to run a module, the current directory gets added to the PYTHONPATH. So if the entry point of your program is inside of Proj, then using import Common.Common should work inside both Server.py and Client.py.

Don't do a relative import. It won't work how you want it to.

How do I clear/delete the current line in terminal?

Alt+# comments out the current line. It will be available in history if needed.

Understanding Chrome network log "Stalled" state

DevTools: [network] explain empty bars preceeding request

Investigated further and have identified that there's no significant difference between our Stalled and Queueing ranges. Both are calculated from the delta's of other timestamps, rather than provided from netstack or renderer.


Currently, if we're waiting for a socket to become available:

  • we'll call it stalled if some proxy negotiation happened
  • we'll call it queuing if no proxy/ssl work was required.

Git: "Not currently on any branch." Is there an easy way to get back on a branch, while keeping the changes?

this helped me

git checkout -b newbranch
git checkout master
git merge newbranch
git branch -d newbranch

getting "No column was specified for column 2 of 'd'" in sql server cte?

I had a similar query and a similar issue.

SELECT
    *
FROM
    Users ru
    LEFT OUTER JOIN 
    (
        SELECT ru1.UserID, COUNT(*)
        FROM Referral r
        LEFT OUTER JOIN Users ru1 ON r.ReferredUserId = ru1.UserID
        GROUP BY ru1.UserID
    ) ReferralTotalCount ON ru.UserID = ReferralTotalCount.UserID

I found that SQL Server was choking on the COUNT(*) column, and was giving me the error No column was specified for column 2.

Putting an alias on the COUNT(*) column fixed the issue.

  SELECT
        *
    FROM
        Users ru
        LEFT OUTER JOIN 
        (
            SELECT ru1.UserID, COUNT(*) AS -->MyCount<--
            FROM Referral r
            LEFT OUTER JOIN Users ru1 ON r.ReferredUserId = ru1.UserID
            GROUP BY ru1.UserID
        ) ReferralTotalCount ON ru.UserID = ReferralTotalCount.UserID

How can I display a tooltip on an HTML "option" tag?

I just tried doing this on Chrome:

var $sel = $('#sel'); $sel.find('option').hover(function(){$sel.attr('title',$(this).attr('title'));console.log($(this).attr('title'))}, function(){$sel.attr('title','');});

However, the hover enter never fires... So you wouldn't be able to do this at all using the standard select. You could achieve this though through some non standard ways:

  • You could fake a select box by using radio boxes that look like dropdowns. So for example, have a radio box absolute positioned and opacity set to 0 placed over the styled box that is pretending to be the option.
  • Or you could use pure javascript and have a series of boxes and adding javascript onclick events to recreate the dropbox yourself - so you will update a hidden value with whichever box was clicked using javascript.
  • Or use one of the non standard libraries already out there. (If there are any?)

How to create a List with a dynamic object type

Just use dynamic as the argument:

var list = new List<dynamic>();

Format SQL in SQL Server Management Studio

Azure Data Studio - free and from Microsoft - offers automatic formatting (ctrl + shift + p while editing -> format document). More information about Azure Data Studio here.

While this is not SSMS, it's great for writing queries, free and an official product from Microsoft. It's even cross-platform. Short story: Just switch to Azure Data Studio to write your queries!

Update: Actually Azure Data Studio is in some way the recommended tool for writing queries (source)

Use Azure Data Studio if you: [..] Are mostly editing or executing queries.

Debugging PHP Mail() and/or PHPMailer

It looks like the class.phpmailer.php file is corrupt. I would download the latest version and try again.

I've always used phpMailer's SMTP feature:

$mail->IsSMTP();
$mail->Host = "localhost";

And if you need debug info:

$mail->SMTPDebug  = 2; // enables SMTP debug information (for testing)
                       // 1 = errors and messages
                       // 2 = messages only

close fancy box from function from within open 'fancybox'

After struggling myself with this I found a solution that works just replace the $ with jQueryjQuery.fancybox.close() and I made it an inline script on an onClick. Going to check if i can call it from the parent

CSS to keep element at "fixed" position on screen

You can do like this:

#mydiv {
    position: fixed; 
    height: 30px; 
    top: 0; 
    left: 0; 
    width: 100%; 
}

This will create a div, that will be fixed on top of your screen. - fixed

DateTimePicker time picker in 24 hour but displaying in 12hr?

I don't understand why the other friends tell you use HH, But after I test so many time, The correct 24 hour format is :

hh

.

I see it from : http://www.malot.fr/bootstrap-datetimepicker/

I don't know why they don't use the common type HH for 24 hour.....

I hope anyone could tell me if I'm wrong.....

Convert pyspark string to date format

The strptime() approach does not work for me. I get another cleaner solution, using cast:

from pyspark.sql.types import DateType
spark_df1 = spark_df.withColumn("record_date",spark_df['order_submitted_date'].cast(DateType()))
#below is the result
spark_df1.select('order_submitted_date','record_date').show(10,False)

+---------------------+-----------+
|order_submitted_date |record_date|
+---------------------+-----------+
|2015-08-19 12:54:16.0|2015-08-19 |
|2016-04-14 13:55:50.0|2016-04-14 |
|2013-10-11 18:23:36.0|2013-10-11 |
|2015-08-19 20:18:55.0|2015-08-19 |
|2015-08-20 12:07:40.0|2015-08-20 |
|2013-10-11 21:24:12.0|2013-10-11 |
|2013-10-11 23:29:28.0|2013-10-11 |
|2015-08-20 16:59:35.0|2015-08-20 |
|2015-08-20 17:32:03.0|2015-08-20 |
|2016-04-13 16:56:21.0|2016-04-13 |

Hibernate Delete query

To understand this peculiar behavior of hibernate, it is important to understand a few hibernate concepts -

Hibernate Object States

Transient - An object is in transient status if it has been instantiated and is still not associated with a Hibernate session.

Persistent - A persistent instance has a representation in the database and an identifier value. It might just have been saved or loaded, however, it is by definition in the scope of a Session.

Detached - A detached instance is an object that has been persistent, but its Session has been closed.

http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/objectstate.html#objectstate-overview

Transaction Write-Behind

The next thing to understand is 'Transaction Write behind'. When objects attached to a hibernate session are modified they are not immediately propagated to the database. Hibernate does this for at least two different reasons.

  • To perform batch inserts and updates.
  • To propagate only the last change. If an object is updated more than once, it still fires only one update statement.

http://learningviacode.blogspot.com/2012/02/write-behind-technique-in-hibernate.html

First Level Cache

Hibernate has something called 'First Level Cache'. Whenever you pass an object to save(), update() or saveOrUpdate(), and whenever you retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session. This is where it tracks changes to various objects.

Hibernate Intercepters and Object Lifecycle Listeners -

The Interceptor interface and listener callbacks from the session to the application, allow the application to inspect and/or manipulate properties of a persistent object before it is saved, updated, deleted or loaded. http://docs.jboss.org/hibernate/orm/4.0/hem/en-US/html/listeners.html#d0e3069


This section Updated

Cascading

Hibernate allows applications to define cascade relationships between associations. For example, 'cascade-delete' from parent to child association will result in deletion of all children when a parent is deleted.

So, why are these important.

To be able to do transaction write-behind, to be able to track multiple changes to objects (object graphs) and to be able to execute lifecycle callbacks hibernate needs to know whether the object is transient/detached and it needs to have the object in it's first level cache before it makes any changes to the underlying object and associated relationships.

That's why hibernate (sometimes) issues a 'SELECT' statement to load the object (if it's not already loaded) in to it's first level cache before it makes changes to it.

Why does hibernate issue the 'SELECT' statement only sometimes?

Hibernate issues a 'SELECT' statement to determine what state the object is in. If the select statement returns an object, the object is in detached state and if it does not return an object, the object is in transient state.

Coming to your scenario -

Delete - The 'Delete' issued a SELECT statement because hibernate needs to know if the object exists in the database or not. If the object exists in the database, hibernate considers it as detached and then re-attches it to the session and processes delete lifecycle.

Update - Since you are explicitly calling 'Update' instead of 'SaveOrUpdate', hibernate blindly assumes that the object is in detached state, re-attaches the given object to the session first level cache and processes the update lifecycle. If it turns out that the object does not exist in the database contrary to hibernate's assumption, an exception is thrown when session flushes.

SaveOrUpdate - If you call 'SaveOrUpdate', hibernate has to determine the state of the object, so it uses a SELECT statement to determine if the object is in Transient/Detached state. If the object is in transient state, it processes the 'insert' lifecycle and if the object is in detached state, it processes the 'Update' lifecycle.

Why doesn't Java offer operator overloading?

I think that people making decisions simply forgot about complex values, matrix algebra, set theory and other cases when overloading would allow to use the standard notation without building everything into the language. Anyway, only mathematically oriented software really benefits from such features. A generic customer application almost never needs them.

They arguments about the unnecessary obfuscation are obviously valid when a programmer defines some program-specific operator where it could be the function instead. A name of the function, when clearly visible, provides the hint that it does. Operator is a function without the readable name.

Java is generally designed about philosophy that some extra verbosity is not bad as it makes the code more readable. Constructs that do the same just have less code to type in used to be called a "syntax sugar" in the past. This is very different from the Python philosophy, for instance, where shorter is near always seen as better, even if providing less context for the second reader.

How to Execute a Python File in Notepad ++?

There is one issue that I didn't see resolved in the above solutions. Python sets the current working directory to wherever you start the interpreter from. If you need the current working directory to be the same directory as where you saved the file on, then you could hit F5 and type this:

cmd /K cd "$(CURRENT_DIRECTORY)"&C:\Users\username\Python36-32\python.exe -i "$(FULL_CURRENT_PATH)"

Except you would replace C:\Users\username\Python36-32\python.exe with whatever the path to the python interpreter is on your machine.

Basically you're starting up command line, changing the directory to the directory containing the .py file you're trying to run, and then running it. You can string together as many command line commands as you like with the '&' symbol.

Url to a google maps page to show a pin given a latitude / longitude?

From my notes:

http://maps.google.com/maps?q=37.4185N+122.08774W+(label)&ll=37.419731,-122.088715&spn=0.004250,0.011579&t=h&iwloc=A&hl=en

Which parses like this:

    q=latN+lonW+(label)     location of teardrop

    t=k             keyhole (satelite map)
    t=h             hybrid

    ll=lat,-lon     center of map
    spn=w.w,h.h     span of map, degrees

iwloc has something to do with the info window. hl is obviously language.

See also: http://www.seomoz.org/ugc/everything-you-never-wanted-to-know-about-google-maps-parameters

PHP - find entry by object property from an array of objects

I solved this problem by keying the array with the ID. It's simpler and possibly faster for this scenario where the ID is what you're looking for.

[420] => stdClass Object
        (
            [name] => Mary
         )

[10957] => stdClass Object
        (
            [name] => Blah
         )
...

Now I can directly address the array:

$array[$v]->name = ...

Or, if I want to verify the existence of an ID:

if (array_key_exists($v, $array)) { ...

How do I vertically align text in a paragraph?

Alternative solution which scales for multi-line text:

Set vertical and horizontal padding to be (height - line-height) / 2

p.event_desc {
    font: bold 12px "Helvetica Neue", Helvetica, Arial, sans-serif;
    line-height: 14px;
    padding: 10.5px 0;
    margin: 0px;
}

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

In addition to C Johnson list I would add the following point:

Check in Visual Studio:
Project Properties -> Configuration Properties -> Linker -> Command line.

"Additional Options" should NOT contain /machine:X86

I have such key, generated by CMake output: CMake generated x86 project, then I added x64 platform via Configuration Manager in Visual Studio 2010 - everything was created fine for the new platform except that the linker command line, specified /machine:X86 separately.

Converting VS2012 Solution to VS2010

the simplest solution is.....open your website in vs2013 and go to Debug->WebsiteProperties (last option) a new window will open..

in this window go to "Build" option and change .net framework version from 4.5 to 4.0.....then select ok. [note: this step will only work if your project does not have dependencies with vs2013...]

Now open your website in vs2010

How do I convert Long to byte[] and back in java

Just write the long to a DataOutputStream with an underlying ByteArrayOutputStream. From the ByteArrayOutputStream you can get the byte-array via toByteArray():

class Main
{

        public static byte[] long2byte(long l) throws IOException
        {
        ByteArrayOutputStream baos=new ByteArrayOutputStream(Long.SIZE/8);
        DataOutputStream dos=new DataOutputStream(baos);
        dos.writeLong(l);
        byte[] result=baos.toByteArray();
        dos.close();    
        return result;
        }


        public static long byte2long(byte[] b) throws IOException
        {
        ByteArrayInputStream baos=new ByteArrayInputStream(b);
        DataInputStream dos=new DataInputStream(baos);
        long result=dos.readLong();
        dos.close();
        return result;
        }


        public static void main (String[] args) throws java.lang.Exception
        {

         long l=123456L;
         byte[] b=long2byte(l);
         System.out.println(l+": "+byte2long(b));       
        }
}

Works for other primitives accordingly.

Hint: For TCP you do not need the byte[] manually. You will use a Socket socket and its streams

OutputStream os=socket.getOutputStream(); 
DataOutputStream dos=new DataOutputStream(os);
dos.writeLong(l);
//etc ..

instead.

Check if array is empty or null

You should check for '' (empty string) before pushing into your array. Your array has elements that are empty strings. Then your album_text.length === 0 will work just fine.

A url resource that is a dot (%2E)

It's actually not really clearly stated in the standard (RFC 3986) whether a percent-encoded version of . or .. is supposed to have the same this-folder/up-a-folder meaning as the unescaped version. Section 3.3 only talks about “The path segments . and ..”, without clarifying whether they match . and .. before or after pct-encoding.

Personally I find Firefox's interpretation that %2E does not mean . most practical, but unfortunately all the other browsers disagree. This would mean that you can't have a path component containing only . or ...

I think the only possible suggestion is “don't do that”! There are other path components that are troublesome too, typically due to server limitations: %2F, %00 and %5C sequences in paths may also be blocked by some web servers, and the empty path segment can also cause problems. So in general it's not possible to fit all possible byte sequences into a path component.

How can I trim leading and trailing white space?

As of R 3.2.0 a new function was introduced for removing leading/trailing white spaces:

trimws()

See: Remove Leading/Trailing Whitespace

Access denied for user 'root'@'localhost' while attempting to grant privileges. How do I grant privileges?

For those who still stumble upon this like I did, it's worth checking to make sure the attempted GRANT does not already exist:

SHOW GRANTS FOR username;

In my case, the error was not actually because there was a permission error, but because the GRANT already existed.

Accessing a Dictionary.Keys Key through a numeric index

In case you decide to use dangerous code that is subject to breakage, this extension function will fetch a key from a Dictionary<K,V> according to its internal indexing (which for Mono and .NET currently appears to be in the same order as you get by enumerating the Keys property).

It is much preferable to use Linq: dict.Keys.ElementAt(i), but that function will iterate O(N); the following is O(1) but with a reflection performance penalty.

using System;
using System.Collections.Generic;
using System.Reflection;

public static class Extensions
{
    public static TKey KeyByIndex<TKey,TValue>(this Dictionary<TKey, TValue> dict, int idx)
    {
        Type type = typeof(Dictionary<TKey, TValue>);
        FieldInfo info = type.GetField("entries", BindingFlags.NonPublic | BindingFlags.Instance);
        if (info != null)
        {
            // .NET
            Object element = ((Array)info.GetValue(dict)).GetValue(idx);
            return (TKey)element.GetType().GetField("key", BindingFlags.Public | BindingFlags.Instance).GetValue(element);
        }
        // Mono:
        info = type.GetField("keySlots", BindingFlags.NonPublic | BindingFlags.Instance);
        return (TKey)((Array)info.GetValue(dict)).GetValue(idx);
    }
};

Undefined reference to pow( ) in C, despite including math.h

You need to link with the math library:

gcc -o sphere sphere.c -lm

The error you are seeing: error: ld returned 1 exit status is from the linker ld (part of gcc that combines the object files) because it is unable to find where the function pow is defined.

Including math.h brings in the declaration of the various functions and not their definition. The def is present in the math library libm.a. You need to link your program with this library so that the calls to functions like pow() are resolved.

How to get the file extension in PHP?

You could try with this for mime type

$image = getimagesize($_FILES['image']['tmp_name']);

$image['mime'] will return the mime type.

This function doesn't require GD library. You can find the documentation here.

This returns the mime type of the image.

Some people use the $_FILES["file"]["type"] but it's not reliable as been given by the browser and not by PHP.

You can use pathinfo() as ThiefMaster suggested to retrieve the image extension.

First make sure that the image is being uploaded successfully while in development before performing any operations with the image.

Convert HTML Character Back to Text Using Java Standard Library

Or you can use unescapeHtml4:

    String miCadena="GU&#205;A TELEF&#211;NICA";
    System.out.println(StringEscapeUtils.unescapeHtml4(miCadena));

This code print the line: GUÍA TELEFÓNICA

Regex to validate JSON

I realize that this is from over 6 years ago. However, I think there is a solution that nobody here has mentioned that is way easier than regexing

function isAJSON(string) {
    try {
        JSON.parse(string)  
    } catch(e) {
        if(e instanceof SyntaxError) return false;
    };  
    return true;
}

Make hibernate ignore class variables that are not mapped

Placing @Transient on getter with private field worked for me.

private String name;

    @Transient
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

HTML-Tooltip position relative to mouse pointer

I prefer this technique:

_x000D_
_x000D_
function showTooltip(e) {_x000D_
  var tooltip = e.target.classList.contains("tooltip")_x000D_
      ? e.target_x000D_
      : e.target.querySelector(":scope .tooltip");_x000D_
  tooltip.style.left =_x000D_
      (e.pageX + tooltip.clientWidth + 10 < document.body.clientWidth)_x000D_
          ? (e.pageX + 10 + "px")_x000D_
          : (document.body.clientWidth + 5 - tooltip.clientWidth + "px");_x000D_
  tooltip.style.top =_x000D_
      (e.pageY + tooltip.clientHeight + 10 < document.body.clientHeight)_x000D_
          ? (e.pageY + 10 + "px")_x000D_
          : (document.body.clientHeight + 5 - tooltip.clientHeight + "px");_x000D_
}_x000D_
_x000D_
var tooltips = document.querySelectorAll('.couponcode');_x000D_
for(var i = 0; i < tooltips.length; i++) {_x000D_
  tooltips[i].addEventListener('mousemove', showTooltip);_x000D_
}
_x000D_
.couponcode {_x000D_
    color: red;_x000D_
    cursor: pointer;_x000D_
}_x000D_
_x000D_
.couponcode:hover .tooltip {_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
.tooltip {_x000D_
    position: absolute;_x000D_
    white-space: nowrap;_x000D_
    display: none;_x000D_
    background: #ffffcc;_x000D_
    border: 1px solid black;_x000D_
    padding: 5px;_x000D_
    z-index: 1000;_x000D_
    color: black;_x000D_
}
_x000D_
Lorem ipsum dolor sit amet, <span class="couponcode">consectetur_x000D_
adipiscing<span class="tooltip">This is a tooltip</span></span>_x000D_
elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua._x000D_
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi_x000D_
ut aliquip ex ea commodo consequat. Duis aute irure dolor in <span_x000D_
class="couponcode">reprehenderit<span class="tooltip">This is_x000D_
another tooltip</span></span> in voluptate velit esse cillum dolore eu_x000D_
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident,_x000D_
sunt in culpa qui officia deserunt mollit anim id est <span_x000D_
class="couponcode">laborum<span class="tooltip">This is yet_x000D_
another tooltip</span></span>.
_x000D_
_x000D_
_x000D_

(see also this Fiddle)

What is the best method to merge two PHP objects?

The \ArrayObject class has the possibility to exchange the current array to disconnect the original reference. To do so, it comes with two handy methods: exchangeArray() and getArrayCopy(). The rest is plain simple array_merge() of the provided object with the ArrayObjects public properties:

class MergeBase extends ArrayObject
{
     public final function merge( Array $toMerge )
     {
          $this->exchangeArray( array_merge( $this->getArrayCopy(), $toMerge ) );
     }
 }

The usage is as easy as this:

 $base = new MergeBase();

 $base[] = 1;
 $base[] = 2;

 $toMerge = [ 3,4,5, ];

 $base->merge( $toMerge );

How can I check if the array of objects have duplicate property values?

if you are looking for a boolean, the quickest way would be

_x000D_
_x000D_
var values = [_x000D_
    { name: 'someName1' },_x000D_
    { name: 'someName2' },_x000D_
    { name: 'someName1' },_x000D_
    { name: 'someName1' }_x000D_
]_x000D_
_x000D_
// solution_x000D_
var hasDuplicate = false;_x000D_
values.map(v => v.name).sort().sort((a, b) => {_x000D_
  if (a === b) hasDuplicate = true_x000D_
})_x000D_
console.log('hasDuplicate', hasDuplicate)
_x000D_
_x000D_
_x000D_

Loop through JSON object List

This will work!

$(document).ready(function ()
    {
        $.ajax(
            {
            type: 'POST',
            url: "/Home/MethodName",
            success: function (data) {
                //data is the string that the method returns in a json format, but in string
                var jsonData = JSON.parse(data); //This converts the string to json

                for (var i = 0; i < jsonData.length; i++) //The json object has lenght
                {
                    var object = jsonData[i]; //You are in the current object
                    $('#olListId').append('<li class="someclass>' + object.Atributte  + '</li>'); //now you access the property.

                }

                /* JSON EXAMPLE
                [{ "Atributte": "value" }, 
                { "Atributte": "value" }, 
                { "Atributte": "value" }]
                */
            }
        });
    });

The main thing about this is using the property exactly the same as the attribute of the JSON key-value pair.

calling another method from the main method in java

First java will not allow you to have do() method. Instead you can make it doOperation().

Second You cann't invoke directly non static methods from static function. Main is a static function. You need to instantiate the class first and then invoke method using that instance.

Third you can invoke static method directly from non static methods.

Gaussian fit for Python

After losing hours trying to find my error, the problem is your formula:

sigma = sum(y*(x-mean)**2)/n

This previous formula is wrong, the correct formula is the square root of this!;

sqrt(sum(y*(x-mean)**2)/n)

Hope this helps

Calling pylab.savefig without display in ipython

This is a matplotlib question, and you can get around this by using a backend that doesn't display to the user, e.g. 'Agg':

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

plt.plot([1,2,3])
plt.savefig('/tmp/test.png')

EDIT: If you don't want to lose the ability to display plots, turn off Interactive Mode, and only call plt.show() when you are ready to display the plots:

import matplotlib.pyplot as plt

# Turn interactive plotting off
plt.ioff()

# Create a new figure, plot into it, then close it so it never gets displayed
fig = plt.figure()
plt.plot([1,2,3])
plt.savefig('/tmp/test0.png')
plt.close(fig)

# Create a new figure, plot into it, then don't close it so it does get displayed
plt.figure()
plt.plot([1,3,2])
plt.savefig('/tmp/test1.png')

# Display all "open" (non-closed) figures
plt.show()

How do I check if string contains substring?

The includes() method determines whether one string may be found within another string, returning true or false as appropriate.

Syntax :-string.includes(searchString[, position])

searchString:-A string to be searched for within this string.

position:-Optional. The position in this string at which to begin searching for searchString; defaults to 0.

string = 'LOL';
console.log(string.includes('lol')); // returns false 
console.log(string.includes('LOL')); // returns true 

Genymotion Android emulator - adb access?

I know it's way too late to answer this question, but I'll just post the solution that worked for me, in case someone runs into trouble again in the future.

I tried using genymotion's own adb tools and the original Android SDK ones, and even purging and reinstalling adb from my system, but nothing worked. I kept getting the error:

adb server is out of date. killing... cannot bind 'tcp:5037' ADB server didn't ACK *failed to start daemon* error:
So I tried adb connect [ip] as suggested here, but I didn't work either, the same error came up.

What finally worked for me was downloading ADT, and running adb directly from the downloaded folder, instead of the system-wide command. So adb devices will give me the error above, but /yourdownloadpath/adb devices works just fine for me.

Hope it helped.

Could not load file or assembly System.Web.Http.WebHost after published to Azure web site

In the case if "Copy Local" is already True, I find it sometimes to work if you remove the files where it has been published to and publish again.

For example if you're using IIS, remove the websites and the contents of the directory to which they are published to, and publish again.

There might be older versions of files at the destination, so to ensure you aren't using older versions, delete everything before publishing again.

Why is using "for...in" for array iteration a bad idea?

Also, due to semantics, the way for, in treats arrays (i.e. the same as any other JavaScript object) is not aligned with other popular languages.

// C#
char[] a = new char[] {'A', 'B', 'C'};
foreach (char x in a) System.Console.Write(x); //Output: "ABC"

// Java
char[] a = {'A', 'B', 'C'};
for (char x : a) System.out.print(x);          //Output: "ABC"

// PHP
$a = array('A', 'B', 'C');
foreach ($a as $x) echo $x;                    //Output: "ABC"

// JavaScript
var a = ['A', 'B', 'C'];
for (var x in a) document.write(x);            //Output: "012"

What's the difference between Thread start() and Runnable run()

Start() method call run override method of Thread extended class and Runnable implements interface.

But by calling run() it search for run method but if class implementing Runnable interface then it call run() override method of Runnable.

ex.:

`

public class Main1
{
A a=new A();
B b=new B();
a.run();//This call run() of Thread because run() of Thread only call when class 
        //implements with Runnable not when class extends Thread.
b.run();//This not run anything because no run method found in class B but it 
        //didn't show any error.

a.start();//this call run() of Thread
b.start();//this call run() of Thread
}

class A implements Runnable{
@Override
    public void run() {
            System.out.println("A ");
    }
}

class B extends Thread {

    @Override
    public void run() {
            System.out.println("B ");
    }
}

`

How to check if any value is NaN in a Pandas DataFrame

let df be the name of the Pandas DataFrame and any value that is numpy.nan is a null value.

  1. If you want to see which columns has nulls and which do not(just True and False)

    df.isnull().any()
    
  2. If you want to see only the columns that has nulls

    df.loc[:, df.isnull().any()].columns
    
  3. If you want to see the count of nulls in every column

    df.isna().sum()
    
  4. If you want to see the percentage of nulls in every column

    df.isna().sum()/(len(df))*100
    
  5. If you want to see the percentage of nulls in columns only with nulls:

df.loc[:,list(df.loc[:,df.isnull().any()].columns)].isnull().sum()/(len(df))*100

EDIT 1:

If you want to see where your data is missing visually:

import missingno
missingdata_df = df.columns[df.isnull().any()].tolist()
missingno.matrix(df[missingdata_df])

Is there a way to split a widescreen monitor in to two or more virtual monitors?

The next version of Windows (Windows 7) will be able to snap windows to the left or right half of the screen. Doesn't help right now, but it's something to look forward to.

http://arstechnica.com/news.ars/post/20081028-first-look-at-windows-7.html

Remove blank lines with grep

The same as the previous answers:

grep -v -e '^$' foo.txt

Here, grep -e means the extended version of grep. '^$' means that there isn't any character between ^(Start of line) and $(end of line). '^' and '$' are regex characters.

So the command grep -v will print all the lines that do not match this pattern (No characters between ^ and $).

This way, empty blank lines are eliminated.

Use HTML5 to resize an image before upload

If some of you, like me, encounter orientation problems I have combined the solutions here with a exif orientation fix

https://gist.github.com/SagiMedina/f00a57de4e211456225d3114fd10b0d0

Resize external website content to fit iFrame width

Tip for 1 website resizing the height. But you can change to 2 websites.

Here is my code to resize an iframe with an external website. You need insert a code into the parent (with iframe code) page and in the external website as well, so, this won't work with you don't have access to edit the external website.

  • local (iframe) page: just insert a code snippet
  • remote (external) page: you need a "body onload" and a "div" that holds all contents. And body needs to be styled to "margin:0"

Local:

<IFRAME STYLE="width:100%;height:1px" SRC="http://www.remote-site.com/" FRAMEBORDER="no" BORDER="0" SCROLLING="no" ID="estframe"></IFRAME>

<SCRIPT>
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
  if (e.data.substring(0,3)=='frm') document.getElementById('estframe').style.height = e.data.substring(3) + 'px';
},false);
</SCRIPT>

You need this "frm" prefix to avoid problems with other embeded codes like Twitter or Facebook plugins. If you have a plain page, you can remove the "if" and the "frm" prefix on both pages (script and onload).

Remote:

You need jQuery to accomplish about "real" page height. I cannot realize how to do with pure JavaScript since you'll have problem when resize the height down (higher to lower height) using body.scrollHeight or related. For some reason, it will return always the biggest height (pre-redimensioned).

<BODY onload="parent.postMessage('frm'+$('#master').height(),'*')" STYLE="margin:0">
<SCRIPT SRC="path-to-jquery/jquery.min.js"></SCRIPT>
<DIV ID="master">
your content
</DIV>

So, parent page (iframe) has a 1px default height. The script inserts a "wait for message/event" from the iframe. When a message (post message) is received and the first 3 chars are "frm" (to avoid the mentioned problem), will get the number from 4th position and set the iframe height (style), including 'px' unit.

The external site (loaded in the iframe) will "send a message" to the parent (opener) with the "frm" and the height of the main div (in this case id "master"). The "*" in postmessage means "any source".

Hope this helps. Sorry for my english.

How can I style the border and title bar of a window in WPF?

I found a more straight forward solution from @DK comment in this question, the solution is written by Alex and described here with source, To make customized window:

  1. download the sample project here
  2. edit the generic.xaml file to customize the layout.
  3. enjoy :).

How to save a bitmap on internal storage

Modify onClick() as follows:

@Override
public void onClick(View v) {
    if(v == btn) {
        canvas=sv.getHolder().lockCanvas();
        if(canvas!=null) {
            canvas.drawBitmap(bitmap, 100, 100, null);
            sv.getHolder().unlockCanvasAndPost(canvas);
        }
    } else if(v == btn1) {
        saveBitmapToInternalStorage(bitmap);
    }
}

There are several ways to enforce that btn must be pressed before btn1 so that the bitmap is painted before you attempt to save it.

I suggest that you initially disable btn1, and that you enable it when btn is clicked, like this:

if(v == btn) {
    ...
    btn1.setEnabled(true);
}

Failed to fetch URL https://dl-ssl.google.com/android/repository/addons_list-1.xml, reason: Connection to https://dl-ssl.google.com refused

I was facing same problem below is the solution that worked for me

First Go to Android SDK Manager then

select Tools then,

select Options

then check the box "Force https://... sources to be fetched using http://..."

hope it will help you also.

How to sum all column values in multi-dimensional array?

It can also be done using array_map :

$rArray = array(
    0 => array(
        'gozhi' => 2,
        'uzorong' => 1,
        'ngangla' => 4,
        'langthel' => 5
    ),
    1 => array(
        'gozhi' => 5,
        'uzorong' => 0,
        'ngangla' => 3,
        'langthel' => 2
    ),
    2 => array(
        'gozhi' => 3,
        'uzorong' => 0,
        'ngangla' => 1,
        'langthel' => 3
    ),
);

$sumResult = call_user_func_array('array_map', array_merge(['sum'], $rArray));

function sum()
{
    return array_sum(func_get_args());
}

Composer install error - requires ext_curl when it's actually enabled

Not sure why an answer with Linux commands would get so many up votes for a Windows related question, but anyway...

If phpinfo() shows Curl as enabled, yet php -m does NOT, it means that you probably have a php-cli.ini too. run php -i and see which ini file loaded. If it's different, diff it and reflect and differences in the CLI ini file. Then you should be good to go.

Btw download and use Git Bash instead of cmd.exe!

Switching the order of block elements with CSS

Possible in CSS3: http://www.w3.org/TR/css3-writing-modes/#writing-mode

Why not change the orders of the tags? Your HTML page isn't made out of stone, are they?

What's the canonical way to check for type in Python?

A simple way to check type is to compare it with something whose type you know.

>>> a  = 1
>>> type(a) == type(1)
True
>>> b = 'abc'
>>> type(b) == type('')
True

Sending HTML mail using a shell script

Heres mine (given "mail" is configured correctly):

scanuser@owncloud:~$ vi sendMailAboutNewDocuments.sh

mail -s "You have new mail" -a "Content-type: text/html" -a "From: [email protected]" $1 << EOF
<html>
<body>
Neues Dokument: $2<br>
<a href="https://xxx/index.php/apps/files/?dir=/Post">Hier anschauen</a>
</body>
</html>

EOF

to make executable:

chmod +x sendMailAboutNewDocuments.sh

then call:

./sendMailAboutNewDocuments.sh [email protected] test.doc

How to remove provisioning profiles from Xcode

Provisioning profiles are stored under settings > accounts. Just press the "View details..." for the developer account you want and the provisioning profiles will be listed there.

How to clear Tkinter Canvas?

Yes, I believe you are creating thousands of objects. If you're looking for an easy way to delete a bunch of them at once, use canvas tags described here. This lets you perform the same operation (such as deletion) on a large number of objects.

How do you detect where two line segments intersect?

Here's an improvement to Gavin's answer. marcp's solution is similar also, but neither postpone the division.

This actually turns out to be a practical application of Gareth Rees' answer as well, because the cross-product's equivalent in 2D is the perp-dot-product, which is what this code uses three of. Switching to 3D and using the cross-product, interpolating both s and t at the end, results in the two closest points between the lines in 3D. Anyway, the 2D solution:

int get_line_intersection(float p0_x, float p0_y, float p1_x, float p1_y, 
    float p2_x, float p2_y, float p3_x, float p3_y, float *i_x, float *i_y)
{
    float s02_x, s02_y, s10_x, s10_y, s32_x, s32_y, s_numer, t_numer, denom, t;
    s10_x = p1_x - p0_x;
    s10_y = p1_y - p0_y;
    s32_x = p3_x - p2_x;
    s32_y = p3_y - p2_y;

    denom = s10_x * s32_y - s32_x * s10_y;
    if (denom == 0)
        return 0; // Collinear
    bool denomPositive = denom > 0;

    s02_x = p0_x - p2_x;
    s02_y = p0_y - p2_y;
    s_numer = s10_x * s02_y - s10_y * s02_x;
    if ((s_numer < 0) == denomPositive)
        return 0; // No collision

    t_numer = s32_x * s02_y - s32_y * s02_x;
    if ((t_numer < 0) == denomPositive)
        return 0; // No collision

    if (((s_numer > denom) == denomPositive) || ((t_numer > denom) == denomPositive))
        return 0; // No collision
    // Collision detected
    t = t_numer / denom;
    if (i_x != NULL)
        *i_x = p0_x + (t * s10_x);
    if (i_y != NULL)
        *i_y = p0_y + (t * s10_y);

    return 1;
}

Basically it postpones the division until the last moment, and moves most of the tests until before certain calculations are done, thereby adding early-outs. Finally, it also avoids the division by zero case which occurs when the lines are parallel.

You also might want to consider using an epsilon test rather than comparison against zero. Lines that are extremely close to parallel can produce results that are slightly off. This is not a bug, it is a limitation with floating point math.

Failed to execute 'atob' on 'Window'

In my case, I was going nuts since there wasn't any issues with the string to be decoded, since I could successfully decode it on online tools. Until I found out that you first have to decodeURIComponent what you are decoding, like so:

atob(decodeURIComponent(dataToBeDecoded));

Difference between Spring MVC and Spring Boot

Spring MVC and Spring Boot are exist for the different purpose. So, it is not wise to compare each other as the contenders.

What is Spring Boot?

Spring Boot is a framework for packaging the spring application with sensible defaults. What does this mean?. You are developing a web application using Spring MVC, Spring Data, Hibernate and Tomcat. How do you package and deploy this application to your web server. As of now, we have to manually write the configurations, XML files, etc. for deploying to web server.

Spring Boot does that for you with Zero XML configuration in your project. Believe me, you don't need deployment descriptor, web server, etc. Spring Boot is magical framework that bundles all the dependencies for you. Finally your web application will be a standalone JAR file with embeded servers.

If you are still confused how this works, please read about microservice framework development using spring boot.

What is Spring MVC?

It is a traditional web application framework that helps you to build web applications. It is similar to Struts framework.

A Spring MVC is a Java framework which is used to build web applications. It follows the Model-View-Controller design pattern. It implements all the basic features of a core spring framework like Inversion of Control, Dependency Injection.

A Spring MVC provides an elegant solution to use MVC in spring framework by the help of DispatcherServlet. Here, DispatcherServlet is a class that receives the incoming request and maps it to the right resource such as controllers, models, and views.

I hope this helps you to understand the difference.

Delaying function in swift

You can use GCD (in the example with a 10 second delay):

Swift 2

let triggerTime = (Int64(NSEC_PER_SEC) * 10)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, triggerTime), dispatch_get_main_queue(), { () -> Void in
    self.functionToCall()
})

Swift 3 and Swift 4

DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: {
    self.functionToCall()
})

Swift 5 or Later

 DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {
        //call any function
    }

MySQL query to select events between start/end date

In PHP and phpMyAdmin

$tb = tableDataName; //Table name
$now = date('Y-m-d'); //Current date

//start and end is the fields of tabla with date format value (yyyy-m-d)

$query = "SELECT * FROM $tb WHERE start <= '".$now."' AND end >= '".$now."'";

How do I implement interfaces in python?

Using the abc module for abstract base classes seems to do the trick.

from abc import ABCMeta, abstractmethod

class IInterface:
    __metaclass__ = ABCMeta

    @classmethod
    def version(self): return "1.0"
    @abstractmethod
    def show(self): raise NotImplementedError

class MyServer(IInterface):
    def show(self):
        print 'Hello, World 2!'

class MyBadServer(object):
    def show(self):
        print 'Damn you, world!'


class MyClient(object):

    def __init__(self, server):
        if not isinstance(server, IInterface): raise Exception('Bad interface')
        if not IInterface.version() == '1.0': raise Exception('Bad revision')

        self._server = server


    def client_show(self):
        self._server.show()


# This call will fail with an exception
try:
    x = MyClient(MyBadServer)
except Exception as exc:
    print 'Failed as it should!'

# This will pass with glory
MyClient(MyServer()).client_show()

ToString() function in Go

Another example with a struct :

package types

import "fmt"

type MyType struct {
    Id   int    
    Name string
}

func (t MyType) String() string {
    return fmt.Sprintf(
    "[%d : %s]",
    t.Id, 
    t.Name)
}

Be careful when using it,
concatenation with '+' doesn't compile :

t := types.MyType{ 12, "Blabla" }

fmt.Println(t) // OK
fmt.Printf("t : %s \n", t) // OK
//fmt.Println("t : " + t) // Compiler error !!!
fmt.Println("t : " + t.String()) // OK if calling the function explicitly

How to select where ID in Array Rails ActiveRecord without exception

Update: This answer is more relevant for Rails 4.x

Do this:

current_user.comments.where(:id=>[123,"456","Michael Jackson"])

The stronger side of this approach is that it returns a Relation object, to which you can join more .where clauses, .limit clauses, etc., which is very helpful. It also allows non-existent IDs without throwing exceptions.

The newer Ruby syntax would be:

current_user.comments.where(id: [123, "456", "Michael Jackson"])

Ping with timestamp on Windows CLI

WindowsPowershell:

option 1

ping.exe -t COMPUTERNAME|Foreach{"{0} - {1}" -f (Get-Date),$_}

option 2

Test-Connection -Count 9999 -ComputerName COMPUTERNAME | Format-Table @{Name='TimeStamp';Expression={Get-Date}},Address,ProtocolAddress,ResponseTime

How add "or" in switch statements?

case 2:
case 5:
do something
break;

How to get a vCard (.vcf file) into Android contacts from website

I had problems with importing a VERSION:4.0 vcard file on Android 7 (LineageOS) with the standard Contacts app.

Since this is on the top search hits for "android vcard format not supported", I just wanted to note that I was able to import them with the Simple Contacts app (Play or F-Droid).

Add space between cells (td) using css

Suppose cellspcing / cellpadding / border-spacing property did not worked, you can use the code as follow.

<div class="form-group">
  <table width="100%" cellspacing="2px" style="border-spacing: 10px;">
    <tr>                        
      <td width="47%">
        <input type="submit" class="form-control btn btn-info" id="submit" name="Submit" />
      </td>
      <td width="5%"></td>
      <td width="47%">
        <input type="reset" class="form-control btn btn-info" id="reset" name="Reset" />
      </td>
    </tr>
  </table>
</div>

I've tried and got succeed while seperate the button by using table-width and make an empty td as 2 or 1% it doesn't return more different.

How to make Bootstrap 4 cards the same height in card-columns?

I am a novice at this so please forgive if I am missing something all together.

I tried many of the above. If you set the height = 100% the card will always expand to the greatest length of the longest card. The container will constrain all to the same length.

I wanted to see the container, so I used background color to help me see what was going on.

<div class="col-lg-3"  style="background-color: rosybrown;">
    <div class="card w-100" Style="height: 100%">
        <div class="card-body">
            <img src="images/beHappy.png" alt="" class="img-fluid rounded-circle w-25 mb-3">
            <h4>CBe Happy</h2>

C# Convert string from UTF-8 to ISO-8859-1 (Latin1) H

Use Encoding.Convert to adjust the byte array before attempting to decode it into your destination encoding.

Encoding iso = Encoding.GetEncoding("ISO-8859-1");
Encoding utf8 = Encoding.UTF8;
byte[] utfBytes = utf8.GetBytes(Message);
byte[] isoBytes = Encoding.Convert(utf8, iso, utfBytes);
string msg = iso.GetString(isoBytes);

Convert factor to integer

You can combine the two functions; coerce to characters thence to numerics:

> fac <- factor(c("1","2","1","2"))
> as.numeric(as.character(fac))
[1] 1 2 1 2

How can I mock requests and the response?

This is how you can do it (you can run this file as-is):

import requests
import unittest
from unittest import mock

# This is the class we want to test
class MyGreatClass:
    def fetch_json(self, url):
        response = requests.get(url)
        return response.json()

# This method will be used by the mock to replace requests.get
def mocked_requests_get(*args, **kwargs):
    class MockResponse:
        def __init__(self, json_data, status_code):
            self.json_data = json_data
            self.status_code = status_code

        def json(self):
            return self.json_data

    if args[0] == 'http://someurl.com/test.json':
        return MockResponse({"key1": "value1"}, 200)
    elif args[0] == 'http://someotherurl.com/anothertest.json':
        return MockResponse({"key2": "value2"}, 200)

    return MockResponse(None, 404)

# Our test case class
class MyGreatClassTestCase(unittest.TestCase):

    # We patch 'requests.get' with our own method. The mock object is passed in to our test case method.
    @mock.patch('requests.get', side_effect=mocked_requests_get)
    def test_fetch(self, mock_get):
        # Assert requests.get calls
        mgc = MyGreatClass()
        json_data = mgc.fetch_json('http://someurl.com/test.json')
        self.assertEqual(json_data, {"key1": "value1"})
        json_data = mgc.fetch_json('http://someotherurl.com/anothertest.json')
        self.assertEqual(json_data, {"key2": "value2"})
        json_data = mgc.fetch_json('http://nonexistenturl.com/cantfindme.json')
        self.assertIsNone(json_data)

        # We can even assert that our mocked method was called with the right parameters
        self.assertIn(mock.call('http://someurl.com/test.json'), mock_get.call_args_list)
        self.assertIn(mock.call('http://someotherurl.com/anothertest.json'), mock_get.call_args_list)

        self.assertEqual(len(mock_get.call_args_list), 3)

if __name__ == '__main__':
    unittest.main()

Important Note: If your MyGreatClass class lives in a different package, say my.great.package, you have to mock my.great.package.requests.get instead of just 'request.get'. In that case your test case would look like this:

import unittest
from unittest import mock
from my.great.package import MyGreatClass

# This method will be used by the mock to replace requests.get
def mocked_requests_get(*args, **kwargs):
    # Same as above


class MyGreatClassTestCase(unittest.TestCase):

    # Now we must patch 'my.great.package.requests.get'
    @mock.patch('my.great.package.requests.get', side_effect=mocked_requests_get)
    def test_fetch(self, mock_get):
        # Same as above

if __name__ == '__main__':
    unittest.main()

Enjoy!

How to printf uint64_t? Fails with: "spurious trailing ‘%’ in format"

The ISO C99 standard specifies that these macros must only be defined if explicitly requested.

#define __STDC_FORMAT_MACROS
#include <inttypes.h>

... now PRIu64 will work

How do I get the height and width of the Android Navigation Bar programmatically?

How to get the height of the navigation bar and status bar. This code works for me on some Huawei devices and Samsung devices. Egis's solution above is good, however, it is still incorrect on some devices. So, I improved it.

This is code to get the height of status bar

private fun getStatusBarHeight(resources: Resources): Int {
        var result = 0
        val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android")
        if (resourceId > 0) {
            result = resources.getDimensionPixelSize(resourceId)
        }
        return result
    }

This method always returns the height of navigation bar even when the navigation bar is hidden.

private fun getNavigationBarHeight(resources: Resources): Int {
    val resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android")
    return if (resourceId > 0) {
        resources.getDimensionPixelSize(resourceId)
    } else 0
}

NOTE: on Samsung A70, this method returns the height of the status bar + height of the navigation bar. On other devices (Huawei), it only returns the height of the Navigation bar and returns 0 when the navigation bar is hidden.

private fun getNavigationBarHeight(): Int {
        val display = activity?.windowManager?.defaultDisplay
        return if (display == null) {
            0
        } else {
            val realMetrics = DisplayMetrics()
            display.getRealMetrics(realMetrics)
            val metrics = DisplayMetrics()
            display.getMetrics(metrics)
            realMetrics.heightPixels - metrics.heightPixels
        }
    }

This is code to get height of navigation bar and status bar

val metrics = DisplayMetrics()
        activity?.windowManager?.defaultDisplay?.getRealMetrics(metrics)

        //resources is got from activity

        //NOTE: on SamSung A70, this height = height of status bar + height of Navigation bar
        //On other devices (Huawei), this height = height of Navigation bar
        val navigationBarHeightOrNavigationBarPlusStatusBarHeight = getNavigationBarHeight()

        val statusBarHeight = getStatusBarHeight(resources)
        //The method will always return the height of navigation bar even when the navigation bar was hidden.
        val realNavigationBarHeight = getNavigationBarHeight(resources)

        val realHeightOfStatusBarAndNavigationBar =
                if (navigationBarHeightOrNavigationBarPlusStatusBarHeight == 0 || navigationBarHeightOrNavigationBarPlusStatusBarHeight < statusBarHeight) {
                    //Huawei: navigation bar is hidden
                    statusBarHeight
                } else if (navigationBarHeightOrNavigationBarPlusStatusBarHeight == realNavigationBarHeight) {
                    //Huawei: navigation bar is visible
                    statusBarHeight + realNavigationBarHeight
                } else if (navigationBarHeightOrNavigationBarPlusStatusBarHeight < realNavigationBarHeight) {
                    //SamSung A70: navigation bar is still visible but it only displays as a under line
                    //navigationBarHeightOrNavigationBarPlusStatusBarHeight = navigationBarHeight'(under line) + statusBarHeight
                    navigationBarHeightOrNavigationBarPlusStatusBarHeight
                } else {
                    //SamSung A70: navigation bar is visible
                    //navigationBarHeightOrNavigationBarPlusStatusBarHeight == statusBarHeight + realNavigationBarHeight
                    navigationBarHeightOrNavigationBarPlusStatusBarHeight
                }

How to resolve ORA-011033: ORACLE initialization or shutdown in progress

What worked for me is that i hadn't set the local_listener, to see if the local listener is set login to sqlplus / as sysdba, make sure the database is open and run the following command show parameter local_listener, if the value is empty, then you will have to set the local_listener with the following SQL command ALTER SYSTEM SET LOCAL_LISTENER='<LISTENER_NAME_GOES_HERE>'

How to scroll the window using JQuery $.scrollTo() function

Looks like you've got the syntax slightly wrong... I'm assuming based on your code that you're trying to scroll down 100px in 800ms, if so then this works (using scrollTo 1.4.1):

$.scrollTo('+=100px', 800, { axis:'y' });

Declaring functions in JSP?

You need to enclose that in <%! %> as follows:

<%!

public String getQuarter(int i){
String quarter;
switch(i){
        case 1: quarter = "Winter";
        break;

        case 2: quarter = "Spring";
        break;

        case 3: quarter = "Summer I";
        break;

        case 4: quarter = "Summer II";
        break;

        case 5: quarter = "Fall";
        break;

        default: quarter = "ERROR";
}

return quarter;
}

%>

You can then invoke the function within scriptlets or expressions:

<%
     out.print(getQuarter(4));
%>

or

<%= getQuarter(17) %>

how to set "camera position" for 3d plots using python/matplotlib?

Minimal example varying azim, dist and elev

To add some simple sample images to what was explained at: https://stackoverflow.com/a/12905458/895245

Here is my test program:

#!/usr/bin/env python3

import sys

import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')

if len(sys.argv) > 1:
    azim = int(sys.argv[1])
else:
    azim = None
if len(sys.argv) > 2:
    dist = int(sys.argv[2])
else:
    dist = None
if len(sys.argv) > 3:
    elev = int(sys.argv[3])
else:
    elev = None

# Make data.
X = np.arange(-5, 6, 1)
Y = np.arange(-5, 6, 1)
X, Y = np.meshgrid(X, Y)
Z = X**2

# Plot the surface.
surf = ax.plot_surface(X, Y, Z, linewidth=0, antialiased=False)

# Labels.
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')

if azim is not None:
    ax.azim = azim
if dist is not None:
    ax.dist = dist
if elev is not None:
    ax.elev = elev

print('ax.azim = {}'.format(ax.azim))
print('ax.dist = {}'.format(ax.dist))
print('ax.elev = {}'.format(ax.elev))

plt.savefig(
    'main_{}_{}_{}.png'.format(ax.azim, ax.dist, ax.elev),
    format='png',
    bbox_inches='tight'
)

Running it without arguments gives the default values:

ax.azim = -60
ax.dist = 10
ax.elev = 30

main_-60_10_30.png

enter image description here

Vary azim

The azimuth is the rotation around the z axis e.g.:

  • 0 means "looking from +x"
  • 90 means "looking from +y"

main_-60_10_30.png

enter image description here

main_0_10_30.png

enter image description here

main_60_10_30.png

enter image description here

Vary dist

dist seems to be the distance from the center visible point in data coordinates.

main_-60_10_30.png

enter image description here

main_-60_5_30.png

enter image description here

main_-60_20_-30.png

enter image description here

Vary elev

From this we understand that elev is the angle between the eye and the xy plane.

main_-60_10_60.png

enter image description here

main_-60_10_30.png

enter image description here

main_-60_10_0.png

enter image description here

main_-60_10_-30.png

enter image description here

Tested on matpotlib==3.2.2.

how to POST/Submit an Input Checkbox that is disabled?

I just combined the HTML, JS and CSS suggestions in the answers here

HTML:

<input type="checkbox" readonly>

jQuery:

(function(){
    // Raj: https://stackoverflow.com/a/14753503/260665
    $(document).on('click', 'input[type="checkbox"][readonly]', function(e){
        e.preventDefault();
    });
})();

CSS:

input[type="checkbox"][readonly] {
  cursor: not-allowed;
  opacity: 0.5;
}

Since the element is not 'disabled' it still goes through the POST.

Get a particular cell value from HTML table using JavaScript

<td class="virtualTd" onclick="putThis(this)">my td value </td>

function putThis(control) { 
    alert(control.innerText);
}

How do I remove repeated elements from ArrayList?

Although converting the ArrayList to a HashSet effectively removes duplicates, if you need to preserve insertion order, I'd rather suggest you to use this variant

// list is some List of Strings
Set<String> s = new LinkedHashSet<>(list);

Then, if you need to get back a List reference, you can use again the conversion constructor.

What is the difference between a static and a non-static initialization code block

This is directly from http://www.programcreek.com/2011/10/java-class-instance-initializers/

1. Execution Order

Look at the following class, do you know which one gets executed first?

public class Foo {
 
    //instance variable initializer
    String s = "abc";
 
    //constructor
    public Foo() {
        System.out.println("constructor called");
    }
 
    //static initializer
    static {
        System.out.println("static initializer called");
    }
 
    //instance initializer
    {
        System.out.println("instance initializer called");
    }
 
    public static void main(String[] args) {
        new Foo();
        new Foo();
    }
}

Output:

static initializer called

instance initializer called

constructor called

instance initializer called

constructor called

2. How do Java instance initializer work?

The instance initializer above contains a println statement. To understand how it works, we can treat it as a variable assignment statement, e.g., b = 0. This can make it more obvious to understand.

Instead of

int b = 0, you could write

int b;
b = 0;

Therefore, instance initializers and instance variable initializers are pretty much the same.

3. When are instance initializers useful?

The use of instance initializers are rare, but still it can be a useful alternative to instance variable initializers if:

  1. Initializer code must handle exceptions
  2. Perform calculations that can’t be expressed with an instance variable initializer.

Of course, such code could be written in constructors. But if a class had multiple constructors, you would have to repeat the code in each constructor.

With an instance initializer, you can just write the code once, and it will be executed no matter what constructor is used to create the object. (I guess this is just a concept, and it is not used often.)

Another case in which instance initializers are useful is anonymous inner classes, which can’t declare any constructors at all. (Will this be a good place to place a logging function?)

Thanks to Derhein.

Also note that Anonymous classes that implement interfaces [1] have no constructors. Therefore instance initializers are needed to execute any kinds of expressions at construction time.

Hibernate JPA Sequence (non-Id)

Hibernate definitely supports this. From the docs:

"Generated properties are properties which have their values generated by the database. Typically, Hibernate applications needed to refresh objects which contain any properties for which the database was generating values. Marking properties as generated, however, lets the application delegate this responsibility to Hibernate. Essentially, whenever Hibernate issues an SQL INSERT or UPDATE for an entity which has defined generated properties, it immediately issues a select afterwards to retrieve the generated values."

For properties generated on insert only, your property mapping (.hbm.xml) would look like:

<property name="foo" generated="insert"/>

For properties generated on insert and update your property mapping (.hbm.xml) would look like:

<property name="foo" generated="always"/>

Unfortunately, I don't know JPA, so I don't know if this feature is exposed via JPA (I suspect possibly not)

Alternatively, you should be able to exclude the property from inserts and updates, and then "manually" call session.refresh( obj ); after you have inserted/updated it to load the generated value from the database.

This is how you would exclude the property from being used in insert and update statements:

<property name="foo" update="false" insert="false"/>

Again, I don't know if JPA exposes these Hibernate features, but Hibernate does support them.

Create auto-numbering on images/figures in MS Word

I assume you are using the caption feature of Word, that is, captions were not typed in as normal text, but were inserted using Insert > Caption (Word versions before 2007), or References > Insert Caption (in the ribbon of Word 2007 and up). If done correctly, the captions are really 'fields'. You'll know if it is a field if the caption's background turns grey when you put your cursor on them (or is permanently displayed grey).

Captions are fields - Unfortunately fields (like caption fields) are only updated on specific actions, like opening of the document, printing, switching from print view to normal view, etc. The easiest way to force updating of all (caption) fields when you want it is by doing the following:

  1. Select all text in your document (easiest way is to press ctrl-a)
  2. Press F9, this command tells Word to update all fields in the selection.

Captions are normal text - If the caption number is not a field, I am afraid you'll have to edit the text manually.

How can I tell how many objects I've stored in an S3 bucket?

There is a --summarize switch which includes bucket summary information (i.e. number of objects, total size).

Here's the correct answer using AWS cli:

aws s3 ls s3://bucketName/path/ --recursive --summarize | grep "Total Objects:"

Total Objects: 194273

See the documentation

Convert a file path to Uri in Android

Below code works fine before 18 API :-

public String getRealPathFromURI(Uri contentUri) {

        // can post image
        String [] proj={MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery( contentUri,
                        proj, // Which columns to return
                        null,       // WHERE clause; which rows to return (all rows)
                        null,       // WHERE clause selection arguments (none)
                        null); // Order-by clause (ascending by name)
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();

        return cursor.getString(column_index);
}

below code use on kitkat :-

public static String getPath(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[] {
                    split[1]
            };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

/**
 * Get the value of the data column for this Uri. This is useful for
 * MediaStore Uris, and other file-based ContentProviders.
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @param selection (Optional) Filter used in the query.
 * @param selectionArgs (Optional) Selection arguments used in the query.
 * @return The value of the _data column, which is typically a file path.
 */
public static String getDataColumn(Context context, Uri uri, String selection,
        String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}


/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is ExternalStorageProvider.
 */
public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 */
public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 */
public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

see below link for more info:-

https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java

How to remove underline from a link in HTML?

  1. Add this to your external style sheet (preferred):

    a {text-decoration:none;}
    
  2. Or add this to the <head> of your HTML document:

    <style type="text/css">
     a {text-decoration:none;}
    </style>
    
  3. Or add it to the a element itself (not recommended):

    <!-- Add [ style="text-decoration:none;"] -->
    <a href="http://example.com" style="text-decoration:none;">Text</a>
    

The APK file does not exist on disk

in my case, just

View > Tool Windows > Gradle > right click [project] > Refresh Gradle Project

How to put a jar in classpath in Eclipse?

As of rev 17 of the Android Developer Tools, the correct way to add a library jar when.using the tools and Eclipse is to create a directory called libs on the same level as your src and assets directories and then drop the jar in there. Nothing else.required, the tools take care of all the rest for you automatically.

How to change a field name in JSON using Jackson

Be aware that there is org.codehaus.jackson.annotate.JsonProperty in Jackson 1.x and com.fasterxml.jackson.annotation.JsonProperty in Jackson 2.x. Check which ObjectMapper you are using (from which version), and make sure you use the proper annotation.

Submit form after calling e.preventDefault()

The problem is that, even if you see the error, your return false affects the callback of the .each() method ... so, even if there is an error, you reach the line

$('form').unbind('submit').submit();

and the form is submitted.

You should create a variable, validated, for example, and set it to true. Then, in the callback, instead of return false, set validated = false.

Finally...

if (validated) $('form').unbind('submit').submit();

This way, only if there are no errors will the form be submitted.

How to make GREP select only numeric values?

Don't use more commands than necessary, leave away tail, grep and cut. You can do this with only (a simple) awk

PS: giving a block-size en print only de persentage is a bit silly ;-) So leave also away the "-B MB"

df . |awk -F'[multiple field seperators]' '$NF=="Last field must be exactly --> mounted patition" {print $(NF-number from last field)}'

in your case, use:

df . |awk -F'[ %]' '$NF=="/" {print $(NF-2)}'

output: 81

If you want to show the percent symbol, you can leave the -F'[ %]' away and your print field will move 1 field further back

df . |awk '$NF=="/" {print $(NF-1)}'

output: 81%

HTML: How to center align a form

This will have the field take 50% of the width and be centered and resized properly


    {    
        width: 50%;
        margin-left : 25%
    }

May also use "vw" (view width) units instead of "%"

How do I change an HTML selected option using JavaScript?

Tools as pure JavaScript code for handling Selectbox:

Graphical Understanding:

Image - A

enter image description here


Image - B

enter image description here


Image - C

enter image description here

Updated - 25-June-2019 | Fiddler DEMO

JavaScript Code:

/**
 * Empty Select Box
 * @param eid Element ID
 * @param value text
 * @param text text
 * @author Neeraj.Singh
 */
function emptySelectBoxById(eid, value, text) {
    document.getElementById(eid).innerHTML = "<option value='" + value + "'>" + text + "</option>";
}


/**
 * Reset Select Box
 * @param eid Element ID
 */

function resetSelectBoxById(eid) {
    document.getElementById(eid).options[0].selected = 'selected';
}


/**
 * Set Select Box Selection By Index
 * @param eid Element ID
 * @param eindx Element Index
 */

function setSelectBoxByIndex(eid, eindx) {
    document.getElementById(eid).getElementsByTagName('option')[eindx].selected = 'selected';
    //or
    document.getElementById(eid).options[eindx].selected = 'selected';
}


/**
 * Set Select Box Selection By Value
 * @param eid Element ID
 * @param eval Element Index
 */
function setSelectBoxByValue(eid, eval) {
    document.getElementById(eid).value = eval;
}


/**
 * Set Select Box Selection By Text
 * @param eid Element ID
 * @param eval Element Index
 */
function setSelectBoxByText(eid, etxt) {
    var eid = document.getElementById(eid);
    for (var i = 0; i < eid.options.length; ++i) {
        if (eid.options[i].text === etxt)
            eid.options[i].selected = true;
    }
}


/**
 * Get Select Box Text By ID
 * @param eid Element ID
 * @return string
 */

function getSelectBoxText(eid) {
    return document.getElementById(eid).options[document.getElementById(eid).selectedIndex].text;
}


/**
 * Get Select Box Value By ID
 * @param eid Element ID
 * @return string
 */

function getSelectBoxValue(id) {
    return document.getElementById(id).options[document.getElementById(id).selectedIndex].value;
}

How to run a cronjob every X minutes?

You are setting your cron to run on 10th minute in every hour.
To set it to every 5 mins change to */5 * * * * /usr/bin/php /mydomain.in/cronmail.php > /dev/null 2>&1

Check if not nil and not empty in Rails shortcut?

You can use .present? which comes included with ActiveSupport.

@city = @user.city.present?
# etc ...

You could even write it like this

def show
  %w(city state bio contact twitter mail).each do |attr|
    instance_variable_set "@#{attr}", @user[attr].present?
  end
end

It's worth noting that if you want to test if something is blank, you can use .blank? (this is the opposite of .present?)

Also, don't use foo == nil. Use foo.nil? instead.

Compare two List<T> objects for equality, ignoring order

Thinking this should do what you want:

list1.All(item => list2.Contains(item)) &&
list2.All(item => list1.Contains(item));

if you want it to be distinct, you could change it to:

list1.All(item => list2.Contains(item)) &&
list1.Distinct().Count() == list1.Count &&
list1.Count == list2.Count

using facebook sdk in Android studio

Scott Barta's solution worked for me, except I had to add these to the dependencies of my main project build.gradle file:

compile files('libs/android-support-v4.jar')
compile project(':libraries:facebook')

Also worth mentioning, you need to make sure:

android {
    compileSdkVersion 18
    buildToolsVersion "18.1.1"

    defaultConfig {
        minSdkVersion 7
        targetSdkVersion 18
    }

Are the same in both build.gradle files...Once i did this it ran like a charm.

Valid content-type for XML, HTML and XHTML documents

HTML: text/html, full-stop.

XHTML: application/xhtml+xml, or only if following HTML compatbility guidelines, text/html. See the W3 Media Types Note.

XML: text/xml, application/xml (RFC 2376).

There are also many other media types based around XML, for example application/rss+xml or image/svg+xml. It's a safe bet that any unrecognised but registered ending in +xml is XML-based. See the IANA list for registered media types ending in +xml.

(For unregistered x- types, all bets are off, but you'd hope +xml would be respected.)

What is Hive: Return Code 2 from org.apache.hadoop.hive.ql.exec.MapRedTask

That's not the real error, here's how to find it:

Go to the hadoop jobtracker web-dashboard, find the hive mapreduce jobs that failed and look at the logs of the failed tasks. That will show you the real error.

The console output errors are useless, largely beause it doesn't have a view of the individual jobs/tasks to pull the real errors (there could be errors in multiple tasks)

Hope that helps.

Make first letter of a string upper case (with maximum performance)

As BobBeechey suggests in his response to this question, the following code will work for this:

private void txt_fname_TextChanged(object sender, EventArgs e)
{
    char[] c = txt_fname.Text.ToCharArray();
    int j;
    for (j = 0; j < txt_fname.Text.Length; j++)
    {
        if (j==0) c[j]=c[j].ToString().ToUpper()[0];
        else c[j] = c[j].ToString().ToLower()[0];
    }
    txt_fname.Text = new string(c); 
    txt_fname.Select(txt_fname.Text.Length, 1);
}

What does FETCH_HEAD in Git mean?

FETCH_HEAD is a short-lived ref, to keep track of what has just been fetched from the remote repository. git pull first invokes git fetch, in normal cases fetching a branch from the remote; FETCH_HEAD points to the tip of this branch (it stores the SHA1 of the commit, just as branches do). git pull then invokes git merge, merging FETCH_HEAD into the current branch.

The result is exactly what you'd expect: the commit at the tip of the appropriate remote branch is merged into the commit at the tip of your current branch.

This is a bit like doing git fetch without arguments (or git remote update), updating all your remote branches, then running git merge origin/<branch>, but using FETCH_HEAD internally instead to refer to whatever single ref was fetched, instead of needing to name things.

Making text background transparent but not text itself

For a fully transparent background use:

background: transparent;

Otherwise for a semi-transparent color fill use:

background: rgba(255,255,255,0.5); // or hsla(0, 0%, 100%, 0.5)

where the values are:

background: rgba(red,green,blue,opacity); // or hsla(hue, saturation, lightness, opacity)

You can also use rgba values for gradient backgrounds.

To get transparency on an image background simply reduce the opacity of the image in an image editor of you choice beforehand.

How to properly override clone method?

Just because java's implementation of Cloneable is broken it doesn't mean you can't create one of your own.

If OP real purpose was to create a deep clone, i think that it is possible to create an interface like this:

public interface Cloneable<T> {
    public T getClone();
}

then use the prototype constructor mentioned before to implement it:

public class AClass implements Cloneable<AClass> {
    private int value;
    public AClass(int value) {
        this.vaue = value;
    }

    protected AClass(AClass p) {
        this(p.getValue());
    }

    public int getValue() {
        return value;
    }

    public AClass getClone() {
         return new AClass(this);
    }
}

and another class with an AClass object field:

public class BClass implements Cloneable<BClass> {
    private int value;
    private AClass a;

    public BClass(int value, AClass a) {
         this.value = value;
         this.a = a;
    }

    protected BClass(BClass p) {
        this(p.getValue(), p.getA().getClone());
    }

    public int getValue() {
        return value;
    }

    public AClass getA() {
        return a;
    }

    public BClass getClone() {
         return new BClass(this);
    }
}

In this way you can easely deep clone an object of class BClass without need for @SuppressWarnings or other gimmicky code.

CSS Inset Borders

If you want to make sure the border is on the inside of your element, you can use

box-sizing:border-box;

this will place the following border on the inside of the element:

border: 10px solid black;

(similar result you'd get using the additonal parameter inset on box-shadow, but instead this one is for the real border and you can still use your shadow for something else.)

Note to another answer above: as soon as you use any inset on box-shadow of a certain element, you are limited to a maximum of 2 box-shadows on that element and would require a wrapper div for further shadowing.

Both solutions should as well get you rid of the undesired 3D effects. Also note both solutions are stackable (see the example I've added in 2018)

_x000D_
_x000D_
.example-border {_x000D_
  width:100px;_x000D_
  height:100px;_x000D_
  border:40px solid blue;_x000D_
  box-sizing:border-box;_x000D_
  float:left;_x000D_
}_x000D_
_x000D_
.example-shadow {_x000D_
  width:100px;_x000D_
  height:100px;_x000D_
  float:left;_x000D_
  margin-left:20px;_x000D_
  box-shadow:0 0 0 40px green inset;_x000D_
}_x000D_
_x000D_
.example-combined {_x000D_
  width:100px;_x000D_
  height:100px;_x000D_
  float:left;_x000D_
  margin-left:20px;_x000D_
  border:20px solid orange;_x000D_
  box-sizing:border-box;_x000D_
  box-shadow:0 0 0 20px red inset;_x000D_
}
_x000D_
<div class="example-border"></div>_x000D_
<div class="example-shadow"></div>_x000D_
<div class="example-combined"></div>
_x000D_
_x000D_
_x000D_

Compiler error: "class, interface, or enum expected"

Look at your function s definition. If you forget using "()" after function declaration somewhere, you ll get plenty of errors with the same format:

 ... ??: class, interface, or enum expected ...

And also you have forgot closing bracket after your class or function definition ends. But note that these missing bracket, is not the only reason for this type of error.

Generate sql insert script from excel worksheet

I had to make SQL scripts often and add them to source control and send them to DBA. I used this ExcelIntoSQL App from windows store https://www.microsoft.com/store/apps/9NH0W51XXQRM It creates complete script with "CREATE TABLE" and INSERTS.

CentOS 7 and Puppet unable to install nc

yum install nmap-ncat.x86_64

resolved my problem

Maximum execution time in phpMyadmin

What worked for me on WAMP was modifying file: \Wamp64\alias\phpmyadmin.conf, lines:

 php_admin_value max_execution_time 600
 php_admin_value max_input_time 600

I did not have to change the library file.

Can't import Numpy in Python

The following command worked for me:

python.exe -m pip install numpy

How Stuff and 'For Xml Path' work in SQL Server?

Declare @Temp As Table (Id Int,Name Varchar(100))
Insert Into @Temp values(1,'A'),(1,'B'),(1,'C'),(2,'D'),(2,'E'),(3,'F'),(3,'G'),(3,'H'),(4,'I'),(5,'J'),(5,'K')
Select X.ID,
stuff((Select ','+ Z.Name from @Temp Z Where X.Id =Z.Id For XML Path('')),1,1,'')
from @Temp X
Group by X.ID

Why is the gets function so dangerous that it should not be used?

In order to use gets safely, you have to know exactly how many characters you will be reading, so that you can make your buffer large enough. You will only know that if you know exactly what data you will be reading.

Instead of using gets, you want to use fgets, which has the signature

char* fgets(char *string, int length, FILE * stream);

(fgets, if it reads an entire line, will leave the '\n' in the string; you'll have to deal with that.)

It remained an official part of the language up to the 1999 ISO C standard, but it was officially removed by the 2011 standard. Most C implementations still support it, but at least gcc issues a warning for any code that uses it.

How to re-sync the Mysql DB if Master and slave have different database incase of Mysql replication?

This is the full step-by-step procedure to resync a master-slave replication from scratch:

At the master:

RESET MASTER;
FLUSH TABLES WITH READ LOCK;
SHOW MASTER STATUS;

And copy the values of the result of the last command somewhere.

Without closing the connection to the client (because it would release the read lock) issue the command to get a dump of the master:

mysqldump -u root -p --all-databases > /a/path/mysqldump.sql

Now you can release the lock, even if the dump hasn't ended yet. To do it, perform the following command in the MySQL client:

UNLOCK TABLES;

Now copy the dump file to the slave using scp or your preferred tool.

At the slave:

Open a connection to mysql and type:

STOP SLAVE;

Load master's data dump with this console command:

mysql -uroot -p < mysqldump.sql

Sync slave and master logs:

RESET SLAVE;
CHANGE MASTER TO MASTER_LOG_FILE='mysql-bin.000001', MASTER_LOG_POS=98;

Where the values of the above fields are the ones you copied before.

Finally, type:

START SLAVE;

To check that everything is working again, after typing:

SHOW SLAVE STATUS;

you should see:

Slave_IO_Running: Yes
Slave_SQL_Running: Yes

That's it!

Apache Spark: The number of cores vs. the number of executors

From the excellent resources available at RStudio's Sparklyr package page:

SPARK DEFINITIONS:

It may be useful to provide some simple definitions for the Spark nomenclature:

Node: A server

Worker Node: A server that is part of the cluster and are available to run Spark jobs

Master Node: The server that coordinates the Worker nodes.

Executor: A sort of virtual machine inside a node. One Node can have multiple Executors.

Driver Node: The Node that initiates the Spark session. Typically, this will be the server where sparklyr is located.

Driver (Executor): The Driver Node will also show up in the Executor list.

Can Selenium WebDriver open browser windows silently in the background?

I had the same problem with my chromedriver using Python and options.add_argument("headless") did not work for me, but then I realized how to fix it so I bring it in the code below:

opt = webdriver.ChromeOptions()
opt.arguments.append("headless")

Using boolean values in C

Nowadays C99 supports boolean types but you need to #include <stdbool.h>.

Example:

#include <stdbool.h>

int main() 
{ 
    bool arr[2] = {true, false}; 

    printf("%d\n", arr[0] && arr[1]);
    printf("%d\n", arr[0] || arr[1]);

    return 0; 
} 

Output:

0
1

Detecting user leaving page with react-router

For react-router 2.4.0+

NOTE: It is advisable to migrate all your code to the latest react-router to get all the new goodies.

As recommended in the react-router documentation:

One should use the withRouter higher order component:

We think this new HoC is nicer and easier, and will be using it in documentation and examples, but it is not a hard requirement to switch.

As an ES6 example from the documentation:

import React from 'react'
import { withRouter } from 'react-router'

const Page = React.createClass({

  componentDidMount() {
    this.props.router.setRouteLeaveHook(this.props.route, () => {
      if (this.state.unsaved)
        return 'You have unsaved information, are you sure you want to leave this page?'
    })
  }

  render() {
    return <div>Stuff</div>
  }

})

export default withRouter(Page)

JavaScript get child element

ULs don't have a name attribute, but you can reference the ul by tag name.

Try replacing line 3 in your script with this:

var sub = cat.getElementsByTagName("UL");

Can overridden methods differ in return type?

Yes it may differ but there are some limitations.

Before Java 5.0, when you override a method, both parameters and return type must match exactly. Java 5.0 it introduces a new facility called covariant return type. You can override a method with the same signature but return a subclass of the object returned.

In another words, a method in a subclass can return an object whose type is a subclass of the type returned by the method with the same signature in the superclass.

Android - implementing startForeground for a service?

In my case It was totally different since I was not having activity to launch the service in Oreo.

Below are the steps which I used to resolve this foreground service issue -

public class SocketService extends Service {
    private String TAG = this.getClass().getSimpleName();

    @Override
    public void onCreate() {
        Log.d(TAG, "Inside onCreate() API");
        if (Build.VERSION.SDK_INT >= 26) {
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
            mBuilder.setSmallIcon(R.drawable.ic_launcher);
            mBuilder.setContentTitle("Notification Alert, Click Me!");
            mBuilder.setContentText("Hi, This is Android Notification Detail!");
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            // notificationID allows you to update the notification later on.
            mNotificationManager.notify(100, mBuilder.build());
            startForeground(100, mBuilder.mNotification);
        }
        Toast.makeText(getApplicationContext(), "inside onCreate()", Toast.LENGTH_LONG).show();
    }


    @Override
    public int onStartCommand(Intent resultIntent, int resultCode, int startId) {
        Log.d(TAG, "inside onStartCommand() API");

        return startId;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "inside onDestroy() API");

    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
}

And after that to initiate this service I triggered below cmd -


adb -s " + serial_id + " shell am startforegroundservice -n com.test.socket.sample/.SocketService


So this helps me to start service without activity on Oreo devices :)

Is there a way to make text unselectable on an HTML page?

Here's a Sass mixin (scss) for those interested. Compass/CSS 3 doesn't seem to have a user-select mixin.

// @usage use within a rule
// ex. img {@include user-select(none);}
// @param assumed valid user-select value
@mixin user-select($value)
{
    & {
        -webkit-touch-callout: $value;
        -webkit-user-select: $value;
        -khtml-user-select: $value;
        -moz-user-select: $value;
        -ms-user-select: $value;
        user-select: $value;
    }
}

Though Compass would do it in a more robust way, i.e. only add support for vendors you've chosen.

CSS Animation onClick

You can achieve this by binding an onclick listener and then adding the animate class like this:

$('#button').onClick(function(){
    $('#target_element').addClass('animate_class_name');
});

How can I install a package with go get?

First, we need GOPATH

The $GOPATH is a folder (or set of folders) specified by its environment variable. We must notice that this is not the $GOROOT directory where Go is installed.

export GOPATH=$HOME/gocode
export PATH=$PATH:$GOPATH/bin

We used ~/gocode path in our computer to store the source of our application and its dependencies. The GOPATH directory will also store the binaries of their packages.

Then check Go env

You system must have $GOPATH and $GOROOT, below is my Env:

GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/elpsstu/gocode"
GORACE=""
GOROOT="/home/pravin/go"
GOTOOLDIR="/home/pravin/go/pkg/tool/linux_amd64"
CC="gcc"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0"
CXX="g++"
CGO_ENABLED="1"

Now, you run download go package:

go get [-d] [-f] [-fix] [-t] [-u] [build flags] [packages]

Get downloads and installs the packages named by the import paths, along with their dependencies. For more details you can look here.

When does System.getProperty("java.io.tmpdir") return "c:\temp"

Value of %TEMP% environment variable is often user-specific and Windows sets it up with regard to currently logged in user account. Some user accounts may have no user profile, for example when your process runs as a service on SYSTEM, LOCALSYSTEM or other built-in account, or is invoked by IIS application with AppPool identity with Create user profile option disabled. So even when you do not overwrite %TEMP% variable explicitly, Windows may use c:\temp or even c:\windows\temp folders for, lets say, non-usual user accounts. And what's more important, process might have no access rights to this directory!

How to redirect to action from JavaScript method?

(This is more of a comment but I can't comment because of the low reputation, somebody might find these useful)

If you're in sth.com/product and you want to redirect to sth.com/product/index use

window.location.href = "index";

If you want to redirect to sth.com/home

window.location.href = "/home";

and if you want you want to redirect to sth.com/home/index

window.location.href = "/home/index";

throwing an exception in objective-c/cocoa

Sample code for case: @throw([NSException exceptionWithName:...

- (void)parseError:(NSError *)error
       completionBlock:(void (^)(NSString *error))completionBlock {


    NSString *resultString = [NSString new];

    @try {

    NSData *errorData = [NSData dataWithData:error.userInfo[@"SomeKeyForData"]];

    if(!errorData.bytes) {

        @throw([NSException exceptionWithName:@"<Set Yours exc. name: > Test Exc" reason:@"<Describe reason: > Doesn't contain data" userInfo:nil]);
    }


    NSDictionary *dictFromData = [NSJSONSerialization JSONObjectWithData:errorData
                                                                 options:NSJSONReadingAllowFragments
                                                                   error:&error];

    resultString = dictFromData[@"someKey"];
    ...


} @catch (NSException *exception) {

      NSLog( @"Caught Exception Name: %@", exception.name);
      NSLog( @"Caught Exception Reason: %@", exception.reason );

    resultString = exception.reason;

} @finally {

    completionBlock(resultString);
}

}

Using:

[self parseError:error completionBlock:^(NSString *error) {
            NSLog(@"%@", error);
        }];

Another more advanced use-case:

- (void)parseError:(NSError *)error completionBlock:(void (^)(NSString *error))completionBlock {

NSString *resultString = [NSString new];

NSException* customNilException = [NSException exceptionWithName:@"NilException"
                                                          reason:@"object is nil"
                                                        userInfo:nil];

NSException* customNotNumberException = [NSException exceptionWithName:@"NotNumberException"
                                                                reason:@"object is not a NSNumber"
                                                              userInfo:nil];

@try {

    NSData *errorData = [NSData dataWithData:error.userInfo[@"SomeKeyForData"]];

    if(!errorData.bytes) {

        @throw([NSException exceptionWithName:@"<Set Yours exc. name: > Test Exc" reason:@"<Describe reason: > Doesn't contain data" userInfo:nil]);
    }


    NSDictionary *dictFromData = [NSJSONSerialization JSONObjectWithData:errorData
                                                                 options:NSJSONReadingAllowFragments
                                                                   error:&error];

    NSArray * array = dictFromData[@"someArrayKey"];

    for (NSInteger i=0; i < array.count; i++) {

        id resultString = array[i];

        if (![resultString isKindOfClass:NSNumber.class]) {

            [customNotNumberException raise]; // <====== HERE is just the same as: @throw customNotNumberException;

            break;

        } else if (!resultString){

            @throw customNilException;        // <======

            break;
        }

    }

} @catch (SomeCustomException * sce) {
    // most specific type
    // handle exception ce
    //...
} @catch (CustomException * ce) {
    // most specific type
    // handle exception ce
    //...
} @catch (NSException *exception) {
    // less specific type

    // do whatever recovery is necessary at his level
    //...
    // rethrow the exception so it's handled at a higher level

    @throw (SomeCustomException * customException);

} @finally {
    // perform tasks necessary whether exception occurred or not

}

}

How to display gpg key details without importing it?

The option --list-packets parses pgp data from a file and outputs its structure - in a very technical way, though. When parsing a public key, you can easily extract the user ids and the key ids of the signatures.

Be wary that this command only parses the data format, it does no validation of signatures or similar things.

Rails 3 execute custom sql query without a model

I'd recommend using ActiveRecord::Base.connection.exec_query instead of ActiveRecord::Base.connection.execute which returns a ActiveRecord::Result (available in rails 3.1+) which is a bit easier to work with.

Then you can access it in various the result in various ways like .rows, .each, or .to_hash

From the docs:

result = ActiveRecord::Base.connection.exec_query('SELECT id, title, body FROM posts')
result # => #<ActiveRecord::Result:0xdeadbeef>


# Get the column names of the result:
result.columns
# => ["id", "title", "body"]

# Get the record values of the result:
result.rows
# => [[1, "title_1", "body_1"],
      [2, "title_2", "body_2"],
      ...
     ]

# Get an array of hashes representing the result (column => value):
result.to_hash
# => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
      {"id" => 2, "title" => "title_2", "body" => "body_2"},
      ...
     ]

# ActiveRecord::Result also includes Enumerable.
result.each do |row|
  puts row['title'] + " " + row['body']
end

note: copied my answer from here

Unable to Install Any Package in Visual Studio 2015

You need to Clear All NuGet Caches; for this you need go to Options and click on it like this:

enter image description here

Intro to GPU programming

I think the others have answered your second question. As for the first, the "Hello World" of CUDA, I don't think there is a set standard, but personally, I'd recommend a parallel adder (i.e. a programme that sums N integers).

If you look the "reduction" example in the NVIDIA SDK, the superficially simple task can be extended to demonstrate numerous CUDA considerations such as coalesced reads, memory bank conflicts and loop unrolling.

See this presentation for more info:

http://www.gpgpu.org/sc2007/SC07_CUDA_5_Optimization_Harris.pdf

Initializing C dynamic arrays

Instead of using

int * p;
p = {1,2,3};

we can use

int * p;
p =(int[3]){1,2,3};

CSS Div stretch 100% page height

* {
margin: 0;
}
html, body {
height: 90%;
}
.content {
min-height: 100%;
height: auto !important;
height: 100%;
margin: 0 auto ;
}

Setting a property by reflection with a string value

I tried the answer from LBushkin and it worked great, but it won't work for null values and nullable fields. So I've changed it to this:

propertyName= "Latitude";
PropertyInfo propertyInfo = ship.GetType().GetProperty(propertyName);
if (propertyInfo != null)
{
     Type t = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType;
     object safeValue = (value == null) ? null : Convert.ChangeType(value, t);
     propertyInfo.SetValue(ship, safeValue, null);
}

Detecting negative numbers

You could check if $profitloss < 0

if ($profitloss < 0):
    echo "Less than 0\n";
endif;

How Can I Set the Default Value of a Timestamp Column to the Current Timestamp with Laravel Migrations?

Use Paulo Freitas suggestion instead.


Until Laravel fixes this, you can run a standard database query after the Schema::create have been run.

    Schema::create("users", function($table){
        $table->increments('id');
        $table->string('email', 255);
        $table->string('given_name', 100);
        $table->string('family_name', 100);
        $table->timestamp('joined');
        $table->enum('gender', ['male', 'female', 'unisex'])->default('unisex');
        $table->string('timezone', 30)->default('UTC');
        $table->text('about');
    });
    DB::statement("ALTER TABLE ".DB::getTablePrefix()."users CHANGE joined joined TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL");

It worked wonders for me.

Inputting a default image in case the src attribute of an html <img> is not valid?

An HTML only solution, where the only requirement is that you know the size of the image that you're inserting. Will not work for transparent images, as it uses background-image as a filler.

We can successfully use background-image to link the image that appears if the given image is missing. Then the only problem is the broken icon image - we can remove it by inserting a very big empty character, thus pushing the content outside the display of img.

_x000D_
_x000D_
img {_x000D_
  background-image: url("http://placehold.it/200x200");_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
img:before {_x000D_
  content: " ";_x000D_
  font-size: 1000px;_x000D_
}
_x000D_
This image is missing:_x000D_
<img src="a.jpg" style="width: 200px; height: 200px"/><br/>_x000D_
And is displaying the placeholder
_x000D_
_x000D_
_x000D_


An CSS only solution (Webkit only)

_x000D_
_x000D_
img:before {_x000D_
  content: " ";_x000D_
  font-size: 1000px;_x000D_
  background-image: url("http://placehold.it/200x200");_x000D_
  display: block;_x000D_
  width: 200px;_x000D_
  height: 200px;_x000D_
  position: relative;_x000D_
  z-index: 0;_x000D_
  margin-bottom: -16px;_x000D_
}
_x000D_
This image is there:_x000D_
<img src="http://placehold.it/100x100"/><br/>_x000D_
_x000D_
This image is missing:_x000D_
<img src="a.jpg"/><br/>_x000D_
And is displaying the placeholder
_x000D_
_x000D_
_x000D_

How to pass arguments and redirect stdin from a file to program run in gdb?

You can do this:

gdb --args path/to/executable -every -arg you can=think < of

The magic bit being --args.

Just type run in the gdb command console to start debugging.

Angular 2 beta.17: Property 'map' does not exist on type 'Observable<Response>'

You need to import the map operator:

import 'rxjs/add/operator/map'

How do I call REST API from an android app?

  1. If you want to integrate Retrofit (all steps defined here):

Goto my blog : retrofit with kotlin

  1. Please use android-async-http library.

the link below explains everything step by step.

http://loopj.com/android-async-http/

Here are sample apps:

  1. http://www.techrepublic.com/blog/software-engineer/calling-restful-services-from-your-android-app/

  2. http://blog.strikeiron.com/bid/73189/Integrate-a-REST-API-into-Android-Application-in-less-than-15-minutes

Create a class :

public class HttpUtils {
  private static final String BASE_URL = "http://api.twitter.com/1/";
 
  private static AsyncHttpClient client = new AsyncHttpClient();

  public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(getAbsoluteUrl(url), params, responseHandler);
  }

  public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(getAbsoluteUrl(url), params, responseHandler);
  }
      
  public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(url, params, responseHandler);
  }

  public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(url, params, responseHandler);
  }

  private static String getAbsoluteUrl(String relativeUrl) {
      return BASE_URL + relativeUrl;
  }
}

Call Method :

    RequestParams rp = new RequestParams();
    rp.add("username", "aaa"); rp.add("password", "aaa@123");
                    
    HttpUtils.post(AppConstant.URL_FEED, rp, new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            // If the response is JSONObject instead of expected JSONArray
            Log.d("asd", "---------------- this is response : " + response);
            try {
                JSONObject serverResp = new JSONObject(response.toString());                                                
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }                   
        }
            
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
            // Pull out the first event on the public timeline
                    
        }
    });

Please grant internet permission in your manifest file.

 <uses-permission android:name="android.permission.INTERNET" />

you can add compile 'com.loopj.android:android-async-http:1.4.9' for Header[] and compile 'org.json:json:20160212' for JSONObject in build.gradle file if required.

jquery-ui-dialog - How to hook into dialog close event

I have found it!

You can catch the close event using the following code:

 $('div#popup_content').on('dialogclose', function(event) {
     alert('closed');
 });

Obviously I can replace the alert with whatever I need to do.
Edit: As of Jquery 1.7, the bind() has become on()

How to detect my browser version and operating system using JavaScript?

I wasn't able to get some of the other answers to work on Chrome, Firefox, IE11, and Edge with the same code. I came up with the below and it appears to work for those browsers listed above. I also wanted to see what OS the user was on. I haven't tested this against a browser with user overridden User-Agent settings, so mileage may vary. The order of the IFs is important for this to work correctly.

let os, osStore, bStore, appVersion, browser;
// Chrome
if(navigator.vendor === "Google Inc."){
    appVersion = navigator.appVersion.split(" ");
    os = [appVersion[1],appVersion[2],appVersion[3],appVersion[4],appVersion[5]].join(" ");
    os = os.split("(")[1].split(")")[0]
    browser = appVersion[appVersion.length-2].split("/").join(" ");
    console.log("Browser:",browser,"- OS:",os);
}

// Safari
else if(navigator.vendor === "Apple Computer, Inc."){
    appVersion = navigator.appVersion.split(" ");
    os = [appVersion[1],appVersion[2],appVersion[3],appVersion[4],appVersion[5]].join(" ");
    os = os.split("(")[1].split(")")[0];
    browser = appVersion[appVersion.length-1].split("/").join(" ");
    console.log("Browser:",browser,"- OS:",os);
}

// Firefox is seems the only browser with oscpu
else if(navigator.oscpu){
    bStore = navigator.userAgent.split("; ").join("-").split(" ");
    browser = bStore[bStore.length-1].replace("/"," ");
    osStore = [bStore[1],bStore[2],bStore[3]].join(" ");
    osStore = osStore.split("-");
    osStore.pop(osStore.lastIndexOf)
    osStore = osStore.join(" ").split("(");
    os = osStore[1];
    console.log("Browser:",browser,"- OS:",os);
}

// IE is seems the only browser with cpuClass
// MSIE 11:10 Mode
else if(navigator.appName === "Microsoft Internet Explorer"){
    bStore = navigator.appVersion.split("; ");
    browser = bStore[1]+" / "+bStore[4].replace("/"," ");
    os = [bStore[2],bStore[3]].join(" ");
    console.log("Browser:",browser,"- OS:",os);
}

// MSIE 11
else if(navigator.cpuClass){
    bStore = navigator.appVersion.split("; ");
    osStore = [bStore[0],bStore[1]].join(" ");
    os = osStore.split("(")[1];
    browser = "MSIE 11 "+bStore[2].split("/").join(" ");
    console.log("Browser:",browser,"- OS:",os);
}

// Edge
else if(navigator.appVersion){
    browser = navigator.appVersion.split(" ");
    browser = browser[browser.length -1].split("/").join(" ");
    os = navigator.appVersion.split(")")[0].split("(")[1];
    console.log("Browser:",browser,"- OS:",os);
}

// Other browser
else {
    console.log(JSON.stringify(navigator));
}

How to upgrade Angular CLI to the latest version

To update Angular CLI to a new version, you must update both the global package and your project's local package.

Global package:

npm uninstall -g @angular/cli
npm cache clean
# if npm version is > 5 then use `npm cache verify` to avoid errors (or to avoid using --force)
npm install -g @angular/cli@latest

Local project package:

rm -rf node_modules dist # use rmdir /S/Q node_modules dist in Windows Command Prompt; use rm -r -fo node_modules,dist in Windows PowerShell
npm install --save-dev @angular/cli@latest
npm install

Source: Github

Is there a way I can retrieve sa password in sql server 2005

There is no way to get the old password back. Log into the SQL server management console as a machine or domain admin using integrated authentication, you can then change any password (including sa).

Start the SQL service again and use the new created login (recovery in my example) Go via the security panel to the properties and change the password of the SA account.

enter image description here

Now write down the new SA password.

JSON: why are forward slashes escaped?

I asked the same question some time ago and had to answer it myself. Here's what I came up with:

It seems, my first thought [that it comes from its JavaScript roots] was correct.

'\/' === '/' in JavaScript, and JSON is valid JavaScript. However, why are the other ignored escapes (like \z) not allowed in JSON?

The key for this was reading http://www.cs.tut.fi/~jkorpela/www/revsol.html, followed by http://www.w3.org/TR/html4/appendix/notes.html#h-B.3.2. The feature of the slash escape allows JSON to be embedded in HTML (as SGML) and XML.

composer laravel create project

You are missing a parameter in the command. It should be in this order:

composer create-project [PACKAGE] [DESTINATION PATH] [--FLAGS]

You're mistakingly specifying your local path as the Composer/Packagist package you wish to create a project from. Hence the "Could not find package" message.

Simply make sure you're specifying the Laravel package and you should be good to go:

composer create-project laravel/laravel /Applications/MAMP/htdocs/test_laravel

Creating Scheduled Tasks

This works for me https://www.nuget.org/packages/ASquare.WindowsTaskScheduler/

It is nicely designed Fluent API.

//This will create Daily trigger to run every 10 minutes for a duration of 18 hours
SchedulerResponse response = WindowTaskScheduler
    .Configure()
    .CreateTask("TaskName", "C:\\Test.bat")
    .RunDaily()
    .RunEveryXMinutes(10)
    .RunDurationFor(new TimeSpan(18, 0, 0))
    .SetStartDate(new DateTime(2015, 8, 8))
    .SetStartTime(new TimeSpan(8, 0, 0))
    .Execute();

Failed to run sdkmanager --list with Java 9

The Android Tools are still incompatible with JDK 9 or 10. You need to install JDK 8 or, if you need multiple Java versions make sure that the system-wide Java home points to a JDK 8.

More details here: How to configure Unity 2017.4 to target Android and avoid build failures on OSX?

Chaining multiple filter() in Django, is this a bug?

Saw this in a comment and I thought it was the simplest explanation.

filter(A, B) is the AND filter(A).filter(B) is OR

Should functions return null or an empty object?

Forgive my pseudo-php/code.

I think it really depends on the intended use of the result.

If you intend to edit/modify the return value and save it, then return an empty object. That way, you can use the same function to populate data on a new or existing object.

Say I have a function that takes a primary key and an array of data, fills the row with data, then saves the resulting record to the db. Since I'm intending to populate the object with my data either way, it can be a huge advantage to get an empty object back from the getter. That way, I can perform identical operations in either case. You use the result of the getter function no matter what.

Example:

function saveTheRow($prim_key, $data) {
    $row = getRowByPrimKey($prim_key);

    // Populate the data here

    $row->save();
}

Here we can see that the same series of operations manipulates all records of this type.

However, if the ultimate intent of the return value is to read and do something with the data, then I would return null. This way, I can very quickly determine if there was no data returned and display the appropriate message to the user.

Usually, I'll catch exceptions in my function that retrieves the data (so I can log error messages, etc...) then return null straight from the catch. It generally doesn't matter to the end user what the problem is, so I find it best to encapsulate my error logging/processing directly in the function that gets the data. If you're maintaining a shared codebase in any large company this is especially beneficial because you can force proper error logging/handling on even the laziest programmer.

Example:

function displayData($row_id) {
    // Logging of the error would happen in this function
    $row = getRow($row_id);
    if($row === null) {
        // Handle the error here
    }

    // Do stuff here with data
}

function getRow($row_id) {
 $row = null;
 try{
     if(!$db->connected()) {
   throw excpetion("Couldn't Connect");
  }

  $result = $db->query($some_query_using_row_id);

  if(count($result) == 0 ) {
   throw new exception("Couldn't find a record!");
  }

  $row = $db->nextRow();

 } catch (db_exception) {
  //Log db conn error, alert admin, etc...
  return null; // This way I know that null means an error occurred
 }
 return $row;
}

That's my general rule. It's worked well so far.

What is "runtime"?

Run time is the instance where you don't know about of what type of objects creates during its execution, objects creation are based on certain condition or some computation work. In contradict, compile time is the instance where required objects are defined by you before its executions.

JOptionPane Input to int

Please note that Integer.parseInt throws an NumberFormatException if the passed string doesn't contain a parsable string.

What programming language does facebook use?

might be surprised to know.. its PHP. read all about it here

How to add a TextView to a LinearLayout dynamically in Android?

If you are using Linearlayout. its params should be "wrap_content" to add dynamic data in your layout xml. if you use match or fill parent then you cannot see the output.

It Should be like this.

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content" android:layout_height="wrap_content">
        <ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >
        </ListView>
    </LinearLayout>

java- reset list iterator to first element of the list

If the order doesn't matter, we can re-iterate backward with the same iterator using the hasPrevious() and previous() methods:

ListIterator<T> lit = myList.listIterator(); // create just one iterator

Initially the iterator sits at the beginning, we do forward iteration:

while (lit.hasNext()) process(lit.next()); // begin -> end

Then the iterator sits at the end, we can do backward iteration:

while (lit.hasPrevious()) process2(lit.previous()); // end -> begin

ASP.Net MVC How to pass data from view to controller

<form action="myController/myAction" method="POST">
 <input type="text" name="valueINeed" />
 <input type="submit" value="View Report" />
</form> 

controller:

[HttpPost]
public ActionResult myAction(string valueINeed)
{
   //....
}

How can I sort a List alphabetically?

Same in JAVA 8 :-

//Assecnding order
        listOfCountryNames.stream().sorted().forEach((x) -> System.out.println(x));

//Decending order
        listOfCountryNames.stream().sorted((o1, o2) -> o2.compareTo(o1)).forEach((x) -> System.out.println(x));

ASP.NET MVC View Engine Comparison

I like ndjango. It is very easy to use and very flexible. You can easily extend view functionality with custom tags and filters. I think that "greatly tied to F#" is rather advantage than disadvantage.

Why an abstract class implementing an interface can miss the declaration/implementation of one of the interface's methods?

That's because if a class is abstract, then by definition you are required to create subclasses of it to instantiate. The subclasses will be required (by the compiler) to implement any interface methods that the abstract class left out.

Following your example code, try making a subclass of AbstractThing without implementing the m2 method and see what errors the compiler gives you. It will force you to implement this method.