Programs & Examples On #Silverlightcontrols

Opening PDF String in new window with javascript

I just want to add with @Noby Fujioka's response, Edge will not support following

window.open("data:application/pdf," + encodeURI(pdfString));

For Edge we need to convert it to blob and this is something like following

//If Browser is Edge
            if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                var byteCharacters = atob(<Your_base64_Report Data>);
                var byteNumbers = new Array(byteCharacters.length);
                for (var i = 0; i < byteCharacters.length; i++) {
                    byteNumbers[i] = byteCharacters.charCodeAt(i);
                }
                var byteArray = new Uint8Array(byteNumbers);
                var blob = new Blob([byteArray], {
                    type: 'application/pdf'
                });
                window.navigator.msSaveOrOpenBlob(blob, "myreport.pdf");
            } else {
                var pdfWindow = window.open("", '_blank');
                pdfWindow.document.write("<iframe width='100%' style='margin: -8px;border: none;' height='100%' src='data:application/pdf;base64, " + encodeURI(<Your_base64_Report Data>) + "'></iframe>");
            }

Is it possible to change the package name of an Android app on Google Play?

Never, you can't do it since package name is the unique name Identifier for your app.....

Transpose a matrix in Python

You can use zip with * to get transpose of a matrix:

>>> A = [[ 1, 2, 3],[ 4, 5, 6]]
>>> zip(*A)
[(1, 4), (2, 5), (3, 6)]
>>> lis  = [[1,2,3], 
... [4,5,6],
... [7,8,9]]
>>> zip(*lis)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

If you want the returned list to be a list of lists:

>>> [list(x) for x in zip(*lis)]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
#or
>>> map(list, zip(*lis))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

How to center a <p> element inside a <div> container?

?you should do these steps :

  1. the mother Element should be positioned(for EXP you can give it position:relative;)
  2. the child Element should have positioned "Absolute" and values should set like this: top:0;buttom:0;right:0;left:0; (to be middle vertically)
  3. for the child Element you should set "margin : auto" (to be middle vertically)
  4. the child and mother Element should have "height"and"width" value
  5. for mother Element => text-align:center (to be middle horizontally)

??simply here is the summery of those 5 steps:

.mother_Element {
    position : relative;
    height : 20%;
    width : 5%;
    text-align : center
    }
.child_Element {
    height : 1.2 em;
    width : 5%;
    margin : auto;
    position : absolute;
    top:0;
    bottom:0;
    left:0;
    right:0;
    }

How to examine processes in OS X's Terminal?

To sort by cpu usage: top -o cpu

What's the difference between Visual Studio Community and other, paid versions?

Visual Studio Community is same (almost) as professional edition. What differs is that VS community do not have TFS features, and the licensing is different. As stated by @Stefan.

The different versions on VS are compared here - https://www.visualstudio.com/en-us/products/compare-visual-studio-2015-products-vs

enter image description here

How do I tidy up an HTML file's indentation in VI?

The main problem using the smart indentation is that if the XML (or HTML) sits on one line as it may end up coming back from a curl request then gg=G won't do the trick. Instead I have just experienced a good indentation using tidy directly called from VI:

:!tidy -mi -xml -wrap 0 %

This basically tells VI to call tidy to cleanup an XML file not wrapping the lines to make them fit on the default 68 characters wide lines. I processed a large 29MB XML file and it took 5 or 6 seconds. I guess for an HTML file the command should therefore be:

:!tidy -mi -html -wrap 0 %

As mentioned in comments, tidy is a basic tool which you could find on many base Linux / MacOS systems. Here is the projet's page in case you wish you had it but don't: HTML Tidy.

Import multiple csv files into pandas and concatenate into one DataFrame

Based on @Sid's good answer.

Before concatenating, you can load csv files into an intermediate dictionary which gives access to each data set based on the file name (in the form dict_of_df['filename.csv']). Such a dictionary can help you identify issues with heterogeneous data formats, when column names are not aligned for example.

Import modules and locate file paths:

import os
import glob
import pandas
from collections import OrderedDict
path =r'C:\DRO\DCL_rawdata_files'
filenames = glob.glob(path + "/*.csv")

Note: OrderedDict is not necessary, but it'll keep the order of files which might be useful for analysis.

Load csv files into a dictionary. Then concatenate:

dict_of_df = OrderedDict((f, pandas.read_csv(f)) for f in filenames)
pandas.concat(dict_of_df, sort=True)

Keys are file names f and values are the data frame content of csv files. Instead of using f as a dictionary key, you can also use os.path.basename(f) or other os.path methods to reduce the size of the key in the dictionary to only the smaller part that is relevant.

How to find out the location of currently used MySQL configuration file in linux

mysqld --help --verbose will find only location of default configuration file. What if you use 2 MySQL instances on the same server? It's not going to help.

Good article about figuring it out:

"How to find MySQL configuration file?"

How to print exact sql query in zend framework ?

This one's from Zend Framework documentation (ie. UPDATE):

echo $update->getSqlString();

(Bonus) I use this one in my own model files:

echo $this->tableGateway->getSql()->getSqlstringForSqlObject($select);

Have a nice day :)

How can I disable HREF if onclick is executed?

You can use the first un-edited solution, if you put return first in the onclick attribute:

<a href="https://example.com/no-js-login" onclick="return yes_js_login();">Log in</a>

yes_js_login = function() {
     // Your code here
     return false;
}

Example: https://jsfiddle.net/FXkgV/289/

How to "comment-out" (add comment) in a batch/cmd?

Use :: or REM

::   commenttttttttttt
REM  commenttttttttttt

BUT (as people noted):

  • :: doesn't work inline; add & character:
    your commands here & :: commenttttttttttt
  • Inside nested parts (IF/ELSE, FOR loops, etc...) :: should be followed with normal line, otherwise it gives error (use REM there).
  • :: may also fail within setlocal ENABLEDELAYEDEXPANSION

Ruby on Rails 3 Can't connect to local MySQL server through socket '/tmp/mysql.sock' on OSX

The default location for the MySQL socket on Mac OS X is /var/mysql/mysql.sock.

How to access component methods from “outside” in ReactJS?

You could also do it like this, not sure if it's a good plan :D

class Parent extends Component {
  handleClick() {
    if (this._getAlert !== null) {
      this._getAlert()
    }
  }

  render() {
    return (
      <div>
        <Child>
        {(getAlert, childScope) => (
          <span> {!this._getAlert ? this._getAlert = getAlert.bind(childScope) : null}</span>
        )}
        </Child>
        <button onClick={() => this.handleClick()}> Click me</button>
      </div>
      );
    }
  }

class Child extends Component {
  constructor() {
    super();
    this.state = { count: 0 }
  }

  getAlert() {
    alert(`Child function called state: ${this.state.count}`);
    this.setState({ count: this.state.count + 1 });
  }

  render() {
    return this.props.children(this.getAlert, this)
  }
}

How to find row number of a value in R code

I would be tempted to use grepl, which should give all the lines with matches and can be generalised for arbitrary strings.

mydata_2 <- read.table(textConnection("
sex age height_seca1 height_chad1 height_DL weight_alog1
1 F 19 1800 1797 180 70.0
2 F 19 1682 1670 167 69.0
3 F 21 1765 1765 178 80.0
4 F 21 1829 1833 181 74.0
5 F 21 1706 1705 170 103.0
6 F 18 1607 1606 160 76.0
7 F 19 1578 1576 156 50.0
8 F 19 1577 1575 156 61.0
9 F 21 1666 1665 166 52.0
10 F 17 1710 1716 172 65.0
11 F 28 1616 1619 161 65.5
12 F 22 1648 1644 165 57.5
13 F 19 1569 1570 155 55.0
14 F 19 1779 1777 177 55.0
15 M 18 1773 1772 179 70.0
16 M 18 1816 1809 181 81.0
17 M 19 1766 1765 178 77.0
18 M 19 1745 1741 174 76.0
19 M 18 1716 1714 170 71.0
20 M 21 1785 1783 179 64.0
21 M 19 1850 1854 185 71.0
22 M 31 1875 1880 188 95.0
23 M 26 1877 1877 186 105.5
24 M 19 1836 1837 185 100.0
25 M 18 1825 1823 182 85.0
26 M 19 1755 1754 174 79.0
27 M 26 1658 1658 165 69.0
28 M 20 1816 1818 183 84.0
29 M 18 1755 1755 175 67.0"),
                       sep = " ", header = TRUE)

which(grepl(1578, mydata_2$height_seca1))

The output is:

> which(grepl(1578, mydata_2$height_seca1))
[1] 7
> 

[Edit] However, as pointed out in the comments, this will capture much more than the string 1578 (e.g. it also matches for 21578 etc) and thus should be used only if you are certain that you the length of the values you are searching will not be larger than the four characters or digits shown here.

And subsetting as per the other answer also works fine:

mydata_2[mydata_2$height_seca1 == 1578, ]
  sex age height_seca1 height_chad1 height_DL weight_alog1
7   F  19         1578         1576       156           50
> 

If you're looking for several different values, you could put them in a vector and then use the %in% operator:

look.for <- c(1578, 1658, 1616)
> mydata_2[mydata_2$height_seca1 %in% look.for, ]
   sex age height_seca1 height_chad1 height_DL weight_alog1
7    F  19         1578         1576       156         50.0
11   F  28         1616         1619       161         65.5
27   M  26         1658         1658       165         69.0
> 

How to use jQuery to select a dropdown option?

This works for me:

$selectedindex=4

If you want to randomise options, you could always do something like this:

$0selectedindex=Math.floor((Math.random()*($0.length-1)+1)

Whilst 2nd bullet lies outside scope of your questions, it serves to illustrate how 1st bullet could be applied / amended as req.

How to query MongoDB with "like"?

For PHP mongo Like.
I had several issues with php mongo like. i found that concatenating the regex params helps in some situations PHP mongo find field starts with. I figured I would post on here to contribute to the more popular thread

e.g

db()->users->insert(['name' => 'john']);
db()->users->insert(['name' => 'joe']);
db()->users->insert(['name' => 'jason']);

// starts with
$like_var = 'jo';
$prefix = '/^';
$suffix = '/';
$name = $prefix . $like_var . $suffix;
db()->users->find(['name' => array('$regex'=>new MongoRegex($name))]);
output: (joe, john)

// contains
$like_var = 'j';
$prefix = '/';
$suffix = '/';
$name = $prefix . $like_var . $suffix;
db()->users->find(['name' => array('$regex'=>new MongoRegex($name))]);

output: (joe, john, jason)

Angular JS: Full example of GET/POST/DELETE/PUT client for a REST/CRUD backend?

Because your update uses PUT method, {entryId: $scope.entryId} is considered as data, to tell angular generate from the PUT data, you need to add params: {entryId: '@entryId'} when you define your update, which means

return $resource('http://localhost\\:3000/realmen/:entryId', {}, {
  query: {method:'GET', params:{entryId:''}, isArray:true},
  post: {method:'POST'},
  update: {method:'PUT', params: {entryId: '@entryId'}},
  remove: {method:'DELETE'}
});

Fix: Was missing a closing curly brace on the update line.

Dialogs / AlertDialogs: How to "block execution" while dialog is up (.NET-style)

A simplified version of Daniel's answer above. This function gets a yes or no from user in an alert dialog but could easily be modified to get other input.

private boolean mResult;
public boolean getYesNoWithExecutionStop(String title, String message, Context context) {
    // make a handler that throws a runtime exception when a message is received
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message mesg) {
            throw new RuntimeException();
        } 
    };

    // make a text input dialog and show it
    AlertDialog.Builder alert = new AlertDialog.Builder(context);
    alert.setTitle(title);
    alert.setMessage(message);
    alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            mResult = true;
            handler.sendMessage(handler.obtainMessage());
        }
    });
    alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            mResult = false;
            handler.sendMessage(handler.obtainMessage());
        }
    });
    alert.show();

    // loop till a runtime exception is triggered.
    try { Looper.loop(); }
    catch(RuntimeException e2) {}

    return mResult;
}

How to read a text file directly from Internet using Java?

I did that in the following way for an image, you should be able to do it for text using similar steps.

// folder & name of image on PC          
File fileObj = new File("C:\\Displayable\\imgcopy.jpg"); 

Boolean testB = fileObj.createNewFile();

System.out.println("Test this file eeeeeeeeeeeeeeeeeeee "+testB);

// image on server
URL url = new URL("http://localhost:8181/POPTEST2/imgone.jpg"); 
InputStream webIS = url.openStream();

FileOutputStream fo = new FileOutputStream(fileObj);
int c = 0;
do {
    c = webIS.read();
    System.out.println("==============> " + c);
    if (c !=-1) {
        fo.write((byte) c);
    }
} while(c != -1);

webIS.close();
fo.close();

jQuery get textarea text

Where it is often the text function you use (e.g. in divs etc) then for text area it is val

get:

$('#myTextBox').val();

set:

$('#myTextBox').val('new value');

if (select count(column) from table) > 0 then

Edit:

The oracle tag was not on the question when this answer was offered, and apparently it doesn't work with oracle, but it does work with at least postgres and mysql

No, just use the value directly:

begin
  if (select count(*) from table) > 0 then
     update table
  end if;
end;

Note there is no need for an "else".

Edited

You can simply do it all within the update statement (ie no if construct):

update table
set ...
where ...
and exists (select 'x' from table where ...)

Get div tag scroll position using JavaScript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function scollPos() {
            var div = document.getElementById("myDiv").scrollTop;
            document.getElementById("pos").innerHTML = div;
        }
    </script>
</head>
<body>
    <form id="form1">
    <div id="pos">
    </div>
    <div id="myDiv" style="overflow: auto; height: 200px; width: 200px;" onscroll="scollPos();">
        Place some large content here
    </div>
    </form>
</body>
</html>

Posting a File and Associated Data to a RESTful WebService preferably as JSON

I wanted send some strings to backend server. I didnt use json with multipart, I have used request params.

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public void uploadFile(HttpServletRequest request,
        HttpServletResponse response, @RequestParam("uuid") String uuid,
        @RequestParam("type") DocType type,
        @RequestParam("file") MultipartFile uploadfile)

Url would look like

http://localhost:8080/file/upload?uuid=46f073d0&type=PASSPORT

I am passing two params (uuid and type) along with file upload. Hope this will help who don't have the complex json data to send.

