Programs & Examples On #Context switch

When to use Task.Delay, when to use Thread.Sleep?

The biggest difference between Task.Delay and Thread.Sleep is that Task.Delay is intended to run asynchronously. It does not make sense to use Task.Delay in synchronous code. It is a VERY bad idea to use Thread.Sleep in asynchronous code.

Normally you will call Task.Delay() with the await keyword:

await Task.Delay(5000);

or, if you want to run some code before the delay:

var sw = new Stopwatch();
sw.Start();
Task delay = Task.Delay(5000);
Console.WriteLine("async: Running for {0} seconds", sw.Elapsed.TotalSeconds);
await delay;

Guess what this will print? Running for 0.0070048 seconds. If we move the await delay above the Console.WriteLine instead, it will print Running for 5.0020168 seconds.

Let's look at the difference with Thread.Sleep:

class Program
{
    static void Main(string[] args)
    {
        Task delay = asyncTask();
        syncCode();
        delay.Wait();
        Console.ReadLine();
    }

    static async Task asyncTask()
    {
        var sw = new Stopwatch();
        sw.Start();
        Console.WriteLine("async: Starting");
        Task delay = Task.Delay(5000);
        Console.WriteLine("async: Running for {0} seconds", sw.Elapsed.TotalSeconds);
        await delay;
        Console.WriteLine("async: Running for {0} seconds", sw.Elapsed.TotalSeconds);
        Console.WriteLine("async: Done");
    }

    static void syncCode()
    {
        var sw = new Stopwatch();
        sw.Start();
        Console.WriteLine("sync: Starting");
        Thread.Sleep(5000);
        Console.WriteLine("sync: Running for {0} seconds", sw.Elapsed.TotalSeconds);
        Console.WriteLine("sync: Done");
    }
}

Try to predict what this will print...

async: Starting
async: Running for 0.0070048 seconds
sync: Starting
async: Running for 5.0119008 seconds
async: Done
sync: Running for 5.0020168 seconds
sync: Done

Also, it is interesting to notice that Thread.Sleep is far more accurate, ms accuracy is not really a problem, while Task.Delay can take 15-30ms minimal. The overhead on both functions is minimal compared to the ms accuracy they have (use Stopwatch Class if you need something more accurate). Thread.Sleep still ties up your Thread, Task.Delay release it to do other work while you wait.

Command-line Git on Windows

In windows 8.1, setting the PATH Environment Variable to Git's bin directory didn't work for me. Instead, I had to use the cmd directory C:\Program Files (x86)\Git\cmd.

Credit to @VonC in this question

PostgreSQL: How to change PostgreSQL user password?

check pg_hba.conf

In case the authentication method is 'peer', the client's operating system user name/password must match the database user name and password. In that case, set the password for Linux user 'postgres' and the DB user 'postgres' to be the same.

see the documentation for details: https://www.postgresql.org/docs/9.1/auth-pg-hba-conf.html

Javascript Drag and drop for touch devices

Old thread I know.......

Problem with the answer of @ryuutatsuo is that it blocks also any input or other element that has to react on 'clicks' (for example inputs), so i wrote this solution. This solution made it possible to use any existing drag and drop library that is based upon mousedown, mousemove and mouseup events on any touch device (or cumputer). This is also a cross-browser solution.

I have tested in on several devices and it works fast (in combination with the drag and drop feature of ThreeDubMedia (see also http://threedubmedia.com/code/event/drag)). It is a jQuery solution so you can use it only with jQuery libs. I have used jQuery 1.5.1 for it because some newer functions don't work properly with IE9 and above (not tested with newer versions of jQuery).

Before you add any drag or drop operation to an event you have to call this function first:

simulateTouchEvents(<object>);

You can also block all components/children for input or to speed up event handling by using the following syntax:

simulateTouchEvents(<object>, true); // ignore events on childs

Here is the code i wrote. I used some nice tricks to speed up evaluating things (see code).

function simulateTouchEvents(oo,bIgnoreChilds)
{
 if( !$(oo)[0] )
  { return false; }

 if( !window.__touchTypes )
 {
   window.__touchTypes  = {touchstart:'mousedown',touchmove:'mousemove',touchend:'mouseup'};
   window.__touchInputs = {INPUT:1,TEXTAREA:1,SELECT:1,OPTION:1,'input':1,'textarea':1,'select':1,'option':1};
 }

$(oo).bind('touchstart touchmove touchend', function(ev)
{
    var bSame = (ev.target == this);
    if( bIgnoreChilds && !bSame )
     { return; }

    var b = (!bSame && ev.target.__ajqmeclk), // Get if object is already tested or input type
        e = ev.originalEvent;
    if( b === true || !e.touches || e.touches.length > 1 || !window.__touchTypes[e.type]  )
     { return; } //allow multi-touch gestures to work

    var oEv = ( !bSame && typeof b != 'boolean')?$(ev.target).data('events'):false,
        b = (!bSame)?(ev.target.__ajqmeclk = oEv?(oEv['click'] || oEv['mousedown'] || oEv['mouseup'] || oEv['mousemove']):false ):false;

    if( b || window.__touchInputs[ev.target.tagName] )
     { return; } //allow default clicks to work (and on inputs)

    // https://developer.mozilla.org/en/DOM/event.initMouseEvent for API
    var touch = e.changedTouches[0], newEvent = document.createEvent("MouseEvent");
    newEvent.initMouseEvent(window.__touchTypes[e.type], true, true, window, 1,
            touch.screenX, touch.screenY,
            touch.clientX, touch.clientY, false,
            false, false, false, 0, null);

    touch.target.dispatchEvent(newEvent);
    e.preventDefault();
    ev.stopImmediatePropagation();
    ev.stopPropagation();
    ev.preventDefault();
});
 return true;
}; 

What it does: At first, it translates single touch events into mouse events. It checks if an event is caused by an element on/in the element that must be dragged around. If it is an input element like input, textarea etc, it skips the translation, or if a standard mouse event is attached to it it will also skip a translation.

Result: Every element on a draggable element is still working.

Happy coding, greetz, Erwin Haantjes

Entity Framework - Include Multiple Levels of Properties

For EF 6

using System.Data.Entity;

query.Include(x => x.Collection.Select(y => y.Property))

Make sure to add using System.Data.Entity; to get the version of Include that takes in a lambda.


For EF Core

Use the new method ThenInclude

query.Include(x => x.Collection)
     .ThenInclude(x => x.Property);

What's the best way to share data between activities?

There is a new and better way to share data between activities, and it is LiveData. Notice in particular this quote from the Android developer's page:

The fact that LiveData objects are lifecycle-aware means that you can share them between multiple activities, fragments, and services. To keep the example simple, you can implement the LiveData class as a singleton

The implication of this is huge - any model data can be shared in a common singleton class inside a LiveData wrapper. It can be injected from the activities into their respective ViewModel for the sake of testability. And you no longer need to worry about weak references to prevent memory leaks.

Difference between array_push() and $array[] =

You can add more than 1 element in one shot to array using array_push,

e.g. array_push($array_name, $element1, $element2,...)

Where $element1, $element2,... are elements to be added to array.

But if you want to add only one element at one time, then other method (i.e. using $array_name[]) should be preferred.

No Activity found to handle Intent : android.intent.action.VIEW

Had this exception even changed to

"audio/*"

But thanx to @Stan i have turned very simple but usefully solution:

Uri.fromFile(File(content)) instead Uri.parse(path)

 val intent =Intent(Intent.ACTION_VIEW)
                    intent.setDataAndType(Uri.fromFile(File(content)),"audio/*")
                    startActivity(intent)

"The stylesheet was not loaded because its MIME type, "text/html" is not "text/css"

Actually I had wrongly put href="", and hence the html file was referencing itself as the CSS. Mozilla had the similar bug once, and I got the answer from there.

Error while retrieving information from the server RPC:s-7:AEC-0 in Google play?

Check if you are using latest version of Google Play.

OR

Following the steps below.

RPC:AEC:0 error is known as CPU/RAM/Device/Identity failure.

Only possible way you can follow to get rid off this error is,

Go to settings >application > Play Store >Clear Data & Clear Cache.

Go to accounts >Google >Remove account.

Reboot device.

Again Settings>Account >Google >Log In.

Refer to this link

OR

Factory Reset is the last working option, if none of the above worked.

Changing the sign of a number in PHP?

function invertSign($value)
{
    return -$value;
}

Create a Cumulative Sum Column in MySQL

If performance is an issue, you could use a MySQL variable:

set @csum := 0;
update YourTable
set cumulative_sum = (@csum := @csum + count)
order by id;

Alternatively, you could remove the cumulative_sum column and calculate it on each query:

set @csum := 0;
select id, count, (@csum := @csum + count) as cumulative_sum
from YourTable
order by id;

This calculates the running sum in a running way :)

How to set cornerRadius for only top-left and top-right corner of a UIView?

iOS 11 , Swift 4
And you can try this code:

if #available(iOS 11.0, *) {
   element.clipsToBounds = true
   element.layer.cornerRadius = CORNER_RADIUS
   element.layer.maskedCorners = [.layerMaxXMaxYCorner]
} else {
   // Fallback on earlier versions
}

And you can using this in table view cell.

Homebrew install specific version of formula?

Along the lines of @halfcube's suggestion, this works really well:

  1. Find the library you're looking for at https://github.com/Homebrew/homebrew-core/tree/master/Formula
  2. Click it: https://github.com/Homebrew/homebrew-core/blob/master/Formula/postgresql.rb
  3. Click the "history" button to look at old commits: https://github.com/Homebrew/homebrew-core/commits/master/Formula/postgresql.rb
  4. Click the one you want: "postgresql: update version to 8.4.4", https://github.com/Homebrew/homebrew-core/blob/8cf29889111b44fd797c01db3cf406b0b14e858c/Formula/postgresql.rb
  5. Click the "raw" link: https://raw.githubusercontent.com/Homebrew/homebrew-core/8cf29889111b44fd797c01db3cf406b0b14e858c/Formula/postgresql.rb
  6. brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/8cf29889111b44fd797c01db3cf406b0b14e858c/Formula/postgresql.rb

Set folder for classpath

If you are using Java 6 or higher you can use wildcards of this form:

java -classpath ".;c:\mylibs\*;c:\extlibs\*" MyApp

If you would like to add all subdirectories: lib\a\, lib\b\, lib\c\, there is no mechanism for this in except:

java -classpath ".;c:\lib\a\*;c:\lib\b\*;c:\lib\c\*" MyApp

There is nothing like lib\*\* or lib\** wildcard for the kind of job you want to be done.

Excel: Creating a dropdown using a list in another sheet?

Yes it is. Use Data Validation from the Data panel. Select Allow: List and pick those cells on the other sheet as your source.

Get the client's IP address in socket.io

This works for the 2.3.0 version:

io.on('connection', socket => {
   const ip = socket.handshake.headers['x-forwarded-for'] || socket.conn.remoteAddress.split(":")[3];
   console.log(ip);
});

How do you specify a different port number in SQL Management Studio?

127.0.0.1,6283

Add a comma between the ip and port

Is there a Subversion command to reset the working copy?

Pure Windows cmd/bat solution:

svn cleanup .
svn revert -R .
For /f "tokens=1,2" %%A in ('svn status --no-ignore') Do (
     If [%%A]==[?] ( Call :UniDelete %%B
     ) Else If [%%A]==[I] Call :UniDelete %%B
   )
svn update .
goto :eof

:UniDelete delete file/dir
IF EXIST "%1\*" (
    RD /S /Q "%1"
) Else (
    If EXIST "%1" DEL /S /F /Q "%1"
)
goto :eof

What is the best way to delete a value from an array in Perl?

You could use array slicing instead of splicing. Grep to return the indices you want keep and use slicing:

my @arr = ...;
# run through each item.
my @indicesToKeep = grep { $arr[$_] ne 'foo' } 0..$#arr;
@arr = @arr[@indicesToKeep];

RegEx to parse or validate Base64 data

From the RFC 4648:

Base encoding of data is used in many situations to store or transfer data in environments that, perhaps for legacy reasons, are restricted to US-ASCII data.

So it depends on the purpose of usage of the encoded data if the data should be considered as dangerous.

But if you’re just looking for a regular expression to match Base64 encoded words, you can use the following:

^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$

Show which git tag you are on?

git log --decorate

This will tell you what refs are pointing to the currently checked out commit.

What does "fatal: bad revision" mean?

in my case I had an inconsistent state where the file in question (with the bad commit hash) was not actually added to Git, this clashed somehow with IntelliJ's state. Manually adding the file using git on the command line fixed the issue for me.

SyntaxError: Use of const in strict mode?

Since the time the question was asked, the draft for the const keyword is already a living standard as part of ECMAScript 2015. Also the current version of Node.js supports const declarations without the --harmony flag.

With the above said you can now run node app.js, with app.js:

'use strict';
const MB = 1024 * 1024;
...

getting both the syntax sugar and the benefits of strict mode.

Converting a double to an int in C#

Casting will ignore anything after the decimal point, so 8.6 becomes 8.

Convert.ToInt32(8.6) is the safe way to ensure your double gets rounded to the nearest integer, in this case 9.

window.onload vs $(document).ready()

window.onload: A normal JavaScript event.

document.ready: A specific jQuery event when the entire HTML has been loaded.

How to assign execute permission to a .sh file in windows to be executed in linux

This is not possible. Linux permissions and windows permissions do not translate. They are machine specific. It would be a security hole to allow permissions to be set on files before they even arrive on the target system.

Change span text?

Replace whatever is in the address bar with this:

javascript:document.getElementById('serverTime').innerHTML='[text here]';

Example.

Get the name of a pandas DataFrame

Sometimes df.name doesn't work.

you might get an error message:

'DataFrame' object has no attribute 'name'

try the below function:

def get_df_name(df):
    name =[x for x in globals() if globals()[x] is df][0]
    return name

What are the main performance differences between varchar and nvarchar SQL Server data types?

I hesitate to add yet another answer here as there are already quite a few, but a few points need to be made that have either not been made or not been made clearly.

First: Do not always use NVARCHAR. That is a very dangerous, and often costly, attitude / approach. And it is no better to say "Never use cursors" since they are sometimes the most efficient means of solving a particular problem, and the common work-around of doing a WHILE loop will almost always be slower than a properly done Cursor.

The only time you should use the term "always" is when advising to "always do what is best for the situation". Granted that is often difficult to determine, especially when trying to balance short-term gains in development time (manager: "we need this feature -- that you didn't know about until just now -- a week ago!") with long-term maintenance costs (manager who initially pressured team to complete a 3-month project in a 3-week sprint: "why are we having these performance problems? How could we have possibly done X which has no flexibility? We can't afford a sprint or two to fix this. What can we get done in a week so we can get back to our priority items? And we definitely need to spend more time in design so this doesn't keep happening!").

Second: @gbn's answer touches on some very important points to consider when making certain data modeling decisions when the path isn't 100% clear. But there is even more to consider:

  • size of transaction log files
  • time it takes to replicate (if using replication)
  • time it takes to ETL (if ETLing)
  • time it takes to ship logs to a remote system and restore (if using Log Shipping)
  • size of backups
  • length of time it takes to complete the backup
  • length of time it takes to do a restore (this might be important some day ;-)
  • size needed for tempdb
  • performance of triggers (for inserted and deleted tables that are stored in tempdb)
  • performance of row versioning (if using SNAPSHOT ISOLATION, since the version store is in tempdb)
  • ability to get new disk space when the CFO says that they just spent $1 million on a SAN last year and so they will not authorize another $250k for additional storage
  • length of time it takes to do INSERT and UPDATE operations
  • length of time it takes to do index maintenance
  • etc, etc, etc.

