Programs & Examples On #Windows principal

SQL join on multiple columns in same tables

You want to join on condition 1 AND condition 2, so simply use the AND keyword as below

ON a.userid = b.sourceid AND a.listid = b.destinationid;

avrdude: stk500v2_ReceiveMessage(): timeout

I had the same problem, and in my case, the solution was updating the usb-serial driver using windows update on windows 10 device's manager. There was no need to download a especific driver, I just let windows update find a suitable driver.

Parsing domain from a URL

Please consider replacring the accepted solution with the following:

parse_url() will always include any sub-domain(s), so this function doesn't parse domain names very well. Here are some examples:

$url = 'http://www.google.com/dhasjkdas/sadsdds/sdda/sdads.html';
$parse = parse_url($url);
echo $parse['host']; // prints 'www.google.com'

echo parse_url('https://subdomain.example.com/foo/bar', PHP_URL_HOST);
// Output: subdomain.example.com

echo parse_url('https://subdomain.example.co.uk/foo/bar', PHP_URL_HOST);
// Output: subdomain.example.co.uk

Instead, you may consider this pragmatic solution. It will cover many, but not all domain names -- for instance, lower-level domains such as 'sos.state.oh.us' are not covered.

function getDomain($url) {
    $host = parse_url($url, PHP_URL_HOST);

    if(filter_var($host,FILTER_VALIDATE_IP)) {
        // IP address returned as domain
        return $host; //* or replace with null if you don't want an IP back
    }

    $domain_array = explode(".", str_replace('www.', '', $host));
    $count = count($domain_array);
    if( $count>=3 && strlen($domain_array[$count-2])==2 ) {
        // SLD (example.co.uk)
        return implode('.', array_splice($domain_array, $count-3,3));
    } else if( $count>=2 ) {
        // TLD (example.com)
        return implode('.', array_splice($domain_array, $count-2,2));
    }
}

// Your domains
    echo getDomain('http://google.com/dhasjkdas/sadsdds/sdda/sdads.html'); // google.com
    echo getDomain('http://www.google.com/dhasjkdas/sadsdds/sdda/sdads.html'); // google.com
    echo getDomain('http://google.co.uk/dhasjkdas/sadsdds/sdda/sdads.html'); // google.co.uk

// TLD
    echo getDomain('https://shop.example.com'); // example.com
    echo getDomain('https://foo.bar.example.com'); // example.com
    echo getDomain('https://www.example.com'); // example.com
    echo getDomain('https://example.com'); // example.com

// SLD
    echo getDomain('https://more.news.bbc.co.uk'); // bbc.co.uk
    echo getDomain('https://www.bbc.co.uk'); // bbc.co.uk
    echo getDomain('https://bbc.co.uk'); // bbc.co.uk

// IP
    echo getDomain('https://1.2.3.45');  // 1.2.3.45

Finally, Jeremy Kendall's PHP Domain Parser allows you to parse the domain name from a url. League URI Hostname Parser will also do the job.

How do I use 'git reset --hard HEAD' to revert to a previous commit?

First, it's always worth noting that git reset --hard is a potentially dangerous command, since it throws away all your uncommitted changes. For safety, you should always check that the output of git status is clean (that is, empty) before using it.

Initially you say the following:

So I know that Git tracks changes I make to my application, and it holds on to them until I commit the changes, but here's where I'm hung up:

That's incorrect. Git only records the state of the files when you stage them (with git add) or when you create a commit. Once you've created a commit which has your project files in a particular state, they're very safe, but until then Git's not really "tracking changes" to your files. (for example, even if you do git add to stage a new version of the file, that overwrites the previously staged version of that file in the staging area.)

In your question you then go on to ask the following:

When I want to revert to a previous commit I use: git reset --hard HEAD And git returns: HEAD is now at 820f417 micro

How do I then revert the files on my hard drive back to that previous commit?

If you do git reset --hard <SOME-COMMIT> then Git will:

  • Make your current branch (typically master) back to point at <SOME-COMMIT>.
  • Then make the files in your working tree and the index ("staging area") the same as the versions committed in <SOME-COMMIT>.

HEAD points to your current branch (or current commit), so all that git reset --hard HEAD will do is to throw away any uncommitted changes you have.

So, suppose the good commit that you want to go back to is f414f31. (You can find that via git log or any history browser.) You then have a few different options depending on exactly what you want to do:

  • Change your current branch to point to the older commit instead. You could do that with git reset --hard f414f31. However, this is rewriting the history of your branch, so you should avoid it if you've shared this branch with anyone. Also, the commits you did after f414f31 will no longer be in the history of your master branch.
  • Create a new commit that represents exactly the same state of the project as f414f31, but just adds that on to the history, so you don't lose any history. You can do that using the steps suggested in this answer - something like:

    git reset --hard f414f31
    git reset --soft HEAD@{1}
    git commit -m "Reverting to the state of the project at f414f31"
    

Error while trying to retrieve text for error ORA-01019

Well,

Just worked it out. While having both installations we have two ORACLE_HOME directories and both have SQAORA32.dll files. While looking up for ORACLE_HOMe my app was getting confused..I just removed the Client oracle home entry as oracle client is by default present in oracle DB Now its working...Thanks!!

ValidateAntiForgeryToken purpose, explanation and example

Microsoft provides us built-in functionality which we use in our application for security purposes, so no one can hack our site or invade some critical information.

From Purpose Of ValidateAntiForgeryToken In MVC Application by Harpreet Singh:

Use of ValidateAntiForgeryToken

Let’s try with a simple example to understand this concept. I do not want to make it too complicated, that’s why I am going to use a template of an MVC application, already available in Visual Studio. We will do this step by step. Let’s start.

  1. Step 1 - Create two MVC applications with default internet template and give those names as CrossSite_RequestForgery and Attack_Application respectively.

  2. Now, open CrossSite_RequestForgery application's Web Config and change the connection string with the one given below and then save.