Using Mysql WHERE IN clause in codeigniter

You can use sub query way of codeigniter to do this for this purpose you will have to hack codeigniter. like this
Go to system/database/DB_active_rec.php Remove public or protected keyword from these functions

public function _compile_select($select_override = FALSE)
public function _reset_select()

Now subquery writing in available And now here is your query with active record

$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();

$this->db->_reset_select();
// And now your main query
$this->db->select("*");
$this->db->where_in("$subQuery");
$this->db->where('code !=', 'B');
$this->db->get('myTable');

And the thing is done. Cheers!!!
Note : While using sub queries you must use

$this->db->from('myTable')

instead of

$this->db->get('myTable')

which runs the query.
Watch this too

How can I rewrite this SQL into CodeIgniter's Active Records?

Note : In Codeigntier 3 these functions are already public so you do not need to hack them.

Filtering DataGridView without changing datasource

//"Comment" Filter datagrid without changing dataset,Perfectly works.

            (dg.ItemsSource as ListCollectionView).Filter = (d) =>
            {
                DataRow myRow = ((System.Data.DataRowView)(d)).Row;
                if (myRow["FName"].ToString().ToUpper().Contains(searchText.ToString().ToUpper()) || myRow["LName"].ToString().ToUpper().Contains(searchText.ToString().ToUpper()))
                    return true; //if want to show in grid
                return false;    //if don't want to show in grid
            };         

"No X11 DISPLAY variable" - what does it mean?

you must enable X11 forwarding in you PuTTy

to do so open PuTTy, go to Connection => SSH => Tunnels and check mark the Enable X11 forwarding

Also sudo to server and export the below variable here IP is your local machine's IP

export DISPLAY=10.75.75.75:0.0

enter image description here

How to select first and last TD in a row?

You could use the :first-child and :last-child pseudo-selectors:

tr td:first-child,
tr td:last-child {
    /* styles */
}

This should work in all major browsers, but IE7 has some problems when elements are added dynamically (and it won't work in IE6).

Check if current date is between two dates Oracle SQL

SELECT to_char(emp_login_date,'DD-MON-YYYY HH24:MI:SS'),A.* 
FROM emp_log A
WHERE emp_login_date BETWEEN to_date(to_char('21-MAY-2015 11:50:14'),'DD-MON-YYYY HH24:MI:SS')
AND
to_date(to_char('22-MAY-2015 17:56:52'),'DD-MON-YYYY HH24:MI:SS') 
ORDER BY emp_login_date

Node Version Manager install - nvm command not found

The nvm install script by default adds initialization code to your $HOME/.profile, which is only loaded by a login shell (in a desktop environment you may never see a login shell).

The nvm command in your login shell is not propagated to sub-shells (like console windows and IDE terminals after you log in). This snippet in your $HOME/.bashrc will only load nvm if it is an interactive shell and has not been loaded already

# if nvm dir is not set and the standard nvm directory exists
if [ -z "$NVM_DIR" -a -d "$HOME/.nvm" ] ; then
# set nvm dir
  export NVM_DIR="$HOME/.nvm"
fi

# if nvm dir is set and this shell is interactive
if [ -d "$NVM_DIR" -a -n "$PS1" ] ; then
  # if nvm command is not defined
  if ! type -t nvm >/dev/null ; then
    # set it
    source "$NVM_DIR/nvm.sh"
  fi
fi

Putting this in your $HOME/.bashrc file will fix the missing nvm problem in interactive bash shells, even from a gui, and even if nvm is installed in a non-standard location.

Splitting string with pipe character ("|")

split takes regex as a parameter.| has special meaning in regex.. use \\| instead of | to escape it.

Looping through GridView rows and Checking Checkbox Control

Loop like

foreach (GridViewRow row in grid.Rows)
{
   if (((CheckBox)row.FindControl("chkboxid")).Checked)
   {
    //read the label            
   }            
}

Regex to match string containing two names in any order

Explanation of command that i am going to write:-

. means any character, digit can come in place of .

* means zero or more occurrences of thing written just previous to it.

| means 'or'.

So,

james.*jack

would search james , then any number of character until jack comes.

Since you want either jack.*james or james.*jack

Hence Command:

jack.*james|james.*jack

What are the date formats available in SimpleDateFormat class?

check the formats here http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

main

System.out.println("date  : " + new classname().getMyDate("2014-01-09 14:06", "dd-MMM-yyyy E hh:mm a z", "yyyy-MM-dd HH:mm"));

method

 public String getMyDate(String myDate, String returnFormat, String myFormat)
            {
                DateFormat dateFormat = new SimpleDateFormat(returnFormat);
                Date date=null;
                String returnValue="";
                try {
                    date = new SimpleDateFormat(myFormat, Locale.ENGLISH).parse(myDate);
                    returnValue = dateFormat.format(date);
                } catch (ParseException e) {
                    returnValue= myDate;
                    System.out.println("failed");
                    e.printStackTrace();
                }

            return returnValue;
            }

Saving results with headers in Sql Server Management Studio

At least in SQL Server 2012, you can right click in the query window and select Query Options. From there you can select Include Headers for grid and/or text and have the Save As work the way you want it without restarting SSMS.

You'll still need to change it in Tools->Options in the menu bar to have new query windows use those settings by default.

showDialog deprecated. What's the alternative?

To display dialog box, you can use the following code. This is to display a simple AlertDialog box with multiple check boxes:

AlertDialog.Builder alertDialog= new AlertDialog.Builder(MainActivity.this); .
            alertDialog.setTitle("this is a dialog box ");
            alertDialog.setPositiveButton("ok", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    Toast.makeText(getBaseContext(),"ok ive wrote this 'ok' here" ,Toast.LENGTH_SHORT).show();

                }
            });
            alertDialog.setNegativeButton("cancel", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                        Toast.makeText(getBaseContext(), "cancel ' comment same as ok'", Toast.LENGTH_SHORT).show();


                }
            });
            alertDialog.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                    // TODO Auto-generated method stub
                    Toast.makeText(getBaseContext(), items[which] +(isChecked?"clicked'again i've wrrten this click'":"unchecked"),Toast.LENGTH_SHORT).show();

                }
            });
            alertDialog.show();

Heading

Whereas if you are using the showDialog function to display different dialog box or anything as per the arguments passed, you can create a self function and can call it under the onClickListener() function. Something like:

 public CharSequence[] items={"google","Apple","Kaye"};
public boolean[] checkedItems=new boolean[items.length];
Button bt;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    bt=(Button) findViewById(R.id.bt);
    bt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            display(0);             
        }       
    });
}

and add the code of dialog box given above in the function definition.

HTML/CSS: Making two floating divs the same height

By using css property --> display:table-cell

_x000D_
_x000D_
div {_x000D_
    border: 1px solid #000;_x000D_
    margin: 5px;_x000D_
    padding: 4px;_x000D_
 display:table-cell;_x000D_
 width:25% ;position:relative;_x000D_
}_x000D_
body{display:table;_x000D_
 border-collapse:separate;_x000D_
 border-spacing:5px 5px}
_x000D_
<div>_x000D_
    This is my div one This is my div one This is my div one_x000D_
</div>_x000D_
<div>_x000D_
    This is my div two This is my div two This is my div two This is my div two This is my div two This is my div two_x000D_
</div>_x000D_
<div>_x000D_
    This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3_x000D_
</div>
_x000D_
_x000D_
_x000D_

JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors

I've gotten same problem. The servers logs showed:

DEBUG: <-- origin: null

I've investigated that and it occurred that this is not populated when I've been calling from file from local drive. When I've copied file to the server and used it from server - the request worked perfectly fine

When and Why to use abstract classes/methods?

Abstract classes/methods are generally used when a class provides some high level functionality but leaves out certain details to be implemented by derived classes. Making the class/method abstract ensures that it cannot be used on its own, but must be specialized to define the details that have been left out of the high level implementation. This is most often used with the template method pattern:

http://en.wikipedia.org/wiki/Template_method_pattern

Routing with multiple Get methods in ASP.NET Web API

First, add new route with action on top:

  config.Routes.MapHttpRoute(
           name: "ActionApi",
           routeTemplate: "api/{controller}/{action}/{id}",
           defaults: new { id = RouteParameter.Optional }
       );

  config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

Then use ActionName attribute to map:

[HttpGet]
public List<Customer> Get()
{
    //gets all customer
}

[ActionName("CurrentMonth")]
public List<Customer> GetCustomerByCurrentMonth()
{
    //gets some customer on some logic
}

[ActionName("customerById")]
public Customer GetCustomerById(string id)
{
    //gets a single customer using id
}

[ActionName("customerByUsername")]
public Customer GetCustomerByUsername(string username)
{
    //gets a single customer using username
}

Select query to remove non-numeric characters

In case if there are some characters possible between digits (e.g. thousands separators), you may try following:

declare @table table (DirtyCol varchar(100))
insert into @table values
    ('AB ABCDE # 123')
    ,('ABCDE# 123')
    ,('AB: ABC# 123')
    ,('AB#')
    ,('AB # 1 000 000')
    ,('AB # 1`234`567')
    ,('AB # (9)(876)(543)')

;with tally as (select top (100) N=row_number() over (order by @@spid) from sys.all_columns),
data as (
    select DirtyCol, Col
    from @table
        cross apply (
            select (select C + ''
            from (select N, substring(DirtyCol, N, 1) C from tally where N<=datalength(DirtyCol)) [1]
            where C between '0' and '9'
            order by N
            for xml path(''))
        ) p (Col)
    where p.Col is not NULL
)
select DirtyCol, cast(Col as int) IntCol
from data

Output is:

DirtyCol              IntCol
--------------------- -------
AB ABCDE # 123        123
ABCDE# 123            123
AB: ABC# 123          123
AB # 1 000 000        1000000
AB # 1`234`567        1234567
AB # (9)(876)(543)    9876543

For update, add ColToUpdate to select list of the data cte:

;with num as (...),
data as (
    select ColToUpdate, /*DirtyCol, */Col
    from ...
)
update data
set ColToUpdate = cast(Col as int)

Test whether string is a valid integer

For me, the simplest solution was to use the variable inside a (()) expression, as so:

if ((VAR > 0))
then
  echo "$VAR is a positive integer."
fi

Of course, this solution is only valid if a value of zero doesn't make sense for your application. That happened to be true in my case, and this is much simpler than the other solutions.

As pointed out in the comments, this can make you subject to a code execution attack: The (( )) operator evaluates VAR, as stated in the Arithmetic Evaluation section of the bash(1) man page. Therefore, you should not use this technique when the source of the contents of VAR is uncertain (nor should you use ANY other form of variable expansion, of course).

UIButton action in table view cell

in Swift 4

in cellForRowAt indexPath:

 cell.prescriptionButton.addTarget(self, action: Selector("onClicked:"), for: .touchUpInside)

function that run after user pressed button:

@objc func onClicked(sender: UIButton){
        let tag = sender.tag


    }

How to Force New Google Spreadsheets to refresh and recalculate?

I know that you are looking for an auto-refresh; perhaps some coming in here may be happy with a quick fix for a manual button (like the checkbox proposed above). I actually just stumbled upon a similar solution to the checkbox: select the cells you want to refresh, and then press CTRL and the "+" key. Seems to work in Office 365 v16; hope it works for others in need.

Passing argument to alias in bash

This is the solution which can avoid using function:

alias addone='{ num=$(cat -); echo "input: $num"; echo "result:$(($num+1))"; }<<<'

test result

addone 200
input: 200
result:201

Common CSS Media Queries Break Points

Instead of using pixels should use em or percentage as it is more adaptive and fluid, better not target devices target your content:

HTML5 rockrs read, mobile first

Styling an input type="file" button

Here is a solution, that also shows the chosen file name: http://jsfiddle.net/raft9pg0/1/

HTML:

<label for="file-upload" class="custom-file-upload">Chose file</label>
<input id="file-upload" type="file"/>
File: <span id="file-upload-value">-</span>

JS:

$(function() {
    $("input:file[id=file-upload]").change(function() {
        $("#file-upload-value").html( $(this).val() );
    });
});

CSS:

input[type="file"] {
    display: none;
}

.custom-file-upload {
      background: #ddd;
      border: 1px solid #aaa;
      border-top: 1px solid #ccc;
      border-left: 1px solid #ccc;
      -moz-border-radius: 3px;
      -webkit-border-radius: 3px;
      border-radius: 3px;
      color: #444;
      display: inline-block;
      font-size: 11px;
      font-weight: bold;
      text-decoration: none;
      text-shadow: 0 1px rgba(255, 255, 255, .75);
      cursor: pointer;
      margin-bottom: 20px;
      line-height: normal;
      padding: 8px 10px; }

Convert integer into byte array (Java)

use this function it works for me

public byte[] toByteArray(int value) {
    return new byte[] {
            (byte)(value >> 24),
            (byte)(value >> 16),
            (byte)(value >> 8),
            (byte)value};
}

it translates the int into a byte value

select data up to a space?

An alternative if you sometimes do not have spaces do not want to use the CASE statement

select REVERSE(RIGHT(REVERSE(YourColumn), LEN(YourColumn) - CHARINDEX(' ', REVERSE(YourColumn))))

This works in SQL Server, and according to my searching MySQL has the same functions

How to know when a web page was last updated?

Take a look at archive.org

You can find almost everything about the past of a website there.

When should I use nil and NULL in Objective-C?

This will help you to understand the difference between nil, NIL and null.

The below link may help you in some way:

http://nshipster.com/nil/

nil -> literal null value for Objective-C objects.

Nil -> literal null value for Objective-C classes.

NULL -> literal null value for C pointers.

NSNULL -> singleton object used to represent null.

A fatal error has been detected by the Java Runtime Environment: SIGSEGV, libjvm

Not really to answer OP's question (it's resolved anyway), but to help people who may stumble into the similar issue.

Here is what we had:

#
# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x0000000000000000, pid=11, tid=139910430250752
#
# JRE version: Java(TM) SE Runtime Environment (8.0_77-b03) (build 1.8.0_77-b03)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.77-b03 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# C  0x0000000000000000
#
# Core dump written. Default location: /builds/c5b22963/0/reporting/arsng2/core or core.11
#

The reason was defective RAM.

How to assign text size in sp value using java code

You can use a DisplayMetrics object to help convert between pixels and scaled pixels with the scaledDensity attribute.

DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
pixelSize = (int)scaledPixelSize * dm.scaledDensity; 

How can I execute Shell script in Jenkinsfile?

Previous answers are correct but here is one more way of doing this and some tips:

Option #1 Go to you Jenkins job and search for "add build step" and then just copy and paste your script there

Option #2 Go to Jenkins and do the same again "add build step" but this time put the fully qualified path for your script in there example : ./usr/somewhere/helloWorld.sh

enter image description here enter image description here

things to watch for /tips:

  • Environment variables, if your job is running at the same time then you need to worry about concurrency issues. One job may be setting the value of environment variables and the next may use the value or take some action based on that incorrectly.
  • Make sure all paths are fully qualified
  • Think about logging /var/log or somewhere so you would also have something to go to on the server (optional)
  • thing about space issue and permissions, running out of space and permission issues are very common in linux environment
  • Alerting and make sure your script/job fails the jenkin jobs when your script fails

What does -Xmn jvm option stands for

From here:

-Xmn : the size of the heap for the young generation

Young generation represents all the objects which have a short life of time. Young generation objects are in a specific location into the heap, where the garbage collector will pass often. All new objects are created into the young generation region (called "eden"). When an object survive is still "alive" after more than 2-3 gc cleaning, then it will be swap has an "old generation" : they are "survivor".

And a more "official" source from IBM:

-Xmn

Sets the initial and maximum size of the new (nursery) heap to the specified value when using -Xgcpolicy:gencon. Equivalent to setting both -Xmns and -Xmnx. If you set either -Xmns or -Xmnx, you cannot set -Xmn. If you attempt to set -Xmn with either -Xmns or -Xmnx, the VM will not start, returning an error. By default, -Xmn is selected internally according to your system's capability. You can use the -verbose:sizes option to find out the values that the VM is currently using.

How to create a Date in SQL Server given the Day, Month and Year as Integers

Old Microsoft Sql Sever (< 2012)

RETURN dateadd(month, 12 * @year + @month - 22801, @day - 1)  

Understanding the Rails Authenticity Token

Beware the Authenticity Token mechanism can result in race conditions if you have multiple, concurrent requests from the same client. In this situation your server can generate multiple authenticity tokens when there should only be one, and the client receiving the earlier token in a form will fail on it's next request because the session cookie token has been overwritten. There is a write up on this problem and a not entirely trivial solution here: http://www.paulbutcher.com/2007/05/race-conditions-in-rails-sessions-and-how-to-fix-them/

Converting an OpenCV Image to Black and White

Here's a two line code I found online that might be helpful for a beginner

# Absolute value of the 32/64
abs_image_in32_64 = np.absolute(image_in32_64)

image_8U = np.uint8(abs_image_in32_64)

Origin null is not allowed by Access-Control-Allow-Origin

I would like to humbly add that according to this SO source: https://stackoverflow.com/a/14671362/1743693, this kind of trouble is now partially solved simply by using the following jQuery instruction:

<script> 
    $.support.cors = true;
</script>

I tried it on IE10.0.9200, and it worked immediately (using jquery-1.9.0.js).

On chrome 28.0.1500.95 - this instruction doesn't work (this happens all over as david complains in the comments at the link above)

Running chrome with --allow-file-access-from-files did not work for me (as Maistora's claims above)

delete all from table

This should be faster:

DELETE * FROM table_name;

because RDBMS don't have to look where is what.

You should be fine with truncate though:

truncate table table_name

Why does the Visual Studio editor show dots in blank spaces?

In Visual Studio 2019, this can also be configured in Tools -> Options -> General -> View whitespace

Generate a Hash from string in Javascript

Note: Even with the best 32-bit hash, collisions will occur sooner or later.

The hash collision probablility can be calculated as 1 - e ^ (-k(k-1) / 2N, aproximated as k^2 / 2N (see here). This may be higher than intuition suggests:
Assuming a 32-bit hash and k=10,000 items, a collision will occur with a probablility of 1.2%. For 77,163 samples the probability becomes 50%! (calculator).
I suggest a workaround at the bottom.

In an answer to this question Which hashing algorithm is best for uniqueness and speed?, Ian Boyd posted a good in depth analysis. In short (as I interpret it), he comes to the conclusion that Murmur is best, followed by FNV-1a.
Java’s String.hashCode() algorithm that esmiralha proposed seems to be a variant of DJB2.

  • FNV-1a has a a better distribution than DJB2, but is slower
  • DJB2 is faster than FNV-1a, but tends to yield more collisions
  • MurmurHash3 is better and faster than DJB2 and FNV-1a (but the optimized implementation requires more lines of code than FNV and DJB2)

Some benchmarks with large input strings here: http://jsperf.com/32-bit-hash
When short input strings are hashed, murmur's performance drops, relative to DJ2B and FNV-1a: http://jsperf.com/32-bit-hash/3

So in general I would recommend murmur3.
See here for a JavaScript implementation: https://github.com/garycourt/murmurhash-js

If input strings are short and performance is more important than distribution quality, use DJB2 (as proposed by the accepted answer by esmiralha).

If quality and small code size are more important than speed, I use this implementation of FNV-1a (based on this code).

/**
 * Calculate a 32 bit FNV-1a hash
 * Found here: https://gist.github.com/vaiorabbit/5657561
 * Ref.: http://isthe.com/chongo/tech/comp/fnv/
 *
 * @param {string} str the input value
 * @param {boolean} [asString=false] set to true to return the hash value as 
 *     8-digit hex string instead of an integer
 * @param {integer} [seed] optionally pass the hash of the previous chunk
 * @returns {integer | string}
 */
function hashFnv32a(str, asString, seed) {
    /*jshint bitwise:false */
    var i, l,
        hval = (seed === undefined) ? 0x811c9dc5 : seed;

    for (i = 0, l = str.length; i < l; i++) {
        hval ^= str.charCodeAt(i);
        hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
    }
    if( asString ){
        // Convert to 8 digit hex string
        return ("0000000" + (hval >>> 0).toString(16)).substr(-8);
    }
    return hval >>> 0;
}

Improve Collision Probability

As explained here, we can extend the hash bit size using this trick:

function hash64(str) {
    var h1 = hash32(str);  // returns 32 bit (as 8 byte hex string)
    return h1 + hash32(h1 + str);  // 64 bit (as 16 byte hex string)
}

Use it with care and don't expect too much though.

How to get a pixel's x,y coordinate color from an image?

Building on Jeff's answer, your first step would be to create a canvas representation of your PNG. The following creates an off-screen canvas that is the same width and height as your image and has the image drawn on it.

var img = document.getElementById('my-image');
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);

After that, when a user clicks, use event.offsetX and event.offsetY to get the position. This can then be used to acquire the pixel:

var pixelData = canvas.getContext('2d').getImageData(event.offsetX, event.offsetY, 1, 1).data;

Because you are only grabbing one pixel, pixelData is a four entry array containing the pixel's R, G, B, and A values. For alpha, anything less than 255 represents some level of transparency with 0 being fully transparent.

Here is a jsFiddle example: http://jsfiddle.net/thirtydot/9SEMf/869/ I used jQuery for convenience in all of this, but it is by no means required.

Note: getImageData falls under the browser's same-origin policy to prevent data leaks, meaning this technique will fail if you dirty the canvas with an image from another domain or (I believe, but some browsers may have solved this) SVG from any domain. This protects against cases where a site serves up a custom image asset for a logged in user and an attacker wants to read the image to get information. You can solve the problem by either serving the image from the same server or implementing Cross-origin resource sharing.

Conditionally formatting if multiple cells are blank (no numerics throughout spreadsheet )

enter image description here

How about just > Format only cells that contain - in the drop down box select Blanks

Why do I get PLS-00302: component must be declared when it exists?

You can get that error if you have an object with the same name as the schema. For example:

create sequence s2;

begin
  s2.a;
end;
/

ORA-06550: line 2, column 6:
PLS-00302: component 'A' must be declared
ORA-06550: line 2, column 3:
PL/SQL: Statement ignored

When you refer to S2.MY_FUNC2 the object name is being resolved so it doesn't try to evaluate S2 as a schema name. When you just call it as MY_FUNC2 there is no confusion, so it works.

The documentation explains name resolution. The first piece of the qualified object name - S2 here - is evaluated as an object on the current schema before it is evaluated as a different schema.

It might not be a sequence; other objects can cause the same error. You can check for the existence of objects with the same name by querying the data dictionary.

select owner, object_type, object_name
from all_objects
where object_name = 'S2';

Best solution to protect PHP code without encryption

You need to consider your objectives:

1) Are you trying to prevent people from reading/modifying your code? If yes, you'll need an obfuscation/encryption tool. I've used Zend Guard with good success.

2) Are you trying to prevent unauthorized redistribution of your code?? A EULA/proprietary license will give you the legal power to prevent that, but won't actually stop it. An key/activation scheme will allow you to actively monitor usage, but can be removed unless you also encrypt your code. Zend Guard also has capabilities to lock a particular script to a particular customer machine and/or create time limited versions of the code if that's what you want to do.

I'm not familiar with vBulletin and the like, but they'd either need to encrypt/obfuscate or trust their users to do the right thing. In the latter case they have the protection of having a EULA which prohibits the behaviors they find undesirable, and the legal system to back up breaches of the EULA.

If you're not prepared/able to take legal action to protect your software and you don't want to encrypt/obfuscate, your options are a) Release it with a EULA so you're have a legal option if you ever need it and hope for the best, or b) consider whether an open source license might be more appropriate and just allow redistribution.

How to set the locale inside a Debian/Ubuntu Docker container?

You guys don't need those complex things to set locales on Ubuntu/Debian. You don't even need /etc/local.gen file.

Simply locale-gen will do everything and the author only missed locales package.

RUN apt-get update && apt-get install -y locales && rm -rf /var/lib/apt/lists/* \
 && locale-gen "en_US.UTF-8"
ENV LANG=en_US.UTF-8 \
    LANGUAGE=en_US:en \
    LC_ALL=en_US.UTF-8

I found this the simplest and the most effective. I confirm it works on Ubuntu 16.04.

Cannot create PoolableConnectionFactory

This is a network problem. Check out your database connectivity. Either your database connection link, username and password is wrong or your database server is stopped.

Git push/clone to new server

There are many ways to move repositories around, git bundle is a nice way if you have insufficient network availability. Since a Git repository is really just a directory full of files, you can "clone" a repository by making a copy of the .git directory in whatever way suits you best.

The most efficient way is to use an external repository somewhere (use GitHub or set up Gitosis), and then git push.

How can I read large text files in Python, line by line, without loading it into memory?

All you need to do is use the file object as an iterator.

for line in open("log.txt"):
    do_something_with(line)

Even better is using context manager in recent Python versions.

with open("log.txt") as fileobject:
    for line in fileobject:
        do_something_with(line)

This will automatically close the file as well.

Angularjs - Pass argument to directive

Insert the var msg in the click event with scope.$apply to make the changes to the confirm, based on your controller changes to the variables shown in ng-confirm-click therein.

<button type="button" class="btn" ng-confirm-click="You are about to send {{quantity}} of {{thing}} selected? Confirm with OK" confirmed-click="youraction(id)" aria-describedby="passwordHelpBlock">Send</button>




app.directive('ngConfirmClick', [
  function() {
    return {
      link: function(scope, element, attr) {
        var clickAction = attr.confirmedClick;
        element.on('click', function(event) {
          var msg = attr.ngConfirmClick || "Are you sure? Click OK to confirm.";
          if (window.confirm(msg)) {
            scope.$apply(clickAction)
          }
        });
      }
    };
  }
])

TimeSpan to DateTime conversion

var StartTime = new DateTime(item.StartTime.Ticks);

Using C++ base class constructors?

Prefer initialization:

class C : public A
{
public:
    C(const string &val) : A(anInt) {}
};

In C++11, you can use inheriting constructors (which has the syntax seen in your example D).

Update: Inheriting Constructors have been available in GCC since version 4.8.


If you don't find initialization appealing (e.g. due to the number of possibilities in your actual case), then you might favor this approach for some TMP constructs:

class A
{
public: 
    A() {}
    virtual ~A() {}
    void init(int) { std::cout << "A\n"; }
};

class B : public A
{
public:
    B() : A() {}
    void init(int) { std::cout << "B\n"; }
};

class C : public A
{
public:
    C() : A() {}
    void init(int) { std::cout << "C\n"; }
};

class D : public A
{
public:
    D() : A() {}
    using A::init;
    void init(const std::string& s) { std::cout << "D -> " << s << "\n"; }
};

int main()
{
    B b; b.init(10);
    C c; c.init(10);
    D d; d.init(10); d.init("a");

    return 0;
}

Java/Groovy - simple date reformatting

oldDate is not in the format of the SimpleDateFormat you are using to parse it.

Try this format: dd-MMM-yyyy - It matches what you're trying to parse.

What is the difference between single and double quotes in SQL?

A simple rule for us to remember what to use in which case:

  • [S]ingle quotes are for [S]trings ; [D]ouble quotes are for [D]atabase identifiers;

In MySQL and MariaDB, the ` (backtick) symbol is the same as the " symbol. You can use " when your SQL_MODE has ANSI_QUOTES enabled.

Detect Android phone via Javascript / jQuery

js version, catches iPad too:

var is_mobile = /mobile|android/i.test (navigator.userAgent);

How to change date format in JavaScript

You can certainly format the date yourself..

var mydate = new Date(form.startDate.value);
var month = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"][mydate.getMonth()];
var str = month + ' ' + mydate.getFullYear();

You can also use an external library, such as DateJS.

Here's a DateJS example:

<script src="http://www.datejs.com/build/date.js" type="text/javascript"></script>
<script>
   var mydate = new Date(form.startDate.value);
   var str = mydate.toString("MMMM yyyy");
   window.alert(str);
</script>

Excel VBA - Sum up a column

I have a label on my form receiving the sum of numbers from Column D in Sheet1. I am only interested in rows 2 to 50, you can use a row counter if your row count is dynamic. I have some blank entries as well in column D and they are ignored.

Me.lblRangeTotal = Application.WorksheetFunction.Sum(ThisWorkbook.Sheets("Sheet1").Range("D2:D50"))

Setting a max height on a table

Seems very similar to this question. From there it seems that this should do the trick:

table {
  display: block; /* important */
  height: 600px;
  overflow-y: scroll;
}

