Programs & Examples On #Assertions

Assertion is a method of verifying, if the code works as it was designed to. For instance, after reading an XML file, the result should contain exactly one root node. Failed assertion means, that program is in an unstable state and usually in such case its execution is terminated.

Java/ JUnit - AssertTrue vs AssertFalse

I think it's just for your convenience (and the readers of your code)

Your code, and your unit tests should be ideally self documenting which this API helps with,

Think abt what is more clear to read:

AssertTrue(!(a > 3));

or

AssertFalse(a > 3);

When you open your tests after xx months when your tests suddenly fail, it would take you much less time to understand what went wrong in the second case (my opinion). If you disagree, you can always stick with AssertTrue for all cases :)

Comparing arrays in JUnit assertions, concise built-in way?

I prefer to convert arrays to strings:

Assert.assertEquals(
                Arrays.toString(values),
                Arrays.toString(new int[] { 7, 8, 9, 3 }));

this way I can see clearly where wrong values are. This works effectively only for small sized arrays, but I rarely use arrays with more items than 7 in my unit tests.

This method works for primitive types and for other types when overload of toString returns all essential information.

Cycles in family tree software

Genealogical data is cyclic and does not fit into an acyclic graph, so if you have assertions against cycles you should remove them.

The way to handle this in a view without creating a custom view is to treat the cyclic parent as a "ghost" parent. In other words, when a person is both a father and a grandfather to the same person, then the grandfather node is shown normally, but the father node is rendered as a "ghost" node that has a simple label like ("see grandfather") and points to the grandfather.

In order to do calculations you may need to improve your logic to handle cyclic graphs so that a node is not visited more than once if there is a cycle.

What does the Java assert keyword do, and when should it be used?

Let's assume that you are supposed to write a program to control a nuclear power-plant. It is pretty obvious that even the most minor mistake could have catastrophic results, therefore your code has to be bug-free (assuming that the JVM is bug-free for the sake of the argument).

Java is not a verifiable language, which means: you cannot calculate that the result of your operation will be perfect. The main reason for this are pointers: they can point anywhere or nowhere, therefore they cannot be calculated to be of this exact value, at least not within a reasonable span of code. Given this problem, there is no way to prove that your code is correct at a whole. But what you can do is to prove that you at least find every bug when it happens.

This idea is based on the Design-by-Contract (DbC) paradigm: you first define (with mathematical precision) what your method is supposed to do, and then verify this by testing it during actual execution. Example:

// Calculates the sum of a (int) + b (int) and returns the result (int).
int sum(int a, int b) {
  return a + b;
}

While this is pretty obvious to work fine, most programmers will not see the hidden bug inside this one (hint: the Ariane V crashed because of a similar bug). Now DbC defines that you must always check the input and output of a function to verify that it worked correctly. Java can do this through assertions:

// Calculates the sum of a (int) + b (int) and returns the result (int).
int sum(int a, int b) {
    assert (Integer.MAX_VALUE - a >= b) : "Value of " + a + " + " + b + " is too large to add.";
  final int result = a + b;
    assert (result - a == b) : "Sum of " + a + " + " + b + " returned wrong sum " + result;
  return result;
}

Should this function now ever fail, you will notice it. You will know that there is a problem in your code, you know where it is and you know what caused it (similar to Exceptions). And what is even more important: you stop executing right when it happens to prevent any further code to work with wrong values and potentially cause damage to whatever it controls.

Java Exceptions are a similar concept, but they fail to verify everything. If you want even more checks (at the cost of execution speed) you need to use assertions. Doing so will bloat your code, but you can in the end deliver a product at a surprisingly short development time (the earlier you fix a bug, the lower the cost). And in addition: if there is any bug inside your code, you will detect it. There is no way of a bug slipping-through and cause issues later.

This still is not a guarantee for bug-free code, but it is much closer to that, than usual programs.

Add jars to a Spark Job - spark-submit

There is restriction on using --jars: if you want to specify a directory for location of jar/xml file, it doesn't allow directory expansions. This means if you need to specify absolute path for each jar.

If you specify --driver-class-path and you are executing in yarn cluster mode, then driver class doesn't get updated. We can verify if class path is updated or not under spark ui or spark history server under tab environment.

Option which worked for me to pass jars which contain directory expansions and which worked in yarn cluster mode was --conf option. It's better to pass driver and executor class paths as --conf, which adds them to spark session object itself and those paths are reflected on Spark Configuration. But Please make sure to put jars on the same path across the cluster.

spark-submit \
  --master yarn \
  --queue spark_queue \
  --deploy-mode cluster    \
  --num-executors 12 \
  --executor-memory 4g \
  --driver-memory 8g \
  --executor-cores 4 \
  --conf spark.ui.enabled=False \
  --conf spark.driver.extraClassPath=/usr/hdp/current/hbase-master/lib/hbase-server.jar:/usr/hdp/current/hbase-master/lib/hbase-common.jar:/usr/hdp/current/hbase-master/lib/hbase-client.jar:/usr/hdp/current/hbase-master/lib/zookeeper.jar:/usr/hdp/current/hbase-master/lib/hbase-protocol.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/scopt_2.11-3.3.0.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/spark-examples_2.10-1.1.0.jar:/etc/hbase/conf \
  --conf spark.hadoop.mapred.output.dir=/tmp \
  --conf spark.executor.extraClassPath=/usr/hdp/current/hbase-master/lib/hbase-server.jar:/usr/hdp/current/hbase-master/lib/hbase-common.jar:/usr/hdp/current/hbase-master/lib/hbase-client.jar:/usr/hdp/current/hbase-master/lib/zookeeper.jar:/usr/hdp/current/hbase-master/lib/hbase-protocol.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/scopt_2.11-3.3.0.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/spark-examples_2.10-1.1.0.jar:/etc/hbase/conf \
  --conf spark.hadoop.mapreduce.output.fileoutputformat.outputdir=/tmp

How to read line by line of a text area HTML tag

Two options: no JQuery required, or JQuery version

No JQuery (or anything else required)

var textArea = document.getElementById('myTextAreaId');
var lines = textArea.value.split('\n');    // lines is an array of strings

// Loop through all lines
for (var j = 0; j < lines.length; j++) {
  console.log('Line ' + j + ' is ' + lines[j])
}

JQuery version

var lines = $('#myTextAreaId').val().split('\n');   // lines is an array of strings

// Loop through all lines
for (var j = 0; j < lines.length; j++) {
  console.log('Line ' + j + ' is ' + lines[j])
}

Side note, if you prefer forEach a sample loop is

lines.forEach(function(line) {
  console.log('Line is ' + line)
})

Script to kill all connections to a database (More than RESTRICTED_USER ROLLBACK)

You can use Cursor like that:

USE master
GO

DECLARE @SQL AS VARCHAR(255)
DECLARE @SPID AS SMALLINT
DECLARE @Database AS VARCHAR(500)
SET @Database = 'AdventureWorks2016CTP3'

DECLARE Murderer CURSOR FOR
SELECT spid FROM sys.sysprocesses WHERE DB_NAME(dbid) = @Database

OPEN Murderer

FETCH NEXT FROM Murderer INTO @SPID
WHILE @@FETCH_STATUS = 0

    BEGIN
    SET @SQL = 'Kill ' + CAST(@SPID AS VARCHAR(10)) + ';'
    EXEC (@SQL)
    PRINT  ' Process ' + CAST(@SPID AS VARCHAR(10)) +' has been killed'
    FETCH NEXT FROM Murderer INTO @SPID
    END 

CLOSE Murderer
DEALLOCATE Murderer

I wrote about that in my blog here: http://www.pigeonsql.com/single-post/2016/12/13/Kill-all-connections-on-DB-by-Cursor

What causes "Unable to access jarfile" error?

I finally pasted my jar file into the same folder as my JDK so I didn't have to include the paths. I also had to open the command prompt as an admin.

  1. Right click Command Prompt and "Run as administrator"
  2. Navigate to the directory where you saved your jdk to
  3. In the command prompt type: java.exe -jar <jar file name>.jar

What are some reasons for jquery .focus() not working?

This solved!!!

setTimeout(function(){
    $("#name").filter(':visible').focus();
}, 500);

You can adjust time accordingly.

How to access a preexisting collection with Mongoose?

Mongoose added the ability to specify the collection name under the schema, or as the third argument when declaring the model. Otherwise it will use the pluralized version given by the name you map to the model.

Try something like the following, either schema-mapped:

new Schema({ url: String, text: String, id: Number}, 
           { collection : 'question' });   // collection name

or model mapped:

mongoose.model('Question', 
               new Schema({ url: String, text: String, id: Number}), 
               'question');     // collection name

Eclipse projects not showing up after placing project files in workspace/projects

Even I had also observed the similar problem. I had closed my eclipse project because of some reason and on restart some of my file added were not visible in explorer even though corresponding file were existing.

Following solution worked for me: Select whole workspace (Ctrl+A) ==> Righ click and press Refresh.

Creating table variable in SQL server 2008 R2

@tableName Table variables are alive for duration of the script running only i.e. they are only session level objects.

To test this, open two query editor windows under sql server management studio, and create table variables with same name but different structures. You will get an idea. The @tableName object is thus temporary and used for our internal processing of data, and it doesn't contribute to the actual database structure.

There is another type of table object which can be created for temporary use. They are #tableName objects declared like similar create statement for physical tables:

Create table #test (Id int, Name varchar(50))

This table object is created and stored in temp database. Unlike the first one, this object is more useful, can store large data and takes part in transactions etc. These tables are alive till the connection is open. You have to drop the created object by following script before re-creating it.

IF OBJECT_ID('tempdb..#test') IS NOT NULL
  DROP TABLE #test 

Hope this makes sense !

Viewing full version tree in git

You can try the following:

gitk --all

You can tell gitk what to display using anything that git rev-list understands, so if you just want a few branches, you can do:

gitk master origin/master origin/experiment

... or more exotic things like:

gitk --simplify-by-decoration --all

MVC Return Partial View as JSON

You can extract the html string from the PartialViewResult object, similar to the answer to this thread:

Render a view as a string

PartialViewResult and ViewResult both derive from ViewResultBase, so the same method should work on both.

Using the code from the thread above, you would be able to use:

public ActionResult ReturnSpecialJsonIfInvalid(AwesomenessModel model)
{
    if (ModelState.IsValid)
    {
        if(Request.IsAjaxRequest())
            return PartialView("NotEvil", model);
        return View(model)
    }
    if(Request.IsAjaxRequest())
    {
        return Json(new { error = true, message = RenderViewToString(PartialView("Evil", model))});
    }
    return View(model);
}

Add a new item to recyclerview programmatically?

First add your item to mItems and then use:

mAdapter.notifyItemInserted(mItems.size() - 1);

this method is better than using:

mAdapter.notifyDataSetChanged();

in performance.

How do I concatenate strings in Swift?

You can concatenate strings a number of ways:

let a = "Hello"
let b = "World"

let first = a + ", " + b
let second = "\(a), \(b)"

You could also do:

var c = "Hello"
c += ", World"

I'm sure there are more ways too.

Bit of description

let creates a constant. (sort of like an NSString). You can't change its value once you have set it. You can still add it to other things and create new variables though.

var creates a variable. (sort of like NSMutableString) so you can change the value of it. But this has been answered several times on Stack Overflow, (see difference between let and var).

Note

In reality let and var are very different from NSString and NSMutableString but it helps the analogy.

Forcing a postback

By using Server.Transfer("YourCurrentPage.aspx"); we can easily acheive this and it is better than Response.Redirect(); coz Server.Transfer() will save you the round trip.

Mailto on submit button

The full list of possible fields in the html based email-creating form:

  • subject
  • cc
  • bcc
  • body
<form action="mailto:[email protected]" method="GET">
  <input name="subject" type="text" /></br>
  <input name="cc" type="email" /><br />
  <input name="bcc" type="email" /><br />
  <textarea name="body"></textarea><br />
  <input type="submit" value="Send" />
</form>

https://codepen.io/garfunkel61/pen/oYGNGp

Best XML Parser for PHP

I would have to say SimpleXML takes the cake because it is firstly an extension, written in C, and is very fast. But second, the parsed document takes the form of a PHP object. So you can "query" like $root->myElement.

Java out.println() how is this possible?

You will have to create an object out first. More about this here:

    // write to stdout
    out = System.out;
    out.println("Test 1");
    out.close();

How to set the margin or padding as percentage of height of parent container?

Other way to center one line text is:

.parent{
  position: relative;
}

.child{
   position: absolute;
   top: 50%;
   line-height: 0;
}

or just

.parent{
  overflow: hidden; /* if this ins't here the parent will adopt the 50% margin of the child */
}

.child{
   margin-top: 50%;
   line-height: 0;
}

'innerText' works in IE, but not in Firefox

myElement.innerText = myElement.textContent = "foo";

Edit (thanks to Mark Amery for the comment below): Only do it this way if you know beyond a reasonable doubt that no code will be relying on checking the existence of these properties, like (for example) jQuery does. But if you are using jQuery, you would probably just use the "text" function and do $('#myElement').text('foo') as some other answers show.

AngularJS event on window innerWidth size change

If Khanh TO's solution caused UI issues for you (like it did for me) try using $timeout to not update the attribute until it has been unchanged for 500ms.

var oldWidth = window.innerWidth;
$(window).on('resize.doResize', function () {
    var newWidth = window.innerWidth,
        updateStuffTimer;

    if (newWidth !== oldWidth) {
        $timeout.cancel(updateStuffTimer);
    }

    updateStuffTimer = $timeout(function() {
         updateStuff(newWidth); // Update the attribute based on window.innerWidth
    }, 500);
});

$scope.$on('$destroy',function (){
    $(window).off('resize.doResize'); // remove the handler added earlier
});

Reference: https://gist.github.com/tommaitland/7579618

Foreach Control in form, how can I do something to all the TextBoxes in my Form?

foreach (Control X in this.Controls)
{
  if (X is TextBox)
  {
    (X as TextBox).Text = string.Empty;
  }
}

CSS I want a div to be on top of everything

You need to add position:relative; to the menu. Z-index only works when you have a non static positioning scheme.

Adding a custom header to HTTP request using angular.js

Basic authentication using HTTP POST method:

$http({
    method: 'POST',
    url: '/API/authenticate',
    data: 'username=' + username + '&password=' + password + '&email=' + email,
    headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        "X-Login-Ajax-call": 'true'
    }
}).then(function(response) {
    if (response.data == 'ok') {
        // success
    } else {
        // failed
    }
});

...and GET method call with header:

$http({
    method: 'GET',
    url: '/books',
    headers: {
        'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
        'Accept': 'application/json',
        "X-Login-Ajax-call": 'true'
    }
}).then(function(response) {
    if (response.data == 'ok') {
        // success
    } else {
        // failed
    }
});

Rails: How can I rename a database column in a Ruby on Rails migration?

Just generate migration using command

rails g migration rename_hased_password

After that edit the migration add following line in change method

rename_column :table, :hased_password, :hashed_password

This should do the trick.

Missing artifact com.oracle:ojdbc6:jar:11.2.0 in pom.xml

Due to Oracle license restriction, there are no public repositories that provide ojdbc jar.

You need to download it and install in your local repository. Get jar from Oracle and install it in your local maven repository using

mvn install:install-file -Dfile={path/to/your/ojdbc.jar} -DgroupId=com.oracle 
-DartifactId=ojdbc6 -Dversion=11.2.0 -Dpackaging=jar

If you are using ojdbc7, here is the link

Change hash without reload in jQuery

You can simply assign it a new value as follows,

window.location.hash

Stored procedure - return identity as output parameter or scalar

Its all depend on your client data access-layer. Many ORM frameworks rely on explicitly querying the SCOPE_IDENTITY during the insert operation.

If you are in complete control over the data access layer then is arguably better to return SCOPE_IDENTITY() as an output parameter. Wrapping the return in a result set adds unnecessary meta data overhead to describe the result set, and complicates the code to process the requests result.

If you prefer a result set return, then again is arguable better to use the OUTPUT clause:

INSERT INTO  MyTable (col1, col2, col3)
OUTPUT INSERTED.id, col1, col2, col3
VALUES (@col1, @col2, @col3);

This way you can get the entire inserted row back, including default and computed columns, and you get a result set containing one row for each row inserted, this working correctly with set oriented batch inserts.

Overall, I can't see a single case when returning SCOPE_IDENTITY() as a result set would be a good practice.

SQLite with encryption/password protection

SQLite has hooks built-in for encryption which are not used in the normal distribution, but here are a few implementations I know of:

  • SEE - The official implementation.
  • wxSQLite - A wxWidgets style C++ wrapper that also implements SQLite's encryption.
  • SQLCipher - Uses openSSL's libcrypto to implement.
  • SQLiteCrypt - Custom implementation, modified API.
  • botansqlite3 - botansqlite3 is an encryption codec for SQLite3 that can use any algorithms in Botan for encryption.
  • sqleet - another encryption implementation, using ChaCha20/Poly1305 primitives. Note that wxSQLite mentioned above can use this as a crypto provider.

The SEE and SQLiteCrypt require the purchase of a license.

Disclosure: I created botansqlite3.

delete a column with awk or sed

If you're open to a Perl solution...

perl -ane 'print "$F[0] $F[1]\n"' file

These command-line options are used:

  • -n loop around every line of the input file, do not automatically print every line

  • -a autosplit mode – split input lines into the @F array. Defaults to splitting on whitespace

  • -e execute the following perl code

How can you flush a write using a file descriptor?

You have two choices:

  1. Use fileno() to obtain the file descriptor associated with the stdio stream pointer

  2. Don't use <stdio.h> at all, that way you don't need to worry about flush either - all writes will go to the device immediately, and for character devices the write() call won't even return until the lower-level IO has completed (in theory).

For device-level IO I'd say it's pretty unusual to use stdio. I'd strongly recommend using the lower-level open(), read() and write() functions instead (based on your later reply):

int fd = open("/dev/i2c", O_RDWR);
ioctl(fd, IOCTL_COMMAND, args);
write(fd, buf, length);

Triggering change detection manually in Angular

I used accepted answer reference and would like to put an example, since Angular 2 documentation is very very hard to read, I hope this is easier:

  1. Import NgZone:

    import { Component, NgZone } from '@angular/core';
    
  2. Add it to your class constructor

    constructor(public zone: NgZone, ...args){}
    
  3. Run code with zone.run:

    this.zone.run(() => this.donations = donations)
    

PHP function overloading

In PHP 5.6 you can use the splat operator ... as the last parameter and do away with func_get_args() and func_num_args():

function example(...$args)
{
   count($args); // Equivalent to func_num_args()
}

example(1, 2);
example(1, 2, 3, 4, 5, 6, 7);

You can use it to unpack arguments as well:

$args[] = 1;
$args[] = 2;
$args[] = 3;
example(...$args);

Is equivalent to:

example(1, 2, 3);

Unresolved external symbol on static class members

If you are using C++ 17 you can just use the inline specifier (see https://stackoverflow.com/a/11711082/55721)


If using older versions of the C++ standard, you must add the definitions to match your declarations of X and Y

unsigned char test::X;
unsigned char test::Y;

somewhere. You might want to also initialize a static member

unsigned char test::X = 4;

and again, you do that in the definition (usually in a CXX file) not in the declaration (which is often in a .H file)

Bootstrap combining rows (rowspan)

Paul's answer seems to defeat the purpose of bootstrap; that of being responsive to the viewport / screen size.

By nesting rows and columns you can achieve the same result, while retaining responsiveness.

Here is an up-to-date response to this problem;

_x000D_
_x000D_
<div class="container-fluid">_x000D_
  <h1>  Responsive Nested Bootstrap </h1> _x000D_
  <div class="row">_x000D_
    <div class="col-md-5" style="background-color:red;">Span 5</div>_x000D_
    <div class="col-md-3" style="background-color:blue;">Span 3</div>_x000D_
    <div class="col-md-2">_x000D_
      <div class="row">_x000D_
        <div class="container" style="background-color:green;">Span 2</div>_x000D_
      </div>_x000D_
      <div class="row">_x000D_
        <div class="container" style="background-color:purple;">Span 2</div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="col-md-2" style="background-color:yellow;">Span 2</div>_x000D_
  </div>_x000D_
  _x000D_
  <div class="row">_x000D_
    <div class="col-md-6">_x000D_
      <div class="row">_x000D_
        <div class="container" style="background-color:yellow;">Span 6</div>_x000D_
      </div>_x000D_
      <div class="row">_x000D_
        <div class="container" style="background-color:green;">Span 6</div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="col-md-6" style="background-color:red;">Span 6</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can view the codepen here.

difference between primary key and unique key

difference between Primary Key and Unique Key

Both Primary key and Unique Key are used to uniquely define of a row in a table. Primary Key creates a clustered index of the column whereas a Unique creates an unclustered index of the column.

A Primary Key doesn’t allow NULL value, however a Unique Key does allow one NULL value.

Parsing XML with namespace in Python via 'ElementTree'

ElementTree is not too smart about namespaces. You need to give the .find(), findall() and iterfind() methods an explicit namespace dictionary. This is not documented very well:

namespaces = {'owl': 'http://www.w3.org/2002/07/owl#'} # add more as needed

root.findall('owl:Class', namespaces)

Prefixes are only looked up in the namespaces parameter you pass in. This means you can use any namespace prefix you like; the API splits off the owl: part, looks up the corresponding namespace URL in the namespaces dictionary, then changes the search to look for the XPath expression {http://www.w3.org/2002/07/owl}Class instead. You can use the same syntax yourself too of course:

root.findall('{http://www.w3.org/2002/07/owl#}Class')

If you can switch to the lxml library things are better; that library supports the same ElementTree API, but collects namespaces for you in a .nsmap attribute on elements.

How can I autoplay a video using the new embed code style for Youtube?

The only way I was able to get autoplay to work was to use the iframe player api.

<div id="ytplayer"></div>
<script>
// Load the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// Replace the 'ytplayer' element with an <iframe> and
// YouTube player after the API code downloads.
var player;
function onYouTubePlayerAPIReady() {
    player = new YT.Player('ytplayer', {
        height: '480',
        width: '853',
        videoId: 'JW5meKfy3fY',
        playerVars: {
            'autoplay': 1,
            'showinfo': 0,
            'controls': 0
        }
    });
}
</script>

How can I pass an argument to a PowerShell script?

Call the script from a batch file (*.bat) or CMD

PowerShell Core

pwsh.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 -Param1 Hello -Param2 World"

pwsh.exe -NoLogo -ExecutionPolicy Bypass -Command "path-to-script/Script.ps1 -Param1 Hello -Param2 World"

pwsh.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 Hello -Param2 World"

pwsh.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 Hello World"

pwsh.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 -Param2 World Hello"

PowerShell

powershell.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 -Param1 Hello -Param2 World"

powershell.exe -NoLogo -ExecutionPolicy Bypass -Command "path-to-script/Script.ps1 -Param1 Hello -Param2 World"

powershell.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 Hello -Param2 World"

powershell.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 Hello World"

powershell.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 -Param2 World Hello"

Call from PowerShell

PowerShell Core or Windows PowerShell

& path-to-script/Script.ps1 -Param1 Hello -Param2 World
& ./Script.ps1 -Param1 Hello -Param2 World

Script.ps1 - Script Code

param(
    [Parameter(Mandatory=$True, Position=0, ValueFromPipeline=$false)]
    [System.String]
    $Param1,

    [Parameter(Mandatory=$True, Position=1, ValueFromPipeline=$false)]
    [System.String]
    $Param2
)

Write-Host $Param1
Write-Host $Param2

How to check whether a Button is clicked by using JavaScript

This will do it

<input id="button" type="submit" name="button" onclick="myFunction();" value="enter"/>

<script>
function myFunction(){
    alert("You button was pressed");
};   
</script>

How to show the last queries executed on MySQL?

You can do the flowing thing for monitoring mysql query logs.

Open mysql configuration file my.cnf

sudo nano /etc/mysql/my.cnf

Search following lines under a [mysqld] heading and uncomment these lines to enable log

general_log_file        = /var/log/mysql/mysql.log
general_log             = 1

Restart your mysql server for reflect changes

sudo service mysql start

Monitor mysql server log with following command in terminal

tail -f /var/log/mysql/mysql.log

What is the basic difference between the Factory and Abstract Factory Design Patterns?

With the Factory pattern, you produce instances of implementations (Apple, Banana, Cherry, etc.) of a particular interface -- say, IFruit.

With the Abstract Factory pattern, you provide a way for anyone to provide their own factory. This allows your warehouse to be either an IFruitFactory or an IJuiceFactory, without requiring your warehouse to know anything about fruits or juices.

PHP: Get key from array?

Another way to use key($array) in a foreach loop is by using next($array) at the end of the loop, just make sure each iteration calls the next() function (in case you have complex branching inside the loop)

Spark specify multiple column conditions for dataframe join

As of Spark version 1.5.0 (which is currently unreleased), you can join on multiple DataFrame columns. Refer to SPARK-7990: Add methods to facilitate equi-join on multiple join keys.

Python

Leads.join(
    Utm_Master, 
    ["LeadSource","Utm_Source","Utm_Medium","Utm_Campaign"],
    "left_outer"
)

Scala

The question asked for a Scala answer, but I don't use Scala. Here is my best guess....

Leads.join(
    Utm_Master,
    Seq("LeadSource","Utm_Source","Utm_Medium","Utm_Campaign"),
    "left_outer"
)

Using CSS for a fade-in effect on page load

In response to @A.M.K's question about how to do transitions without jQuery. A very simple example I threw together. If I had time to think this through some more, I might be able to eliminate the JavaScript code altogether:

<style>
    body {
        background-color: red;
        transition: background-color 2s ease-in;
    }
</style>

<script>
    window.onload = function() {
        document.body.style.backgroundColor = '#00f';
    }
</script>

<body>
    <p>test</p>
</body>

How to get HTML 5 input type="date" working in Firefox and/or IE 10

You can try webshims, which is available on cdn + only loads the polyfill, if it is needed.

Here is a demo with CDN: http://jsfiddle.net/trixta/BMEc9/

<!-- cdn for modernizr, if you haven't included it already -->
<script src="http://cdn.jsdelivr.net/webshim/1.12.4/extras/modernizr-custom.js"></script>
<!-- polyfiller file to detect and load polyfills -->
<script src="http://cdn.jsdelivr.net/webshim/1.12.4/polyfiller.js"></script>
<script>
  webshims.setOptions('waitReady', false);
  webshims.setOptions('forms-ext', {types: 'date'});
  webshims.polyfill('forms forms-ext');
</script>

<input type="date" />

In case the default configuration does not satisfy, there are many ways to configure it. Here you find the datepicker configurator.

Note: While there might be new bugfix releases for webshim in the future. There won't be any major releases anymore. This includes support for jQuery 3.0 or any new features.

Subset and ggplot2

Are you looking for the following plot:

library(ggplot2) 
l<-df[df$ID %in% c("P1","P3"),]
myplot<-ggplot(l)+geom_line(aes(Value1, Value2, group=ID, colour=ID))

enter image description here

Add line break to ::after or ::before pseudo-element content

Add line break to ::after or ::before pseudo-element content

.yourclass:before {
    content: 'text here first \A  text here second';
    white-space: pre;
}

sqlalchemy filter multiple columns

You can use SQLAlchemy's or_ function to search in more than one column (the underscore is necessary to distinguish it from Python's own or).

Here's an example:

from sqlalchemy import or_
query = meta.Session.query(User).filter(or_(User.firstname.like(searchVar),
                                            User.lastname.like(searchVar)))

Show only two digit after decimal

Here i will demonstrate you that how to make your decimal number short. Here i am going to make it short upto 4 value after decimal.

  double value = 12.3457652133
  value =Double.parseDouble(new DecimalFormat("##.####").format(value));

Ruby: character to ascii from a string

"a"[0]

or

?a

Both would return their ASCII equivalent.

Rotating a Div Element in jQuery

I doubt you can rotate an element using DOM/CSS. Your best bet would be to render to a canvas and rotate that (not sure on the specifics).

Jquery: Checking to see if div contains text, then action

Your code contains two problems:

  • The equality operator in JavaScript is ==, not =.
  • jQuery.text() joins all text nodes of matched elements into a single string. If you have two successive elements, of which the first contains 'some' and the second contains 'Text', then your code will incorrectly think that there exists an element that contains 'someText'.

I suggest the following instead:

if ($('#field > div.field-item:contains("someText")').length > 0) {
    $("#somediv").addClass("thisClass");
}

Disable / Check for Mock Location (prevent gps spoofing)

You can add additional check based on cell tower triangulation or Wifi Access Points info using Google Maps Geolocation API

The simplest way to get info about CellTowers

final TelephonyManager telephonyManager = (TelephonyManager) appContext.getSystemService(Context.TELEPHONY_SERVICE);
String networkOperator = telephonyManager.getNetworkOperator();
int mcc = Integer.parseInt(networkOperator.substring(0, 3));
int mnc = Integer.parseInt(networkOperator.substring(3));
String operatorName = telephonyManager.getNetworkOperatorName();
final GsmCellLocation cellLocation = (GsmCellLocation) telephonyManager.getCellLocation();
int cid = cellLocation.getCid();
int lac = cellLocation.getLac();

You can compare your results with site

To get info about Wifi Access Points

final WifiManager mWifiManager = (WifiManager) appContext.getApplicationContext().getSystemService(Context.WIFI_SERVICE);

if (mWifiManager != null && mWifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {

    // register WiFi scan results receiver
    IntentFilter filter = new IntentFilter();
    filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);

    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                List<ScanResult> results = mWifiManager.getScanResults();//<-result list
            }
        };

        appContext.registerReceiver(broadcastReceiver, filter);

        // start WiFi Scan
        mWifiManager.startScan();
}