Wasting space has a huge cascade effect on the entire system. I wrote an article going into explicit detail on this topic: Disk Is Cheap! ORLY? (free registration required; sorry I don't control that policy).

Third: While some answers are incorrectly focusing on the "this is a small app" aspect, and some are correctly suggesting to "use what is appropriate", none of the answers have provided real guidance to the O.P. An important detail mentioned in the Question is that this is a web page for their school. Great! So we can suggest that:

  • Fields for Student and/or Faculty names should probably be NVARCHAR since, over time, it is only getting more likely that names from other cultures will be showing up in those places.
  • But for street address and city names? The purpose of the app was not stated (it would have been helpful) but assuming the address records, if any, pertain to just to a particular geographical region (i.e. a single language / culture), then use VARCHAR with the appropriate Code Page (which is determined from the Collation of the field).
  • If storing State and/or Country ISO codes (no need to store INT / TINYINT since ISO codes are fixed length, human readable, and well, standard :) use CHAR(2) for two letter codes and CHAR(3) if using 3 letter codes. And consider using a binary Collation such as Latin1_General_100_BIN2.
  • If storing postal codes (i.e. zip codes), use VARCHAR since it is an international standard to never use any letter outside of A-Z. And yes, still use VARCHAR even if only storing US zip codes and not INT since zip codes are not numbers, they are strings, and some of them have a leading "0". And consider using a binary Collation such as Latin1_General_100_BIN2.
  • If storing email addresses and/or URLs, use NVARCHAR since both of those can now contain Unicode characters.
  • and so on....

Fourth: Now that you have NVARCHAR data taking up twice as much space than it needs to for data that fits nicely into VARCHAR ("fits nicely" = doesn't turn into "?") and somehow, as if by magic, the application did grow and now there are millions of records in at least one of these fields where most rows are standard ASCII but some contain Unicode characters so you have to keep NVARCHAR, consider the following:

  1. If you are using SQL Server 2008 - 2016 RTM and are on Enterprise Edition, OR if using SQL Server 2016 SP1 (which made Data Compression available in all editions) or newer, then you can enable Data Compression. Data Compression can (but won't "always") compress Unicode data in NCHAR and NVARCHAR fields. The determining factors are:

    1. NCHAR(1 - 4000) and NVARCHAR(1 - 4000) use the Standard Compression Scheme for Unicode, but only starting in SQL Server 2008 R2, AND only for IN ROW data, not OVERFLOW! This appears to be better than the regular ROW / PAGE compression algorithm.
    2. NVARCHAR(MAX) and XML (and I guess also VARBINARY(MAX), TEXT, and NTEXT) data that is IN ROW (not off row in LOB or OVERFLOW pages) can at least be PAGE compressed, but not ROW compressed. Of course, PAGE compression depends on size of the in-row value: I tested with VARCHAR(MAX) and saw that 6000 character/byte rows would not compress, but 4000 character/byte rows did.
    3. Any OFF ROW data, LOB or OVERLOW = No Compression For You!
  2. If using SQL Server 2005, or 2008 - 2016 RTM and not on Enterprise Edition, you can have two fields: one VARCHAR and one NVARCHAR. For example, let's say you are storing URLs which are mostly all base ASCII characters (values 0 - 127) and hence fit into VARCHAR, but sometimes have Unicode characters. Your schema can include the following 3 fields:

      ...
      URLa VARCHAR(2048) NULL,
      URLu NVARCHAR(2048) NULL,
      URL AS (ISNULL(CONVERT(NVARCHAR([URLa])), [URLu])),
      CONSTRAINT [CK_TableName_OneUrlMax] CHECK (
                        ([URLa] IS NOT NULL OR [URLu] IS NOT NULL)
                    AND ([URLa] IS NULL OR [URLu] IS NULL))
    );
    

    In this model you only SELECT from the [URL] computed column. For inserting and updating, you determine which field to use by seeing if converting alters the incoming value, which has to be of NVARCHAR type:

    INSERT INTO TableName (..., URLa, URLu)
    VALUES (...,
            IIF (CONVERT(VARCHAR(2048), @URL) = @URL, @URL, NULL),
            IIF (CONVERT(VARCHAR(2048), @URL) <> @URL, NULL, @URL)
           );
    
  3. You can GZIP incoming values into VARBINARY(MAX) and then unzip on the way out:

    • For SQL Server 2005 - 2014: you can use SQLCLR. SQL# (a SQLCLR library that I wrote) comes with Util_GZip and Util_GUnzip in the Free version
    • For SQL Server 2016 and newer: you can use the built-in COMPRESS and DECOMPRESS functions, which are also GZip.
  4. If using SQL Server 2017 or newer, you can look into making the table a Clustered Columnstore Index.

  5. While this is not a viable option yet, SQL Server 2019 introduces native support for UTF-8 in VARCHAR / CHAR datatypes. There are currently too many bugs with it for it to be used, but if they are fixed, then this is an option for some scenarios. Please see my post, "Native UTF-8 Support in SQL Server 2019: Savior or False Prophet?", for a detailed analysis of this new feature.

Test only if variable is not null in if statement

I don't believe the expression is sensical as it is.

Elvis means "if truthy, use the value, else use this other thing."

Your "other thing" is a closure, and the value is status != null, neither of which would seem to be what you want. If status is null, Elvis says true. If it's not, you get an extra layer of closure.

Why can't you just use:

(it.description == desc) && ((status == null) || (it.status == status))

Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find calls, just use an intermediate variable.

Adding an img element to a div with javascript

function image()
{
    //dynamically add an image and set its attribute
    var img=document.createElement("img");
    img.src="p1.jpg"
    img.id="picture"
    var foo = document.getElementById("fooBar");
    foo.appendChild(img);
}

<span id="fooBar">&nbsp;</span>

jQuery trigger file input

Correct code:

<style>
    .upload input[type='file']{
        position: absolute;
        float: left;
        opacity: 0; /* For IE8 "Keep the IE opacity settings in this order for max compatibility" */
        -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)"; /* For IE5 - 7 */
        filter: alpha(opacity=0);
        width: 100px; height: 30px; z-index: 51
    }
    .upload input[type='button']{
        width: 100px;
        height: 30px;
        z-index: 50;
    }
    .upload input[type='submit']{
        display: none;
    }
    .upload{
        width: 100px; height: 30px
    }
</style>
<div class="upload">
    <input type='file' ID="flArquivo" onchange="upload();" />
    <input type="button" value="Selecionar" onchange="open();" />
    <input type='submit' ID="btnEnviarImagem"  />
</div>

<script type="text/javascript">
    function open() {
        $('#flArquivo').click();
    }
    function upload() {
        $('#btnEnviarImagem').click();
    }
</script>

Stop all active ajax requests in jQuery

I have updated the code to make it works for me

$.xhrPool = [];
$.xhrPool.abortAll = function() {
    $(this).each(function(idx, jqXHR) {
        jqXHR.abort();
    });
    $(this).each(function(idx, jqXHR) {
        var index = $.inArray(jqXHR, $.xhrPool);
        if (index > -1) {
            $.xhrPool.splice(index, 1);
        }
    });
};

$.ajaxSetup({
    beforeSend: function(jqXHR) {
        $.xhrPool.push(jqXHR);
    },
    complete: function(jqXHR) {
        var index = $.inArray(jqXHR, $.xhrPool);
        if (index > -1) {
            $.xhrPool.splice(index, 1);
        }
    }
});

How do I view the full content of a text or varchar(MAX) column in SQL Server 2008 Management Studio?

Starting from SSMS 18.2, you can now view up to 2 million characters in the grid results. Source

Allow more data to be displayed (Result to Text) and stored in cells (Result to Grid). SSMS now allows up to 2M characters for both.

I verified this with the code below.

DECLARE @S varchar(max) = 'A'

SET @S =  REPLICATE(@S,2000000) + 'B' 

SELECT @S as a

How can I create an object based on an interface file definition in TypeScript?

Since I haven't found an equal answer in the top and my answer is different. I do:

modal: IModal = <IModal>{}

What's the difference between Apache's Mesos and Google's Kubernetes

Mesos and Kubernetes both are container orchestration tools.

When you say "Google Kubernetes"?

Google Kubernetes Engine provides a managed environment for deploying, managing, and scaling your containerized applications using Google infrastructure.

Kubernetes is an open-source system for automating deployment, scaling, and management of containerized applications.” Kubernetes was built by Google based on their experience running containers in production over the last decade.

The major components in a Kubernetes cluster are:

pods — a way to group containers together replication controllers — a way to handle the lifecycle of containers labels — a way to find and query containers, and services — a set of containers performing a common function

Mesos is an open-source cluster management project by Apache, designed to scale to very large clusters, from hundreds to thousands of hosts. Mesos supports diverse kinds of workloads such as Hadoop tasks, cloud native applications etc. It gives you the ability to run both containerized, and non-containerized workloads in a distributed manner.

It was initially written as a research project at Berkeley and was later adopted by Twitter as an answer to Google’s Borg (Kubernetes’ predecessor). To combat its high degree of complexity (Mesos is super complicated and hard to manage!), Mesosphere came into the picture to try and make Mesos into something regular human beings can use.

Mesosphere supplied the superb Marathon “plugin” to Mesos, which provides users with an easy way to manage container orchestration over Mesos.

In mid-2016, DC/OS (Data Center Operating System) — an open source project backed by Mesosphere — was introduced, which simplifies Mesos even further and allows you to deploy your own Mesos cluster, with Marathon, in a matter of minutes.

Now, if we compare kubernetes and Mesos(DC/OS)

kubernetes is a cluster manager for containers while mesos is a distributed system kernel that will make your cluster look like one giant computer system to all supported frameworks and apps that are built to be run on mesos.

Mesos was born for a world where you own a lot of physical resources to create a big static computing cluster. The great thing about it is that lots of modern scalable data processing application runs very well on Mesos (Hadoop, Kafka, Spark) and it is nice because you can run them all on the same basic resource pool, along with your new age container packaged apps.

Mesos cluster also runs alongside the Marathon cluster. Marathon, created by Mesosphere, is designed to start, monitor and scale long-running applications, including cloud native apps. Clients interact with Marathon through a REST API.

Also, a point to be noted is that you can actually run Kubernetes on top of DC/OS and schedule containers with it instead of using Marathon. This implies the biggest difference of all — DC/OS, as it name suggests, is more similar to an operating system rather than an orchestration framework. You can run non-containerized, stateful workloads on it. Container scheduling is handled by the Marathon.

How to detect when facebook's FB.init is complete

I've avoided using setTimeout by using a global function:

EDIT NOTE: I've updated the following helper scripts and created a class that easier/simpler to use; check it out here ::: https://github.com/tjmehta/fbExec.js

window.fbAsyncInit = function() {
    FB.init({
        //...
    });
    window.fbApiInit = true; //init flag
    if(window.thisFunctionIsCalledAfterFbInit)
        window.thisFunctionIsCalledAfterFbInit();
};

fbEnsureInit will call it's callback after FB.init

function fbEnsureInit(callback){
  if(!window.fbApiInit) {
    window.thisFunctionIsCalledAfterFbInit = callback; //find this in index.html
  }
  else{
    callback();
  }
}

fbEnsureInitAndLoginStatus will call it's callback after FB.init and after FB.getLoginStatus

function fbEnsureInitAndLoginStatus(callback){
  runAfterFbInit(function(){
    FB.getLoginStatus(function(response){
      if (response.status === 'connected') {
        // the user is logged in and has authenticated your
        // app, and response.authResponse supplies
        // the user's ID, a valid access token, a signed
        // request, and the time the access token
        // and signed request each expire
        callback();

      } else if (response.status === 'not_authorized') {
        // the user is logged in to Facebook,
        // but has not authenticated your app

      } else {
        // the user isn't logged in to Facebook.

      }
    });
  });
}

fbEnsureInit example usage:

(FB.login needs to be run after FB has been initialized)

fbEnsureInit(function(){
    FB.login(
       //..enter code here
    );
});

fbEnsureInitAndLogin example usage:

(FB.api needs to be run after FB.init and FB user must be logged in.)

fbEnsureInitAndLoginStatus(function(){
    FB.api(
       //..enter code here
    );
});

How to read file from relative path in Java project? java.io.File cannot find the path specified

String basePath = new File("myFile.txt").getAbsolutePath(); this basepath you can use as the correct path of your file

VBA: Counting rows in a table (list object)

You can use:

Sub returnname(ByVal TableName As String)

MsgBox (Range("Table15").Rows.count)

End Sub

and call the function as below

Sub called()

returnname "Table15"

End Sub

Error renaming a column in MySQL

The standard Mysql rename statement is:

ALTER [ONLINE | OFFLINE] [IGNORE] TABLE tbl_name 
CHANGE [COLUMN] old_col_name new_col_name column_definition 
[FIRST|AFTER col_name]

for this example:

ALTER TABLE xyz CHANGE manufacurerid manufacturerid datatype(length)

Reference: MYSQL 5.1 ALTER TABLE Syntax

Position DIV relative to another DIV?

You need to set postion:relative of outer DIV and position:absolute of inner div.
Try this. Here is the Demo

#one
{
    background-color: #EEE;
    margin: 62px 258px;
    padding: 5px;
    width: 200px;
    position: relative;   
}

#two
{
    background-color: #F00;
    display: inline-block;
    height: 30px;
    position: absolute;
    width: 100px;
    top:10px;
}?

what is Promotional and Feature graphic in Android Market/Play Store?

Promo graphic

The promo graphic is used for promotions on older versions of the Android OS (earlier than 4.0). This image is not required to submit an update for your Store Listing.

Requirements

  • JPG or 24-bit PNG (no alpha)
  • Dimensions: 180px by 120px

https://support.google.com/googleplay/android-developer/answer/1078870

What is log4j's default log file dumping path

You have copy this sample code from Here,right?
now, as you can see there property file they have define, have you done same thing? if not then add below code in your project with property file for log4j

So the content of log4j.properties file would be as follows:

# Define the root logger with appender file
log = /usr/home/log4j
log4j.rootLogger = DEBUG, FILE

# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${log}/log.out

# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n

make changes as per your requirement like log path

Create a OpenSSL certificate on Windows

Consider using certificate depot web app to easily create private key and certificate based on it: http://www.cert-depot.com/

It can also create a PFX for you.

Disclaimer: I am the creator of certificate depot.

Handling JSON Post Request in Go

type test struct {
    Test string `json:"test"`
}

func test(w http.ResponseWriter, req *http.Request) {
    var t test_struct

    body, _ := ioutil.ReadAll(req.Body)
    json.Unmarshal(body, &t)

    fmt.Println(t)
}

How and where are Annotations used in Java?

Annotations in Java, provide a mean to describe classes, fields and methods. Essentially, they are a form of metadata added to a Java source file, they can't affect the semantics of a program directly. However, annotations can be read at run-time using Reflection & this process is known as Introspection. Then it could be used to modify classes, fields or methods.

This feature, is often exploited by Libraries & SDKs (hibernate, JUnit, Spring Framework) to simplify or reduce the amount of code that a programmer would unless do in orer to work with these Libraries or SDKs.Therefore, it's fair to say Annotations and Reflection work hand-in hand in Java.

We also get to limit the availability of an annotation to either compile-time or runtime.Below is a simple example on creating a custom annotation

Driver.java

package io.hamzeen;

import java.lang.annotation.Annotation;

public class Driver {

    public static void main(String[] args) {
        Class<TestAlpha> obj = TestAlpha.class;
        if (obj.isAnnotationPresent(IssueInfo.class)) {

            Annotation annotation = obj.getAnnotation(IssueInfo.class);
            IssueInfo testerInfo = (IssueInfo) annotation;

            System.out.printf("%nType: %s", testerInfo.type());
            System.out.printf("%nReporter: %s", testerInfo.reporter());
            System.out.printf("%nCreated On: %s%n%n",
                    testerInfo.created());
        }
    }
}

TestAlpha.java

package io.hamzeen;

import io.hamzeen.IssueInfo;
import io.hamzeen.IssueInfo.Type;

@IssueInfo(type = Type.IMPROVEMENT, reporter = "Hamzeen. H.")
public class TestAlpha {

}

IssueInfo.java

package io.hamzeen;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author Hamzeen. H.
 * @created 10/01/2015
 * 
 * IssueInfo annotation definition
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface IssueInfo {

    public enum Type {
        BUG, IMPROVEMENT, FEATURE
    }

    Type type() default Type.BUG;

    String reporter() default "Vimesh";

    String created() default "10/01/2015";
}

Using Mockito to test abstract classes

class Dependency{
  public void method(){};
}

public abstract class My {

  private Dependency dependency;
  public abstract boolean myAbstractMethod();

  public void myNonAbstractMethod() {
    // ...
    dependency.method();
  }
}

@RunWith(MockitoJUnitRunner.class)
public class MyTest {

  @InjectMocks
  private My my = Mockito.mock(My.class, Mockito.CALLS_REAL_METHODS);
  // we can mock dependencies also here
  @Mock
  private Dependency dependency;

  @Test
  private void shouldPass() {
    // can be mock the dependency object here.
    // It will be useful to test non abstract method
    my.myNonAbstractMethod();
  }
}

Documentation for using JavaScript code inside a PDF file

Here you can find "Adobe Acrobat Forms JavaScript Object Specification Version 4.0"

Revised: January 27, 1999

It’s very old, but it is still useful.

Very Simple Image Slider/Slideshow with left and right button. No autoplay

<script type="text/javascript">
                    $(document).ready(function(e) {
                        $(".mqimg").mouseover(function()
                        {
                            $("#imgprev").animate({height: "250px",width: "70%",left: "15%"},100).html("<img src='"+$(this).attr('src')+"' width='100%' height='100%' />"); 
                        })
                        $(".mqimg").mouseout(function()
                        {
                            $("#imgprev").animate({height: "0px",width: "0%",left: "50%"},100);
                        })
                    });
                    </script>
                    <style>
                    .mqimg{ cursor:pointer;}
                    </style>
                    <div style="position:relative; width:100%; height:1px; text-align:center;">`enter code here`
                    <div id="imgprev" style="position:absolute; display:block; box-shadow:2px 5px 10px #333; width:70%; height:0px; background:#999; left:15%; bottom:15px; "></div>
<img class='mqimg' src='spppimages/1.jpg' height='100px' />
<img class='mqimg' src='spppimages/2.jpg' height='100px' />
<img class='mqimg' src='spppimages/3.jpg' height='100px' />
<img class='mqimg' src='spppimages/4.jpg' height='100px' />
<img class='mqimg' src='spppimages/5.jpg' height='100px' />

Case Insensitive String comp in C

Simple solution:

int str_case_ins_cmp(const char* a, const char* b) {
  int rc;

  while (1) {
    rc = tolower((unsigned char)*a) - tolower((unsigned char)*b);
    if (rc || !*a) {
      break;
    }

    ++a;
    ++b;
  }

  return rc;
}

Difference between save and saveAndFlush in Spring data jpa

On saveAndFlush, changes will be flushed to DB immediately in this command. With save, this is not necessarily true, and might stay just in memory, until flush or commit commands are issued.

But be aware, that even if you flush the changes in transaction and do not commit them, the changes still won't be visible to the outside transactions until the commit in this transaction.

In your case, you probably use some sort of transactions mechanism, which issues commit command for you if everything works out fine.

Does adding a duplicate value to a HashSet/HashMap replace the previous value

You need to check put method in Hash map first as HashSet is backed up by HashMap

  1. When you add duplicate value say a String "One" into HashSet,
  2. An entry ("one", PRESENT) will get inserted into Hashmap(for all the values added into set, the value will be "PRESENT" which if of type Object)
  3. Hashmap adds the entry into Map and returns the value, which is in this case "PRESENT" or null if Entry is not there.
  4. Hashset's add method then returns true if the returned value from Hashmap equals null otherwise false which means an entry already exists...

How to delete history of last 10 commands in shell?

edit:

Changed the braced iterators, good call. Also, call this function with a reverse iterator.

You can probably do something like this:

#!/bin/bash
HISTFILE=~/.bash_history   # if you are running it in a 
                           # non interactive shell history would not work else
set -o history
for i in `seq $1 $2`;
do
    history -d $i
done
history -w

Where you will evoke like this:

./nameOfYourScript 563 514

Notice I haven't put any error checking in for the bounds. I'll leave that as an exercise to the reader.

see also this question

How can I listen for keypress event on the whole page?

yurzui's answer didn't work for me, it might be a different RC version, or it might be a mistake on my part. Either way, here's how I did it with my component in Angular2 RC4 (which is now quite outdated).

@Component({
    ...
    host: {
        '(document:keydown)': 'handleKeyboardEvents($event)'
    }
})
export class MyComponent {
    ...
    handleKeyboardEvents(event: KeyboardEvent) {
        this.key = event.which || event.keyCode;
    }
}

Footnotes for tables in LaTeX

A maybe not-so-elegant method, which I think is just a variation of what some other people have said, is to just hardcode it. Many journals have a template that in some way allows for table footnotes, so I try to keep things pretty basic. Although, there really are some incredible packages already out there, and I think this thread does a good job of pointing that out.

\documentclass{article}
\begin{document}
\begin{table}[!th]
\renewcommand{\arraystretch}{1.3} % adds row cushion
\caption{Data, level$^a$, and sources$^b$}
\vspace{4mm}
\centering
\begin{tabular}{|l|l|c|c|}
  \hline      
  \textbf{Data}  & \textbf{Description}   & \textbf{Level} & \textbf{Source} \\
  \hline      
  \hline
  Data1  &  Description. . . . . . . . . . . . . . . . . .   &  cnty & USGS \\
  \hline
  Data2  &  Description. . . . . . . . . . . . . . . . . .   &  MSA & USGS \\
  \hline
  Data3  &  Description. . . . . . . . . . . . . . . . . .   &  cnty & Census  \\
  \hline  
\end{tabular}
\end{table}
\footnotesize{$^a$ The smallest spatial unit is county, $^b$ more details in appendix A}\\
\end{document}

Output from above code

HTML-encoding lost when attribute read from input field

I ran into some issues with backslash in my Domain\User string.

I added this to the other escapes from Anentropic's answer

.replace(/\\/g, '&#92;')

Which I found here: How to escape backslash in JavaScript?

How to fix broken paste clipboard in VNC on Windows

http://rreddy.blogspot.com/2009/07/vncviewer-clipboard-operations-like.html

Many times you must have observed that clipboard operations like copy/cut and paste suddenly stops workings with the vncviewer. The main reason for this there is a program called as vncconfig responsible for these clipboard transfers. Some times the program may get closed because of some bug in vnc or some other reasons like you closed that window.

To get those clipboard operations back you need to run the program "vncconfig &".

After this your clipboard actions should work fine with out any problems.

Run "vncconfig &" on the client.

Python "TypeError: unhashable type: 'slice'" for encoding categorical data

Your x and y values ??are not running so first of all youre begin to write this point

 import numpy as np
 import pandas as pd
 import matplotlib as plt

 dataframe=pd.read_csv(".\datasets\Position_Salaries.csv")

 x=dataframe.iloc[:,1:2].values 
 y=dataframe.iloc[:,2].values    
 x1=dataframe.iloc[:,:-1].values 

point of value have publish

How do you dynamically add elements to a ListView on Android?

Code for MainActivity.java file.

public class MainActivity extends Activity {

    ListView listview;
    Button Addbutton;
    EditText GetValue;
    String[] ListElements = new String[] {
        "Android",
        "PHP"
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listview = (ListView) findViewById(R.id.listView1);
        Addbutton = (Button) findViewById(R.id.button1);
        GetValue = (EditText) findViewById(R.id.editText1);

        final List < String > ListElementsArrayList = new ArrayList < String >
            (Arrays.asList(ListElements));


        final ArrayAdapter < String > adapter = new ArrayAdapter < String >
            (MainActivity.this, android.R.layout.simple_list_item_1,
                ListElementsArrayList);

        listview.setAdapter(adapter);

        Addbutton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                ListElementsArrayList.add(GetValue.getText().toString());
                adapter.notifyDataSetChanged();
            }
        });
    }
}