How to override and extend basic Django admin templates?

You can use django-overextends, which provides circular template inheritance for Django.

It comes from the Mezzanine CMS, from where Stephen extracted it into a standalone Django extension.

More infos you find in "Overriding vs Extending Templates" (http:/mezzanine.jupo.org/docs/content-architecture.html#overriding-vs-extending-templates) inside the Mezzanine docs.

For deeper insides look at Stephens Blog "Circular Template Inheritance for Django" (http:/blog.jupo.org/2012/05/17/circular-template-inheritance-for-django).

And in Google Groups the discussion (https:/groups.google.com/forum/#!topic/mezzanine-users/sUydcf_IZkQ) which started the development of this feature.

Note:

I don't have the reputation to add more than 2 links. But I think the links provide interesting background information. So I just left out a slash after "http(s):". Maybe someone with better reputation can repair the links and remove this note.

Finding moving average from data points in Python

My Moving Average function, without numpy function:

from __future__ import division  # must be on first line of script

class Solution:
    def Moving_Avg(self,A):
        m = A[0]
        B = []
        B.append(m)
        for i in range(1,len(A)):
            m = (m * i + A[i])/(i+1)
            B.append(m)
        return B

Unable to connect to mongodb Error: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:L112

If you are on unix-like systems.

Starting in MongoDB 4.4, a startup error is generated if the ulimit value for number of open files is under 64000. View the current val

$ ulimit -n

Change value

$ ulimit -n <val>

Newline character in StringBuilder

Just create an extension for the StringBuilder class:

Public Module Extensions
    <Extension()>
    Public Sub AppendFormatWithNewLine(ByRef sb As System.Text.StringBuilder, ByVal format As String, ParamArray values() As Object)
        sb.AppendLine(String.Format(format, values))
    End Sub
End Module

how to set cursor style to pointer for links without hrefs

in your css file add this....

a:hover {
 cursor:pointer;
}

if you don't have a css file, add this to the HEAD of your HTML page

<style type="text/css">
 a:hover {
  cursor:pointer;
 }
</style>

also you can use the href="" attribute by returning false at the end of your javascript.

<a href="" onclick="doSomething(); return false;">a link</a>

this is good for many reasons. SEO or if people don't have javascript, the href="" will work. e.g.

<a href="nojavascriptpage.html" onclick="doSomething(); return false;">a link</a>

@see http://www.alistapart.com/articles/behavioralseparation

Edit: Worth noting @BalusC's answer where he mentions :hover is not necessary for the OP's use case. Although other style can be add with the :hover selector.

Seeking useful Eclipse Java code templates

Some more templates here.

Includes:

  • Create a date object from a particular date
  • Create a new generic ArrayList
  • Logger setup
  • Log with specified level
  • Create a new generic HashMap
  • Iterate through a map, print the keys and values
  • Parse a time using SimpleDateFormat
  • Read a file line by line
  • Log and rethrow a caught exeption
  • Print execution time of a block of code
  • Create periodic Timer
  • Write a String to a file

How to obtain the start time and end time of a day?

private Date getStartOfDay(Date date) {
    Calendar calendar = Calendar.getInstance();
    int year = calendar.get(Calendar.YEAR);
    int month = calendar.get(Calendar.MONTH);
    int day = calendar.get(Calendar.DATE);
    calendar.setTimeInMillis(0);
    calendar.set(year, month, day, 0, 0, 0);
    return calendar.getTime();
    }

private Date getEndOfDay(Date date) {
    Calendar calendar = Calendar.getInstance();
    int year = calendar.get(Calendar.YEAR);
    int month = calendar.get(Calendar.MONTH);
    int day = calendar.get(Calendar.DATE);
    calendar.setTimeInMillis(0);
    calendar.set(year, month, day, 23, 59, 59);
    return calendar.getTime();
    }

calendar.setTimeInMillis(0); gives you accuracy upto milliseconds

Convert a PHP object to an associative array

First of all, if you need an array from an object you probably should constitute the data as an array first. Think about it.

Don't use a foreach statement or JSON transformations. If you're planning this, again you're working with a data structure, not with an object.

If you really need it use an object-oriented approach to have a clean and maintainable code. For example:

Object as array

class PersonArray implements \ArrayAccess, \IteratorAggregate
{
    public function __construct(Person $person) {
        $this->person = $person;
    }
    // ...
 }

If you need all properties, use a transfer object:

class PersonTransferObject
{
    private $person;

    public function __construct(Person $person) {
        $this->person = $person;
    }

    public function toArray() {
        return [
            // 'name' => $this->person->getName();
        ];
    }

 }

Java, List only subdirectories from a directory, not files

The solution that worked for me, is missing from the list of answers. Hence I am posting this solution here:

File[]dirs = new File("/mypath/mydir/").listFiles((FileFilter)FileFilterUtils.directoryFileFilter());

Here I have used org.apache.commons.io.filefilter.FileFilterUtils from Apache commons-io-2.2.jar. Its documentation is available here: https://commons.apache.org/proper/commons-io/javadocs/api-2.2/org/apache/commons/io/filefilter/FileFilterUtils.html

How are parameters sent in an HTTP POST request?

The values are sent in the request body, in the format that the content type specifies.

Usually the content type is application/x-www-form-urlencoded, so the request body uses the same format as the query string:

parameter=value&also=another

When you use a file upload in the form, you use the multipart/form-data encoding instead, which has a different format. It's more complicated, but you usually don't need to care what it looks like, so I won't show an example, but it can be good to know that it exists.

How to iterate through range of Dates in Java?

Apache Commons

    for (Date dateIter = fromDate; !dateIter.after(toDate); dateIter = DateUtils.addDays(dateIter, 1)) {
        // ...
    }

Batch file to map a drive when the folder name contains spaces

net use "m:\Server01\my folder" /USER:mynetwork\Administrator "Mypassword" /persistent:yes 

does not work?

How to show code but hide output in RMarkdown?

For muting library("name_of_library") codes, meanly just showing the codes, {r loadlib, echo=T, results='hide', message=F, warning=F} is great. And imho a better way than library(package, warn.conflicts=F, quietly=T)

Android - how do I investigate an ANR?

Consider using the ANR-Watchdog library to accurately track and capture ANR stack traces in a high level of detail. You can then send them to your crash reporting library. I recommend using setReportMainThreadOnly() in this scenario. You can either make the app throw a non-fatal exception of the freeze point, or make the app force quit when the ANR happens.

Note that the standard ANR reports sent to your Google Play Developer console are often not accurate enough to pinpoint the exact problem. That's why a third-party library is needed.

Vue.js data-bind style backgroundImage not working

For single repeated component this technic work for me

<div class="img-section" :style=img_section_style >

computed: {
            img_section_style: function(){
                var bgImg= this.post_data.fet_img
                return {
                    "color": "red",
                    "border" : "5px solid ",
                    "background": 'url('+bgImg+')'
                }
            },
}

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

I ran into this a couple times a quarter. This time I had a minimal change summary in my git diff and tracked the problem to a reset classpath (missing my WEB-INF/lib dependency) in eclipse. This seems to occur any time I pull in or pull out parent/sibling maven projects.

There are mentions of adding your spring jars to the tomcat web container lib - this is ok and is the way most EE servers run. However be aware that by placing spring higher in the classloader tree on tomcat you will be running higher than the classloader level of your war context. I recommend you leave the libs in a per/war lower level classloader.

We see the following after a truncated .classpath after a structural project change in eclipse.

Dec 18, 2016 11:13:39 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Error configuring application listener of class org.springframework.web.context.request.RequestContextListener
java.lang.ClassNotFoundException: org.springframework.web.context.request.RequestContextListener

My classpath was reset and the WEB-INF/lib dependency was removed.

<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
    <attributes>
        <attribute name="maven.pomderived" value="true"/>
        <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
    </attributes>
</classpathentry>

put back

<attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>

and you will be OK.

thank you /michael

Detecting arrow key presses in JavaScript

Modern answer since keyCode is now deprecated in favor of key:

document.onkeydown = function (e) {
    switch (e.key) {
        case 'ArrowUp':
            // up arrow
            break;
        case 'ArrowDown':
            // down arrow
            break;
        case 'ArrowLeft':
            // left arrow
            break;
        case 'ArrowRight':
            // right arrow
    }
};

Visual C++ executable and missing MSVCR100d.dll

Debug version of the vc++ library dlls are NOT meant to be redistributed!

Debug versions of an application are not redistributable, and debug versions of the Visual C++ library DLLs are not redistributable. You may deploy debug versions of applications and Visual C++ DLLs only to your other computers, for the sole purpose of debugging and testing the applications on a computer that does not have Visual Studio installed. For more information, see Redistributing Visual C++ Files.

I will provide the link as well : http://msdn.microsoft.com/en-us/library/aa985618.aspx

Close virtual keyboard on button press

Crash Null Point Exception Fix: I had a case where the keyboard might not open when the user clicks the button. You have to write an if statement to check that getCurrentFocus() isn't a null:

            InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if(getCurrentFocus() != null) {
            inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

How to display scroll bar onto a html table

Worth noting, that depending on your purpose (mine was the autofill results of a searchbar) you may want the height to be changeable, and for the scrollbar to only exist if the height exceeds that.

If you want that, replace height: x; with max-height: x;, and overflow:scroll with overflow:auto.

Additionally, you can use overflow-x and overflow-y if you want, and obviously the same thing works horizontally with width : x;

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse

I was also facing the same problem

Download mysql-connector-java jar file

paste it in the C:\Program Files\Apache Software Foundation\Tomcat 9.0\lib

Hope this work for you also !!

How can I delete a query string parameter in JavaScript?

Assuming you want to remove key=val parameter from URI:

function removeParam(uri) {
   return uri.replace(/([&\?]key=val*$|key=val&|[?&]key=val(?=#))/, '');
}

How to get the EXIF data from a file using C#

You can use TagLib# which is used by applications such as F-Spot. Besides Exif, it will read a good amount of metadata formats for image, audio and video.

I also like ExifUtils API but it is buggy and is not actively developed.

What is a deadlock?

Lock-based concurrency control

Using locking for controlling access to shared resources is prone to deadlocks, and the transaction scheduler alone cannot prevent their occurrences.

For instance, relational database systems use various locks to guarantee transaction ACID properties.

No matter what relational database system you are using, locks will always be acquired when modifying (e.g., UPDATE or DELETE) a certain table record. Without locking a row that was modified by a currently running transaction, Atomicity would be compromised).

What is a deadlock

A deadlock happens when two concurrent transactions cannot make progress because each one waits for the other to release a lock, as illustrated in the following diagram.

Deadlock

Because both transactions are in the lock acquisition phase, neither one releases a lock prior to acquiring the next one.

Recovering from a deadlock situation

If you're using a Concurrency Control algorithm that relies on locks, then there is always the risk of running into a deadlock situation. Deadlocks can occur in any concurrency environment, not just in a database system.

For instance, a multithreading program can deadlock if two or more threads are waiting on locks that were previously acquired so that no thread can make any progress. If this happens in a Java application, the JVM cannot just force a Thread to stop its execution and release its locks.

Even if the Thread class exposes a stop method, that method has been deprecated since Java 1.1 because it can cause objects to be left in an inconsistent state after a thread is stopped. Instead, Java defines an interrupt method, which acts as a hint as a thread that gets interrupted can simply ignore the interruption and continue its execution.

For this reason, a Java application cannot recover from a deadlock situation, and it is the responsibility of the application developer to order the lock acquisition requests in such a way that deadlocks can never occur.

However, a database system cannot enforce a given lock acquisition order since it's impossible to foresee what other locks a certain transaction will want to acquire further. Preserving the lock order becomes the responsibility of the data access layer, and the database can only assist in recovering from a deadlock situation.

The database engine runs a separate process that scans the current conflict graph for lock-wait cycles (which are caused by deadlocks). When a cycle is detected, the database engine picks one transaction and aborts it, causing its locks to be released, so that the other transaction can make progress.

Unlike the JVM, a database transaction is designed as an atomic unit of work. Hence, a rollback leaves the database in a consistent state.

How to set TLS version on apache HttpClient

For HttpClient-4.1 using TLSv1.2, code would go something like this:

        SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(null, null, new SecureRandom());
        SSLSocketFactory sf = new SSLSocketFactory(sslContext);
        Scheme httpsScheme = new Scheme("https", 443, sf);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(httpsScheme);
        ClientConnectionManager cm =  new        SingleClientConnManager(schemeRegistry);
        HttpClient client = new DefaultHttpClient(cm);

       // Use client to make the connection and get the results.

When to use HashMap over LinkedList or ArrayList and vice-versa

The downfall of ArrayList and LinkedList is that when iterating through them, depending on the search algorithm, the time it takes to find an item grows with the size of the list.

The beauty of hashing is that although you sacrifice some extra time searching for the element, the time taken does not grow with the size of the map. This is because the HashMap finds information by converting the element you are searching for, directly into the index, so it can make the jump.

Long story short... LinkedList: Consumes a little more memory than ArrayList, low cost for insertions(add & remove) ArrayList: Consumes low memory, but similar to LinkedList, and takes extra time to search when large. HashMap: Can perform a jump to the value, making the search time constant for large maps. Consumes more memory and takes longer to find the value than small lists.

Darkening an image with CSS (In any shape)

I would make a new image of the dog's silhouette (black) and the rest the same as the original image. In the html, add a wrapper div with this silhouette as as background. Now, make the original image semi-transparent. The dog will become darker and the background of the dog will stay the same. You can do :hover tricks by setting the opacity of the original image to 100% on hover. Then the dog pops out when you mouse over him!

style

.wrapper{background-image:url(silhouette.png);} 
.original{opacity:0.7:}
.original:hover{opacity:1}

<div class="wrapper">
  <div class="img">
    <img src="original.png">
  </div>
</div>

Emulate Samsung Galaxy Tab

I found under website.

http://developer.samsung.com/android/tools-sdks/Samsung-GALAXY-Tab-Emulator

Extract zip file to add-ons under android sdk path. then launch Android SDK Manager. under "extras" folder check "Android + Google APIs for GALAXY Tab, API 8, revision 1" item and install package.

That's all.

Postgres - Transpose Rows to Columns

If anyone else that finds this question and needs a dynamic solution for this where you have an undefined number of columns to transpose to and not exactly 3, you can find a nice solution here: https://github.com/jumpstarter-io/colpivot

Awk if else issues

Try the code

awk '{s=($3==0)?"-":$3/$4; print s}'

How to display a confirmation dialog when clicking an <a> link?

USING PHP, HTML AND JAVASCRIPT for prompting

Just if someone looking for using php, html and javascript in a single file, the answer below is working for me.. i attached with the used of bootstrap icon "trash" for the link.

<a class="btn btn-danger" href="<?php echo "delete.php?&var=$var"; ?>" onclick="return confirm('Are you sure want to delete this?');"><span class="glyphicon glyphicon-trash"></span></a>

the reason i used php code in the middle is because i cant use it from the beginning..

the code below doesnt work for me:-

echo "<a class='btn btn-danger' href='delete.php?&var=$var' onclick='return confirm('Are you sure want to delete this?');'><span class='glyphicon glyphicon-trash'></span></a>";

and i modified it as in the 1st code then i run as just what i need.. I hope that can i can help someone inneed of my case.

How to resolve the "ADB server didn't ACK" error?

On my end, I used Resource Monitor to see which application was still listening to port 5037 after all the Eclipse and adb restart were unsuccessful for me.

Start > All Programs > Accessories > System Tools >
Resource Monitor > Network > Listening Ports

This eventually showed that java.exe was listening to port 5037, hence, preventing adb from doing so. I killed java.exe, immediately start adb (with adb start-server) and received a confirmation that adb was able to start:

android-sdks\platform-tools>adb start-server
* daemon not running. starting it now on port 5037 *
* daemon started successfully *

Custom method names in ASP.NET Web API

In case you're using ASP.NET 5 with ASP.NET MVC 6, most of these answers simply won't work because you'll normally let MVC create the appropriate route collection for you (using the default RESTful conventions), meaning that you won't find any Routes.MapRoute() call to edit at will.

The ConfigureServices() method invoked by the Startup.cs file will register MVC with the Dependency Injection framework built into ASP.NET 5: that way, when you call ApplicationBuilder.UseMvc() later in that class, the MVC framework will automatically add these default routes to your app. We can take a look of what happens behind the hood by looking at the UseMvc() method implementation within the framework source code:

public static IApplicationBuilder UseMvc(
    [NotNull] this IApplicationBuilder app,
    [NotNull] Action<IRouteBuilder> configureRoutes)
{
    // Verify if AddMvc was done before calling UseMvc
    // We use the MvcMarkerService to make sure if all the services were added.
    MvcServicesHelper.ThrowIfMvcNotRegistered(app.ApplicationServices);

    var routes = new RouteBuilder
    {
        DefaultHandler = new MvcRouteHandler(),
        ServiceProvider = app.ApplicationServices
    };

    configureRoutes(routes);

    // Adding the attribute route comes after running the user-code because
    // we want to respect any changes to the DefaultHandler.
    routes.Routes.Insert(0, AttributeRouting.CreateAttributeMegaRoute(
        routes.DefaultHandler,
        app.ApplicationServices));

    return app.UseRouter(routes.Build());
}

The good thing about this is that the framework now handles all the hard work, iterating through all the Controller's Actions and setting up their default routes, thus saving you some redundant work.

The bad thing is, there's little or no documentation about how you could add your own routes. Luckily enough, you can easily do that by using either a Convention-Based and/or an Attribute-Based approach (aka Attribute Routing).

Convention-Based

In your Startup.cs class, replace this:

app.UseMvc();

with this:

app.UseMvc(routes =>
            {
                // Route Sample A
                routes.MapRoute(
                    name: "RouteSampleA",
                    template: "MyOwnGet",
                    defaults: new { controller = "Items", action = "Get" }
                );
                // Route Sample B
                routes.MapRoute(
                    name: "RouteSampleB",
                    template: "MyOwnPost",
                    defaults: new { controller = "Items", action = "Post" }
                );
            });

Attribute-Based

A great thing about MVC6 is that you can also define routes on a per-controller basis by decorating either the Controller class and/or the Action methods with the appropriate RouteAttribute and/or HttpGet / HttpPost template parameters, such as the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;

namespace MyNamespace.Controllers
{
    [Route("api/[controller]")]
    public class ItemsController : Controller
    {
        // GET: api/items
        [HttpGet()]
        public IEnumerable<string> Get()
        {
            return GetLatestItems();
        }

        // GET: api/items/5
        [HttpGet("{num}")]
        public IEnumerable<string> Get(int num)
        {
            return GetLatestItems(5);
        }       

        // GET: api/items/GetLatestItems
        [HttpGet("GetLatestItems")]
        public IEnumerable<string> GetLatestItems()
        {
            return GetLatestItems(5);
        }

        // GET api/items/GetLatestItems/5
        [HttpGet("GetLatestItems/{num}")]
        public IEnumerable<string> GetLatestItems(int num)
        {
            return new string[] { "test", "test2" };
        }

        // POST: /api/items/PostSomething
        [HttpPost("PostSomething")]
        public IActionResult Post([FromBody]string someData)
        {
            return Content("OK, got it!");
        }
    }
}

This controller will handle the following requests:

 [GET] api/items
 [GET] api/items/5
 [GET] api/items/GetLatestItems
 [GET] api/items/GetLatestItems/5
 [POST] api/items/PostSomething

Also notice that if you use the two approaches togheter, Attribute-based routes (when defined) would override Convention-based ones, and both of them would override the default routes defined by UseMvc().

For more info, you can also read the following post on my blog.

Spring MVC: Complex object as GET @RequestParam

Yes, You can do it in a simple way. See below code of lines.

URL - http://localhost:8080/get/request/multiple/param/by/map?name='abc' & id='123'

 @GetMapping(path = "/get/request/header/by/map")
    public ResponseEntity<String> getRequestParamInMap(@RequestParam Map<String,String> map){
        // Do your business here 
        return new ResponseEntity<String>(map.toString(),HttpStatus.OK);
    } 

How to create a popup windows in javafx

Have you looked into ControlsFx Popover control.


import org.controlsfx.control.PopOver;
import org.controlsfx.control.PopOver.ArrowLocation;

private PopOver item;

final Scene scene = addItemButton.getScene();

final Point2D windowCoord = new Point2D(scene.getWindow()
        .getX(), scene.getWindow().getY());

final Point2D sceneCoord = new Point2D(scene.getX(), scene.
                getY());

final Point2D nodeCoord = addItemButton.localToScene(0.0,
                        0.0);
final double clickX = Math.round(windowCoord.getX()
    + sceneCoord.getY() + nodeCoord.getX());

final double clickY = Math.round(windowCoord.getY()
        + sceneCoord.getY() + nodeCoord.getY());
item.setContentNode(addItemScreen);
item.setArrowLocation(ArrowLocation.BOTTOM_LEFT);
item.setCornerRadius(4);                            
item.setDetachedTitle("Add New Item");
item.show(addItemButton.getParent(), clickX, clickY);

This is only an example but a PopOver sounds like it could accomplish what you want. Check out the documentation for more info.

Important note: ControlsFX will only work on JavaFX 8.0 b118 or later.

How to get the CPU Usage in C#?

It's OK, I got it! Thanks for your help!

Here is the code to do it:

private void button1_Click(object sender, EventArgs e)
{
    selectedServer = "JS000943";
    listBox1.Items.Add(GetProcessorIdleTime(selectedServer).ToString());
}

private static int GetProcessorIdleTime(string selectedServer)
{
    try
    {
        var searcher = new
           ManagementObjectSearcher
             (@"\\"+ selectedServer +@"\root\CIMV2",
              "SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor WHERE Name=\"_Total\"");

        ManagementObjectCollection collection = searcher.Get();
        ManagementObject queryObj = collection.Cast<ManagementObject>().First();

        return Convert.ToInt32(queryObj["PercentIdleTime"]);
    }
    catch (ManagementException e)
    {
        MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
    }
    return -1;
}

$(document).ready(function() is not working

I just had this issue and it was because of me trying to included jQuery via http while my page was loaded as https.

SQLite with encryption/password protection

You can use SQLite's function creation routines (PHP manual):

$db_obj->sqliteCreateFunction('Encrypt', 'MyEncryptFunction', 2);
$db_obj->sqliteCreateFunction('Decrypt', 'MyDecryptFunction', 2);

When inserting data, you can use the encryption function directly and INSERT the encrypted data or you can use the custom function and pass unencrypted data:

$insert_obj = $db_obj->prepare('INSERT INTO table (Clear, Encrypted) ' .
 'VALUES (:clear, Encrypt(:data, "' . $passwordhash_str . '"))');

When retrieving data, you can also use SQL search functionality:

$select_obj = $db_obj->prepare('SELECT Clear, ' .
 'Decrypt(Encrypted, "' . $passwordhash_str . '") AS PlainText FROM table ' .
 'WHERE PlainText LIKE :searchterm');

Comparing strings in C# with OR in an if statement

Here's a more valid way which also check if your textbox is filled with only blanks.

// When spaces are not allowed
if (string.IsNullOrWhiteSpace(txtBox1.Text) || string.IsNullOrWhiteSpace(txtBox2.Text))
  //...give error...

// When spaces are allowed
if (string.IsNullOrEmpty(txtBox1.Text) || string.IsNullOrEmpty(txtBox2.Text))
  //...give error...

The edited answer of @Habib.OSU is also fine, this is just another approach.

Adding a favicon to a static HTML page

I used convert -resize 16x16 img.png favicon.ico (on linux konsole) to convert my image, and add <link rel="icon" href="images/favicon.ico" type="image/png" sizes="16x16"> to my header and everything work perfect.

Bootstrap onClick button event

There is no show event in js - you need to bind your button either to the click event:

$('#id').on('click', function (e) {

     //your awesome code here

})

Mind that if your button is inside a form, you may prefer to bind the whole form to the submit event.

How to save MySQL query output to excel or .txt file?

You can write following codes to achieve this task:

SELECT ... FROM ... WHERE ... 
INTO OUTFILE 'textfile.csv'
FIELDS TERMINATED BY '|'

It export the result to CSV and then export it to excel sheet.

How to send a POST request in Go?

I know this is old but this answer came up in search results. For the next guy - the proposed and accepted answer works, however the code initially submitted in the question is lower-level than it needs to be. Nobody got time for that.

//one-line post request/response...
response, err := http.PostForm(APIURL, url.Values{
    "ln": {c.ln},
    "ip": {c.ip},
    "ua": {c.ua}})

//okay, moving on...
if err != nil {
  //handle postform error
}

defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)

if err != nil {
  //handle read response error
}

fmt.Printf("%s\n", string(body))

https://golang.org/pkg/net/http/#pkg-overview

How to correctly close a feature branch in Mercurial?

imho there are two cases for branches that were forgot to close

Case 1: branch was not merged into default

in this case I update to the branch and do another commit with --close-branch, unfortunatly this elects the branch to become the new tip and hence before pushing it to other clones I make sure that the real tip receives some more changes and others don't get confused about that strange tip.

hg up myBranch
hg commit --close-branch

Case 2: branch was merged into default

This case is not that much different from case 1 and it can be solved by reproducing the steps for case 1 and two additional ones.

in this case I update to the branch changeset, do another commit with --close-branch and merge the new changeset that became the tip into default. the last operation creates a new tip that is in the default branch - HOORAY!

hg up myBranch
hg commit --close-branch
hg up default
hg merge myBranch

Hope this helps future readers.

Java 8 Lambda function that throws exception?

I'm the author of a tiny lib with some generic magic to throw any Java Exception anywhere without the need of catching them nor wrapping them into RuntimeException.

Usage: unchecked(() -> methodThrowingCheckedException())

public class UncheckedExceptions {

    /**
     * throws {@code exception} as unchecked exception, without wrapping exception.
     *
     * @return will never return anything, return type is set to {@code exception} only to be able to write <code>throw unchecked(exception)</code>
     * @throws T {@code exception} as unchecked exception
     */
    @SuppressWarnings("unchecked")
    public static <T extends Throwable> T unchecked(Exception exception) throws T {
        throw (T) exception;
    }


    @FunctionalInterface
    public interface UncheckedFunction<R> {
        R call() throws Exception;
    }

    /**
     * Executes given function,
     * catches and rethrows checked exceptions as unchecked exceptions, without wrapping exception.
     *
     * @return result of function
     * @see #unchecked(Exception)
     */
    public static <R> R unchecked(UncheckedFunction<R> function) {
        try {
            return function.call();
        } catch (Exception e) {
            throw unchecked(e);
        }
    }


    @FunctionalInterface
    public interface UncheckedMethod {
        void call() throws Exception;
    }

    /**
     * Executes given method,
     * catches and rethrows checked exceptions as unchecked exceptions, without wrapping exception.
     *
     * @see #unchecked(Exception)
     */
    public static void unchecked(UncheckedMethod method) {
        try {
            method.call();
        } catch (Exception e) {
            throw unchecked(e);
        }
    }
}

source: https://github.com/qoomon/unchecked-exceptions-java

How can I generate a list or array of sequential integers in Java?

You can use the Interval class from Eclipse Collections.

List<Integer> range = Interval.oneTo(10);
range.forEach(System.out::print);  // prints 12345678910

The Interval class is lazy, so doesn't store all of the values.

LazyIterable<Integer> range = Interval.oneTo(10);
System.out.println(range.makeString(",")); // prints 1,2,3,4,5,6,7,8,9,10

Your method would be able to be implemented as follows:

public List<Integer> makeSequence(int begin, int end) {
    return Interval.fromTo(begin, end);
}

If you would like to avoid boxing ints as Integers, but would still like a list structure as a result, then you can use IntList with IntInterval from Eclipse Collections.

public IntList makeSequence(int begin, int end) {
    return IntInterval.fromTo(begin, end);
}

IntList has the methods sum(), min(), minIfEmpty(), max(), maxIfEmpty(), average() and median() available on the interface.

Update for clarity: 11/27/2017

An Interval is a List<Integer>, but it is lazy and immutable. It is extremely useful for generating test data, especially if you deal a lot with collections. If you want you can easily copy an interval to a List, Set or Bag as follows:

Interval integers = Interval.oneTo(10);
Set<Integer> set = integers.toSet();
List<Integer> list = integers.toList();
Bag<Integer> bag = integers.toBag();

An IntInterval is an ImmutableIntList which extends IntList. It also has converter methods.

IntInterval ints = IntInterval.oneTo(10);
IntSet set = ints.toSet();
IntList list = ints.toList();
IntBag bag = ints.toBag();

An Interval and an IntInterval do not have the same equals contract.

Update for Eclipse Collections 9.0

You can now create primitive collections from primitive streams. There are withAll and ofAll methods depending on your preference. If you are curious, I explain why we have both here. These methods exist for mutable and immutable Int/Long/Double Lists, Sets, Bags and Stacks.

Assert.assertEquals(
        IntInterval.oneTo(10),
        IntLists.mutable.withAll(IntStream.rangeClosed(1, 10)));

Assert.assertEquals(
        IntInterval.oneTo(10),
        IntLists.immutable.withAll(IntStream.rangeClosed(1, 10)));

Note: I am a committer for Eclipse Collections

Vue.js : How to set a unique ID for each component instance?

If your uid is not used by other compoment, I have an idea.

uid: Math.random()

Simple and enough.

Get current folder path

This works best for me, especially when using dotnet core single file publish. Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName).

Accessing @attribute from SimpleXML

I used before so many times for getting @attributes like below and it was a little bit longer.

$att = $xml->attributes();
echo $att['field'];

It should be more easy and you can get attributes following format only at once:

Standard Way - Array-Access Attributes (AAA)

$xml['field'];

Other alternatives are:

Right & Quick Format

$xml->attributes()->{'field'};

Wrong Formats

$xml->attributes()->field;
$xml->{"@attributes"}->field;
$xml->attributes('field');
$xml->attributes()['field'];
$xml->attributes->['field'];

Switch role after connecting to database

--create a user that you want to use the database as:

create role neil;

--create the user for the web server to connect as:

create role webgui noinherit login password 's3cr3t';

--let webgui set role to neil:

grant neil to webgui; --this looks backwards but is correct.

webgui is now in the neil group, so webgui can call set role neil . However, webgui did not inherit neil's permissions.

Later, login as webgui:

psql -d some_database -U webgui
(enter s3cr3t as password)

set role neil;

webgui does not need superuser permission for this.

You want to set role at the beginning of a database session and reset it at the end of the session. In a web app, this corresponds to getting a connection from your database connection pool and releasing it, respectively. Here's an example using Tomcat's connection pool and Spring Security:

public class SetRoleJdbcInterceptor extends JdbcInterceptor {

    @Override
    public void reset(ConnectionPool connectionPool, PooledConnection pooledConnection) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if(authentication != null) {
            try {

                /* 
                  use OWASP's ESAPI to encode the username to avoid SQL Injection. Can't use parameters with SET ROLE. Need to write PG codec.

                  Or use a whitelist-map approach
                */
                String username = ESAPI.encoder().encodeForSQL(MY_CODEC, authentication.getName());

                Statement statement = pooledConnection.getConnection().createStatement();
                statement.execute("set role \"" + username + "\"");
                statement.close();
            } catch(SQLException exp){
                throw new RuntimeException(exp);
            }
        }
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        if("close".equals(method.getName())){
            Statement statement = ((Connection)proxy).createStatement();
            statement.execute("reset role");
            statement.close();
        }

        return super.invoke(proxy, method, args);
    }
}

Given a DateTime object, how do I get an ISO 8601 date in string format?

To convert DateTime.UtcNow to a string representation of yyyy-MM-ddTHH:mm:ssZ, you can use the ToString() method of the DateTime structure with a custom formatting string. When using custom format strings with a DateTime, it is important to remember that you need to escape your seperators using single quotes.

The following will return the string represention you wanted:

DateTime.UtcNow.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", DateTimeFormatInfo.InvariantInfo)

What is an opaque response, and what purpose does it serve?

Opaque responses can't be accessed by JavaScript, but you can still cache them with the Cache API and respond with them in the fetch event handler in a service worker. So they're useful for making your app offline, also for resources that you can't control (e.g. resources on a CDN that doesn't set the CORS headers).

Calling the base constructor in C#

Modify your constructor to the following so that it calls the base class constructor properly:

public class MyExceptionClass : Exception
{
    public MyExceptionClass(string message, string extrainfo) : base(message)
    {
        //other stuff here
    }
}

Note that a constructor is not something that you can call anytime within a method. That's the reason you're getting errors in your call in the constructor body.

How To Run PHP From Windows Command Line in WAMPServer

Try using batch file

  1. Open notepad
  2. type php -S localhost:8000
  3. save file as .bat extension, server.bat
  4. now click on server.bat file your server is ready on http://localhost:8000

Dependency

if you got error php not recognize any internal or external command then goto environment variable and edit path to php.exe "C:\wamp\bin\php\php5.4.3"

PHP Echo a large block of text

Just break out where you need to.

<html>
(html code)
<?php
(php code)
?>
(html code)
</html>

Do not use shortened-form. <? conflicts with XML and is disabled by default on most servers.

How can I download a specific Maven artifact in one command line?

one liner to download latest maven artifact without mvn:

curl -O -J -L  "https://repository.sonatype.org/service/local/artifact/maven/content?r=central-proxy&g=io.staticcdn.sdk&a=staticcdn-sdk-standalone-optimizer&e=zip&v=LATEST"

How to add new DataRow into DataTable?

You can try with this code - based on Rows.Add method

DataTable table = new DataTable();
DataRow row = table.NewRow();
table.Rows.Add(row);

Link : https://msdn.microsoft.com/en-us/library/9yfsd47w.aspx

How to update two tables in one statement in SQL Server 2005?

For general updating table1 specific colom based on Table2 specific colom, below query works perfectly...

UPDATE table 1  
SET Col 2 = t2.Col2,  
Col 3 = t2.Col3  
FROM table1 t1  
INNER JOIN table 2 t2 ON t1.Col1 = t2.col1 

Telling gcc directly to link a library statically

You can add .a file in the linking command:

  gcc yourfiles /path/to/library/libLIBRARY.a

But this is not talking with gcc driver, but with ld linker as options like -Wl,anything are.

When you tell gcc or ld -Ldir -lLIBRARY, linker will check both static and dynamic versions of library (you can see a process with -Wl,--verbose). To change order of library types checked you can use -Wl,-Bstatic and -Wl,-Bdynamic. Here is a man page of gnu LD: http://linux.die.net/man/1/ld

To link your program with lib1, lib3 dynamically and lib2 statically, use such gcc call:

gcc program.o -llib1 -Wl,-Bstatic -llib2 -Wl,-Bdynamic -llib3

Assuming that default setting of ld is to use dynamic libraries (it is on Linux).

Check if a Postgres JSON array contains a string

You could use @> operator to do this something like

SELECT info->>'name'
FROM rabbits
WHERE info->'food' @> '"carrots"';

How can I export the schema of a database in PostgreSQL?

You should take a look at pg_dump:

pg_dump -s databasename

Will dump only the schema to stdout as .sql.

For windows, you'll probably want to call pg_dump.exe. I don't have access to a Windows machine but I'm pretty sure from memory that's the command. See if the help works for you too.

Is there a way to make a DIV unselectable?

Wouldn't a simple background image for the textarea suffice?

Import CSV to SQLite

Follow the steps:-

  1. 1] sqlite3 name 2] .mode csv tablename 3] .import Filename.csv tablename