Powershell Error "The term 'Get-SPWeb' is not recognized as the name of a cmdlet, function..."

Instead of Windows PowerShell, find the item in the Start Menu called SharePoint 2013 Management Shell:

enter image description here

How to hide element label by element id in CSS?

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

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

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

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

Databound drop down list - initial value

To select a value from the dropdown use the index like this:

if we have the

<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true"></asp:DropDownList>

you would use :

DropDownList1.Items[DropDownList1.SelectedIndex].Value

this would return the value for the selected index.

How do I print a datetime in the local timezone?

I believe the best way to do this is to use the LocalTimezone class defined in the datetime.tzinfo documentation (goto http://docs.python.org/library/datetime.html#tzinfo-objects and scroll down to the "Example tzinfo classes" section):

Assuming Local is an instance of LocalTimezone

t = datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=utc)
local_t = t.astimezone(Local)

then str(local_t) gives:

'2009-07-11 04:44:59.193982+10:00'

which is what you want.

(Note: this may look weird to you because I'm in New South Wales, Australia which is 10 or 11 hours ahead of UTC)

What are the Ruby File.open modes and options?

In Ruby IO module documentation, I suppose.

Mode |  Meaning
-----+--------------------------------------------------------
"r"  |  Read-only, starts at beginning of file  (default mode).
-----+--------------------------------------------------------
"r+" |  Read-write, starts at beginning of file.
-----+--------------------------------------------------------
"w"  |  Write-only, truncates existing file
     |  to zero length or creates a new file for writing.
-----+--------------------------------------------------------
"w+" |  Read-write, truncates existing file to zero length
     |  or creates a new file for reading and writing.
-----+--------------------------------------------------------
"a"  |  Write-only, starts at end of file if file exists,
     |  otherwise creates a new file for writing.
-----+--------------------------------------------------------
"a+" |  Read-write, starts at end of file if file exists,
     |  otherwise creates a new file for reading and
     |  writing.
-----+--------------------------------------------------------
"b"  |  Binary file mode (may appear with
     |  any of the key letters listed above).
     |  Suppresses EOL <-> CRLF conversion on Windows. And
     |  sets external encoding to ASCII-8BIT unless explicitly
     |  specified.
-----+--------------------------------------------------------
"t"  |  Text file mode (may appear with
     |  any of the key letters listed above except "b").

Calling Web API from MVC controller

well, you can do it a lot of ways... one of them is to create a HttpRequest. I would advise you against calling your own webapi from your own MVC (the idea is redundant...) but, here's a end to end tutorial.

How to build a 'release' APK in Android Studio?

Follow this steps:

-Build
-Generate Signed Apk
-Create new

Then fill up "New Key Store" form. If you wand to change .jnk file destination then chick on destination and give a name to get Ok button. After finishing it you will get "Key store password", "Key alias", "Key password" Press next and change your the destination folder. Then press finish, thats all. :)

enter image description here

enter image description here enter image description here

enter image description here enter image description here

How to insert table values from one database to another database?

For SQL Server, you can use tool Import Data from another Database, It's easier to configuration mapping columns.

Send email by using codeigniter library via localhost

I had the same problem and I solved by using the postcast server. You can install it locally and use it.

How do I export (and then import) a Subversion repository?

You can also use svnsync. This only requires read-only access on the source repository

more at svnbook

jquery onclick change css background image

Use your jquery like this

$('.home').css({'background-image':'url(images/tabs3.png)'});

phonegap open link in browser

With Cordova 5.0 and greater the plugin InAppBrowser is renamed in the Cordova plugin registry, so you should install it using

cordova plugin add cordova-plugin-inappbrowser --save

Then use

_x000D_
_x000D_
<a href="#" onclick="window.open('http://www.kidzout.com', '_system');">www.kidzout.com</a>
_x000D_
_x000D_
_x000D_

How to solve ADB device unauthorized in Android ADB host device?

I found one solution with Nexus 5, and TWRP installed. Basically format was the only solution I found and I tried all solutions listed here before: ADB Android Device Unauthorized

Ask Google to make backup of your apps. Save all important files you may have on your phone

Please note that I decline all liability in case of failure as what I did was quite risky but worked in my case:

Enable USB debugging in developer option (not sure if it helped as device was unauthorized but still...)

Make sure your phone is connected to computer and you can access storage

Download google img of your nexus: https://developers.google.com/android/nexus/images unrar your files and places them in a new folder on your computer, name it factory (any name will do).

wipe ALL datas... you will have 0 file in your android accessed from computer.

Then reboot into BOOTLOADER mode... you will have the message "you have no OS installed are you sure you want to reboot ?"

Then execute (double click) the .bat file inside the "factory" folder.

You will see command line detailed installation of the OS. Of course avoid disconnecting cable during this phase...

Phone will take about 5mn to initialize.

Could not autowire field in spring. why?

When you get this error some annotation is missing. I was missing @service annotation on service. When I added that annotation it worked fine for me.

How to make full screen background in a web page

I have followed this tutorial: https://css-tricks.com/perfect-full-page-background-image/

Specifically, the first Demo was the one that helped me out a lot!

CSS
 {
    background: url(images/bg.jpg) no-repeat center center fixed;
    -webkit-background-size: cover;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover; 
}

this might help!

How to pass arguments from command line to gradle

My program with two arguments, args[0] and args[1]:

public static void main(String[] args) throws Exception {
    System.out.println(args);
    String host = args[0];
    System.out.println(host);
    int port = Integer.parseInt(args[1]);

my build.gradle

run {
    if ( project.hasProperty("appArgsWhatEverIWant") ) {
        args Eval.me(appArgsWhatEverIWant)
    }
}

my terminal prompt:

gradle run  -PappArgsWhatEverIWant="['localhost','8080']"

Get index of clicked element in collection with jQuery

$('selector').click(function (event) {
    alert($(this).index());
});

jsfiddle

What's the purpose of the LEA instruction?

Another important feature of the LEA instruction is that it does not alter the condition codes such as CF and ZF, while computing the address by arithmetic instructions like ADD or MUL does. This feature decreases the level of dependency among instructions and thus makes room for further optimization by the compiler or hardware scheduler.

How to start rails server?

Rails version < 2
From project root run:

./script/server

How to convert a const char * to std::string

std::string the_string(c_string);
if(the_string.size() > max_length)
    the_string.resize(max_length);

How to Implement DOM Data Binding in JavaScript

I have gone through some basic javascript example using onkeypress and onchange event handlers for making binding view to our js and js to view

Here example plunker http://plnkr.co/edit/7hSOIFRTvqLAvdZT4Bcc?p=preview

<!DOCTYPE html>
<html>
<body>

    <p>Two way binding data.</p>

    <p>Binding data from  view to JS</p>

    <input type="text" onkeypress="myFunction()" id="myinput">
    <p id="myid"></p>
    <p>Binding data from  js to view</p>
    <input type="text" id="myid2" onkeypress="myFunction1()" oninput="myFunction1()">
    <p id="myid3" onkeypress="myFunction1()" id="myinput" oninput="myFunction1()"></p>

    <script>

        document.getElementById('myid2').value="myvalue from script";
        document.getElementById('myid3').innerHTML="myvalue from script";
        function myFunction() {
            document.getElementById('myid').innerHTML=document.getElementById('myinput').value;
        }
        document.getElementById("myinput").onchange=function(){

            myFunction();

        }
        document.getElementById("myinput").oninput=function(){

            myFunction();

        }

        function myFunction1() {

            document.getElementById('myid3').innerHTML=document.getElementById('myid2').value;
        }
    </script>

</body>
</html>

DBNull if statement

I use String.IsNullorEmpty often. It will work her because when DBNull is set to .ToString it returns empty.

if(!(String.IsNullorEmpty(rsData["usr.ursrdaystime"].toString())){
        strLevel = rsData["usr.ursrdaystime"].toString();
    }

Auto-redirect to another HTML page

I'm Maybe kind of late but here is a way to have a redirect for your website and another link if it does not do in auto redirect for them,

<meta charset="UTF-8" />
<meta http-equiv="refresh" content="5; url=YOUR_URL_HERE" />
<script type="text/javascript">
  window.location.href = "site";
</script>
<title>Page Redirection</title>

<!-- Note: don't tell people to `click` the link, just tell them that it is a link. -->
If you are not redirected automatically, follow this <a href="/site">Link</a>

Convert seconds to HH-MM-SS with JavaScript?

None of the answers here satisfies my requirements as I want to be able to handle

  1. Large numbers of seconds (days), and
  2. Negative numbers

Although those are not required by the OP, it's good practice to cover edge cases, especially when it takes little effort.

It's pretty obvious is that the OP means a NUMBER of seconds when he says seconds. Why would peg your function on String?

function secondsToTimeSpan(seconds) {
    const value = Math.abs(seconds);
    const days = Math.floor(value / 1440);
    const hours = Math.floor((value - (days * 1440)) / 3600);
    const min = Math.floor((value - (days * 1440) - (hours * 3600)) / 60);
    const sec = value - (days * 1440) - (hours * 3600) - (min * 60);
    return `${seconds < 0 ? '-':''}${days > 0 ? days + '.':''}${hours < 10 ? '0' + hours:hours}:${min < 10 ? '0' + min:min}:${sec < 10 ? '0' + sec:sec}`
}
secondsToTimeSpan(0);       // => 00:00:00
secondsToTimeSpan(1);       // => 00:00:01
secondsToTimeSpan(1440);    // => 1.00:00:00
secondsToTimeSpan(-1440);   // => -1.00:00:00
secondsToTimeSpan(-1);      // => -00:00:01

How to calculate the intersection of two sets?

Yes there is retainAll check out this

Set<Type> intersection = new HashSet<Type>(s1);
intersection.retainAll(s2);

C++ Fatal Error LNK1120: 1 unresolved externals

Well it seems that you are missing a reference to some library. I had the similar error solved it by adding a reference to the #pragma comment(lib, "windowscodecs.lib")

How to shrink/purge ibdata1 file in MySQL

That ibdata1 isn't shrinking is a particularly annoying feature of MySQL. The ibdata1 file can't actually be shrunk unless you delete all databases, remove the files and reload a dump.

But you can configure MySQL so that each table, including its indexes, is stored as a separate file. In that way ibdata1 will not grow as large. According to Bill Karwin's comment this is enabled by default as of version 5.6.6 of MySQL.

It was a while ago I did this. However, to setup your server to use separate files for each table you need to change my.cnf in order to enable this:

[mysqld]
innodb_file_per_table=1

https://dev.mysql.com/doc/refman/5.6/en/innodb-file-per-table-tablespaces.html

As you want to reclaim the space from ibdata1 you actually have to delete the file:

  1. Do a mysqldump of all databases, procedures, triggers etc except the mysql and performance_schema databases
  2. Drop all databases except the above 2 databases
  3. Stop mysql
  4. Delete ibdata1 and ib_log files
  5. Start mysql
  6. Restore from dump

When you start MySQL in step 5 the ibdata1 and ib_log files will be recreated.

Now you're fit to go. When you create a new database for analysis, the tables will be located in separate ibd* files, not in ibdata1. As you usually drop the database soon after, the ibd* files will be deleted.

http://dev.mysql.com/doc/refman/5.1/en/drop-database.html

You have probably seen this:
http://bugs.mysql.com/bug.php?id=1341

By using the command ALTER TABLE <tablename> ENGINE=innodb or OPTIMIZE TABLE <tablename> one can extract data and index pages from ibdata1 to separate files. However, ibdata1 will not shrink unless you do the steps above.

Regarding the information_schema, that is not necessary nor possible to drop. It is in fact just a bunch of read-only views, not tables. And there are no files associated with the them, not even a database directory. The informations_schema is using the memory db-engine and is dropped and regenerated upon stop/restart of mysqld. See https://dev.mysql.com/doc/refman/5.7/en/information-schema.html.

One-line list comprehension: if-else variants

[x if x % 2 else x * 100 for x in range(1, 10) ]

How to get difference between two rows for a column field?

Query to Find the date difference between 2 rows of a single column

SELECT
Column name,
DATEDIFF(
(SELECT MAX(date) FROM table name WHERE Column name < b. Column name),
Column name) AS days_since_last
FROM table name AS b

How to validate phone numbers using regex

My gut feeling is reinforced by the amount of replies to this topic - that there is a virtually infinite number of solutions to this problem, none of which are going to be elegant.

Honestly, I would recommend you don't try to validate phone numbers. Even if you could write a big, hairy validator that would allow all the different legitimate formats, it would end up allowing pretty much anything even remotely resembling a phone number in the first place.

In my opinion, the most elegant solution is to validate a minimum length, nothing more.

Java - remove last known item from ArrayList

clients.get will return a ClientThread and not a String, and it will bomb with an IndexOutOfBoundsException if it would compile as Java is zero based for indexing.

Similarly I think you should call remove on the clients list.

ClientThread hey = clients.get(clients.size()-1);
clients.remove(hey);
System.out.println(hey + " has logged out.");
System.out.println("CONNECTED PLAYERS: " + clients.size());

I would use the stack functions of a LinkedList in this case though.

ClientThread hey = clients.removeLast()

Table row and column number in jQuery

Off the top of my head, one way would be to grab all previous elements and count them.

$('td').click(function(){ 
    var colIndex = $(this).prevAll().length;
    var rowIndex = $(this).parent('tr').prevAll().length;
});

Currently running queries in SQL Server

here is what you need to install the SQL profiler http://msdn.microsoft.com/en-us/library/bb500441.aspx. However, i would suggest you to read through this one http://blog.sqlauthority.com/2009/08/03/sql-server-introduction-to-sql-server-2008-profiler-2/ if you are looking to do it on your Production Environment. There is another better way to look at the queries watch this one and see if it helps http://www.youtube.com/watch?v=vvziPI5OQyE

Android SDK Manager Not Installing Components

In my case I was using Windows 7 with the 64-bit OS. We installed the 64-bit Java SE and 64-bit ADT Bundle. With that set up, we couldn't get the SDK manager to work correctly (specifically, no downloads allowed and it didn't show all the API download options). After trying all of the above answers and from other posts, we decided to look into the Java set up and realized it might the 64-bit configuration that's giving the ADT bundle grief (I vaguely recall seeing/reading this issue before).

So we uninstalled Java 64-bit and reinstalled the 32-bit, and then used the 32-bit ADT bundle, and it worked correctly. The system user was already an admin, so we didn't need to "Run as Administrator"

Start / Stop a Windows Service from a non-Administrator user account

It's significantly easier to grant management permissions to a service using one of these tools:

  • Group Policy
  • Security Template
  • subinacl.exe command-line tool.

Here's the MSKB article with instructions for Windows Server 2008 / Windows 7, but the instructions are the same for 2000 and 2003.

How to add default signature in Outlook

My solution is to display an empty message first (with default signature!) and insert the intended strHTMLBody into the existing HTMLBody.

If, like PowerUser states, the signature is wiped out while editing HTMLBody you might consider storing the contents of ObjMail.HTMLBody into variable strTemp immediately after ObjMail.Display and add strTemp afterwards but that should not be necessary.

Sub X(strTo as string, strSubject as string, strHTMLBody as string)

   Dim OlApp As Outlook.Application   
   Dim ObjMail As Outlook.MailItem 

   Set OlApp = Outlook.Application
   Set ObjMail = OlApp.CreateItem(olMailItem)

   ObjMail.To = strTo
   ObjMail.Subject = strSubject   
   ObjMail.Display
   'You now have the default signature within ObjMail.HTMLBody.
   'Add this after adding strHTMLBody
   ObjMail.HTMLBody = strHTMLBody & ObjMail.HTMLBody

   'ObjMail.Send 'send immediately or 
   'ObjMail.close olSave 'save as draft
   'Set OlApp = Nothing

End sub

How do you assert that a certain exception is thrown in JUnit 4 tests?

You can also do this:

@Test
public void testFooThrowsIndexOutOfBoundsException() {
    try {
        foo.doStuff();
        assert false;
    } catch (IndexOutOfBoundsException e) {
        assert true;
    }
}

How do I remove an item from a stl vector with a certain value?

*

C++ community has heard your request :)

