Programs & Examples On #Ignoreroute

IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication”

I faced similar error, tried all the suggestions above, but did not resolve. what worked for me is this:

Right-click your Global.asax file and click View Markup. You will see the attribute Inherits="nadeem.MvcApplication". This means that your Global.asax file is trying to inherit from the type nadeem.MvcApplication.

Now double click your Global.asax file and see what the class name specified in your Global.asax.cs file is. It should look something like this:

namespace nadeem
{

public class MvcApplication: System.Web.HttpApplication
    {
    ....

But if it doesn't look like above, you will receive that error, The value in the Inherits attribute of your Global.asax file must match a type that is derived from System.Web.HttpApplication.

Check below link for more info:

Parser Error: Server Error in '/' Application

How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas

I hate answering my own question, but @Matt Bodily put me on the right track.

The @Html.Action method actually invokes a controller and renders the view, so that wouldn't work to create a snippet of HTML in my case, as this was causing a recursive function call resulting in a StackOverflowException. The @Url.Action(action, controller, { area = "abc" }) does indeed return the URL, but I finally discovered an overload of Html.ActionLink that provided a better solution for my case:

@Html.ActionLink("Admin", "Index", "Home", new { area = "Admin" }, null)

Note: , null is significant in this case, to match the right signature.

Documentation: @Html.ActionLink (LinkExtensions.ActionLink)

Documentation for this particular overload:

LinkExtensions.ActionLink(Controller, Action, Text, RouteArgs, HtmlAttributes)

It's been difficult to find documentation for these helpers. I tend to search for "Html.ActionLink" when I probably should have searched for "LinkExtensions.ActionLink", if that helps anyone in the future.

Still marking Matt's response as the answer.

Edit: Found yet another HTML helper to solve this:

@Html.RouteLink("Admin", new { action = "Index", controller = "Home", area = "Admin" })

The view or its master was not found or no view engine supports the searched locations

In your LoginRegister action when returning the view, do below, i know this can be done in mvc 5, im not sure if in mvc 4 also.

 public ActionResult Index()
 {
     return View("~/Views/home/LoginRegister.cshtml");
 }

Serving favicon.ico in ASP.NET MVC

None of the above worked for me. I finally solved this problem by renaming favicon.ico to myicon.ico, and reference it in the head <link rel="icon" href="~/myicon.ico" type="image/x-icon" />

Comparing results with today's date?

Just zero off the time element of the date. e.g.

SELECT DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)

I've used GetDate as that's an MSSQL function, as you've tagged, but Now() is probably MySQL or you're using the ODBC function call, still should work if you just replace one with the other.

How to get Current Directory?

#include <iostream>    
#include <stdio.h>
#include <dirent.h>

std::string current_working_directory()
{
    char* cwd = _getcwd( 0, 0 ) ; // **** microsoft specific ****
    std::string working_directory(cwd) ;
    std::free(cwd) ;
    return working_directory ;
}

int main(){
    std::cout << "i am now in " << current_working_directory() << endl;
}

I failed to use GetModuleFileName correctly. I found this work very well. just tested on Windows, not yet try on Linux :)

ADB Driver and Windows 8.1

http://adbdriver.com/

this worked for me, in my latest Micromax Yu Yuphoria! just download the installer and install it

Is False == 0 and True == 1 an implementation detail or is it guaranteed by the language?

Link to the PEP discussing the new bool type in Python 2.3: http://www.python.org/dev/peps/pep-0285/.

When converting a bool to an int, the integer value is always 0 or 1, but when converting an int to a bool, the boolean value is True for all integers except 0.

>>> int(False)
0
>>> int(True)
1
>>> bool(5)
True
>>> bool(-5)
True
>>> bool(0)
False

How to check Elasticsearch cluster health?

The _cluster/health API can do far more than the typical output that most see with it:

 $ curl -XGET 'localhost:9200/_cluster/health?pretty'

Most APIs within Elasticsearch can take a variety of arguments to augment their output. This applies to Cluster Health API as well.

Examples