Code for activity_main.xml layout file.

<RelativeLayout 
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:paddingBottom="@dimen/activity_vertical_margin"
  android:paddingLeft="@dimen/activity_horizontal_margin"
  android:paddingRight="@dimen/activity_horizontal_margin"
  android:paddingTop="@dimen/activity_vertical_margin"
  tools:context="com.listviewaddelementsdynamically_android_examples
    .com.MainActivity" >

  <Button
    android:id="@+id/button1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/editText1"
    android:layout_centerHorizontal="true"
    android:text="ADD Values to listview" />

  <EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="26dp"
    android:ems="10"
    android:hint="Add elements listView" />

  <ListView
    android:id="@+id/listView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/button1"
    android:layout_centerHorizontal="true" >
  </ListView>

</RelativeLayout>

ScreenShot

enter image description here

Can git undo a checkout of unstaged files

If you work with a terminal/cmd prompt open, and used any git commands that would have showed the unstaged changes (diff, add -p, checkout -p, etc.), and haven't closed the terminal/cmd prompt since, you'll find the unstaged changes are still available if you scroll up to where you ran those aforementioned git commands.

Add new attribute (element) to JSON object using JavaScript

A JSON object is simply a javascript object, so with Javascript being a prototype based language, all you have to do is address it using the dot notation.

mything.NewField = 'foo';

When is assembly faster than C?

In days where processor speed was measured in MHz and screen size was below 1 megapixel, a well known trick to have faster display was to unroll loops: write operation for each scan line of the screen. It avoided overhead of maintaining a loop index! Coupled with detection of screen refresh, it was quite effective.
That's something a C compiler wouldn't do... (although often you can choose between optimization for speed or for size, I suppose the former uses some similar tricks.)

I know some people enjoy writing Windows applications in assembly language. They claim they are faster (hard to prove) and smaller (indeed!).
Obviously, while it is fun to do, it is probably wasted time (except for learning purpose, of course!), particularly for GUI operations... Now, perhaps some operations, like searching a string in a file, can be optimized by carefully written assembly code.

How to change background color of cell in table using java script

Try this:

function btnClick() {
    var x = document.getElementById("mytable").getElementsByTagName("td");
    x[0].innerHTML = "i want to change my cell color";
    x[0].style.backgroundColor = "yellow";            
}

Set from JS, backgroundColor is the equivalent of background-color in your style-sheet.

Note also that the .cells collection belongs to a table row, not to the table itself. To get all the cells from all rows you can instead use getElementsByTagName().

Demo: http://jsbin.com/ekituv/edit#preview

Check that a variable is a number in UNIX shell

if echo $var | egrep -q '^[0-9]+$'

Actually this does not work if var is multiline.

ie

var="123
qwer"

Especially if var comes from a file :

var=`cat var.txt`

This is the simplest :

if [ "$var" -eq "$var" ] 2> /dev/null
then echo yes
else echo no
fi

Draw horizontal rule in React Native

import { View, Dimensions } from 'react-native'

var { width, height } = Dimensions.get('window')

// Create Component

<View style={{
   borderBottomColor: 'black', 
   borderBottomWidth: 0.5, 
   width: width - 20,}}>
</View>

List Git commits not pushed to the origin yet

git log origin/master..master

or, more generally:

git log <since>..<until>

You can use this with grep to check for a specific, known commit:

git log <since>..<until> | grep <commit-hash>

Or you can also use git-rev-list to search for a specific commit:

git rev-list origin/master | grep <commit-hash>

Gradle finds wrong JAVA_HOME even though it's correctly set

Before running the command try entering:

export JAVA_HOME="path_to_java_home"

Where path_to_java_home is the folder where your bin/java is.

If java is properly installed you can find it's location, by using the command:

readlink -f $(which java)

Don't forget to remove bin/java from the end of the path while putting it into JAVA_HOME

Optional query string parameters in ASP.NET Web API

Default values cannot be supplied for parameters that are not declared 'optional'

 Function GetFindBooks(id As Integer, ByVal pid As Integer, Optional sort As String = "DESC", Optional limit As Integer = 99)

In your WebApiConfig

 config.Routes.MapHttpRoute( _
          name:="books", _
          routeTemplate:="api/{controller}/{action}/{id}/{pid}/{sort}/{limit}", _
          defaults:=New With {.id = RouteParameter.Optional, .pid = RouteParameter.Optional, .sort = UrlParameter.Optional, .limit = UrlParameter.Optional} _
      )

How to execute Ant build in command line

Go to the Ant website and download. This way, you have a copy of Ant outside of Eclipse. I recommend to put it under the C:\ant directory. This way, it doesn't have any spaces in the directory names. In your System Control Panel, set the Environment Variable ANT_HOME to this directory, then pre-pend to the System PATHvariable, %ANT_HOME%\bin. This way, you don't have to put in the whole directory name.

Assuming you did the above, try this:

C:\> cd \Silk4J\Automation\iControlSilk4J
C:\Silk4J\Automation\iControlSilk4J> ant -d build

This will do several things:

  • It will eliminate the possibility that the problem is with Eclipe's version of Ant.
  • It is way easier to type
  • Since you're executing the build.xml in the directory where it exists, you don't end up with the possibility that your Ant build can't locate a particular directory.

The -d will print out a lot of output, so you might want to capture it, or set your terminal buffer to something like 99999, and run cls first to clear out the buffer. This way, you'll capture all of the output from the beginning in the terminal buffer.

Let's see how Ant should be executing. You didn't specify any targets to execute, so Ant should be taking the default build target. Here it is:

<target depends="build-subprojects,build-project" name="build"/>

The build target does nothing itself. However, it depends upon two other targets, so these will be called first:

The first target is build-subprojects:

<target name="build-subprojects"/>

This does nothing at all. It doesn't even have a dependency.

The next target specified is build-project does have code:

<target depends="init" name="build-project">

This target does contain tasks, and some dependent targets. Before build-project executes, it will first run the init target:

<target name="init">
    <mkdir dir="bin"/>
    <copy includeemptydirs="false" todir="bin">
        <fileset dir="src">
            <exclude name="**/*.java"/>
        </fileset>
    </copy>
</target>

This target creates a directory called bin, then copies all files under the src tree with the suffix *.java over to the bin directory. The includeemptydirs mean that directories without non-java code will not be created.

Ant uses a scheme to do minimal work. For example, if the bin directory is created, the <mkdir/> task is not executed. Also, if a file was previously copied, or there are no non-Java files in your src directory tree, the <copy/> task won't run. However, the init target will still be executed.

Next, we go back to our previous build-project target:

<target depends="init" name="build-project">
    <echo message="${ant.project.name}: ${ant.file}"/>
    <javac debug="true" debuglevel="${debuglevel}" destdir="bin" source="${source}" target="${target}">
        <src path="src"/>
        <classpath refid="iControlSilk4J.classpath"/>
    </javac>
</target>

Look at this line:

<echo message="${ant.project.name}: ${ant.file}"/>

That should have always executed. Did your output print:

[echo] iControlSilk4J: C:\Silk4J\Automation\iControlSilk4J\build.xml

Maybe you didn't realize that was from your build.

After that, it runs the <javac/> task. That is, if there's any files to actually compile. Again, Ant tries to avoid work it doesn't have to do. If all of the *.java files have previously been compiled, the <javac/> task won't execute.

And, that's the end of the build. Your build might not have done anything simply because there was nothing to do. You can try running the clean task, and then build:

C:\Silk4J\Automation\iControlSilk4J> ant -d clean build

However, Ant usually prints the target being executed. You should have seen this:

init:

build-subprojects:

build-projects:

    [echo] iControlSilk4J: C:\Silk4J\Automation\iControlSilk4J\build.xml

build:

Build Successful

Note that the targets are all printed out in order they're executed, and the tasks are printed out as they are executed. However, if there's nothing to compile, or nothing to copy, then you won't see these tasks being executed. Does this look like your output? If so, it could be there's nothing to do.

  • If the bin directory already exists, <mkdir/> isn't going to execute.
  • If there are no non-Java files in src, or they have already been copied into bin, the <copy/> task won't execute.
  • If there are no Java file in your src directory, or they have already been compiled, the <java/> task won't run.

If you look at the output from the -d debug, you'll see Ant looking at a task, then explaining why a particular task wasn't executed. Plus, the debug option will explain how Ant decides what tasks to execute.

See if that helps.

When should I use uuid.uuid1() vs. uuid.uuid4() in python?

One thing to note when using uuid1, if you use the default call (without giving clock_seq parameter) you have a chance of running into collisions: you have only 14 bit of randomness (generating 18 entries within 100ns gives you roughly 1% chance of a collision see birthday paradox/attack). The problem will never occur in most use cases, but on a virtual machine with poor clock resolution it will bite you.

integrating barcode scanner into php application?

If you have Bluetooth, Use twedge on windows and getblue app on android, they also have a few videos of it. It's made by TEC-IT. I've got it to work by setting the interface option to bluetooth server in TWedge and setting the output setting in getblue to Bluetooth client and selecting my computer from the Bluetooth devices list. Make sure your computer and phone is paired. Also to get the barcode as input set the action setting in TWedge to Keyboard Wedge. This will allow for you to first click the input text box on said form, then scan said product with your phone and wait a sec for the barcode number to be put into the text box. Using this method requires no php that doesn't already exist in your current form processing, just process the text box as usual and viola your phone scans bar codes, sends them to your pc via Bluetooth wirelessly, your computer inserts the barcode into whatever text field is selected in any application or website. Hope this helps.

How to iterate over a JSONObject?

I will avoid iterator as they can add/remove object during iteration, also for clean code use for loop. it will be simply clean & fewer lines.

Using Java 8 and Lamda [Update 4/2/2019]

import org.json.JSONObject;

public static void printJsonObject(JSONObject jsonObj) {
    jsonObj.keySet().forEach(keyStr ->
    {
        Object keyvalue = jsonObj.get(keyStr);
        System.out.println("key: "+ keyStr + " value: " + keyvalue);

        //for nested objects iteration if required
        //if (keyvalue instanceof JSONObject)
        //    printJsonObject((JSONObject)keyvalue);
    });
}

Using old way [Update 4/2/2019]

import org.json.JSONObject;

public static void printJsonObject(JSONObject jsonObj) {
    for (String keyStr : jsonObj.keySet()) {
        Object keyvalue = jsonObj.get(keyStr);

        //Print key and value
        System.out.println("key: "+ keyStr + " value: " + keyvalue);

        //for nested objects iteration if required
        //if (keyvalue instanceof JSONObject)
        //    printJsonObject((JSONObject)keyvalue);
    }
}

Original Answer

import org.json.simple.JSONObject;
public static void printJsonObject(JSONObject jsonObj) {
    for (Object key : jsonObj.keySet()) {
        //based on you key types
        String keyStr = (String)key;
        Object keyvalue = jsonObj.get(keyStr);

        //Print key and value
        System.out.println("key: "+ keyStr + " value: " + keyvalue);

        //for nested objects iteration if required
        if (keyvalue instanceof JSONObject)
            printJsonObject((JSONObject)keyvalue);
    }
}

$this->session->set_flashdata() and then $this->session->flashdata() doesn't work in codeigniter

Displaying a flash message after redirect in Codeigniter

In Your Controller set this

<?php

public function change_password(){







if($this->input->post('submit')){
$change = $this->common_register->change_password();

if($change == true){
$messge = array('message' => 'Password chnage successfully','class' => 'alert alert-success fade in');
$this->session->set_flashdata('item', $messge);
}else{
$messge = array('message' => 'Wrong password enter','class' => 'alert alert-danger fade in');
$this->session->set_flashdata('item',$messge );
}
$this->session->keep_flashdata('item',$messge);



redirect('controllername/methodname','refresh');
}

?>

In Your View File Set this
<script type="application/javascript">
/** After windod Load */
$(window).bind("load", function() {
  window.setTimeout(function() {
    $(".alert").fadeTo(500, 0).slideUp(500, function(){
        $(this).remove();
    });
}, 4000);
});
</script>

<?php

if($this->session->flashdata('item')) {
$message = $this->session->flashdata('item');
?>
<div class="<?php echo $message['class'] ?>"><?php echo $message['message']; ?>

</div>
<?php
}

?>

Please check below link for Displaying a flash message after redirect in Codeigniter

Is it possible to force row level locking in SQL Server?

You can use the ROWLOCK hint, but AFAIK SQL may decide to escalate it if it runs low on resources

From the doco:

ROWLOCK Specifies that row locks are taken when page or table locks are ordinarily taken. When specified in transactions operating at the SNAPSHOT isolation level, row locks are not taken unless ROWLOCK is combined with other table hints that require locks, such as UPDLOCK and HOLDLOCK.

and

Lock hints ROWLOCK, UPDLOCK, AND XLOCK that acquire row-level locks may place locks on index keys rather than the actual data rows. For example, if a table has a nonclustered index, and a SELECT statement using a lock hint is handled by a covering index, a lock is acquired on the index key in the covering index rather than on the data row in the base table.

And finally this gives a pretty in-depth explanation about lock escalation in SQL Server 2005 which was changed in SQL Server 2008.

There is also, the very in depth: Locking in The Database Engine (in books online)

So, in general

UPDATE
Employees WITH (ROWLOCK)
SET Name='Mr Bean'
WHERE Age>93

Should be ok, but depending on the indexes and load on the server it may end up escalating to a page lock.

Declare and assign multiple string variables at the same time

Just a reminder: Implicit type var in multiple declaration is not allowed. There might be the following compilation errors.

var Foo = 0, Bar = 0;

Implicitly-typed variables cannot have multiple declarators

Similarly,

var Foo, Bar;

Implicitly-typed variables must be initialized

Oracle to_date, from mm/dd/yyyy to dd-mm-yyyy

You don't need to muck about with extracting parts of the date. Just cast it to a date using to_date and the format in which its stored, then cast that date to a char in the format you want. Like this:

select to_char(to_date('1/10/2011','mm/dd/yyyy'),'mm-dd-yyyy') from dual

How to embed small icon in UILabel

Try dragging a UIView onto the screen in IB. From there you can drag a UIImageView and UILabel into the view you just created. Set the image of the UIImageView in the properties inspector as the custom bullet image (which you will have to add to your project by dragging it into the navigation pane) and you can write some text in the label.

How do I set a cookie on HttpClient's HttpRequestMessage

For me the simple solution works to set cookies in HttpRequestMessage object.

protected async Task<HttpResponseMessage> SendRequest(HttpRequestMessage requestMessage, CancellationToken cancellationToken = default(CancellationToken))
{
    requestMessage.Headers.Add("Cookie", $"<Cookie Name 1>=<Cookie Value 1>;<Cookie Name 2>=<Cookie Value 2>");

    return await _httpClient.SendAsync(requestMessage, cancellationToken).ConfigureAwait(false);
}

OnItemClickListener using ArrayAdapter for ListView

Use OnItemClickListener

   ListView lv = getListView();
   lv.setOnItemClickListener(new OnItemClickListener()
   {
      @Override
      public void onItemClick(AdapterView<?> adapter, View v, int position,
            long arg3) 
      {
            String value = (String)adapter.getItemAtPosition(position); 
            // assuming string and if you want to get the value on click of list item
            // do what you intend to do on click of listview row
      }
   });

When you click on a row a listener is fired. So you setOnClickListener on the listview and use the annonymous inner class OnItemClickListener.

You also override onItemClick. The first param is a adapter. Second param is the view. third param is the position ( index of listview items).

Using the position you get the item .

Edit : From your comments i assume you need to set the adapter o listview

So assuming your activity extends ListActivtiy

     setListAdapter(adapter); 

Or if your activity class extends Activity

     ListView lv = (ListView) findViewById(R.id.listview1);
     //initialize adapter 
     lv.setAdapter(adapter); 

Sqlite primary key on multiple columns

Yes. But remember that such primary key allow NULL values in both columns multiple times.

Create a table as such:

    sqlite> CREATE TABLE something (
column1, column2, value, PRIMARY KEY (column1, column2));

Now this works without any warning:

sqlite> insert into something (value) VALUES ('bla-bla');
sqlite> insert into something (value) VALUES ('bla-bla');
sqlite> select * from something;
NULL|NULL|bla-bla
NULL|NULL|bla-bla

How to get a list of sub-folders and their files, ordered by folder-names

Command to put list of all files and folders into a text file is as below:

Eg: dir /b /s | sort > ListOfFilesFolders.txt

C# Clear Session

The other big difference is Abandon does not remove items immediately, but when it does then cleanup it does a loop over session items to check for STA COM objects it needs to handle specially. And this can be a problem.

Under high load it's possible for two (or more) requests to make it to the server for the same session (that is two requests with the same session cookie). Their execution will be serialized, but since Abandon doesn't clear out the items synchronously but rather sets a flag it's possible for both requests to run, and both requests to schedule a work item to clear out session "later". Both these work items can then run at the same time, and both are checking the session objects, and both are clearing out the array of objects, and what happens when you have two things iterating over a list and changing it?? Boom! And since this happens in a queueuserworkitem callback and is NOT done in a try/catch (thanks MS), it will bring down your entire app domain. Been there.

gpg: no valid OpenPGP data found

This problem might occur if you are behind corporate proxy and corporation uses its own certificate. Just add "--no-check-certificate" in the command. e.g. wget --no-check-certificate -qO - http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key | sudo apt-key add -

It works. If you want to see what is going on, you can use verbose command instead of quiet before adding "--no-check-certificate" option. e.g. wget -vO - http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key | sudo apt-key add - This will tell you to use "--no-check-certificate" if you are behind proxy.

Cannot use a leading ../ to exit above the top directory

You can use ~/img/myImage.png instead of ../img/myImage.png to avoid this error in ASP.NET pages.

matplotlib: colorbars and its text labels

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap

#discrete color scheme
cMap = ListedColormap(['white', 'green', 'blue','red'])

#data
np.random.seed(42)
data = np.random.rand(4, 4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=cMap)

#legend
cbar = plt.colorbar(heatmap)

cbar.ax.get_yaxis().set_ticks([])
for j, lab in enumerate(['$0$','$1$','$2$','$>3$']):
    cbar.ax.text(.5, (2 * j + 1) / 8.0, lab, ha='center', va='center')
cbar.ax.get_yaxis().labelpad = 15
cbar.ax.set_ylabel('# of contacts', rotation=270)


# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)
ax.invert_yaxis()

#labels
column_labels = list('ABCD')
row_labels = list('WXYZ')
ax.set_xticklabels(column_labels, minor=False)
ax.set_yticklabels(row_labels, minor=False)

plt.show()

You were very close. Once you have a reference to the color bar axis, you can do what ever you want to it, including putting text labels in the middle. You might want to play with the formatting to make it more visible.

demo

How to view file diff in git before commit

git difftool -d HEAD filename.txt

This shows a comparison using VI slit window in the terminal.

Count a list of cells with the same background color

Yes VBA is the way to go.

But, if you don't need to have a cell with formula that auto-counts/updates the number of cells with a particular colour, an alternative is simply to use the 'Find and Replace' function and format the cell to have the appropriate colour fill.

Hitting 'Find All' will give you the total number of cells found at the bottom left of the dialogue box.

enter image description here

This becomes especially useful if your search range is massive. The VBA script will be very slow but the 'Find and Replace' function will still be very quick.

How do you test a public/private DSA keypair?

I always compare an MD5 hash of the modulus using these commands:

Certificate: openssl x509 -noout -modulus -in server.crt | openssl md5
Private Key: openssl rsa -noout -modulus -in server.key | openssl md5
CSR: openssl req -noout -modulus -in server.csr | openssl md5

If the hashes match, then those two files go together.

How to modify a text file?

As mentioned by Adam you have to take your system limitations into consideration before you can decide on approach whether you have enough memory to read it all into memory replace parts of it and re-write it.

If you're dealing with a small file or have no memory issues this might help:

Option 1) Read entire file into memory, do a regex substitution on the entire or part of the line and replace it with that line plus the extra line. You will need to make sure that the 'middle line' is unique in the file or if you have timestamps on each line this should be pretty reliable.

# open file with r+b (allow write and binary mode)
f = open("file.log", 'r+b')   
# read entire content of file into memory
f_content = f.read()
# basically match middle line and replace it with itself and the extra line
f_content = re.sub(r'(middle line)', r'\1\nnew line', f_content)
# return pointer to top of file so we can re-write the content with replaced string
f.seek(0)
# clear file content 
f.truncate()
# re-write the content with the updated content
f.write(f_content)
# close file
f.close()

Option 2) Figure out middle line, and replace it with that line plus the extra line.

# open file with r+b (allow write and binary mode)
f = open("file.log" , 'r+b')   
# get array of lines
f_content = f.readlines()
# get middle line
middle_line = len(f_content)/2
# overwrite middle line
f_content[middle_line] += "\nnew line"
# return pointer to top of file so we can re-write the content with replaced string
f.seek(0)
# clear file content 
f.truncate()
# re-write the content with the updated content
f.write(''.join(f_content))
# close file
f.close()

How do I update the element at a certain position in an ArrayList?

Let arrList be the ArrayList and newValue the new String, then just do:

arrList.set(5, newValue);

This can be found in the java api reference here.

Address already in use: JVM_Bind

Your local port 443 / 8181 / 3820 is used.

If you are on linux/unix:

  • use netstat -an and lsof -n to check who is using this port

If you are on windows

  • use netstat -an and tcpview to check.

Switch statement: must default be the last case?

There are cases when you are converting ENUM to a string or converting string to enum in case where you are writing/reading to/from a file.

You sometimes need to make one of the values default to cover errors made by manually editing files.

switch(textureMode)
{
case ModeTiled:
default:
    // write to a file "tiled"
    break;

case ModeStretched:
    // write to a file "stretched"
    break;
}

Open Cygwin at a specific folder

When a fresh install is needed, I create a Windows "user environment variable " named HOME and assigns it the path of wherever "My Documents" reside.

The cygwin installer detects the HOME variable, automatically translates this into a cygpath and selects this it to be my ~ directory.