*

C++ 20 provides an easy way of doing it now. It gets as simple as :

#include <vector>
...
vector<int> cnt{5, 0, 2, 8, 0, 7};
std::erase(cnt, 0);

You should check out std::erase and std::erase_if.

Not only will it remove all elements of the value (here '0'), it will do it in O(n) time complexity. Which is the very best you can get.

If your compiler does not support C++ 20, you should use erase-remove idiom:

#include <algorithm>
...
vec.erase(std::remove(vec.begin(), vec.end(), 0), vec.end());

Replace preg_replace() e modifier with preg_replace_callback

You shouldn't use flag e (or eval in general).

You can also use T-Regx library

pattern('(^|_)([a-z])')->replace($word)->by()->group(2)->callback('strtoupper');

Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2

Flyway is comparing the checksum of the SQL script with that of the previously run checksum. This exception typically occurs if you change a SQL script that has already been applied by Flyway, thus causing a checksum mismatch.

If this is development, you can drop your database and start the migrations from scratch.

If you're in production, never edit SQL scripts that have already been applied. Only create new SQL scripts going forward.

Error: could not find function "%>%"

One needs to install magrittr as follows

install.packages("magrittr")

Then, in one's script, don't forget to add on top

library(magrittr)

For the meaning of the operator %>% you might want to consider this question: What does %>% function mean in R?

Note that the same operator would also work with the library dplyr, as it imports from magrittr.

dplyr used to have a similar operator (%.%), which is now deprecated. Here we can read about the differences between %.% (deprecated operator from the library dplyr) and %>% (operator from magrittr, that is also available in dplyr)

Create table using Javascript

_x000D_
_x000D_
var btn = document.createElement('button');_x000D_
btn.innerHTML = "Create Table";_x000D_
document.body.appendChild(btn);_x000D_
btn.addEventListener("click", createTable, true);_x000D_
function createTable(){_x000D_
var div = document.createElement('div');_x000D_
div.setAttribute("id", "tbl");_x000D_
document.body.appendChild(div)_x000D_
 document.getElementById("tbl").innerHTML = "<table border = '1'>" +_x000D_
  '<tr>' +_x000D_
    '<th>Header 1</th>' +_x000D_
    '<th>Header 2</th> ' +_x000D_
    '<th>Header 3</th>' +_x000D_
  '</tr>' +_x000D_
  '<tr>' +_x000D_
    '<td>Data 1</td>' +_x000D_
    '<td>Data 2</td>' +_x000D_
    '<td>Data 3</td>' +_x000D_
  '</tr>' +_x000D_
  '<tr>' +_x000D_
    '<td>Data 1</td>' +_x000D_
    '<td>Data 2</td>' +_x000D_
    '<td>Data 3</td>' +_x000D_
  '</tr>' +_x000D_
  '<tr>' +_x000D_
    '<td>Data 1</td>' +_x000D_
    '<td>Data 2</td>' +_x000D_
    '<td>Data 3</td>' +_x000D_
  '</tr>' _x000D_
};
_x000D_
_x000D_
_x000D_

How can I convert JSON to a HashMap using Gson?

I had the exact same question and ended up here. I had a different approach that seems much simpler (maybe newer versions of gson?).

    Gson gson = new Gson();
    Map jsonObject = (Map) gson.fromJson(data, Object.class);

with the following json

{
  "map-00": {
    "array-00": [
      "entry-00",
      "entry-01"
     ],
     "value": "entry-02"
   }
}

The following

    Map map00 = (Map) jsonObject.get("map-00");
    List array00 = (List) map00.get("array-00");
    String value = (String) map00.get("value");
    for (int i = 0; i < array00.size(); i++) {
        System.out.println("map-00.array-00[" + i + "]= " + array00.get(i));
    }
    System.out.println("map-00.value = " + value);

outputs

map-00.array-00[0]= entry-00
map-00.array-00[1]= entry-01
map-00.value = entry-02

You could dynamically check using instanceof when navigating your jsonObject. Something like

Map json = gson.fromJson(data, Object.class);
if(json.get("field") instanceof Map) {
  Map field = (Map)json.get("field");
} else if (json.get("field") instanceof List) {
  List field = (List)json.get("field");
} ...

It works for me, so it must work for you ;-)

Pandas dataframe groupby plot

Simple plot,

you can use:

df.plot(x='Date',y='adj_close')

Or you can set the index to be Date beforehand, then it's easy to plot the column you want:

df.set_index('Date', inplace=True)
df['adj_close'].plot()

If you want a chart with one series by ticker on it

You need to groupby before:

df.set_index('Date', inplace=True)
df.groupby('ticker')['adj_close'].plot(legend=True)

enter image description here


If you want a chart with individual subplots:

grouped = df.groupby('ticker')

ncols=2
nrows = int(np.ceil(grouped.ngroups/ncols))

fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(12,4), sharey=True)

for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):
    grouped.get_group(key).plot(ax=ax)

ax.legend()
plt.show()

enter image description here

How to query for Xml values and attributes from table in SQL Server?

I've been trying to do something very similar but not using the nodes. However, my xml structure is a little different.

You have it like this:

<Metrics>
    <Metric id="TransactionCleanupThread.RefundOldTrans" type="timer" ...>

If it were like this instead:

<Metrics>
    <Metric>
        <id>TransactionCleanupThread.RefundOldTrans</id>
        <type>timer</type>
        .
        .
        .

Then you could simply use this SQL statement.

SELECT
    Sqm.SqmId,
    Data.value('(/Sqm/Metrics/Metric/id)[1]', 'varchar(max)') as id,
    Data.value('(/Sqm/Metrics/Metric/type)[1]', 'varchar(max)') AS type,
    Data.value('(/Sqm/Metrics/Metric/unit)[1]', 'varchar(max)') AS unit,
    Data.value('(/Sqm/Metrics/Metric/sum)[1]', 'varchar(max)') AS sum,
    Data.value('(/Sqm/Metrics/Metric/count)[1]', 'varchar(max)') AS count,
    Data.value('(/Sqm/Metrics/Metric/minValue)[1]', 'varchar(max)') AS minValue,
    Data.value('(/Sqm/Metrics/Metric/maxValue)[1]', 'varchar(max)') AS maxValue,
    Data.value('(/Sqm/Metrics/Metric/stdDeviation)[1]', 'varchar(max)') AS stdDeviation,
FROM Sqm

To me this is much less confusing than using the outer apply or cross apply.

I hope this helps someone else looking for a simpler solution!

How do I see all foreign keys to a table or column?

If you use InnoDB and defined FK's you could query the information_schema database e.g.:

SELECT * FROM information_schema.TABLE_CONSTRAINTS 
WHERE information_schema.TABLE_CONSTRAINTS.CONSTRAINT_TYPE = 'FOREIGN KEY' 
AND information_schema.TABLE_CONSTRAINTS.TABLE_SCHEMA = 'myschema'
AND information_schema.TABLE_CONSTRAINTS.TABLE_NAME = 'mytable';

Assigning more than one class for one event

Have you tried this:

 function doSomething() {
     if ($(this).hasClass('clickedTag')){
         // code here
     } else {
         // and here
     }
 }

 $('.tag1, .tag2').click(doSomething);

How to ignore whitespace in a regular expression subject string?

If you only want to allow spaces, then

\bc *a *t *s\b

should do it. To also allow tabs, use

\bc[ \t]*a[ \t]*t[ \t]*s\b

Remove the \b anchors if you also want to find cats within words like bobcats or catsup.

Detect Safari browser

Maybe this works :

Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor')

EDIT: NO LONGER WORKING

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax — PHP — PDO

Same pdo error in sql query while trying to insert into database value from multidimential array:

$sql = "UPDATE test SET field=arr[$s][a] WHERE id = $id";
$sth = $db->prepare($sql);    
$sth->execute();

Extracting array arr[$s][a] from sql query, using instead variable containing it fixes the problem.

HashSet vs LinkedHashSet

The answer lies in which constructors the LinkedHashSet uses to construct the base class:

public LinkedHashSet(int initialCapacity, float loadFactor) {
    super(initialCapacity, loadFactor, true);      // <-- boolean dummy argument
}

...

public LinkedHashSet(int initialCapacity) {
    super(initialCapacity, .75f, true);            // <-- boolean dummy argument
}

...

public LinkedHashSet() {
    super(16, .75f, true);                         // <-- boolean dummy argument
}

...

public LinkedHashSet(Collection<? extends E> c) {
    super(Math.max(2*c.size(), 11), .75f, true);   // <-- boolean dummy argument
    addAll(c);
}

And (one example of) a HashSet constructor that takes a boolean argument is described, and looks like this:

/**
 * Constructs a new, empty linked hash set.  (This package private
 * constructor is only used by LinkedHashSet.) The backing
 * HashMap instance is a LinkedHashMap with the specified initial
 * capacity and the specified load factor.
 *
 * @param      initialCapacity   the initial capacity of the hash map
 * @param      loadFactor        the load factor of the hash map
 * @param      dummy             ignored (distinguishes this
 *             constructor from other int, float constructor.)
 * @throws     IllegalArgumentException if the initial capacity is less
 *             than zero, or if the load factor is nonpositive
 */
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
    map = new LinkedHashMap<E,Object>(initialCapacity, loadFactor);
}

jquery append div inside div with id and manipulate