all the indices health
$ curl -XGET 'localhost:9200/_cluster/health?level=indices&pretty' | head -50
{
  "cluster_name" : "rdu-es-01",
  "status" : "green",
  "timed_out" : false,
  "number_of_nodes" : 9,
  "number_of_data_nodes" : 6,
  "active_primary_shards" : 1106,
  "active_shards" : 2213,
  "relocating_shards" : 0,
  "initializing_shards" : 0,
  "unassigned_shards" : 0,
  "delayed_unassigned_shards" : 0,
  "number_of_pending_tasks" : 0,
  "number_of_in_flight_fetch" : 0,
  "task_max_waiting_in_queue_millis" : 0,
  "active_shards_percent_as_number" : 100.0,
  "indices" : {
    "filebeat-6.5.1-2019.06.10" : {
      "status" : "green",
      "number_of_shards" : 3,
      "number_of_replicas" : 1,
      "active_primary_shards" : 3,
      "active_shards" : 6,
      "relocating_shards" : 0,
      "initializing_shards" : 0,
      "unassigned_shards" : 0
    },
    "filebeat-6.5.1-2019.06.11" : {
      "status" : "green",
      "number_of_shards" : 3,
      "number_of_replicas" : 1,
      "active_primary_shards" : 3,
      "active_shards" : 6,
      "relocating_shards" : 0,
      "initializing_shards" : 0,
      "unassigned_shards" : 0
    },
    "filebeat-6.5.1-2019.06.12" : {
      "status" : "green",
      "number_of_shards" : 3,
      "number_of_replicas" : 1,
      "active_primary_shards" : 3,
      "active_shards" : 6,
      "relocating_shards" : 0,
      "initializing_shards" : 0,
      "unassigned_shards" : 0
    },
    "filebeat-6.5.1-2019.06.13" : {
      "status" : "green",
      "number_of_shards" : 3,
all shards health
$ curl -XGET 'localhost:9200/_cluster/health?level=shards&pretty' | head -50
{
  "cluster_name" : "rdu-es-01",
  "status" : "green",
  "timed_out" : false,
  "number_of_nodes" : 9,
  "number_of_data_nodes" : 6,
  "active_primary_shards" : 1106,
  "active_shards" : 2213,
  "relocating_shards" : 0,
  "initializing_shards" : 0,
  "unassigned_shards" : 0,
  "delayed_unassigned_shards" : 0,
  "number_of_pending_tasks" : 0,
  "number_of_in_flight_fetch" : 0,
  "task_max_waiting_in_queue_millis" : 0,
  "active_shards_percent_as_number" : 100.0,
  "indices" : {
    "filebeat-6.5.1-2019.06.10" : {
      "status" : "green",
      "number_of_shards" : 3,
      "number_of_replicas" : 1,
      "active_primary_shards" : 3,
      "active_shards" : 6,
      "relocating_shards" : 0,
      "initializing_shards" : 0,
      "unassigned_shards" : 0,
      "shards" : {
        "0" : {
          "status" : "green",
          "primary_active" : true,
          "active_shards" : 2,
          "relocating_shards" : 0,
          "initializing_shards" : 0,
          "unassigned_shards" : 0
        },
        "1" : {
          "status" : "green",
          "primary_active" : true,
          "active_shards" : 2,
          "relocating_shards" : 0,
          "initializing_shards" : 0,
          "unassigned_shards" : 0
        },
        "2" : {
          "status" : "green",
          "primary_active" : true,
          "active_shards" : 2,
          "relocating_shards" : 0,
          "initializing_shards" : 0,
          "unassigned_shards" : 0

The API also has a variety of wait_* options where it'll wait for various state changes before returning immediately or after some specified timeout.

Getting min and max Dates from a pandas dataframe

min(df['some_property'])
max(df['some_property'])

The built-in functions work well with Pandas Dataframes.

Twitter Bootstrap date picker

add

z-index:1151;

to the style sheet in

.datepicker

How to set opacity in parent div and not affect in child div?

You can do it with pseudo-elements: (demo on dabblet.com) enter image description here

your markup:

<div class="parent">
    <div class="child"> Hello I am child </div>
</div>

css:

.parent{
    position: relative;
}

.parent:before {
    z-index: -1;
    content: '';
    position: absolute;

    opacity: 0.2;
    width: 400px;
    height: 200px;
    background: url('http://img42.imageshack.us/img42/1893/96c75664f7e94f9198ad113.png') no-repeat 0 0; 
}

.child{
    Color:black;
}

The view 'Index' or its master was not found.

I got the same problem in here, and guess what.... looking at the csproj's xml' structure, I noticed the Content node (inside ItemGroup node) was as "none"... not sure why but that was the reason I was getting the same error, just edited that to "Content" as the others, and it's working.

Hope that helps

Get selected option text with JavaScript

You'll need to get the innerHTML of the option, and not its value.

Use this.innerHTML instead of this.selectedIndex.

Edit: You'll need to get the option element first and then use innerHTML.

Use this.text instead of this.selectedIndex.

How to determine programmatically the current active profile using Spring boot

It doesn't matter is your app Boot or just raw Spring. There is just enough to inject org.springframework.core.env.Environment to your bean.

@Autowired
private Environment environment;
....

this.environment.getActiveProfiles();

How to add constraints programmatically using Swift

This is one way to adding constraints programmatically

override func viewDidLoad() {
            super.viewDidLoad()


let myLabel = UILabel()
        myLabel.labelFrameUpdate(label: myLabel, text: "Welcome User", font: UIFont(name: "times new roman", size: 40)!, textColor: UIColor.red, textAlignment: .center, numberOfLines: 0, borderWidth: 2.0, BorderColor: UIColor.red.cgColor)
        self.view.addSubview(myLabel)


         let myLabelhorizontalConstraint = NSLayoutConstraint(item: myLabel, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
        let myLabelverticalConstraint = NSLayoutConstraint(item: myLabel, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)
        let mylabelLeading = NSLayoutConstraint(item: myLabel, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.leading, multiplier: 1, constant: 10)
        let mylabelTrailing = NSLayoutConstraint(item: myLabel, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.trailing, multiplier: 1, constant: -10)
        let myLabelheightConstraint = NSLayoutConstraint(item: myLabel, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 50)
        NSLayoutConstraint.activate(\[myLabelhorizontalConstraint, myLabelverticalConstraint, myLabelheightConstraint,mylabelLeading,mylabelTrailing\])
}

extension UILabel
{
    func labelFrameUpdate(label:UILabel,text:String = "This is sample Label",font:UIFont = UIFont(name: "times new roman", size: 20)!,textColor:UIColor = UIColor.red,textAlignment:NSTextAlignment = .center,numberOfLines:Int = 0,borderWidth:CGFloat = 2.0,BorderColor:CGColor = UIColor.red.cgColor){
        label.translatesAutoresizingMaskIntoConstraints = false
        label.text = text
        label.font = font
        label.textColor = textColor
        label.textAlignment = textAlignment
        label.numberOfLines = numberOfLines
        label.layer.borderWidth = borderWidth
        label.layer.borderColor = UIColor.red.cgColor
    }
}

enter image description here

how to append a css class to an element by javascript?

var element = document.getElementById(element_id);
element.className += " " + newClassName;

Voilà. This will work on pretty much every browser ever. The leading space is important, because the className property treats the css classes like a single string, which ought to match the class attribute on HTML elements (where multiple classes must be separated by spaces).

Incidentally, you're going to be better off using a Javascript library like prototype or jQuery, which have methods to do this, as well as functions that can first check if an element already has a class assigned.

In prototype, for instance:

// Prototype automatically checks that the element doesn't already have the class
$(element_id).addClassName(newClassName);

See how much nicer that is?!

What is the most efficient/quickest way to loop through rows in VBA (excel)?

If you are just looping through 10k rows in column A, then dump the row into a variant array and then loop through that.

You can then either add the elements to a new array (while adding rows when needed) and using Transpose() to put the array onto your range in one move, or you can use your iterator variable to track which row you are on and add rows that way.

Dim i As Long
Dim varray As Variant

varray = Range("A2:A" & Cells(Rows.Count, "A").End(xlUp).Row).Value

For i = 1 To UBound(varray, 1)
    ' do stuff to varray(i, 1)
Next

Here is an example of how you could add rows after evaluating each cell. This example just inserts a row after every row that has the word "foo" in column A. Not that the "+2" is added to the variable i during the insert since we are starting on A2. It would be +1 if we were starting our array with A1.

Sub test()

Dim varray As Variant
Dim i As Long

varray = Range("A2:A10").Value

'must step back or it'll be infinite loop
For i = UBound(varray, 1) To LBound(varray, 1) Step -1
    'do your logic and evaluation here
    If varray(i, 1) = "foo" Then
       'not how to offset the i variable 
       Range("A" & i + 2).EntireRow.Insert
    End If
Next

End Sub

Accept function as parameter in PHP

PHP VERSION >= 5.3.0

Example 1: basic

function test($test_param, $my_function) {
    return $my_function($test_param);
}

test("param", function($param) {
    echo $param;
}); //will echo "param"

Example 2: std object

$obj = new stdClass();
$obj->test = function ($test_param, $my_function) {
    return $my_function($test_param);
};

$test = $obj->test;
$test("param", function($param) {
    echo $param;
});

Example 3: non static class call

class obj{
    public function test($test_param, $my_function) {
        return $my_function($test_param);
    }
}

$obj = new obj();
$obj->test("param", function($param) {
    echo $param;
});

Example 4: static class call

class obj {
    public static function test($test_param, $my_function) {
        return $my_function($test_param);
    }
}

obj::test("param", function($param) {
    echo $param;
});

Put search icon near textbox using bootstrap

<input type="text" name="whatever" id="funkystyling" />

Here's the CSS for the image on the left:

#funkystyling {
    background: white url(/path/to/icon.png) left no-repeat;
    padding-left: 17px;
}

And here's the CSS for the image on the right:

#funkystyling {
    background: white url(/path/to/icon.png) right no-repeat;
    padding-right: 17px;
}

Git pull after forced update

Pull with rebase

A regular pull is fetch + merge, but what you want is fetch + rebase. This is an option with the pull command:

git pull --rebase

How to disable HTML button using JavaScript?

<button disabled=true>text here</button>

You can still use an attribute. Just use the 'disabled' attribute instead of 'value'.

How do I do pagination in ASP.NET MVC?

public ActionResult Paging(int? pageno,bool? fwd,bool? bwd)        
{
    if(pageno!=null)
     {
       Session["currentpage"] = pageno;
     }

    using (HatronEntities DB = new HatronEntities())
    {
        if(fwd!=null && (bool)fwd)
        {
            pageno = Convert.ToInt32(Session["currentpage"]) + 1;
            Session["currentpage"] = pageno;
        }
        if (bwd != null && (bool)bwd)
        {
            pageno = Convert.ToInt32(Session["currentpage"]) - 1;
            Session["currentpage"] = pageno;
        }
        if (pageno==null)
        {
            pageno = 1;
        }
        if(pageno<0)
        {
            pageno = 1;
        }
        int total = DB.EmployeePromotion(0, 0, 0).Count();
        int  totalPage = (int)Math.Ceiling((double)total / 20);
        ViewBag.pages = totalPage;
        if (pageno > totalPage)
        {
            pageno = totalPage;
        }
        return View (DB.EmployeePromotion(0,0,0).Skip(GetSkip((int)pageno,20)).Take(20).ToList());     
    }
}

private static int GetSkip(int pageIndex, int take)
{
    return (pageIndex - 1) * take;
}

@model IEnumerable<EmployeePromotion_Result>
@{
  Layout = null;
}

 <!DOCTYPE html>

 <html>
 <head>
    <meta name="viewport" content="width=device-width" />
    <title>Paging</title>
  </head>
  <body>
 <div> 
    <table border="1">
        @foreach (var itm in Model)
        {
 <tr>
   <td>@itm.District</td>
   <td>@itm.employee</td>
   <td>@itm.PromotionTo</td>
 </tr>
        }
    </table>
    <a href="@Url.Action("Paging", "Home",new { pageno=1 })">First  page</a> 
    <a href="@Url.Action("Paging", "Home", new { bwd =true })"><<</a> 
    @for(int itmp =1; itmp< Convert.ToInt32(ViewBag.pages)+1;itmp++)
   {
       <a href="@Url.Action("Paging", "Home",new { pageno=itmp   })">@itmp.ToString()</a>
   }
    <a href="@Url.Action("Paging", "Home", new { fwd = true })">>></a> 
    <a href="@Url.Action("Paging", "Home", new { pageno =                                                                               Convert.ToInt32(ViewBag.pages) })">Last page</a> 
</div>
   </body>
  </html>

How to convert Base64 String to javascript file object like as from file input form?

const url = 'data:image/png;base6....';
fetch(url)
  .then(res => res.blob())
  .then(blob => {
    const file = new File([blob], "File name",{ type: "image/png" })
  })

Base64 String -> Blob -> File.

Filtering a data frame by values in a column

Thought I'd update this with a dplyr solution

library(dplyr)    
filter(studentdata, Drink == "water")

MySQL equivalent of DECODE function in Oracle

You can use IF() where in Oracle you would have used DECODE().

mysql> select if(emp_id=1,'X','Y') as test, emp_id from emps; 

Adding an onclicklistener to listview (android)

list.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1,
                int arg2, long arg3) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub

        }
    });

What are file descriptors, explained in simple terms?

File Descriptors are the descriptors to a file. They give links to a file. With the help of them we can read, write and open a file.

How to use Macro argument as string literal?

#define NAME(x) printf("Hello " #x);
main(){
    NAME(Ian)
}
//will print: Hello Ian

Pandas: rolling mean by time interval

What about something like this:

First resample the data frame into 1D intervals. This takes the mean of the values for all duplicate days. Use the fill_method option to fill in missing date values. Next, pass the resampled frame into pd.rolling_mean with a window of 3 and min_periods=1 :

pd.rolling_mean(df.resample("1D", fill_method="ffill"), window=3, min_periods=1)

            favorable  unfavorable     other
enddate
2012-10-25   0.495000     0.485000  0.025000
2012-10-26   0.527500     0.442500  0.032500
2012-10-27   0.521667     0.451667  0.028333
2012-10-28   0.515833     0.450000  0.035833
2012-10-29   0.488333     0.476667  0.038333
2012-10-30   0.495000     0.470000  0.038333
2012-10-31   0.512500     0.460000  0.029167
2012-11-01   0.516667     0.456667  0.026667
2012-11-02   0.503333     0.463333  0.033333
2012-11-03   0.490000     0.463333  0.046667
2012-11-04   0.494000     0.456000  0.043333
2012-11-05   0.500667     0.452667  0.036667
2012-11-06   0.507333     0.456000  0.023333
2012-11-07   0.510000     0.443333  0.013333

UPDATE: As Ben points out in the comments, with pandas 0.18.0 the syntax has changed. With the new syntax this would be:

df.resample("1d").sum().fillna(0).rolling(window=3, min_periods=1).mean()

Is it possible to insert HTML content in XML document?

You can include HTML content. One possibility is encoding it in BASE64 as you have mentioned.

Another might be using CDATA tags.

Example using CDATA:

<xml>
    <title>Your HTML title</title>
    <htmlData><![CDATA[<html>
        <head>
            <script/>
        </head>
        <body>
        Your HTML's body
        </body>
        </html>
     ]]>
    </htmlData>
</xml>

Please note:

CDATA's opening character sequence: <![CDATA[

CDATA's closing character sequence: ]]>

Solr vs. ElasticSearch

I have been working on both solr and elastic search for .Net applications. The major difference what i have faced is

Elastic search :

  • More code and less configuration, however there are api's to change but still is a code change
  • for complex types, type within types i.e nested types(wasn't able to achieve in solr)

Solr :

  • less code and more configuration and hence less maintenance
  • for grouping results during querying(lots of work to achieve in elastic search in short no straight way)

Setting environment variable in react-native?

It is possible to access the variables with process.env.blabla instead of process.env['blabla']. I recently made it work and commented on how I did it on an issue on GitHub because I had some problems with cache based on the accepted answer. Here is the issue.

how to change php version in htaccess in server

just FYI in GoDaddy it's this:

AddHandler x-httpd-php5-3 .php

How to return values in javascript

Javascript is duck typed, so you can create a small structure.

function myFunction(value1,value2,value3)
{         
     var myObject = new Object();
     myObject.value2 = somevalue2;
     myObject.value3 = somevalue3;
     return myObject;
}


var value = myFunction("1",value2,value3);

if(value.value2  && value.value3)
{
//Do some stuff
}

How to handle ETIMEDOUT error?

In case if you are using node js, then this could be the possible solution

const express = require("express");
const app = express();
const server = app.listen(8080);
server.keepAliveTimeout = 61 * 1000;

https://medium.com/hk01-tech/running-eks-in-production-for-2-years-the-kubernetes-journey-at-hk01-68130e603d76

Ruby get object keys as array

hash = {"apple" => "fruit", "carrot" => "vegetable"}
array = hash.keys   #=> ["apple", "carrot"]

it's that simple

How to insert the current timestamp into MySQL database using a PHP insert query

Instead of NOW() you can use UNIX_TIMESTAMP() also:

$update_query = "UPDATE db.tablename 
                 SET insert_time=UNIX_TIMESTAMP()
                 WHERE username='$somename'";

Difference between UNIX_TIMESTAMP and NOW() in MySQL

In VBA get rid of the case sensitivity when comparing words?

You can convert both the values to lower case and compare.

Here is an example:

If LCase(Range("J6").Value) = LCase("Tawi") Then
   Range("J6").Value = "Tawi-Tawi"
End If

Change text from "Submit" on input tag

The value attribute is used to determine the rendered label of a submit input.

<input type="submit" class="like" value="Like" />

Note that if the control is successful (this one won't be as it has no name) this will also be the submitted value for it.

To have a different submitted value and label you need to use a button element, in which the textNode inside the element determines the label. You can include other elements (including <img> here).

<button type="submit" class="like" name="foo" value="bar">Like</button>

Note that support for <button> is dodgy in older versions of Internet Explorer.

Postman: sending nested JSON object

To post a nested object with the key-value interface you can use a similar method to sending arrays. Pass an object key in square brackets after the object index.

Passing a nested item with Postman

"Items": [
      {
        "sku": "9257",
        "Price": "100"
      }
 ]

Can't connect to local MySQL server through socket '/var/mysql/mysql.sock' (38)

are you sure you installed mysql as well as mysql server..

For example to install mySql server I'll use yum or apt to install both mysql command line tool and the server:

yum -y install mysql mysql-server (or apt-get install mysql mysql-server)

Enable the MySQL service:

/sbin/chkconfig mysqld on

Start the MySQL server:

/sbin/service mysqld start

afterwards set the MySQL root password:

mysqladmin -u root password 'new-password' (with the quotes)

I hope it helps.

How to install wkhtmltopdf on a linux based (shared hosting) web server

I've managed to successfully install wkhtmltopdf-amd64 on my shared hosting account without root access.

Here's what i did:

Downloaded the relevant static binary v0.10.0 from here: http://code.google.com/p/wkhtmltopdf/downloads/list

EDIT: The above has moved to here

via ssh on my shared host typed the following:

$ wget {relavant url to binary from link above}
$ tar -xvf {filename of above wget'd file}

you'll then have the binary on your host and will be able to run it regardless of if its in the /usr/bin/ folder or not. (or at least i was able to)

To test:

$ ./wkhtmltopdf-amd64 http://www.example.com example.pdf
  • Note remember that if you're in the folder in which the executable is, you should probably preface it with ./ just to be sure.

Worked for me anyway

Compare two dates in Java

Date equality depends on the two dates being equal to the millisecond. Creating a new Date object using new Date() will never equal a date created in the past. Joda Time's APIs simplify working with dates; however, using the Java's SDK alone:

if (removeTime(questionDate).equals(removeTime(today)) 
  ...

public Date removeTime(Date date) {    
    Calendar cal = Calendar.getInstance();  
    cal.setTime(date);  
    cal.set(Calendar.HOUR_OF_DAY, 0);  
    cal.set(Calendar.MINUTE, 0);  
    cal.set(Calendar.SECOND, 0);  
    cal.set(Calendar.MILLISECOND, 0);  
    return cal.getTime(); 
}

Run Batch File On Start-up

To run a batch file at start up: start >> all programs >> right-click startup >> open >> right click batch file >> create shortcut >> drag shortcut to startup folder.

The path to the folder is : [D|C]:\Profiles\{User}\??AppData\Roaming\Micro??soft\Windows\Start Menu\Programs\Startu??p

Submit button doesn't work

I ran into this on a friend's HTML code and in his case, he was missing quotes.

For example:

<form action="formHandler.php" name="yourForm" id="theForm" method="post">    
<input type="text" name="fname" id="fname" style="width:90;font-size:10>     
<input type="submit" value="submit"/>
</form>

In this example, a missing quote on the input text fname will simply render the submit button un-usable and the form will not submit.

Of course, this is a bad example because I should be using CSS in the first place ;) but anyways, check all your single and double quotes to see that they are closing properly.

Also, if you have any tags like center, move them out of the form.

<form action="formHandler.php" name="yourForm" id="theForm" method="post">  
<center> <-- bad

As strange it may seems, it can have an impact.

How long would it take a non-programmer to learn C#, the .NET Framework, and SQL?

That's like asking how long it would take to learn French:

  • 1 day to learn what it is
  • 1 week to learn it to an infant/elementary level
  • 1 year to be considered a beginner by professionals
  • Several years to be considered an experienced professional
  • Plus there's "deep" knowledge of those subjects which a mere mortal such as you or I will never learn

Then again, plenty of people (most normal people, non-programmers) never learn those subjects, so if you're like "most" people then the answer would be "it would take forever" or "it will never happen".

How to use executeReader() method to retrieve the value of just one cell

It is not recommended to use DataReader and Command.ExecuteReader to get just one value from the database. Instead, you should use Command.ExecuteScalar as following:

String sql = "SELECT ColumnNumber FROM learer WHERE learer.id = " + index;
SqlCommand cmd = new SqlCommand(sql,conn);
learerLabel.Text = (String) cmd.ExecuteScalar();

Here is more information about Connecting to database and managing data.

Get source JARs from Maven repository

To download any artifact use

mvn dependency:get -Dartifact=groupId:artifactId:version:packaging:classifier

For Groovy sources this would be

mvn dependency:get -Dartifact=org.codehaus.groovy:groovy-all:2.4.6:jar:sources

For Groovy's javadoc you would use

mvn dependency:get -Dartifact=org.codehaus.groovy:groovy-all:2.4.6:jar:javadoc

This puts the given artifact into your local Maven repository, i.e. usually $HOME/.m2/repository.

dependency:sources just downloads the project dependencies' sources, not the plugins sources nor the sources of dependencies defined inside plugins.

Is there more to an interface than having the correct methods

Don't forget that at a later date you can take an existing class, and make it implement IBox, and it will then become available to all your box-aware code.

This becomes a bit clearer if interfaces are named -able. e.g.

public interface Saveable {
....

public interface Printable {
....

etc. (Naming schemes don't always work e.g. I'm not sure Boxable is appropriate here)

Numpy array dimensions

You can use .ndim for dimension and .shape to know the exact dimension

var = np.array([[1,2,3,4,5,6], [1,2,3,4,5,6]])

var.ndim
# displays 2

var.shape
# display 6, 2

You can change the dimension using .reshape function

var = np.array([[1,2,3,4,5,6], [1,2,3,4,5,6]]).reshape(3,4)

var.ndim
#display 2

var.shape
#display 3, 4

jQuery event handlers always execute in order they were bound - any way around this?

A very good question ... I was intrigued so I did a little digging; for those who are interested, here's where I went, and what I came up with.

Looking at the source code for jQuery 1.4.2 I saw this block between lines 2361 and 2392:

jQuery.each(["bind", "one"], function( i, name ) {
    jQuery.fn[ name ] = function( type, data, fn ) {
        // Handle object literals
        if ( typeof type === "object" ) {
            for ( var key in type ) {
                this[ name ](key, data, type[key], fn);
            }
            return this;
        }

        if ( jQuery.isFunction( data ) ) {
            fn = data;
            data = undefined;
        }

        var handler = name === "one" ? jQuery.proxy( fn, function( event ) {
            jQuery( this ).unbind( event, handler );
            return fn.apply( this, arguments );
        }) : fn;

        if ( type === "unload" && name !== "one" ) {
            this.one( type, data, fn );

        } else {
            for ( var i = 0, l = this.length; i < l; i++ ) {
                jQuery.event.add( this[i], type, handler, data );
            }
        }

        return this;
    };
});

There is a lot of interesting stuff going on here, but the part we are interested in is between lines 2384 and 2388:

else {
    for ( var i = 0, l = this.length; i < l; i++ ) {
        jQuery.event.add( this[i], type, handler, data );
    }
}

Every time we call bind() or one() we are actually making a call to jQuery.event.add() ... so let's take a look at that (lines 1557 to 1672, if you are interested)

add: function( elem, types, handler, data ) {
// ... snip ...
        var handleObjIn, handleObj;

        if ( handler.handler ) {
            handleObjIn = handler;
            handler = handleObjIn.handler;
        }

// ... snip ...

        // Init the element's event structure
        var elemData = jQuery.data( elem );

// ... snip ...

        var events = elemData.events = elemData.events || {},
            eventHandle = elemData.handle, eventHandle;

        if ( !eventHandle ) {
            elemData.handle = eventHandle = function() {
                // Handle the second event of a trigger and when
                // an event is called after a page has unloaded
                return typeof jQuery !== "undefined" && !jQuery.event.triggered ?
                    jQuery.event.handle.apply( eventHandle.elem, arguments ) :
                    undefined;
            };
        }

// ... snip ...

        // Handle multiple events separated by a space
        // jQuery(...).bind("mouseover mouseout", fn);
        types = types.split(" ");

        var type, i = 0, namespaces;

        while ( (type = types[ i++ ]) ) {
            handleObj = handleObjIn ?
                jQuery.extend({}, handleObjIn) :
                { handler: handler, data: data };

            // Namespaced event handlers
                    ^
                    |
      // There is is! Even marked with a nice handy comment so you couldn't miss it 
      // (Unless of course you are not looking for it ... as I wasn't)

            if ( type.indexOf(".") > -1 ) {
                namespaces = type.split(".");
                type = namespaces.shift();
                handleObj.namespace = namespaces.slice(0).sort().join(".");

            } else {
                namespaces = [];
                handleObj.namespace = "";
            }

            handleObj.type = type;
            handleObj.guid = handler.guid;

            // Get the current list of functions bound to this event
            var handlers = events[ type ],
                special = jQuery.event.special[ type ] || {};

            // Init the event handler queue
            if ( !handlers ) {
                handlers = events[ type ] = [];

                   // ... snip ...

            }

                  // ... snip ...

            // Add the function to the element's handler list
            handlers.push( handleObj );

            // Keep track of which events have been used, for global triggering
            jQuery.event.global[ type ] = true;
        }

     // ... snip ...
    }

At this point I realized that understanding this was going to take more than 30 minutes ... so I searched Stackoverflow for

jquery get a list of all event handlers bound to an element

and found this answer for iterating over bound events:

//log them to the console (firebug, ie8)
console.dir( $('#someElementId').data('events') );

//or iterate them
jQuery.each($('#someElementId').data('events'), function(i, event){

    jQuery.each(event, function(i, handler){

        console.log( handler.toString() );

    });

});

Testing that in Firefox I see that the events object in the data attribute of every element has a [some_event_name] attribute (click in our case) to which is attatched an array of handler objects, each of which has a guid, a namespace, a type, and a handler. "So", I think, "we should theoretically be able to add objects built in the same manner to the [element].data.events.[some_event_name].push([our_handler_object); ... "

And then I go to finish writing up my findings ... and find a much better answer posted by RusselUresti ... which introduces me to something new that I didn't know about jQuery (even though I was staring it right in the face.)

Which is proof that Stackoverflow is the best question-and-answer site on the internet, at least in my humble opinion.

So I'm posting this for posterity's sake ... and marking it a community wiki, since RussellUresti already answered the question so well.

Selenium and xPath - locating a link by containing text

Use this

//*[@id='popover-search']/div/div/ul/li[1]/a/span[contains(text(),'Some text')]

OR

//*[@id='popover-search']/div/div/ul/li[1]/a/span[contains(.,'Some text')]

What are invalid characters in XML

In summary, valid characters in the text are:

  • tab, line-feed and carriage-return.
  • all non-control characters are valid except & and <.
  • > is not valid if following ]].

Sections 2.2 and 2.4 of the XML specification provide the answer in detail:

Characters

Legal characters are tab, carriage return, line feed, and the legal characters of Unicode and ISO/IEC 10646

Character data

The ampersand character (&) and the left angle bracket (<) must not appear in their literal form, except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section. If they are needed elsewhere, they must be escaped using either numeric character references or the strings " & " and " < " respectively. The right angle bracket (>) may be represented using the string " > ", and must, for compatibility, be escaped using either " > " or a character reference when it appears in the string " ]]> " in content, when that string is not marking the end of a CDATA section.

jQuery $.cookie is not a function

The old version of jQuery Cookie has been deprecated, so if you're getting the error:

$.cookie is not a function

you should upgrade to the new version.

The API for the new version is also different - rather than using

$.cookie("yourCookieName");

you should use

Cookies.get("yourCookieName");

What is Java String interning?

JLS

JLS 7 3.10.5 defines it and gives a practical example:

Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.

Example 3.10.5-1. String Literals

The program consisting of the compilation unit (§7.3):

package testPackage;
class Test {
    public static void main(String[] args) {
        String hello = "Hello", lo = "lo";
        System.out.print((hello == "Hello") + " ");
        System.out.print((Other.hello == hello) + " ");
        System.out.print((other.Other.hello == hello) + " ");
        System.out.print((hello == ("Hel"+"lo")) + " ");
        System.out.print((hello == ("Hel"+lo)) + " ");
        System.out.println(hello == ("Hel"+lo).intern());
    }
}
class Other { static String hello = "Hello"; }

and the compilation unit:

package other;
public class Other { public static String hello = "Hello"; }

produces the output:

true true true true false true

JVMS

JVMS 7 5.1 says says that interning is implemented magically and efficiently with a dedicated CONSTANT_String_info struct (unlike most other objects which have more generic representations):

A string literal is a reference to an instance of class String, and is derived from a CONSTANT_String_info structure (§4.4.3) in the binary representation of a class or interface. The CONSTANT_String_info structure gives the sequence of Unicode code points constituting the string literal.

The Java programming language requires that identical string literals (that is, literals that contain the same sequence of code points) must refer to the same instance of class String (JLS §3.10.5). In addition, if the method String.intern is called on any string, the result is a reference to the same class instance that would be returned if that string appeared as a literal. Thus, the following expression must have the value true:

("a" + "b" + "c").intern() == "abc"

To derive a string literal, the Java Virtual Machine examines the sequence of code points given by the CONSTANT_String_info structure.

  • If the method String.intern has previously been called on an instance of class String containing a sequence of Unicode code points identical to that given by the CONSTANT_String_info structure, then the result of string literal derivation is a reference to that same instance of class String.

  • Otherwise, a new instance of class String is created containing the sequence of Unicode code points given by the CONSTANT_String_info structure; a reference to that class instance is the result of string literal derivation. Finally, the intern method of the new String instance is invoked.

Bytecode

Let's decompile some OpenJDK 7 bytecode to see interning in action.

If we decompile:

public class StringPool {
    public static void main(String[] args) {
        String a = "abc";
        String b = "abc";
        String c = new String("abc");
        System.out.println(a);
        System.out.println(b);
        System.out.println(a == c);
    }
}

we have on the constant pool:

#2 = String             #32   // abc
[...]
#32 = Utf8               abc

and main:

 0: ldc           #2          // String abc
 2: astore_1
 3: ldc           #2          // String abc
 5: astore_2
 6: new           #3          // class java/lang/String
 9: dup
10: ldc           #2          // String abc
12: invokespecial #4          // Method java/lang/String."<init>":(Ljava/lang/String;)V
15: astore_3
16: getstatic     #5          // Field java/lang/System.out:Ljava/io/PrintStream;
19: aload_1
20: invokevirtual #6          // Method java/io/PrintStream.println:(Ljava/lang/String;)V
23: getstatic     #5          // Field java/lang/System.out:Ljava/io/PrintStream;
26: aload_2
27: invokevirtual #6          // Method java/io/PrintStream.println:(Ljava/lang/String;)V
30: getstatic     #5          // Field java/lang/System.out:Ljava/io/PrintStream;
33: aload_1
34: aload_3
35: if_acmpne     42
38: iconst_1
39: goto          43
42: iconst_0
43: invokevirtual #7          // Method java/io/PrintStream.println:(Z)V

Note how:

  • 0 and 3: the same ldc #2 constant is loaded (the literals)
  • 12: a new string instance is created (with #2 as argument)
  • 35: a and c are compared as regular objects with if_acmpne

The representation of constant strings is quite magic on the bytecode:

and the JVMS quote above seems to say that whenever the Utf8 pointed to is the same, then identical instances are loaded by ldc.

I have done similar tests for fields, and:

  • static final String s = "abc" points to the constant table through the ConstantValue Attribute
  • non-final fields don't have that attribute, but can still be initialized with ldc

Conclusion: there is direct bytecode support for the string pool, and the memory representation is efficient.

Bonus: compare that to the Integer pool, which does not have direct bytecode support (i.e. no CONSTANT_String_info analogue).

Hide element by class in pure Javascript

<script type="text/javascript">
        $(document).ready(function(){

                $('.appBanner').fadeOut('slow');

        });
    </script>

or

<script type="text/javascript">
        $(document).ready(function(){

                $('.appBanner').hide();

        });
    </script>

MVC Razor Hidden input and passing values

You are doing it wrong since you try to map WebForms in the MVC application.

There are no server side controlls in MVC. Only the View and the Controller on the back-end. You send the data from server to the client by means of initialization of the View with your model.

This is happening on the HTTP GET request to your resource.

[HttpGet]
public ActionResult Home() 
{
  var model = new HomeModel { Greeatings = "Hi" };
  return View(model);
}

You send data from client to server by means of posting data to server. To make that happen, you create a form inside your view and [HttpPost] handler in your controller.

// View

@using (Html.BeginForm()) {
  @Html.TextBoxFor(m => m.Name)
  @Html.TextBoxFor(m => m.Password)
}

// Controller

[HttpPost]
public ActionResult Home(LoginModel model) 
{
  // do auth.. and stuff
  return Redirect();
}

Set min-width in HTML table's <td>

min-width and max-width properties do not work the way you expect for table cells. From spec:

In CSS 2.1, the effect of 'min-width' and 'max-width' on tables, inline tables, table cells, table columns, and column groups is undefined.

This hasn't changed in CSS3.

Struct like objects in Java

A very-very old question, but let me make another short contribution. Java 8 introduced lambda expressions and method references. Lambda expressions can be simple method references and not declare a "true" body. But you cannot "convert" a field into a method reference. Thus

stream.mapToInt(SomeData1::x)

isn't legal, but

stream.mapToInt(SomeData2::getX)

is.

jQuery textbox change event

There is no real solution to this - even in the links to other questions given above. In the end I have decided to use setTimeout and call a method that checks every second! Not an ideal solution, but a solution that works and code I am calling is simple enough to not have an effect on performance by being called all the time.

function InitPageControls() {
        CheckIfChanged();
    }

    function CheckIfChanged() {
        // do logic

        setTimeout(function () {
            CheckIfChanged();
        }, 1000);
    }

Hope this helps someone in the future as it seems there is no surefire way of acheiving this using event handlers...

What are the complexity guarantees of the standard containers?

Another quick lookup table is available at this github page

Note : This does not consider all the containers such as, unordered_map etc. but is still great to look at. It is just a cleaner version of this

Capturing URL parameters in request.GET

I would like to share a tip that may save you some time.
If you plan to use something like this in your urls.py file:

url(r'^(?P<username>\w+)/$', views.profile_page,),

Which basically means www.example.com/<username>. Be sure to place it at the end of your URL entries, because otherwise, it is prone to cause conflicts with the URL entries that follow below, i.e. accessing one of them will give you the nice error: User matching query does not exist.

I've just experienced it myself; hope it helps!

Replacing NULL with 0 in a SQL server query

Wrap your column in this code.

 ISNULL(Yourcolumn, 0)

Maybe check why you are getting nulls

How do I export a project in the Android studio?

From the menu:

Build|Generate Signed APK

or

Build|Build APK

(the latter if you don't need a signed one to publish to the Play Store)

CMake is not able to find BOOST libraries

Try to complete cmake process with following libs:

sudo apt-get install cmake libblkid-dev e2fslibs-dev libboost-all-dev libaudit-dev

Text overflow ellipsis on two lines

This is a total hack, but it works:

http://jsfiddle.net/2wPNg/

div {
    width: 30%;
    float: left;
    margin-right: 2%;
    height: 94px;
    overflow: hidden;
    position: relative;
}

div:after {
     display: block;
      content: '...';
      width: 1em;
  height: 1.5em;
  background: #fff;
  position: absolute;
  bottom: -6px;
  right: 0;
    }

It does have problems.... it might cut off a letter awkwardly, and it will probably have some weird results on a responsive site.

How to print a two dimensional array?

Something like this that i answer in another question

public class Snippet {
    public static void main(String[] args) {
        int [][]lst = new int[10][10];

        for (int[] arr : lst) {
            System.out.println(Arrays.toString(arr));
        }
    }

}

How to convert a String into an ArrayList?

If you want to convert a string into a ArrayList try this:

public ArrayList<Character> convertStringToArraylist(String str) {
    ArrayList<Character> charList = new ArrayList<Character>();      
    for(int i = 0; i<str.length();i++){
        charList.add(str.charAt(i));
    }
    return charList;
}

But i see a string array in your example, so if you wanted to convert a string array into ArrayList use this:

public static ArrayList<String> convertStringArrayToArraylist(String[] strArr){
    ArrayList<String> stringList = new ArrayList<String>();
    for (String s : strArr) {
        stringList.add(s);
    }
    return stringList;
}

How to verify an XPath expression in Chrome Developers tool or Firefox's Firebug?

I verify XPath and CSS selectors using WebSync Chrome extension.

It provides possibility to verify selectors and also to generate/modify selectors by clicking on element attributes.

https://chrome.google.com/webstore/detail/natu-websync/aohpgnblncapofbobbilnlfliihianac

enter image description here

Case insensitive comparison of strings in shell script

if you have bash

str1="MATCH"
str2="match"
shopt -s nocasematch
case "$str1" in
 $str2 ) echo "match";;
 *) echo "no match";;
esac

otherwise, you should tell us what shell you are using.

alternative, using awk

str1="MATCH"
str2="match"
awk -vs1="$str1" -vs2="$str2" 'BEGIN {
  if ( tolower(s1) == tolower(s2) ){
    print "match"
  }
}'

get the value of input type file , and alert if empty

There should be

$('.send_upload')

but not $('.upload')

Hiding user input on terminal in Linux script

I always like to use Ansi escape characters:

echo -e "Enter your password: \x1B[8m"
echo -e "\x1B[0m"

8m makes text invisible and 0m resets text to "normal." The -e makes Ansi escapes possible.

The only caveat is that you can still copy and paste the text that is there, so you probably shouldn't use this if you really want security.

It just lets people not look at your passwords when you type them in. Just don't leave your computer on afterwards. :)


NOTE:

The above is platform independent as long as it supports Ansi escape sequences.

However, for another Unix solution, you could simply tell read to not echo the characters...

printf "password: "
let pass $(read -s)
printf "\nhey everyone, the password the user just entered is $pass\n"

Why doesn't [01-12] range work as expected?

You seem to have misunderstood how character classes definition works in regex.

To match any of the strings 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, or 12, something like this works:

0[1-9]|1[0-2]

References


Explanation

A character class, by itself, attempts to match one and exactly one character from the input string. [01-12] actually defines [012], a character class that matches one character from the input against any of the 3 characters 0, 1, or 2.

The - range definition goes from 1 to 1, which includes just 1. On the other hand, something like [1-9] includes 1, 2, 3, 4, 5, 6, 7, 8, 9.

Beginners often make the mistakes of defining things like [this|that]. This doesn't "work". This character definition defines [this|a], i.e. it matches one character from the input against any of 6 characters in t, h, i, s, | or a. More than likely (this|that) is what is intended.

References


How ranges are defined

So it's obvious now that a pattern like between [24-48] hours doesn't "work". The character class in this case is equivalent to [248].

That is, - in a character class definition doesn't define numeric range in the pattern. Regex engines doesn't really "understand" numbers in the pattern, with the exception of finite repetition syntax (e.g. a{3,5} matches between 3 and 5 a).

Range definition instead uses ASCII/Unicode encoding of the characters to define ranges. The character 0 is encoded in ASCII as decimal 48; 9 is 57. Thus, the character definition [0-9] includes all character whose values are between decimal 48 and 57 in the encoding. Rather sensibly, by design these are the characters 0, 1, ..., 9.

See also


Another example: A to Z

Let's take a look at another common character class definition [a-zA-Z]

In ASCII:

  • A = 65, Z = 90
  • a = 97, z = 122

This means that:

  • [a-zA-Z] and [A-Za-z] are equivalent
  • In most flavors, [a-Z] is likely to be an illegal character range
    • because a (97) is "greater than" than Z (90)
  • [A-z] is legal, but also includes these six characters:
    • [ (91), \ (92), ] (93), ^ (94), _ (95), ` (96)

Related questions

FPDF error: Some data has already been output, can't send PDF

For fpdf to work properly, there cannot be any output at all beside what fpdf generates. For example, this will work:

<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

While this will not (note the leading space before the opening <? tag)

 <?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

Also, this will not work either (the echo will break it):

<?php
echo "About to create pdf";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

I'm not sure about the drupal side of things, but I know that absolutely zero non-fpdf output is a requirement for fpdf to work.


add ob_start (); at the top and at the end add ob_end_flush();

<?php
    ob_start();
    require('fpdf.php');
    $pdf = new FPDF();
    $pdf->AddPage();
    $pdf->SetFont('Arial','B',16);
    $pdf->Cell(40,10,'Hello World!');
    $pdf->Output();
    ob_end_flush(); 
?>

give me an error as below:
FPDF error: Some data has already been output, can't send PDF

to over come this error: go to fpdf.php in that,goto line number 996

function Output($name='', $dest='')

after that make changes like this:

function Output($name='', $dest='') {   
    ob_clean();     //Output PDF to so

Hi do you have a session header on the top of your page. or any includes If you have then try to add this codes on top pf your page it should works fine.

<?

while (ob_get_level())
ob_end_clean();
header("Content-Encoding: None", true);

?>

cheers :-)


In my case i had set:

ini_set('display_errors', 'on');
error_reporting(E_ALL | E_STRICT);

When i made the request to generate the report, some warnings were displayed in the browser (like the usage of deprecated functions).
Turning off the display_errors option, the report was generated successfully.

Show / hide div on click with CSS

HTML

<input type="text" value="CLICK TO SHOW CONTENT">
<div id="content">
and the content will show.
</div>

CSS

_x000D_
_x000D_
#content {
  display: none;
}
input[type="text"]{
    color: transparent;
    text-shadow: 0 0 0 #000;
    padding: 6px 12px;
    width: 150px;
    cursor: pointer;
}
input[type="text"]:focus{
    outline: none;
}
input:focus + div#content {
  display: block;
}
_x000D_
<input type="text" value="CLICK TO SHOW CONTENT">
<div id="content">
and the content will show.
</div>
_x000D_
_x000D_
_x000D_

How to use sys.exit() in Python

sys.exit() raises a SystemExit exception which you are probably assuming as some error. If you want your program not to raise SystemExit but return gracefully, you can wrap your functionality in a function and return from places you are planning to use sys.exit

How to pass object from one component to another in Angular 2?

For one-way data binding from parent to child, use the @Input decorator (as recommended by the style guide) to specify an input property on the child component

@Input() model: any;   // instead of any, specify your type

and use template property binding in the parent template

<child [model]="parentModel"></child>

Since you are passing an object (a JavaScript reference type) any changes you make to object properties in the parent or the child component will be reflected in the other component, since both components have a reference to the same object. I show this in the Plunker.

If you reassign the object in the parent component

this.model = someNewModel;

Angular will propagate the new object reference to the child component (automatically, as part of change detection).

The only thing you shouldn't do is reassign the object in the child component. If you do this, the parent will still reference the original object. (If you do need two-way data binding, see https://stackoverflow.com/a/34616530/215945).

@Component({
  selector: 'child',
  template: `<h3>child</h3> 
    <div>{{model.prop1}}</div>
    <button (click)="updateModel()">update model</button>`
})
class Child {
  @Input() model: any;   // instead of any, specify your type
  updateModel() {
    this.model.prop1 += ' child';
  }
}

@Component({
  selector: 'my-app',
  directives: [Child],
  template: `
    <h3>Parent</h3>
    <div>{{parentModel.prop1}}</div>
    <button (click)="updateModel()">update model</button>
    <child [model]="parentModel"></child>`
})
export class AppComponent {
  parentModel = { prop1: '1st prop', prop2: '2nd prop' };
  constructor() {}
  updateModel() { this.parentModel.prop1 += ' parent'; }
}

Plunker - Angular RC.2

Submitting the value of a disabled input field

Input elements have a property called disabled. When the form submits, just run some code like this:

var myInput = document.getElementById('myInput');
myInput.disabled = true;

Parsing a JSON string in Ruby

It looks like a JSON string. You can use one of many JSON libraries and it's as simple as doing:

JSON.parse(string)

Can I have an IF block in DOS batch file?

I ran across this article in the results returned by a search related to the IF command in a batch file, and I couldn't resist the opportunity to correct the misconception that IF blocks are limited to single commands. Following is a portion of a production Windows NT command script that runs daily on the machine on which I am composing this reply.

    if "%COPYTOOL%" equ "R" (
    WWLOGGER.exe "%APPDATA%\WizardWrx\%~n0.LOG" "Using RoboCopy to make a backup of %USERPROFILE%\My Documents\Outlook Files\*"
    %TOOLPATH% %SRCEPATH% %DESTPATH% /copyall %RCLOGSTR% /m /np /r:0 /tee
    C:\BIN\ExitCodeMapper.exe C:\BIN\ExitCodeMapper.INI[Robocopy] %TEMP%\%~n0.TMP %ERRORLEVEL%
) else (
    WWLOGGER.exe "%APPDATA%\WizardWrx\%~n0.LOG" "Using XCopy to make a backup of %USERPROFILE%\My Documents\Outlook Files\*"
    call %TOOLPATH%  "%USERPROFILE%\My Documents\Outlook Files\*" "%USERPROFILE%\My Documents\Outlook Files\_backups" /f /m /v /y
    C:\BIN\ExitCodeMapper.exe C:\BIN\ExitCodeMapper.INI[Xcopy] %TEMP%\%~n0.TMP %ERRORLEVEL%
)

Perhaps blocks of two or more lines applies exclusively to Windows NT command scripts (.CMD files), because a search of the production scripts directory of an application that is restricted to old school batch (.BAT) files, revealed only one-command blocks. Since the application has gone into extended maintenance (meaning that I am not actively involved in supporting it), I can't say whether that is because I didn't need more than one line, or that I couldn't make them work.

Regardless, if the latter is true, there is a simple workaround; move the multiple lines into either a separate batch file or a batch file subroutine. I know that the latter works in both kinds of scripts.

retrieve data from db and display it in table in php .. see this code whats wrong with it?

Here is the solution total html with php and database connections

   <!doctype html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>database connections</title>
    </head>
    <body>
      <?php
      $username = "database-username";
      $password = "database-password";
      $host = "localhost";

      $connector = mysql_connect($host,$username,$password)
          or die("Unable to connect");
        echo "Connections are made successfully::";
      $selected = mysql_select_db("test_db", $connector)
        or die("Unable to connect");

      //execute the SQL query and return records
      $result = mysql_query("SELECT * FROM table_one ");
      ?>
      <table border="2" style= "background-color: #84ed86; color: #761a9b; margin: 0 auto;" >
      <thead>
        <tr>
          <th>Employee_id</th>
          <th>Employee_Name</th>
          <th>Employee_dob</th>
          <th>Employee_Adress</th>
          <th>Employee_dept</th>
          <td>Employee_salary</td>
        </tr>
      </thead>
      <tbody>
        <?php
          while( $row = mysql_fetch_assoc( $result ) ){
            echo
            "<tr>
              <td>{$row\['employee_id'\]}</td>
              <td>{$row\['employee_name'\]}</td>
              <td>{$row\['employee_dob'\]}</td>
              <td>{$row\['employee_addr'\]}</td>
              <td>{$row\['employee_dept'\]}</td>
              <td>{$row\['employee_sal'\]}</td> 
            </tr>\n";
          }
        ?>
      </tbody>
    </table>
     <?php mysql_close($connector); ?>
    </body>
    </html>

mySQL :: insert into table, data from another table?

This query is for add data from one table to another table using foreign key

let qry = "INSERT INTO `tb_customer_master` (`My_Referral_Code`, `City_Id`, `Cust_Name`, `Reg_Date_Time`, `Mobile_Number`, `Email_Id`, `Gender`, `Cust_Age`, `Profile_Image`, `Token`, `App_Type`, `Refer_By_Referral_Code`, `Status`) values ('" + randomstring.generate(7) + "', '" + req.body.City_Id + "', '" + req.body.Cust_Name + "', '" + req.body.Reg_Date_Time + "','" + req.body.Mobile_Number + "','" + req.body.Email_Id + "','" + req.body.Gender + "','" + req.body.Cust_Age + "','" + req.body.Profile_Image + "','" + req.body.Token + "','" + req.body.App_Type + "','" + req.body.Refer_By_Referral_Code + "','" + req.body.Status + "')";
                        connection.query(qry, (err, rows) => {
                            if (err) { res.send(err) } else {
                                let insert = "INSERT INTO `tb_customer_and_transaction_master` (`Cust_Id`)values ('" + rows.insertId + "')";
                                connection.query(insert, (err) => {
                                    if (err) {
                                        res.json(err)
                                    } else {
                                        res.json("Customer added")
                                    }
                                })
                            }
    
    
                        })
                    }
                }
    
            }
        })
    })

Curl and PHP - how can I pass a json through curl by PUT,POST,GET

PUT

$data = array('username'=>'dog','password'=>'tall');
$data_json = json_encode($data);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_json)));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response  = curl_exec($ch);
curl_close($ch);

POST

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response  = curl_exec($ch);
curl_close($ch);

GET See @Dan H answer

DELETE

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response  = curl_exec($ch);
curl_close($ch);

How does delete[] know it's an array?

The answer:

int* pArray = new int[5];

int size = *(pArray-1);

Posted above is not correct and produces invalid value. The "-1"counts elements On 64 bit Windows OS the correct buffer size resides in Ptr - 4 bytes address

Applying Comic Sans Ms font style

The httpd dæmon on OpenBSD uses the following stylesheet for all of its error messages, which presumably covers all the Comic Sans variations on non-Windows systems:

http://openbsd.su/src/usr.sbin/httpd/server_http.c#server_abort_http

810    style = "body { background-color: white; color: black; font-family: "
811        "'Comic Sans MS', 'Chalkboard SE', 'Comic Neue', sans-serif; }\n"
812        "hr { border: 0; border-bottom: 1px dashed; }\n";

E.g., try this:

font-family: 'Comic Sans MS', 'Chalkboard SE', 'Comic Neue', sans-serif;

Bash conditionals: how to "and" expressions? (if [ ! -z $VAR && -e $VAR ])

Simply quote your variable:

[ -e "$VAR" ]

This evaluates to [ -e "" ] if $VAR is empty.

Your version does not work because it evaluates to [ -e ]. Now in this case, bash simply checks if the single argument (-e) is a non-empty string.

From the manpage:

test and [ evaluate conditional expressions using a set of rules based on the number of arguments. ...

1 argument

The expression is true if and only if the argument is not null.

(Also, this solution has the additional benefit of working with filenames containing spaces)

`require': no such file to load -- mkmf (LoadError)

After some search for a solution it turns out the -dev package is needed, not just ruby1.8. So if you have ruby1.9.1 doing

sudo apt-get install ruby1.9.1-dev

or to install generic ruby version, use (as per @lamplightdev comment):

sudo apt-get install ruby-dev

should fix it.

Try locate mkmf to see if the file is actually there.

How to create an executable .exe file from a .m file

mcc -?

explains that the syntax to make *.exe (Standalone Application) with *.m is:

 mcc -m <matlabFile.m> 

For example:

mcc -m file.m

will create file.exe in the curent directory.

Complexities of binary tree traversals

Travesal is O(n) for any order - because you are hitting each node once. Lookup is where it can be less than O(n) IF the tree has some sort of organizing schema (ie binary search tree).

add class with JavaScript

In your snippet, button is an instance of NodeList, to which you can't attach an event listener directly, nor can you change the elements' className properties directly.
Your best bet is to delegate the event:

document.body.addEventListener('mouseover',function(e)
{
    e = e || window.event;
    var target = e.target || e.srcElement;
    if (target.tagName.toLowerCase() === 'img' && target.className.match(/\bnavButton\b/))
    {
        target.className += ' active';//set class
    }
},false);

Of course, my guess is that the active class needs to be removed once the mouseout event fires, you might consider using a second delegator for that, but you could just aswell attach an event handler to the one element that has the active class:

document.body.addEventListener('mouseover',function(e)
{
    e = e || window.event;
    var oldSrc, target = e.target || e.srcElement;
    if (target.tagName.toLowerCase() === 'img' && target.className.match(/\bnavButton\b/))
    {
        target.className += ' active';//set class
        oldSrc = target.getAttribute('src');
        target.setAttribute('src', 'images/arrows/top_o.png');
        target.onmouseout = function()
        {
            target.onmouseout = null;//remove this event handler, we don't need it anymore
            target.className = target.className.replace(/\bactive\b/,'').trim();
            target.setAttribute('src', oldSrc);
        };
    }
},false);

There is some room for improvements, with this code, but I'm not going to have all the fun here ;-).

Check the fiddle here

SQL select statements with multiple tables

select P.*,
A.Street,
A.City,
A.State
from Preson P
inner join Address A on P.id=A.Person_id
where A.Zip=97229
Order by A.Street,A.City,A.State

How to "log in" to a website using Python's Requests module?

I know you've found another solution, but for those like me who find this question, looking for the same thing, it can be achieved with requests as follows:

Firstly, as Marcus did, check the source of the login form to get three pieces of information - the url that the form posts to, and the name attributes of the username and password fields. In his example, they are inUserName and inUserPass.

Once you've got that, you can use a requests.Session() instance to make a post request to the login url with your login details as a payload. Making requests from a session instance is essentially the same as using requests normally, it simply adds persistence, allowing you to store and use cookies etc.

Assuming your login attempt was successful, you can simply use the session instance to make further requests to the site. The cookie that identifies you will be used to authorise the requests.

Example

import requests

# Fill in your details here to be posted to the login form.
payload = {
    'inUserName': 'username',
    'inUserPass': 'password'
}

# Use 'with' to ensure the session context is closed after use.
with requests.Session() as s:
    p = s.post('LOGIN_URL', data=payload)
    # print the html returned or something more intelligent to see if it's a successful login page.
    print p.text

    # An authorised request.
    r = s.get('A protected web page url')
    print r.text
        # etc...

how to redirect to home page

document.location.href="/";

GitHub Error Message - Permission denied (publickey)

This Worked for me

There are 2 options in github - HTTPS/SSH

I had selected SSH by mistake due to which the error was occuring -_-

Switch it to HTTPS and then copy the url again and try :)

Angular: 'Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays'

I was the same problem and as Pengyy suggest, that is the fix. Thanks a lot.

My problem on the Browser Console:

Image Problem on Browser Console

PortafolioComponent.html:3 ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed(…)

In my case my code fix was:

//productos.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

@Injectable()
export class ProductosService {

  productos:any[] = [];
  cargando:boolean = true;

  constructor( private http:Http) {
    this.cargar_productos();
  }

  public cargar_productos(){

    this.cargando = true;

    this.http.get('https://webpage-88888a1.firebaseio.com/productos.json')
      .subscribe( res => {
        console.log(res.json());
        this.cargando = false;
        this.productos = res.json().productos; // Before this.productos = res.json(); 
      });
  }

}

How to auto-reload files in Node.js?

I have tried pm2 : installation is easy and easy to use too; the result is satisfying. However, we have to take care of which edition of pm2 that we want. pm 2 runtime is the free edition, whereas pm2 plus and pm2 enterprise are not free.

As for Strongloop, my installation failed or was not complete, so I couldn't use it.

Android and Facebook share intent

Here is something I did which open Facebook App with Link

shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setComponent(new ComponentName("com.facebook.katana",
                    "com.facebook.katana.activity.composer.ImplicitShareIntentHandler"));

shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT,  videoUrl);

ServletContext.getRequestDispatcher() vs ServletRequest.getRequestDispatcher()

The request method getRequestDispatcher() can be used for referring to local servlets within single webapp.

Servlet context based getRequestDispatcher() method can used of referring servlets from other web applications deployed on SAME server.

How to stop PHP code execution?

You can use __halt_compiler function which will Halt the compiler execution

http://www.php.net/manual/en/function.halt-compiler.php

What is the difference between spark.sql.shuffle.partitions and spark.default.parallelism?

From the answer here, spark.sql.shuffle.partitions configures the number of partitions that are used when shuffling data for joins or aggregations.

spark.default.parallelism is the default number of partitions in RDDs returned by transformations like join, reduceByKey, and parallelize when not set explicitly by the user. Note that spark.default.parallelism seems to only be working for raw RDD and is ignored when working with dataframes.

If the task you are performing is not a join or aggregation and you are working with dataframes then setting these will not have any effect. You could, however, set the number of partitions yourself by calling df.repartition(numOfPartitions) (don't forget to assign it to a new val) in your code.


To change the settings in your code you can simply do:

sqlContext.setConf("spark.sql.shuffle.partitions", "300")
sqlContext.setConf("spark.default.parallelism", "300")

Alternatively, you can make the change when submitting the job to a cluster with spark-submit:

./bin/spark-submit --conf spark.sql.shuffle.partitions=300 --conf spark.default.parallelism=300

When should I use File.separator and when File.pathSeparator?

java.io.File class contains four static separator variables. For better understanding, Let's understand with the help of some code

  1. separator: Platform dependent default name-separator character as String. For windows, it’s ‘\’ and for unix it’s ‘/’
  2. separatorChar: Same as separator but it’s char
  3. pathSeparator: Platform dependent variable for path-separator. For example PATH or CLASSPATH variable list of paths separated by ‘:’ in Unix systems and ‘;’ in Windows system
  4. pathSeparatorChar: Same as pathSeparator but it’s char

Note that all of these are final variables and system dependent.

Here is the java program to print these separator variables. FileSeparator.java

import java.io.File;

public class FileSeparator {

    public static void main(String[] args) {
        System.out.println("File.separator = "+File.separator);
        System.out.println("File.separatorChar = "+File.separatorChar);
        System.out.println("File.pathSeparator = "+File.pathSeparator);
        System.out.println("File.pathSeparatorChar = "+File.pathSeparatorChar);
    }

}

Output of above program on Unix system:

File.separator = /
File.separatorChar = /
File.pathSeparator = :
File.pathSeparatorChar = :

Output of the program on Windows system:

File.separator = \
File.separatorChar = \
File.pathSeparator = ;
File.pathSeparatorChar = ;

To make our program platform independent, we should always use these separators to create file path or read any system variables like PATH, CLASSPATH.

Here is the code snippet showing how to use separators correctly.

//no platform independence, good for Unix systems
File fileUnsafe = new File("tmp/abc.txt");
//platform independent and safe to use across Unix and Windows
File fileSafe = new File("tmp"+File.separator+"abc.txt");

Removing the remembered login and password list in SQL Server Management Studio

For SQL Server Management Studio 2008

  1. You need to go C:\Documents and Settings\%username%\Application Data\Microsoft\Microsoft SQL Server\100\Tools\Shell

  2. Delete SqlStudio.bin

onKeyDown event not working on divs in React

You're thinking too much in pure Javascript. Get rid of your listeners on those React lifecycle methods and use event.key instead of event.keyCode (because this is not a JS event object, it is a React SyntheticEvent). Your entire component could be as simple as this (assuming you haven't bound your methods in a constructor).

onKeyPressed(e) {
  console.log(e.key);
}

render() {
  let player = this.props.boards.dungeons[this.props.boards.currentBoard].player;
  return (
    <div 
      className="player"
      style={{ position: "absolute" }}
      onKeyDown={this.onKeyPressed}
    >
      <div className="light-circle">
        <div className="image-wrapper">
          <img src={IMG_URL+player.img} />
        </div>
      </div>
    </div>
  )
}

How to restore the menu bar in Visual Studio Code

Press Ctrl + Shift + P to open the Command Palette, then write command : Toggle Menu Bar

Reading e-mails from Outlook with Python through MAPI

I had the same issue. Combining various approaches from the internet (and above) come up with the following approach (checkEmails.py)

class CheckMailer:

        def __init__(self, filename="LOG1.txt", mailbox="Mailbox - Another User Mailbox", folderindex=3):
            self.f = FileWriter(filename)
            self.outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI").Folders(mailbox)
            self.inbox = self.outlook.Folders(folderindex)


        def check(self):                
        #===============================================================================
        # for i in xrange(1,100):                           #Uncomment this section if index 3 does not work for you
        #     try:
        #         self.inbox = self.outlook.Folders(i)     # "6" refers to the index of inbox for Default User Mailbox
        #         print "%i %s" % (i,self.inbox)            # "3" refers to the index of inbox for Another user's mailbox
        #     except:
        #         print "%i does not work"%i
        #===============================================================================

                self.f.pl(time.strftime("%H:%M:%S"))
                tot = 0                
                messages = self.inbox.Items
                message = messages.GetFirst()
                while message:
                    self.f.pl (message.Subject)
                    message = messages.GetNext()
                    tot += 1
                self.f.pl("Total Messages found: %i" % tot)
                self.f.pl("-" * 80)
                self.f.flush()

if __name__ == "__main__":
    mail = CheckMailer()
    for i in xrange(320):  # this is 10.6 hours approximately
            mail.check()
            time.sleep(120.00)

For concistency I include also the code for the FileWriter class (found in FileWrapper.py). I needed this because trying to pipe UTF8 to a file in windows did not work.

class FileWriter(object):
    '''
    convenient file wrapper for writing to files
    '''


    def __init__(self, filename):
        '''
        Constructor
        '''
        self.file = open(filename, "w")

    def pl(self, a_string):
        str_uni = a_string.encode('utf-8')
        self.file.write(str_uni)
        self.file.write("\n")

    def flush(self):
        self.file.flush()

Checking from shell script if a directory contains files

if ls /some/dir/* >/dev/null 2>&1 ; then echo "huzzah"; fi;

error C2039: 'string' : is not a member of 'std', header file problem

You need to have

#include <string>

in the header file too.The forward declaration on it's own doesn't do enough.

Also strongly consider header guards for your header files to avoid possible future problems as your project grows. So at the top do something like:

#ifndef THE_FILE_NAME_H
#define THE_FILE_NAME_H

/* header goes in here */

#endif

This will prevent the header file from being #included multiple times, if you don't have such a guard then you can have issues with multiple declarations.

Opening PDF String in new window with javascript

An updated version of answer by @Noby Fujioka:

function showPdfInNewTab(base64Data, fileName) {  
  let pdfWindow = window.open("");
  pdfWindow.document.write("<html<head><title>"+fileName+"</title><style>body{margin: 0px;}iframe{border-width: 0px;}</style></head>");
  pdfWindow.document.write("<body><embed width='100%' height='100%' src='data:application/pdf;base64, " + encodeURI(base64Data)+"#toolbar=0&navpanes=0&scrollbar=0'></embed></body></html>");
}

When and why to 'return false' in JavaScript?

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

Definition and Usage

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

For example, this can be useful when:

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

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

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

How can I get the Windows last reboot reason

Take a look at the Event Log API. Case a) (bluescreen, user cut the power cord or system hang) causes a note ('system did not shutdown correctly' or something like that) to be left in the 'System' event log the next time the system is rebooted properly. You should be able to access it programmatically using the above API (honestly, I've never used it but it should work).

Check status of one port on remote host

Use nc command,

nc -zv <hostname/ip> <port/port range>

For example,
nc -zv localhost 27017-27019
or
nc -zv localhost 27017

You can also use telnet command

telnet <ip/host> port

Add inline style using Javascript

If you don't want to add each css property line by line, you can do something like this:

_x000D_
_x000D_
document.body.insertAdjacentHTML('afterbegin','<div id="div"></div>');_x000D_
_x000D_
/**_x000D_
 * Add styles to DOM element_x000D_
 * @element DOM element_x000D_
 * @styles object with css styles_x000D_
 */_x000D_
function addStyles(element,styles){_x000D_
  for(id in styles){_x000D_
    element.style[id] = styles[id];_x000D_
  }_x000D_
}_x000D_
_x000D_
// usage_x000D_
var nFilter = document.getElementById('div');_x000D_
var styles = {_x000D_
  color: "red"_x000D_
  ,width: "100px"_x000D_
  ,height: "100px"_x000D_
  ,display: "block"_x000D_
  ,border: "1px solid blue"_x000D_
}_x000D_
addStyles(nFilter,styles);
_x000D_
_x000D_
_x000D_

Change background color of iframe issue

An <iframe> background can be changed like this:

<iframe allowtransparency="true" style="background: #FFFFFF;" 
    src="http://zingaya.com/widget/9d043c064dc241068881f045f9d8c151" 
    frameborder="0" height="184" width="100%">
</iframe>

I don't think it's possible to change the background of the page that you have loaded in the iframe.

git: How to diff changed files versus previous versions after a pull?

There are all kinds of wonderful ways to specify commits - see the specifying revisions section of man git-rev-parse for more details. In this case, you probably want:

git diff HEAD@{1}

The @{1} means "the previous position of the ref I've specified", so that evaluates to what you had checked out previously - just before the pull. You can tack HEAD on the end there if you also have some changes in your work tree and you don't want to see the diffs for them.

I'm not sure what you're asking for with "the commit ID of my latest version of the file" - the commit "ID" (SHA1 hash) is that 40-character hex right at the top of every entry in the output of git log. It's the hash for the entire commit, not for a given file. You don't really ever need more - if you want to diff just one file across the pull, do

git diff HEAD@{1} filename

This is a general thing - if you want to know about the state of a file in a given commit, you specify the commit and the file, not an ID/hash specific to the file.

HTTP Status 405 - Request method 'POST' not supported (Spring MVC)

I found the problem that was causing the HTTP error.

In the setFalse() function that is triggered by the Save button my code was trying to submit the form that contained the button.

        function setFalse(){
            document.getElementById("hasId").value ="false";
            document.deliveryForm.submit();
            document.submitForm.submit();

when I remove the document.submitForm.submit(); it works:

        function setFalse(){
            document.getElementById("hasId").value ="false";
            document.deliveryForm.submit()

@Roger Lindsjö Thank you for spotting my error where I wasn't passing on the right parameter!

Using success/error/finally/catch with Promises in AngularJS

Forget about using success and error method.

Both methods have been deprecated in angular 1.4. Basically, the reason behind the deprecation is that they are not chainable-friendly, so to speak.

With the following example, I'll try to demonstrate what I mean about success and error being not chainable-friendly. Suppose we call an API that returns a user object with an address:

User object:

{name: 'Igor', address: 'San Francisco'}

Call to the API:

$http.get('/user')
    .success(function (user) {
        return user.address;   <---  
    })                            |  // you might expect that 'obj' is equal to the
    .then(function (obj) {   ------  // address of the user, but it is NOT

        console.log(obj); // -> {name: 'Igor', address: 'San Francisco'}
    });
};

What happened?

Because success and error return the original promise, i.e. the one returned by $http.get, the object passed to the callback of the then is the whole user object, that is to say the same input to the preceding success callback.

If we had chained two then, this would have been less confusing:

$http.get('/user')
    .then(function (user) {
        return user.address;  
    })
    .then(function (obj) {  
        console.log(obj); // -> 'San Francisco'
    });
};

Use Font Awesome icon as CSS content

Update for Font Awesome 5 using SCSS

.icon {
  @extend %fa-icon;
  @extend .fas;

  &:before {
    content: fa-content($fa-var-user);
  }
}

Programmatically relaunch/recreate an activity?

After looking for the gingerbread implement for recreate, I'd like to use following codes (for gingerbread):

activity.mMainThread.mAppThread.scheduleRelaunchActivity(activity.mToken, null, null, 0, false, null);

For these codes, it's from the implementation in higher api.

public void recreate() {
    if (mParent != null) {
        throw new IllegalStateException("Can only be called on top-level activity");
    }
    if (Looper.myLooper() != mMainThread.getLooper()) {
        throw new IllegalStateException("Must be called from main thread");
    }
    mMainThread.requestRelaunchActivity(mToken, null, null, 0, false, null, false);
}

Api-10 has no requestRelaunchActivity, however, from the diff, i found this:

             public final void scheduleRelaunchActivity(IBinder token,
                     List<ResultInfo> pendingResults, List<Intent> pendingNewIntents,
                     int configChanges, boolean notResumed, Configuration config) {
    -            ActivityClientRecord r = new ActivityClientRecord();
    -
    -            r.token = token;
    -            r.pendingResults = pendingResults;
    -            r.pendingIntents = pendingNewIntents;
    -            r.startsNotResumed = notResumed;
    -            r.createdConfig = config;
    -
    -            synchronized (mPackages) {
    -                mRelaunchingActivities.add(r);
    -            }
    -
    -            queueOrSendMessage(H.RELAUNCH_ACTIVITY, r, configChanges);
    +            requestRelaunchActivity(token, pendingResults, pendingNewIntents,
    +                    configChanges, notResumed, config, true);
             }

So I think I could use scheduleRelaunchActivity instead of requestRelaunchActivity.

And I have written them using reflect:

package me.piebridge.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.res.Configuration;
import android.os.Build;
import android.os.IBinder;

public class GingerBreadUtil {

    private static Field scanField(Class<?> clazz, String... names) {
        for (String name : names) {
            Field field;
            try {
                field = clazz.getDeclaredField(name);
                field.setAccessible(true);
                return field;
            } catch (NoSuchFieldException e) {
            }
            try {
                field = clazz.getField(name);
                field.setAccessible(true);
                return field;
            } catch (NoSuchFieldException e) {
            }
        }
        return null;
    }

    public static void recreate(Activity activity) {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD_MR1) {
            recreateHC(activity);
        } else {
            try {
                recreateGB(activity);
            } catch (InvocationTargetException e) {
                e.getTargetException().printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private static void recreateHC(Activity activity) {
        ((Activity) activity).recreate();
    }

    private static void recreateGB(Activity activity) throws IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Field Activity$mToken = scanField(Activity.class, "mToken");
        IBinder mToken = (IBinder) Activity$mToken.get(activity);
        Field Activity$mMainThread = scanField(Activity.class, "mMainThread");
        Object mMainThread = Activity$mMainThread.get(activity);
        Field ActivityThread$mAppThread = scanField(mMainThread.getClass(), "mAppThread");
        Object mAppThread = ActivityThread$mAppThread.get(mMainThread);
        Method method = mAppThread.getClass().getMethod("scheduleRelaunchActivity",
            IBinder.class, List.class, List.class, int.class, boolean.class, Configuration.class);
        method.invoke(mAppThread, mToken, null, null, 0, false, null);
    }

}

I'm using these codes for the back-porting of xposed framework.

Sql Query to list all views in an SQL Server 2005 database

SELECT SCHEMA_NAME(schema_id) AS schema_name
,name AS view_name
,OBJECTPROPERTYEX(OBJECT_ID,'IsIndexed') AS IsIndexed
,OBJECTPROPERTYEX(OBJECT_ID,'IsIndexable') AS IsIndexable
FROM sys.views

How can I convert my Java program to an .exe file?

You could make a batch file with the following code:

start javaw -jar JarFile.jar

and convert the .bat to an .exe using any .bat to .exe converter.

jQuery - getting custom attribute from selected option

Try this:

$(function() { 
    $("#location").change(function(){ 
        var element = $(this).find('option:selected'); 
        var myTag = element.attr("myTag"); 

        $('#setMyTag').val(myTag); 
    }); 
}); 

Java better way to delete file if exists

I was working on this type of function, maybe this will interests some of you ...

public boolean deleteFile(File file) throws IOException {
    if (file != null) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();

            for (File f: files) {
                deleteFile(f);
            }
        }
        return Files.deleteIfExists(file.toPath());
    }
    return false;
}

How can I determine browser window size on server side C#

Here how I solved it using Cookies:

First of all, inside the website main script:

var browserWindowSize = getCookie("_browserWindowSize");
var newSize = $(window).width() + "," + $(window).height();
var reloadForCookieRefresh = false;

if (browserWindowSize == undefined || browserWindowSize == null || newSize != browserWindowSize) {
    setCookie("_browserWindowSize", newSize, 30);
    reloadForCookieRefresh = true;
}

if (reloadForCookieRefresh)
    window.location.reload();

function setCookie(name, value, days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "") + expires + "; path=/";
}

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

And inside MVC action filter:

public class SetCurrentRequestDataFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // currentRequestService is registered per web request using IoC
        var currentRequestService = iocResolver.Resolve<ICurrentRequestService>();

        if (filterContext.HttpContext.Request.Cookies.AllKeys.Contains("_browserWindowSize"))
        {
            var browserWindowSize = filterContext.HttpContext.Request.Cookies.Get("_browserWindowSize").Value.Split(',');
            currentRequestService.browserWindowWidth = int.Parse(browserWindowSize[0]);
            currentRequestService.browserWindowHeight = int.Parse(browserWindowSize[1]);
        }

    }
}