This has worked fine for every workstation I have used professionally the last 5 years (about 3 or 4, Win7). I have always been the only user on these machines, cannot say what the effect is.

Adding null values to arraylist

Yes, you can always use null instead of an object. Just be careful because some methods might throw error.

It would be 1.

also nulls would be factored in in the for loop, but you could use

 for(Item i : itemList) {
        if (i!= null) {
               //code here
        }
 }

Python - Module Not Found

you need to import the function so the program know what that is here is example:

import os 
import pyttsx3

i had the same problem first then i import the function and it work so i would really recommend to try it

How to ignore PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException?

If the issue is a missing intermediate certificate, you can enable Oracle JRE to automatically download the missing intermediate certificate as explained in this answer.

Just set the Java system property -Dcom.sun.security.enableAIAcaIssuers=true

For this to work the server's certificate must provide the URI to the intermediate certificate (the certificate's issuer). As far as I can tell, this is what browsers do as well and should be just as secure - I'm not a security expert though.

Edit: If I recall correctly, this seems to work at least with Java 8 and is documented here for Java 9.

How to place two divs next to each other?

My approach:

<div class="left">Left</div>
<div class="right">Right</div>

CSS:

.left {
    float: left;
    width: calc(100% - 200px);
    background: green;
}

.right {
    float: right;
    width: 200px;
    background: yellow;
}

php - How do I fix this illegal offset type error

I had a similar problem. As I got a Character from my XML child I had to convert it first to a String (or Integer, if you expect one). The following shows how I solved the problem.

foreach($xml->children() as $newInstr){
        $iInstrument = new Instrument($newInstr['id'],$newInstr->Naam,$newInstr->Key);
        $arrInstruments->offsetSet((String)$iInstrument->getID(), $iInstrument);
    }

Invoking JavaScript code in an iframe from the parent page

Some of these answers don't address the CORS issue, or don't make it obvious where you place the code snippets to make the communication possible.

Here is a concrete example. Say I want to click a button on the parent page, and have that do something inside the iframe. Here is how I would do it.

parent_frame.html

<button id='parent_page_button' onclick='call_button_inside_frame()'></button>

function call_button_inside_frame() {
   document.getElementById('my_iframe').contentWindow.postMessage('foo','*');
}

iframe_page.html

window.addEventListener("message", receiveMessage, false);

function receiveMessage(event)
    {
      if(event) {
        click_button_inside_frame();
    }
}

function click_button_inside_frame() {
   document.getElementById('frame_button').click();
}

To go the other direction (click button inside iframe to call method outside iframe) just switch where the code snippet live, and change this:

document.getElementById('my_iframe').contentWindow.postMessage('foo','*');

to this:

window.parent.postMessage('foo','*')

MySQL "Group By" and "Order By"

A simple solution is to wrap the query into a subselect with the ORDER statement first and applying the GROUP BY later:

SELECT * FROM ( 
    SELECT `timestamp`, `fromEmail`, `subject`
    FROM `incomingEmails` 
    ORDER BY `timestamp` DESC
) AS tmp_table GROUP BY LOWER(`fromEmail`)

This is similar to using the join but looks much nicer.

Using non-aggregate columns in a SELECT with a GROUP BY clause is non-standard. MySQL will generally return the values of the first row it finds and discard the rest. Any ORDER BY clauses will only apply to the returned column value, not to the discarded ones.

IMPORTANT UPDATE Selecting non-aggregate columns used to work in practice but should not be relied upon. Per the MySQL documentation "this is useful primarily when all values in each nonaggregated column not named in the GROUP BY are the same for each group. The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate."

As of 5.7.5 ONLY_FULL_GROUP_BY is enabled by default so non-aggregate columns cause query errors (ER_WRONG_FIELD_WITH_GROUP)

As @mikep points out below the solution is to use ANY_VALUE() from 5.7 and above

See http://www.cafewebmaster.com/mysql-order-sort-group https://dev.mysql.com/doc/refman/5.6/en/group-by-handling.html https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_any-value

set div height using jquery (stretch div height)

well you can do this:

$(function(){

    var $header = $('#header');
    var $footer = $('#footer');
    var $content = $('#content');
    var $window = $(window).on('resize', function(){
       var height = $(this).height() - $header.height() + $footer.height();
       $content.height(height);
    }).trigger('resize'); //on page load

});

see fiddle here: http://jsfiddle.net/maniator/JVKbR/
demo: http://jsfiddle.net/maniator/JVKbR/show/

How to download Visual Studio 2017 Community Edition for offline installation?

No, there should be an .exe file (vs_Community_xxxxx.exe) directly in you f:\vs2017c directory !

Just start from the this directory, not from a longer path. the packages downloaded are partly having very long path names, it fails if you start from a longer path.

@Scope("prototype") bean scope not creating new bean

Using ApplicationContextAware is tying you to Spring (which may or may not be an issue). I would recommend passing in a LoginActionFactory, which you can ask for a new instance of a LoginAction each time you need one.

How can I delete a user in linux when the system says its currently used in a process

First use pkill or kill -9 <pid> to kill the process.

Then use following userdel command to delete user,

userdel -f cafe_fixer

According to userdel man page:

-f, --force

This option forces the removal of the user account, even if the user is still logged in. It also forces userdel to remove the user's home directory and mail spool, even if another user uses the same home directory or if the mail spool is not owned by the specified user. If USERGROUPS_ENAB is defined to yes in /etc/login.defs and if a group exists with the same name as the deleted user, then this group will be removed, even if it is still the primary group of another user.

Edit 1: (by @Ajedi32)

Note: This option (i.e. --force) is dangerous and may leave your system in an inconsistent state.

Edit 2: (by @socketpair)

In spite of the description about some files, this key allows removing the user while it is in use. Don't forget to chdir / before, because this command will also remove home directory.

How can I get an HTTP response body as a string?

We can use the below code also to get the HTML Response in java

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.HttpResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.log4j.Logger;

public static void main(String[] args) throws Exception {
    HttpClient client = new DefaultHttpClient();
    //  args[0] :-  http://hostname:8080/abc/xyz/CheckResponse
    HttpGet request1 = new HttpGet(args[0]);
    HttpResponse response1 = client.execute(request1);
    int code = response1.getStatusLine().getStatusCode();

    try (BufferedReader br = new BufferedReader(new InputStreamReader((response1.getEntity().getContent())));) {
        // Read in all of the post results into a String.
        String output = "";
        Boolean keepGoing = true;
        while (keepGoing) {
            String currentLine = br.readLine();

            if (currentLine == null) {
                keepGoing = false;
            } else {
                output += currentLine;
            }
        }

        System.out.println("Response-->" + output);
    } catch (Exception e) {
        System.out.println("Exception" + e);

    }
}

Using multiple .cpp files in c++ program?

You can simply place a forward declaration of your second() function in your main.cpp above main(). If your second.cpp has more than one function and you want all of it in main(), put all the forward declarations of your functions in second.cpp into a header file and #include it in main.cpp.

Like this-

Second.h:

void second();
int third();
double fourth();

main.cpp:

#include <iostream>
#include "second.h"
int main()
{
    //.....
    return 0;
}

second.cpp:

void second()
{
    //...
}

int third()
{ 
    //...
    return foo;
}

double fourth()
{ 
    //...
    return f;
}

Note that: it is not necessary to #include "second.h" in second.cpp. All your compiler need is forward declarations and your linker will do the job of searching the definitions of those declarations in the other files.

contenteditable change events

The onchange event doesn't fires when an element with the contentEditable attribute is changed, a suggested approach could be to add a button, to "save" the edition.

Check this plugin which handles the issue in that way:

Bootstrap 3.0 Popovers and tooltips

You just need to enable the tooltip:

$('some id or class that you add to the above a tag').popover({
    trigger: "hover" 
})

How to convert a negative number to positive?

simply multiplying by -1 works in both ways ...

>>> -10 * -1
10
>>> 10 * -1
-10

How to Decrease Image Brightness in CSS

In short, place black behind the image, and lower the opactiy. You can do this by wrapping the image within a div, and then lowering the opacity of the image.

For example:

<!DOCTYPE html>

<style>
    .img-wrap {
        background: black;
        display: inline-block;
        line-height: 0;
    }
        .img-wrap > img {
            opacity: 0.8;
        }
</style>

<div class="img-wrap">
    <img src="http://mikecane.files.wordpress.com/2007/03/kitten.jpg" />
</div>

Here is a JSFiddle.

How to get a path to a resource in a Java JAR file

follow code!

/src/main/resources/file

streamToFile(getClass().getClassLoader().getResourceAsStream("file"))

public static File streamToFile(InputStream in) {
    if (in == null) {
        return null;
    }

    try {
        File f = File.createTempFile(String.valueOf(in.hashCode()), ".tmp");
        f.deleteOnExit();

        FileOutputStream out = new FileOutputStream(f);
        byte[] buffer = new byte[1024];

        int bytesRead;
        while ((bytesRead = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
        }

        return f;
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
        return null;
    }
}

What's the correct way to convert bytes to a hex string in Python 3?

import codecs
codecs.getencoder('hex_codec')(b'foo')[0]

works in Python 3.3 (so "hex_codec" instead of "hex").

Maximum concurrent connections to MySQL

I can assure you that raw speed ultimately lies in the non-standard use of Indexes for blazing speed using large tables.

Git 'fatal: Unable to write new index file'

If you have your github setup in some sort of online syncing service, such as google drive or dropbox, try disabling the syncing as the syncing service tries to read/write to the file as github tries to do the same, leading to github not working correctly.

IPython/Jupyter Problems saving notebook as PDF

For converting any Jupyter notebook to PDF, please follow the below instructions:

(Be inside Jupyter notebook):

On Mac OS:

command + P --> you will get a print dialog box --> change destination as PDF --> Click print

On Windows:

Ctrl + P --> you will get a print dialog box --> change destination as PDF --> Click print

If the above steps doesn't generate full PDF of the Jupyter notebook (probably because Chrome, some times, don't print all the outputs because Jupyter make a scroll for big outputs),

Try performing below steps for removing the auto scroll in the menu:-

Credits: @ÂngeloPolotto

  1. In your Jupyter Notebook, click Cell on top of the jupyter notebook enter image description here

  2. Next click All output --> Toggle scrolling for removing auto scroll.

enter image description here

Access index of last element in data frame

The former answer is now superseded by .iloc:

>>> df = pd.DataFrame({"date": range(10, 64, 8)})
>>> df.index += 17
>>> df
    date
17    10
18    18
19    26
20    34
21    42
22    50
23    58
>>> df["date"].iloc[0]
10
>>> df["date"].iloc[-1]
58

The shortest way I can think of uses .iget():

>>> df = pd.DataFrame({"date": range(10, 64, 8)})
>>> df.index += 17
>>> df
    date
17    10
18    18
19    26
20    34
21    42
22    50
23    58
>>> df['date'].iget(0)
10
>>> df['date'].iget(-1)
58

Alternatively:

>>> df['date'][df.index[0]]
10
>>> df['date'][df.index[-1]]
58

There's also .first_valid_index() and .last_valid_index(), but depending on whether or not you want to rule out NaNs they might not be what you want.

Remember that df.ix[0] doesn't give you the first, but the one indexed by 0. For example, in the above case, df.ix[0] would produce

>>> df.ix[0]
Traceback (most recent call last):
  File "<ipython-input-489-494245247e87>", line 1, in <module>
    df.ix[0]
[...]
KeyError: 0

Add/Delete table rows dynamically using JavaScript

This seems a lot cleaner than the answer above...

<script>
var maxID = 0;
function getTemplateRow() {
var x = document.getElementById("templateRow").cloneNode(true);
x.id = "";
x.style.display = "";
x.innerHTML = x.innerHTML.replace(/{id}/, ++maxID);
return x;
}
function addRow() {
var t = document.getElementById("theTable");
var rows = t.getElementsByTagName("tr");
var r = rows[rows.length - 1];
r.parentNode.insertBefore(getTemplateRow(), r);

}
</script>


<table id="theTable">
<tr>
<td>id</td>
<td>name</td>
</tr>
<tr id="templateRow" style="display:none">
<td>{id}</td>
<td><input /></td>
</tr>
</table>


<button onclick="addRow();">Go</button>

How many parameters are too many?

IMO, the justification for a long param list is that the data or context is dynamic in nature, think of printf(); a good example of using varargs. A better way to handle such cases is by passing a stream or xml structure, this again minimises the number of parameters.

A machine surely wouldn't mind a large number of arguments, but developers do, also think of the maintenance overhead, the number of unit test cases and validation checks. Designers also hate lengthy args list, more arguments mean more changes to interface definitions, whenever a change is to be done. The questions about the coupling/cohesion spring from above aspects.

How to convert string to char array in C++?

Well I know this maybe rather dumb than and simple, but I think it should work:

string n;
cin>> n;
char b[200];
for (int i = 0; i < sizeof(n); i++)
{
    b[i] = n[i];
    cout<< b[i]<< " ";
}

How to get full width in body element

You can use CSS to do it for example

<style>
html{
    width:100%;
    height:100%;
}
body{
    width:100%;
    height:100%;
    background-color:#DDD;
}
</style>

From io.Reader to string in Go

The most efficient way would be to always use []byte instead of string.

In case you need to print data received from the io.ReadCloser, the fmt package can handle []byte, but it isn't efficient because the fmt implementation will internally convert []byte to string. In order to avoid this conversion, you can implement the fmt.Formatter interface for a type like type ByteSlice []byte.

How to determine device screen size category (small, normal, large, xlarge) using code?

private String getDeviceDensity() {
    int density = mContext.getResources().getDisplayMetrics().densityDpi;
    switch (density)
    {
        case DisplayMetrics.DENSITY_MEDIUM:
            return "MDPI";
        case DisplayMetrics.DENSITY_HIGH:
            return "HDPI";
        case DisplayMetrics.DENSITY_LOW:
            return "LDPI";
        case DisplayMetrics.DENSITY_XHIGH:
            return "XHDPI";
        case DisplayMetrics.DENSITY_TV:
            return "TV";
        case DisplayMetrics.DENSITY_XXHIGH:
            return "XXHDPI";
        case DisplayMetrics.DENSITY_XXXHIGH:
            return "XXXHDPI";
        default:
            return "Unknown";
    }
}

While, Do While, For loops in Assembly Language (emu8086)

For-loops:

For-loop in C:

for(int x = 0; x<=3; x++)
{
    //Do something!
}

The same loop in 8086 assembler:

        xor cx,cx   ; cx-register is the counter, set to 0
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        inc cx      ; Increment
        cmp cx,3    ; Compare cx to the limit
        jle loop1   ; Loop while less or equal

That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:

        mov cx,4    ; 4 iterations
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        loop loop1  ; loop instruction decrements cx and jumps to label if not 0

If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction

times 4 nop

Do-while-loops

Do-while-loop in C:

int x=1;
do{
    //Do something!
}
while(x==1)

The same loop in assembler:

        mov ax,1
loop1   nop         ; Whatever you wanna do goes here
        cmp ax,1    ; Check wether cx is 1
        je loop1    ; And loop if equal

While-loops

While-loop in C:

while(x==1){
    //Do something
}

The same loop in assembler:

        jmp loop1   ; Jump to condition first
cloop1  nop         ; Execute the content of the loop
loop1   cmp ax,1    ; Check the condition
        je cloop1   ; Jump to content of the loop if met

For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.

Copy multiple files with Ansible

Or you can use with_items:

- copy:
    src: "{{ item }}"
    dest: /etc/fooapp/
    owner: root
    mode: 600
  with_items:
    - dest_dir

Python Requests library redirect new url

For python3.5, you can use the following code:

import urllib.request
res = urllib.request.urlopen(starturl)
finalurl = res.geturl()
print(finalurl)

Get current rowIndex of table in jQuery

Try this,

$('td').click(function(){
   var row_index = $(this).parent().index();
   var col_index = $(this).index();
});

If you need the index of table contain td then you can change it to

var row_index = $(this).parent('table').index(); 

FAIL - Application at context path /Hello could not be started

check web.xml file maybe servletContextlistener not doing well . in my case i added servletContextlistener and let him an empty and gave me the same error, i tried to delete it from project files but it still in web.xml file .finally i delete it from the web.xml and save the file . run the project and it stated successfully

Angular 6: How to set response type as text while making http call

By Default angular return responseType as Json, but we can configure below types according to your requirement.

responseType: 'arraybuffer'|'blob'|'json'|'text'

Ex:

this.http.post(
    'http://localhost:8080/order/addtocart', 
    { dealerId: 13, createdBy: "-1", productId, quantity }, 
    { headers, responseType: 'text'});

How to launch multiple Internet Explorer windows/tabs from batch file?

You can use either of these two scripts to open the URLs in separate tabs in a (single) new IE window. You can call either of these scripts from within your batch script (or at the command prompt):

JavaScript
Create a file with a name like: "urls.js":

var navOpenInNewWindow = 0x1;
var navOpenInNewTab = 0x800;
var navOpenInBackgroundTab = 0x1000;

var intLoop = 0;
var intArrUBound = 0;
var navFlags = navOpenInBackgroundTab;
var arrstrUrl = new Array(3);
var objIE;

    intArrUBound = arrstrUrl.length;

    arrstrUrl[0] = "http://bing.com/";
    arrstrUrl[1] = "http://google.com/";
    arrstrUrl[2] = "http://msn.com/";
    arrstrUrl[3] = "http://yahoo.com/";

    objIE = new ActiveXObject("InternetExplorer.Application");
    objIE.Navigate2(arrstrUrl[0]);

    for (intLoop=1;intLoop<=intArrUBound;intLoop++) {

        objIE.Navigate2(arrstrUrl[intLoop], navFlags);

    }

    objIE.Visible = true;
    objIE = null;


VB Script
Create a file with a name like: "urls.vbs":

Option Explicit

Const navOpenInNewWindow = &h1
Const navOpenInNewTab = &h800
Const navOpenInBackgroundTab = &h1000

Dim intLoop       : intLoop = 0
Dim intArrUBound  : intArrUBound = 0
Dim navFlags      : navFlags = navOpenInBackgroundTab

Dim arrstrUrl(3)
Dim objIE

    intArrUBound = UBound(arrstrUrl)

    arrstrUrl(0) = "http://bing.com/"
    arrstrUrl(1) = "http://google.com/"
    arrstrUrl(2) = "http://msn.com/"
    arrstrUrl(3) = "http://yahoo.com/"

    set objIE = CreateObject("InternetExplorer.Application")
    objIE.Navigate2 arrstrUrl(0)

    For intLoop = 1 to intArrUBound

        objIE.Navigate2 arrstrUrl(intLoop), navFlags

    Next

    objIE.Visible = True
    set objIE = Nothing


Once you decide on "JavaScript" or "VB Script", you have a few choices:

If your URLs are static:

1) You could write the "JS/VBS" script file (above) and then just call it from a batch script.

From within the batch script (or command prompt), call the "JS/VBS" script like this:

cscript //nologo urls.vbs
cscript //nologo urls.js


If the URLs change infrequently:

2) You could have the batch script write the "JS/VBS" script on the fly and then call it.


If the URLs could be different each time:

3) Use the "JS/VBS" scripts (below) and pass the URLs of the pages to open as command line arguments:

JavaScript
Create a file with a name like: "urls.js":

var navOpenInNewWindow = 0x1;
var navOpenInNewTab = 0x800;
var navOpenInBackgroundTab = 0x1000;

var intLoop = 0;
var navFlags = navOpenInBackgroundTab;
var objIE;
var intArgsLength = WScript.Arguments.Length;

    if (intArgsLength == 0) {

        WScript.Echo("Missing parameters");
        WScript.Quit(1);

    }

    objIE = new ActiveXObject("InternetExplorer.Application");
    objIE.Navigate2(WScript.Arguments(0));

    for (intLoop=1;intLoop<intArgsLength;intLoop++) {

        objIE.Navigate2(WScript.Arguments(intLoop), navFlags);

    }

    objIE.Visible = true;
    objIE = null;


VB Script
Create a file with a name like: "urls.vbs":

Option Explicit

Const navOpenInNewWindow = &h1
Const navOpenInNewTab = &h800
Const navOpenInBackgroundTab = &h1000

Dim intLoop
Dim navFlags      : navFlags = navOpenInBackgroundTab
Dim objIE

    If WScript.Arguments.Count = 0 Then

        WScript.Echo "Missing parameters"
        WScript.Quit(1)

    End If

    set objIE = CreateObject("InternetExplorer.Application")
    objIE.Navigate2 WScript.Arguments(0)

    For intLoop = 1 to (WScript.Arguments.Count-1)

        objIE.Navigate2 WScript.Arguments(intLoop), navFlags

    Next

    objIE.Visible = True
    set objIE = Nothing


If the script is called without any parameters, these will return %errorlevel%=1, otherwise they will return %errorlevel%=0. No checking is done regarding the "validity" or "availability" of any of the URLs.


From within the batch script (or command prompt), call the "JS/VBS" script like this:

cscript //nologo urls.js "http://bing.com/" "http://google.com/" "http://msn.com/" "http://yahoo.com/"
cscript //nologo urls.vbs "http://bing.com/" "http://google.com/" "http://msn.com/" "http://yahoo.com/"

OR even:

cscript //nologo urls.js "bing.com" "google.com" "msn.com" "yahoo.com"
cscript //nologo urls.vbs "bing.com" "google.com" "msn.com" "yahoo.com"


If for some reason, you wanted to run these with "wscript" instead, remember to use "start /w" so the exit codes (%errorlevel%) will be returned to your batch script:

start /w "" wscript //nologo urls.js "url1" "url2" ...
start /w "" wscript //nologo urls.vbs "url1" "url2" ...


Edit: 21-Sep-2016

There has been a comment that my solution is too complicated. I disagree. You pick the JavaScript solution, or the VB Script solution (not both), and each is only about 10 lines of actual code (less if you eliminate the error checking/reporting), plus a few lines to initialize constants and variables.

Once you have decided (JS or VB), you write that script one time, and then you call that script from batch, passing the URLs, anytime you want to use it, like:

cscript //nologo urls.vbs "bing.com" "google.com" "msn.com" "yahoo.com"

The reason I wrote this answer, is because all the other answers, which work for some people, will fail to work for others, depending on:

  1. The current Internet Explorer settings for "open popups in a new tab", "open in current/new window/tab", etc... Assuming you already have those setting set how you like them for general browsing, most people would find it undesirable to have change those settings back and forth in order to make the script work.
  2. Their behavior is (can be) inconsistent depending on whether or not there was an IE window already open before the "new" links were opened. If there was an IE window (perhaps with many open tabs) already open, then all the new tabs would be added there as well. This might not be desired.

The solution I provided doesn't have these issues and should behave the same, regardless of any IE Settings or any existing IE Windows. (Please let me know if I'm wrong about this and I'll try to address it.)

Best way to get user GPS location in background in Android

You can archive it with a Service and Alarm Manager, but be careful with this, because if you setup a high priority you gonna drain the battery of the phone, in other hand, you really need notify the location every minute? This is because the only way to see a considerably change of the user location, it's traveling in a car or train. I only ask, because that gonna depend of you app and the requirement of the tracking.

How to get a value from a cell of a dataframe?

df_gdp.columns

Index([u'Country', u'Country Code', u'Indicator Name', u'Indicator Code', u'1960', u'1961', u'1962', u'1963', u'1964', u'1965', u'1966', u'1967', u'1968', u'1969', u'1970', u'1971', u'1972', u'1973', u'1974', u'1975', u'1976', u'1977', u'1978', u'1979', u'1980', u'1981', u'1982', u'1983', u'1984', u'1985', u'1986', u'1987', u'1988', u'1989', u'1990', u'1991', u'1992', u'1993', u'1994', u'1995', u'1996', u'1997', u'1998', u'1999', u'2000', u'2001', u'2002', u'2003', u'2004', u'2005', u'2006', u'2007', u'2008', u'2009', u'2010', u'2011', u'2012', u'2013', u'2014', u'2015', u'2016'], dtype='object')

df_gdp[df_gdp["Country Code"] == "USA"]["1996"].values[0]

8100000000000.0

Change event on select with knockout binding, how can I know if it is a real change?

I had a similar problem and I just modified the event handler to check the type of the variable. The type is only set after the user selects a value, not when the page is first loaded.

self.permissionChanged = function (l) {
    if (typeof l != 'undefined') {
        ...
    }
}

This seems to work for me.

Display Images Inline via CSS

The code you have posted here and code on your site both are different. There is a break <br> after second image, so the third image into new line, remove this <br> and it will display correctly.

How do you reindex an array in PHP but with indexes starting from 1?

Similar to Nick's contribution, I came to the same solution for reindexing an array, but enhanced the function a little since from PHP version 5.4, it doesn't work because of passing variables by reference. Example reindexing function is then like this using use keyword closure:

function indexArrayByElement($array, $element)
{
    $arrayReindexed = [];
    array_walk(
        $array,
        function ($item, $key) use (&$arrayReindexed, $element) {
            $arrayReindexed[$item[$element]] = $item;
        }
    );
    return $arrayReindexed;
}

Adding two Java 8 streams, or an extra element to a stream

Just do:

Stream.of(stream1, stream2, Stream.of(element)).flatMap(identity());

where identity() is a static import of Function.identity().

Concatenating multiple streams into one stream is the same as flattening a stream.

However, unfortunately, for some reason there is no flatten() method on Stream, so you have to use flatMap() with the identity function.

How can I get the username of the logged-in user in Django?

You can use the request object to find the logged in user

def my_view(request):
    username = None
    if request.user.is_authenticated():
        username = request.user.username

According to https://docs.djangoproject.com/en/2.0/releases/1.10/

In version Django 2.0 the syntax has changed to

request.user.is_authenticated

Git merge is not possible because I have unmerged files

Another potential cause for this (Intellij was involved in my case, not sure that mattered though): trying to merge in changes from a main branch into a branch off of a feature branch.

In other words, merging "main" into "current" in the following arrangement:

main
  |
  --feature
      |
      --current

I resolved all conflicts and GiT reported unmerged files and I was stuck until I merged from main into feature, then feature into current.

Composer - the requested PHP extension mbstring is missing from your system

I set the PHPRC variable and uncommented zend_extension=php_opcache.dll in php.ini and all works well.

CSS Float: Floating an image to the left of the text

Just need to float both elements left:

.post-container{
    margin: 20px 20px 0 0;  
    border:5px solid #333;
}

.post-thumb img {
    float: left;
}

.post-content {
    float: left;
}

Edit: actually, you do not need the width, just float both left

Cloning git repo causes error - Host key verification failed. fatal: The remote end hung up unexpectedly

The issue could be that Github isn't present in your ~/.ssh/known_hosts file.

Append GitHub to the list of authorized hosts:

ssh-keyscan -H github.com >> ~/.ssh/known_hosts

An exception of type 'System.NullReferenceException' occurred in myproject.DLL but was not handled in user code

It means you have a null reference somewhere in there. Can you debug the app and stop the debugger when it gets here and investigate? Probably img1 is null or ConfigurationManager.AppSettings.Get("Url") is returning null.

How do I disable and re-enable a button in with javascript?

<script>
function checkusers()
{
   var shouldEnable = document.getElementById('checkbox').value == 0;
   document.getElementById('add_button').disabled = shouldEnable;
}
</script>

keyword not supported data source

What you have is a valid ADO.NET connection string - but it's NOT a valid Entity Framework connection string.

The EF connection string would look something like this:

<connectionStrings> 
  <add name="NorthwindEntities" connectionString=
     "metadata=.\Northwind.csdl|.\Northwind.ssdl|.\Northwind.msl;
      provider=System.Data.SqlClient;
      provider connection string=&quot;Data Source=SERVER\SQL2000;Initial Catalog=Northwind;Integrated Security=True;MultipleActiveResultSets=False&quot;" 
      providerName="System.Data.EntityClient" /> 
</connectionStrings>

You're missing all the metadata= and providerName= elements in your EF connection string...... you basically only have what's contained in the provider connection string part.

Using the EDMX designer should create a valid EF connection string for you, in your web.config or app.config.

Marc

UPDATE: OK, I understand what you're trying to do: you need a second "ADO.NET" connection string just for ASP.NET user / membership database. Your string is OK, but the providerName is wrong - it would have to be "System.Data.SqlClient" - this connection doesn't use ENtity Framework - don't specify the "EntityClient" for it then!

<add name="ASPNETMembership" 
     connectionString="Data Source=MONTGOMERY-DEV\SQLEXPRESS;Initial Catalog=ASPNETDB;Integrated Security=True;" 
     providerName="System.Data.SqlClient" />

If you specify providerName=System.Data.EntityClient ==> Entity Framework connection string (with the metadata= and everything).

If you need and specify providerName=System.Data.SqlClient ==> straight ADO.NET SQL Server connection string without all the EF additions

C# - How to get Program Files (x86) on Windows 64 bit

The function below will return the x86 Program Files directory in all of these three Windows configurations:

  • 32 bit Windows
  • 32 bit program running on 64 bit Windows
  • 64 bit program running on 64 bit windows

 