var e = $('<div style="display:block; id="myid" float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
$("#box").html(e);

How to reduce the image file size using PIL

If you hava a fact png (1MB for 400x400 etc.):

__import__("importlib").import_module("PIL.Image").open("out.png").save("out.png")

Uint8Array to string in Javascript

I was frustrated to see that people were not showing how to go both ways or showing that things work on none trivial UTF8 strings. I found a post on codereview.stackexchange.com that has some code that works well. I used it to turn ancient runes into bytes, to test some crypo on the bytes, then convert things back into a string. The working code is on github here. I renamed the methods for clarity:

// https://codereview.stackexchange.com/a/3589/75693
function bytesToSring(bytes) {
    var chars = [];
    for(var i = 0, n = bytes.length; i < n;) {
        chars.push(((bytes[i++] & 0xff) << 8) | (bytes[i++] & 0xff));
    }
    return String.fromCharCode.apply(null, chars);
}

// https://codereview.stackexchange.com/a/3589/75693
function stringToBytes(str) {
    var bytes = [];
    for(var i = 0, n = str.length; i < n; i++) {
        var char = str.charCodeAt(i);
        bytes.push(char >>> 8, char & 0xFF);
    }
    return bytes;
}

The unit test uses this UTF-8 string:

    // http://kermitproject.org/utf8.html
    // From the Anglo-Saxon Rune Poem (Rune version) 
    const secretUtf8 = `?????????????????????????????
?????????????????????????????????????????
?????????????????????????????????????`;

Note that the string length is only 117 characters but the byte length, when encoded, is 234.

If I uncomment the console.log lines I can see that the string that is decoded is the same string that was encoded (with the bytes passed through Shamir's secret sharing algorithm!):

unit test that demos encoding and decoding

How to lay out Views in RelativeLayout programmatically?

If you really want to layout manually, i'd suggest not to use a standard layout at all. Do it all on your own, here a kotlin example:

class ProgrammaticalLayout @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : ViewGroup(context, attrs, defStyleAttr) { 
    private val firstTextView = TextView(context).apply {
        test = "First Text"
    }

    private val secondTextView = TextView(context).apply {
        text = "Second Text"
    }

    init {
        addView(firstTextView)
        addView(secondTextView)
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        // center the views verticaly and horizontaly
        val firstTextLeft = (measuredWidth - firstTextView.measuredWidth) / 2
        val firstTextTop = (measuredHeight - (firstTextView.measuredHeight + secondTextView.measuredHeight)) / 2
        firstTextView.layout(firstTextLeft,firstTextTop, firstTextLeft + firstTextView.measuredWidth,firstTextTop + firstTextView.measuredHeight)

        val secondTextLeft = (measuredWidth - secondTextView.measuredWidth) / 2
        val secondTextTop = firstTextView.bottom
        secondTextView.layout(secondTextLeft,secondTextTop, secondTextLeft + secondTextView.measuredWidth,secondTextTop + secondTextView.measuredHeight)
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { 
        // just assume we`re getting measured exactly by the parent
        val measuredWidth = MeasureSpec.getSize(widthMeasureSpec)
        val measuredHeight = MeasureSpec.getSize(heightMeasureSpec)

        firstTextView.measures(MeasureSpec.makeMeasureSpec(meeasuredWidth, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED))
        secondTextView.measures(MeasureSpec.makeMeasureSpec(meeasuredWidth, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED))

        setMeasuredDimension(measuredWidth, measuredHeight)
    }
}

This might give you an idea how this could work

Laravel 4: how to run a raw SQL?

Laravel raw sql – Insert query:

lets create a get link to insert data which is accessible through url . so our link name is ‘insertintodb’ and inside that function we use db class . db class helps us to interact with database . we us db class static function insert . Inside insert function we will write our PDO query to insert data in database . in below query we will insert ‘ my title ‘ and ‘my content’ as data in posts table .

put below code in your web.php file inside routes directory :

Route::get('/insertintodb',function(){
DB::insert('insert into posts(title,content) values (?,?)',['my title','my content']);
});

Now fire above insert query from browser link below :

localhost/yourprojectname/insertintodb

You can see output of above insert query by going into your database table .you will find a record with id 1 .

Laravel raw sql – Read query :

Now , lets create a get link to read data , which is accessible through url . so our link name is ‘readfromdb’. we us db class static function read . Inside read function we will write our PDO query to read data from database . in below query we will read data of id ‘1’ from posts table .

put below code in your web.php file inside routes directory :

Route::get('/readfromdb',function() {
    $result =  DB::select('select * from posts where id = ?', [1]);
    var_dump($result);
});

now fire above read query from browser link below :

localhost/yourprojectname/readfromdb

How to determine the Boost version on a system?

If one installed boost on macOS via Homebrew, one is likely to see the installed boost version(s) with:

ls /usr/local/Cellar/boost*

Understanding ibeacon distancing

The iBeacon output power is measured (calibrated) at a distance of 1 meter. Let's suppose that this is -59 dBm (just an example). The iBeacon will include this number as part of its LE advertisment.

The listening device (iPhone, etc), will measure the RSSI of the device. Let's suppose, for example, that this is, say, -72 dBm.

Since these numbers are in dBm, the ratio of the power is actually the difference in dB. So:

ratio_dB = txCalibratedPower - RSSI

To convert that into a linear ratio, we use the standard formula for dB:

ratio_linear = 10 ^ (ratio_dB / 10)

If we assume conservation of energy, then the signal strength must fall off as 1/r^2. So:

power = power_at_1_meter / r^2. Solving for r, we get:

r = sqrt(ratio_linear)

In Javascript, the code would look like this:

function getRange(txCalibratedPower, rssi) {
    var ratio_db = txCalibratedPower - rssi;
    var ratio_linear = Math.pow(10, ratio_db / 10);

    var r = Math.sqrt(ratio_linear);
    return r;
}

Note, that, if you're inside a steel building, then perhaps there will be internal reflections that make the signal decay slower than 1/r^2. If the signal passes through a human body (water) then the signal will be attenuated. It's very likely that the antenna doesn't have equal gain in all directions. Metal objects in the room may create strange interference patterns. Etc, etc... YMMV.

How to generate a Dockerfile from an image?

A bash solution :

docker history --no-trunc $argv  | tac | tr -s ' ' | cut -d " " -f 5- | sed 's,^/bin/sh -c #(nop) ,,g' | sed 's,^/bin/sh -c,RUN,g' | sed 's, && ,\n  & ,g' | sed 's,\s*[0-9]*[\.]*[0-9]*\s*[kMG]*B\s*$,,g' | head -n -1

Step by step explanations:

tac : reverse the file
tr -s ' '                                       trim multiple whitespaces into 1
cut -d " " -f 5-                                remove the first fields (until X months/years ago)
sed 's,^/bin/sh -c #(nop) ,,g'                  remove /bin/sh calls for ENV,LABEL...
sed 's,^/bin/sh -c,RUN,g'                       remove /bin/sh calls for RUN
sed 's, && ,\n  & ,g'                           pretty print multi command lines following Docker best practices
sed 's,\s*[0-9]*[\.]*[0-9]*\s*[kMG]*B\s*$,,g'      remove layer size information
head -n -1                                      remove last line ("SIZE COMMENT" in this case)

Example:

 ~ ? dih ubuntu:18.04
ADD file:28c0771e44ff530dba3f237024acc38e8ec9293d60f0e44c8c78536c12f13a0b in /
RUN set -xe
   &&  echo '#!/bin/sh' > /usr/sbin/policy-rc.d
   &&  echo 'exit 101' >> /usr/sbin/policy-rc.d
   &&  chmod +x /usr/sbin/policy-rc.d
   &&  dpkg-divert --local --rename --add /sbin/initctl
   &&  cp -a /usr/sbin/policy-rc.d /sbin/initctl
   &&  sed -i 's/^exit.*/exit 0/' /sbin/initctl
   &&  echo 'force-unsafe-io' > /etc/dpkg/dpkg.cfg.d/docker-apt-speedup
   &&  echo 'DPkg::Post-Invoke { "rm -f /var/cache/apt/archives/*.deb /var/cache/apt/archives/partial/*.deb /var/cache/apt/*.bin || true"; };' > /etc/apt/apt.conf.d/docker-clean
   &&  echo 'APT::Update::Post-Invoke { "rm -f /var/cache/apt/archives/*.deb /var/cache/apt/archives/partial/*.deb /var/cache/apt/*.bin || true"; };' >> /etc/apt/apt.conf.d/docker-clean
   &&  echo 'Dir::Cache::pkgcache ""; Dir::Cache::srcpkgcache "";' >> /etc/apt/apt.conf.d/docker-clean
   &&  echo 'Acquire::Languages "none";' > /etc/apt/apt.conf.d/docker-no-languages
   &&  echo 'Acquire::GzipIndexes "true"; Acquire::CompressionTypes::Order:: "gz";' > /etc/apt/apt.conf.d/docker-gzip-indexes
   &&  echo 'Apt::AutoRemove::SuggestsImportant "false";' > /etc/apt/apt.conf.d/docker-autoremove-suggests
RUN rm -rf /var/lib/apt/lists/*
RUN sed -i 's/^#\s*\(deb.*universe\)$/\1/g' /etc/apt/sources.list
RUN mkdir -p /run/systemd
   &&  echo 'docker' > /run/systemd/container
CMD ["/bin/bash"]

How to resolve a Java Rounding Double issue

See responses to this question. Essentially what you are seeing is a natural consequence of using floating point arithmetic.

You could pick some arbitrary precision (significant digits of your inputs?) and round your result to it, if you feel comfortable doing that.

C++ performance vs. Java/C#

Orion Adrian, let me invert your post to see how unfounded your remarks are, because a lot can be said about C++ as well. And telling that Java/C# compiler optimize away empty functions does really make you sound like you are not my expert in optimization, because a) why should a real program contain empty functions, except for really bad legacy code, b) that is really not black and bleeding edge optimization.

Apart from that phrase, you ranted blatantly about pointers, but don't objects in Java and C# basically work like C++ pointers? May they not overlap? May they not be null? C (and most C++ implementations) has the restrict keyword, both have value types, C++ has reference-to-value with non-null guarantee. What do Java and C# offer?

>>>>>>>>>>

Generally, C and C++ can be just as fast or faster because the AOT compiler -- a compiler that compiles your code before deployment, once and for all, on your high memory many core build server -- can make optimizations that a C# compiled program cannot because it has a ton of time to do so. The compiler can determine if the machine is Intel or AMD; Pentium 4, Core Solo, or Core Duo; or if supports SSE4, etc, and if your compiler does not support runtime dispatch, you can solve for that yourself by deploying a handful of specialized binaries.

A C# program is commonly compiled upon running it so that it runs decently well on all machines, but is not optimized as much as it could be for a single configuration (i.e. processor, instruction set, other hardware), and it must spend some time first. Features like loop fission, loop inversion, automatic vectorization, whole program optimization, template expansion, IPO, and many more, are very hard to be solved all and completely in a way that does not annoy the end user.

Additionally certain language features allow the compiler in C++ or C to make assumptions about your code that allows it to optimize certain parts away that just aren't safe for the Java/C# compiler to do. When you don't have access to the full type id of generics or a guaranteed program flow there's a lot of optimizations that just aren't safe.

Also C++ and C do many stack allocations at once with just one register incrementation, which surely is more efficient than Javas and C# allocations as for the layer of abstraction between the garbage collector and your code.

Now I can't speak for Java on this next point, but I know that C++ compilers for example will actually remove methods and method calls when it knows the body of the method is empty, it will eliminate common subexpressions, it may try and retry to find optimal register usage, it does not enforce bounds checking, it will autovectorize loops and inner loops and will invert inner to outer, it moves conditionals out of loops, it splits and unsplits loops. It will expand std::vector into native zero overhead arrays as you'd do the C way. It will do inter procedural optimmizations. It will construct return values directly at the caller site. It will fold and propagate expressions. It will reorder data into a cache friendly manner. It will do jump threading. It lets you write compile time ray tracers with zero runtime overhead. It will make very expensive graph based optimizations. It will do strength reduction, were it replaces certain codes with syntactically totally unequal but semantically equivalent code (the old "xor foo, foo" is just the simplest, though outdated optimization of such kind). If you kindly ask it, you may omit IEEE floating point standards and enable even more optimizations like floating point operand re-ordering. After it has massaged and massacred your code, it might repeat the whole process, because often, certain optimizations lay the foundation for even certainer optimizations. It might also just retry with shuffled parameters and see how the other variant scores in its internal ranking. And it will use this kind of logic throughout your code.

So as you can see, there are lots of reasons why certain C++ or C implementations will be faster.

Now this all said, many optimizations can be made in C++ that will blow away anything that you could do with C#, especially in the number crunching, realtime and close-to-metal realm, but not exclusively there. You don't even have to touch a single pointer to come a long way.

So depending on what you're writing I would go with one or the other. But if you're writing something that isn't hardware dependent (driver, video game, etc), I wouldn't worry about the performance of C# (again can't speak about Java). It'll do just fine.

<<<<<<<<<<

Generally, certain generalized arguments might sound cool in specific posts, but don't generally sound certainly credible.

Anyways, to make peace: AOT is great, as is JIT. The only correct answer can be: It depends. And the real smart people know that you can use the best of both worlds anyways.

Retrieving values from nested JSON Object

To see all keys of Jsonobject use this

    String JSON = "{\"LanguageLevels\":{\"1\":\"Pocz\\u0105tkuj\\u0105cy\",\"2\":\"\\u015arednioZaawansowany\",\"3\":\"Zaawansowany\",\"4\":\"Ekspert\"}}\n";
    JSONObject obj = new JSONObject(JSON);
    Iterator iterator = obj.keys();
    String key = null;
    while (iterator.hasNext()) {
        key = (String) iterator.next();
        System.out.pritnln(key);
    } 

How to validate domain name in PHP?

Your regular expression is fine, but you're not using preg_match right. It returns an int (0 or 1), not a boolean. Just write if(!preg_match($regex, $string)) { ... }

React Native android build failed. SDK location not found

I am on Windows and I had to modify sdk path irrespective of having it in PATH env. variable

sdk.dir=C:/Users/MY_USERNAME/AppData/Local/Android/Sdk

Changed this file:

MyProject\android\local.properties

How can I change the date format in Java?

tl;dr

LocalDate.parse( 
    "23/01/2017" ,  
    DateTimeFormatter.ofPattern( "dd/MM/uuuu" , Locale.UK ) 
).format(
    DateTimeFormatter.ofPattern( "uuuu/MM/dd" , Locale.UK )
)

2017/01/23

Avoid legacy date-time classes

The answer by Christopher Parker is correct but outdated. The troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleTextFormat are now legacy, supplanted by the java.time classes.

Using java.time

Parse the input string as a date-time object, then generate a new String object in the desired format.

The LocalDate class represents a date-only value without time-of-day and without time zone.

DateTimeFormatter fIn = DateTimeFormatter.ofPattern( "dd/MM/uuuu" , Locale.UK );  // As a habit, specify the desired/expected locale, though in this case the locale is irrelevant.
LocalDate ld = LocalDate.parse( "23/01/2017" , fIn );

Define another formatter for the output.

DateTimeFormatter fOut = DateTimeFormatter.ofPattern( "uuuu/MM/dd" , Locale.UK );
String output = ld.format( fOut );

2017/01/23

By the way, consider using standard ISO 8601 formats for strings representing date-time values.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


Joda-Time

UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. This section here is left for the sake of history.

For fun, here is his code adapted for using the Joda-Time library.

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;

final String OLD_FORMAT = "dd/MM/yyyy";
final String NEW_FORMAT = "yyyy/MM/dd";

// August 12, 2010
String oldDateString = "12/08/2010";
String newDateString;

DateTimeFormatter formatterOld = DateTimeFormat.forPattern(OLD_FORMAT);
DateTimeFormatter formatterNew = DateTimeFormat.forPattern(NEW_FORMAT);
LocalDate localDate = formatterOld.parseLocalDate( oldDateString );
newDateString = formatterNew.print( localDate );

Dump to console…

System.out.println( "localDate: " + localDate );
System.out.println( "newDateString: " + newDateString );

When run…

localDate: 2010-08-12
newDateString: 2010/08/12

Is there any boolean type in Oracle databases?

No, there isn't a boolean type in Oracle Database, but you can do this way:

You can put a check constraint on a column.

If your table hasn't a check column, you can add it:

ALTER TABLE table_name
ADD column_name_check char(1) DEFAULT '1';

When you add a register, by default this column get 1.

Here you put a check that limit the column value, just only put 1 or 0

ALTER TABLE table_name ADD
CONSTRAINT name_constraint 
column_name_check (ONOFF in ( '1', '0' ));

How to enable/disable bluetooth programmatically in android

Here is a bit more robust way of doing this, also handling the return values of enable()\disable() methods:

public static boolean setBluetooth(boolean enable) {
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    boolean isEnabled = bluetoothAdapter.isEnabled();
    if (enable && !isEnabled) {
        return bluetoothAdapter.enable(); 
    }
    else if(!enable && isEnabled) {
        return bluetoothAdapter.disable();
    }
    // No need to change bluetooth state
    return true;
}

And add the following permissions into your manifest file:

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

But remember these important points:

This is an asynchronous call: it will return immediately, and clients should listen for ACTION_STATE_CHANGED to be notified of subsequent adapter state changes. If this call returns true, then the adapter state will immediately transition from STATE_OFF to STATE_TURNING_ON, and some time later transition to either STATE_OFF or STATE_ON. If this call returns false then there was an immediate problem that will prevent the adapter from being turned on - such as Airplane mode, or the adapter is already turned on.

UPDATE:

Ok, so how to implement bluetooth listener?:

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();

        if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
            final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
                                                 BluetoothAdapter.ERROR);
            switch (state) {
            case BluetoothAdapter.STATE_OFF:
                // Bluetooth has been turned off;
                break;
            case BluetoothAdapter.STATE_TURNING_OFF:
                // Bluetooth is turning off;
                break;
            case BluetoothAdapter.STATE_ON:
                // Bluetooth is on
                break;
            case BluetoothAdapter.STATE_TURNING_ON:
                // Bluetooth is turning on
                break;
            }
        }
    }
};

And how to register/unregister the receiver? (In your Activity class)

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

    // ...

    // Register for broadcasts on BluetoothAdapter state change
    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    registerReceiver(mReceiver, filter);
}

@Override
public void onStop() {
    super.onStop();

     // ...

    // Unregister broadcast listeners
    unregisterReceiver(mReceiver);
}

How to pass credentials to httpwebrequest for accessing SharePoint Library

You could also use:

request.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; 

Use StringFormat to add a string to a WPF XAML binding

Please note that using StringFormat in Bindings only seems to work for "text" properties. Using this for Label.Content will not work

How can we convert an integer to string in AngularJs

.toString() is available, or just add "" to the end of the int

var x = 3,
    toString = x.toString(),
    toConcat = x + "";

Angular is simply JavaScript at the core.

How to convert JSON string to array

Use json_decode($json_string, TRUE) function to convert the JSON object to an array.

Example:

$json_string   = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

$my_array_data = json_decode($json_string, TRUE);

NOTE: The second parameter will convert decoded JSON string into an associative array.

===========

Output:

var_dump($my_array_data);

array(5) {

    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

HTML button to NOT submit form

I think this is the most annoying little peculiarity of HTML... That button needs to be of type "button" in order to not submit.

<button type="button">My Button</button>

Update 5-Feb-2019: As per the HTML Living Standard (and also HTML 5 specification):

The missing value default and invalid value default are the Submit Button state.

Converting ArrayList to Array in java

List<String> list=new ArrayList<String>();
list.add("sravan");
list.add("vasu");
list.add("raki");
String names[]=list.toArray(new String[list.size()])

How can I position my div at the bottom of its container?

Using the translateY and top property

Just set element child to position: relative and than move it top: 100% (that's the 100% height of the parent) and stick to bottom of parent by transform: translateY(-100%) (that's -100% of the height of the child).

BenefitS

  • you do not take the element from the page flow
  • it is dynamic

But still just workaround :(

.copyright{
   position: relative;
   top: 100%;
   transform: translateY(-100%);
}

Don't forget prefixes for the older browser.

Embedding VLC plugin on HTML page

I found this:

<embed type="application/x-vlc-plugin"
pluginspage="http://www.videolan.org"version="VideoLAN.VLCPlugin.2"  width="100%"        
height="100%" id="vlc" loop="yes"autoplay="yes" target="http://10.1.2.201:8000/"></embed>

I don't see that in your code anywhere.... I think that's all you need and the target would be the location of your video...

and here is more info on the vlc plugin:
http://wiki.videolan.org/Documentation%3aWebPlugin#Input_object

Another thing to check is that the address for the video file is correct....

Python Tkinter clearing a frame

pack_forget and grid_forget will only remove widgets from view, it doesn't destroy them. If you don't plan on re-using the widgets, your only real choice is to destroy them with the destroy method.

To do that you have two choices: destroy each one individually, or destroy the frame which will cause all of its children to be destroyed. The latter is generally the easiest and most effective.

Since you claim you don't want to destroy the container frame, create a secondary frame. Have this secondary frame be the container for all the widgets you want to delete, and then put this one frame inside the parent you do not want to destroy. Then, it's just a matter of destroying this one frame and all of the interior widgets will be destroyed along with it.

How do I parse JSON with Objective-C?

  1. I recommend and use TouchJSON for parsing JSON.
  2. To answer your comment to Alex. Here's quick code that should allow you to get the fields like activity_details, last_name, etc. from the json dictionary that is returned:

    NSDictionary *userinfo=[jsondic valueforKey:@"#data"];
    NSDictionary *user;
    NSInteger i = 0;
    NSString *skey;
    if(userinfo != nil){
        for( i = 0; i < [userinfo count]; i++ ) {
            if(i)
                skey = [NSString stringWithFormat:@"%d",i];
            else
                skey = @"";
    
            user = [userinfo objectForKey:skey];
            NSLog(@"activity_details:%@",[user objectForKey:@"activity_details"]);
            NSLog(@"last_name:%@",[user objectForKey:@"last_name"]);
            NSLog(@"first_name:%@",[user objectForKey:@"first_name"]);
            NSLog(@"photo_url:%@",[user objectForKey:@"photo_url"]);
        }
    }
    

How do you change the datatype of a column in SQL Server?

Use the Alter table statement.

Alter table TableName Alter Column ColumnName nvarchar(100)

How do synchronized static methods work in Java and can I use it for loading Hibernate entities?

If it is something to do with the data in your database, why not utilize database isolation locking to achieve?

How to linebreak an svg text within javascript?

With the tspan solution, let's say you don't know in advance where to put your line breaks: you can use this nice function, that I found here: http://bl.ocks.org/mbostock/7555321

That automatically does line breaks for long text svg for a given width in pixel.

function wrap(text, width) {
  text.each(function() {
    var text = d3.select(this),
        words = text.text().split(/\s+/).reverse(),
        word,
        line = [],
        lineNumber = 0,
        lineHeight = 1.1, // ems
        y = text.attr("y"),
        dy = parseFloat(text.attr("dy")),
        tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
    while (word = words.pop()) {
      line.push(word);
      tspan.text(line.join(" "));
      if (tspan.node().getComputedTextLength() > width) {
        line.pop();
        tspan.text(line.join(" "));
        line = [word];
        tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
      }
    }
  });
}

Bootstrap control with multiple "data-toggle"

Not yet. However, it has been suggested that someone add this feature one day.

The following bootstrap Github issue shows a perfect example of what you are wishing for. It is possible- but not without writing your own workaround code at this stage though.

Check it out... :-)

https://github.com/twitter/bootstrap/issues/7011

Define: What is a HashSet?

From application perspective, if one needs only to avoid duplicates then HashSet is what you are looking for since it's Lookup, Insert and Remove complexities are O(1) - constant. What this means it does not matter how many elements HashSet has it will take same amount of time to check if there's such element or not, plus since you are inserting elements at O(1) too it makes it perfect for this sort of thing.

Awk if else issues

You forgot braces around the if block, and a semicolon between the statements in the block.

awk '{if($3 != 0) {a = ($3/$4); print $0, a;} else if($3==0) print $0, "-" }' file > out

Setting values on a copy of a slice from a DataFrame

This warning comes because your dataframe x is a copy of a slice. This is not easy to know why, but it has something to do with how you have come to the current state of it.

You can either create a proper dataframe out of x by doing

x = x.copy()

This will remove the warning, but it is not the proper way

You should be using the DataFrame.loc method, as the warning suggests, like this:

x.loc[:,'Mass32s'] = pandas.rolling_mean(x.Mass32, 5).shift(-2)

pandas get rows which are NOT in other dataframe

You can also concat df1, df2:

x = pd.concat([df1, df2])

and then remove all duplicates:

y = x.drop_duplicates(keep=False, inplace=False)

Warning: Attempt to present * on * whose view is not in the window hierarchy - swift

Use of main thread to present and dismiss view controller worked for me.

DispatchQueue.main.async { self.present(viewController, animated: true, completion: nil) }

A good Sorted List for Java

GlazedLists has a very, very good sorted list implementation

Nginx: stat() failed (13: permission denied)

By default the static data, when you install the nginx, will be in /var/www/html. So you can just copy your static folder into /var/html/ and set the

root /var/www/<your static folder>

in ngix.conf (or /etc/nginx/sites-available/default)

This worked for me on ubuntu but I guess it should not be much different for other distros.

Hope it helps.

MyISAM versus InnoDB

A bit late to the game...but here's a quite comprehensive post I wrote a few months back, detailing the major differences between MYISAM and InnoDB. Grab a cuppa (and maybe a biscuit), and enjoy.


The major difference between MyISAM and InnoDB is in referential integrity and transactions. There are also other difference such as locking, rollbacks, and full-text searches.

Referential Integrity

Referential integrity ensures that relationships between tables remains consistent. More specifically, this means when a table (e.g. Listings) has a foreign key (e.g. Product ID) pointing to a different table (e.g. Products), when updates or deletes occur to the pointed-to table, these changes are cascaded to the linking table. In our example, if a product is renamed, the linking table’s foreign keys will also update; if a product is deleted from the ‘Products’ table, any listings which point to the deleted entry will also be deleted. Furthermore, any new listing must have that foreign key pointing to a valid, existing entry.

InnoDB is a relational DBMS (RDBMS) and thus has referential integrity, while MyISAM does not.

Transactions & Atomicity

Data in a table is managed using Data Manipulation Language (DML) statements, such as SELECT, INSERT, UPDATE and DELETE. A transaction group two or more DML statements together into a single unit of work, so either the entire unit is applied, or none of it is.

MyISAM do not support transactions whereas InnoDB does.

If an operation is interrupted while using a MyISAM table, the operation is aborted immediately, and the rows (or even data within each row) that are affected remains affected, even if the operation did not go to completion.

If an operation is interrupted while using an InnoDB table, because it using transactions, which has atomicity, any transaction which did not go to completion will not take effect, since no commit is made.

Table-locking vs Row-locking

When a query runs against a MyISAM table, the entire table in which it is querying will be locked. This means subsequent queries will only be executed after the current one is finished. If you are reading a large table, and/or there are frequent read and write operations, this can mean a huge backlog of queries.

When a query runs against an InnoDB table, only the row(s) which are involved are locked, the rest of the table remains available for CRUD operations. This means queries can run simultaneously on the same table, provided they do not use the same row.

This feature in InnoDB is known as concurrency. As great as concurrency is, there is a major drawback that applies to a select range of tables, in that there is an overhead in switching between kernel threads, and you should set a limit on the kernel threads to prevent the server coming to a halt.

Transactions & Rollbacks

When you run an operation in MyISAM, the changes are set; in InnoDB, those changes can be rolled back. The most common commands used to control transactions are COMMIT, ROLLBACK and SAVEPOINT. 1. COMMIT - you can write multiple DML operations, but the changes will only be saved when a COMMIT is made 2. ROLLBACK - you can discard any operations that have not yet been committed yet 3. SAVEPOINT - sets a point in the list of operations to which a ROLLBACK operation can rollback to

Reliability

MyISAM offers no data integrity - Hardware failures, unclean shutdowns and canceled operations can cause the data to become corrupt. This would require full repair or rebuilds of the indexes and tables.

InnoDB, on the other hand, uses a transactional log, a double-write buffer and automatic checksumming and validation to prevent corruption. Before InnoDB makes any changes, it records the data before the transactions into a system tablespace file called ibdata1. If there is a crash, InnoDB would autorecover through the replay of those logs.

FULLTEXT Indexing

InnoDB does not support FULLTEXT indexing until MySQL version 5.6.4. As of the writing of this post, many shared hosting providers’ MySQL version is still below 5.6.4, which means FULLTEXT indexing is not supported for InnoDB tables.

However, this is not a valid reason to use MyISAM. It’s best to change to a hosting provider that supports up-to-date versions of MySQL. Not that a MyISAM table that uses FULLTEXT indexing cannot be converted to an InnoDB table.

Conclusion

In conclusion, InnoDB should be your default storage engine of choice. Choose MyISAM or other data types when they serve a specific need.

how to evenly distribute elements in a div next to each other?

You just need to display the div with id #menu as flex container like this:

#menu{
    width: 800px;
    display: flex;
    justify-content: space-between;
}

PHP: How to remove all non printable characters in a string?

Many of the other answers here do not take into account unicode characters (e.g. öäüß??îû??????? ). In this case you can use the following:

$string = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/u', '', $string);

There's a strange class of characters in the range \x80-\x9F (Just above the 7-bit ASCII range of characters) that are technically control characters, but over time have been misused for printable characters. If you don't have any problems with these, then you can use:

$string = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/u', '', $string);

If you wish to also strip line feeds, carriage returns, tabs, non-breaking spaces, and soft-hyphens, you can use:

$string = preg_replace('/[\x00-\x1F\x7F-\xA0\xAD]/u', '', $string);

Note that you must use single quotes for the above examples.

If you wish to strip everything except basic printable ASCII characters (all the example characters above will be stripped) you can use:

$string = preg_replace( '/[^[:print:]]/', '',$string);

For reference see http://www.fileformat.info/info/charset/UTF-8/list.htm

$date + 1 year?

There is also a simpler and less sophisticated solution:

$monthDay = date('m/d');
$year = date('Y')+1;
$oneYearFuture = "".$monthDay."/".$year."";
echo"The date one year in the future is: ".$oneYearFuture."";

How to dynamic new Anonymous Class?

Anonymous types are just regular types that are implicitly declared. They have little to do with dynamic.

Now, if you were to use an ExpandoObject and reference it through a dynamic variable, you could add or remove fields on the fly.

edit

Sure you can: just cast it to IDictionary<string, object>. Then you can use the indexer.

You use the same casting technique to iterate over the fields:

dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
employee.Age = 33;

foreach (var property in (IDictionary<string, object>)employee)
{
    Console.WriteLine(property.Key + ": " + property.Value);
}
// This code example produces the following output:
// Name: John Smith
// Age: 33

The above code and more can be found by clicking on that link.

add created_at and updated_at fields to mongoose schemas

I actually do this in the back

If all goes well with the updating:

 // All ifs passed successfully. Moving on the Model.save
    Model.lastUpdated = Date.now(); // <------ Now!
    Model.save(function (err, result) {
      if (err) {
        return res.status(500).json({
          title: 'An error occured',
          error: err
        });
      }
      res.status(200).json({
        message: 'Model Updated',
        obj: result
      });
    });

Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type

TypeScript is basically implementing rules and adding types to your code to make it more clear and more accurate due to the lack of constraints in Javascript. TypeScript requires you to describe your data, so that the compiler can check your code and find errors. The compiler will let you know if you are using mismatched types, if you are out of your scope or you try to return a different type. So, when you are using external libraries and modules with TypeScript, they need to contain files that describe the types in that code. Those files are called type declaration files with an extension d.ts. Most of the declaration types for npm modules are already written and you can include them using npm install @types/module_name (where module_name is the name of the module whose types you wanna include).

However, there are modules that don't have their type definitions and in order to make the error go away and import the module using import * as module_name from 'module-name', create a folder typings in the root of your project, inside create a new folder with your module name and in that folder create a module_name.d.ts file and write declare module 'module_name'. After this just go to your tsconfig.json file and add "typeRoots": [ "../../typings", "../../node_modules/@types"] in the compilerOptions (with the proper relative path to your folders) to let TypeScript know where it can find the types definitions of your libraries and modules and add a new property "exclude": ["../../node_modules", "../../typings"] to the file. Here is an example of how your tsconfig.json file should look like:

{
    "compilerOptions": {
        "module": "commonjs",
        "noImplicitAny": true,
        "sourceMap": true,
        "outDir": "../dst/",
        "target": "ESNEXT",
        "typeRoots": [
            "../../typings",
            "../../node_modules/@types"
        ]
    },
    "lib": [
            "es2016"
    ],
    "exclude": [
        "../../node_modules",
        "../../typings"
    ]
}

By doing this, the error will go away and you will be able to stick to the latest ES6 and TypeScript rules.

Showing empty view when ListView is empty

When you extend FragmentActivity or Activity and not ListActivity, you'll want to take a look at:

ListView.setEmptyView()

What is the difference among col-lg-*, col-md-* and col-sm-* in Bootstrap?

Device Sizes and class prefix:

  • Extra small devices Phones (<768px) - .col-xs-
  • Small devices Tablets (=768px) - .col-sm-
  • Medium devices Desktops (=992px) - .col-md-
  • Large devices Desktops (=1200px) - .col-lg-

Grid options:

Bootstarp Grid System

Reference: Grid System

C++ int to byte array

Using std::vector<unsigned char>:

#include <vector>
using namespace std;

vector<unsigned char> intToBytes(int paramInt)
{
     vector<unsigned char> arrayOfByte(4);
     for (int i = 0; i < 4; i++)
         arrayOfByte[3 - i] = (paramInt >> (i * 8));
     return arrayOfByte;
}

Is there a way to pass javascript variables in url?

Try this:

 window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat="+elemA+"&lon="+elemB+"&setLatLon=Set";

To put a variable in a string enclose the variable in quotes and addition signs like this:

var myname = "BOB";
var mystring = "Hi there "+myname+"!"; 

Just remember that one rule!

Android Material: Status bar color won't change

This solution sets the statusbar color of Lollipop, Kitkat and some pre Lollipop devices (Samsung and Sony). The SystemBarTintManager is managing the Kitkat devices ;)

@Override
protected void onCreate( Bundle savedInstanceState ) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    hackStatusBarColor(this, R.color.primary_dark);
}

@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
public static View hackStatusBarColor( final Activity act, final int colorResID ) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        try {

            if (act.getWindow() != null) {

                final ViewGroup vg = (ViewGroup) act.getWindow().getDecorView();
                if (vg.getParent() == null && applyColoredStatusBar(act, colorResID)) {
                    final View statusBar = new View(act);

                    vg.post(new Runnable() {
                        @Override
                        public void run() {

                            int statusBarHeight = (int) Math.ceil(25 * vg.getContext().getResources().getDisplayMetrics().density);
                            statusBar.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, statusBarHeight));
                            statusBar.setBackgroundColor(act.getResources().getColor(colorResID));
                            statusBar.setId(13371337);
                            vg.addView(statusBar, 0);
                        }
                    });
                    return statusBar;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    else if (act.getWindow() != null) {
        act.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        act.getWindow().setStatusBarColor(act.getResources().getColor(colorResID));
    }
    return null;
}

private static boolean applyColoredStatusBar( Activity act, int colorResID ) {
    final Window window = act.getWindow();
    final int flag;
    if (window != null) {
        View decor = window.getDecorView();
        if (decor != null) {
            flag = resolveTransparentStatusBarFlag(act);

            if (flag != 0) {
                decor.setSystemUiVisibility(flag);
                return true;
            }
            else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
                act.findViewById(android.R.id.content).setFitsSystemWindows(false);
                setTranslucentStatus(window, true);
                final SystemBarTintManager tintManager = new SystemBarTintManager(act);
                tintManager.setStatusBarTintEnabled(true);
                tintManager.setStatusBarTintColor(colorResID);
            }
        }
    }
    return false;
}

public static int resolveTransparentStatusBarFlag( Context ctx ) {
    String[] libs = ctx.getPackageManager().getSystemSharedLibraryNames();
    String reflect = null;

    if (libs == null)
        return 0;

    final String SAMSUNG = "touchwiz";
    final String SONY = "com.sonyericsson.navigationbar";

    for (String lib : libs) {

        if (lib.equals(SAMSUNG)) {
            reflect = "SYSTEM_UI_FLAG_TRANSPARENT_BACKGROUND";
        }
        else if (lib.startsWith(SONY)) {
            reflect = "SYSTEM_UI_FLAG_TRANSPARENT";
        }
    }

    if (reflect == null)
        return 0;

    try {
        Field field = View.class.getField(reflect);
        if (field.getType() == Integer.TYPE) {
            return field.getInt(null);
        }
    } catch (Exception e) {
    }

    return 0;
}

@TargetApi(Build.VERSION_CODES.KITKAT)
public static void setTranslucentStatus( Window win, boolean on ) {
    WindowManager.LayoutParams winParams = win.getAttributes();
    final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
    if (on) {
        winParams.flags |= bits;
    }
    else {
        winParams.flags &= ~bits;
    }
    win.setAttributes(winParams);
}

How to cin to a vector

you have 2 options:

If you know the size of vector will be (in your case/example it's seems you know it):

vector<int> V(size)
for(int i =0;i<size;i++){
    cin>>V[i];
 }

if you don't and you can't get it in you'r program flow then:

int helper;
while(cin>>helper){
    V.push_back(helper);
}

How to load images dynamically (or lazily) when users scrolls them into view

Im using jQuery Lazy. It took me about 10 minutes to test out and an hour or two to add to most of the image links on one of my websites (CollegeCarePackages.com). I have NO (none/zero) relationship of any kind to the dev, but it saved me a lot of time and basically helped improve our bounce rate for mobile users and I appreciate it.

Junit - run set up method once

When setUp() is in a superclass of the test class (e.g. AbstractTestBase below), the accepted answer can be modified as follows:

public abstract class AbstractTestBase {
    private static Class<? extends AbstractTestBase> testClass;
    .....
    public void setUp() {
        if (this.getClass().equals(testClass)) {
            return;
        }

        // do the setup - once per concrete test class
        .....
        testClass = this.getClass();
    }
}

This should work for a single non-static setUp() method but I'm unable to produce an equivalent for tearDown() without straying into a world of complex reflection... Bounty points to anyone who can!

Warp \ bend effect on a UIView?

What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.

I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)

How to post raw body data with curl?

curl's --data will by default send Content-Type: application/x-www-form-urlencoded in the request header. However, when using Postman's raw body mode, Postman sends Content-Type: text/plain in the request header.

So to achieve the same thing as Postman, specify -H "Content-Type: text/plain" for curl:

curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/

Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network tab :

enter image description here

CAST to DECIMAL in MySQL

DECIMAL has two parts: Precision and Scale. So part of your query will look like this:

CAST((COUNT(*) * 1.5) AS DECIMAL(8,2))

Precision represents the number of significant digits that are stored for values.
Scale represents the number of digits that can be stored following the decimal point.

How to initialize an array's length in JavaScript?

The array constructor has an ambiguous syntax, and JSLint just hurts your feelings after all.

Also, your example code is broken, the second var statement will raise a SyntaxError. You're setting the property length of the array test, so there's no need for another var.

As far as your options go, array.length is the only "clean" one. Question is, why do you need to set the size in the first place? Try to refactor your code to get rid of that dependency.

Counting in a FOR loop using Windows Batch script

It's not working because the entire for loop (from the for to the final closing parenthesis, including the commands between those) is being evaluated when it's encountered, before it begins executing.

In other words, %count% is replaced with its value 1 before running the loop.

What you need is something like:

setlocal enableextensions enabledelayedexpansion
set /a count = 1
for /f "tokens=*" %%a in (config.properties) do (
  set /a count += 1
  echo !count!
)
endlocal

Delayed expansion using ! instead of % will give you the expected behaviour. See also here.


Also keep in mind that setlocal/endlocal actually limit scope of things changed inside so that they don't leak out. If you want to use count after the endlocal, you have to use a "trick" made possible by the very problem you're having:

endlocal && set count=%count%

Let's say count has become 7 within the inner scope. Because the entire command is interpreted before execution, it effectively becomes:

endlocal && set count=7

Then, when it's executed, the inner scope is closed off, returning count to it's original value. But, since the setting of count to seven happens in the outer scope, it's effectively leaking the information you need.

You can string together multiple sub-commands to leak as much information as you need:

endlocal && set count=%count% && set something_else=%something_else%

jQuery Refresh/Reload Page if Ajax Success after time

Lots of good answers here, just out of curiosity after looking into this today, is it not best to use setInterval rather than the setTimeout?

setInterval(function() {
location.reload();
}, 30000);

let me know you thoughts.

Xcode 4 - "Archive" is greyed out?

You have to select the device in the schemes menu in the top left where you used to select between simulator/device. It won’t let you archive a build for the simulator.

Or you may find that if the iOS device is already selected the archive box isn’t selected when you choose “Edit Schemes” => “Build”.

How to use SharedPreferences in Android to store, fetch and edit values

Using this simple library, here is how you make the calls to SharedPreferences..

TinyDB tinydb = new TinyDB(context);

tinydb.putInt("clickCount", 2);

tinydb.putString("userName", "john");
tinydb.putBoolean("isUserMale", true); 

tinydb.putList("MyUsers", mUsersArray);
tinydb.putImagePNG("DropBox/WorkImages", "MeAtlunch.png", lunchBitmap);

//These plus the corresponding get methods are all Included

Python Iterate Dictionary by Index

You can iterate over keys and get values by keys:

for key in dict.iterkeys():
    print key, dict[key]

You can iterate over keys and corresponding values:

for key, value in dict.iteritems():
    print key, value

You can use enumerate if you want indexes (remember that dictionaries don't have an order):

>>> for index, key in enumerate(dict):
...     print index, key
... 
0 orange
1 mango
2 apple
>>> 

How can I create an error 404 in PHP?

try this once.

$wp_query->set_404();
status_header(404);
get_template_part('404'); 

How to custom switch button?

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

enter image description here

enter image description here

Invert colors of an image in CSS or JavaScript

CSS3 has a new filter attribute which will only work in webkit browsers supported in webkit browsers and in Firefox. It does not have support in IE or Opera mini:

_x000D_
_x000D_
img {_x000D_
   -webkit-filter: invert(1);_x000D_
   filter: invert(1);_x000D_
   }
_x000D_
<img src="http://i.imgur.com/1H91A5Y.png">
_x000D_
_x000D_
_x000D_

How can I create an Asynchronous function in Javascript?

Function.prototype.applyAsync = function(params, cb){
      var function_context = this;
      setTimeout(function(){
          var val = function_context.apply(undefined, params); 
          if(cb) cb(val);
      }, 0);
}

// usage
var double = function(n){return 2*n;};
var display = function(){console.log(arguments); return undefined;};
double.applyAsync([3], display);

Although not fundamentally different than the other solutions, I think my solution does a few additional nice things:

  • it allows for parameters to the functions
  • it passes the output of the function to the callback
  • it is added to Function.prototype allowing a nicer way to call it

Also, the similarity to the built-in function Function.prototype.apply seems appropriate to me.

Git: Create a branch from unstaged/uncommitted changes on master

Two things you can do:

git checkout -b sillyname
git commit -am "silly message"
git checkout - 

or

git stash -u
git branch sillyname stash@{0}

(git checkout - <-- the dash is a shortcut for the previous branch you were on )

(git stash -u <-- the -u means that it also takes unstaged changes )

HttpServletRequest get JSON POST data

Normaly you can GET and POST parameters in a servlet the same way:

request.getParameter("cmd");

But only if the POST data is encoded as key-value pairs of content type: "application/x-www-form-urlencoded" like when you use a standard HTML form.

If you use a different encoding schema for your post data, as in your case when you post a json data stream, you need to use a custom decoder that can process the raw datastream from:

BufferedReader reader = request.getReader();

Json post processing example (uses org.json package )

public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

  StringBuffer jb = new StringBuffer();
  String line = null;
  try {
    BufferedReader reader = request.getReader();
    while ((line = reader.readLine()) != null)
      jb.append(line);
  } catch (Exception e) { /*report an error*/ }

  try {
    JSONObject jsonObject =  HTTP.toJSONObject(jb.toString());
  } catch (JSONException e) {
    // crash and burn
    throw new IOException("Error parsing JSON request string");
  }

  // Work with the data using methods like...
  // int someInt = jsonObject.getInt("intParamName");
  // String someString = jsonObject.getString("stringParamName");
  // JSONObject nestedObj = jsonObject.getJSONObject("nestedObjName");
  // JSONArray arr = jsonObject.getJSONArray("arrayParamName");
  // etc...
}

How to send a correct authorization header for basic authentication

Per https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding and http://en.wikipedia.org/wiki/Basic_access_authentication , here is how to do Basic auth with a header instead of putting the username and password in the URL. Note that this still doesn't hide the username or password from anyone with access to the network or this JS code (e.g. a user executing it in a browser):

$.ajax({
  type: 'POST',
  url: http://theappurl.com/api/v1/method/,
  data: {},
  crossDomain: true,
  beforeSend: function(xhr) {
    xhr.setRequestHeader('Authorization', 'Basic ' + btoa(unescape(encodeURIComponent(YOUR_USERNAME + ':' + YOUR_PASSWORD))))
  }
});

How to search for string in an array

Another option that enforces exact matching (i.e. no partial matching) would be:

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
  IsInArray = Not IsError(Application.Match(stringToBeFound, arr, 0))
End Function

You can read more about the Match method and its arguments at http://msdn.microsoft.com/en-us/library/office/ff835873(v=office.15).aspx

AngularJS - Access to child scope

Scopes in AngularJS use prototypal inheritance, when looking up a property in a child scope the interpreter will look up the prototype chain starting from the child and continue to the parents until it finds the property, not the other way around.

Check Vojta's comments on the issue https://groups.google.com/d/msg/angular/LDNz_TQQiNE/ygYrSvdI0A0J

In a nutshell: You cannot access child scopes from a parent scope.

Your solutions:

  1. Define properties in parents and access them from children (read the link above)
  2. Use a service to share state
  3. Pass data through events. $emit sends events upwards to parents until the root scope and $broadcast dispatches events downwards. This might help you to keep things semantically correct.

Unprotect workbook without password

No longer works for spreadsheets Protected with Excel 2013 or later -- they improved the pw hash. So now need to unzip .xlsx and hack the internals.

LF will be replaced by CRLF in git - What is that and is it important?

If you want, you can deactivate this feature in your git core config using

git config core.autocrlf false

But it would be better to just get rid of the warnings using

git config core.autocrlf true

How to run cron once, daily at 10pm

Here is what I look at everytime I am writing a new crontab entry:

To start editing from terminal -type:

 zee$ crontab -e

what you will add to crontab file:

0 22 * * 0  some-user /opt/somescript/to/run.sh

What it means:

[ 
+ user => 'some-user',      
+ minute => ‘0’,             <<= on top of the hour.
+ hour => '22',              <<= at 10 PM. Military time.
+ monthday => '*',           <<= Every day of the month*
+ month => '*',              <<= Every month*
+ weekday => ‘0’,            <<= Everyday (0 thru 6) = sunday thru saturday
] 

Also, check what shell your machine is running and name the the file accordingly OR it wont execute.

Check the shell with either echo $SHELL or echo $0

It can be "Bourne shell (sh) , Bourne again shell (bash),Korn shell (ksh)..etc"

Simple IEnumerator use (with example)

I'd do something like:

private IEnumerable<string> DoWork(IEnumerable<string> data)
{
    List<string> newData = new List<string>();
    foreach(string item in data)
    {
        newData.Add(item + "roxxors");
    }
    return newData;
}

Simple stuff :)