Using jQuery how to get click coordinates on the target element

Try this:

jQuery(document).ready(function(){
   $("#special").click(function(e){
      $('#status2').html(e.pageX +', '+ e.pageY);
   }); 
})

Here you can find more info with DEMO

Click through div to underlying elements

An easier way would be to inline the transparent background image using Data URIs as follows:

.click-through {
    pointer-events: none;
    background: url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7);
}

How would you do a "not in" query with LINQ?

You want the Except operator.

var answer = list1.Except(list2);

Better explanation here: https://docs.microsoft.com/archive/blogs/charlie/linq-farm-more-on-set-operators

NOTE: This technique works best for primitive types only, since you have to implement an IEqualityComparer to use the Except method with complex types.

Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

Probably you didn't add your room class to child RoomDatabase child class in @Database(entities = {your_classes})

Check if value exists in dataTable?

You can use LINQ-to-DataSet with Enumerable.Any:

String author = "John Grisham";
bool contains = tbl.AsEnumerable().Any(row => author == row.Field<String>("Author"));

Another approach is to use DataTable.Select:

DataRow[] foundAuthors = tbl.Select("Author = '" + searchAuthor + "'");
if(foundAuthors.Length != 0)
{
    // do something...
}

Q: what if we do not know the columns Headers and we want to find if any cell value PEPSI exist in any rows'c columns? I can loop it all to find out but is there a better way? –