`

<connectionStrings> <add name="DefaultConnection" connectionString="Data Source=local\SQLEXPRESS;Initial Catalog=CSRF;
Integrated Security=true;" providerName="System.Data.SqlClient" /> 
 </connectionStrings>
  1. Now, click on Tools >> NuGet Package Manager, then Package Manager Console

  2. Now, run the below mentioned three commands in Package Manager Console to create the database.

Enable-Migrations add-migration first update-database

Important Notes - I have created database with code first approach because I want to make this example in the way developers work. You can create database manually also. It's your choice.

  1. Now, open Account Controller. Here, you will see a register method whose type is post. Above this method, there should be an attribute available as [ValidateAntiForgeryToken]. Comment this attribute. Now, right click on register and click go to View. There again, you will find an html helper as @Html.AntiForgeryToken() . Comment this one also. Run the application and click on register button. The URL will be open as:

http://localhost:52269/Account/Register

Notes- I know now the question being raised in all readers’ minds is why these two helpers need to be commented, as everyone knows these are used to validate request. Then, I just want to let you all know that this is just because I want to show the difference after and before applying these helpers.

  1. Now, open the second application which is Attack_Application. Then, open Register method of Account Controller. Just change the POST method with the simple one, shown below.

    Registration Form
    1. @Html.LabelFor(m => m.UserName) @Html.TextBoxFor(m => m.UserName)
    2. @Html.LabelFor(m => m.Password) @Html.PasswordFor(m => m.Password)
    3. @Html.LabelFor(m => m.ConfirmPassword) @Html.PasswordFor(m => m.ConfirmPassword)

7.Now, suppose you are a hacker and you know the URL from where you can register user in CrossSite_RequestForgery application. Now, you created a Forgery site as Attacker_Application and just put the same URL in post method.

8.Run this application now and fill the register fields and click on register. You will see you are registered in CrossSite_RequestForgery application. If you check the database of CrossSite_RequestForgery application then you will see and entry you have entered.

  1. Important - Now, open CrossSite_RequestForgery application and comment out the token in Account Controller and register the View. Try to register again with the same process. Then, an error will occur as below.

Server Error in '/' Application. ________________________________________ The required anti-forgery cookie "__RequestVerificationToken" is not present.

This is what the concept says. What we add in View i.e. @Html.AntiForgeryToken() generates __RequestVerificationToken on load time and [ValidateAntiForgeryToken] available on Controller method. Match this token on post time. If token is the same, then it means this is a valid request.

How to insert date values into table

insert into run(id,name,dob)values(&id,'&name',[what should I write here?]);

insert into run(id,name,dob)values(&id,'&name',TO_DATE('&dob','YYYY-MM-DD'));

Explicitly calling return in a function or not

Question was: Why is not (explicitly) calling return faster or better, and thus preferable?

There is no statement in R documentation making such an assumption.
The main page ?'function' says:

function( arglist ) expr
return(value)

Is it faster without calling return?

Both function() and return() are primitive functions and the function() itself returns last evaluated value even without including return() function.

Calling return() as .Primitive('return') with that last value as an argument will do the same job but needs one call more. So that this (often) unnecessary .Primitive('return') call can draw additional resources. Simple measurement however shows that the resulting difference is very small and thus can not be the reason for not using explicit return. The following plot is created from data selected this way:

bench_nor2 <- function(x,repeats) { system.time(rep(
# without explicit return
(function(x) vector(length=x,mode="numeric"))(x)
,repeats)) }

bench_ret2 <- function(x,repeats) { system.time(rep(
# with explicit return
(function(x) return(vector(length=x,mode="numeric")))(x)
,repeats)) }

maxlen <- 1000
reps <- 10000
along <- seq(from=1,to=maxlen,by=5)
ret <- sapply(along,FUN=bench_ret2,repeats=reps)
nor <- sapply(along,FUN=bench_nor2,repeats=reps)
res <- data.frame(N=along,ELAPSED_RET=ret["elapsed",],ELAPSED_NOR=nor["elapsed",])

# res object is then visualized
# R version 2.15

Function elapsed time comparison

The picture above may slightly difffer on your platform. Based on measured data, the size of returned object is not causing any difference, the number of repeats (even if scaled up) makes just a very small difference, which in real word with real data and real algorithm could not be counted or make your script run faster.

Is it better without calling return?

Return is good tool for clearly designing "leaves" of code where the routine should end, jump out of the function and return value.

# here without calling .Primitive('return')
> (function() {10;20;30;40})()
[1] 40
# here with .Primitive('return')
> (function() {10;20;30;40;return(40)})()
[1] 40
# here return terminates flow
> (function() {10;20;return();30;40})()
NULL
> (function() {10;20;return(25);30;40})()
[1] 25
> 

It depends on strategy and programming style of the programmer what style he use, he can use no return() as it is not required.

R core programmers uses both approaches ie. with and without explicit return() as it is possible to find in sources of 'base' functions.

Many times only return() is used (no argument) returning NULL in cases to conditially stop the function.

It is not clear if it is better or not as standard user or analyst using R can not see the real difference.

My opinion is that the question should be: Is there any danger in using explicit return coming from R implementation?

Or, maybe better, user writing function code should always ask: What is the effect in not using explicit return (or placing object to be returned as last leaf of code branch) in the function code?

use video as background for div

Pure CSS method

It is possible to center a video inside an element just like a cover sized background-image without JS using the object-fit attribute or CSS Transforms.

2021 answer: object-fit

As pointed in the comments, it is possible to achieve the same result without CSS transform, but using object-fit, which I think it's an even better option for the same result:

_x000D_
_x000D_
.video-container {
    height: 300px;
    width: 300px;
    position: relative;
}

.video-container video {
  width: 100%;
  height: 100%;
  position: absolute;
  object-fit: cover;
  z-index: 0;
}

/* Just styling the content of the div, the *magic* in the previous rules */
.video-container .caption {
  z-index: 1;
  position: relative;
  text-align: center;
  color: #dc0000;
  padding: 10px;
}
_x000D_
<div class="video-container">
    <video autoplay muted loop>
        <source src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4" />
    </video>
    <div class="caption">
      <h2>Your caption here</h2>
    </div>
</div>
_x000D_
_x000D_
_x000D_


Previous answer: CSS Transform

You can set a video as a background to any HTML element easily thanks to transform CSS property.

Note that you can use the transform technique to center vertically and horizontally any HTML element.

_x000D_
_x000D_
.video-container {
  height: 300px;
  width: 300px;
  overflow: hidden;
  position: relative;
}

.video-container video {
  min-width: 100%;
  min-height: 100%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
}

/* Just styling the content of the div, the *magic* in the previous rules */
.video-container .caption {
  z-index: 1;
  position: relative;
  text-align: center;
  color: #dc0000;
  padding: 10px;
}
_x000D_
<div class="video-container">
  <video autoplay muted loop>
    <source src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4" />
  </video>
  <div class="caption">
    <h2>Your caption here</h2>
  </div>
</div>
_x000D_
_x000D_
_x000D_

Running Node.js in apache?

While doing my own server side JS experimentation I ended up using teajs. It conforms to common.js, is based on V8 AND is the only project that I know of that provides 'mod_teajs' apache server module.

In my opinion Node.js server is not production ready and lacks too many features - Apache is battle tested and the right way to do SSJS.

Creating the checkbox dynamically using JavaScript?

You're trying to put a text node inside an input element.

Input elements are empty and can't have children.

...
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "name";
checkbox.value = "value";
checkbox.id = "id";

var label = document.createElement('label')
label.htmlFor = "id";
label.appendChild(document.createTextNode('text for label after checkbox'));

container.appendChild(checkbox);
container.appendChild(label);

Android Gradle plugin 0.7.0: "duplicate files during packaging of APK"

It's more than one error

Under apply plugin: 'android-library'

add this ::

android {
    packagingOptions {
        exclude 'META-INF/ASL2.0'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/NOTICE'
    }
}

In case of duplicate files it's easy, look inside the JAR under the META-INF dir and see what's causing the error. It could be multiple. In my case Couchbase Lite plugin. As you add more plugins, you will need more exceptions

How to set combobox default value?

You can do something like this:

    public myform()
    {
         InitializeComponent(); // this will be called in ComboBox ComboBox = new System.Windows.Forms.ComboBox();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'myDataSet.someTable' table. You can move, or remove it, as needed.
        this.myTableAdapter.Fill(this.myDataSet.someTable);
        comboBox1.SelectedItem = null;
        comboBox1.SelectedText = "--select--";           
    }

What should main() return in C and C++?

The accepted answer appears to be targetted for C++, so I thought I'd add an answer that pertains to C, and this differs in a few ways. There were also some changes made between ISO/IEC 9899:1989 (C90) and ISO/IEC 9899:1999 (C99).

main() should be declared as either:

int main(void)
int main(int argc, char **argv)

Or equivalent. For example, int main(int argc, char *argv[]) is equivalent to the second one. In C90, the int return type can be omitted as it is a default, but in C99 and newer, the int return type may not be omitted.

If an implementation permits it, main() can be declared in other ways (e.g., int main(int argc, char *argv[], char *envp[])), but this makes the program implementation defined, and no longer strictly conforming.

The standard defines 3 values for returning that are strictly conforming (that is, does not rely on implementation defined behaviour): 0 and EXIT_SUCCESS for a successful termination, and EXIT_FAILURE for an unsuccessful termination. Any other values are non-standard and implementation defined. In C90, main() must have an explicit return statement at the end to avoid undefined behaviour. In C99 and newer, you may omit the return statement from main(). If you do, and main() finished, there is an implicit return 0.

Finally, there is nothing wrong from a standards point of view with calling main() recursively from a C program.

ASP.NET MVC: Custom Validation by DataAnnotation

You could write a custom validation attribute:

public class CombinedMinLengthAttribute: ValidationAttribute
{
    public CombinedMinLengthAttribute(int minLength, params string[] propertyNames)
    {
        this.PropertyNames = propertyNames;
        this.MinLength = minLength;
    }

    public string[] PropertyNames { get; private set; }
    public int MinLength { get; private set; }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var properties = this.PropertyNames.Select(validationContext.ObjectType.GetProperty);
        var values = properties.Select(p => p.GetValue(validationContext.ObjectInstance, null)).OfType<string>();
        var totalLength = values.Sum(x => x.Length) + Convert.ToString(value).Length;
        if (totalLength < this.MinLength)
        {
            return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
        }
        return null;
    }
}

and then you might have a view model and decorate one of its properties with it:

public class MyViewModel
{
    [CombinedMinLength(20, "Bar", "Baz", ErrorMessage = "The combined minimum length of the Foo, Bar and Baz properties should be longer than 20")]
    public string Foo { get; set; }
    public string Bar { get; set; }
    public string Baz { get; set; }
}

SQL error "ORA-01722: invalid number"

try this as well, when you have a invalid number error

In this a.emplid is number and b.emplid is an varchar2 so if you got to convert one of the sides

where to_char(a.emplid)=b.emplid

Detecting endianness programmatically in a C++ program

I would do something like this:

bool isBigEndian() {
    static unsigned long x(1);
    static bool result(reinterpret_cast<unsigned char*>(&x)[0] == 0);
    return result;
}

Along these lines, you would get a time efficient function that only does the calculation once.

UINavigationBar Hide back Button Text

The current answer wasn't working. I wanted to remove the title entirely, yet the text "back" wasn't going away.

Go back to the previous view controller and set its title property:

self.title = @" ";

ONLY works when the previous View Controller does not have a title

Passing environment-dependent variables in webpack

Since my Edit on the above post by thevangelist wasn't approved, posting additional information.

If you want to pick value from package.json like a defined version number and access it through DefinePlugin inside Javascript.

{"version": "0.0.1"}

Then, Import package.json inside respective webpack.config, access the attribute using the import variable, then use the attribute in the DefinePlugin.

const PACKAGE = require('../package.json');
const _version = PACKAGE.version;//Picks the version number from package.json

For example certain configuration on webpack.config is using METADATA for DefinePlugin:

const METADATA = webpackMerge(commonConfig({env: ENV}).metadata, {
  host: HOST,
  port: PORT,
  ENV: ENV,
  HMR: HMR,
  RELEASE_VERSION:_version//Version attribute retrieved from package.json
});

new DefinePlugin({
        'ENV': JSON.stringify(METADATA.ENV),
        'HMR': METADATA.HMR,
        'process.env': {
          'ENV': JSON.stringify(METADATA.ENV),
          'NODE_ENV': JSON.stringify(METADATA.ENV),
          'HMR': METADATA.HMR,
          'VERSION': JSON.stringify(METADATA.RELEASE_VERSION)//Setting it for the Scripts usage.
        }
      }),

Access this inside any typescript file:

this.versionNumber = process.env.VERSION;

The smartest way would be like this:

// webpack.config.js
plugins: [
    new webpack.DefinePlugin({
      VERSION: JSON.stringify(require("./package.json").version)
    })
  ]

Thanks to Ross Allen

Iterating over dictionaries using 'for' loops

I have a use case where I have to iterate through the dict to get the key, value pair, also the index indicating where I am. This is how I do it:

d = {'x': 1, 'y': 2, 'z': 3} 
for i, (key, value) in enumerate(d.items()):
   print(i, key, value)

Note that the parentheses around the key, value are important, without them, you'd get an ValueError "not enough values to unpack".

Calculate row means on subset of columns

rowMeans is nice, but if you are still trying to wrap your head around the apply family of functions, this is a good opprotunity to begin understanding it.

DF['Mean'] <- apply(DF[,2:4], 1, mean)

Notice I'm doing a slightly different assignment than the first example. This approach makes it easier to incorporate it into for loops.

How can I make a weak protocol reference in 'pure' Swift (without @objc)

AnyObject is the official way to use a weak reference in Swift.

class MyClass {
    weak var delegate: MyClassDelegate?
}

protocol MyClassDelegate: AnyObject {
}

From Apple:

To prevent strong reference cycles, delegates should be declared as weak references. For more information about weak references, see Strong Reference Cycles Between Class Instances. Marking the protocol as class-only will later allow you to declare that the delegate must use a weak reference. You mark a protocol as being class-only by inheriting from AnyObject, as discussed in Class-Only Protocols.

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html#//apple_ref/doc/uid/TP40014097-CH25-ID276

NOT IN vs NOT EXISTS

I have a table which has about 120,000 records and need to select only those which does not exist (matched with a varchar column) in four other tables with number of rows approx 1500, 4000, 40000, 200. All the involved tables have unique index on the concerned Varchar column.

NOT IN took about 10 mins, NOT EXISTS took 4 secs.

I have a recursive query which might had some untuned section which might have contributed to the 10 mins, but the other option taking 4 secs explains, atleast to me that NOT EXISTS is far better or at least that IN and EXISTS are not exactly the same and always worth a check before going ahead with code.

How to pass an array into a SQL Server stored procedure

CREATE TYPE dumyTable
AS TABLE
(
  RateCodeId int,
  RateLowerRange int,
  RateHigherRange int,
  RateRangeValue int
);
GO
CREATE PROCEDURE spInsertRateRanges
  @dt AS dumyTable READONLY
AS
BEGIN
  SET NOCOUNT ON;

  INSERT  tblRateCodeRange(RateCodeId,RateLowerRange,RateHigherRange,RateRangeValue) 
  SELECT * 
  FROM @dt 
END

CSS selectors ul li a {...} vs ul > li > a {...}

to answer to your second question - performance IS affected - if you are using those selectors with a single (no nested) ul:

<ul>
    <li>jjj</li>
    <li>jjj</li>    
    <li>jjj</li>
</ul>

the child selector ul > li is more performant than ul li because it is more specific. the browser traverse the dom "right to left", so when it finds a li it then looks for a any ul as a parent in the case of a child selector, while it has to traverse the whole dom tree to find any ul ancestors in case of the descendant selector

JavaScript error: "is not a function"

I also hit this error. In my case the root cause was async related (during a codebase refactor): An asynchronous function that builds the object to which the "not a function" function belongs was not awaited, and the subsequent attempt to invoke the function throws the error, example below:

const car = carFactory.getCar();
car.drive() //throws TypeError: drive is not a function

The fix was:

const car = await carFactory.getCar();
car.drive()

Posting this incase it helps anyone else facing this error.

Could not resolve Spring property placeholder

the following property must be added in the gradle.build file

processResources {
    filesMatching("**/*.properties") {
        expand project.properties
    }
}

Additionally, if working with Intellij, the project must be re-imported.

Export MySQL data to Excel in PHP

You can export the data from MySQL to Excel by using this simple code.

<?php
include('db_con.php');


$stmt=$db_con->prepare('select * from books');
$stmt->execute();


$columnHeader ='';
$columnHeader = "Sr NO"."\t"."Book Name"."\t"."Book Author"."\t"."Book 
ISBN"."\t";


$setData='';

while($rec =$stmt->FETCH(PDO::FETCH_ASSOC))
{
 $rowData = '';
 foreach($rec as $value)
 {
  $value = '"' . $value . '"' . "\t";
  $rowData .= $value;
 }
 $setData .= trim($rowData)."\n";
}


header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=Book record 
sheet.xls");
header("Pragma: no-cache");
header("Expires: 0");

echo ucwords($columnHeader)."\n".$setData."\n";

?>

complete code here php export to excel

SQL query to group by day

use linq

from c in Customers
group c by DbFunctions.TruncateTime(c.CreateTime) into date
orderby date.Key descending
select new  
{
    Value = date.Count().ToString(),
    Name = date.Key.ToString().Substring(0, 10)
}

How do I do a case-insensitive string comparison?

How about converting to lowercase first? you can use string.lower().

Git diff between current branch and master but not including unmerged master commits

git diff `git merge-base master branch`..branch

Merge base is the point where branch diverged from master.

Git diff supports a special syntax for this:

git diff master...branch

You must not swap the sides because then you would get the other branch. You want to know what changed in branch since it diverged from master, not the other way round.

Loosely related:


Note that .. and ... syntax does not have the same semantics as in other Git tools. It differs from the meaning specified in man gitrevisions.

Quoting man git-diff:

  • git diff [--options] <commit> <commit> [--] [<path>…]

    This is to view the changes between two arbitrary <commit>.

  • git diff [--options] <commit>..<commit> [--] [<path>…]

    This is synonymous to the previous form. If <commit> on one side is omitted, it will have the same effect as using HEAD instead.

  • git diff [--options] <commit>...<commit> [--] [<path>…]

    This form is to view the changes on the branch containing and up to the second <commit>, starting at a common ancestor of both <commit>. "git diff A...B" is equivalent to "git diff $(git-merge-base A B) B". You can omit any one of <commit>, which has the same effect as using HEAD instead.

Just in case you are doing something exotic, it should be noted that all of the <commit> in the above description, except in the last two forms that use ".." notations, can be any <tree>.

For a more complete list of ways to spell <commit>, see "SPECIFYING REVISIONS" section in gitrevisions[7]. However, "diff" is about comparing two endpoints, not ranges, and the range notations ("<commit>..<commit>" and "<commit>...<commit>") do not mean a range as defined in the "SPECIFYING RANGES" section in gitrevisions[7].

How to serve static files in Flask

The simplest way is create a static folder inside the main project folder. Static folder containing .css files.

main folder

/Main Folder
/Main Folder/templates/foo.html
/Main Folder/static/foo.css
/Main Folder/application.py(flask script)

Image of main folder containing static and templates folders and flask script

flask

from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
def login():
    return render_template("login.html")

html (layout)

<!DOCTYPE html>
<html>
    <head>
        <title>Project(1)</title>
        <link rel="stylesheet" href="/static/styles.css">
     </head>
    <body>
        <header>
            <div class="container">
                <nav>
                    <a class="title" href="">Kamook</a>
                    <a class="text" href="">Sign Up</a>
                    <a class="text" href="">Log In</a>
                </nav>
            </div>
        </header>  
        {% block body %}
        {% endblock %}
    </body>
</html>

html

{% extends "layout.html" %}

{% block body %}
    <div class="col">
        <input type="text" name="username" placeholder="Username" required>
        <input type="password" name="password" placeholder="Password" required>
        <input type="submit" value="Login">
    </div>
{% endblock %}

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

As a last resort, if all other suggestions fail, then backup all your data and do a factory reset.

How do I deal with installing peer dependencies in Angular CLI?

You can ignore the peer dependency warnings by using the --force flag with Angular cli when updating dependencies.

ng update @angular/cli @angular/core --force

For a full list of options, check the docs: https://angular.io/cli/update

How to add 'libs' folder in Android Studio?

also you should click right button on mouse at your projectname and choose "open module settings" or press F4 button. Then on "dependencies" tab add your lib.jar to declare needed lib

Javascript objects: get parent

You will need the child to store the parents this variable. As the Parent is the only object that has access to it's this variable it will also need a function that places the this variable into the child's that variable, something like this.

var Parent = {
  Child : {
    that : {},
  },
  init : function(){
    this.Child.that = this;
  }
}

To test this out try to run this in Firefox's Scratchpad, it worked for me.

var Parent = {
  data : "Parent Data",

  Child : {
    that : {},
    data : "Child Data",
    display : function(){
      console.log(this.data);
      console.log(this.that.data);
    }
  },
  init : function(){
    this.Child.that = this;
  }
}

Parent.init();
Parent.Child.display();

Repeat-until or equivalent loop in Python

REPEAT
    ...
UNTIL cond

Is equivalent to

while True:
    ...
    if cond:
        break

The simplest possible JavaScript countdown timer?

I have two demos, one with jQuery and one without. Neither use date functions and are about as simple as it gets.

Demo with vanilla JavaScript

_x000D_
_x000D_
function startTimer(duration, display) {_x000D_
    var timer = duration, minutes, seconds;_x000D_
    setInterval(function () {_x000D_
        minutes = parseInt(timer / 60, 10);_x000D_
        seconds = parseInt(timer % 60, 10);_x000D_
_x000D_
        minutes = minutes < 10 ? "0" + minutes : minutes;_x000D_
        seconds = seconds < 10 ? "0" + seconds : seconds;_x000D_
_x000D_
        display.textContent = minutes + ":" + seconds;_x000D_
_x000D_
        if (--timer < 0) {_x000D_
            timer = duration;_x000D_
        }_x000D_
    }, 1000);_x000D_
}_x000D_
_x000D_
window.onload = function () {_x000D_
    var fiveMinutes = 60 * 5,_x000D_
        display = document.querySelector('#time');_x000D_
    startTimer(fiveMinutes, display);_x000D_
};
_x000D_
<body>_x000D_
    <div>Registration closes in <span id="time">05:00</span> minutes!</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Demo with jQuery

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.text(minutes + ":" + seconds);

        if (--timer < 0) {
            timer = duration;
        }
    }, 1000);
}

jQuery(function ($) {
    var fiveMinutes = 60 * 5,
        display = $('#time');
    startTimer(fiveMinutes, display);
});

However if you want a more accurate timer that is only slightly more complicated:

_x000D_
_x000D_
function startTimer(duration, display) {_x000D_
    var start = Date.now(),_x000D_
        diff,_x000D_
        minutes,_x000D_
        seconds;_x000D_
    function timer() {_x000D_
        // get the number of seconds that have elapsed since _x000D_
        // startTimer() was called_x000D_
        diff = duration - (((Date.now() - start) / 1000) | 0);_x000D_
_x000D_
        // does the same job as parseInt truncates the float_x000D_
        minutes = (diff / 60) | 0;_x000D_
        seconds = (diff % 60) | 0;_x000D_
_x000D_
        minutes = minutes < 10 ? "0" + minutes : minutes;_x000D_
        seconds = seconds < 10 ? "0" + seconds : seconds;_x000D_
_x000D_
        display.textContent = minutes + ":" + seconds; _x000D_
_x000D_
        if (diff <= 0) {_x000D_
            // add one second so that the count down starts at the full duration_x000D_
            // example 05:00 not 04:59_x000D_
            start = Date.now() + 1000;_x000D_
        }_x000D_
    };_x000D_
    // we don't want to wait a full second before the timer starts_x000D_
    timer();_x000D_
    setInterval(timer, 1000);_x000D_
}_x000D_
_x000D_
window.onload = function () {_x000D_
    var fiveMinutes = 60 * 5,_x000D_
        display = document.querySelector('#time');_x000D_
    startTimer(fiveMinutes, display);_x000D_
};
_x000D_
<body>_x000D_
    <div>Registration closes in <span id="time"></span> minutes!</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Now that we have made a few pretty simple timers we can start to think about re-usability and separating concerns. We can do this by asking "what should a count down timer do?"

  • Should a count down timer count down? Yes
  • Should a count down timer know how to display itself on the DOM? No
  • Should a count down timer know to restart itself when it reaches 0? No
  • Should a count down timer provide a way for a client to access how much time is left? Yes

So with these things in mind lets write a better (but still very simple) CountDownTimer

function CountDownTimer(duration, granularity) {
  this.duration = duration;
  this.granularity = granularity || 1000;
  this.tickFtns = [];
  this.running = false;
}

CountDownTimer.prototype.start = function() {
  if (this.running) {
    return;
  }
  this.running = true;
  var start = Date.now(),
      that = this,
      diff, obj;

  (function timer() {
    diff = that.duration - (((Date.now() - start) / 1000) | 0);

    if (diff > 0) {
      setTimeout(timer, that.granularity);
    } else {
      diff = 0;
      that.running = false;
    }

    obj = CountDownTimer.parse(diff);
    that.tickFtns.forEach(function(ftn) {
      ftn.call(this, obj.minutes, obj.seconds);
    }, that);
  }());
};

CountDownTimer.prototype.onTick = function(ftn) {
  if (typeof ftn === 'function') {
    this.tickFtns.push(ftn);
  }
  return this;
};

CountDownTimer.prototype.expired = function() {
  return !this.running;
};

CountDownTimer.parse = function(seconds) {
  return {
    'minutes': (seconds / 60) | 0,
    'seconds': (seconds % 60) | 0
  };
};

So why is this implementation better than the others? Here are some examples of what you can do with it. Note that all but the first example can't be achieved by the startTimer functions.

An example that displays the time in XX:XX format and restarts after reaching 00:00

An example that displays the time in two different formats

An example that has two different timers and only one restarts

An example that starts the count down timer when a button is pressed

How do I show multiple recaptchas on a single page?

This is a JQuery-free version of the answer provided by raphadko and noun.

1) Create your recaptcha fields normally with this:

<div class="g-recaptcha"></div>

2) Load the script with this:

<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit" async defer></script>

3) Now call this to iterate over the fields and create the recaptchas:

var CaptchaCallback = function() {
    var captchas = document.getElementsByClassName("g-recaptcha");
    for(var i = 0; i < captchas.length; i++) {
        grecaptcha.render(captchas[i], {'sitekey' : 'YOUR_KEY_HERE'});
    }
};

Open window in JavaScript with HTML inserted

You can use window.open to open a new window/tab(according to browser setting) in javascript.

By using document.write you can write HTML content to the opened window.

Node JS Error: ENOENT

change

"/tmp/test.jpg".

to

"./tmp/test.jpg"

How to refer to Excel objects in Access VBA?

Inside a module

Option Explicit
dim objExcelApp as Excel.Application
dim wb as Excel.Workbook

sub Initialize()
   set objExcelApp = new Excel.Application
end sub

sub ProcessDataWorkbook()
    dim ws as Worksheet
    set wb = objExcelApp.Workbooks.Open("path to my workbook")
    set ws = wb.Sheets(1)

    ws.Cells(1,1).Value = "Hello"
    ws.Cells(1,2).Value = "World"

    'Close the workbook
    wb.Close
    set wb = Nothing
end sub

sub Release()
   set objExcelApp = Nothing
end sub

How to check compiler log in sql developer?

To see your log in SQL Developer then press:

CTRL+SHIFT + L (or CTRL + CMD + L on macOS)

or

View -> Log

or by using mysql query

show errors;

Get type of a generic parameter in Java with reflection

Here is another trick. Use a generic vararg array

import java.util.ArrayList;

class TypedArrayList<E> extends ArrayList<E>
{
    @SafeVarargs
    public TypedArrayList (E... typeInfo)
    {
        // Get generic type at runtime ...
        System.out.println (typeInfo.getClass().getComponentType().getTypeName());
    }
}

public class GenericTest
{
    public static void main (String[] args)
    {
        // No need to supply the dummy argument
        ArrayList<Integer> ar1 = new TypedArrayList<> ();
        ArrayList<String> ar2 = new TypedArrayList<> ();
        ArrayList<?> ar3 = new TypedArrayList<> ();
    }
}

How to putAll on Java hashMap contents of one to another, but not replace existing keys and values?

Java 8 solution using Map#merge

As of you can use Map#merge(K key, V value, BiFunction remappingFunction) which merges a value into the Map using remappingFunction in case the key is already found in the Map you want to put the pair into.

// using lambda
newMap.forEach((key, value) -> map.merge(key, value, (oldValue, newValue) -> oldValue));
// using for-loop
for (Map.Entry<Integer, String> entry: newMap.entrySet()) {
    map.merge(entry.getKey(), entry.getValue(), (oldValue, newValue) -> oldValue);
}

The code iterates the newMap entries (key and value) and each one is merged into map through the method merge. The remappingFunction is triggered in case of duplicated key and in that case it says that the former (original) oldValue value will be used and not rewritten.

With this solution, you don't need a temporary Map.


Let's have an example of merging newMap entries into map and keeping the original values in case of the duplicated antry.

Map<Integer, String> newMap = new HashMap<>();
newMap.put(2, "EVIL VALUE");                         // this will NOT be merged into
newMap.put(4, "four");                               // this WILL be merged into
newMap.put(5, "five");                               // this WILL be merged into

Map<Integer, String> map = new HashMap<>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");

newMap.forEach((k, v) -> map.merge(k, v, (oldValue, newValue) -> oldValue));

map.forEach((k, v) -> System.out.println(k + " " + v));
1 one
2 two
3 three
4 four
5 five

Parse error: syntax error, unexpected [

Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "] with array("title" => "Welcome ")

Multiple parameters in a List. How to create without a class?

If you are using .NET 4.0 you can use a Tuple.

List<Tuple<T1, T2>> list;

For older versions of .NET you have to create a custom class (unless you are lucky enough to be able to find a class that fits your needs in the base class library).

How to convert String into Hashmap in java

@Test
public void testToStringToMap() {
    Map<String,String> expected = new HashMap<>();
    expected.put("first_name", "naresh");
    expected.put("last_name", "kumar");
    expected.put("gender", "male");
    String mapString = expected.toString();
    Map<String, String> actual = Arrays.stream(mapString.replace("{", "").replace("}", "").split(","))
            .map(arrayData-> arrayData.split("="))
            .collect(Collectors.toMap(d-> ((String)d[0]).trim(), d-> (String)d[1]));

    expected.entrySet().stream().forEach(e->assertTrue(actual.get(e.getKey()).equals(e.getValue())));
}

How change default SVN username and password to commit changes?

For Windows (7), the same folder is located at,

%APPDATA%\Subversion\auth

Type in the above in the Run(Win key + R) dialog box and hit Enter,

To check the existing username open the below file as a text file,

%APPDATA%\Subversion\auth\svn.simple\xxxxxxxxxx

How do you change Background for a Button MouseOver in WPF?

A slight more difficult answer that uses ControlTemplate and has an animation effect (adapted from https://docs.microsoft.com/en-us/dotnet/framework/wpf/controls/customizing-the-appearance-of-an-existing-control)

In your resource dictionary define a control template for your button like this one:

<ControlTemplate TargetType="Button" x:Key="testButtonTemplate2">
    <Border Name="RootElement">
        <Border.Background>
            <SolidColorBrush x:Name="BorderBrush" Color="Black"/>
        </Border.Background>

        <Grid Margin="4" >
            <Grid.Background>
                <SolidColorBrush x:Name="ButtonBackground" Color="Aquamarine"/>
            </Grid.Background>
            <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" Margin="4,5,4,4"/>
        </Grid>
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="CommonStates">
                <VisualState x:Name="Normal"/>
                <VisualState x:Name="MouseOver">
                    <Storyboard>
                        <ColorAnimation Storyboard.TargetName="ButtonBackground" Storyboard.TargetProperty="Color" To="Red"/>
                    </Storyboard>
                </VisualState>
                <VisualState x:Name="Pressed">
                    <Storyboard>
                        <ColorAnimation Storyboard.TargetName="ButtonBackground" Storyboard.TargetProperty="Color" To="Red"/>
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
    </Border>
</ControlTemplate>

in your XAML you can use the template above for your button as below:

Define your button

<Button Template="{StaticResource testButtonTemplate2}" 
HorizontalAlignment="Center" VerticalAlignment="Center" 
Foreground="White">My button</Button>

Hope it helps

How to download files using axios

My answer is a total hack- I just created a link that looks like a button and add the URL to that.

<a class="el-button"
  style="color: white; background-color: #58B7FF;"
  :href="<YOUR URL ENDPOINT HERE>"
  :download="<FILE NAME NERE>">
<i class="fa fa-file-excel-o"></i>&nbsp;Excel
</a>

I'm using the excellent VueJs hence the odd anotations, however, this solution is framework agnostic. The idea would work for any HTML based design.

What is Unicode, UTF-8, UTF-16?

Unicode is a standard which maps the characters in all languages to a particular numeric value called Code Points. The reason it does this is that it allows different encodings to be possible using the same set of code points.

UTF-8 and UTF-16 are two such encodings. They take code points as input and encodes them using some well-defined formula to produce the encoded string.

Choosing a particular encoding depends upon your requirements. Different encodings have different memory requirements and depending upon the characters that you will be dealing with, you should choose the encoding which uses the least sequences of bytes to encode those characters.

For more in-depth details about Unicode, UTF-8 and UTF-16, you can check out this article,

What every programmer should know about Unicode

SQL LEFT-JOIN on 2 fields for MySQL

select a.ip, a.os, a.hostname, a.port, a.protocol,
       b.state
from a
left join b on a.ip = b.ip 
           and a.port = b.port

How do I find the duplicates in a list and create another list with them?

You don't need the count, just whether or not the item was seen before. Adapted that answer to this problem:

def list_duplicates(seq):
  seen = set()
  seen_add = seen.add
  # adds all elements it doesn't know yet to seen and all other to seen_twice
  seen_twice = set( x for x in seq if x in seen or seen_add(x) )
  # turn the set into a list (as requested)
  return list( seen_twice )

a = [1,2,3,2,1,5,6,5,5,5]
list_duplicates(a) # yields [1, 2, 5]

Just in case speed matters, here are some timings:

# file: test.py
import collections

def thg435(l):
    return [x for x, y in collections.Counter(l).items() if y > 1]

def moooeeeep(l):
    seen = set()
    seen_add = seen.add
    # adds all elements it doesn't know yet to seen and all other to seen_twice
    seen_twice = set( x for x in l if x in seen or seen_add(x) )
    # turn the set into a list (as requested)
    return list( seen_twice )

def RiteshKumar(l):
    return list(set([x for x in l if l.count(x) > 1]))

def JohnLaRooy(L):
    seen = set()
    seen2 = set()
    seen_add = seen.add
    seen2_add = seen2.add
    for item in L:
        if item in seen:
            seen2_add(item)
        else:
            seen_add(item)
    return list(seen2)

l = [1,2,3,2,1,5,6,5,5,5]*100

Here are the results: (well done @JohnLaRooy!)

$ python -mtimeit -s 'import test' 'test.JohnLaRooy(test.l)'
10000 loops, best of 3: 74.6 usec per loop
$ python -mtimeit -s 'import test' 'test.moooeeeep(test.l)'
10000 loops, best of 3: 91.3 usec per loop
$ python -mtimeit -s 'import test' 'test.thg435(test.l)'
1000 loops, best of 3: 266 usec per loop
$ python -mtimeit -s 'import test' 'test.RiteshKumar(test.l)'
100 loops, best of 3: 8.35 msec per loop

Interestingly, besides the timings itself, also the ranking slightly changes when pypy is used. Most interestingly, the Counter-based approach benefits hugely from pypy's optimizations, whereas the method caching approach I have suggested seems to have almost no effect.

$ pypy -mtimeit -s 'import test' 'test.JohnLaRooy(test.l)'
100000 loops, best of 3: 17.8 usec per loop
$ pypy -mtimeit -s 'import test' 'test.thg435(test.l)'
10000 loops, best of 3: 23 usec per loop
$ pypy -mtimeit -s 'import test' 'test.moooeeeep(test.l)'
10000 loops, best of 3: 39.3 usec per loop

Apparantly this effect is related to the "duplicatedness" of the input data. I have set l = [random.randrange(1000000) for i in xrange(10000)] and got these results:

$ pypy -mtimeit -s 'import test' 'test.moooeeeep(test.l)'
1000 loops, best of 3: 495 usec per loop
$ pypy -mtimeit -s 'import test' 'test.JohnLaRooy(test.l)'
1000 loops, best of 3: 499 usec per loop
$ pypy -mtimeit -s 'import test' 'test.thg435(test.l)'
1000 loops, best of 3: 1.68 msec per loop

Custom ImageView with drop shadow

I manage to apply gradient border using this code..

public static Bitmap drawShadow(Bitmap bitmap, int leftRightThk, int bottomThk, int padTop) {
    int w = bitmap.getWidth();
    int h = bitmap.getHeight();

    int newW = w - (leftRightThk * 2);
    int newH = h - (bottomThk + padTop);

    Bitmap.Config conf = Bitmap.Config.ARGB_8888;
    Bitmap bmp = Bitmap.createBitmap(w, h, conf);
    Bitmap sbmp = Bitmap.createScaledBitmap(bitmap, newW, newH, false);

    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    Canvas c = new Canvas(bmp);

    // Left
    int leftMargin = (leftRightThk + 7)/2;
    Shader lshader = new LinearGradient(0, 0, leftMargin, 0, Color.TRANSPARENT, Color.BLACK, TileMode.CLAMP);
    paint.setShader(lshader);
    c.drawRect(0, padTop, leftMargin, newH, paint); 

    // Right
    Shader rshader = new LinearGradient(w - leftMargin, 0, w, 0, Color.BLACK, Color.TRANSPARENT, TileMode.CLAMP);
    paint.setShader(rshader);
    c.drawRect(newW, padTop, w, newH, paint);

    // Bottom
    Shader bshader = new LinearGradient(0, newH, 0, bitmap.getHeight(), Color.BLACK, Color.TRANSPARENT, TileMode.CLAMP);
    paint.setShader(bshader);
    c.drawRect(leftMargin -3, newH, newW + leftMargin + 3, bitmap.getHeight(), paint);
    c.drawBitmap(sbmp, leftRightThk, 0, null);

    return bmp;
}

hope this helps !

What is the largest Safe UDP Packet Size on the Internet

It is true that a typical IPv4 header is 20 bytes, and the UDP header is 8 bytes. However it is possible to include IP options which can increase the size of the IP header to as much as 60 bytes. In addition, sometimes it is necessary for intermediate nodes to encapsulate datagrams inside of another protocol such as IPsec (used for VPNs and the like) in order to route the packet to its destination. So if you do not know the MTU on your particular network path, it is best to leave a reasonable margin for other header information that you may not have anticipated. A 512-byte UDP payload is generally considered to do that, although even that does not leave quite enough space for a maximum size IP header.

Reading CSV file and storing values into an array

I have a library that is doing exactly you need.

Some time ago I had wrote simple and fast enough library for work with CSV files. You can find it by the following link: https://github.com/ukushu/DataExporter

It works with CSV like with 2 dimensions array. Exactly like you need.

As example, in case of you need all of values of 3rd row only you need is to write:

Csv csv = new Csv();

csv.FileOpen("c:\\file1.csv");

var allValuesOf3rdRow = csv.Rows[2];

or to read 2nd cell of

var value = csv.Rows[2][1];

GitHub Error Message - Permission denied (publickey)

Another solution :

create the SSH keys, type ssh-keygen -t rsa -C "[email protected]". This will create both id_rsa and id_rsa.pub files.

Add the id_rsa to ssh list on local computer: ssh-add ~/.ssh/id_rsa.

After generating the keys get the pubkey using :

cat ~/.ssh/id_rsa.pub 

you will get something like :

cat ~/.ssh/id_rsa.pub 

ssh-rsa AAAB3NzaC1yc2EAAAADAQABAAACAQCvMzmFEUPvaA1AFEBH6zGIF3N6pVE2SJv9V1MHgEwk4C7xovdk7Lr4LDoqEcqxgeJftwWQWWVrWWf7q9qCdHTAanH2Q5vx5nZjLB+B7saksehVOPWDR/MOSpVcr5bwIjf8dc8u5S8h24uBlguGkX+4lFJ+zwhiuwJlhykMvs5py1gD2hy+hvOs1Y17JPWhVVesGV3tlmtbfVolEiv9KShgkk3Hq56fyl+QmPzX1jya4TIC3k55FTzwRWBd+IpblbrGlrIBS6hvpHQpgUs47nSHLEHTn0Xmn6Q== [email protected]

copy this key (value) and go to github.com and under the setting (ssh and pgp key) add your public key.

MySQL error 2006: mysql server has gone away

There are several causes for this error.

MySQL/MariaDB related:

  • wait_timeout - Time in seconds that the server waits for a connection to become active before closing it.
  • interactive_timeout - Time in seconds that the server waits for an interactive connection.
  • max_allowed_packet - Maximum size in bytes of a packet or a generated/intermediate string. Set as large as the largest BLOB, in multiples of 1024.

Example of my.cnf:

[mysqld]
# 8 hours
wait_timeout = 28800
# 8 hours
interactive_timeout = 28800
max_allowed_packet = 256M

Server related:

  • Your server has full memory - check info about RAM with free -h

Framework related:

  • Check settings of your framework. Django for example use CONN_MAX_AGE (see docs)

How to debug it:

  • Check values of MySQL/MariaDB variables.
    • with sql: SHOW VARIABLES LIKE '%time%';
    • command line: mysqladmin variables
  • Turn on verbosity for errors:
    • MariaDB: log_warnings = 4
    • MySQL: log_error_verbosity = 3
  • Check docs for more info about the error

how to remove only one style property with jquery

The documentation for css() says that setting the style property to the empty string will remove that property if it does not reside in a stylesheet:

Setting the value of a style property to an empty string — e.g. $('#mydiv').css('color', '') — removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's .css() method, or through direct DOM manipulation of the style property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or <style> element.

Since your styles are inline, you can write:

$(selector).css("-moz-user-select", "");

Python os.path.join on Windows

For a system-agnostic solution that works on both Windows and Linux, no matter what the input path, one could use os.path.join(os.sep, rootdir + os.sep, targetdir)

On WIndows:

>>> os.path.join(os.sep, "C:" + os.sep, "Windows")
'C:\\Windows'

On Linux:

>>> os.path.join(os.sep, "usr" + os.sep, "lib")
'/usr/lib'

adding to window.onload event?

This might not be a popular option, but sometimes the scripts end up being distributed in various chunks, in that case I've found this to be a quick fix

if(window.onload != null){var f1 = window.onload;}
window.onload=function(){
    //do something

    if(f1!=null){f1();}
}

then somewhere else...

if(window.onload != null){var f2 = window.onload;}
window.onload=function(){
    //do something else

    if(f2!=null){f2();}
}

this will update the onload function and chain as needed

How to get current route in react-router 2.0.0-rc5

Try grabbing the path using: document.location.pathname

In Javascript you can the current URL in parts. Check out: https://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/

How do I properly force a Git push?

I would really recommend to:

  • push only to the main repo

  • make sure that main repo is a bare repo, in order to never have any problem with the main repo working tree being not in sync with its .git base. See "How to push a local git repository to another computer?"

  • If you do have to make modification in the main (bare) repo, clone it (on the main server), do your modification and push back to it

In other words, keep a bare repo accessible both from the main server and the local computer, in order to have a single upstream repo from/to which to pull/pull.

How do I set a variable to the output of a command in Bash?

If you want to do it with multiline/multiple command/s then you can do this:

output=$( bash <<EOF
# Multiline/multiple command/s
EOF
)

Or:

output=$(
# Multiline/multiple command/s
)

Example:

#!/bin/bash
output="$( bash <<EOF
echo first
echo second
echo third
EOF
)"
echo "$output"

Output:

first
second
third

Using heredoc, you can simplify things pretty easily by breaking down your long single line code into a multiline one. Another example:

output="$( ssh -p $port $user@$domain <<EOF
# Breakdown your long ssh command into multiline here.
EOF
)"

How to play ringtone/alarm sound in Android

For the future googlers: use RingtoneManager.getActualDefaultRingtoneUri() instead of RingtoneManager.getDefaultUri(). According to its name, it would return the actual uri, so you can freely use it. From documentation of getActualDefaultRingtoneUri():

Gets the current default sound's Uri. This will give the actual sound Uri, instead of using this, most clients can use DEFAULT_RINGTONE_URI.

Meanwhile getDefaultUri() says this:

Returns the Uri for the default ringtone of a particular type. Rather than returning the actual ringtone's sound Uri, this will return the symbolic Uri which will resolved to the actual sound when played.

Send a base64 image in HTML email

Support, unfortunately, is brutal at best. Here's a post on the topic:

https://www.campaignmonitor.com/blog/email-marketing/2013/02/embedded-images-in-html-email/

And the post content: enter image description here

How to copy a char array in C?

You cannot assign arrays to copy them. How you can copy the contents of one into another depends on multiple factors:

For char arrays, if you know the source array is null terminated and destination array is large enough for the string in the source array, including the null terminator, use strcpy():

#include <string.h>

char array1[18] = "abcdefg";
char array2[18];

...

strcpy(array2, array1);

If you do not know if the destination array is large enough, but the source is a C string, and you want the destination to be a proper C string, use snprinf():

#include <stdio.h>

char array1[] = "a longer string that might not fit";
char array2[18];

...

snprintf(array2, sizeof array2, "%s", array1);

If the source array is not necessarily null terminated, but you know both arrays have the same size, you can use memcpy:

#include <string.h>

char array1[28] = "a non null terminated string";
char array2[28];

...

memcpy(array2, array1, sizeof array2);

Call child component method from parent class - Angular

I think most easy way is using Subject. In bellow example code the child will be notified each time 'tellChild' is called.

Parent.component.ts

import {Subject} from 'rxjs/Subject';
...
export class ParentComp {
    changingValue: Subject<boolean> = new Subject();
    tellChild(){
    this.changingValue.next(true);
  }
}

Parent.component.html

<my-comp [changing]="changingValue"></my-comp>

Child.component.ts

...
export class ChildComp implements OnInit{
@Input() changing: Subject<boolean>;
ngOnInit(){
  this.changing.subscribe(v => { 
     console.log('value is changing', v);
  });
}

Working sample on Stackblitz

Is it possible to save HTML page as PDF using JavaScript or jquery?

Yes. For example you can use the solution by https://grabz.it.

It's got a Javascript API which can be used in different ways to grab and manipulate the screenshot. In order to use it in your app you will need to first get an app key and secret and download the free Javascript SDK.

So, let's see a simple example for using it:

//first include the grabzit.min.js library in the web page
<script src="grabzit.min.js"></script>
//include the code below to add the screenshot to the body tag    
<script>
//use secret key to sign in. replace the url.
GrabzIt("Sign in to view your Application Key").ConvertURL("http://www.google.com").Create();
</script>

Then simply wait a short while and the image will automatically appear at the bottom of the page, without you needing to reload the page.

That's the simplest one. For more examples with image manipulation, attaching screenshots to elements and etc check the documentation.

Most efficient way to see if an ArrayList contains an object in Java

I would say the simplest solution would be to wrap the object and delegate the contains call to a collection of the wrapped class. This is similar to the comparator but doesn't force you to sort the resulting collection, you can simply use ArrayList.contains().

public class Widget {
        private String name;
        private String desc;

        public String getName() {
            return name;
        }

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

        public String getDesc() {
            return desc;
        }

        public void setDesc(String desc) {
            this.desc = desc;
        }
    }



    public abstract class EqualsHashcodeEnforcer<T> {

        protected T wrapped;

        public T getWrappedObject() {
            return wrapped;
        }

        @Override
        public boolean equals(Object obj) {
            return equalsDelegate(obj);
        }

        @Override
        public int hashCode() {
            return hashCodeDelegate();
        }

        protected abstract boolean equalsDelegate(Object obj);

        protected abstract int hashCodeDelegate();
    }


    public class WrappedWidget extends EqualsHashcodeEnforcer<Widget> {

        @Override
        protected boolean equalsDelegate(Object obj) {
            if (obj == null) {
                return false;
            }
            if (obj == getWrappedObject()) {
                return true;
            }
            if (obj.getClass() != getWrappedObject().getClass()) {
                return false;
            }
            Widget rhs = (Widget) obj;

            return new EqualsBuilder().append(getWrappedObject().getName(),
                    rhs.getName()).append(getWrappedObject().getDesc(),
                    rhs.getDesc()).isEquals();
        }

        @Override
        protected int hashCodeDelegate() {

            return new HashCodeBuilder(121, 991).append(
                    getWrappedObject().getName()).append(
                    getWrappedObject().getDesc()).toHashCode();
        }

    }

Good ways to sort a queryset? - Django

I just wanted to illustrate that the built-in solutions (SQL-only) are not always the best ones. At first I thought that because Django's QuerySet.objects.order_by method accepts multiple arguments, you could easily chain them:

ordered_authors = Author.objects.order_by('-score', 'last_name')[:30]

But, it does not work as you would expect. Case in point, first is a list of presidents sorted by score (selecting top 5 for easier reading):

>>> auths = Author.objects.order_by('-score')[:5]
>>> for x in auths: print x
... 
James Monroe (487)
Ulysses Simpson (474)
Harry Truman (471)
Benjamin Harrison (467)
Gerald Rudolph (464)

Using Alex Martelli's solution which accurately provides the top 5 people sorted by last_name:

>>> for x in sorted(auths, key=operator.attrgetter('last_name')): print x
... 
Benjamin Harrison (467)
James Monroe (487)
Gerald Rudolph (464)
Ulysses Simpson (474)
Harry Truman (471)

And now the combined order_by call:

>>> myauths = Author.objects.order_by('-score', 'last_name')[:5]
>>> for x in myauths: print x
... 
James Monroe (487)
Ulysses Simpson (474)
Harry Truman (471)
Benjamin Harrison (467)
Gerald Rudolph (464)

As you can see it is the same result as the first one, meaning it doesn't work as you would expect.

Query error with ambiguous column name in SQL

One of your tables has the same column name's which brings a confusion in the query as to which columns of the tables are you referring to. Copy this code and run it.

SELECT 
    v.VendorName, i.InvoiceID, iL.InvoiceSequence, iL.InvoiceLineItemAmount
FROM Vendors AS v
JOIN Invoices AS i ON (v.VendorID = .VendorID)
JOIN InvoiceLineItems AS iL ON (i.InvoiceID = iL.InvoiceID)
WHERE  
    I.InvoiceID IN
        (SELECT iL.InvoiceSequence 
         FROM InvoiceLineItems
         WHERE iL.InvoiceSequence > 1)
ORDER BY 
    V.VendorName, i.InvoiceID, iL.InvoiceSequence, iL.InvoiceLineItemAmount

ssh server connect to host xxx port 22: Connection timed out on linux-ubuntu

There can be many possible reasons for this failure.

Some are listed above. I faced the same issue, it is very hard to find the root cause of the failure.

I will recommend you to check the session timeout for shh from ssh_config file. Try to increase the session timeout and see if it fails again

How does HttpContext.Current.User.Identity.Name know which usernames exist?

How does [HttpContext.Current.User] know which usernames exist or do not exist?

Let's look at an example of one way this works. Suppose you are using Forms Authentication and the "OnAuthenticate" event fires. This event occurs "when the application authenticates the current request" (Reference Source).

Up until this point, the application has no idea who you are.

Since you are using Forms Authentication, it first checks by parsing the authentication cookie (usually .ASPAUTH) via a call to ExtractTicketFromCookie. This calls FormsAuthentication.Decrypt (This method is public; you can call this yourself!). Next, it calls Context.SetPrincipalNoDemand, turning the cookie into a user and stuffing it into Context.User (Reference Source).

jQuery UI autocomplete with item and id

You need to use the ui.item.label (the text) and ui.item.value (the id) properties

$('#selector').autocomplete({
    source: url,
    select: function (event, ui) {
        $("#txtAllowSearch").val(ui.item.label); // display the selected text
        $("#txtAllowSearchID").val(ui.item.value); // save selected id to hidden input
    }
});

$('#button').click(function() {
    alert($("#txtAllowSearchID").val()); // get the id from the hidden input
}); 

[Edit] You also asked how to create the multi-dimensional array...

You should be able create the array like so:

var $local_source = [[0,"c++"], [1,"java"], [2,"php"], [3,"coldfusion"], 
                     [4,"javascript"], [5,"asp"], [6,"ruby"]];

Read more about how to work with multi-dimensional arrays here: http://www.javascriptkit.com/javatutors/literal-notation2.shtml

Is it possible to get an Excel document's row count without loading the entire document into memory?

Adding on to what Hubro said, apparently get_highest_row() has been deprecated. Using the max_row and max_column properties returns the row and column count. For example:

    wb = load_workbook(path, use_iterators=True)
    sheet = wb.worksheets[0]

    row_count = sheet.max_row
    column_count = sheet.max_column

What does "control reaches end of non-void function" mean?

The compiler cannot tell from that code if the function will ever reach the end and still return something. To make that clear, replace the last else if(...) with just else.

Min/Max of dates in an array?

var max_date = dates.sort(function(d1, d2){
    return d2-d1;
})[0];

Adding author name in Eclipse automatically to existing files

Actually in Eclipse Indigo thru Oxygen, you have to go to the Types template Window -> Preferences -> Java -> Code Style -> Code templates -> (in right-hand pane) Comments -> double-click Types and make sure it has the following, which it should have by default:

/**
 * @author ${user}
 *
 * ${tags}
 */

and as far as I can tell, there is nothing in Eclipse to add the javadoc automatically to existing files in one batch. You could easily do it from the command line with sed & awk but that's another question.

If you are prepared to open each file individually, then selected the class / interface declaration line, e.g. public class AdamsClass { and then hit the key combo Shift + Alt + J and that will insert a new javadoc comment above, along with the author tag for your user. To experiment with other settings, go to Windows->Preferences->Java->Editor->Templates.

How to handle invalid SSL certificates with Apache HttpClient?

For Apache HttpClient 4.5+ & Java8:

SSLContext sslContext = SSLContexts.custom()
        .loadTrustMaterial((chain, authType) -> true).build();

SSLConnectionSocketFactory sslConnectionSocketFactory =
        new SSLConnectionSocketFactory(sslContext, new String[]
        {"SSLv2Hello", "SSLv3", "TLSv1","TLSv1.1", "TLSv1.2" }, null,
        NoopHostnameVerifier.INSTANCE);
CloseableHttpClient client = HttpClients.custom()
        .setSSLSocketFactory(sslConnectionSocketFactory)
        .build();

But if your HttpClient use a ConnectionManager for seeking connection, e.g. like this:

 PoolingHttpClientConnectionManager connectionManager = new 
         PoolingHttpClientConnectionManager();

 CloseableHttpClient client = HttpClients.custom()
            .setConnectionManager(connectionManager)
            .build();

The HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory) has no effect, the problem is not resolved.

Because that the HttpClient use the specified connectionManager for seeking connection and the specified connectionManager haven't register our customized SSLConnectionSocketFactory. To resolve this, should register the The customized SSLConnectionSocketFactory in the connectionManager. The correct code should like this:

PoolingHttpClientConnectionManager connectionManager = new 
    PoolingHttpClientConnectionManager(RegistryBuilder.
                <ConnectionSocketFactory>create()
      .register("http",PlainConnectionSocketFactory.getSocketFactory())
      .register("https", sslConnectionSocketFactory).build());

CloseableHttpClient client = HttpClients.custom()
            .setConnectionManager(connectionManager)
            .build();

Inserting a tab character into text using C#

var text = "Ann@26"

var editedText = text.Replace("@", "\t");

How to count frequency of characters in a string?

A concise way to do this is:

Map<Character,Integer> frequencies = new HashMap<>();
for (char ch : input.toCharArray()) 
   frequencies.put(ch, frequencies.getOrDefault(ch, 0) + 1);

We use a for-each to loop through every character. The frequencies.getOrDefault() gets value if key is present or returns(as default) its second argument.

MySQL > Table doesn't exist. But it does (or it should)

My table had somehow been renamed to ' Customers' i.e. with a leading space

This meant

a) queries broke

b) the table didn't appear where expected in the alphabetical order of my tables, which in my panic meant I couldn't see it!

RENAME TABLE ` Customer` TO `Customer`;

PHP $_POST not working?

I had something similar this evening which was driving me batty. Submitting a form was giving me the values in $_REQUEST but not in $_POST.

Eventually I noticed that there were actually two requests going through on the network tab in firebug; first a POST with a 301 response, then a GET with a 200 response.

Hunting about the interwebs it sounded like most people thought this was to do with mod_rewrite causing the POST request to redirect and thus change to a GET.

In my case it wasn't mod_rewrite to blame, it was something far simpler... my URL for the POST also contained a GET query string which was starting without a trailing slash on the URL. It was this causing apache to redirect.

Spot the difference...

Bad: http://blah.de.blah/my/path?key=value&otherkey=othervalue
Good: http://blah.de.blah/my/path/?key=value&otherkey=othervalue

The bottom one doesn't cause a redirect and gives me $_POST!

Highlight Bash/shell code in Markdown files

If I need only to highlight the first word as a command, I often use properties:

```properties
npm run build
```  

I obtain something like:

npm run build

Delete all files in directory (but not directory) - one liner solution

rm -rf was much more performant than FileUtils.cleanDirectory.

Not a one-liner solution but after extensive benchmarking, we found that using rm -rf was multiple times faster than using FileUtils.cleanDirectory.

Of course, if you have a small or simple directory, it won't matter but in our case we had multiple gigabytes and deeply nested sub directories where it would take over 10 minutes with FileUtils.cleanDirectory and only 1 minute with rm -rf.

Here's our rough Java implementation to do that:

// Delete directory given and all subdirectories and files (i.e. recursively).
//
static public boolean clearDirectory( File file ) throws IOException, InterruptedException {

    if ( file.exists() ) {

        String deleteCommand = "rm -rf " + file.getAbsolutePath();
        Runtime runtime = Runtime.getRuntime();

        Process process = runtime.exec( deleteCommand );
        process.waitFor();

        file.mkdirs(); // Since we only want to clear the directory and not delete it, we need to re-create the directory.

        return true;
    }

    return false;

}

Worth trying if you're dealing with large or complex directories.

When do you use varargs in Java?

I have a varargs-related fear, too:

If the caller passes in an explicit array to the method (as opposed to multiple parameters), you will receive a shared reference to that array.

If you need to store this array internally, you might want to clone it first to avoid the caller being able to change it later.

 Object[] args = new Object[] { 1, 2, 3} ;

 varArgMethod(args);  // not varArgMethod(1,2,3);

 args[2] = "something else";  // this could have unexpected side-effects

While this is not really different from passing in any kind of object whose state might change later, since the array is usually (in case of a call with multiple arguments instead of an array) a fresh one created by the compiler internally that you can safely use, this is certainly unexpected behaviour.

How to run JUnit tests with Gradle?

How do I add a junit 4 dependency correctly?

Assuming you're resolving against a standard Maven (or equivalent) repo:

dependencies {
    ...
    testCompile "junit:junit:4.11"  // Or whatever version
}

Run those tests in the folders of tests/model?

You define your test source set the same way:

sourceSets {
    ...

    test {
        java {
            srcDirs = ["test/model"]  // Note @Peter's comment below
        }
    }
}

Then invoke the tests as:

./gradlew test

EDIT: If you are using JUnit 5 instead, there are more steps to complete, you should follow this tutorial.

Set encoding and fileencoding to utf-8 in Vim

You can set the variable 'fileencodings' in your .vimrc.

This is a list of character encodings considered when starting to edit an existing file. When a file is read, Vim tries to use the first mentioned character encoding. If an error is detected, the next one in the list is tried. When an encoding is found that works, 'fileencoding' is set to it. If all fail, 'fileencoding' is set to an empty string, which means the value of 'encoding' is used.

See :help filencodings

If you often work with e.g. cp1252, you can add it there:

set fileencodings=ucs-bom,utf-8,cp1252,default,latin9

Xcode/Simulator: How to run older iOS version?

If you have iAds in your binary you will not be able to run it on anything before iOS 4.0 and it will be rejected if you try and submit a binary like this.

You can still run the simulator from 3.2 onwards after upgrading.

In the iPhone Simulator try selecting Hardware -> Version -> 3.2

Entity Framework - "An error occurred while updating the entries. See the inner exception for details"

It could be caused by a data conversion from .NET to SQL, for instance a datetime conversion error. For me it was a null reference to a datetime column.

Also, that is not an exact error message. You can see the exact error in watch at exception.InnerException.InnerException -> ResultView.

OPTION (RECOMPILE) is Always Faster; Why?

Necroing this question but there's an explanation that no-one seems to have considered.

STATISTICS - Statistics are not available or misleading

If all of the following are true:

  1. The columns feedid and feedDate are likely to be highly correlated (e.g. a feed id is more specific than a feed date and the date parameter is redundant information).
  2. There is no index with both columns as sequential columns.
  3. There are no manually created statistics covering both these columns.

Then sql server may be incorrectly assuming that the columns are uncorrelated, leading to lower than expected cardinality estimates for applying both restrictions and a poor execution plan being selected. The fix in this case would be to create a statistics object linking the two columns, which is not an expensive operation.

What's the difference between subprocess Popen and call (how can I use them)?

The other answer is very complete, but here is a rule of thumb:

  • call is blocking:

    call('notepad.exe')
    print('hello')  # only executed when notepad is closed
    
  • Popen is non-blocking:

    Popen('notepad.exe')
    print('hello')  # immediately executed
    

Is it possible to interactively delete matching search pattern in Vim?

There are 3 ways I can think of:

The way that is easiest to explain is

:%s/phrase to delete//gc

but you can also (personally I use this second one more often) do a regular search for the phrase to delete

/phrase to delete

Vim will take you to the beginning of the next occurrence of the phrase.

Go into insert mode (hit i) and use the Delete key to remove the phrase.

Hit escape when you have deleted all of the phrase.

Now that you have done this one time, you can hit n to go to the next occurrence of the phrase and then hit the dot/period "." key to perform the delete action you just performed

Continue hitting n and dot until you are done.

Lastly you can do a search for the phrase to delete (like in second method) but this time, instead of going into insert mode, you

Count the number of characters you want to delete

Type that number in (with number keys)

Hit the x key - characters should get deleted

Continue through with n and dot like in the second method.

PS - And if you didn't know already you can do a capital n to move backwards through the search matches.

How do I enumerate the properties of a JavaScript object?

Here's how to enumerate an object's properties:

var params = { name: 'myname', age: 'myage' }

for (var key in params) {
  alert(key + "=" + params[key]);
}

Why use ICollection and not IEnumerable or List<T> on many-many/one-many relationships?

There are some basics difference between ICollection and IEnumerable

  • IEnumerable - contains only GetEnumerator method to get Enumerator and allows looping
  • ICollection contains additional methods: Add, Remove, Contains, Count, CopyTo
  • ICollection is inherited from IEnumerable
  • With ICollection you can modify the collection by using the methods like add/remove. You don't have the liberty to do the same with IEnumerable.

Simple Program:

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

namespace StackDemo
{
    class Program 
    {
        static void Main(string[] args)
        {
            List<Person> persons = new List<Person>();
            persons.Add(new Person("John",30));
            persons.Add(new Person("Jack", 27));

            ICollection<Person> personCollection = persons;
            IEnumerable<Person> personEnumeration = persons;

            // IEnumeration
            // IEnumration Contains only GetEnumerator method to get Enumerator and make a looping
            foreach (Person p in personEnumeration)
            {                                   
               Console.WriteLine("Name:{0}, Age:{1}", p.Name, p.Age);
            }

            // ICollection
            // ICollection Add/Remove/Contains/Count/CopyTo
            // ICollection is inherited from IEnumerable
            personCollection.Add(new Person("Tim", 10));

            foreach (Person p in personCollection)
            {
                Console.WriteLine("Name:{0}, Age:{1}", p.Name, p.Age);        
            }
            Console.ReadLine();

        }
    }

    class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public Person(string name, int age)
        {
            this.Name = name;
            this.Age = age;
        }
    }
}

I keep getting "Uncaught SyntaxError: Unexpected token o"

Another hints for Unexpected token errors. There are two major differences between javascript objects and json:

  1. json data must be always quoted with double quotes.
  2. keys must be quoted

Correct JSON

 {
    "english": "bag",
    "kana": "kaban",
    "kanji": "K"
}

Error JSON 1

 {
    'english': 'bag',
    'kana': 'kaban',
    'kanji': 'K'
 }

Error JSON 2

 {
    english: "bag",
    kana: "kaban",
    kanji: "K"
}

Remark

This is not a direct answer for that question. But it's an answer for Unexpected token errors. So it may be help others who stumple upon that question.

ADB Shell Input Events

To send a reload call to a React-Native app running in a android device: adb shell input keyboard text "rr"

Is mongodb running?

this should work fine...

pgrep mongod

JQuery - how to select dropdown item based on value

You can select dropdown option value by name

// deom
jQuery("#option_id").find("option:contains('Monday')").each(function()
{
 if( jQuery(this).text() == 'Monday' )
 {
  jQuery(this).attr("selected","selected");
  }

});

Clear ComboBox selected text

This is what you need:

comboBox1.ResetText();

Use Awk to extract substring

You don't need awk for this...

echo aaa0.bbb.ccc | cut -d. -f1
cut -d. -f1 <<< aaa0.bbb.ccc

echo aaa0.bbb.ccc | { IFS=. read a _ ; echo $a ; }
{ IFS=. read a _ ; echo $a ; } <<< aaa0.bbb.ccc 

x=aaa0.bbb.ccc; echo ${x/.*/}

Heavier options:

sed:
echo aaa0.bbb.ccc | sed 's/\..*//'
sed 's/\..*//' <<< aaa0.bbb.ccc 
awk:
echo aaa0.bbb.ccc | awk -F. '{print $1}'
awk -F. '{print $1}' <<< aaa0.bbb.ccc 

Display TIFF image in all web browser

You can try converting your image from tiff to PNG, here is how to do it:

import com.sun.media.jai.codec.ImageCodec;
import com.sun.media.jai.codec.ImageDecoder;
import com.sun.media.jai.codec.ImageEncoder;
import com.sun.media.jai.codec.PNGEncodeParam;
import com.sun.media.jai.codec.TIFFDecodeParam;
import java.awt.image.RenderedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import javaxt.io.Image;

public class ImgConvTiffToPng {

    public static byte[] convert(byte[] tiff) throws Exception {

        byte[] out = new byte[0];
        InputStream inputStream = new ByteArrayInputStream(tiff);

        TIFFDecodeParam param = null;

        ImageDecoder dec = ImageCodec.createImageDecoder("tiff", inputStream, param);
        RenderedImage op = dec.decodeAsRenderedImage(0);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        PNGEncodeParam jpgparam = null;
        ImageEncoder en = ImageCodec.createImageEncoder("png", outputStream, jpgparam);
        en.encode(op);
        outputStream = (ByteArrayOutputStream) en.getOutputStream();
        out = outputStream.toByteArray();
        outputStream.flush();
        outputStream.close();

        return out;

    }

How to get the file path from HTML input form in Firefox 3

This is an example that could work for you if what you need is not exactly the path, but a reference to the file working offline.

http://www.ab-d.fr/date/2008-07-12/

It is in french, but the code is javascript :)

This are the references the article points to: http://developer.mozilla.org/en/nsIDOMFile http://developer.mozilla.org/en/nsIDOMFileList

How can I fix WebStorm warning "Unresolved function or method" for "require" (Firefox Add-on SDK)

Another solution that helped me a lot is to update all libs in "Node.js and NPM". You need just mark all libs and click blue arrow - 'update' enter image description here

How to display raw html code in PRE or something like it but without escaping it

If you have jQuery enabled you can use an escapeXml function and not have to worry about escaping arrows or special characters.

<pre>
  ${fn:escapeXml('
    <!-- all your code --> 
  ')};
</pre>

How to select an element by classname using jqLite?

angualr uses the lighter version of jquery called as jqlite which means it doesnt have all the features of jQuery. here is a reference in angularjs docs about what you can use from jquery. Angular Element docs

In your case you need to find a div with ID or class name. for class name you can use

var elems =$element.find('div') //returns all the div's in the $elements
    angular.forEach(elems,function(v,k)){
    if(angular.element(v).hasClass('class-name')){
     console.log(angular.element(v));
}}

or you can use much simpler way by query selector

angular.element(document.querySelector('#id'))

angular.element(elem.querySelector('.classname'))

it is not as flexible as jQuery but what

How to check whether a variable is a class or not?

class Foo: is called old style class and class X(object): is called new style class.

Check this What is the difference between old style and new style classes in Python? . New style is recommended. Read about "unifying types and classes"

Using LIKE operator with stored procedure parameters

I was working on same. Check below statement. Worked for me!!


SELECT * FROM [Schema].[Table] WHERE [Column] LIKE '%' + @Parameter + '%'

SQL Server copy all rows from one table into another i.e duplicate table

This will work:

select * into DestinationDatabase.dbo.[TableName1] from (
Select * from sourceDatabase.dbo.[TableName1])Temp

Horizontal list items

A much better way is to use inline-block, because you don't need to use clear:both at the end of your list anymore.

Try this:

<ul>
    <li>
        <a href="#">some item</a>
    </li>
    <li>
        <a href="#">another item</a>
    </li>
</ul>

CSS:

ul > li{
    display:inline-block;
}

Have a look at it here : http://jsfiddle.net/shahverdy/4N6Ap/

How to remove white space characters from a string in SQL Server

Using ASCII(RIGHT(ProductAlternateKey, 1)) you can see that the right most character in row 2 is a Line Feed or Ascii Character 10.

This can not be removed using the standard LTrim RTrim functions.

You could however use (REPLACE(ProductAlternateKey, CHAR(10), '')

You may also want to account for carriage returns and tabs. These three (Line feeds, carriage returns and tabs) are the usual culprits and can be removed with the following :

LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(ProductAlternateKey, CHAR(10), ''), CHAR(13), ''), CHAR(9), '')))

If you encounter any more "white space" characters that can't be removed with the above then try one or all of the below:

--NULL
Replace([YourString],CHAR(0),'');
--Horizontal Tab
Replace([YourString],CHAR(9),'');
--Line Feed
Replace([YourString],CHAR(10),'');
--Vertical Tab
Replace([YourString],CHAR(11),'');
--Form Feed
Replace([YourString],CHAR(12),'');
--Carriage Return
Replace([YourString],CHAR(13),'');
--Column Break
Replace([YourString],CHAR(14),'');
--Non-breaking space
Replace([YourString],CHAR(160),'');

This list of potential white space characters could be used to create a function such as :

Create Function [dbo].[CleanAndTrimString] 
(@MyString as varchar(Max))
Returns varchar(Max)
As
Begin
    --NULL
    Set @MyString = Replace(@MyString,CHAR(0),'');
    --Horizontal Tab
    Set @MyString = Replace(@MyString,CHAR(9),'');
    --Line Feed
    Set @MyString = Replace(@MyString,CHAR(10),'');
    --Vertical Tab
    Set @MyString = Replace(@MyString,CHAR(11),'');
    --Form Feed
    Set @MyString = Replace(@MyString,CHAR(12),'');
    --Carriage Return
    Set @MyString = Replace(@MyString,CHAR(13),'');
    --Column Break
    Set @MyString = Replace(@MyString,CHAR(14),'');
    --Non-breaking space
    Set @MyString = Replace(@MyString,CHAR(160),'');

    Set @MyString = LTRIM(RTRIM(@MyString));
    Return @MyString
End
Go

Which you could then use as follows:

Select 
    dbo.CleanAndTrimString(ProductAlternateKey) As ProductAlternateKey
from DimProducts

MySQL default datetime through phpmyadmin

You can't set CURRENT_TIMESTAMP as default value with DATETIME.

But you can do it with TIMESTAMP.

See the difference here.

Words from this blog

The DEFAULT value clause in a data type specification indicates a default value for a column. With one exception, the default value must be a constant; it cannot be a function or an expression.

This means, for example, that you cannot set the default for a date column to be the value of a function such as NOW() or CURRENT_DATE.

The exception is that you can specify CURRENT_TIMESTAMP as the default for a TIMESTAMP column.

Parameterize an SQL IN clause

For a variable number of arguments like this the only way I'm aware of is to either generate the SQL explicitly or do something that involves populating a temporary table with the items you want and joining against the temp table.

Rails - How to use a Helper Inside a Controller

You can use

  • helpers.<helper> in Rails 5+ (or ActionController::Base.helpers.<helper>)
  • view_context.<helper> (Rails 4 & 3) (WARNING: this instantiates a new view instance per call)
  • @template.<helper> (Rails 2)
  • include helper in a singleton class and then singleton.helper
  • include the helper in the controller (WARNING: will make all helper methods into controller actions)

How to define an optional field in protobuf 3

In proto3, all fields are "optional" (in that it is not an error if the sender fails to set them). But, fields are no longer "nullable", in that there's no way to tell the difference between a field being explicitly set to its default value vs. not having been set at all.

If you need a "null" state (and there is no out-of-range value that you can use for this) then you will instead need to encode this as a separate field. For instance, you could do:

message Foo {
  bool has_baz = 1;  // always set this to "true" when using baz
  int32 baz = 2;
}

Alternatively, you could use oneof:

message Foo {
  oneof baz {
    bool baz_null = 1;  // always set this to "true" when null
    int32 baz_value = 2;
  }
}

The oneof version is more explicit and more efficient on the wire but requires understanding how oneof values work.

Finally, another perfectly reasonable option is to stick with proto2. Proto2 is not deprecated, and in fact many projects (including inside Google) very much depend on proto2 features which are removed in proto3, hence they will likely never switch. So, it's safe to keep using it for the foreseeable future.

JPanel setBackground(Color.BLACK) does nothing

If your panel is 'not opaque' (transparent) you wont see your background color.

Iterate over object keys in node.js

Also remember that you can pass a second argument to the .forEach() function specifying the object to use as the this keyword.

// myOjbect is the object you want to iterate.
// Notice the second argument (secondArg) we passed to .forEach.
Object.keys(myObject).forEach(function(element, key, _array) {
  // element is the name of the key.
  // key is just a numerical value for the array
  // _array is the array of all the keys

  // this keyword = secondArg
  this.foo;
  this.bar();
}, secondArg);

Rendering JSON in controller

For the instance of

render :json => @projects, :include => :tasks

You are stating that you want to render @projects as JSON, and include the association tasks on the Project model in the exported data.

For the instance of

render :json => @projects, :callback => 'updateRecordDisplay'

You are stating that you want to render @projects as JSON, and wrap that data in a javascript call that will render somewhat like:

updateRecordDisplay({'projects' => []})

This allows the data to be sent to the parent window and bypass cross-site forgery issues.

What is the difference between a static method and a non-static method?

A static method belongs to the class itself and a non-static (aka instance) method belongs to each object that is generated from that class. If your method does something that doesn't depend on the individual characteristics of its class, make it static (it will make the program's footprint smaller). Otherwise, it should be non-static.

Example:

class Foo {
    int i;

    public Foo(int i) { 
       this.i = i;
    }

    public static String method1() {
       return "An example string that doesn't depend on i (an instance variable)";
    }

    public int method2() {
       return this.i + 1; // Depends on i
    }
}

You can call static methods like this: Foo.method1(). If you try that with method2, it will fail. But this will work: Foo bar = new Foo(1); bar.method2();

#1142 - SELECT command denied to user ''@'localhost' for table 'pma_table_uiprefs'

If you use XAMPP Path ( $cfg['Servers'][$i]['pmadb'] = 'phpmyadmin'; ) C:\xampp\phpmyadmin\config.inc.php (Probably XAMPP1.8 at Line Number 34)

Another Solution: I face same type problem "#1142 - SELECT command denied to user ''@'localhost' for table 'pma_recent'"

  1. open phpmyadmin==>setting==>Navigation frame==> Recently used tables==>0(set the value 0) ==> Save

Java Interfaces/Implementation naming convention

Some people don't like this, and it's more of a .NET convention than Java, but you can name your interfaces with a capital I prefix, for example:

IProductRepository - interface
ProductRepository, SqlProductRepository, etc. - implementations

The people opposed to this naming convention might argue that you shouldn't care whether you're working with an interface or an object in your code, but I find it easier to read and understand on-the-fly.

I wouldn't name the implementation class with a "Class" suffix. That may lead to confusion, because you can actually work with "class" (i.e. Type) objects in your code, but in your case, you're not working with the class object, you're just working with a plain-old object.

How can I check whether a radio button is selected with JavaScript?

With JQuery, another way to check the current status of the radio buttons is to get the attribute 'checked'.

For Example:

<input type="radio" name="gender_male" value="Male" />
<input type="radio" name="gender_female" value="Female" />

In this case you can check the buttons using:

if ($("#gender_male").attr("checked") == true) {
...
}

Set value of input instead of sendKeys() - Selenium WebDriver nodejs

An alternative way of sending a large number of repeating characters to a text field (for instance to test the maximum number of characters the field will allow) is to type a few characters and then repeatedly copy and paste them:

inputField.sendKeys('0123456789');
for(int i = 0; i < 100; i++) {
    inputField.sendKeys(Key.chord(Key.CONTROL, 'a'));
    inputField.sendKeys(Key.chord(Key.CONTROL, 'c'));
    for(int i = 0; i < 10; i++) {
        inputField.sendKeys(Key.chord(Key.CONTROL, 'v'));
    }
}

Unfortunately pressing CTRL doesn't seem to work for IE unless REQUIRE_WINDOW_FOCUS is enabled (which can cause other issues), but it works fine for Firefox and Chrome.

bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml. Do you need to install a parser library?

Actually 3 of the options mentioned by other work.

1.

soup_object= BeautifulSoup(markup,"html.parser") #Python HTML parser
pip install lxml

soup_object= BeautifulSoup(markup,'lxml') # C dependent parser 
pip install html5lib

soup_object= BeautifulSoup(markup,'html5lib') # C dependent parser 

How would I find the second largest salary from the employee table?

Most of the other answers seem to be db specific.

General SQL query should be as follows:

select
   sal 
from
   emp a 
where
   N = (
      select
         count(distinct sal) 
      from
         emp b 
      where
         a.sal <= b.sal
   )
where
   N = any value

and this query should be able to work on any database.

Rename a column in MySQL

From MySQL 8.0 you could use

ALTER TABLE table_name RENAME COLUMN old_col_name TO new_col_name;

ALTER TABLE Syntax:

RENAME COLUMN:

  • Can change a column name but not its definition.

  • More convenient than CHANGE to rename a column without changing its definition.

DBFiddle Demo

warning: control reaches end of non-void function [-Wreturn-type]

You can also use EXIT_SUCCESS instead of return 0;. The macro EXIT_SUCCESS is actually defined as zero, but makes your program more readable.

How can I use ":" as an AWK field separator?

AWK works as a text interpreter that goes linewise for the whole document and that goes fieldwise for each line. Thus $1, $2...$n are references to the fields of each line ($1 is the first field, $2 is the second field, and so on...).

You can define a field separator by using the "-F" switch under the command line or within two brackets with "FS=...".

Now consider the answer of Jürgen:

echo "1: " | awk -F  ":" '/1/ {print $1}'

Above the field, boundaries are set by ":" so we have two fields $1 which is "1" and $2 which is the empty space. After comes the regular expression "/1/" that instructs the filter to output the first field only when the interpreter stumbles upon a line containing such an expression (I mean 1).

The output of the "echo" command is one line that contains "1", so the filter will work...

When dealing with the following example:

echo "1: " | awk '/1/ -F ":" {print $1}'

The syntax is messy and the interpreter chose to ignore the part F ":" and switches to the default field splitter which is the empty space, thus outputting "1:" as the first field and there will be not a second field!

The answer of Jürgen contains the good syntax...

How do I update a model value in JavaScript in a Razor view?

This should work

function updatePostID(val)
{
    document.getElementById('PostID').value = val;

    //and probably call document.forms[0].submit();
}

Then have a hidden field or other control for the PostID

@Html.Hidden("PostID", Model.addcomment.PostID)
//OR
@Html.HiddenFor(model => model.addcomment.PostID)

Safely turning a JSON string into an object

Try this.This one is written in typescript.

         export function safeJsonParse(str: string) {
               try {
                 return JSON.parse(str);
                   } catch (e) {
                 return str;
                 }
           }

How to calculate rolling / moving average using NumPy / SciPy?

By comparing the solution below with the one that uses cumsum of numpy, This one takes almost half the time. This is because it does not need to go through the entire array to do the cumsum and then do all the subtraction. Moreover, the cumsum can be "dangerous" if the array is huge and the number are huge (possible overflow). Of course, also here the danger exists but at least are summed together only the essential numbers.

def moving_average(array_numbers, n):
    if n > len(array_numbers):
      return []
    temp_sum = sum(array_numbers[:n])
    averages = [temp_sum / float(n)]
    for first_index, item in enumerate(array_numbers[n:]):
        temp_sum += item - array_numbers[first_index]
        averages.append(temp_sum / float(n))
    return averages

Redirecting exec output to a buffer or file

After forking, use dup2(2) to duplicate the file's FD into stdout's FD, then exec.

Submit button doesn't work

If you are not using any javascript/jquery for form validation, then a simple layout for your form would look like this.

within the body of your html document:

<form action="formHandler.php" name="yourForm" id="theForm" method="post">    
    <input type="text" name="fname" id="fname" />    
    <input type="submit" value="submit"/>
</form>

You need to ensure you have the submit button within the form tags, and an appropriate action assigned. Such as sending to a php file.

For a more direct answer, provide the code you are working with.

You may find the following of use: http://www.w3.org/TR/html401/interact/forms.html

Relative path to absolute path in C#?

This worked for me.

//used in an ASP.NET MVC app
private const string BatchFilePath = "/MyBatchFileDirectory/Mybatchfiles.bat"; 
var batchFile = HttpContext.Current.Server.MapPath(BatchFilePath);

"Invalid form control" only in Google Chrome

Chrome wants to focus on a control that is required but still empty so that it can pop up the message 'Please fill out this field'. However, if the control is hidden at the point that Chrome wants to pop up the message, that is at the time of form submission, Chrome can't focus on the control because it is hidden, therefore the form won't submit.

So, to get around the problem, when a control is hidden by javascript, we also must remove the 'required' attribute from that control.

HTML tag <a> want to add both href and onclick working

Use ng-click in place of onclick. and its as simple as that:

<a href="www.mysite.com" ng-click="return theFunction();">Item</a>

<script type="text/javascript">
function theFunction () {
    // return true or false, depending on whether you want to allow 
    // the`href` property to follow through or not
 }
</script>

jQuery - Increase the value of a counter when a button is clicked

It's just

var counter = 0;

$("#update").click(function() {
   counter++;
});

How do I clone a specific Git branch?

Here is a really simple way to do it :)

Clone the repository

git clone <repository_url>

List all branches

git branch -a 

Checkout the branch that you want

git checkout <name_of_branch>

How to write a stored procedure using phpmyadmin and how to use it through php?

try this

delimiter ;;

drop procedure if exists test2;;

create procedure test2()

begin

select ‘Hello World’;

end

;;

mysql Foreign key constraint is incorrectly formed error

Just for completion.

This error might be as well the case if you have a foreign key with VARCHAR(..) and the charset of the referenced table is different from the table referencing it.

e.g. VARCHAR(50) in a Latin1 Table is different than the VARCHAR(50) in a UTF8 Table.

zsh compinit: insecure directories

My suggestion would be to run compaudit and then just fix permissions on the directories found by the audit. Make sure the identified directories do not have write permissions for group or other.

Redirect with CodeIgniter

If you want to redirect previous location or last request then you have to include user_agent library:

$this->load->library('user_agent');

and then use at last in a function that you are using:

redirect($this->agent->referrer());

its working for me.

How to format a float in javascript?

The key here I guess is to round up correctly first, then you can convert it to String.

function roundOf(n, p) {
    const n1 = n * Math.pow(10, p + 1);
    const n2 = Math.floor(n1 / 10);
    if (n1 >= (n2 * 10 + 5)) {
        return (n2 + 1) / Math.pow(10, p);
    }
    return n2 / Math.pow(10, p);
}

// All edge cases listed in this thread
roundOf(95.345, 2); // 95.35
roundOf(95.344, 2); // 95.34
roundOf(5.0364342423, 2); // 5.04
roundOf(0.595, 2); // 0.60
roundOf(0.335, 2); // 0.34
roundOf(0.345, 2); // 0.35
roundOf(551.175, 2); // 551.18
roundOf(0.3445434, 2); // 0.34

Now you can safely format this value with toFixed(p). So with your specific case:

roundOf(0.3445434, 2).toFixed(2); // 0.34

What is a deadlock?

Deadlock occurs when a thread is waiting for other thread to finish and vice versa.

How to avoid?
- Avoid Nested Locks
- Avoid Unnecessary Locks
- Use thread join()

How do you detect it?
run this command in cmd:

jcmd $PID Thread.print

reference : geeksforgeeks

Trigger css hover with JS

If you bind events to the onmouseover and onmouseout events in Jquery, you can then trigger that effect using mouseenter().

What are you trying to accomplish?

How to implement DrawerArrowToggle from Android appcompat v7 21 library

I want to correct little bit the above code

    public class MainActivity extends ActionBarActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
        DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(
            this,  mDrawerLayout, mToolbar,
            R.string.navigation_drawer_open, R.string.navigation_drawer_close
        );
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
    }

and all the other things will remain same...

For those who are having problem Drawerlayout overlaying toolbar

add android:layout_marginTop="?attr/actionBarSize" to root layout of drawer content

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

On a rather unrelated note: more performance hacks!

  • [the first «conjecture» has been finally debunked by @ShreevatsaR; removed]

  • When traversing the sequence, we can only get 3 possible cases in the 2-neighborhood of the current element N (shown first):

    1. [even] [odd]
    2. [odd] [even]
    3. [even] [even]

    To leap past these 2 elements means to compute (N >> 1) + N + 1, ((N << 1) + N + 1) >> 1 and N >> 2, respectively.

    Let`s prove that for both cases (1) and (2) it is possible to use the first formula, (N >> 1) + N + 1.

    Case (1) is obvious. Case (2) implies (N & 1) == 1, so if we assume (without loss of generality) that N is 2-bit long and its bits are ba from most- to least-significant, then a = 1, and the following holds:

    (N << 1) + N + 1:     (N >> 1) + N + 1:
    
            b10                    b1
             b1                     b
           +  1                   + 1
           ----                   ---
           bBb0                   bBb
    

    where B = !b. Right-shifting the first result gives us exactly what we want.

    Q.E.D.: (N & 1) == 1 ? (N >> 1) + N + 1 == ((N << 1) + N + 1) >> 1.

    As proven, we can traverse the sequence 2 elements at a time, using a single ternary operation. Another 2× time reduction.