Hex transparency in colors

I realize this is an old question, but I came across it when doing something similar.

Using SASS, you have a very elegant way to convert RGBA to hex ARGB: ie-hex-str. I've used it here in a mixin.

@mixin ie8-rgba ($r, $g, $b, $a){
    $rgba: rgba($r, $g, $b, $a);
    $ie8-rgba: ie-hex-str($rgba);
    .lt-ie9 &{
      background-color: transparent;
      filter:progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#{$ie8-rgba}', endColorstr='#{$ie8-rgba}');
  }
}

.transparent{
    @include ie8-rgba(88,153,131,.8);
    background-color: rgba(88,153,131,.8);
}

outputs:

_x000D_
_x000D_
.transparent {_x000D_
  background-color: rgba(88, 153, 131, 0.8);_x000D_
}_x000D_
.lt-ie9 .transparent {_x000D_
  background-color: transparent;_x000D_
  filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#CC589983', endColorstr='#CC589983');_x000D_
  zoom: 1;_x000D_
}
_x000D_
_x000D_
_x000D_

Accessing JSON elements

Here's an alternative solution using requests:

import requests
wjdata = requests.get('url').json()
print wjdata['data']['current_condition'][0]['temp_C']

JPA getSingleResult() or null

Here's another extension, this time in Scala.