Yes, you can use this query:

DataColumn[] columns = tbl.Columns.Cast<DataColumn>().ToArray();
bool anyFieldContainsPepsi = tbl.AsEnumerable()
    .Any(row => columns.Any(col => row[col].ToString() == "PEPSI"));

Numbering rows within groups in a data frame

Another dplyr possibility could be:

df %>%
 group_by(cat) %>%
 mutate(num = 1:n())

   cat      val   num
   <fct>  <dbl> <int>
 1 aaa   0.0564     1
 2 aaa   0.258      2
 3 aaa   0.308      3
 4 aaa   0.469      4
 5 aaa   0.552      5
 6 bbb   0.170      1
 7 bbb   0.370      2
 8 bbb   0.484      3
 9 bbb   0.547      4
10 bbb   0.812      5
11 ccc   0.280      1
12 ccc   0.398      2
13 ccc   0.625      3
14 ccc   0.763      4
15 ccc   0.882      5

How do I list all the columns in a table?

MS SQL Server:

sp_columns [tablename]

Search an array for matching attribute

you can also use the Array.find feature of es6. the doc is here

return restaurants.find(item => {
   return item.restaurant.food == 'chicken'
})

List Git commits not pushed to the origin yet

how to determine if a commit with particular hash have been pushed to the origin already?