The resulting algorithm looks like this:

uint64_t sequence(uint64_t size, uint64_t *path) {
    uint64_t n, i, c, maxi = 0, maxc = 0;

    for (n = i = (size - 1) | 1; i > 2; n = i -= 2) {
        c = 2;
        while ((n = ((n & 3)? (n >> 1) + n + 1 : (n >> 2))) > 2)
            c += 2;
        if (n == 2)
            c++;
        if (c > maxc) {
            maxi = i;
            maxc = c;
        }
    }
    *path = maxc;
    return maxi;
}

int main() {
    uint64_t maxi, maxc;

    maxi = sequence(1000000, &maxc);
    printf("%llu, %llu\n", maxi, maxc);
    return 0;
}

Here we compare n > 2 because the process may stop at 2 instead of 1 if the total length of the sequence is odd.

[EDIT:]

Let`s translate this into assembly!

MOV RCX, 1000000;



DEC RCX;
AND RCX, -2;
XOR RAX, RAX;
MOV RBX, RAX;

@main:
  XOR RSI, RSI;
  LEA RDI, [RCX + 1];

  @loop:
    ADD RSI, 2;
    LEA RDX, [RDI + RDI*2 + 2];
    SHR RDX, 1;
    SHRD RDI, RDI, 2;    ror rdi,2   would do the same thing
    CMOVL RDI, RDX;      Note that SHRD leaves OF = undefined with count>1, and this doesn't work on all CPUs.
    CMOVS RDI, RDX;
    CMP RDI, 2;
  JA @loop;

  LEA RDX, [RSI + 1];
  CMOVE RSI, RDX;

  CMP RAX, RSI;
  CMOVB RAX, RSI;
  CMOVB RBX, RCX;

  SUB RCX, 2;
JA @main;



MOV RDI, RCX;
ADD RCX, 10;
PUSH RDI;
PUSH RCX;

@itoa:
  XOR RDX, RDX;
  DIV RCX;
  ADD RDX, '0';
  PUSH RDX;
  TEST RAX, RAX;
JNE @itoa;

  PUSH RCX;
  LEA RAX, [RBX + 1];
  TEST RBX, RBX;
  MOV RBX, RDI;
JNE @itoa;

POP RCX;
INC RDI;
MOV RDX, RDI;

@outp:
  MOV RSI, RSP;
  MOV RAX, RDI;
  SYSCALL;
  POP RAX;
  TEST RAX, RAX;
JNE @outp;

LEA RAX, [RDI + 59];
DEC RDI;
SYSCALL;

Use these commands to compile:

nasm -f elf64 file.asm
ld -o file file.o

See the C and an improved/bugfixed version of the asm by Peter Cordes on Godbolt. (editor's note: Sorry for putting my stuff in your answer, but my answer hit the 30k char limit from Godbolt links + text!)

Printing out a linked list using toString

A very simple solution is to override the toString() method in the Node. Then, you can call print by passing LinkedList's head. You don't need to implement any kind of loop.

Code:

public class LinkedListNode {
    ...

    //New
    @Override
    public String toString() {
        return String.format("Node(%d, next = %s)", data, next);
    }
} 


public class LinkedList {

    public static void main(String[] args) {

        LinkedList l = new LinkedList();
        l.insertFront(0);
        l.insertFront(1);
        l.insertFront(2);
        l.insertFront(3);

        //New
        System.out.println(l.head);
    }
}

Using continue in a switch statement

Yes, it's OK - it's just like using it in an if statement. Of course, you can't use a break to break out of a loop from inside a switch.

How to convert/parse from String to char in java?

If you want to parse a String to a char, whereas the String object represent more than one character, you just simply use the following expression: char c = (char) Integer.parseInt(s). Where s equals the String you want to parse. Most people forget that char's represent a 16-bit number, and thus can be a part of any numerical expression :)

Sort objects in ArrayList by date?

This may be an old response but I used some examples from this post to create a comparator that would sort an ArrayList of HashMap<String, String> by one object in the list, that being the timestamp.

I have these objects:

ArrayList<Map<String, String>> alList = new ArrayList<Map<String, String>>();

The map objects are as follows:

Map<String, Object> map = new HashMap<>();
        // of course this is the actual formatted date below in the timestamp
        map.put("timestamp", "MM/dd/yyyy HH:mm:ss"); 
        map.put("item1", "my text goes here");
        map.put("item2", "my text goes here");

That mapping is what I use to load all my objects into the array list, using the alList.add(map) function, within a loop.

Now, I created my own comparator:

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

 public class DateSorter implements Comparator {
     public int compare(Object firstObjToCompare, Object secondObjToCompare) {
    String firstDateString = ((HashMap<String, String>) firstObjToCompare).get("timestamp");
    String secondDateString = ((HashMap<String, String>) secondObjToCompare).get("timestamp");

    if (secondDateString == null || firstDateString == null) {
        return 0;
    }

    // Convert to Dates
    DateTimeFormatter dtf = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
    DateTime firstDate = dtf.parseDateTime(firstDateString);
    DateTime secondDate = dtf.parseDateTime(secondDateString);

    if (firstDate.isAfter(secondDate)) return -1;
    else if (firstDate.isBefore(secondDate)) return 1;
    else return 0;
    }
}

I can now just call the Comparator at any time on the array and it will sort my array, giving me the Latest timestamp in position 0 (top of the list) and the earliest timestamp at the end of the list. New posts get put to the top basically.

Collections.sort(alList, new DateSorter());

This may help someone out, which is why I posted it. Take into consideration the return statements within the compare() function. There are 3 types of results. Returning 0 if they are equal, returning >0 if the first date is before the second date and returning <0 if the first date is after the second date. If you want your list to be reversed, then just switch those two return statements! Simple =]

Asp.net - <customErrors mode="Off"/> error when trying to access working webpage

Sometime in the future Comment out the following code in web.config

 <!--<system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>-->

update the to the following code.

<system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1" />
    <customErrors mode="Off"/>
    <trust level="Full"/>
  </system.web>

ERROR 1064 (42000) in MySQL

Faced the same issue. Indeed it was wrong SQL at the beginning of the file because when dumping I did:

mysqldump -u username --password=password db_name > dump.sql

Which wrote at the beginning of the file something that was in stdout which was:

mysqldump: [Warning] Using a password on the command line interface can be insecure.

Resulting in the restore raising that error.

So deleting the first line of the SQL dump enables a proper restore.

Looking at the way the restore was done in the original question, there is a high chance the dump was done similarly as mine, causing a stdout warning printing in the SQL file (if ever mysqldump was printing it back then).

What is "not assignable to parameter of type never" error in typescript?

You need to type result to an array of string const result: string[] = [];.

Trigger a Travis-CI rebuild without pushing a commit?

I just triggered the tests on a pull request to be re-run by clicking 'update branch' here: github check tests component

Display a table/list data dynamically in MVC3/Razor from a JsonResult?

The normal way of doing it is:

  • You get the users from the database in controller.
  • You send a collection of users to the View
  • In the view to loop the list of users building the list.

You don't need a JsonResult or jQuery for this.

OS X Framework Library not loaded: 'Image not found'

I experienced that problem only when running on real device (iPhone SE). On simulator project worked as expected.

I did try all fixes from this very thread and from here. None of those worked for me.

For me problem was solved after restarting iPhone (sic!).

I did:

  • clean build folder,
  • clean derived data,
  • delete app from device,
  • reboot device

And it finally works. :)

If every other solution fails don't forget to try it out.

Making RGB color in Xcode

Color picker plugin for Interface Builder

There's a nice color picker from Panic which works well with IB: http://panic.com/~wade/picker/

Xcode plugin

This one gives you a GUI for choosing colors: http://www.youtube.com/watch?v=eblRfDQM0Go

Objective-C

UIColor *color = [UIColor colorWithRed:(160/255.0) green:(97/255.0) blue:(5/255.0) alpha:1.0];

Swift

let color = UIColor(red: 160/255, green: 97/255, blue: 5/255, alpha: 1.0)

Pods and libraries

There's a nice pod named MPColorTools: https://github.com/marzapower/MPColorTools

TypeError: 'float' object not iterable

use

range(count)

int and float are not iterable

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

I would use @HostListener decorator within your component:

import { HostListener } from '@angular/core';

@Component({
  ...
})
export class AppComponent {

  @HostListener('document:keypress', ['$event'])
  handleKeyboardEvent(event: KeyboardEvent) { 
    this.key = event.key;
  }
}

There are also other options like:

host property within @Component decorator

Angular recommends using @HostListener decorator over host property https://angular.io/guide/styleguide#style-06-03

@Component({
  ...
  host: {
    '(document:keypress)': 'handleKeyboardEvent($event)'
  }
})
export class AppComponent {
  handleKeyboardEvent(event: KeyboardEvent) {
    console.log(event);
  }
}

renderer.listen

import { Component, Renderer2 } from '@angular/core';

@Component({
  ...
})
export class AppComponent {
  globalListenFunc: Function;

  constructor(private renderer: Renderer2) {}

  ngOnInit() {
    this.globalListenFunc = this.renderer.listen('document', 'keypress', e => {
      console.log(e);
    });
  }

  ngOnDestroy() {
    // remove listener
    this.globalListenFunc();
  }
}

Observable.fromEvent

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
import { Subscription } from 'rxjs/Subscription';

@Component({
  ...
})
export class AppComponent {
  subscription: Subscription;

  ngOnInit() {
    this.subscription = Observable.fromEvent(document, 'keypress').subscribe(e => {
      console.log(e);
    })
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

Enable tcp\ip remote connections to sql server express already installed database with code or script(query)

I recommend to use SMO (Enable TCP/IP Network Protocol for SQL Server). However, it was not available in my case.

I rewrote the WMI commands from Krzysztof Kozielczyk to PowerShell.

# Enable TCP/IP

Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocol -Filter "InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'" |
Invoke-CimMethod -Name SetEnable

# Open the right ports in the firewall
New-NetFirewallRule -DisplayName 'MSSQL$SQLEXPRESS' -Direction Inbound -Action Allow -Protocol TCP -LocalPort 1433

# Modify TCP/IP properties to enable an IP address

$properties = Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocolProperty -Filter "InstanceName='SQLEXPRESS' and ProtocolName = 'Tcp' and IPAddressName='IPAll'"
$properties | ? { $_.PropertyName -eq 'TcpPort' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '1433' }
$properties | ? { $_.PropertyName -eq 'TcpPortDynamic' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '' }

# Restart SQL Server

Restart-Service 'MSSQL$SQLEXPRESS'

How do you change the character encoding of a postgres database?

To change the encoding of your database:

  1. Dump your database
  2. Drop your database,
  3. Create new database with the different encoding
  4. Reload your data.

Make sure the client encoding is set correctly during all this.

Source: http://archives.postgresql.org/pgsql-novice/2006-03/msg00210.php

how to open a url in python

Here is another way to do it.

import webbrowser

webbrowser.open("foobar.com")

Select objects based on value of variable in object using jq

Just try this one as a full copy paste in the shell and you will grasp it

# create the example file to  be working on .. 
cat << EOF > tmp.json
[  
 { "card_id": "id-00", "card_id_type": "card_id_type-00"},
 {"card_id": "id-01", "card_id_type": "card_id_type-01"},
 {  "card_id": "id-02", "card_id_type": "card_id_type-02"}
]
EOF


# pipe the content of the file to the  jq query, which gets the array of objects
# and select the attribute named "card_id" ONLY if it's neighbour attribute
# named "card_id_type" has the "card_id_type-01" value
# jq -r means give me ONLY the value of the jq query no quotes aka raw
cat tmp.json | jq -r '.[]| select (.card_id_type == "card_id_type-01")|.card_id'

id-01

or with an aws cli command

 # list my vpcs or
 # list the values of the tags which names are "Name" 
 aws ec2 describe-vpcs | jq -r '.| .Vpcs[].Tags[]|select (.Key == "Name") | .Value'|sort  -nr

Vue template or render function not defined yet I am using neither?

Something like this should resolve the issue..

Vue.component(
'example-component', 
require('./components/ExampleComponent.vue').default);

Selenium WebDriver: I want to overwrite value in field instead of appending to it with sendKeys using Java

I think you can try to firstly select all the text in the field and then send the new sequence:

from selenium.webdriver.common.keys import Keys
element.sendKeys(Keys.chord(Keys.CONTROL, "a"), "55");

How to determine if a number is positive or negative?

Combined generics with double API. Guess it's a bit of cheating, but at least we need to write only one method:

static <T extends Number> boolean isNegative(T number)
{       
    return ((number.doubleValue() * Double.POSITIVE_INFINITY) == Double.NEGATIVE_INFINITY);
}

Cleanest way to toggle a boolean variable in Java?

This answer came up when searching for "java invert boolean function". The example below will prevent certain static analysis tools from failing builds due to branching logic. This is useful if you need to invert a boolean and haven't built out comprehensive unit tests ;)

Boolean.valueOf(aBool).equals(false)

or alternatively:

Boolean.FALSE.equals(aBool)

or

Boolean.FALSE::equals

The type must be a reference type in order to use it as parameter 'T' in the generic type or method

I can't repro, but I suspect that in your actual code there is a constraint somewhere that T : class - you need to propagate that to make the compiler happy, for example (hard to say for sure without a repro example):

public class Derived<SomeModel> : Base<SomeModel> where SomeModel : class, IModel
                                                                    ^^^^^
                                                                 see this bit

Convert String to Uri

Java's parser in java.net.URI is going to fail if the URI isn't fully encoded to its standards. For example, try to parse: http://www.google.com/search?q=cat|dog. An exception will be thrown for the vertical bar.

urllib makes it easy to convert a string to a java.net.URI. It will pre-process and escape the URL.

assertEquals("http://www.google.com/search?q=cat%7Cdog",
    Urls.createURI("http://www.google.com/search?q=cat|dog").toString());

jquery how to empty input field

Setting val('') will empty the input field. So you would use this:

Clear the input field when the page loads:

$(function(){
    $('#shares').val('');
});

This could be due to the service endpoint binding not using the HTTP protocol

In my instance, the error was generated because one of my complex types had a property with no set method.

The serializer threw an exception because of that fact. Added internal set methods and it all worked fine.

Best way to find out why this is happening (in my opinion) is to enable trace logging.

I achieved this by adding the following section to my web.config:

<system.diagnostics>
  <sources>
    <source name="System.ServiceModel.MessageLogging" switchValue="Warning,ActivityTracing">
      <listeners>
        <add name="traceListener"
              type="System.Diagnostics.XmlWriterTraceListener"
              initializeData= "c:\log\Traces.svclog" />
        <add type="System.Diagnostics.DefaultTraceListener" name="Default" />
      </listeners>
    </source>
    <source propagateActivity="true" name="System.ServiceModel" switchValue="Verbose,ActivityTracing">
      <listeners>
        <add name="traceListener"
              type="System.Diagnostics.XmlWriterTraceListener"
              initializeData= "c:\log\Traces.svclog" />
        <add type="System.Diagnostics.DefaultTraceListener" name="Default" />
      </listeners>
    </source>
  </sources>
  <trace autoflush="true" />
</system.diagnostics>

Once set, I ran my client, got exception and checked the 'Traces.svclog' file. From there, I only needed to find the exception.

Is there Unicode glyph Symbol to represent "Search"

There is U+1F50D LEFT-POINTING MAGNIFYING GLASS () and U+1F50E RIGHT-POINTING MAGNIFYING GLASS ().

You should use (in HTML) &#x1F50D; or &#x1F50E;

They are, however not supported by many fonts (fileformat.info only lists a few fonts as supporting the Codepoint with a proper glyph).

Also note that they are outside of the BMP, so some Unicode-capable software might have problems rendering them, even if they have fonts that support them.

Generally Unicode Glyphs can be searched using a site such as fileformat.info. This searches "only" in the names and properties of the Unicode glyphs, but they usually contain enough metadata to allow for good search results (for this answer I searched for "glass" and browsed the resulting list, for example)

ValueError: unsupported format character while forming strings

You could escape the % in %20 like so:

print "Hello%%20World%s" %"!"

or you could try using the string formatting routines instead, like:

print "Hello%20World{0}".format("!")

http://docs.python.org/library/string.html#formatstrings

how to display excel sheet in html page

Office 365 and OneDrive offer an embed feature. You can then include via IFrame.

I found that setting the iframe height and width to 100% works best. That way on ipad or any device for that matter it fits the screen.

<body style="margin:0px;padding:0px;overflow:hidden">
    <iframe src="embed url" frameborder="0" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:100%;width:100%;position:absolute;top:0px;left:0px;right:0px;bottom:0px" height="100%" width="100%"></iframe>
</body>

How to build query string with Javascript

If you're using jQuery you might want to check out jQuery.param() http://api.jquery.com/jQuery.param/

Example:

var params = {
    parameter1: 'value1',
    parameter2: 'value2',
    parameter3: 'value3' 
};
?var query = $.param(params);
document.write(query);

Use Conditional formatting to turn a cell Red, yellow or green depending on 3 values in another sheet

  1. Highlight the range in question.
  2. On the Home tab, in the Styles Group, Click "Conditional Formatting".
  3. Click "Highlight cell rules"

For the first rule,

Click "greater than", then in the value option box, click on the cell criteria you want it to be less than, than use the format drop-down to select your color.

For the second,

Click "less than", then in the value option box, type "=.9*" and then click the cell criteria, then use the formatting just like step 1.

For the third,

Same as the second, except your formula is =".8*" rather than .9.

Android getResources().getDrawable() deprecated API 22

For some who still got this issue to solve even after applying the suggestion of this thread(i used to be one like that) add this line on your Application class, onCreate() method

AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)

As suggested here and here sometimes this is required to access vectors from resources especially when you're dealing with menu items, etc

My eclipse won't open, i download the bundle pack it keeps saying error log

Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.

This will be a JRE and JDK package.

There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.

Java substring: 'string index out of range'

Java's substring method fails when you try and get a substring starting at an index which is longer than the string.

An easy alternative is to use Apache Commons StringUtils.substring:

public static String substring(String str, int start)

Gets a substring from the specified String avoiding exceptions.

A negative start position can be used to start n characters from the end of the String.

A null String will return null. An empty ("") String will return "".

 StringUtils.substring(null, *)   = null
 StringUtils.substring("", *)     = ""
 StringUtils.substring("abc", 0)  = "abc"
 StringUtils.substring("abc", 2)  = "c"
 StringUtils.substring("abc", 4)  = ""
 StringUtils.substring("abc", -2) = "bc"
 StringUtils.substring("abc", -4) = "abc"

Parameters:
str - the String to get the substring from, may be null
start - the position to start from, negative means count back from the end of the String by this many characters

Returns:
substring from start position, null if null String input

Note, if you can't use Apache Commons lib for some reason, you could just grab the parts you need from the source

// Substring
//-----------------------------------------------------------------------
/**
 * <p>Gets a substring from the specified String avoiding exceptions.</p>
 *
 * <p>A negative start position can be used to start {@code n}
 * characters from the end of the String.</p>
 *
 * <p>A {@code null} String will return {@code null}.
 * An empty ("") String will return "".</p>
 *
 * <pre>
 * StringUtils.substring(null, *)   = null
 * StringUtils.substring("", *)     = ""
 * StringUtils.substring("abc", 0)  = "abc"
 * StringUtils.substring("abc", 2)  = "c"
 * StringUtils.substring("abc", 4)  = ""
 * StringUtils.substring("abc", -2) = "bc"
 * StringUtils.substring("abc", -4) = "abc"
 * </pre>
 *
 * @param str  the String to get the substring from, may be null
 * @param start  the position to start from, negative means
 *  count back from the end of the String by this many characters
 * @return substring from start position, {@code null} if null String input
 */
public static String substring(final String str, int start) {
    if (str == null) {
        return null;
    }

    // handle negatives, which means last n characters
    if (start < 0) {
        start = str.length() + start; // remember start is negative
    }

    if (start < 0) {
        start = 0;
    }
    if (start > str.length()) {
        return EMPTY;
    }

    return str.substring(start);
}

How to declare a constant in Java

  1. You can use an enum type in Java 5 and onwards for the purpose you have described. It is type safe.
  2. A is an instance variable. (If it has the static modifier, then it becomes a static variable.) Constants just means the value doesn't change.
  3. Instance variables are data members belonging to the object and not the class. Instance variable = Instance field.

If you are talking about the difference between instance variable and class variable, instance variable exist per object created. While class variable has only one copy per class loader regardless of the number of objects created.

Java 5 and up enum type

public enum Color{
 RED("Red"), GREEN("Green");

 private Color(String color){
    this.color = color;
  }

  private String color;

  public String getColor(){
    return this.color;
  }

  public String toString(){
    return this.color;
  }
}

If you wish to change the value of the enum you have created, provide a mutator method.

public enum Color{
 RED("Red"), GREEN("Green");

 private Color(String color){
    this.color = color;
  }

  private String color;

  public String getColor(){
    return this.color;
  }

  public void setColor(String color){
    this.color = color;
  }

  public String toString(){
    return this.color;
  }
}

Example of accessing:

public static void main(String args[]){
  System.out.println(Color.RED.getColor());

  // or

  System.out.println(Color.GREEN);
}

Check if ADODB connection is open

This topic is old but if other people like me search a solution, this is a solution that I have found:

Public Function DBStats() As Boolean
    On Error GoTo errorHandler
        If Not IsNull(myBase.Version) Then 
            DBStats = True
        End If
        Exit Function
    errorHandler:
        DBStats = False  
End Function

So "myBase" is a Database Object, I have made a class to access to database (class with insert, update etc...) and on the module the class is use declare in an object (obviously) and I can test the connection with "[the Object].DBStats":

Dim BaseAccess As New myClass
BaseAccess.DBOpen 'I open connection
Debug.Print BaseAccess.DBStats ' I test and that tell me true
BaseAccess.DBClose ' I close the connection
Debug.Print BaseAccess.DBStats ' I test and tell me false

Edit : In DBOpen I use "OpenDatabase" and in DBClose I use ".Close" and "set myBase = nothing" Edit 2: In the function, if you are not connect, .version give you an error so if aren't connect, the errorHandler give you false

How to set up file permissions for Laravel?

I decided to write my own script to ease some of the pain of setting up projects.

Run the following inside your project root:

wget -qO- https://raw.githubusercontent.com/defaye/bootstrap-laravel/master/bootstrap.sh | sh

Wait for the bootstrapping to complete and you're good to go.

Review the script before use.

How to insert a line break in a SQL Server VARCHAR/NVARCHAR string

All of these options work depending on your situation, but you may not see any of them work if you're using SSMS (as mentioned in some comments SSMS hides CR/LFs)

So rather than driving yourself round the bend, Check this setting in

Tools | Options

which will replace the

SQLite table constraint - unique on multiple columns

Well, your syntax doesn't match the link you included, which specifies:

 CREATE TABLE name (column defs) 
    CONSTRAINT constraint_name    -- This is new
    UNIQUE (col_name1, col_name2) ON CONFLICT REPLACE

Python Binomial Coefficient

Your program will continue with the second if statement in the case of y == x, causing a ZeroDivisionError. You need to make the statements mutually exclusive; the way to do that is to use elif ("else if") instead of if:

import math
x = int(input("Enter a value for x: "))
y = int(input("Enter a value for y: "))
if y == x:
    print(1)
elif y == 1:         # see georg's comment
    print(x)
elif y > x:          # will be executed only if y != 1 and y != x
    print(0)
else:                # will be executed only if y != 1 and y != x and x <= y
    a = math.factorial(x)
    b = math.factorial(y)
    c = math.factorial(x-y)  # that appears to be useful to get the correct result
    div = a // (b * c)
    print(div)  

NoClassDefFoundError on Maven dependency

Choosing to Project -> Clean should resolve this

How to unlock a file from someone else in Team Foundation Server

In my case, I tried unlocking the file with tf lock but was told I couldn't because the stale workspace on an old computer that no longer existed was a local workspace. I then tried deleting the workspace with tf workspace /delete, but deleting the workspace did not remove the lock (and then I couldn't try to unlock it again because I just got an error saying the workspace no longer existed).

I ended up tf destroying the file and checking it in again, which was pretty silly and had the undesirable effect of removing\ it from previous changesets, but at least got us working again. It wasn't that big a deal in this case since the file had never been changed since being checked in.

Convert unix time to readable date in pandas dataframe

Alternatively, by changing a line of the above code:

# df.date = df.date.apply(lambda d: datetime.strptime(d, "%Y-%m-%d"))
df.date = df.date.apply(lambda d: datetime.datetime.fromtimestamp(int(d)).strftime('%Y-%m-%d'))

It should also work.

How do I determine the dependencies of a .NET application?

It's funny I had a similar issue and didn't find anything suitable and was aware of good old Dependency Walker so in the end I wrote one myself.

This deals with .NET specifically and will show what references an assembly has (and missing) recursively. It'll also show native library dependencies.

It's free (for personal use) and available here for anyone interested: www.netdepends.com

www.netdepends.com

Feedback welcome.

When maven says "resolution will not be reattempted until the update interval of MyRepo has elapsed", where is that interval specified?

you can delete the corresponding failed artifact directory in you local repository. And also you can simply use the -U in the goal. It will do the work. This works with maven 3. So no need to downgrade to maven 2.

How to show/hide JPanels in a JFrame?

Call parent.remove(panel), where parent is the container that you want the frame in and panel is the panel you want to add.

What does "both" mean in <div style="clear:both">

Clear:both gives you that space between them.

For example your code:

  <div style="float:left">Hello</div>
  <div style="float:right">Howdy dere pardner</div>

Will currently display as :

Hello  ...................   Howdy dere pardner

If you add the following to above snippet,

  <div style="clear:both"></div>

In between them it will display as:

Hello ................ 
                       Howdy dere pardner

giving you that space between hello and Howdy dere pardner.

Js fiiddle http://jsfiddle.net/Qk5vR/1/

GnuPG: "decryption failed: secret key not available" error from gpg on Windows

One more cause for the "secret key not available" message: GPG version mismatch.

Practical example: I had been using GPG v1.4. Switching packaging systems, the MacPorts supplied gpg was removed, and revealed another gpg binary in the path, this one version 2.0. For decryption, it was unable to locate the secret key and gave this very error. For encryption, it complained about an unusable public key. However, gpg -k and -K both listed valid keys, which was the cause of major confusion.

adding multiple event listeners to one element

For large numbers of events this might help:

var element = document.getElementById("myId");
var myEvents = "click touchstart touchend".split(" ");
var handler = function (e) {
    do something
};

for (var i=0, len = myEvents.length; i < len; i++) {
    element.addEventListener(myEvents[i], handler, false);
}

Update 06/2017:

Now that new language features are more widely available you could simplify adding a limited list of events that share one listener.

const element = document.querySelector("#myId");

function handleEvent(e) {
    // do something
}
// I prefer string.split because it makes editing the event list slightly easier

"click touchstart touchend touchmove".split(" ")
    .map(name => element.addEventListener(name, handleEvent, false));

If you want to handle lots of events and have different requirements per listener you can also pass an object which most people tend to forget.

const el = document.querySelector("#myId");

const eventHandler = {
    // called for each event on this element
    handleEvent(evt) {
        switch (evt.type) {
            case "click":
            case "touchstart":
                // click and touchstart share click handler
                this.handleClick(e);
                break;
            case "touchend":
                this.handleTouchend(e);
                break;
            default:
                this.handleDefault(e);
        }
    },
    handleClick(e) {
        // do something
    },
    handleTouchend(e) {
        // do something different
    },
    handleDefault(e) {
        console.log("unhandled event: %s", e.type);
    }
}

el.addEventListener(eventHandler);

Update 05/2019:

const el = document.querySelector("#myId");

const eventHandler = {
    handlers: {
        click(e) {
            // do something
        },
        touchend(e) {
            // do something different
        },
        default(e) {
            console.log("unhandled event: %s", e.type);
        }
    },
    // called for each event on this element
    handleEvent(evt) {
        switch (evt.type) {
            case "click":
            case "touchstart":
                // click and touchstart share click handler
                this.handlers.click(e);
                break;
            case "touchend":
                this.handlers.touchend(e);
                break;
            default:
                this.handlers.default(e);
        }
    }
}

Object.keys(eventHandler.handlers)
    .map(eventName => el.addEventListener(eventName, eventHandler))