customerQuery.getSingleOrNone match {
  case Some(c) => // ...
  case None    => // ...
}

With this pimp:

import javax.persistence.{NonUniqueResultException, TypedQuery}
import scala.collection.JavaConversions._

object Implicits {

  class RichTypedQuery[T](q: TypedQuery[T]) {

    def getSingleOrNone : Option[T] = {

      val results = q.setMaxResults(2).getResultList

      if (results.isEmpty)
        None
      else if (results.size == 1)
        Some(results.head)
      else
        throw new NonUniqueResultException()
    }
  }

  implicit def query2RichQuery[T](q: TypedQuery[T]) = new RichTypedQuery[T](q)
}

How to create full compressed tar file using Python?

To build a .tar.gz (aka .tgz) for an entire directory tree:

import tarfile
import os.path

def make_tarfile(output_filename, source_dir):
    with tarfile.open(output_filename, "w:gz") as tar:
        tar.add(source_dir, arcname=os.path.basename(source_dir))

This will create a gzipped tar archive containing a single top-level folder with the same name and contents as source_dir.

What's the easiest way to call a function every 5 seconds in jQuery?

The functions mentioned above execute no matter if it has completed in previous invocation or not, this one runs after every x seconds once the execution is complete

// IIFE
(function runForever(){
  // Do something here
  setTimeout(runForever, 5000)
})()