# list remote branches that contain $commit
git branch -r --contains $commit

Best Free Text Editor Supporting *More Than* 4GB Files?

Textpad also works well at opening files that size. I have done it many times when having to deal with extremely large log files in the 3-5gb range. Also, using grep to pull out the worthwhile lines and then look at those works great.

How to add elements of a Java8 stream into an existing List

You just have to refer your original list to be the one that the Collectors.toList() returns.

Here's a demo:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Reference {

  public static void main(String[] args) {
    List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
    System.out.println(list);

    // Just collect even numbers and start referring the new list as the original one.
    list = list.stream()
               .filter(n -> n % 2 == 0)
               .collect(Collectors.toList());
    System.out.println(list);
  }
}

And here's how you can add the newly created elements to your original list in just one line.

List<Integer> list = ...;
// add even numbers from the list to the list again.
list.addAll(list.stream()
                .filter(n -> n % 2 == 0)
                .collect(Collectors.toList())
);

That's what this Functional Programming Paradigm provides.

Retrieve column values of the selected row of a multicolumn Access listbox

Use listboxControl.Column(intColumn,intRow). Both Column and Row are zero-based.

Setting the MySQL root user password on OS X

  1. Stop the mysqld server.

    • Mac OSX: System Preferences > MySQL > Stop MySQL Server
    • Linux (From Terminal): sudo systemctl stop mysqld.service
  2. Start the server in safe mode with privilege bypass

    • From Terminal: sudo /usr/local/mysql/bin/mysqld_safe --skip-grant-tables
  3. In a new terminal window:

    • sudo /usr/local/mysql/bin/mysql -u root
  4. This will open the mysql command line. From here enter:

    • UPDATE mysql.user SET authentication_string=PASSWORD('NewPassword') WHERE User='root';

    • FLUSH PRIVILEGES;

    • quit

  5. Stop the mysqld server again and restart it in normal mode.

    • Mac OSX (From Terminal): sudo /usr/local/mysql/support-files/mysql.server restart
    • Linux Terminal: sudo systemctl restart mysqld