Activity restart on rotation Android

I just discovered this lore:

For keeping the Activity alive through an orientation change, and handling it through onConfigurationChanged, the documentation and the code sample above suggest this in the Manifest file:

<activity android:name=".MyActivity"
      android:configChanges="orientation|keyboardHidden"
      android:label="@string/app_name">

which has the extra benefit that it always works.

The bonus lore is that omitting the keyboardHidden may seem logical, but it causes failures in the emulator (for Android 2.1 at least): specifying only orientation will make the emulator call both OnCreate and onConfigurationChanged sometimes, and only OnCreate other times.

I haven't seen the failure on a device, but I have heard about the emulator failing for others. So it's worth documenting.

Starting a shell in the Docker Alpine container

In case the container is already running:

docker exec -it container_id_or_name ash

SQL Server Service not available in service list after installation of SQL Server Management Studio

downloaded Sql server management 2008 r2 and got it installed. Its getting installed but when I try to connect it via .\SQLEXPRESS it shows error. DO I need to install any SQL service on my system?

You installed management studio which is just a management interface to SQL Server. If you didn't (which is what it seems like) already have SQL Server installed, you'll need to install it in order to have it on your system and use it.

http://www.microsoft.com/en-us/download/details.aspx?id=1695

Printing Batch file results to a text file