static string ProgramFilesx86()
{
    if( 8 == IntPtr.Size 
        || (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432"))))
    {
        return Environment.GetEnvironmentVariable("ProgramFiles(x86)");
    }

    return Environment.GetEnvironmentVariable("ProgramFiles");
}

How to make a <ul> display in a horizontal row

It will work for you:

#ul_top_hypers li {
    display: inline-block;
}

How can I plot separate Pandas DataFrames as subplots?

Building on @joris response above, if you have already established a reference to the subplot, you can use the reference as well. For example,

ax1 = plt.subplot2grid((50,100), (0, 0), colspan=20, rowspan=10)
...

df.plot.barh(ax=ax1, stacked=True)

How to do Base64 encoding in node.js?

I have created a ultimate small js npm library for the base64 encode/decode conversion in Node.js.

Installation

npm install nodejs-base64-converter --save

Usage

var nodeBase64 = require('nodejs-base64-converter');

console.log(nodeBase64.encode("test text")); //dGVzdCB0ZXh0
console.log(nodeBase64.decode("dGVzdCB0ZXh0")); //test text

Convert a String to int?

You can use the FromStr trait's from_str method, which is implemented for i32:

let my_num = i32::from_str("9").unwrap_or(0);

What exactly are iterator, iterable, and iteration?

Here's the explanation I use in teaching Python classes:

An ITERABLE is:

  • anything that can be looped over (i.e. you can loop over a string or file) or
  • anything that can appear on the right-side of a for-loop: for x in iterable: ... or
  • anything you can call with iter() that will return an ITERATOR: iter(obj) or
  • an object that defines __iter__ that returns a fresh ITERATOR, or it may have a __getitem__ method suitable for indexed lookup.

An ITERATOR is an object:

  • with state that remembers where it is during iteration,
  • with a __next__ method that:
    • returns the next value in the iteration
    • updates the state to point at the next value
    • signals when it is done by raising StopIteration
  • and that is self-iterable (meaning that it has an __iter__ method that returns self).

Notes:

  • The __next__ method in Python 3 is spelt next in Python 2, and
  • The builtin function next() calls that method on the object passed to it.

For example:

>>> s = 'cat'      # s is an ITERABLE
                   # s is a str object that is immutable
                   # s has no state
                   # s has a __getitem__() method 

>>> t = iter(s)    # t is an ITERATOR
                   # t has state (it starts by pointing at the "c"
                   # t has a next() method and an __iter__() method

>>> next(t)        # the next() function returns the next value and advances the state
'c'
>>> next(t)        # the next() function returns the next value and advances
'a'
>>> next(t)        # the next() function returns the next value and advances
't'
>>> next(t)        # next() raises StopIteration to signal that iteration is complete
Traceback (most recent call last):
...
StopIteration

>>> iter(t) is t   # the iterator is self-iterable

error: Libtool library used but 'LIBTOOL' is undefined

A good answer for me was to install libtool:

sudo apt-get install libtool

Is there any use for unique_ptr with array?

If you need a dynamic array of objects that are not copy-constructible, then a smart pointer to an array is the way to go. For example, what if you need an array of atomics.

MVC4 Passing model from view to controller

I hope this complete example will help you.

This is the TaxiInfo class which holds information about a taxi ride:

namespace Taxi.Models
{
    public class TaxiInfo
    {
        public String Driver { get; set; }
        public Double Fare { get; set; }
        public Double Distance { get; set; }
        public String StartLocation { get; set; }
        public String EndLocation { get; set; }
    }
}

We also have a convenience model which holds a List of TaxiInfo(s):

namespace Taxi.Models
{
    public class TaxiInfoSet
    {
        public List<TaxiInfo> TaxiInfoList { get; set; }

        public TaxiInfoSet(params TaxiInfo[] TaxiInfos)
        {
            TaxiInfoList = new List<TaxiInfo>();

            foreach(var TaxiInfo in TaxiInfos)
            {
                TaxiInfoList.Add(TaxiInfo);
            }
        }
    }
}

Now in the home controller we have the default Index action which for this example makes two taxi drivers and adds them to the list contained in a TaxiInfo:

public ActionResult Index()
{
    var taxi1 = new TaxiInfo() { Fare = 20.2, Distance = 15, Driver = "Billy", StartLocation = "Perth", EndLocation = "Brisbane" };
    var taxi2 = new TaxiInfo() { Fare = 2339.2, Distance = 1500, Driver = "Smith", StartLocation = "Perth", EndLocation = "America" };

    return View(new TaxiInfoSet(taxi1,taxi2));
}

The code for the view is as follows:

@model Taxi.Models.TaxiInfoSet
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@foreach(var TaxiInfo in Model.TaxiInfoList){
    <form>
        <h1>Cost: [email protected]</h1>
        <h2>Distance: @(TaxiInfo.Distance) km</h2>
        <p>
            Our diver, @TaxiInfo.Driver will take you from @TaxiInfo.StartLocation to @TaxiInfo.EndLocation
        </p>
        @Html.ActionLink("Home","Booking",TaxiInfo)
    </form>
}

The ActionLink is responsible for the re-directing to the booking action of the Home controller (and passing in the appropriate TaxiInfo object) which is defiend as follows:

    public ActionResult Booking(TaxiInfo Taxi)
    {
        return View(Taxi);
    }

This returns a the following view:

@model Taxi.Models.TaxiInfo

@{
    ViewBag.Title = "Booking";
}

<h2>Booking For</h2>
<h1>@Model.Driver, going from @Model.StartLocation to @Model.EndLocation (a total of @Model.Distance km) for [email protected]</h1>

A visual tour:

The Index view

The Booking view

'Static readonly' vs. 'const'

There is one important question, that is not mentioned anywhere in the above answers, and should drive you to prefer "const" especially for basic types like "int", "string" etc.

Constants can be used as Attribute parameters, static readonly field not!

Azure functions HttpTrigger, not using HttpMethods class in attribute

If only microsoft used constants for Http's GET, POST, DELETE etc.

It would be possible to write

[HttpTrigger(AuthorizationLeve.Anonymous,  HttpMethods.Get)] // COMPILE ERROR: static readonly, 

But instead I have to resort to

[HttpTrigger(AuthorizationLeve.Anonymous,  "GET")] // STRING

Or use my own constant:

public class HttpConstants
{
    public const string Get = "GET";
}

[HttpTrigger(AuthorizationLeve.Anonymous,  HttpConstants.Get)] // Compile FINE!

Is there any way to redraw tmux window when switching smaller monitor to bigger one?

A simpler solution on recent versions of tmux (tested on 1.9) you can now do :

tmux detach -a

-a is for all other client on this session except the current one

You can alias it in your .[bash|zsh]rc

alias takeover="tmux detach -a"

Workflow: You can connect to your session normally, and if you are bothered by another session that forced down your tmux window size you can simply call takeover.

How To Show And Hide Input Fields Based On Radio Button Selection

***This will work.........
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
 window.onload = function() {
    document.getElementById('ifYes').style.display = 'none';
    document.getElementById('ifNo').style.display = 'none';
}
function yesnoCheck() {
    if (document.getElementById('yesCheck').checked) {
        document.getElementById('ifYes').style.display = 'block';
        document.getElementById('ifNo').style.display = 'none';
        document.getElementById('redhat1').style.display = 'none';
        document.getElementById('aix1').style.display = 'none';
    } 
    else if(document.getElementById('noCheck').checked) {
        document.getElementById('ifNo').style.display = 'block';
        document.getElementById('ifYes').style.display = 'none';
        document.getElementById('redhat1').style.display = 'none';
        document.getElementById('aix1').style.display = 'none';
   }
}
function yesnoCheck1() {
   if(document.getElementById('redhat').checked) {
       document.getElementById('redhat1').style.display = 'block';
       document.getElementById('aix1').style.display = 'none';
    }
   if(document.getElementById('aix').checked) {
       document.getElementById('aix1').style.display = 'block';
       document.getElementById('redhat1').style.display = 'none';
    }
}
</script>
</head>
<body>
Select os :<br>
windows
<input type="radio" onclick="javascript:yesnoCheck();" name="yesno" id="yesCheck"/>Unix
<input type="radio" onclick="javascript:yesnoCheck();" name="yesno" id="noCheck"/>
<br>
<div id="ifYes" style="display:none">
Windows 2008<input type="radio" name="win" value="2008"/>
Windows 2012<input type="radio" name="win" value="2012"/>
</div>
<div id="ifNo" style="display:none">
Red Hat<input type="radio" name="unix" onclick="javascript:yesnoCheck1();"value="2008" 

id="redhat"/>
AIX<input type="radio" name="unix" onclick="javascript:yesnoCheck1();"  
value="2012" id="aix"/>
</div>
<div id="redhat1" style="display:none">
Red Hat 6.0<input type="radio" name="redhat" value="2008" id="redhat6.0"/>
Red Hat 6.1<input type="radio" name="redhat" value="2012" id="redhat6.1"/>
</div>
<div id="aix1" style="display:none">
aix 6.0<input type="radio" name="aix" value="2008" id="aix6.0"/>
aix 6.1<input type="radio" name="aix" value="2012" id="aix6.1"/
</div>
</body> 
</html>***

How to position a Bootstrap popover?

This works. Tested.

.popover {
    top: 71px !important;
    left: 379px !important;
}

How to open the default webbrowser using java

on windows invoke "cmd /k start http://www.example.com" Infact you can always invoke "default" programs using the start command. For ex start abc.mp3 will invoke the default mp3 player and load the requested mp3 file.

Set NA to 0 in R

You can just use the output of is.na to replace directly with subsetting:

bothbeams.data[is.na(bothbeams.data)] <- 0

Or with a reproducible example:

dfr <- data.frame(x=c(1:3,NA),y=c(NA,4:6))
dfr[is.na(dfr)] <- 0
dfr
  x y
1 1 0
2 2 4
3 3 5
4 0 6

However, be careful using this method on a data frame containing factors that also have missing values:

> d <- data.frame(x = c(NA,2,3),y = c("a",NA,"c"))
> d[is.na(d)] <- 0
Warning message:
In `[<-.factor`(`*tmp*`, thisvar, value = 0) :
  invalid factor level, NA generated

It "works":

> d
  x    y
1 0    a
2 2 <NA>
3 3    c

...but you likely will want to specifically alter only the numeric columns in this case, rather than the whole data frame. See, eg, the answer below using dplyr::mutate_if.

How to delete or add column in SQLITE?

This answer to a different question is oriented toward modifying a column, but I believe a portion of the answer could also yield a useful approach if you have lots of columns and don't want to retype most of them by hand for your INSERT statement:

https://stackoverflow.com/a/10385666

You could dump your database as described in the link above, then grab the "create table" statement and an "insert" template from that dump, then follow the instructions in the SQLite FAQ entry "How do I add or delete columns from an existing table in SQLite." (FAQ is linked elsewhere on this page.)

Using port number in Windows host file

-You can use any free address in the network 127.0.0.0/8 , in my case needed this for python flask and this is what I have done : add this line in the hosts file (you can find it is windows under : C:\Windows\System32\drivers\etc ) :

127.0.0.5 flask.dev
  • Make sure the port is the default port "80" in my case this is what in the python flask: app.run("127.0.0.5","80")

  • now run your code and browse flask.dev

Chrome not rendering SVG referenced via <img> tag

Content type in the HTTP header from the server was the problem for me. I have a node.js server, added:

if( pageName.substring(pageName.lastIndexOf('.')) == '.svg' ) {
  res.writeHead(200, { "Content-Type": "image/svg+xml" });
}

pageName is my local variable for what is requested.

My guess is this is a common problem! Am using the current version of Chrome (Mar 2020).

How Do I Get the Query Builder to Output Its Raw SQL Query as a String?

Print last query

DB::enableQueryLog();

$query        = DB::getQueryLog();
$lastQuery    = end($query);
print_r($lastQuery);

python pip: force install ignoring dependencies

pip has a --no-dependencies switch. You should use that.

For more information, run pip install -h, where you'll see this line:

--no-deps, --no-dependencies
                        Ignore package dependencies

How to check if a process is running via a batch script

You should check the parent process name, see The Code Project article about a .NET based solution**.

A non-programmatic way to check:

  1. Launch Cmd.exe
  2. Launch an application (for instance, c:\windows\notepad.exe)
  3. Check properties of the Notepad.exe process in Process Explorer
  4. Check for parent process (This shows cmd.exe)

The same can be checked by getting the parent process name.

How can I check if two segments intersect?

Here's a solution using dot products:

# assumes line segments are stored in the format [(x0,y0),(x1,y1)]
def intersects(s0,s1):
    dx0 = s0[1][0]-s0[0][0]
    dx1 = s1[1][0]-s1[0][0]
    dy0 = s0[1][1]-s0[0][1]
    dy1 = s1[1][1]-s1[0][1]
    p0 = dy1*(s1[1][0]-s0[0][0]) - dx1*(s1[1][1]-s0[0][1])
    p1 = dy1*(s1[1][0]-s0[1][0]) - dx1*(s1[1][1]-s0[1][1])
    p2 = dy0*(s0[1][0]-s1[0][0]) - dx0*(s0[1][1]-s1[0][1])
    p3 = dy0*(s0[1][0]-s1[1][0]) - dx0*(s0[1][1]-s1[1][1])
    return (p0*p1<=0) & (p2*p3<=0)

Here's a visualization in Desmos: Line Segment Intersection

"Integer number too large" error message for 600851475143

600851475143 cannot be represented as a 32-bit integer (type int). It can be represented as a 64-bit integer (type long). long literals in Java end with an "L": 600851475143L

Transfer data from one database to another database

For those on Azure, follow these modified instructions from Virus:

  1. Open SSMS.
  2. Right-click the Database you wish to copy data from.
  3. Select Generate Scripts >> Select Specific Database Objects >> Choose the tables/object you wish to transfer. strong text
  4. In the "Save to file" pane, click Advanced
  5. Set "Types of data to script" to Schema and data
  6. Set "Script DROP and CREATE" to Script DROP and CREATE
  7. Under "Table/View Options" set relevant items to TRUE. Though I recommend setting all to TRUE just in case. You can always modify the script after it generates.
  8. Set filepath >> Next >> Next
  9. Open newly created SQL file. Remove "Use" from top of file.
  10. Open new query window on destination database, paste script contents (without using) and execute.

Foreach with JSONArray and JSONObject

Make sure you are using this org.json: https://mvnrepository.com/artifact/org.json/json

if you are using Java 8 then you can use

import org.json.JSONArray;
import org.json.JSONObject;

JSONArray array = ...;

array.forEach(item -> {
    JSONObject obj = (JSONObject) item;
    parse(obj);
});

Just added a simple test to prove that it works:

Add the following dependency into your pom.xml file (To prove that it works, I have used the old jar which was there when I have posted this answer)

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

And the simple test code snippet will be:

import org.json.JSONArray;
import org.json.JSONObject;

public class Test {
    public static void main(String args[]) {
        JSONArray array = new JSONArray();

        JSONObject object = new JSONObject();
        object.put("key1", "value1");

        array.put(object);

        array.forEach(item -> {
            System.out.println(item.toString());
        });
    }
}

output:

{"key1":"value1"}

'POCO' definition

"Plain Old C# Object"

Just a normal class, no attributes describing infrastructure concerns or other responsibilities that your domain objects shouldn't have.

EDIT - as other answers have stated, it is technically "Plain Old CLR Object" but I, like David Arno comments, prefer "Plain Old Class Object" to avoid ties to specific languages or technologies.

TO CLARIFY: In other words, they don’t derive from some special base class, nor do they return any special types for their properties.

See below for an example of each.

Example of a POCO:

public class Person
{
    public string Name { get; set; }

    public int Age { get; set; }
}

Example of something that isn’t a POCO:

public class PersonComponent : System.ComponentModel.Component
{
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    public string Name { get; set; }

    public int Age { get; set; }
}

The example above both inherits from a special class to give it additional behavior as well as uses a custom attribute to change behavior… the same properties exist on both classes, but one is not just a plain old object anymore.

SQL Error: ORA-00942 table or view does not exist

Either the user doesn't have privileges needed to see the table, the table doesn't exist or you are running the query in the wrong schema

Does the table exist?

    select owner, 
           object_name 
    from dba_objects 
    where object_name = any ('CUSTOMER','customer');

What privileges did you grant?

    grant select, insert on customer to user;

Are you running the query against the owner from the first query?

How do I delete files programmatically on Android?

I see you've found your answer, however it didn't work for me. Delete kept returning false, so I tried the following and it worked (For anybody else for whom the chosen answer didn't work):

System.out.println(new File(path).getAbsoluteFile().delete());

The System out can be ignored obviously, I put it for convenience of confirming the deletion.

How to remove undefined and null values from an object using lodash?

I like using _.pickBy, because you have full control over what you are removing:

var person = {"name":"bill","age":21,"sex":undefined,"height":null};

var cleanPerson = _.pickBy(person, function(value, key) {
  return !(value === undefined || value === null);
});

Source: https://www.codegrepper.com/?search_term=lodash+remove+undefined+values+from+object

CSS Calc Viewport Units Workaround?

Doing this with a CSS Grid is pretty easy. The trick is to set the grid's height to 100vw, then assign one of the rows to 75vw, and the remaining one (optional) to 1fr. This gives you, from what I assume is what you're after, a ratio-locked resizing container.

Example here: https://codesandbox.io/s/21r4z95p7j

You can even utilize the bottom gutter space if you so choose, simply by adding another "item".

Edit: StackOverflow's built-in code runner has some side effects. Pop over to the codesandbox link and you'll see the ratio in action.

_x000D_
_x000D_
body {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  background-color: #334;_x000D_
  color: #eee;_x000D_
}_x000D_
_x000D_
.main {_x000D_
  min-height: 100vh;_x000D_
  min-width: 100vw;_x000D_
  display: grid;_x000D_
  grid-template-columns: 100%;_x000D_
  grid-template-rows: 75vw 1fr;_x000D_
}_x000D_
_x000D_
.item {_x000D_
  background-color: #558;_x000D_
  padding: 2px;_x000D_
  margin: 1px;_x000D_
}_x000D_
_x000D_
.item.dead {_x000D_
  background-color: transparent;_x000D_
}
_x000D_
<html>_x000D_
  <head>_x000D_
    <title>Parcel Sandbox</title>_x000D_
    <meta charset="UTF-8" />_x000D_
    <link rel="stylesheet" href="src/index.css" />_x000D_
  </head>_x000D_
_x000D_
  <body>_x000D_
    <div id="app">_x000D_
      <div class="main">_x000D_
        <div class="item">Item 1</div>_x000D_
        <!-- <div class="item dead">Item 2 (dead area)</div> -->_x000D_
      </div>_x000D_
    </div>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to get domain URL and application name?

If you are being passed a url as a String and want to extract the context root of that application, you can use this regex to extract it. It will work for full urls or relative urls that begin with the context root.

url.replaceAll("^(.*\\/\\/)?.*?\\/(.+?)\\/.*|\\/(.+)$", "$2$3")

How to write a test which expects an Error to be thrown in Jasmine?

For anyone who still might be facing this issue, for me the posted solution didn't work and it kept on throwing this error: Error: Expected function to throw an exception. I later realised that the function which I was expecting to throw an error was an async function and was expecting promise to be rejected and then throw error and that's what I was doing in my code:

throw new Error('REQUEST ID NOT FOUND');

and thats what I did in my test and it worked:

it('Test should throw error if request not found', willResolve(() => {
         const promise = service.getRequestStatus('request-id');
                return expectToReject(promise).then((err) => {
                    expect(err.message).toEqual('REQUEST NOT FOUND');
                });
            }));

Detect HTTP or HTTPS then force HTTPS in JavaScript

Not a Javascript way to answer this but if you use CloudFlare you can write page rules that redirect the user much faster to HTTPS and it's free. Looks like this in CloudFlare's Page Rules:

enter image description here

How to select rows with no matching entry in another table?

You can do something like this

   SELECT IFNULL(`price`.`fPrice`,100) as fPrice,product.ProductId,ProductName 
          FROM `products` left join `price` ON 
          price.ProductId=product.ProductId AND (GeoFancingId=1 OR GeoFancingId 
          IS NULL) WHERE Status="Active" AND Delete="No"

How to check compiler log in sql developer?

I can also use

show errors;

In sql worksheet.

How do I make a semi transparent background?

If you want to make transparent background is gray, pls try:

   .transparent{
       background:rgba(1,1,1,0.5);
   }

How to take off line numbers in Vi?

For turning off line numbers, any of these commands will work:

  1. :set nu!
  2. :set nonu
  3. :set number!
  4. :set nonumber

Understanding the set() function

Sets are unordered, as you say. Even though one way to implement sets is using a tree, they can also be implemented using a hash table (meaning getting the keys in sorted order may not be that trivial).

If you'd like to sort them, you can simply perform:

sorted(set(y))

which will produce a sorted list containing the set's elements. (Not a set. Again, sets are unordered.)

Otherwise, the only thing guaranteed by set is that it makes the elements unique (nothing will be there more than once).

Hope this helps!

How can I scroll to a specific location on the page using jquery?

Yep, even in plain JavaScript it's pretty easy. You give an element an id and then you can use that as a "bookmark":

<div id="here">here</div>

If you want it to scroll there when a user clicks a link, you can just use the tried-and-true method:

<a href="#here">scroll to over there</a>

To do it programmatically, use scrollIntoView()

document.getElementById("here").scrollIntoView()

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

You need to set

WindowStyle="None", AllowsTransparency="True" and optionally ResizeMode="NoResize"
and then set the Style property of the window to your custom window style, where you design the appearance of the window (title bar, buttons, border) to anything you want and display the window contents in a ContentPresenter.

This seems to be a good article on how you can achieve this, but there are many other articles on the internet.

How to redraw DataTable with new data

You have to first clear the table and then add new data using row.add() function. At last step adjust also column size so that table renders correctly.

$('#upload-new-data').on('click', function () {
   datatable.clear().draw();
   datatable.rows.add(NewlyCreatedData); // Add new data
   datatable.columns.adjust().draw(); // Redraw the DataTable
});

Also if you want to find a mapping between old and new datatable API functions bookmark this

Simple calculations for working with lat/lon and km distance?

If you're using Java, Javascript or PHP, then there's a library that will do these calculations exactly, using some amusingly complicated (but still fast) trigonometry:

http://www.jstott.me.uk/jcoord/

How to pass prepareForSegue: an object

In Swift 4.2 I would do something like that:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let yourVC = segue.destination as? YourViewController {
        yourVC.yourData = self.someData
    }
}

About .bash_profile, .bashrc, and where should alias be written in?

Check out http://mywiki.wooledge.org/DotFiles for an excellent resource on the topic aside from man bash.

Summary:

  • You only log in once, and that's when ~/.bash_profile or ~/.profile is read and executed. Since everything you run from your login shell inherits the login shell's environment, you should put all your environment variables in there. Like LESS, PATH, MANPATH, LC_*, ... For an example, see: My .profile
  • Once you log in, you can run several more shells. Imagine logging in, running X, and in X starting a few terminals with bash shells. That means your login shell started X, which inherited your login shell's environment variables, which started your terminals, which started your non-login bash shells. Your environment variables were passed along in the whole chain, so your non-login shells don't need to load them anymore. Non-login shells only execute ~/.bashrc, not /.profile or ~/.bash_profile, for this exact reason, so in there define everything that only applies to bash. That's functions, aliases, bash-only variables like HISTSIZE (this is not an environment variable, don't export it!), shell options with set and shopt, etc. For an example, see: My .bashrc
  • Now, as part of UNIX peculiarity, a login-shell does NOT execute ~/.bashrc but only ~/.profile or ~/.bash_profile, so you should source that one manually from the latter. You'll see me do that in my ~/.profile too: source ~/.bashrc.