Conditionally formatting cells if their value equals any value of another column

Another simpler solution is to use this formula in the conditional formatting (apply to column A):

=COUNTIF(B:B,A1)

Regards!

alter the size of column in table containing data

Case 1 : Yes, this works fine.

Case 2 : This will fail with the error ORA-01441 : cannot decrease column length because some value is too big.

Share and enjoy.

Java double comparison epsilon

While I agree with the idea that double is bad for money, still the idea of comparing doubles has interest. In particular the suggested use of epsilon is only suited to numbers in a specific range. Here is a more general use of an epsilon, relative to the ratio of the two numbers (test for 0 is omitted):

boolean equal(double d1, double d2) {
  double d = d1 / d2;
  return (Math.abs(d - 1.0) < 0.001);
}

Android - default value in editText

You can use EditText.setText(...) to set the current text of an EditText field.

Example:

yourEditText.setText(currentUserName);

How do I sort a VARCHAR column in SQL server that contains numbers?

select
  Field1, Field2...
from
  Table1
order by
  isnumeric(Field1) desc,
  case when isnumeric(Field1) = 1 then cast(Field1 as int) else null end,
  Field1

This will return values in the order you gave in your question.

Performance won't be too great with all that casting going on, so another approach is to add another column to the table in which you store an integer copy of the data and then sort by that first and then the column in question. This will obviously require some changes to the logic that inserts or updates data in the table, to populate both columns. Either that, or put a trigger on the table to populate the second column whenever data is inserted or updated.

Java Serializable Object to Byte Array

In case you want a nice no dependencies copy-paste solution. Grab the code below.

Example

MyObject myObject = ...

byte[] bytes = SerializeUtils.serialize(myObject);
myObject = SerializeUtils.deserialize(bytes);

Source

import java.io.*;

public class SerializeUtils {

    public static byte[] serialize(Serializable value) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        try(ObjectOutputStream outputStream = new ObjectOutputStream(out)) {
            outputStream.writeObject(value);
        }

        return out.toByteArray();
    }

    public static <T extends Serializable> T deserialize(byte[] data) throws IOException, ClassNotFoundException {
        try(ByteArrayInputStream bis = new ByteArrayInputStream(data)) {
            //noinspection unchecked
            return (T) new ObjectInputStream(bis).readObject();
        }
    }
}

How to make custom dialog with rounded corners in android

You can use the shape for the background as-

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@android:color/transparent"/>
<corners android:radius="10dp" />
<padding android:left="10dp" android:right="10dp"/>
</shape>

Have a look on this for the details.

Is there a way to "limit" the result with ELOQUENT ORM of Laravel?

We can use LIMIT like bellow:

Model::take(20)->get();

MongoDB Aggregation: How to get total records count?

I did it this way:

db.collection.aggregate([
     { $match : { score : { $gt : 70, $lte : 90 } } },
     { $group: { _id: null, count: { $sum: 1 } } }
] ).map(function(record, index){
        print(index);
 });

The aggregate will return the array so just loop it and get the final index .

And other way of doing it is:

var count = 0 ;
db.collection.aggregate([
{ $match : { score : { $gt : 70, $lte : 90 } } },
{ $group: { _id: null, count: { $sum: 1 } } }
] ).map(function(record, index){
        count++
 }); 
print(count);

Python PDF library

Reportlab. There is an open source version, and a paid version which adds the Report Markup Language (an alternative method of defining your document).

How to print last two columns using awk

Please try this out to take into account all possible scenarios:

awk '{print $(NF-1)"\t"$NF}'  file

or

awk 'BEGIN{OFS="\t"}' file

or

awk '{print $(NF-1), $NF} {print $(NF-1), $NF}' file

IF EXISTS, THEN SELECT ELSE INSERT AND THEN SELECT

It sounds like your table has no key. You should be able to simply try the INSERT: if it’s a duplicate then the key constraint will bite and the INSERT will fail. No worries: you just need to ensure the application doesn't see/ignores the error. When you say 'primary key' you presumably mean IDENTITY value. That's all very well but you also need a key constraint (e.g. UNIQUE) on your natural key.

Also, I wonder whether your procedure is doing too much. Consider having separate procedures for 'create' and 'read' actions respectively.

How to make correct date format when writing data to Excel

Old question but still relevant. I've generated a dictionary that gets the appropriate datetime format for each region, here is the helper class I generated:

https://github.com/anakic/ExcelDateTimeFormatHelper/blob/master/FormatHelper.cs

FWIW this is how I went about it:

  1. opened excel, manually entered a datetime into the first cell of a workbook
  2. opened the regions dialog in control panel
  3. used Spy to find out the HWND's of the regions combobox and the apply button so I can use SetForegroundWindow and SendKey to change the region (couldn't find how to change region through the Windows API)
  4. iterated through all regions and for each region asked Excel for the NumberFormat of the cell that contained the date, saved this data to into a file

How to get the filename without the extension from a path in Python?

On Windows system I used drivername prefix as well, like:

>>> s = 'c:\\temp\\akarmi.txt'
>>> print(os.path.splitext(s)[0])
c:\temp\akarmi

So because I do not need drive letter or directory name, I use:

>>> print(os.path.splitext(os.path.basename(s))[0])
akarmi

Assigning the return value of new by reference is deprecated

Upgrade your pear/MDB2 from console:

# pear upgrade MDB2-beta
# pear upgrade MDB2_Driver_Mysql-beta

Problem solved at version 2.5.0b3

Gradle version 2.2 is required. Current version is 2.10

The android studio and Gradle version looks like very bad managed. And there's tons of version in-capability issues. And the error message is mostly clueless. For this particular issue. The closest answer is from "Jitendra Singh". Change the version to:

 classpath 'com.android.tools.build:gradle:2.0.0'

But in my case: Android studio 2.2 RC, I still get another error:

Could not find matching constructor for: com.android.build.gradle.internal.LibraryTaskManager(org.gradle.api.internal.project.DefaultProject_Decorated, com.android.builder.core.AndroidBuilder, android.databinding.tool.DataBindingBuilder, com.android.build.gradle.LibraryExtension_Decorated, com.android.build.gradle.internal.SdkHandler, com.android.build.gradle.internal.DependencyManager, org.gradle.tooling.provider.model.internal.DefaultToolingModelBuilderRegistry)

So I went to the maven central to find the latest com.android.tools.build:gradle version which is 2.1.3 for now. So after change to

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.3'
    }
}

Solved my problem eventually.

Maven: How do I activate a profile from command line?

I have encountered this problem and i solved mentioned problem by adding -DprofileIdEnabled=true parameter while running mvn cli command.

Please run your mvn cli command as : mvn clean install -Pdev1 -DprofileIdEnabled=true.

In addition to this solution, you don't need to remove activeByDefault settings in your POM mentioned as previouses answer.

I hope this answer solve your problem.

RecyclerView onClick

Here is a strategy that gives a result similar to the ListView implementation in that you can define the listener in the Activity or Fragment level instead of the Adapter or ViewHolder level. It also defines some abstract classes that take care of a lot of the boilerplate work of adapters and holders.

Abstract Classes

First, define an abstract Holder that extends RecyclerView.ViewHolder and defines a generic data type, T, used to bind data to the views. The bindViews method will be implemented by a subclass to map data to the views.

public abstract class Holder<T> extends RecyclerView.ViewHolder {
    T data;

    public Holder(View itemView) {
        super(itemView);
    }

    public void bindData(T data){
        this.data = data;
        bindViews(data);
    }

    abstract protected void bindViews(T data);
}

Also, create an abstract Adapter that extends RecyclerView.Adapter<Holder<T>>. This defines 2 of the 3 interface methods, and a subclass will need to implement the last, onViewHolderCreated method.

public abstract class Adapter<T> extends RecyclerView.Adapter<Holder<T>> {
    List<T> list = new ArrayList<>();

    @Override
    public void onBindViewHolder(Holder<T> holder, int position) {
        holder.bindData(list.get(position));
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public T getItem(int adapterPosition){
        return list.get(adapterPosition);
    }
}

Concrete Classes

Now create a new concrete class that extends Holder. This method only has to define the Views and handle the binding. Here I'm using the ButterKnife library, but feel free to use itemView.findViewById(...) methods instead.

public class PersonHolder extends Holder<Person>{
    @Bind(R.id.firstname) TextView firstname;
    @Bind(R.id.lastname) TextView lastname;

    public PersonHolder(View view){
        super(view);
        ButterKnife.bind(this, view);
    }