For Print Result to text file

we can follow

echo "test data" > test.txt

This will create test.txt file and written "test data"

If you want to append then

echo "test data" >> test.txt

CSS background-image not working

<span class="btn-pTool">
         <a class="btn-pToolName" href="#"></a>
     </span>

Try to add display:block to .btn-pTool, and give it a width and height.

Also in your code both tbn-pTool and btn-pToolName have no text content, so that may result in them not being displayed at all.

You can try to force come content in them this way

.btn-pTool, .btn-pToolName {
    content: " ";
}

How to display request headers with command line curl

the -v option for curl is too verbose in the error output which contains the leading *(status line) or >(request head field) or <(response head field). to get only the request head field:

curl -v -sS www.stackoverflow.com 2>&1 >/dev/null | grep '>' | cut -c1-2 --complement

to get only the request head field:

curl -v -sS www.stackoverflow.com 2>&1 >/dev/null | grep '<' | cut -c1-2 --complement

or to dump it into /tmp/test.txt file with the -D option

curl -D /tmp/test.txt -sS www.stackoverflow.com > /dev/null

in order to filter the -v output, you should direct the error output to terminal and the std output to /dev/null, the -s option is to forbid the progress metering

Best timestamp format for CSV/Excel?

Try MM/dd/yyyy hh:mm:ss a format.

Java code to create XML file.

xmlResponse.append("mydate>").append(this.formatDate(resultSet.getTimestamp("date"), "MM/dd/yyyy hh:mm:ss a")).append("");

public String formatDate(Date date, String format)
{
    String dateString = "";
    if(null != date)
    {
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        dateString = dateFormat.format(date);
    }
    return dateString;
}

How to convert an address into a Google Maps Link (NOT MAP)

Feb, 2016:

I needed to do this based on client entered database values and without a lat/long generator. Google really likes lat/long these days. Here is what I learned:

1 The beginning of the link looks like this: https://www.google.com/maps/place/

2 Then you put your address:

  • Use a + instead of any space.
  • Put a comma , in front and behind the city.
  • Include the postal/zip and the province/state.
  • Replace any # with nothing.
  • Replace any ++ or ++++ with single +

3 Put the address after the place/

4 Then put a slash at the end.

NOTE: The slash at the end was important. After the user clicks the link, Google goes ahead and appends more to the URL and they do it after this slash.

Working example for this question:

https://www.google.ca/maps/place/1200+Pennsylvania+Ave+SE,+Washington,+DC+20003/

I hope that helps.

MySQL INNER JOIN Alias

Use a seperate column to indicate the join condition

SELECT  t.importid, 
        case 
            when t.importid = g.home 
            then 'home' 
            else 'away' 
        end as join_condition, 
        g.network, 
        g.date_start 
FROM    game g
INNER JOIN team t ON (t.importid = g.home OR t.importid = g.away)
ORDER BY date_start DESC 
LIMIT 7

How to query SOLR for empty fields?

Try this:

?q=-id:["" TO *]

Trying to use Spring Boot REST to Read JSON String from POST

To receive arbitrary Json in Spring-Boot, you can simply use Jackson's JsonNode. The appropriate converter is automatically configured.

    @PostMapping(value="/process")
    public void process(@RequestBody com.fasterxml.jackson.databind.JsonNode payload) {
        System.out.println(payload);
    }

Extracting an attribute value with beautifulsoup

If you want to retrieve multiple values of attributes from the source above, you can use findAll and a list comprehension to get everything you need:

import urllib
f = urllib.urlopen("http://58.68.130.147")
s = f.read()
f.close()

from BeautifulSoup import BeautifulStoneSoup
soup = BeautifulStoneSoup(s)

inputTags = soup.findAll(attrs={"name" : "stainfo"})
### You may be able to do findAll("input", attrs={"name" : "stainfo"})

output = [x["stainfo"] for x in inputTags]

print output
### This will print a list of the values.

Android: Difference between onInterceptTouchEvent and dispatchTouchEvent?