// Regular function with arguments
function someFunction(file, directory){
  // Do something here
  setTimeout(someFunction, 5000, file, directory)
  // YES, setTimeout passes any extra args to
  // function being called
}

Eclipse/Maven error: "No compiler is provided in this environment"

Screen_shot Add 'tools.jar' to installed JRE.

  1. Eclipse -> window -> preference.
  2. Select installed JREs -> Edit
  3. Add External Jars
  4. select tools.jar from java/JDKx.x/lib folder.
  5. Click Finish

Database development mistakes made by application developers

I hate it when developers use nested select statements or even functions the return the result of a select statement inside the "SELECT" portion of a query.

I'm actually surprised I don't see this anywhere else here, perhaps I overlooked it, although @adam has a similar issue indicated.

Example:

SELECT
    (SELECT TOP 1 SomeValue FROM SomeTable WHERE SomeDate = c.Date ORDER BY SomeValue desc) As FirstVal
    ,(SELECT OtherValue FROM SomeOtherTable WHERE SomeOtherCriteria = c.Criteria) As SecondVal
FROM
    MyTable c

In this scenario, if MyTable returns 10000 rows the result is as if the query just ran 20001 queries, since it had to run the initial query plus query each of the other tables once for each line of result.

Developers can get away with this working in a development environment where they are only returning a few rows of data and the sub tables usually only have a small amount of data, but in a production environment, this kind of query can become exponentially costly as more data is added to the tables.

A better (not necessarily perfect) example would be something like:

SELECT
     s.SomeValue As FirstVal
    ,o.OtherValue As SecondVal
FROM
    MyTable c
    LEFT JOIN (
        SELECT SomeDate, MAX(SomeValue) as SomeValue
        FROM SomeTable 
        GROUP BY SomeDate
     ) s ON c.Date = s.SomeDate
    LEFT JOIN SomeOtherTable o ON c.Criteria = o.SomeOtherCriteria

This allows database optimizers to shuffle the data together, rather than requery on each record from the main table and I usually find when I have to fix code where this problem has been created, I usually end up increasing the speed of queries by 100% or more while simultaneously reducing CPU and memory usage.

Android Layout Right Align

This is an example for a RelativeLayout:

RelativeLayout relativeLayout=(RelativeLayout)vi.findViewById(R.id.RelativeLayoutLeft);
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)relativeLayout.getLayoutParams();
                params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                relativeLayout.setLayoutParams(params);

With another kind of layout (example LinearLayout) you just simply has to change RelativeLayout for LinearLayout.

Sleep function in C++

For Windows:

#include "windows.h" 
Sleep(10);

For Unix:

#include <unistd.h>
usleep(10)

Passing variables through handlebars partial

This can also be done in later versions of handlebars using the key=value notation:

 {{> mypartial foo='bar' }}

Allowing you to pass specific values to your partial context.

Reference: Context different for partial #182

How to generate Javadoc from command line

Let's say you have the following directory structure where you want to generate javadocs on file1.java and file2.java (package com.test), with the javadocs being placed in C:\javadoc\test:

C:\
|
+--javadoc\
|  |
|  +--test\
|
+--projects\
   |
   +--com\
      |
      +--test\
         |
         +--file1.java
         +--file2.java

In the command terminal, navigate to the root of your package: C:\projects. If you just want to generate the standard javadocs on all the java files inside the project, run the following command (for multiple packages, separate the package names by spaces):

C:\projects> javadoc -d [path to javadoc destination directory] [package name]

C:\projects> javadoc -d C:\javadoc\test com.test

If you want to run javadocs from elsewhere, you'll need to specify the sourcepath. For example, if you were to run javadocs in in C:\, you would modify the command as such:

C:\> javadoc -d [path to javadoc destination directory] -sourcepath [path to package directory] [package name]

C:\> javadoc -d C:\javadoc\test -sourcepath C:\projects com.test

If you want to run javadocs on only selected .java files, then add the source filenames separated by spaces (you can use an asterisk (*) for a wildcard). Make sure to include the path to the files:

C:\> javadoc -d [path to javadoc destination directory] [source filenames]

C:\> javadoc -d C:\javadoc\test C:\projects\com\test\file1.java

More information/scenarios can be found here.

Mockito : doAnswer Vs thenReturn

doAnswer and thenReturn do the same thing if:

  1. You are using Mock, not Spy
  2. The method you're stubbing is returning a value, not a void method.

Let's mock this BookService

public interface BookService {
    String getAuthor();
    void queryBookTitle(BookServiceCallback callback);
}

You can stub getAuthor() using doAnswer and thenReturn.

BookService service = mock(BookService.class);
when(service.getAuthor()).thenReturn("Joshua");
// or..
doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        return "Joshua";
    }
}).when(service).getAuthor();

Note that when using doAnswer, you can't pass a method on when.

// Will throw UnfinishedStubbingException
doAnswer(invocation -> "Joshua").when(service.getAuthor());

So, when would you use doAnswer instead of thenReturn? I can think of two use cases:

  1. When you want to "stub" void method.

Using doAnswer you can do some additionals actions upon method invocation. For example, trigger a callback on queryBookTitle.

BookServiceCallback callback = new BookServiceCallback() {
    @Override
    public void onSuccess(String bookTitle) {
        assertEquals("Effective Java", bookTitle);
    }
};
doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        BookServiceCallback callback = (BookServiceCallback) invocation.getArguments()[0];
        callback.onSuccess("Effective Java");
        // return null because queryBookTitle is void
        return null;
    }
}).when(service).queryBookTitle(callback);
service.queryBookTitle(callback);
  1. When you are using Spy instead of Mock

When using when-thenReturn on Spy Mockito will call real method and then stub your answer. This can cause a problem if you don't want to call real method, like in this sample:

List list = new LinkedList();
List spy = spy(list);
// Will throw java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
when(spy.get(0)).thenReturn("java");
assertEquals("java", spy.get(0));

Using doAnswer we can stub it safely.

List list = new LinkedList();
List spy = spy(list);
doAnswer(invocation -> "java").when(spy).get(0);
assertEquals("java", spy.get(0));

Actually, if you don't want to do additional actions upon method invocation, you can just use doReturn.

List list = new LinkedList();
List spy = spy(list);
doReturn("java").when(spy).get(0);
assertEquals("java", spy.get(0));

Get the latest record with filter in Django

obj= Model.objects.filter(testfield=12).order_by('-id')[:1] is the right solution

Swipe ListView item From right to left show delete button

I used to have the same problem finding a good library to do that. Eventually, I created a library which can do that: SwipeRevealLayout

In gradle file:

dependencies {
    compile 'com.chauthai.swipereveallayout:swipe-reveal-layout:1.4.0'
}

In your xml file:

<com.chauthai.swipereveallayout.SwipeRevealLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:mode="same_level"
    app:dragEdge="left">

    <!-- Your secondary layout here -->
    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent" />

    <!-- Your main layout here -->
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</com.chauthai.swipereveallayout.SwipeRevealLayout>

Then in your adapter file:

public class Adapter extends RecyclerView.Adapter {
  // This object helps you save/restore the open/close state of each view
  private final ViewBinderHelper viewBinderHelper = new ViewBinderHelper();

  @Override
  public void onBindViewHolder(ViewHolder holder, int position) {
    // get your data object first.
    YourDataObject dataObject = mDataSet.get(position); 

    // Save/restore the open/close state.
    // You need to provide a String id which uniquely defines the data object.
    viewBinderHelper.bind(holder.swipeRevealLayout, dataObject.getId()); 

    // do your regular binding stuff here
  }
}

Is it possible to wait until all javascript files are loaded before executing javascript code?

Expanding a bit on @Eruant's answer,

$(window).on('load', function() {
    // your code here
});

Works very well with both async and defer while loading on scripts.

So you can import all scripts like this:

<script src="/js/script1.js" async defer></script>
<script src="/js/script2.js" async defer></script>
<script src="/js/script3.js" async defer></script>

Just make sure script1 doesn't call functions from script3 before $(window).on('load' ..., make sure to call them inside window load event.

More about async/defer here.

ASP.NET MVC Ajax Error handling

For handling errors from ajax calls on the client side, you assign a function to the error option of the ajax call.

To set a default globally, you can use the function described here: http://api.jquery.com/jQuery.ajaxSetup.

How to remove square brackets in string using regex?

Use this regular expression to match square brackets or single quotes:

/[\[\]']+/g

Replace with the empty string.

_x000D_
_x000D_
console.log("['abc','xyz']".replace(/[\[\]']+/g,''));
_x000D_
_x000D_
_x000D_

How to make Bitmap compress without change the bitmap size?

Are you sure it is smaller?

Bitmap original = BitmapFactory.decodeStream(getAssets().open("1024x768.jpg"));
ByteArrayOutputStream out = new ByteArrayOutputStream();
original.compress(Bitmap.CompressFormat.PNG, 100, out);
Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));

Log.e("Original   dimensions", original.getWidth()+" "+original.getHeight());
Log.e("Compressed dimensions", decoded.getWidth()+" "+decoded.getHeight());

Gives

12-07 17:43:36.333: E/Original   dimensions(278): 1024 768
12-07 17:43:36.333: E/Compressed dimensions(278): 1024 768

Maybe you get your bitmap from a resource, in which case the bitmap dimension will depend on the phone screen density

Bitmap bitmap=((BitmapDrawable)getResources().getDrawable(R.drawable.img_1024x768)).getBitmap();
Log.e("Dimensions", bitmap.getWidth()+" "+bitmap.getHeight());

12-07 17:43:38.733: E/Dimensions(278): 768 576

View tabular file such as CSV from command line

My FOSS project CSVfix allows you to display CSV files in "ASCII art" table format.

Meaning of - <?xml version="1.0" encoding="utf-8"?>

This is the XML optional preamble.

  • version="1.0" means that this is the XML standard this file conforms to
  • encoding="utf-8" means that the file is encoded using the UTF-8 Unicode encoding