    @Override
    protected void bindViews(Person person) {
        firstname.setText(person.firstname);
        lastname.setText(person.lastname);
    }
}

Finally, in your Activity or Fragment class that holds the RecyclerView you would have this code:

// Create adapter, this happens in parent Activity or Fragment of RecyclerView
adapter = new Adapter<Person>(){
    @Override
    public PersonHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.layout_person_view, parent, false);

        PersonHolder holder = new PersonHolder(v);
        v.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                int itemPos = holder.getAdapterPosition();
                Person person = getItem(itemPos);

                // do something with person
                EventBus.getDefault().postSticky(new PersonClickedEvent(itemPos, person));
            }
        });

        return holder;
    }
};

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed

This is due to using obsolete mysql-connection-java version, your MySQl is updated but not your MySQL jdbc Driver, you can update your connection jar from the official site Official MySQL Connector site. Good Luck.

How to delete/truncate tables from Hadoop-Hive?

To Truncate:

hive -e "TRUNCATE TABLE IF EXISTS $tablename"

To Drop:

hive -e "Drop TABLE IF EXISTS $tablename"

Select all columns except one in MySQL?

Select * is a SQL antipattern. It should not be used in production code for many reasons including:

It takes a tiny bit longer to process. When things are run millions of times, those tiny bits can matter. A slow database where the slowness is caused by this type of sloppy coding throughout is the hardest kind to performance tune.

It means you are probably sending more data than you need which causes both server and network bottlenecks. If you have an inner join, the chances of sending more data than you need are 100%.

It causes maintenance problems especially when you have added new columns that you do not want seen everywhere. Further if you have a new column, you may need to do something to the interface to determine what to do with that column.

It can break views (I know this is true in SQl server, it may or may not be true in mysql).

If someone is silly enough to rebuild the tables with the columns in a differnt order (which you shouldn't do but it happens all teh time), all sorts of code can break. Espcially code for an insert for example where suddenly you are putting the city into the address_3 field becasue without specifying, the database can only go on the order of the columns. This is bad enough when the data types change but worse when the swapped columns have the same datatype becasue you can go for sometime inserting bad data that is a mess to clean up. You need to care about data integrity.

If it is used in an insert, it will break the insert if a new column is added in one table but not the other.

It might break triggers. Trigger problems can be difficult to diagnose.

Add up all this against the time it take to add in the column names (heck you may even have an interface that allows you to drag over the columns names (I know I do in SQL Server, I'd bet there is some way to do this is some tool you use to write mysql queries.) Let's see, "I can cause maintenance problems, I can cause performance problems and I can cause data integrity problems, but hey I saved five minutes of dev time." Really just put in the specific columns you want.

I also suggest you read this book: http://www.amazon.com/SQL-Antipatterns-Programming-Pragmatic-Programmers-ebook/dp/B00A376BB2/ref=sr_1_1?s=digital-text&ie=UTF8&qid=1389896688&sr=1-1&keywords=sql+antipatterns

Visual Studio Expand/Collapse keyboard shortcuts

Go to Tools->Options->Text Editor->c#->Advanced and uncheck the first checkbox Enter outlining mode when files open.

This will solve this problem forever

Can I make a <button> not submit a form?

  <form class="form-horizontal" method="post">
        <div class="control-group">

            <input type="text" name="subject_code" id="inputEmail" placeholder="Subject Code">
        </div>
        <div class="control-group">
            <input type="text" class="span8" name="title" id="inputPassword" placeholder="Subject Title" required>
        </div>
        <div class="control-group">
            <input type="text" class="span1" name="unit" id="inputPassword" required>
        </div>
            <div class="control-group">
            <label class="control-label" for="inputPassword">Semester</label>
            <div class="controls">
                <select name="semester">
                    <option></option>
                    <option>1st</option>
                    <option>2nd</option>
                </select>
            </div>
        </div>

        <div class="control-group">
            <label class="control-label" for="inputPassword">Deskripsi</label>
            <div class="controls">
                    <textarea name="description" id="ckeditor_full"></textarea>
 <script>CKEDITOR.replace('ckeditor_full');</script>
            </div>
        </div>



        <div class="control-group">
        <div class="controls">

        <button name="save" type="submit" class="btn btn-info"><i class="icon-save"></i> Simpan</button>
        </div>
        </div>
        </form>

        <?php
        if (isset($_POST['save'])){
        $subject_code = $_POST['subject_code'];
        $title = $_POST['title'];
        $unit = $_POST['unit'];
        $description = $_POST['description'];
        $semester = $_POST['semester'];


        $query = mysql_query("select * from subject where subject_code = '$subject_code' ")or die(mysql_error());
        $count = mysql_num_rows($query);

        if ($count > 0){ ?>
        <script>
        alert('Data Sudah Ada');
        </script>
        <?php
        }else{
        mysql_query("insert into subject (subject_code,subject_title,description,unit,semester) values('$subject_code','$title','$description','$unit','$semester')")or die(mysql_error());


        mysql_query("insert into activity_log (date,username,action) values(NOW(),'$user_username','Add Subject $subject_code')")or die(mysql_error());


        ?>
        <script>
        window.location = "subjects.php";
        </script>
        <?php
        }
        }

        ?>

Strtotime() doesn't work with dd/mm/YYYY format

fastest should probably be

false!== ($date !== $date=preg_replace(';[0-2]{2}/[0-2]{2}/[0-2]{2};','$3-$2-$1',$date))

this will return false if the format does not look like the proper one, but it wont-check wether the date is valid

Is there a Python equivalent of the C# null-coalescing operator?

I realize this is answered, but there is another option when you're dealing with objects.

If you have an object that might be:

{
   name: {
      first: "John",
      last: "Doe"
   }
}

You can use:

obj.get(property_name, value_if_null)

Like:

obj.get("name", {}).get("first", "Name is missing") 

By adding {} as the default value, if "name" is missing, an empty object is returned and passed through to the next get. This is similar to null-safe-navigation in C#, which would be like obj?.name?.first.

How to convert 1 to true or 0 to false upon model fetch

Here's another option that's longer but may be more readable:

Boolean(Number("0")); // false
Boolean(Number("1")); // true

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

json.loads() takes a JSON encoded string, not a filename. You want to use json.load() (no s) instead and pass in an open file object:

with open('/Users/JoshuaHawley/clean1.txt') as jsonfile:
    data = json.load(jsonfile)

The open() command produces a file object that json.load() can then read from, to produce the decoded Python object for you. The with statement ensures that the file is closed again when done.

The alternative is to read the data yourself and then pass it into json.loads().

mysqli_fetch_array while loop columns

Try this...

while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

Change Bootstrap tooltip color

It will change the color of the tooltip in bootstrap4 you can use bottom, left, right to add CSS for respective in place of top in .bs-tooltip-top

.tooltip-inner {
background-color: #00acd6 !important;
color: #fff;
}
.bs-tooltip-top .arrow::before, .bs-tooltip-auto[x-placement^="top"] 
.arrow::before {
border-top-color: #00acd6;
}

Android - set TextView TextStyle programmatically?

Since setTextAppearance(resId) is only available for API 23 and above, use:

TextViewCompat.setTextAppearance(textViewGoesHere, resId)

This method is internally implemented as follows:

public static void setTextAppearance(@NonNull TextView textView, @StyleRes int resId) {
    if (Build.VERSION.SDK_INT >= 23) {
        textView.setTextAppearance(resId);
    } else {
        textView.setTextAppearance(textView.getContext(), resId);
    }
}

How can I indent multiple lines in Xcode?

Another way to quickly reformat indenting is a quick cut and paste. ?+x and ?+v. I often find it faster than ?+[ or ?+] as you can do it with one hand (versus two) and it will reformat to the correct indent level in one shot.

Django check for any exists for a query

As of Django 1.2, you can use exists():

https://docs.djangoproject.com/en/dev/ref/models/querysets/#exists

if some_queryset.filter(pk=entity_id).exists():
    print("Entry contained in queryset")

How to use System.Net.HttpClient to post a complex type?

Make a service call like this:

public async void SaveActivationCode(ActivationCodes objAC)
{
    var client = new HttpClient();
    client.BaseAddress = new Uri(baseAddress);
    HttpResponseMessage response = await client.PutAsJsonAsync(serviceAddress + "/SaveActivationCode" + "?apiKey=445-65-1216", objAC);
} 

And Service method like this:

public HttpResponseMessage PutSaveActivationCode(ActivationCodes objAC)
{
}

PutAsJsonAsync takes care of Serialization and deserialization over the network

How is the default max Java heap size determined?

The Xms and Xmx are flag of Java virtual machine (JVM):

  • Xms: initial and minimum JVM heap size
    • Format: -Xms<size>[g|G|m|M|k|K]
    • Default Size:
      • -server mode: 25% of free physical memory, >=8MB and <= 64MB
      • -client mode: 25% of free physical memory, >=8MB and <= 16MB
    • Typical Size:
      • -Xms128M
      • -Xms256M
      • -Xms512M
    • Function/Effect:
      • -> JVM start with allocate Xms size memory
  • Xmx: maximum JVM heap size
    • Format: -Xmx<size>[g|G|m|M|k|K]
    • Default Size:
      • <= R27.2
        • Windows: 75% of total physical memory up to 1GB
        • Linux/Solaris: 50% of available physical memory up to 1GB
      • >= R27.3
        • Windows X64: 75% of total physical memory up to 2GB
        • Linux/Solaris X64: 50% of available physical memory up to 2GB
        • Windows x86: 75% of total physical memory up to 1GB
        • Linux/Solaris X86: 50% of available physical memory up to 1GB
    • Typical Size:
      • -Xmx1g
      • -Xmx2084M
      • -Xmx4g
      • -Xmx6g
      • -Xmx8g
    • Function/Effect:
      • -> JVM allow use maxium of Xmx size memory
        • when exceed Xmx, will java.lang.OutOfMemoryError
          • How to fix OutOfMemoryError ?
            • exceed Xmx value
              • eg: from -Xmx4g to -Xmx8g

More detail

see official doc: -X Command-line Options

Calculate rolling / moving average in C++

I used a deque... seems to work for me. This example has a vector, but you could skip that aspect and simply add them to deque.

#include <deque>

template <typename T>
double mov_avg(vector<T> vec, int len){
  deque<T> dq = {};
  for(auto i = 0;i < vec.size();i++){
    if(i < len){
      dq.push_back(vec[i]);
    }
    else {
      dq.pop_front();
      dq.push_back(vec[i]);
    }
  }
  double cs = 0;
  for(auto i : dq){
    cs += i;
  }
  return cs / len;
}



//Skip the vector portion, track the input number (or size of deque), and the value.


  double len = 10;
  double val; //Accept as input
  double instance; //Increment each time input accepted.

  deque<double> dq;
  if(instance < len){
      dq.push_back(val);
  }
  else {
      dq.pop_front();
      dq.push_back(val);
    }
  }
  double cs = 0;
  for(auto i : dq){
    cs += i;
  }
  double rolling_avg = cs / len;

//To simplify further -- add values to this, then simply average the deque.

 int MAX_DQ = 3;
 void add_to_dq(deque<double> &dq, double value){
    if(dq.size() < MAX_DQ){
      dq.push_back(value);
    }else {
      dq.pop_front();
      dq.push_back(value);
    }
  }
 

Another sort of hack I use occasionally is using mod to overwrite values in a vector.

  vector<int> test_mod = {0,0,0,0,0};
  int write = 0;
  int LEN = 5;
  
  int instance = 0; //Filler for N -- of Nth Number added.
  int value = 0; //Filler for new number.

  write = instance % LEN;
  test_mod[write] = value;
  //Will write to 0, 1, 2, 3, 4, 0, 1, 2, 3, ...
  //Then average it for MA.

  //To test it...
  int write_idx = 0;
  int len = 5;
  int new_value;
  for(auto i=0;i<100;i++){
      cin >> new_value;
      write_idx = i % len;
      test_mod[write_idx] = new_value;

This last (hack) has no buckets, buffers, loops, nothing. Simply a vector that's overwritten. And it's 100% accurate (for avg / values in vector). Proper order is rarely maintained, as it starts rewriting backwards (at 0), so 5th index would be at 0 in example {5,1,2,3,4}, etc.

How to list active / open connections in Oracle?

When I'd like to view incoming connections from our application servers to the database I use the following command:

SELECT username FROM v$session 
WHERE username IS NOT NULL 
ORDER BY username ASC;

Simple, but effective.

jquery to loop through table rows and cells, where checkob is checked, concatenate

UPDATED

I've updated your demo: http://jsfiddle.net/terryyounghk/QS56z/18/

Also, I've changed two ^= to *=. See http://api.jquery.com/category/selectors/

And note the :checked selector. See http://api.jquery.com/checked-selector/

function createcodes() {

    //run through each row
    $('.authors-list tr').each(function (i, row) {

        // reference all the stuff you need first
        var $row = $(row),
            $family = $row.find('input[name*="family"]'),
            $grade = $row.find('input[name*="grade"]'),
            $checkedBoxes = $row.find('input:checked');

        $checkedBoxes.each(function (i, checkbox) {
            // assuming you layout the elements this way, 
            // we'll take advantage of .next()
            var $checkbox = $(checkbox),
                $line = $checkbox.next(),
                $size = $line.next();

            $line.val(
                $family.val() + ' ' + $size.val() + ', ' + $grade.val()
            );

        });

    });
}

How to write both h1 and h2 in the same line?

h1 and h2 are native display: block elements.

Make them display: inline so they behave like normal text.

You should also reset the default padding and margin that the elements have.

Create a file from a ByteArrayOutputStream

You can do it with using a FileOutputStream and the writeTo method.

ByteArrayOutputStream byteArrayOutputStream = getByteStreamMethod();
try(OutputStream outputStream = new FileOutputStream("thefilename")) {
    byteArrayOutputStream.writeTo(outputStream);
}

Source: "Creating a file from ByteArrayOutputStream in Java." on Code Inventions

Read all files in a folder and apply a function to each data frame

usually i don't use for loop in R, but here is my solution using for loops and two packages : plyr and dostats

plyr is on cran and you can download dostats on https://github.com/halpo/dostats (may be using install_github from Hadley devtools package)

Assuming that i have your first two data.frame (Df.1 and Df.2) in csv files, you can do something like this.

require(plyr)
require(dostats)

files <- list.files(pattern = ".csv")


for (i in seq_along(files)) {

    assign(paste("Df", i, sep = "."), read.csv(files[i]))

    assign(paste(paste("Df", i, sep = ""), "summary", sep = "."), 
           ldply(get(paste("Df", i, sep = ".")), dostats, sum, min, mean, median, max))

}

Here is the output

R> Df1.summary
  .id sum min   mean median max
1   A  34   4 5.6667    5.5   8
2   B  22   1 3.6667    3.0   9
R> Df2.summary
  .id sum min   mean median max
1   A  21   1 3.5000    3.5   6
2   B  16   1 2.6667    2.5   5

Configuring angularjs with eclipse IDE

Since these previous answers above, there is now a release of an Eclipse Plugin to assist with development using AngularJS:

https://marketplace.eclipse.org/content/angularjs-eclipse https://github.com/angelozerr/angularjs-eclipse/wiki/Installation---Update-Site (take a look around the other Wiki pages for information on features)

The release at the time of the answer is 0.1.0.

Please also checkout JSDT (http://www.eclipse.org/webtools/jsdt/) and also Eclipse VJET (http://eclipse.org/vjet/). The VJET project appears to be an attempt to provide better feature sets to the editor without being encumbered by the JSDT project (open source politics at play I guess).

How do I use setsockopt(SO_REUSEADDR)?

After :

sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) 
    error("ERROR opening socket");

You can add (with standard C99 compound literal support) :

if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &(int){1}, sizeof(int)) < 0)
    error("setsockopt(SO_REUSEADDR) failed");

Or :

int enable = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0)
    error("setsockopt(SO_REUSEADDR) failed");