vba pass a group of cells as range to function

As written, your function accepts only two ranges as arguments.

To allow for a variable number of ranges to be used in the function, you need to declare a ParamArray variant array in your argument list. Then, you can process each of the ranges in the array in turn.

For example,

Function myAdd(Arg1 As Range, ParamArray Args2() As Variant) As Double
    Dim elem As Variant
    Dim i As Long
    For Each elem In Arg1
        myAdd = myAdd + elem.Value
    Next elem
    For i = LBound(Args2) To UBound(Args2)
        For Each elem In Args2(i)
            myAdd = myAdd + elem.Value
        Next elem
    Next i
End Function

This function could then be used in the worksheet to add multiple ranges.

myAdd usage

For your function, there is the question of which of the ranges (or cells) that can passed to the function are 'Sessions' and which are 'Customers'.

The easiest case to deal with would be if you decided that the first range is Sessions and any subsequent ranges are Customers.

Function calculateIt(Sessions As Range, ParamArray Customers() As Variant) As Double
    'This function accepts a single Sessions range and one or more Customers
    'ranges
    Dim i As Long
    Dim sessElem As Variant
    Dim custElem As Variant
    For Each sessElem In Sessions
        'do something with sessElem.Value, the value of each
        'cell in the single range Sessions
        Debug.Print "sessElem: " & sessElem.Value
    Next sessElem
    'loop through each of the one or more ranges in Customers()
    For i = LBound(Customers) To UBound(Customers)
        'loop through the cells in the range Customers(i)
        For Each custElem In Customers(i)
            'do something with custElem.Value, the value of
            'each cell in the range Customers(i)
            Debug.Print "custElem: " & custElem.Value
         Next custElem
    Next i
End Function

If you want to include any number of Sessions ranges and any number of Customers range, then you will have to include an argument that will tell the function so that it can separate the Sessions ranges from the Customers range.

This argument could be set up as the first, numeric, argument to the function that would identify how many of the following arguments are Sessions ranges, with the remaining arguments implicitly being Customers ranges. The function's signature would then be:

Function calculateIt(numOfSessionRanges, ParamAray Args() As Variant)

Or it could be a "guard" argument that separates the Sessions ranges from the Customers ranges. Then, your code would have to test each argument to see if it was the guard. The function would look like:

Function calculateIt(ParamArray Args() As Variant)

Perhaps with a call something like:

calculateIt(sessRange1,sessRange2,...,"|",custRange1,custRange2,...)

The program logic might then be along the lines of:

Function calculateIt(ParamArray Args() As Variant) As Double
   ...
   'loop through Args
   IsSessionArg = True
   For i = lbound(Args) to UBound(Args)
       'only need to check for the type of the argument
       If TypeName(Args(i)) = "String" Then
          IsSessionArg = False
       ElseIf IsSessionArg Then
          'process Args(i) as Session range
       Else
          'process Args(i) as Customer range
       End if
   Next i
   calculateIt = <somevalue>
End Function

Cut Java String at a number of character

StringUtils.abbreviate("abcdefg", 6);

This will give you the following result: abc...

Where 6 is the needed length, and "abcdefg" is the string that needs to be abbrevieted.

Failed to resolve: com.google.firebase:firebase-core:9.0.0

If all the above methods are not working then change implementation 'com.google.firebase:firebase-core:12.0.0' to implementation 'com.google.firebase:firebase-core:10.0.0' in your app level build.gradle file. This would surely work.

Using C# regular expressions to remove HTML tags

I would like to echo Jason's response though sometimes you need to naively parse some Html and pull out the text content.

I needed to do this with some Html which had been created by a rich text editor, always fun and games.

In this case you may need to remove the content of some tags as well as just the tags themselves.

In my case and tags were thrown into this mix. Some one may find my (very slightly) less naive implementation a useful starting point.

   /// <summary>
    /// Removes all html tags from string and leaves only plain text
    /// Removes content of <xml></xml> and <style></style> tags as aim to get text content not markup /meta data.
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public static string HtmlStrip(this string input)
    {
        input = Regex.Replace(input, "<style>(.|\n)*?</style>",string.Empty);
        input = Regex.Replace(input, @"<xml>(.|\n)*?</xml>", string.Empty); // remove all <xml></xml> tags and anything inbetween.  
        return Regex.Replace(input, @"<(.|\n)*?>", string.Empty); // remove any tags but not there content "<p>bob<span> johnson</span></p>" becomes "bob johnson"
    }

how to call a function from another function in Jquery

I think in this case you want something like this:

$(window).resize(resize=function resize(){ some code...}

Now u can call resize() within some other nested functions:

$(window).scroll(function(){ resize();}

Algorithm for solving Sudoku

a short attempt to achieve same algorithm using backtracking:

def solve(sudoku):
    #using recursion and backtracking, here we go.
    empties = [(i,j) for i in range(9) for j in range(9) if sudoku[i][j] == 0]
    predict = lambda i, j: set(range(1,10))-set([sudoku[i][j]])-set([sudoku[y+range(1,10,3)[i//3]][x+range(1,10,3)[j//3]] for y in (-1,0,1) for x in (-1,0,1)])-set(sudoku[i])-set(list(zip(*sudoku))[j])
    if len(empties)==0:return True
    gap = next(iter(empties))
    predictions = predict(*gap)
    for i in predictions:
        sudoku[gap[0]][gap[1]] = i
        if solve(sudoku):return True
        sudoku[gap[0]][gap[1]] = 0
    return False

Is it possible to log all HTTP request headers with Apache?

In my case easiest way to get browser headers was to use php. It appends headers to file and prints them to test page.

<?php
$fp = fopen('m:/temp/requests.txt', 'a');
$time = $_SERVER['REQUEST_TIME'];
fwrite($fp, $time  "\n");
echo "$time.<br>";
foreach (getallheaders() as $name => $value) {
    $cur_hd = "$name: $value\n";
    fwrite($fp, $cur_hd);
    echo "$cur_hd.<br>";
}
fwrite($fp, "***\n");
fclose($fp);
?>

How to make image hover in css?

Hi you should give parent position relative and child absolute and give to height or width to absolute class as like this

Css

  .nkhome{
    margin-left:260px;
    width:59px;
    height:59px;
    margin-top:170px;
    position:relative;
    z-index:0;
}
.nkhome a:hover img{
    opacity:0.0;
}
.nkhome a:hover{
  background:url('http://www.prelovac.com/vladimir/wp-content/uploads/2008/03/example.jpg');
    width:100px;
    height:100px;
    position:absolute;
    top:0;
    z-index:1;

}

HTML

 <div class="nkhome">
        <a href="Home.html"><img src="http://dummyimage.com/100/000/fff.jpg" /></a>
    </div>
?

Live demo http://jsfiddle.net/t5FEX/7/


or this

<div class="nkhome">
        <a href="Home.html"><img src="http://dummyimage.com/100/000/fff.jpg" onmouseover="this.src='http://www.prelovac.com/vladimir/wp-content/uploads/2008/03/example.jpg'" 
            onmouseout="this.src='http://dummyimage.com/100/000/fff.jpg'"
            /></a>
    </div>?

Live demo http://jsfiddle.net/t5FEX/9/

Use YAML with variables

This is how I was able to configure yaml files to refer to variable.

I have values.yaml where we have root level fields which are used as template variables inside values.yaml

values.yaml

.....  
databaseUserPropName: spring.datasource.username  
databaseUserName: sa  
.....  
secrets:
    type: Opaque  
    name: dbservice-secrets  
    data:  
      - name: "{{ .Values.databaseUserPropName }}"  
        value: "{{ .Values.databaseUserName }}"  
.....

When referencing these values in secret.yaml, we would use tpl function using syntax {{ tpl TEMPLATE_STRING VALUES }}

secret.yaml

when using inside range i:e iteration

  {{ range .Values.deployments.secrets.data }}
    {{ tpl .name $ }}: "{{ tpl .value $ }}"
  {{ end }}

when directly referring as variable

  {{ tpl .Values.deployments.secrets.data.name . }}
  {{ tpl .Values.deployments.secrets.data.value . }}

$ - this is global variable and will always point to the root context . - this variable will point to the root context based on where it used.

Is it possible to change a UIButtons background color?

Another possibility (the best and most beautiful imho):

Create a UISegmentedControl with 2 segments in the required background color in Interface Builder. Set the type to 'bar'. Then, change it to having only one segment. Interface builder does not accept one segment so you have to do that programmatically.

Therefore, create an IBOutlet for this button and add this to the viewDidLoad of your view:

[segmentedButton removeSegmentAtIndex:1 animated:NO];

Now you have a beautiful glossy, colored button with the specified background color. For actions, use the 'value changed' event.

(I have found this on http://chris-software.com/index.php/2009/05/13/creating-a-nice-glass-buttons/). Thanks Chris!