public boolean dispatchTouchEvent(MotionEvent ev){
    boolean consume =false;
    if(onInterceptTouchEvent(ev){
        consume = onTouchEvent(ev);
    }else{
        consume = child.dispatchTouchEvent(ev);
    }
}

Iterating over a 2 dimensional python list

same way you did the fill in, but reverse the indexes:

>>> for j in range(columns):
...     for i in range(rows):
...        print mylist[i][j],
... 
0,0 1,0 2,0 0,1 1,1 2,1
>>> 

Change Volley timeout duration

req.setRetryPolicy(new DefaultRetryPolicy(
    MY_SOCKET_TIMEOUT_MS, 
    DefaultRetryPolicy.DEFAULT_MAX_RETRIES, 
    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

You can set MY_SOCKET_TIMEOUT_MS as 100. Whatever you want to set this to is in milliseconds. DEFAULT_MAX_RETRIES can be 0 default is 1.

How to make return key on iPhone make keyboard disappear?

When the return key is pressed, call:

[uitextfield resignFirstResponder];

How to add multiple jar files in classpath in linux

For linux users, you should know the following:

  1. $CLASSPATH is specifically what Java uses to look through multiple directories to find all the different classes it needs for your script (unless you explicitly tell it otherwise with the -cp override). Using -cp (--classpath) requires that you keep track of all the directories manually and copy-paste that line every time you run the program (not preferable IMO).

  2. The colon (":") character separates the different directories. There is only one $CLASSPATH and it has all the directories in it. So, when you run "export CLASSPATH=...." you want to include the current value "$CLASSPATH" in order to append to it. For example:

    export CLASSPATH=.
    export CLASSPATH=$CLASSPATH:/usr/share/java/mysql-connector-java-5.1.12.jar
    

    In the first line above, you start CLASSPATH out with just a simple 'dot' which is the path to your current working directory. With that, whenever you run java it will look in the current working directory (the one you're in) for classes. In the second line above, $CLASSPATH grabs the value that you previously entered (.) and appends the path to a mysql dirver. Now, java will look for the driver AND for your classes.

  3. echo $CLASSPATH
    

    is super handy, and what it returns should read like a colon-separated list of all the directories you want java looking in for what it needs to run your script.

  4. Tomcat does not use CLASSPATH. Read what to do about that here: https://tomcat.apache.org/tomcat-8.0-doc/class-loader-howto.html

Unable to preventDefault inside passive event listener

I am getting this issue when using owl carousal and scrolling the images.

So get solved just adding below CSS in your page.

.owl-carousel {
-ms-touch-action: pan-y;
touch-action: pan-y;
}

or

.owl-carousel {
-ms-touch-action: none;
touch-action: none;
}

How to set the size of a column in a Bootstrap responsive table

You could use inline styles and define the width in the <th> tag. Make it so that the sum of the widths = 100%.

    <tr>
        <th style="width:10%">Size</th>
        <th style="width:30%">Bust</th>
        <th style="width:50%">Waist</th>
        <th style="width:10%">Hips</th>
    </tr>

Bootply demo

Typically using inline styles is not ideal, however this does provide flexibility because you can get very specific and granular with exact widths.

What is wrong with this code that uses the mysql extension to fetch data from a database in PHP?

  1. Select a database with identifier mysql_select_db("form1",$connect);

  2. Are you getting syntax error? If please put a ; next to $comment = $rows['Comment'].

  3. Also the variables should be case sensitive here

How do I force git pull to overwrite everything on every pull?

You could try this:

git reset --hard HEAD
git pull

(from How do I force "git pull" to overwrite local files?)

Another idea would be to delete the entire git and make a new clone.

"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"

In case you want to see what this all means, here is a blow-by-blow of everything:

CREATE TABLE `users_partners` (
  `uid` int(11) NOT NULL DEFAULT '0',
  `pid` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`uid`,`pid`),
  KEY `partner_user` (`pid`,`uid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8

Primary key is based on both columns of this quick reference table. A Primary key requires unique values.

Let's begin:

INSERT INTO users_partners (uid,pid) VALUES (1,1);
...1 row(s) affected

INSERT INTO users_partners (uid,pid) VALUES (1,1);
...Error Code : 1062
...Duplicate entry '1-1' for key 'PRIMARY'

INSERT IGNORE INTO users_partners (uid,pid) VALUES (1,1);
...0 row(s) affected

INSERT INTO users_partners (uid,pid) VALUES (1,1) ON DUPLICATE KEY UPDATE uid=uid
...0 row(s) affected

note, the above saved too much extra work by setting the column equal to itself, no update actually needed

REPLACE INTO users_partners (uid,pid) VALUES (1,1)
...2 row(s) affected

and now some multiple row tests:

INSERT INTO users_partners (uid,pid) VALUES (1,1),(1,2),(1,3),(1,4)
...Error Code : 1062
...Duplicate entry '1-1' for key 'PRIMARY'

INSERT IGNORE INTO users_partners (uid,pid) VALUES (1,1),(1,2),(1,3),(1,4)
...3 row(s) affected

no other messages were generated in console, and it now has those 4 values in the table data. I deleted everything except (1,1) so I could test from the same playing field

INSERT INTO users_partners (uid,pid) VALUES (1,1),(1,2),(1,3),(1,4) ON DUPLICATE KEY UPDATE uid=uid
...3 row(s) affected

REPLACE INTO users_partners (uid,pid) VALUES (1,1),(1,2),(1,3),(1,4)
...5 row(s) affected

So there you have it. Since this was all performed on a fresh table with nearly no data and not in production, the times for execution were microscopic and irrelevant. Anyone with real-world data would be more than welcome to contribute it.

Why is this printing 'None' in the output?

Because of double print function. I suggest you to use return instead of print inside the function definition.

def lyrics():
    return "The very first line"
print(lyrics())

OR

def lyrics():
    print("The very first line")
lyrics()

\n or \n in php echo not print

\n must be in double quotes!

 echo '<p>' . $unit1 . "</p>\n";

What charset does Microsoft Excel use when saving files?

Waking up this old thread... We are now in 2017. And still Excel is unable to save a simple spreadsheet into a CSV format while preserving the original encoding ... Just amazing.

Luckily Google Docs lives in the right century. The solution for me is just to open the spreadsheet using Google Docs, than download it back down as CSV. The result is a correctly encoded CSV file (with all strings encoded in UTF8).

Show which git tag you are on?

Show all tags on current HEAD (or commit)

git tag --points-at HEAD

Primitive type 'short' - casting in Java

EDIT: Okay, now we know it's Java...

Section 4.2.2 of the Java Language Specification states:

The Java programming language provides a number of operators that act on integral values:

[...]

  • The numerical operators, which result in a value of type int or long:
  • [...]
  • The additive operators + and - (§15.18)

  • In other words, it's like C# - the addition operator (when applied to integral types) only ever results in int or long, which is why you need to cast to assign to a short variable.

    Original answer (C#)

    In C# (you haven't specified the language, so I'm guessing), the only addition operators on primitive types are:

    int operator +(int x, int y);
    uint operator +(uint x, uint y);
    long operator +(long x, long y);
    ulong operator +(ulong x, ulong y);
    float operator +(float x, float y);
    double operator +(double x, double y);
    

    These are in the C# 3.0 spec, section 7.7.4. In addition, decimal addition is defined:

    decimal operator +(decimal x, decimal y);
    

    (Enumeration addition, string concatenation and delegate combination are also defined there.)

    As you can see, there's no short operator +(short x, short y) operator - so both operands are implicitly converted to int, and the int form is used. That means the result is an expression of type "int", hence the need to cast.

    Xcode 5 and iOS 7: Architecture and Valid architectures

    Set the architecture in build setting to Standard architectures(armv7,armv7s)

    enter image description here

    iPhone 5S is powered by A7 64bit processor. From apple docs

    Xcode can build your app with both 32-bit and 64-bit binaries included. This combined binary requires a minimum deployment target of iOS 7 or later.

    Note: A future version of Xcode will let you create a single app that supports the 32-bit runtime on iOS 6 and later, and that supports the 64-bit runtime on iOS 7.

    From the documentation what i understood is

    • Xcode can create both 64bit 32bit binaries for a single app but the deployment target should be iOS7. They are saying in future it will be iOS 6.0
    • 32 bit binary will work fine in iPhone 5S(64 bit processor).

    Update (Xcode 5.0.1)
    In Xcode 5.0.1 they added the support to create 64 bit binary for iOS 5.1.1 onwards.

    Xcode 5.0.1 can build your app with both 32-bit and 64-bit binaries included. This combined binary requires a minimum deployment target of iOS 5.1.1 or later. The 64-bit binary runs only on 64-bit devices running iOS 7.0.3 and later.

    Update (Xcode 5.1)
    Xcode 5.1 made significant change in the architecture section. This answer will be a followup for you. Check this

    Creating a 3D sphere in Opengl using Visual C++

    Datanewolf's code is ALMOST right. I had to reverse both the winding and the normals to make it work properly with the fixed pipeline. The below works correctly with cull on or off for me:

    std::vector<GLfloat> vertices;
    std::vector<GLfloat> normals;
    std::vector<GLfloat> texcoords;
    std::vector<GLushort> indices;
    
    float const R = 1./(float)(rings-1);
    float const S = 1./(float)(sectors-1);
    int r, s;
    
    vertices.resize(rings * sectors * 3);
    normals.resize(rings * sectors * 3);
    texcoords.resize(rings * sectors * 2);
    std::vector<GLfloat>::iterator v = vertices.begin();
    std::vector<GLfloat>::iterator n = normals.begin();
    std::vector<GLfloat>::iterator t = texcoords.begin();
    for(r = 0; r < rings; r++) for(s = 0; s < sectors; s++) {
        float const y = sin( -M_PI_2 + M_PI * r * R );
        float const x = cos(2*M_PI * s * S) * sin( M_PI * r * R );
        float const z = sin(2*M_PI * s * S) * sin( M_PI * r * R );
    
        *t++ = s*S;
        *t++ = r*R;
    
        *v++ = x * radius;
        *v++ = y * radius;
        *v++ = z * radius;
    
        *n++ = -x;
        *n++ = -y;
        *n++ = -z;
    }
    
    indices.resize(rings * sectors * 4);
    std::vector<GLushort>::iterator i = indices.begin();
    for(r = 0; r < rings-1; r++)
        for(s = 0; s < sectors-1; s++) {
           /* 
            *i++ = r * sectors + s;
            *i++ = r * sectors + (s+1);
            *i++ = (r+1) * sectors + (s+1);
            *i++ = (r+1) * sectors + s;
            */
             *i++ = (r+1) * sectors + s;
             *i++ = (r+1) * sectors + (s+1);
            *i++ = r * sectors + (s+1);
             *i++ = r * sectors + s;
    
    }
    

    Edit: There was a question on how to draw this... in my code I encapsulate these values in a G3DModel class. This is my code to setup the frame, draw the model, and end it:

    void GraphicsProvider3DPriv::BeginFrame()const{
            int win_width;
            int win_height;// framework of choice here
            glfwGetWindowSize(window, &win_width, &win_height); // retrieve window
            float const win_aspect = (float)win_width / (float)win_height;
            // set lighting
            glEnable(GL_LIGHTING);
            glEnable(GL_LIGHT0);
            glEnable(GL_DEPTH_TEST);
            GLfloat lightpos[] = {0, 0.0, 0, 0.};
            glLightfv(GL_LIGHT0, GL_POSITION, lightpos);
            GLfloat lmodel_ambient[] = { 0.2, 0.2, 0.2, 1.0 };
            glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
            glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
            // set up world transform
            glClearColor(0.f, 0.f, 0.f, 1.f);
            glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT|GL_ACCUM_BUFFER_BIT);
            glMatrixMode(GL_PROJECTION);
            glLoadIdentity();
    
            gluPerspective(45, win_aspect, 1, 10);
    
            glMatrixMode(GL_MODELVIEW);
    
        }
    
    
        void GraphicsProvider3DPriv::DrawModel(const G3DModel* model, const Transform3D transform)const{
            G3DModelPriv* privModel = (G3DModelPriv *)model;
            glPushMatrix();
            glLoadMatrixf(transform.GetOGLData());
    
            glEnableClientState(GL_VERTEX_ARRAY);
            glEnableClientState(GL_NORMAL_ARRAY);
            glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    
            glVertexPointer(3, GL_FLOAT, 0, &privModel->vertices[0]);
            glNormalPointer(GL_FLOAT, 0, &privModel->normals[0]);
            glTexCoordPointer(2, GL_FLOAT, 0, &privModel->texcoords[0]);
    
            glEnable(GL_TEXTURE_2D);
            //glFrontFace(GL_CCW);
            glEnable(GL_CULL_FACE);
            glActiveTexture(GL_TEXTURE0);
            glBindTexture(GL_TEXTURE_2D, privModel->texname);
    
            glDrawElements(GL_QUADS, privModel->indices.size(), GL_UNSIGNED_SHORT, &privModel->indices[0]);
            glPopMatrix();
            glDisable(GL_TEXTURE_2D);
    
        }
    
        void GraphicsProvider3DPriv::EndFrame()const{
            /* Swap front and back buffers */
            glDisable(GL_LIGHTING);
            glDisable(GL_LIGHT0);
            glDisable(GL_CULL_FACE);
            glfwSwapBuffers(window);
    
            /* Poll for and process events */
            glfwPollEvents();
        }
    

    How can I open two pages from a single click without using JavaScript?

    also you can open more than two page try this

    `<a href="http://www.microsoft.com" target="_blank" onclick="window.open('http://www.google.com'); window.open('http://www.yahoo.com');">Click Here</a>`
    

    Rails: How do I create a default value for attributes in Rails activerecord's model?

    The solution depends on a few things.

    Is the default value dependent on other information available at creation time? Can you wipe the database with minimal consequences?

    If you answered the first question yes, then you want to use Jim's solution

    If you answered the second question yes, then you want to use Daniel's solution

    If you answered no to both questions, you're probably better off adding and running a new migration.

    class AddDefaultMigration < ActiveRecord::Migration
      def self.up
         change_column :tasks, :status, :string, :default => default_value, :null => false
      end
    end
    

    :string can be replaced with any type that ActiveRecord::Migration recognizes.

    CPU is cheap so the redefinition of Task in Jim's solution isn't going to cause many problems. Especially in a production environment. This migration is proper way of doing it as it is loaded it and called much less often.

    Solving sslv3 alert handshake failure when trying to use a client certificate

    What SSL private key should be sent along with the client certificate?

    None of them :)

    One of the appealing things about client certificates is it does not do dumb things, like transmit a secret (like a password), in the plain text to a server (HTTP basic_auth). The password is still used to unlock the key for the client certificate, its just not used directly to during exchange or tp authenticate the client.

    Instead, the client chooses a temporary, random key for that session. The client then signs the temporary, random key with his cert and sends it to the server (some hand waiving). If a bad guy intercepts anything, its random so it can't be used in the future. It can't even be used for a second run of the protocol with the server because the server will select a new, random value, too.


    Fails with: error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure

    Use TLS 1.0 and above; and use Server Name Indication.

    You have not provided any code, so its not clear to me how to tell you what to do. Instead, here's the OpenSSL command line to test it:

    openssl s_client -connect www.example.com:443 -tls1 -servername www.example.com \
        -cert mycert.pem -key mykey.pem -CAfile <certificate-authority-for-service>.pem
    

    You can also use -CAfile to avoid the “verify error:num=20”. See, for example, “verify error:num=20” when connecting to gateway.sandbox.push.apple.com.

    How to make a checkbox checked with jQuery?

    You don't need to control your checkBoxes with jQuery. You can do it with some simple JavaScript.

    This JS snippet should work fine:

    document.TheFormHere.test.Value = true;

    How to call a View Controller programmatically?

    Import the view controller class which you want to show and use the following code

    KartViewController *viewKart = [[KartViewController alloc]initWithNibName:@"KartViewController" bundle:nil];
    [self presentViewController:viewKart animated:YES completion:nil];
    

    Why is “while ( !feof (file) )” always wrong?

    It's wrong because (in the absence of a read error) it enters the loop one more time than the author expects. If there is a read error, the loop never terminates.

    Consider the following code:

    /* WARNING: demonstration of bad coding technique!! */
    
    #include <stdio.h>
    #include <stdlib.h>
    
    FILE *Fopen(const char *path, const char *mode);
    
    int main(int argc, char **argv)
    {
        FILE *in;
        unsigned count;
    
        in = argc > 1 ? Fopen(argv[1], "r") : stdin;
        count = 0;
    
        /* WARNING: this is a bug */
        while( !feof(in) ) {  /* This is WRONG! */
            fgetc(in);
            count++;
        }
        printf("Number of characters read: %u\n", count);
        return EXIT_SUCCESS;
    }
    
    FILE * Fopen(const char *path, const char *mode)
    {
        FILE *f = fopen(path, mode);
        if( f == NULL ) {
            perror(path);
            exit(EXIT_FAILURE);
        }
        return f;
    }
    

    This program will consistently print one greater than the number of characters in the input stream (assuming no read errors). Consider the case where the input stream is empty:

    $ ./a.out < /dev/null
    Number of characters read: 1
    

    In this case, feof() is called before any data has been read, so it returns false. The loop is entered, fgetc() is called (and returns EOF), and count is incremented. Then feof() is called and returns true, causing the loop to abort.

    This happens in all such cases. feof() does not return true until after a read on the stream encounters the end of file. The purpose of feof() is NOT to check if the next read will reach the end of file. The purpose of feof() is to determine the status of a previous read function and distinguish between an error condition and the end of the data stream. If fread() returns 0, you must use feof/ferror to decide whether an error occurred or if all of the data was consumed. Similarly if fgetc returns EOF. feof() is only useful after fread has returned zero or fgetc has returned EOF. Before that happens, feof() will always return 0.

    It is always necessary to check the return value of a read (either an fread(), or an fscanf(), or an fgetc()) before calling feof().

    Even worse, consider the case where a read error occurs. In that case, fgetc() returns EOF, feof() returns false, and the loop never terminates. In all cases where while(!feof(p)) is used, there must be at least a check inside the loop for ferror(), or at the very least the while condition should be replaced with while(!feof(p) && !ferror(p)) or there is a very real possibility of an infinite loop, probably spewing all sorts of garbage as invalid data is being processed.

    So, in summary, although I cannot state with certainty that there is never a situation in which it may be semantically correct to write "while(!feof(f))" (although there must be another check inside the loop with a break to avoid a infinite loop on a read error), it is the case that it is almost certainly always wrong. And even if a case ever arose where it would be correct, it is so idiomatically wrong that it would not be the right way to write the code. Anyone seeing that code should immediately hesitate and say, "that's a bug". And possibly slap the author (unless the author is your boss in which case discretion is advised.)

    Adding null values to arraylist

    You could create Util class:

    public final class CollectionHelpers {
        public static <T> boolean addNullSafe(List<T> list, T element) {
            if (list == null || element == null) {
                return false;
            }
    
            return list.add(element);
        }
    }
    

    And then use it:

    Element element = getElementFromSomeWhere(someParameter);
    List<Element> arrayList = new ArrayList<>();
    CollectionHelpers.addNullSafe(list, element);
    

    Create a global variable in TypeScript

    I found a way that works if I use JavaScript combined with TypeScript.

    logging.d.ts:

    declare var log: log4javascript.Logger;
    

    log-declaration.js:

    log = null;
    

    initalize-app.ts

    import './log-declaration.js';
    
    // Call stuff to actually setup log.  
    // Similar to this:
    log = functionToSetupLog();
    

    This puts it in the global scope and TypeScript knows about it. So I can use it in all my files.

    NOTE: I think this only works because I have the allowJs TypeScript option set to true.

    If someone posts an pure TypeScript solution, I will accept that.

    Drop all tables command

    I had the same problem with SQLite and Android. Here is my Solution:

    List<String> tables = new ArrayList<String>();
    Cursor cursor = db.rawQuery("SELECT * FROM sqlite_master WHERE type='table';", null);
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        String tableName = cursor.getString(1);
        if (!tableName.equals("android_metadata") &&
                !tableName.equals("sqlite_sequence"))
            tables.add(tableName);
        cursor.moveToNext();
    }
    cursor.close();
    
    for(String tableName:tables) {
        db.execSQL("DROP TABLE IF EXISTS " + tableName);
    }
    

    Get the current date in java.sql.Date format

    Simply in one line:

    java.sql.Date date = new java.sql.Date(Calendar.getInstance().getTime().getTime());
    

    Meaning of = delete after function declaration

    New C++0x standard. Please see section 8.4.3 in the N3242 working draft

    Character Limit in HTML

    there's a maxlength attribute

    <input type="text" name="textboxname" maxlength="100" />
    

    SecurityError: Blocked a frame with origin from accessing a cross-origin frame

    If you have control over the content of the iframe - that is, if it is merely loaded in a cross-origin setup such as on Amazon Mechanical Turk - you can circumvent this problem with the <body onload='my_func(my_arg)'> attribute for the inner html.

    For example, for the inner html, use the this html parameter (yes - this is defined and it refers to the parent window of the inner body element):

    <body onload='changeForm(this)'>

    In the inner html :

        function changeForm(window) {
            console.log('inner window loaded: do whatever you want with the inner html');
            window.document.getElementById('mturk_form').style.display = 'none';
        </script>
    

    Sending email with gmail smtp with codeigniter email library

    send html email via codeiginater

        $this->load->library('email');
        $this->load->library('parser');
    
    
    
        $this->email->clear();
        $config['mailtype'] = "html";
        $this->email->initialize($config);
        $this->email->set_newline("\r\n");
        $this->email->from('[email protected]', 'Website');
        $list = array('[email protected]', '[email protected]');
        $this->email->to($list);
        $data = array();
        $htmlMessage = $this->parser->parse('messages/email', $data, true);
        $this->email->subject('This is an email test');
        $this->email->message($htmlMessage);
    
    
    
        if ($this->email->send()) {
            echo 'Your email was sent, thanks chamil.';
        } else {
            show_error($this->email->print_debugger());
        }
    

    Any way to select without causing locking in MySQL?

    another way to enable dirty read in mysql is add hint: LOCK IN SHARE MODE

    SELECT * FROM TABLE_NAME LOCK IN SHARE MODE; 
    

    MYSQL: How to copy an entire row from one table to another in mysql with the second table having one extra column?

    INSERT INTO dues_storage
    SELECT field1, field2, ..., fieldN, CURRENT_DATE()
    FROM dues
    WHERE id = 5;
    

    Indentation shortcuts in Visual Studio

    You can just use Tab and Shift+Tab

    How do I calculate someone's age based on a DateTime type birthday?

    Here is a very simple and easy to follow example.

    private int CalculateAge()
    {
    //get birthdate
       DateTime dtBirth = Convert.ToDateTime(BirthDatePicker.Value);
       int byear = dtBirth.Year;
       int bmonth = dtBirth.Month;
       int bday = dtBirth.Day;
       DateTime dtToday = DateTime.Now;
       int tYear = dtToday.Year;
       int tmonth = dtToday.Month;
       int tday = dtToday.Day;
       int age = tYear - byear;
       if (bmonth < tmonth)
           age--;
       else if (bmonth == tmonth && bday>tday)
       {
           age--;
       }
    return age;
    }
    

    if statements matching multiple values

    Is this what you are looking for ?

    if (new int[] { 1, 2, 3, 4, 5 }.Contains(value))
    

    Why can't I declare static methods in an interface?

    The reason lies in the design-principle, that java does not allow multiple inheritance. The problem with multiple inheritance can be illustrated by the following example:

    public class A {
       public method x() {...}
    }
    public class B {
       public method x() {...}
    }
    public class C extends A, B { ... }
    

    Now what happens if you call C.x()? Will be A.x() or B.x() executed? Every language with multiple inheritance has to solve this problem.

    Interfaces allow in Java some sort of restricted multiple inheritance. To avoid the problem above, they are not allowed to have methods. If we look at the same problem with interfaces and static methods:

    public interface A {
       public static method x() {...}
    }
    public interface B {
       public static method x() {...}
    }
    public class C implements A, B { ... }
    

    Same problem here, what happen if you call C.x()?

    Scatter plot with error bars

    First of all: it is very unfortunate and surprising that R cannot draw error bars "out of the box".

    Here is my favourite workaround, the advantage is that you do not need any extra packages. The trick is to draw arrows (!) but with little horizontal bars instead of arrowheads (!!!). This not-so-straightforward idea comes from the R Wiki Tips and is reproduced here as a worked-out example.

    Let's assume you have a vector of "average values" avg and another vector of "standard deviations" sdev, they are of the same length n. Let's make the abscissa just the number of these "measurements", so x <- 1:n. Using these, here come the plotting commands:

    plot(x, avg,
        ylim=range(c(avg-sdev, avg+sdev)),
        pch=19, xlab="Measurements", ylab="Mean +/- SD",
        main="Scatter plot with std.dev error bars"
    )
    # hack: we draw arrows but with very special "arrowheads"
    arrows(x, avg-sdev, x, avg+sdev, length=0.05, angle=90, code=3)
    

    The result looks like this:

    example scatter plot with std.dev error bars

    In the arrows(...) function length=0.05 is the size of the "arrowhead" in inches, angle=90 specifies that the "arrowhead" is perpendicular to the shaft of the arrow, and the particularly intuitive code=3 parameter specifies that we want to draw an arrowhead on both ends of the arrow.

    For horizontal error bars the following changes are necessary, assuming that the sdev vector now contains the errors in the x values and the y values are the ordinates:

    plot(x, y,
        xlim=range(c(x-sdev, x+sdev)),
        pch=19,...)
    # horizontal error bars
    arrows(x-sdev, y, x+sdev, y, length=0.05, angle=90, code=3)
    

    Using Mysql in the command line in osx - command not found?

    You can just modified the .bash_profile by adding the MySQL $PATH as the following:
    export PATH=$PATH:/usr/local/mysql/bin.

    I did the following:

    1- Open Terminal then $ nano .bash_profile or $ vim .bash_profile

    2- Add the following PATH code to the .bash_profile

    # Set architecture flags
    export ARCHFLAGS="-arch x86_64"
    # Ensure user-installed binaries take precedence
    export PATH=/usr/local/mysql/bin:$PATH
    # Load .bashrc if it exists
    test -f ~/.bashrc && source ~/.bashrc 
    

    3- Save the file.

    4- Refresh Terminal using $ source ~/.bash_profile

    5- To verify, type in Terminal $ mysql --version

    6- It should print the output something like this:

    $ mysql Ver 14.14 Distrib 5.7.17, for macos10.12 (x86_64)

    The Terminal is now configured to read the MySQL commands from $PATH which is placed in the .bash_profile .

    Selecting non-blank cells in Excel with VBA

    I know I'm am very late on this, but here some usefull samples:

    'select the used cells in column 3 of worksheet wks
    wks.columns(3).SpecialCells(xlCellTypeConstants).Select
    

    or

    'change all formulas in col 3 to values
    with sheet1.columns(3).SpecialCells(xlCellTypeFormulas)
        .value = .value
    end with
    

    To find the last used row in column, never rely on LastCell, which is unreliable (it is not reset after deleting data). Instead, I use someting like

     lngLast = cells(rows.count,3).end(xlUp).row
    

    How do I download the Android SDK without downloading Android Studio?

    Navigate to the "Get just the command line tools" section of the android downloads page, and download the tools for your system.

    For Windows:

    Extract the contents to C:\Android\android-sdk

    Navigate to C:\Android\android-sdk\tools\bin and open a command line window
    (shift + right click)

    Run the following to download the latest android package:

    sdkmanager "platforms;android-25" 
    

    Update everything

    sdkmanager --update
    

    Other operation systems Do pretty much the same, but not using windows directories.

    The sdkmanager page gives more info in to what commands to use to install your sdk.

    Git/GitHub can't push to master

    If you go to http://github.com/my_user_name/my_repo you will see a textbox where you can select the git path to your repository. You'll want to use this!

    HTML5 validation when the input type is not "submit"

    I wanted to add a new way of doing this that I just recently ran into. Even though form validation doesn't run when you submit the form using the submit() method, there's nothing stopping you from clicking a submit button programmatically. Even if it's hidden.

    Having a form:

    <form>
        <input type="text" name="title" required />
        <button style="display: none;" type="submit" id="submit-button">Not Shown</button>
        <button type="button" onclick="doFancyStuff()">Submit</button>
    </form>
    

    This will trigger form validation:

    function doFancyStuff() {
        $("#submit-button").click();
    }
    

    Or without jQuery

    function doFancyStuff() {
        document.getElementById("submit-button").click();
    }
    

    In my case, I do a bunch of validation and calculations when the fake submit button is pressed, if my manual validation fails, then I know I can programmatically click the hidden submit button and display form validation.

    Here's a VERY simple jsfiddle showing the concept:

    https://jsfiddle.net/45vxjz87/1/

    Execute SQL script from command line

    If you use Integrated Security, you might want to know that you simply need to use -E like this:

    sqlcmd -S Serverinstance -E -i import_file.sql
    

    Reading From A Text File - Batch

    Your code "for /f "tokens=* delims=" %%x in (a.txt) do echo %%x" will work on most Windows Operating Systems unless you have modified commands.

    So you could instead "cd" into the directory to read from before executing the "for /f" command to follow out the string. For instance if the file "a.txt" is located at C:\documents and settings\%USERNAME%\desktop\a.txt then you'd use the following.

    cd "C:\documents and settings\%USERNAME%\desktop"
    for /f "tokens=* delims=" %%x in (a.txt) do echo %%x
    echo.
    echo.
    echo.
    pause >nul
    exit
    

    But since this doesn't work on your computer for x reason there is an easier and more efficient way of doing this. Using the "type" command.

    @echo off
    color a
    cls
    cd "C:\documents and settings\%USERNAME%\desktop"
    type a.txt
    echo.
    echo.
    pause >nul
    exit
    

    Or if you'd like them to select the file from which to write in the batch you could do the following.

    @echo off
    :A
    color a
    cls
    echo Choose the file that you want to read.
    echo.
    echo.
    tree
    echo.
    echo.
    echo.
    set file=
    set /p file=File:
    cls
    echo Reading from %file%
    echo.
    type %file%
    echo.
    echo.
    echo.
    set re=
    set /p re=Y/N?:
    if %re%==Y goto :A
    if %re%==y goto :A
    exit