How to get progress from XMLHttpRequest

One of the most promising approaches seems to be opening a second communication channel back to the server to ask it how much of the transfer has been completed.

Removing viewcontrollers from navigation stack

Use this

if let navVCsCount = navigationController?.viewControllers.count {
    navigationController?.viewControllers.removeSubrange(Range(2..<navVCsCount - 1))
}

It will take care of ViewControllers of navigationController. viewControllers and also a navigationItems stacked in navigationBar.

Note: Be sure to call it at least after viewDidAppear

Android TextView Justify Text

FILL_HORIZONTAL is equivalent to CENTER_HORIZONTAL. You can see this code snippet in textview's source code:

case Gravity.CENTER_HORIZONTAL:
case Gravity.FILL_HORIZONTAL:
    return (mLayout.getLineWidth(0) - ((mRight - mLeft) -
            getCompoundPaddingLeft() - getCompoundPaddingRight())) /
            getHorizontalFadingEdgeLength();

How to set selected value from Combobox?

To set value in the ComboBox

cmbEmployeeStatus.Text="Something";

test attribute in JSTL <c:if> tag

<%=%> by itself will be sent to the output, in the context of the JSTL it will be evaluated to a string

In Bash, how do I add a string after each line in a file?

I prefer echo. using pure bash:

cat file | while read line; do echo ${line}$string; done

Boolean operators && and ||

The answer about "short-circuiting" is potentially misleading, but has some truth (see below). In the R/S language, && and || only evaluate the first element in the first argument. All other elements in a vector or list are ignored regardless of the first ones value. Those operators are designed to work with the if (cond) {} else{} construction and to direct program control rather than construct new vectors.. The & and the | operators are designed to work on vectors, so they will be applied "in parallel", so to speak, along the length of the longest argument. Both vectors need to be evaluated before the comparisons are made. If the vectors are not the same length, then recycling of the shorter argument is performed.

When the arguments to && or || are evaluated, there is "short-circuiting" in that if any of the values in succession from left to right are determinative, then evaluations cease and the final value is returned.

> if( print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 2
> if(FALSE && print(1) ) {print(2)} else {print(3)} # `print(1)` not evaluated
[1] 3
> if(TRUE && print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 2
> if(TRUE && !print(1) ) {print(2)} else {print(3)}
[1] 1
[1] 3
> if(FALSE && !print(1) ) {print(2)} else {print(3)}
[1] 3

The advantage of short-circuiting will only appear when the arguments take a long time to evaluate. That will typically occur when the arguments are functions that either process larger objects or have mathematical operations that are more complex.

How to get on scroll events?

Alternative to @HostListener and scroll output on the element I would suggest using fromEvent from RxJS since you can chain it with filter() and distinctUntilChanges() and can easily skip flood of potentially redundant events (and change detections).

Here is a simple example:

// {static: true} can be omitted if you don't need this element/listener in ngOnInit
@ViewChild('elementId', {static: true}) el: ElementRef;

// ...

fromEvent(this.el.nativeElement, 'scroll')
  .pipe(
    // Is elementId scrolled for more than 50 from top?
    map((e: Event) => (e.srcElement as Element).scrollTop > 50),
    // Dispatch change only if result from map above is different from previous result
    distinctUntilChanged());

How to write macro for Notepad++?

Actually, the shortcuts.xml file does not store user-generated macros and no obvious candidates contain this info. These instructions are out of date.

Contrary to various websites' tips, storing user-generated macros isn't enabled for v.5.4.2. That XML file is there, but your macro does not get stored it in.

I'm guessing it's a bug that'll be fixed by the next version.

Center fixed div with dynamic width (CSS)

<div id="container">
    <div id="some_kind_of_popup">
        center me
    </div>
</div>

You'd need to wrap it in a container. here's the css

#container{
    position: fixed;
    top: 100px;
    width: 100%;
    text-align: center;
}
#some_kind_of_popup{
    display:inline-block;
    width: 90%;
    max-width: 900px;  
    min-height: 300px;  
}

Linux command-line call not returning what it should from os.system?

For your requirement, Popen function of subprocess python module is the answer. For example,

import subprocess
..
process = subprocess.Popen("ps -p 2993 -o time --no-headers", stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
print stdout

Escaping ampersand in URL

If you can't use any libraries to encode the value, http://www.urlencoder.org/ or http://www.urlencode-urldecode.com/ or ...

Just enter your value "M&M", not the full URL ;-)

"R cannot be resolved to a variable"?

Check if the package name in the AndroidManifest.xml file is the same than the package name of your java class.

Eg. AndroidManifest.xml

 package="com.example.de.vogella.android.widget.example"

In your class MyWidgetProvider.java

package com.example.de.vogella.android.widget.example;

It was the cause of my error in this example.

How to play only the audio of a Youtube video using HTML 5?

VIDEO_ID with actual ID of your YouTube video.

<div data-video="VIDEO_ID"  
        data-autoplay="0"         
        data-loop="1"             
        id="youtube-audio">
 </div>

 <script src="https://www.youtube.com/iframe_api"></script>
 <script src="https://cdn.rawgit.com/labnol/files/master/yt.js"></script>

Convert a hexadecimal string to an integer efficiently in C?

Try this:

#include <stdio.h>
int main()
{
    char s[] = "fffffffe";
    int x;
    sscanf(s, "%x", &x);
    printf("%u\n", x);
}

What is the recommended project structure for spring boot rest projects?

Please use Spring Tool Suite (Eclipse-based development environment that is customized for developing Spring applications).
Create a Spring Starter Project, it will create the directory structure for you with the spring boot maven dependencies.

Still Reachable Leak detected by Valgrind

There is more than one way to define "memory leak". In particular, there are two primary definitions of "memory leak" that are in common usage among programmers.

The first commonly used definition of "memory leak" is, "Memory was allocated and was not subsequently freed before the program terminated." However, many programmers (rightly) argue that certain types of memory leaks that fit this definition don't actually pose any sort of problem, and therefore should not be considered true "memory leaks".

An arguably stricter (and more useful) definition of "memory leak" is, "Memory was allocated and cannot be subsequently freed because the program no longer has any pointers to the allocated memory block." In other words, you cannot free memory that you no longer have any pointers to. Such memory is therefore a "memory leak". Valgrind uses this stricter definition of the term "memory leak". This is the type of leak which can potentially cause significant heap depletion, especially for long lived processes.

The "still reachable" category within Valgrind's leak report refers to allocations that fit only the first definition of "memory leak". These blocks were not freed, but they could have been freed (if the programmer had wanted to) because the program still was keeping track of pointers to those memory blocks.

In general, there is no need to worry about "still reachable" blocks. They don't pose the sort of problem that true memory leaks can cause. For instance, there is normally no potential for heap exhaustion from "still reachable" blocks. This is because these blocks are usually one-time allocations, references to which are kept throughout the duration of the process's lifetime. While you could go through and ensure that your program frees all allocated memory, there is usually no practical benefit from doing so since the operating system will reclaim all of the process's memory after the process terminates, anyway. Contrast this with true memory leaks which, if left unfixed, could cause a process to run out of memory if left running long enough, or will simply cause a process to consume far more memory than is necessary.

Probably the only time it is useful to ensure that all allocations have matching "frees" is if your leak detection tools cannot tell which blocks are "still reachable" (but Valgrind can do this) or if your operating system doesn't reclaim all of a terminating process's memory (all platforms which Valgrind has been ported to do this).

How to move a git repository into another directory and make that directory a git repository?

To do this without any headache:

  1. Check out what's the current branch in the gitrepo1 with git status, let's say branch "development".
  2. Change directory to the newrepo, then git clone the project from repository.
  3. Switch branch in newrepo to the previous one: git checkout development.
  4. Syncronize newrepo with the older one, gitrepo1 using rsync, excluding .git folder: rsync -azv --exclude '.git' gitrepo1 newrepo/gitrepo1. You don't have to do this with rsync of course, but it does it so smooth.

The benefit of this approach: you are good to continue exactly where you left off: your older branch, unstaged changes, etc.

What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?

Process GET parameters

The <f:viewParam> manages the setting, conversion and validation of GET parameters. It's like the <h:inputText>, but then for GET parameters.

The following example

<f:metadata>
    <f:viewParam name="id" value="#{bean.id}" />
</f:metadata>

does basically the following:

  • Get the request parameter value by name id.
  • Convert and validate it if necessary (you can use required, validator and converter attributes and nest a <f:converter> and <f:validator> in it like as with <h:inputText>)
  • If conversion and validation succeeds, then set it as a bean property represented by #{bean.id} value, or if the value attribute is absent, then set it as request attribtue on name id so that it's available by #{id} in the view.

So when you open the page as foo.xhtml?id=10 then the parameter value 10 get set in the bean this way, right before the view is rendered.

As to validation, the following example sets the param to required="true" and allows only values between 10 and 20. Any validation failure will result in a message being displayed.

<f:metadata>
    <f:viewParam id="id" name="id" value="#{bean.id}" required="true">
        <f:validateLongRange minimum="10" maximum="20" />
    </f:viewParam>
</f:metadata>
<h:message for="id" />

Performing business action on GET parameters

You can use the <f:viewAction> for this.

<f:metadata>
    <f:viewParam id="id" name="id" value="#{bean.id}" required="true">
        <f:validateLongRange minimum="10" maximum="20" />
    </f:viewParam>
    <f:viewAction action="#{bean.onload}" />
</f:metadata>
<h:message for="id" />

with

public void onload() {
    // ...
}

The <f:viewAction> is however new since JSF 2.2 (the <f:viewParam> already exists since JSF 2.0). If you can't upgrade, then your best bet is using <f:event> instead.

<f:event type="preRenderView" listener="#{bean.onload}" />

This is however invoked on every request. You need to explicitly check if the request isn't a postback:

public void onload() {
    if (!FacesContext.getCurrentInstance().isPostback()) {
        // ...
    }
}

When you would like to skip "Conversion/Validation failed" cases as well, then do as follows:

public void onload() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    if (!facesContext.isPostback() && !facesContext.isValidationFailed()) {
        // ...
    }
}

Using <f:event> this way is in essence a workaround/hack, that's exactly why the <f:viewAction> was introduced in JSF 2.2.


Pass view parameters to next view

You can "pass-through" the view parameters in navigation links by setting includeViewParams attribute to true or by adding includeViewParams=true request parameter.

<h:link outcome="next" includeViewParams="true">
<!-- Or -->
<h:link outcome="next?includeViewParams=true">

which generates with the above <f:metadata> example basically the following link

<a href="next.xhtml?id=10">

with the original parameter value.

This approach only requires that next.xhtml has also a <f:viewParam> on the very same parameter, otherwise it won't be passed through.


Use GET forms in JSF

The <f:viewParam> can also be used in combination with "plain HTML" GET forms.

<f:metadata>
    <f:viewParam id="query" name="query" value="#{bean.query}" />
    <f:viewAction action="#{bean.search}" />
</f:metadata>
...
<form>
    <label for="query">Query</label>
    <input type="text" name="query" value="#{empty bean.query ? param.query : bean.query}" />
    <input type="submit" value="Search" />
    <h:message for="query" />
</form>
...
<h:dataTable value="#{bean.results}" var="result" rendered="#{not empty bean.results}">
     ...
</h:dataTable>

With basically this @RequestScoped bean:

private String query;
private List<Result> results;

public void search() {
    results = service.search(query);
}

Note that the <h:message> is for the <f:viewParam>, not the plain HTML <input type="text">! Also note that the input value displays #{param.query} when #{bean.query} is empty, because the submitted value would otherwise not show up at all when there's a validation or conversion error. Please note that this construct is invalid for JSF input components (it is doing that "under the covers" already).


See also:

CronJob not running

Another reason crontab will fail: Special handling of the % character.

From the man file:

The entire command portion of the line, up to a newline or a
"%" character, will be executed by /bin/sh or by the shell specified
in the SHELL variable of the cronfile.  A "%" character in the
command, unless escaped with a backslash (\), will be changed into
newline characters, and all data after the first % will be sent to
the command as standard input.

In my particular case, I was using date --date="7 days ago" "+%Y-%m-%d" to produce parameters to my script, and it was failing silently. I finally found out what was going on when I checked syslog and saw my command was truncated at the % symbol. You need to escape it like this:

date --date="7 days ago" "+\%Y-\%m-\%d"

See here for more details:

http://www.ducea.com/2008/11/12/using-the-character-in-crontab-entries/

URL for public Amazon S3 bucket

The URL structure you're referring to is called the REST endpoint, as opposed to the Web Site Endpoint.


Note: Since this answer was originally written, S3 has rolled out dualstack support on REST endpoints, using new hostnames, while leaving the existing hostnames in place. This is now integrated into the information provided, below.


If your bucket is really in the us-east-1 region of AWS -- which the S3 documentation formerly referred to as the "US Standard" region, but was subsequently officially renamed to the "U.S. East (N. Virginia) Region" -- then http://s3-us-east-1.amazonaws.com/bucket/ is not the correct form for that endpoint, even though it looks like it should be. The correct format for that region is either http://s3.amazonaws.com/bucket/ or http://s3-external-1.amazonaws.com/bucket/

The format you're using is applicable to all the other S3 regions, but not US Standard US East (N. Virginia) [us-east-1].

S3 now also has dual-stack endpoint hostnames for the REST endpoints, and unlike the original endpoint hostnames, the names of these have a consistent format across regions, for example s3.dualstack.us-east-1.amazonaws.com. These endpoints support both IPv4 and IPv6 connectivity and DNS resolution, but are otherwise functionally equivalent to the existing REST endpoints.

If your permissions and configuration are set up such that the web site endpoint works, then the REST endpoint should work, too.

However... the two endpoints do not offer the same functionality.

Roughly speaking, the REST endpoint is better-suited for machine access and the web site endpoint is better suited for human access, since the web site endpoint offers friendly error messages, index documents, and redirects, while the REST endpoint doesn't. On the other hand, the REST endpoint offers HTTPS and support for signed URLs, while the web site endpoint doesn't.

Choose the correct type of endpoint (REST or web site) for your application:

http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html#WebsiteRestEndpointDiff


¹ s3-external-1.amazonaws.com has been referred to as the "Northern Virginia endpoint," in contrast to the "Global endpoint" s3.amazonaws.com. It was unofficially possible to get read-after-write consistency on new objects in this region if the "s3-external-1" hostname was used, because this would send you to a subset of possible physical endpoints that could provide that functionality. This behavior is now officially supported on this endpoint, so this is probably the better choice in many applications. Previously, s3-external-2 had been referred to as the "Pacific Northwest endpoint" for US-Standard, though it is now a CNAME in DNS for s3-external-1 so s3-external-2 appears to have no purpose except backwards-compatibility.