Programs & Examples On #Execvp

execvp, is a POSIX specified function from the exec* family, which replaces the current process with one specified. Questions using this tag should be related to the use and semantics of this function.

How to use execvp()

In cpp, you need to pay special attention to string types when using execvp:

#include <iostream>
#include <string>
#include <cstring>
#include <stdio.h>
#include <unistd.h>
using namespace std;

const size_t MAX_ARGC = 15; // 1 command + # of arguments
char* argv[MAX_ARGC + 1]; // Needs +1 because of the null terminator at the end
// c_str() converts string to const char*, strdup converts const char* to char*
argv[0] = strdup(command.c_str());

// start filling up the arguments after the first command
size_t arg_i = 1;
while (cin && arg_i < MAX_ARGC) {
    string arg;
    cin >> arg;
    if (arg.empty()) {
        argv[arg_i] = nullptr;
        break;
    } else {
        argv[arg_i] = strdup(arg.c_str());
    }
    ++arg_i;
}

// Run the command with arguments
if (execvp(command.c_str(), argv) == -1) {
    // Print error if command not found
    cerr << "command '" << command << "' not found\n";
}

Reference: execlp?execvp?????

Git - remote: Repository not found

I also had that issue. To solve that I: 1. Moved my local .dotfiles away to _.dotfiles_bak 2. Cloned my remote git repository 3. Copied all my files from _.dotfiles_bak to .dotfiles - except the .git folder 3. Then I could work locally again: Editing, committing and pushing

Using Pip to install packages to Anaconda Environment

I solved this problem the following way:

If you have a non-conda pip as your default pip but conda python is your default python (as below)

>which -a pip
/home/<user>/.local/bin/pip   
/home/<user>/.conda/envs/newenv/bin/pip
/usr/bin/pip

>which -a python
/home/<user>/.conda/envs/newenv/bin/python
/usr/bin/python

Then instead of just calling pip install <package>, you can use the module flag -m with python so that it uses the anaconda python for the installation

python -m pip install <package>

This installs the package to the anaconda library directory rather than to the library directory associated with (the non-anaconda) pip

How to know which version of Symfony I have?

Run app/console --version (for Symfony3: bin/console --version), it should give you a pretty good idea. On a random project of mine, the output is:

Symfony version 2.2.0-DEV - app/dev/debug

If you can't access the console, try reading symfony/src/Symfony/Component/HttpKernel/Kernel.php, where the version is hardcoded, for instance:

const VERSION         = '2.2.0';

Just in case you are wondering, console creates an instance of Symfony\Bundle\FrameworkBundle\Console\Application. In this class constructor, it uses Symfony\Component\HttpKernel\Kernel::VERSION to initialize its parent constructor.

Search for all occurrences of a string in a mysql database

Not an elegant solution, but you could achieve it with a nested looping structure

// select tables from database and store in an array

// loop through the array
foreach table in database
{
    // select columns in the table and store in an array

    // loop through the array
    foreach column in table
    {
        // select * from table where column = url
    }
}

You could probably speed this up by checking which columns contain strings while building your column array, and also by combining all the columns per table in one giant, comma-separated WHERE clause.

How to convert SQL Query result to PANDAS Data Structure?

If you are using SQLAlchemy's ORM rather than the expression language, you might find yourself wanting to convert an object of type sqlalchemy.orm.query.Query to a Pandas data frame.

The cleanest approach is to get the generated SQL from the query's statement attribute, and then execute it with pandas's read_sql() method. E.g., starting with a Query object called query:

df = pd.read_sql(query.statement, query.session.bind)

How do I create a readable diff of two spreadsheets using git diff?

I found an openoffice macro here that will invoke openoffice's compare documents function on two files. Unfortunately, openoffice's spreadsheet compare seems a little flaky; I just had the 'Reject All' button insert a superfluous column in my document.

How to set seekbar min and max value

seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                    boolean fromUser) {

                int MIN = 5;
                if (progress < MIN) {

                    value.setText(" Time Interval (" + seektime + " sec)");
                } else {
                    seektime = progress;
                }
                value.setText(" Time Interval (" + seektime + " sec)");

            }
        });

ToString() function in Go

Another example with a struct :

package types

import "fmt"

type MyType struct {
    Id   int    
    Name string
}

func (t MyType) String() string {
    return fmt.Sprintf(
    "[%d : %s]",
    t.Id, 
    t.Name)
}

Be careful when using it,
concatenation with '+' doesn't compile :

t := types.MyType{ 12, "Blabla" }

fmt.Println(t) // OK
fmt.Printf("t : %s \n", t) // OK
//fmt.Println("t : " + t) // Compiler error !!!
fmt.Println("t : " + t.String()) // OK if calling the function explicitly

Easy way to export multiple data.frame to multiple Excel worksheets

Incase data size is small, R has many packages and functions which can be utilized as per your requirement.

write.xlsx, write.xlsx2, XLconnect also do the work but these are sometimes slow as compare to openxlsx.

So, if you are dealing with the large data sets and came across java errors. I would suggest to have a look of "openxlsx" which is really awesome and reduce the time to 1/12th.

I've tested all and finally i was really impressed with the performance of openxlsx capabilities.

Here are the steps for writing multiple datasets into multiple sheets.

 install.packages("openxlsx")
 library("openxlsx")

    start.time <- Sys.time()

    # Creating large data frame
    x <- as.data.frame(matrix(1:4000000,200000,20))
    y <- as.data.frame(matrix(1:4000000,200000,20))
    z <- as.data.frame(matrix(1:4000000,200000,20))

    # Creating a workbook
    wb <- createWorkbook("Example.xlsx")
    Sys.setenv("R_ZIPCMD" = "C:/Rtools/bin/zip.exe") ## path to zip.exe

Sys.setenv("R_ZIPCMD" = "C:/Rtools/bin/zip.exe") has to be static as it takes reference of some utility from Rtools.

Note: Incase Rtools is not installed on your system, please install it first for smooth experience. here is the link for your reference: (choose appropriate version)

https://cran.r-project.org/bin/windows/Rtools/ check the options as per link below (need to select all the check box while installation)

https://cloud.githubusercontent.com/assets/7400673/12230758/99fb2202-b8a6-11e5-82e6-836159440831.png

    # Adding a worksheets : parameters for addWorksheet are 1. Workbook Name 2. Sheet Name

    addWorksheet(wb, "Sheet 1")
    addWorksheet(wb, "Sheet 2")
    addWorksheet(wb, "Sheet 3")

    # Writing data in to respetive sheets: parameters for writeData are 1. Workbook Name 2. Sheet index/ sheet name 3. dataframe name

    writeData(wb, 1, x)

    # incase you would like to write sheet with filter available for ease of access you can pass the parameter withFilter = TRUE in writeData function.
    writeData(wb, 2, x = y, withFilter = TRUE)

    ## Similarly writeDataTable is another way for representing your data with table formatting:

    writeDataTable(wb, 3, z)

    saveWorkbook(wb, file = "Example.xlsx", overwrite = TRUE)

    end.time <- Sys.time()
    time.taken <- end.time - start.time
    time.taken

openxlsx package is really good for reading and writing huge data from/ in excel files and has lots of options for custom formatting within excel.

The interesting fact is that we dont have to bother about java heap memory here.

while EOF in JAVA?

while(inFile.hasNext())

This is correct in java programming language

Can I use DIV class and ID together in CSS?

Yes you can.

You just need to understand what they are for, the class is more general and can be used several times, the id (is like your id's) you can use it only once.

This excellent tutorial helped me with that:

The Difference Between ID and Class

Though it's not an exact answer to your question I'm sure it will help you a lot!

Good luck!

EDIT: Reading your question, I just want to clarify that:

<div class="x" id="y">
    --
</div>

And that if you want to "use them" in CSS for styling purposes you should do as David Says: #x.y { }

Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

I used to have the same problem.

Your config use security="none" so cannot generate _csrf:

<http pattern="/login.jsp" security="none"/>

you can set access="IS_AUTHENTICATED_ANONYMOUSLY" for page /login.jsp replace above config:

<http>
    <intercept-url pattern="/login.jsp*" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
    <intercept-url pattern="/**" access="ROLE_USER"/>
    <form-login login-page="/login.jsp"
            authentication-failure-url="/login.jsp?error=1"
            default-target-url="/index.jsp"/>
    <logout/>
    <csrf />
</http>

Bash: Strip trailing linebreak from output

If you assign its output to a variable, bash automatically strips whitespace:

linecount=`wc -l < log.txt`

How to call a C# function from JavaScript?

Use Blazor http://learn-blazor.com/architecture/interop/

Here's the C#:

namespace BlazorDemo.Client
{
   public static class MyCSharpFunctions
   {
       public static void CsharpFunction()
       {
          // Notification.show();
       }
   }
}

Then the Javascript:

const CsharpFunction = Blazor.platform.findMethod(
"BlazorDemo.Client",
"BlazorDemo.Client",
"MyCSharpFunctions",
"CsharpFunction"
);
if (Javascriptcondition > 0) {
   Blazor.platform.callMethod(CsharpFunction, null)
}

Python try-else

Suppose your programming logic depends on whether a dictionary has an entry with a given key. You can test the result of dict.get(key) using if... else... construct, or you can do:

try:
    val = dic[key]
except KeyError:
    do_some_stuff()
else:
    do_some_stuff_with_val(val)

Alternative to itoa() for converting integer to string C++?

I use these templates

template <typename T> string toStr(T tmp)
{
    ostringstream out;
    out << tmp;
    return out.str();
}


template <typename T> T strTo(string tmp)
{
    T output;
    istringstream in(tmp);
    in >> output;
    return output;
}

Aligning textviews on the left and right edges in Android layout

You can use the gravity property to "float" views.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <LinearLayout 
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:gravity="center_vertical|center_horizontal"
            android:orientation="horizontal">

        <TextView  
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:gravity="left"
            android:layout_weight="1"
            android:text="Left Aligned"
            />

        <TextView  
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content"
            android:gravity="right"
            android:layout_weight="1"
            android:text="Right Aligned"
            />
    </LinearLayout>

</LinearLayout>

Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone

Short ES6 code

const convertFrom24To12Format = (time24) => {
  const [sHours, minutes] = time24.match(/([0-9]{1,2}):([0-9]{2})/).slice(1);
  const period = +sHours < 12 ? 'AM' : 'PM';
  const hours = +sHours % 12 || 12;

  return `${hours}:${minutes} ${period}`;
}
const convertFrom12To24Format = (time12) => {
  const [sHours, minutes, period] = time12.match(/([0-9]{1,2}):([0-9]{2}) (AM|PM)/).slice(1);
  const PM = period === 'PM';
  const hours = (+sHours % 12) + (PM ? 12 : 0);

  return `${('0' + hours).slice(-2)}:${minutes}`;
}

Call static method with reflection

Class that will call the methods:

namespace myNamespace
{
    public class myClass
    {
        public static void voidMethodWithoutParameters()
        {
            // code here
        }
        public static string stringReturnMethodWithParameters(string param1, string param2)
        {
            // code here
            return "output";
        }
    }
}

Calling myClass static methods using Reflection:

var myClassType = Assembly.GetExecutingAssembly().GetType(GetType().Namespace + ".myClass");
                    
// calling my void Method that has no parameters.
myClassType.GetMethod("voidMethodWithoutParameters", BindingFlags.Public | BindingFlags.Static).Invoke(null, null);

// calling my string returning Method & passing to it two string parameters.
Object methodOutput = myClassType.GetMethod("stringReturnMethodWithParameters", BindingFlags.Public | BindingFlags.Static).Invoke(null, new object[] { "value1", "value1" });
Console.WriteLine(methodOutput.ToString());

Note: I don't need to instantiate an object of myClass to use it's methods, as the methods I'm using are static.

Great resources:

How to read PDF files using Java?

PDFBox contains tools for text extraction.

iText has more low-level support for text manipulation, but you'd have to write a considerable amount of code to get text extraction.

iText in Action contains a good overview of the limitations of text extraction from PDF, regardless of the library used (Section 18.2: Extracting and editing text), and a convincing explanation why the library does not have text extraction support. In short, it's relatively easy to write a code that will handle simple cases, but it's basically impossible to extract text from PDF in general.

How can I process each letter of text using Javascript?

You can get an array of the individual characters like so

var test = "test string",
    characters = test.split('');

and then loop using regular Javascript, or else you can iterate over the string's characters using jQuery by

var test = "test string";

$(test.split('')).each(function (index,character) {
    alert(character);
});

When to use RDLC over RDL reports?

I have always thought the different between RDL and RDLC is that RDL are used for SQL Server Reporting Services and RDLC are used in Visual Studio for client side reporting. The implemenation and editor are almost identical. RDL stands for Report Defintion Language and RDLC Report Definition Language Client-side.

I hope that helps.

Oracle "ORA-01008: not all variables bound" Error w/ Parameters

It seems daft, but I think when you use the same bind variable twice you have to set it twice:

cmd.Parameters.Add("VarA", "24");
cmd.Parameters.Add("VarB", "test");
cmd.Parameters.Add("VarB", "test");
cmd.Parameters.Add("VarC", "1234");
cmd.Parameters.Add("VarC", "1234");

Certainly that's true with Native Dynamic SQL in PL/SQL:

SQL> begin
  2     execute immediate 'select * from emp where ename=:name and ename=:name'
  3     using 'KING';
  4  end;
  5  /
begin
*
ERROR at line 1:
ORA-01008: not all variables bound


SQL> begin
  2     execute immediate 'select * from emp where ename=:name and ename=:name' 
  3     using 'KING', 'KING';
  4  end;
  5  /

PL/SQL procedure successfully completed.

JavaScript listener, "keypress" doesn't detect backspace?

KeyPress event is invoked only for character (printable) keys, KeyDown event is raised for all including nonprintable such as Control, Shift, Alt, BackSpace, etc.

UPDATE:

The keypress event is fired when a key is pressed down and that key normally produces a character value

Reference.

How to get file creation & modification date/times in Python?

os.stat returns a named tuple with st_mtime and st_ctime attributes. The modification time is st_mtime on both platforms; unfortunately, on Windows, ctime means "creation time", whereas on POSIX it means "change time". I'm not aware of any way to get the creation time on POSIX platforms.

LinearLayout not expanding inside a ScrollView

In my case i haven't given the

orientation of LinearLayout(ScrollView's Child)

So by default it takes horizontal, but scrollview scrols vertically, so please check if 'android:orientation="vertical"' is set to your ScrollView's Child(In the case of LinearLayout).

This was my case hopes it helps somebody

.

How can I generate Unix timestamps?

nawk:

$ nawk 'BEGIN{print srand()}'
  • Works even on old versions of Solaris and probably other UNIX systems, where '''date +%s''' isn't implemented
  • Doesn't work on Linux and other distros where the posix tools have been replaced with the GNU versions (nawk -> gawk etc.)
  • Pretty unintuitive but definitelly amusing :-)

Check string length in PHP

$message is propably not a string at all, but an array. Use $message[0] to access the first element.

Show constraints on tables command

The main problem with the validated answer is you'll have to parse the output to get the informations. Here is a query allowing you to get them in a more usable manner :

SELECT cols.TABLE_NAME, cols.COLUMN_NAME, cols.ORDINAL_POSITION,
cols.COLUMN_DEFAULT, cols.IS_NULLABLE, cols.DATA_TYPE,
    cols.CHARACTER_MAXIMUM_LENGTH, cols.CHARACTER_OCTET_LENGTH,
    cols.NUMERIC_PRECISION, cols.NUMERIC_SCALE,
    cols.COLUMN_TYPE, cols.COLUMN_KEY, cols.EXTRA,
    cols.COLUMN_COMMENT, refs.REFERENCED_TABLE_NAME, refs.REFERENCED_COLUMN_NAME,
    cRefs.UPDATE_RULE, cRefs.DELETE_RULE,
    links.TABLE_NAME, links.COLUMN_NAME,
    cLinks.UPDATE_RULE, cLinks.DELETE_RULE
FROM INFORMATION_SCHEMA.`COLUMNS` as cols
LEFT JOIN INFORMATION_SCHEMA.`KEY_COLUMN_USAGE` AS refs
ON refs.TABLE_SCHEMA=cols.TABLE_SCHEMA
    AND refs.REFERENCED_TABLE_SCHEMA=cols.TABLE_SCHEMA
    AND refs.TABLE_NAME=cols.TABLE_NAME
    AND refs.COLUMN_NAME=cols.COLUMN_NAME
LEFT JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS cRefs
ON cRefs.CONSTRAINT_SCHEMA=cols.TABLE_SCHEMA
    AND cRefs.CONSTRAINT_NAME=refs.CONSTRAINT_NAME
LEFT JOIN INFORMATION_SCHEMA.`KEY_COLUMN_USAGE` AS links
ON links.TABLE_SCHEMA=cols.TABLE_SCHEMA
    AND links.REFERENCED_TABLE_SCHEMA=cols.TABLE_SCHEMA
    AND links.REFERENCED_TABLE_NAME=cols.TABLE_NAME
    AND links.REFERENCED_COLUMN_NAME=cols.COLUMN_NAME
LEFT JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS cLinks
ON cLinks.CONSTRAINT_SCHEMA=cols.TABLE_SCHEMA
    AND cLinks.CONSTRAINT_NAME=links.CONSTRAINT_NAME
WHERE cols.TABLE_SCHEMA=DATABASE()
    AND cols.TABLE_NAME="table"

How to detect a textbox's content has changed

I would recommend taking a look at jQuery UI autocomplete widget. They handled most of the cases there since their code base is more mature than most ones out there.

Below is a link to a demo page so you can verify it works. http://jqueryui.com/demos/autocomplete/#default

You will get the most benefit from reading the source and seeing how they solved it. You can find it here: https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.autocomplete.js.

Basically they do it all, they bind to input, keydown, keyup, keypress, focus and blur. Then they have special handling for all sorts of keys like page up, page down, up arrow key and down arrow key. A timer is used before getting the contents of the textbox. When a user types a key that does not correspond to a command (up key, down key and so on) there is a timer that explorers the content after about 300 milliseconds. It looks like this in the code:

// switch statement in the 
switch( event.keyCode ) {
            //...
            case keyCode.ENTER:
            case keyCode.NUMPAD_ENTER:
                // when menu is open and has focus
                if ( this.menu.active ) {
                    // #6055 - Opera still allows the keypress to occur
                    // which causes forms to submit
                    suppressKeyPress = true;
                    event.preventDefault();
                    this.menu.select( event );
                }
                break;
            default:
                suppressKeyPressRepeat = true;
                // search timeout should be triggered before the input value is changed
                this._searchTimeout( event );
                break;
            }
// ...
// ...
_searchTimeout: function( event ) {
    clearTimeout( this.searching );
    this.searching = this._delay(function() { // * essentially a warpper for a setTimeout call *
        // only search if the value has changed
        if ( this.term !== this._value() ) { // * _value is a wrapper to get the value *
            this.selectedItem = null;
            this.search( null, event );
        }
    }, this.options.delay );
},

The reason to use a timer is so that the UI gets a chance to be updated. When Javascript is running the UI cannot be updated, therefore the call to the delay function. This works well for other situations such as keeping focus on the textbox (used by that code).

So you can either use the widget or copy the code into your own widget if you are not using jQuery UI (or in my case developing a custom widget).

height: calc(100%) not working correctly in CSS

You need to ensure the html and body are set to 100% and also be sure to add vendor prefixes for calc, so -moz-calc, -webkit-calc.

Following CSS works:

html,body {
    background: blue;
    height:100%;
    padding:0;
    margin:0;
}
header {
    background: red;
    height: 20px;
    width:100%
}
h1 {
    font-size:1.2em;
    margin:0;
    padding:0;
    height: 30px;
    font-weight: bold;
    background:yellow
}
#theCalcDiv {
    background:green;
    height: -moz-calc(100% - (20px + 30px));
    height: -webkit-calc(100% - (20px + 30px));
    height: calc(100% - (20px + 30px));
    display:block
}

I also set your margin/padding to 0 on html and body, otherwise there would be a scrollbar when this is added on.

Here's an updated fiddle

http://jsfiddle.net/UF3mb/10/

Browser support is: IE9+, Firefox 16+ and with vendor prefix Firefox 4+, Chrome 19+, Safari 6+

C - casting int to char and append char to char

Casting int to char is done simply by assigning with the type in parenthesis:

int i = 65535;
char c = (char)i;

Note: I thought that you might be losing data (as in the example), because the type sizes are different.

Appending characters to characters cannot be done (unless you mean arithmetics, then it's simple operators). You need to use strings, AKA arrays of characters, and <string.h> functions like strcat or sprintf.

Java, How do I get current index/key in "for each" loop

Keep track of your index: That's how it is done in Java:

 int index = 0;
    for (Element song: question){
        // Do whatever
         index++;
    }

The HTTP request is unauthorized with client authentication scheme 'Negotiate'. The authentication header received from the server was 'NTLM'

I had the same problem, to solve it set specific user from domain in iis -> action sidebar->Basic Settings -> Connect as... -> specific user

enter image description here

How do I enable NuGet Package Restore in Visual Studio?

Package Manager console (Visual Studio, Tools > NuGet Package Manager > Package Manager Console): Run the Update-Package -reinstall -ProjectName command where is the name of the affected project as it appears in Solution Explorer. Use Update-Package -reinstall by itself to restore all packages in the solution. See Update-Package. You can also reinstall a single package, if desired.

from https://docs.microsoft.com/en-us/nuget/quickstart/restore

How to save username and password with Mercurial?

NOBODY above explained/clarified terms to a novice user. They get confused by the terms

.hg/hgrc -- this file is used for Repository, at local/workspace location / in actual repository's .hg folder.

~/.hgrc -- this file is different than the below one. this file resides at ~ or home directory.

myremote.xxxx=..... bb.xxxx=......

This is one of the lines under [auth] section/directive, while using mercurial keyring extension. Make sure the server name you put there, matches with what you use while doing "hg clone" otherwise keyring will say, user not found. bb or myremote in the line below, are "alias name" that you MUST give while doing "hg clone http:/.../../repo1 bb or myremote" otherwise, it wont work or you have to make sure your local repository's .hg/hgrc file contain same alias, ie (what you gave while doing hg clone .. as last parameter).

PS the following links for clear details, sorry for quickly written grammar.

ex: If inside ~/.hgrc (user's home directory in Linux/Unix) or mercurial.ini in Windows at user's home directory, contains, the following line and if you do

`"hg clone http://.../.../reponame myremote"`

, then you'll never be prompted for user credentials more than once per http repo link. In ~/.hgrc under [extensions] a line for "mercurial_keyring = " or "hgext.mercurial_keyring = /path/to/your/mercurial_keyring.py" .. one of these lines should be there.

[auth]
myremote.schemes = http https
myremote.prefix = thsusncdnvm99/hg
myremote.username = c123456

I'm trying to find out how to set the PREFIX property so that user can clone or perform any Hg operations without username/password prompts and without worrying about what he mentioned in the http://..../... for servername while using the Hg repo link. It can be IP, servername or server's FQDN

How to get unique values in an array

Since I went on about it in the comments for @Rocket's answer, I may as well provide an example that uses no libraries. This requires two new prototype functions, contains and unique

_x000D_
_x000D_
Array.prototype.contains = function(v) {_x000D_
  for (var i = 0; i < this.length; i++) {_x000D_
    if (this[i] === v) return true;_x000D_
  }_x000D_
  return false;_x000D_
};_x000D_
_x000D_
Array.prototype.unique = function() {_x000D_
  var arr = [];_x000D_
  for (var i = 0; i < this.length; i++) {_x000D_
    if (!arr.contains(this[i])) {_x000D_
      arr.push(this[i]);_x000D_
    }_x000D_
  }_x000D_
  return arr;_x000D_
}_x000D_
_x000D_
var duplicates = [1, 3, 4, 2, 1, 2, 3, 8];_x000D_
var uniques = duplicates.unique(); // result = [1,3,4,2,8]_x000D_
_x000D_
console.log(uniques);
_x000D_
_x000D_
_x000D_

For more reliability, you can replace contains with MDN's indexOf shim and check if each element's indexOf is equal to -1: documentation

How to calculate the sum of the datatable column in asp.net?

Compute Sum of Column in Datatable , Works 100%

lbl_TotaAmt.Text = MyDataTable.Compute("Sum(BalAmt)", "").ToString();

if you want to have any conditions, use it like this

   lbl_TotaAmt.Text = MyDataTable.Compute("Sum(BalAmt)", "srno=1 or srno in(1,2)").ToString();

Dynamically change bootstrap progress bar value when checkboxes checked

Bootstrap 4 progress bar

<div class="progress">
<div class="progress-bar" role="progressbar" style="" aria-valuenow="" aria-valuemin="0" aria-valuemax="100"></div>
</div>

Javascript

change progress bar on next/previous page actions

var count = Number(document.getElementById('count').innerHTML); //set this on page load in a hidden field after an ajax call
var total = document.getElementById('total').innerHTML; //set this on initial page load
var pcg = Math.floor(count/total*100);        
document.getElementsByClassName('progress-bar').item(0).setAttribute('aria-valuenow',pcg);
document.getElementsByClassName('progress-bar').item(0).setAttribute('style','width:'+Number(pcg)+'%');

DLL References in Visual C++

You need to do a couple of things to use the library:

  1. Make sure that you have both the *.lib and the *.dll from the library you want to use. If you don't have the *.lib, skip #2

  2. Put a reference to the *.lib in the project. Right click the project name in the Solution Explorer and then select Configuration Properties->Linker->Input and put the name of the lib in the Additional Dependencies property.

  3. You have to make sure that VS can find the lib you just added so you have to go to the Tools menu and select Options... Then under Projects and Solutions select VC++ Directories,edit Library Directory option. From within here you can set the directory that contains your new lib by selecting the 'Library Files' in the 'Show Directories For:' drop down box. Just add the path to your lib file in the list of directories. If you dont have a lib you can omit this, but while your here you will also need to set the directory which contains your header files as well under the 'Include Files'. Do it the same way you added the lib.

After doing this you should be good to go and can use your library. If you dont have a lib file you can still use the dll by importing it yourself. During your applications startup you can explicitly load the dll by calling LoadLibrary (see: http://msdn.microsoft.com/en-us/library/ms684175(VS.85).aspx for more info)

Cheers!

EDIT

Remember to use #include < Foo.h > as opposed to #include "foo.h". The former searches the include path. The latter uses the local project files.

Recursively looping through an object to build a property list

Suppose that you have a JSON object like:

var example = {
    "prop1": "value1",
    "prop2": [ "value2_0", "value2_1"],
    "prop3": {
         "prop3_1": "value3_1"
    }
}

The wrong way to iterate through its 'properties':

function recursivelyIterateProperties(jsonObject) {
    for (var prop in Object.keys(jsonObject)) {
        console.log(prop);
        recursivelyIterateProperties(jsonObject[prop]);
    }
}

You might be surprised of seeing the console logging 0, 1, etc. when iterating through the properties of prop1 and prop2 and of prop3_1. Those objects are sequences, and the indexes of a sequence are properties of that object in Javascript.

A better way to recursively iterate through a JSON object properties would be to first check if that object is a sequence or not:

function recursivelyIterateProperties(jsonObject) {
    for (var prop in Object.keys(jsonObject)) {
        console.log(prop);
        if (!(typeof(jsonObject[prop]) === 'string')
            && !(jsonObject[prop] instanceof Array)) {
                recursivelyIterateProperties(jsonObject[prop]);

            }
     }
}

If you want to find properties inside of objects in arrays, then do the following:

function recursivelyIterateProperties(jsonObject) {

    if (jsonObject instanceof Array) {
        for (var i = 0; i < jsonObject.length; ++i) {
            recursivelyIterateProperties(jsonObject[i])
        }
    }
    else if (typeof(jsonObject) === 'object') {
        for (var prop in Object.keys(jsonObject)) {
            console.log(prop);
            if (!(typeof(jsonObject[prop]) === 'string')) {
                recursivelyIterateProperties(jsonObject[prop]);
            }
        }
    }
}

Is it bad to have my virtualenv directory inside my git repository?

I used to do the same until I started using libraries that are compiled differently depending on the environment such as PyCrypto. My PyCrypto mac wouldn't work on Cygwin wouldn't work on Ubuntu.

It becomes an utter nightmare to manage the repository.

Either way I found it easier to manage the pip freeze & a requirements file than having it all in git. It's cleaner too since you get to avoid the commit spam for thousands of files as those libraries get updated...

KERNELBASE.dll Exception 0xe0434352 offset 0x000000000000a49d

0xe0434352 is the SEH code for a CLR exception. If you don't understand what that means, stop and read A Crash Course on the Depths of Win32™ Structured Exception Handling. So your process is not handling a CLR exception. Don't shoot the messenger, KERNELBASE.DLL is just the unfortunate victim. The perpetrator is MyApp.exe.

There should be a minidump of the crash in DrWatson folders with a full stack, it will contain everything you need to root cause the issue.

I suggest you wire up, in your myapp.exe code, AppDomain.UnhandledException and Application.ThreadException, as appropriate.

GDB: break if variable equal value

First, you need to compile your code with appropriate flags, enabling debug into code.

$ gcc -Wall -g -ggdb -o ex1 ex1.c

then just run you code with your favourite debugger

$ gdb ./ex1

show me the code.

(gdb) list
1   #include <stdio.h>
2   int main(void)
3   { 
4     int i = 0;
5     for(i=0;i<7;++i)
6       printf("%d\n", i);
7   
8     return 0;
9   }

break on lines 5 and looks if i == 5.

(gdb) b 5
Breakpoint 1 at 0x4004fb: file ex1.c, line 5.
(gdb) rwatch i if i==5
Hardware read watchpoint 5: i

checking breakpoints

(gdb) info b
Num     Type           Disp Enb Address            What
1       breakpoint     keep y   0x00000000004004fb in main at ex1.c:5
    breakpoint already hit 1 time
5       read watchpoint keep y                      i
    stop only if i==5

running the program

(gdb) c
Continuing.
0
1
2
3
4
Hardware read watchpoint 5: i

Value = 5
0x0000000000400523 in main () at ex1.c:5
5     for(i=0;i<7;++i)

What is the correct SQL type to store a .Net Timespan with values > 24:00:00?

Typically, I store a TimeSpan as a bigint populated with ticks from the TimeSpan.Ticks property as previously suggested. You can also store a TimeSpan as a varchar(26) populated with the output of TimeSpan.ToString(). The four scalar functions (ConvertFromTimeSpanString, ConvertToTimeSpanString, DateAddTicks, DateDiffTicks) that I wrote are helpful for handling TimeSpan on the SQL side and avoid the hacks that would produce artificially bounded ranges. If you can store the interval in a .NET TimeSpan at all it should work with these functions also. Additionally, the functions allow you to work with TimeSpans and 100-nanosecond ticks even when using technologies that don't include the .NET Framework.

DROP FUNCTION [dbo].[DateDiffTicks]
GO

DROP FUNCTION [dbo].[DateAddTicks]
GO

DROP FUNCTION [dbo].[ConvertToTimeSpanString]
GO

DROP FUNCTION [dbo].[ConvertFromTimeSpanString]
GO

SET ANSI_NULLS OFF
GO

SET QUOTED_IDENTIFIER OFF
GO

-- =============================================
-- Author:      James Coe
-- Create date: 2011-05-23
-- Description: Converts from a varchar(26) TimeSpan string to a bigint containing the number of 100 nanosecond ticks.
-- =============================================
/*
    [-][d.]hh:mm:ss[.fffffff] 

    "-" 
     A minus sign, which indicates a negative time interval. No sign is included for a positive time span.

    "d" 
     The number of days in the time interval. This element is omitted if the time interval is less than one day. 

    "hh" 
     The number of hours in the time interval, ranging from 0 to 23. 

    "mm" 
     The number of minutes in the time interval, ranging from 0 to 59. 

    "ss" 
     The number of seconds in the time interval, ranging from 0 to 59. 

    "fffffff" 
     Fractional seconds in the time interval. This element is omitted if the time interval does not include 
     fractional seconds. If present, fractional seconds are always expressed using seven decimal digits.
    */
CREATE FUNCTION [dbo].[ConvertFromTimeSpanString] (@timeSpan varchar(26))
RETURNS bigint
AS
BEGIN
    DECLARE @hourStart int
    DECLARE @minuteStart int
    DECLARE @secondStart int
    DECLARE @ticks bigint
    DECLARE @hours bigint
    DECLARE @minutes bigint
    DECLARE @seconds DECIMAL(9, 7)

    SET @hourStart = CHARINDEX('.', @timeSpan) + 1
    SET @minuteStart = CHARINDEX(':', @timeSpan) + 1
    SET @secondStart = CHARINDEX(':', @timespan, @minuteStart) + 1
    SET @ticks = 0

    IF (@hourStart > 1 AND @hourStart < @minuteStart)
    BEGIN
        SET @ticks = CONVERT(bigint, LEFT(@timespan, @hourstart - 2)) * 864000000000
    END
    ELSE
    BEGIN
        SET @hourStart = 1
    END

    SET @hours = CONVERT(bigint, SUBSTRING(@timespan, @hourStart, @minuteStart - @hourStart - 1))
    SET @minutes = CONVERT(bigint, SUBSTRING(@timespan, @minuteStart, @secondStart - @minuteStart - 1))
    SET @seconds = CONVERT(DECIMAL(9, 7), SUBSTRING(@timespan, @secondStart, LEN(@timeSpan) - @secondStart + 1))

    IF (@ticks < 0)
    BEGIN
        SET @ticks = @ticks - @hours * 36000000000
    END
    ELSE
    BEGIN
        SET @ticks = @ticks + @hours * 36000000000
    END

    IF (@ticks < 0)
    BEGIN
        SET @ticks = @ticks - @minutes * 600000000
    END
    ELSE
    BEGIN
        SET @ticks = @ticks + @minutes * 600000000
    END

    IF (@ticks < 0)
    BEGIN
        SET @ticks = @ticks - @seconds * 10000000.0
    END
    ELSE
    BEGIN
        SET @ticks = @ticks + @seconds * 10000000.0
    END

    RETURN @ticks
END
GO

-- =============================================
-- Author:      James Coe
-- Create date: 2011-05-23
-- Description: Converts from a bigint containing the number of 100 nanosecond ticks to a varchar(26) TimeSpan string.
-- =============================================
/*
[-][d.]hh:mm:ss[.fffffff] 

"-" 
 A minus sign, which indicates a negative time interval. No sign is included for a positive time span.

"d" 
 The number of days in the time interval. This element is omitted if the time interval is less than one day. 

"hh" 
 The number of hours in the time interval, ranging from 0 to 23. 

"mm" 
 The number of minutes in the time interval, ranging from 0 to 59. 

"ss" 
 The number of seconds in the time interval, ranging from 0 to 59. 

"fffffff" 
 Fractional seconds in the time interval. This element is omitted if the time interval does not include 
 fractional seconds. If present, fractional seconds are always expressed using seven decimal digits.
*/
CREATE FUNCTION [dbo].[ConvertToTimeSpanString] (@ticks bigint)
RETURNS varchar(26)
AS
BEGIN
    DECLARE @timeSpanString varchar(26)

    IF (@ticks < 0)
    BEGIN
        SET @timeSpanString = '-'
    END
    ELSE
    BEGIN
        SET @timeSpanString = ''
    END

    -- Days
    DECLARE @days bigint

    SET @days = FLOOR(ABS(@ticks / 864000000000.0))

    IF (@days > 0)
    BEGIN
        SET @timeSpanString = @timeSpanString + CONVERT(varchar(26), @days) + '.'
    END

    SET @ticks = ABS(@ticks % 864000000000)
    -- Hours
    SET @timeSpanString = @timeSpanString + RIGHT('0' + CONVERT(varchar(26), FLOOR(@ticks / 36000000000.0)), 2) + ':'
    SET @ticks = @ticks % 36000000000
    -- Minutes
    SET @timeSpanString = @timeSpanString + RIGHT('0' + CONVERT(varchar(26), FLOOR(@ticks / 600000000.0)), 2) + ':'
    SET @ticks = @ticks % 600000000
    -- Seconds
    SET @timeSpanString = @timeSpanString + RIGHT('0' + CONVERT(varchar(26), FLOOR(@ticks / 10000000.0)), 2)
    SET @ticks = @ticks % 10000000

    -- Fractional Seconds
    IF (@ticks > 0)
    BEGIN
        SET @timeSpanString = @timeSpanString + '.' + LEFT(CONVERT(varchar(26), @ticks) + '0000000', 7)
    END

    RETURN @timeSpanString
END
GO

-- =============================================
-- Author:      James Coe
-- Create date: 2011-05-23
-- Description: Adds the specified number of 100 nanosecond ticks to a date.
-- =============================================
CREATE FUNCTION [dbo].[DateAddTicks] (
    @ticks bigint
    , @starting_date datetimeoffset
    )
RETURNS datetimeoffset
AS
BEGIN
    DECLARE @dateTimeResult datetimeoffset

    IF (@ticks < 0)
    BEGIN
        -- Hours
        SET @dateTimeResult = DATEADD(HOUR, CEILING(@ticks / 36000000000.0), @starting_date)
        SET @ticks = @ticks % 36000000000
        -- Seconds
        SET @dateTimeResult = DATEADD(SECOND, CEILING(@ticks / 10000000.0), @dateTimeResult)
        SET @ticks = @ticks % 10000000
        -- Nanoseconds
        SET @dateTimeResult = DATEADD(NANOSECOND, @ticks * 100, @dateTimeResult)
    END
    ELSE
    BEGIN
        -- Hours
        SET @dateTimeResult = DATEADD(HOUR, FLOOR(@ticks / 36000000000.0), @starting_date)
        SET @ticks = @ticks % 36000000000
        -- Seconds
        SET @dateTimeResult = DATEADD(SECOND, FLOOR(@ticks / 10000000.0), @dateTimeResult)
        SET @ticks = @ticks % 10000000
        -- Nanoseconds
        SET @dateTimeResult = DATEADD(NANOSECOND, @ticks * 100, @dateTimeResult)
    END

    RETURN @dateTimeResult
END
GO

-- =============================================
-- Author:      James Coe
-- Create date: 2011-05-23
-- Description:  Gets the difference between two dates in 100 nanosecond ticks.
-- =============================================
CREATE FUNCTION [dbo].[DateDiffTicks] (
    @starting_date datetimeoffset
    , @ending_date datetimeoffset
    )
RETURNS bigint
AS
BEGIN
    DECLARE @ticks bigint
    DECLARE @days bigint
    DECLARE @hours bigint
    DECLARE @minutes bigint
    DECLARE @seconds bigint

    SET @hours = DATEDIFF(HOUR, @starting_date, @ending_date)
    SET @starting_date = DATEADD(HOUR, @hours, @starting_date)
    SET @ticks = @hours * 36000000000
    SET @seconds = DATEDIFF(SECOND, @starting_date, @ending_date)
    SET @starting_date = DATEADD(SECOND, @seconds, @starting_date)
    SET @ticks = @ticks + @seconds * 10000000
    SET @ticks = @ticks + CONVERT(bigint, DATEDIFF(NANOSECOND, @starting_date, @ending_date)) / 100

    RETURN @ticks
END
GO

--- BEGIN Test Harness ---
SET NOCOUNT ON

DECLARE @dateTimeOffsetMinValue datetimeoffset
DECLARE @dateTimeOffsetMaxValue datetimeoffset
DECLARE @timeSpanMinValueString varchar(26)
DECLARE @timeSpanZeroString varchar(26)
DECLARE @timeSpanMaxValueString varchar(26)
DECLARE @timeSpanMinValueTicks bigint
DECLARE @timeSpanZeroTicks bigint
DECLARE @timeSpanMaxValueTicks bigint
DECLARE @dateTimeOffsetMinMaxDiffTicks bigint
DECLARE @dateTimeOffsetMaxMinDiffTicks bigint

SET @dateTimeOffsetMinValue = '0001-01-01T00:00:00.0000000+00:00'
SET @dateTimeOffsetMaxValue = '9999-12-31T23:59:59.9999999+00:00'
SET @timeSpanMinValueString = '-10675199.02:48:05.4775808'
SET @timeSpanZeroString = '00:00:00'
SET @timeSpanMaxValueString = '10675199.02:48:05.4775807'
SET @timeSpanMinValueTicks = -9223372036854775808
SET @timeSpanZeroTicks = 0
SET @timeSpanMaxValueTicks = 9223372036854775807
SET @dateTimeOffsetMinMaxDiffTicks = 3155378975999999999
SET @dateTimeOffsetMaxMinDiffTicks = -3155378975999999999

-- TimeSpan Conversion Tests
PRINT 'Testing TimeSpan conversions...'

DECLARE @convertToTimeSpanStringMinTicksResult varchar(26)
DECLARE @convertFromTimeSpanStringMinTimeSpanResult bigint
DECLARE @convertToTimeSpanStringZeroTicksResult varchar(26)
DECLARE @convertFromTimeSpanStringZeroTimeSpanResult bigint
DECLARE @convertToTimeSpanStringMaxTicksResult varchar(26)
DECLARE @convertFromTimeSpanStringMaxTimeSpanResult bigint

SET @convertToTimeSpanStringMinTicksResult = dbo.ConvertToTimeSpanString(@timeSpanMinValueTicks)
SET @convertFromTimeSpanStringMinTimeSpanResult = dbo.ConvertFromTimeSpanString(@timeSpanMinValueString)
SET @convertToTimeSpanStringZeroTicksResult = dbo.ConvertToTimeSpanString(@timeSpanZeroTicks)
SET @convertFromTimeSpanStringZeroTimeSpanResult = dbo.ConvertFromTimeSpanString(@timeSpanZeroString)
SET @convertToTimeSpanStringMaxTicksResult = dbo.ConvertToTimeSpanString(@timeSpanMaxValueTicks)
SET @convertFromTimeSpanStringMaxTimeSpanResult = dbo.ConvertFromTimeSpanString(@timeSpanMaxValueString)

-- Test Results
SELECT 'Convert to TimeSpan String from Ticks (Minimum)' AS Test
    , CASE 
        WHEN @convertToTimeSpanStringMinTicksResult = @timeSpanMinValueString
            THEN 'Pass'
        ELSE 'Fail'
        END AS [Test Status]
    , @timeSpanMinValueTicks AS [Ticks]
    , CONVERT(varchar(26), NULL) AS [TimeSpan String]
    , CONVERT(varchar(26), @convertToTimeSpanStringMinTicksResult) AS [Actual Result]
    , CONVERT(varchar(26), @timeSpanMinValueString) AS [Expected Result]
UNION ALL
SELECT 'Convert from TimeSpan String to Ticks (Minimum)' AS Test
    , CASE 
        WHEN @convertFromTimeSpanStringMinTimeSpanResult = @timeSpanMinValueTicks
            THEN 'Pass'
        ELSE 'Fail'
        END AS [Test Status]
    , NULL AS [Ticks]
    , @timeSpanMinValueString AS [TimeSpan String]
    , CONVERT(varchar(26), @convertFromTimeSpanStringMinTimeSpanResult) AS [Actual Result]
    , CONVERT(varchar(26), @timeSpanMinValueTicks) AS [Expected Result]
UNION ALL
SELECT 'Convert to TimeSpan String from Ticks (Zero)' AS Test
    , CASE 
        WHEN @convertToTimeSpanStringZeroTicksResult = @timeSpanZeroString
            THEN 'Pass'
        ELSE 'Fail'
        END AS [Test Status]
    , @timeSpanZeroTicks AS [Ticks]
    , CONVERT(varchar(26), NULL) AS [TimeSpan String]
    , CONVERT(varchar(26), @convertToTimeSpanStringZeroTicksResult) AS [Actual Result]
    , CONVERT(varchar(26), @timeSpanZeroString) AS [Expected Result]
UNION ALL
SELECT 'Convert from TimeSpan String to Ticks (Zero)' AS Test
    , CASE 
        WHEN @convertFromTimeSpanStringZeroTimeSpanResult = @timeSpanZeroTicks
            THEN 'Pass'
        ELSE 'Fail'
        END AS [Test Status]
    , NULL AS [Ticks]
    , @timeSpanZeroString AS [TimeSpan String]
    , CONVERT(varchar(26), @convertFromTimeSpanStringZeroTimeSpanResult) AS [Actual Result]
    , CONVERT(varchar(26), @timeSpanZeroTicks) AS [Expected Result]
UNION ALL
SELECT 'Convert to TimeSpan String from Ticks (Maximum)' AS Test
    , CASE 
        WHEN @convertToTimeSpanStringMaxTicksResult = @timeSpanMaxValueString
            THEN 'Pass'
        ELSE 'Fail'
        END AS [Test Status]
    , @timeSpanMaxValueTicks AS [Ticks]
    , CONVERT(varchar(26), NULL) AS [TimeSpan String]
    , CONVERT(varchar(26), @convertToTimeSpanStringMaxTicksResult) AS [Actual Result]
    , CONVERT(varchar(26), @timeSpanMaxValueString) AS [Expected Result]
UNION ALL
SELECT 'Convert from TimeSpan String to Ticks (Maximum)' AS Test
    , CASE 
        WHEN @convertFromTimeSpanStringMaxTimeSpanResult = @timeSpanMaxValueTicks
            THEN 'Pass'
        ELSE 'Fail'
        END AS [Test Status]
    , NULL AS [Ticks]
    , @timeSpanMaxValueString AS [TimeSpan String]
    , CONVERT(varchar(26), @convertFromTimeSpanStringMaxTimeSpanResult) AS [Actual Result]
    , CONVERT(varchar(26), @timeSpanMaxValueTicks) AS [Expected Result]

-- Ticks Date Add Test
PRINT 'Testing DateAddTicks...'

DECLARE @DateAddTicksPositiveTicksResult datetimeoffset
DECLARE @DateAddTicksZeroTicksResult datetimeoffset
DECLARE @DateAddTicksNegativeTicksResult datetimeoffset

SET @DateAddTicksPositiveTicksResult = dbo.DateAddTicks(@dateTimeOffsetMinMaxDiffTicks, @dateTimeOffsetMinValue)
SET @DateAddTicksZeroTicksResult = dbo.DateAddTicks(@timeSpanZeroTicks, @dateTimeOffsetMinValue)
SET @DateAddTicksNegativeTicksResult = dbo.DateAddTicks(@dateTimeOffsetMaxMinDiffTicks, @dateTimeOffsetMaxValue)

-- Test Results
SELECT 'Date Add with Ticks Test (Positive)' AS Test
    , CASE 
        WHEN @DateAddTicksPositiveTicksResult = @dateTimeOffsetMaxValue
            THEN 'Pass'
        ELSE 'Fail'
        END AS [Test Status]
    , @dateTimeOffsetMinMaxDiffTicks AS [Ticks]
    , @dateTimeOffsetMinValue AS [Starting Date]
    , @DateAddTicksPositiveTicksResult AS [Actual Result]
    , @dateTimeOffsetMaxValue AS [Expected Result]
UNION ALL
SELECT 'Date Add with Ticks Test (Zero)' AS Test
    , CASE 
        WHEN @DateAddTicksZeroTicksResult = @dateTimeOffsetMinValue
            THEN 'Pass'
        ELSE 'Fail'
        END AS [Test Status]
    , @timeSpanZeroTicks AS [Ticks]
    , @dateTimeOffsetMinValue AS [Starting Date]
    , @DateAddTicksZeroTicksResult AS [Actual Result]
    , @dateTimeOffsetMinValue AS [Expected Result]
UNION ALL
SELECT 'Date Add with Ticks Test (Negative)' AS Test
    , CASE 
        WHEN @DateAddTicksNegativeTicksResult = @dateTimeOffsetMinValue
            THEN 'Pass'
        ELSE 'Fail'
        END AS [Test Status]
    , @dateTimeOffsetMaxMinDiffTicks AS [Ticks]
    , @dateTimeOffsetMaxValue AS [Starting Date]
    , @DateAddTicksNegativeTicksResult AS [Actual Result]
    , @dateTimeOffsetMinValue AS [Expected Result]

-- Ticks Date Diff Test
PRINT 'Testing Date Diff Ticks...'

DECLARE @dateDiffTicksMinMaxResult bigint
DECLARE @dateDiffTicksMaxMinResult bigint

SET @dateDiffTicksMinMaxResult = dbo.DateDiffTicks(@dateTimeOffsetMinValue, @dateTimeOffsetMaxValue)
SET @dateDiffTicksMaxMinResult = dbo.DateDiffTicks(@dateTimeOffsetMaxValue, @dateTimeOffsetMinValue)

-- Test Results
SELECT 'Date Difference in Ticks Test (Min, Max)' AS Test
    , CASE 
        WHEN @dateDiffTicksMinMaxResult = @dateTimeOffsetMinMaxDiffTicks
            THEN 'Pass'
        ELSE 'Fail'
        END AS [Test Status]
    , @dateTimeOffsetMinValue AS [Starting Date]
    , @dateTimeOffsetMaxValue AS [Ending Date]
    , @dateDiffTicksMinMaxResult AS [Actual Result]
    , @dateTimeOffsetMinMaxDiffTicks AS [Expected Result]
UNION ALL
SELECT 'Date Difference in Ticks Test (Max, Min)' AS Test
    , CASE 
        WHEN @dateDiffTicksMaxMinResult = @dateTimeOffsetMaxMinDiffTicks
            THEN 'Pass'
        ELSE 'Fail'
        END AS [Test Status]
    , @dateTimeOffsetMaxValue AS [Starting Date]
    , @dateTimeOffsetMinValue AS [Ending Date]
    , @dateDiffTicksMaxMinResult AS [Actual Result]
    , @dateTimeOffsetMaxMinDiffTicks AS [Expected Result]

PRINT 'Tests Complete.'
GO
--- END Test Harness ---

Java double.MAX_VALUE?

Double.MAX_VALUE is the maximum value a double can represent (somewhere around 1.7*10^308).

This should end in some calculation problems, if you try to subtract the maximum possible value of a data type.

Even though when you are dealing with money you should never use floating point values especially while rounding this can cause problems (you will either have to much or less money in your system then).

What should be in my .gitignore for an Android Studio project?

I disagree with all of these answers. The following configuration is working great for our organization's app.

I ignore:

  • /build
  • /.idea (with possible exceptions, see comments in dalewking's answer)
  • *.iml
  • local.properties

I think almost everyone agrees about /build.

I got sick of constantly seeing messages about the various library.xml files that Gradle creates or deletes in /.idea. The build.gradle will run on the developers's local when they first check out the project, so why do those XML files need to be versioned? Android Studio will also generate the rest of /.idea when a developer creates a project using Check out from Version Control, so why does anything in that folder need to be versioned?

If the *.iml is versioned a new user will have to name the project exactly the same as it was when committed. Since this is also a generated file, why version it in the first place?

The local.properties files points to an absolute path on the file system for the SDK, so it definitely shouldn't be versioned.

Edit 1: Added .gradle to ignore the gradle caching stuff that should not be versioned (thanks Vasily Makarov).

Edit 2: Added .DS_Store now that I am using Mac. This folder is Mac specific and should not be versioned.

Additional note: You probably also want to add a directory to put your signing keys in when building a release version.

For copy/paste convenience:

.gradle
/build
/.idea
*.iml
local.properties
.DS_Store 

Paste a multi-line Java String in Eclipse

Okay, I just found the answer (on Stackoverflow, no less).

Eclipse has an option so that copy-paste of multi-line text into String literals will result in quoted newlines:

Preferences/Java/Editor/Typing/ "Escape text when pasting into a string literal"

OnItemClickListener using ArrayAdapter for ListView

you can use this way...

listView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                final int position, long id) {

          String main = listView.getSelectedItem().toString();
        }
    });

how to get the host url using javascript from the current page

Depending on your needs, you can use one of the window.location properties. In your question you are asking about the host, which may be retrieved using window.location.hostname (e.g. www.example.com). In your example you are showing something what is called origin, which may be retrieved using window.location.origin (e.g. http://www.example.com).

var path = window.location.origin + "/";

//result = "http://localhost:60470/"

How to get an enum value from a string value in Java?

Use the pattern from Joshua Bloch, Effective Java:

(simplified for brevity)

enum MyEnum {
    ENUM_1("A"),
    ENUM_2("B");

    private String name;

    private static final Map<String,MyEnum> ENUM_MAP;

    MyEnum (String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }

    // Build an immutable map of String name to enum pairs.
    // Any Map impl can be used.

    static {
        Map<String,MyEnum> map = new ConcurrentHashMap<String, MyEnum>();
        for (MyEnum instance : MyEnum.values()) {
            map.put(instance.getName().toLowerCase(),instance);
        }
        ENUM_MAP = Collections.unmodifiableMap(map);
    }

    public static MyEnum get (String name) {
        return ENUM_MAP.get(name.toLowerCase());
    }
}

Also see:

Oracle Java Example using Enum and Map of instances

Execution order of of static blocks in an Enum type

How can I lookup a Java enum from its String value

How do you check "if not null" with Eloquent?

If someone like me want to do it with query builder in Laravel 5.2.23 it can be done like ->

 $searchResultQuery = Users::query(); 
 $searchResultQuery->where('status_message', '<>', '', 'and'); // is not null
 $searchResultQuery->where('is_deleted', 'IS NULL', null, 'and'); // is null 

Or with scope in model :

public function scopeNotNullOnly($query){

    return $query->where('status_message', '<>', '');
}

The split() method in Java does not work on a dot (.)

\\. is the simple answer. Here is simple code for your help.

while (line != null) {
    //             
    String[] words = line.split("\\.");
    wr = "";
    mean = "";
    if (words.length > 2) {
        wr = words[0] + words[1];
        mean = words[2];

    } else {
        wr = words[0];
        mean = words[1];
    }
}

Tools for making latex tables in R

Thanks Joris for creating this question. Hopefully, it will be made into a community wiki.

The booktabs packages in latex produces nice looking tables. Here is a blog post on how to use xtable to create latex tables that use booktabs

I would also add the apsrtable package to the mix as it produces nice looking regression tables.

Another Idea: Some of these packages (esp. memisc and apsrtable) allow easy extensions of the code to produce tables for different regression objects. One such example is the lme4 memisc code shown in the question. It might make sense to start a github repository to collect such code snippets, and over time maybe even add it to the memisc package. Any takers?

C library function to perform sort

qsort() is the function you're looking for. You call it with a pointer to your array of data, the number of elements in that array, the size of each element and a comparison function.

It does its magic and your array is sorted in-place. An example follows:

#include <stdio.h>
#include <stdlib.h>
int comp (const void * elem1, const void * elem2) 
{
    int f = *((int*)elem1);
    int s = *((int*)elem2);
    if (f > s) return  1;
    if (f < s) return -1;
    return 0;
}
int main(int argc, char* argv[]) 
{
    int x[] = {4,5,2,3,1,0,9,8,6,7};

    qsort (x, sizeof(x)/sizeof(*x), sizeof(*x), comp);

    for (int i = 0 ; i < 10 ; i++)
        printf ("%d ", x[i]);

    return 0;
}

How can I escape a single quote?

You could try using: &#145;

How do I add a new sourceset to Gradle?

Update for 2021:

A lot has changed in 8ish years. Gradle continues to be a great tool. Now there's a whole section in the docs dedicated to configuring Integration Tests. I recommend you read the docs now.

Original Answer:

This took me a while to figure out and the online resources weren't great. So I wanted to document my solution.

This is a simple gradle build script that has an intTest source set in addition to the main and test source sets:

apply plugin: "java"

sourceSets {
    // Note that just declaring this sourceset creates two configurations.
    intTest {
        java {
            compileClasspath += main.output
            runtimeClasspath += main.output
        }
    }
}

configurations {
    intTestCompile.extendsFrom testCompile
    intTestRuntime.extendsFrom testRuntime
}

task intTest(type:Test){
    description = "Run integration tests (located in src/intTest/...)."
    testClassesDir = project.sourceSets.intTest.output.classesDir
    classpath = project.sourceSets.intTest.runtimeClasspath
}

How to write UTF-8 in a CSV file

It's very simple for Python 3.x (docs).

import csv

with open('output_file_name', 'w', newline='', encoding='utf-8') as csv_file:
    writer = csv.writer(csv_file, delimiter=';')
    writer.writerow('my_utf8_string')

For Python 2.x, look here.

Mailto links do nothing in Chrome but work in Firefox?

I solved the problem using this code:

_x000D_
_x000D_
    _x000D_
<button onclick="email()">Contact me !</button> _x000D_
_x000D_
<script>_x000D_
function email() {_x000D_
    var str = window.open('mailto:[email protected]', '_blank');_x000D_
}_x000D_
</script>
_x000D_
_x000D_
_x000D_

It worked for me like a charm !

How do I pass a string into subprocess.Popen (using the stdin argument)?

Apparently a cStringIO.StringIO object doesn't quack close enough to a file duck to suit subprocess.Popen

I'm afraid not. The pipe is a low-level OS concept, so it absolutely requires a file object that is represented by an OS-level file descriptor. Your workaround is the right one.

join list of lists in python

If you're only going one level deep, a nested comprehension will also work:

>>> x = [["a","b"], ["c"]]
>>> [inner
...     for outer in x
...         for inner in outer]
['a', 'b', 'c']

On one line, that becomes:

>>> [j for i in x for j in i]
['a', 'b', 'c']

How to install Visual Studio 2015 on a different drive

Uninstall the plugins first. And then try this. This uninstaller worked like a charm (I didn't even uninstall 2015 myself, it did everything on its own)!

Any easy way to use icons from resources?

in visual studio for vb.net, go to the project properties, click Add Resource > Existing File, select your Icon.

in your code: Me.Icon = My.Resources.IconResourceName

C# Interfaces. Implicit implementation versus Explicit implementation

In addition to excellent answers already provided, there are some cases where explicit implementation is REQUIRED for the compiler to be able to figure out what is required. Take a look at IEnumerable<T> as a prime example that will likely come up fairly often.

Here's an example:

public abstract class StringList : IEnumerable<string>
{
    private string[] _list = new string[] {"foo", "bar", "baz"};

    // ...

    #region IEnumerable<string> Members
    public IEnumerator<string> GetEnumerator()
    {
        foreach (string s in _list)
        { yield return s; }
    }
    #endregion

    #region IEnumerable Members
    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
    #endregion
}

Here, IEnumerable<string> implements IEnumerable, hence we need to too. But hang on, both the generic and the normal version both implement functions with the same method signature (C# ignores return type for this). This is completely legal and fine. How does the compiler resolve which to use? It forces you to only have, at most, one implicit definition, then it can resolve whatever it needs to.

ie.

StringList sl = new StringList();

// uses the implicit definition.
IEnumerator<string> enumerableString = sl.GetEnumerator();
// same as above, only a little more explicit.
IEnumerator<string> enumerableString2 = ((IEnumerable<string>)sl).GetEnumerator();
// returns the same as above, but via the explicit definition
IEnumerator enumerableStuff = ((IEnumerable)sl).GetEnumerator();

PS: The little piece of indirection in the explicit definition for IEnumerable works because inside the function the compiler knows that the actual type of the variable is a StringList, and that's how it resolves the function call. Nifty little fact for implementing some of the layers of abstraction some of the .NET core interfaces seem to have accumulated.

How can one see content of stack with GDB?

Use:

  • bt - backtrace: show stack functions and args
  • info frame - show stack start/end/args/locals pointers
  • x/100x $sp - show stack memory
(gdb) bt
#0  zzz () at zzz.c:96
#1  0xf7d39cba in yyy (arg=arg@entry=0x0) at yyy.c:542
#2  0xf7d3a4f6 in yyyinit () at yyy.c:590
#3  0x0804ac0c in gnninit () at gnn.c:374
#4  main (argc=1, argv=0xffffd5e4) at gnn.c:389

(gdb) info frame
Stack level 0, frame at 0xffeac770:
 eip = 0x8049047 in main (goo.c:291); saved eip 0xf7f1fea1
 source language c.
 Arglist at 0xffeac768, args: argc=1, argv=0xffffd5e4
 Locals at 0xffeac768, Previous frame's sp is 0xffeac770
 Saved registers:
  ebx at 0xffeac75c, ebp at 0xffeac768, esi at 0xffeac760, edi at 0xffeac764, eip at 0xffeac76c

(gdb) x/10x $sp
0xffeac63c: 0xf7d39cba  0xf7d3c0d8  0xf7d3c21b  0x00000001
0xffeac64c: 0xf78d133f  0xffeac6f4  0xf7a14450  0xffeac678
0xffeac65c: 0x00000000  0xf7d3790e

What is an example of the simplest possible Socket.io example?

Edit: I feel it's better for anyone to consult the excellent chat example on the Socket.IO getting started page. The API has been quite simplified since I provided this answer. That being said, here is the original answer updated small-small for the newer API.

Just because I feel nice today:

index.html

<!doctype html>
<html>
    <head>
        <script src='/socket.io/socket.io.js'></script>
        <script>
            var socket = io();

            socket.on('welcome', function(data) {
                addMessage(data.message);

                // Respond with a message including this clients' id sent from the server
                socket.emit('i am client', {data: 'foo!', id: data.id});
            });
            socket.on('time', function(data) {
                addMessage(data.time);
            });
            socket.on('error', console.error.bind(console));
            socket.on('message', console.log.bind(console));

            function addMessage(message) {
                var text = document.createTextNode(message),
                    el = document.createElement('li'),
                    messages = document.getElementById('messages');

                el.appendChild(text);
                messages.appendChild(el);
            }
        </script>
    </head>
    <body>
        <ul id='messages'></ul>
    </body>
</html>

app.js

var http = require('http'),
    fs = require('fs'),
    // NEVER use a Sync function except at start-up!
    index = fs.readFileSync(__dirname + '/index.html');

// Send index.html to all requests
var app = http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(index);
});

// Socket.io server listens to our app
var io = require('socket.io').listen(app);

// Send current time to all connected clients
function sendTime() {
    io.emit('time', { time: new Date().toJSON() });
}

// Send current time every 10 secs
setInterval(sendTime, 10000);

// Emit welcome message on connection
io.on('connection', function(socket) {
    // Use socket to communicate with this particular client only, sending it it's own id
    socket.emit('welcome', { message: 'Welcome!', id: socket.id });

    socket.on('i am client', console.log);
});

app.listen(3000);

css width: calc(100% -100px); alternative using jquery

Try jQuery animate() method, ex.

$("#divid").animate({'width':perc+'%'});

Docker: Copying files from Docker container to host

docker cp containerId:source_path destination_path

containerId can be obtained from the command docker ps -a

source path should be absolute. for example, if the application/service directory starts from the app in your docker container the path would be /app/some_directory/file

example : docker cp d86844abc129:/app/server/output/server-test.png C:/Users/someone/Desktop/output

Microsoft Excel mangles Diacritics in .csv files?

Check the encoding in which you are generating the file, to make excel display the file correctly you must use the system default codepage.

Wich language are you using? if it's .Net you only need to use Encoding.Default while generating the file.

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

Process GET parameters

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

The following example

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

does basically the following:

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

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

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

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

Performing business action on GET parameters

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

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

with

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

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

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

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

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

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

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

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


Pass view parameters to next view

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

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

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

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

with the original parameter value.

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


Use GET forms in JSF

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

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

With basically this @RequestScoped bean:

private String query;
private List<Result> results;

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

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


See also:

What is the difference between hg forget and hg remove?

The best way to put is that hg forget is identical to hg remove except that it leaves the files behind in your working copy. The files are left behind as untracked files and can now optionally be ignored with a pattern in .hgignore.

In other words, I cannot tell if you used hg forget or hg remove when I pull from you. A file that you ran hg forget on will be deleted when I update to that changeset — just as if you had used hg remove instead.

Multiple inputs with same name through POST in php

It can be:

echo "Welcome".$_POST['firstname'].$_POST['lastname'];

Disable/turn off inherited CSS3 transitions

Another way to remove all transitions is with the unset keyword:

a.tags {
    transition: unset;
}

In the case of transition, unset is equivalent to initial, since transition is not an inherited property:

a.tags {
    transition: initial;
}

A reader who knows about unset and initial can tell that these solutions are correct immediately, without having to think about the specific syntax of transition.

How to filter rows in pandas by regex

Using str slice

foo[foo.b.str[0]=='f']
Out[18]: 
   a    b
1  2  foo
2  3  fat

constant pointer vs pointer on a constant value

I will explain it verbally first and then with an example:

A pointer object can be declared as a const pointer or a pointer to a const object (or both):

const pointer cannot be reassigned to point to a different object from the one it is initially assigned, but it can be used to modify the object that it points to (called the "pointee").
Reference variables are thus an alternate syntax for constpointers.

A pointer to a const object, on the other hand, can be reassigned to point to another object of the same type or of a convertible type, but it cannot be used to modify any object.

const pointer to a const object can also be declared and can neither be used to modify the pointee nor be reassigned to point to another object.

Example:

void Foo( int * ptr,
         int const * ptrToConst,
         int * const constPtr,
         int const * const constPtrToConst ) 
{ 
    *ptr = 0; // OK: modifies the "pointee" data 
    ptr = 0; // OK: modifies the pointer 

    *ptrToConst = 0; // Error! Cannot modify the "pointee" data
     ptrToConst = 0; // OK: modifies the pointer 

    *constPtr = 0; // OK: modifies the "pointee" data 
    constPtr = 0; // Error! Cannot modify the pointer 

    *constPtrToConst = 0; // Error! Cannot modify the "pointee" data 
    constPtrToConst = 0; // Error! Cannot modify the pointer 
}

Happy to help! Good Luck!

Make element fixed on scroll

You can do this with css too.

just use position:fixed; for what you want to be fixed when you scroll down.

you can have some examples here:

http://davidwalsh.name/demo/css-fixed-position.php

http://demo.tutorialzine.com/2010/06/microtut-how-css-position-works/demo.html

Inserting a PDF file in LaTeX

I don't think there would be an automatic way. You might also want to add a page number to the appendix correctly. Assuming that you already have your pdf document of several pages, you'll have to extract each page first of your pdf document using Adobe Acrobat Professional for instance and save each of them as a separate pdf file. Then you'll have to include each of the the pdf documents as images on an each page basis (1 each page) and use newpage between each page e,g,

\appendix
\section{Quiz 1}\label{sec:Quiz}
\begin{figure}[htp] \centering{
\includegraphics[scale=0.82]{quizz.pdf}}
\caption{Experiment 1}
\end{figure}  

\newpage
\section{Sample paper}\label{sec:Sample}
\begin{figure}[htp] \centering{
\includegraphics[scale=0.75]{sampaper.pdf}}
\caption{Experiment 2}
\end{figure}

Now each page will appear with 1 pdf image per page and you'll have a correct page number at the bottom. As shown in my example, you'll have to play a bit with the scale factor for each image to get it in the right size that will fit on a single page. Hope that helps...

Iterating through directories with Python

The actual walk through the directories works as you have coded it. If you replace the contents of the inner loop with a simple print statement you can see that each file is found:

import os
rootdir = 'C:/Users/sid/Desktop/test'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        print os.path.join(subdir, file)

If you still get errors when running the above, please provide the error message.


Updated for Python3

import os
rootdir = 'C:/Users/sid/Desktop/test'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        print(os.path.join(subdir, file))

C# Reflection: How to get class reference from string?

A simple use:

Type typeYouWant = Type.GetType("NamespaceOfType.TypeName, AssemblyName");

Sample:

Type dogClass = Type.GetType("Animals.Dog, Animals");

iPhone/iOS JSON parsing tutorial

Here's a link to my tutorial, which walks you through :

  • creating a JSON WCF Web Service from scratch (and the problems you'll want to avoid)
  • adapting it to read/write SQL Server data
  • getting an iOS 6 app to use the JSON servies.
  • using the JSON web services with JavaScript

http://mikesknowledgebase.com/pages/Services/WebServices-Page1.htm

All source code is provided, free of charge. Enjoy.

Create a table without a header in Markdown

@thamme-gowda's solution works for images too!

| | |:----------------------------------------------------------------------------:| | ![](https://gravatar.com/avatar/4cc702785290b4934c531c56f6061e5e "Tonejito") |

You can check this out on a gist I made for that. Here is a render of the table hack on GitHub and GitLab:

How to generate components in a specific folder with Angular CLI?

Simple

ng g component plainsight/some-name

It will create "plainsight" folder and generate some-name component inside it.

How can I get the size of an std::vector as an int?

In the first two cases, you simply forgot to actually call the member function (!, it's not a value) std::vector<int>::size like this:

#include <vector>

int main () {
    std::vector<int> v;
    auto size = v.size();
}

Your third call

int size = v.size();

triggers a warning, as not every return value of that function (usually a 64 bit unsigned int) can be represented as a 32 bit signed int.

int size = static_cast<int>(v.size());

would always compile cleanly and also explicitly states that your conversion from std::vector::size_type to int was intended.

Note that if the size of the vector is greater than the biggest number an int can represent, size will contain an implementation defined (de facto garbage) value.

Why does make think the target is up to date?

EDIT: This only applies to some versions of make - you should check your man page.

You can also pass the -B flag to make. As per the man page, this does:

-B, --always-make Unconditionally make all targets.

So make -B test would solve your problem if you were in a situation where you don't want to edit the Makefile or change the name of your test folder.

How to get content body from a httpclient call?

If you are not wanting to use async you can add .Result to force the code to execute synchronously:

private string GetResponseString(string text)
{
    var httpClient = new HttpClient();

    var parameters = new Dictionary<string, string>();
    parameters["text"] = text;

    var response = httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters)).Result;
    var contents = response.Content.ReadAsStringAsync().Result;

    return contents;
 }  

How to expand textarea width to 100% of parent (or how to expand any HTML element to 100% of parent width)?

You need to define width of the div containing the textarea and when you declare textarea, you can then set .main > textarea to have width: inherit.

Note: .main > textarea means a <textarea> inside of an element with class="main".

Here is the working solution

The HTML:

<div class="wrapper">
  <div class="left">left</div>
  <div class="main">
    <textarea name="" cols="" rows=""></textarea>
  </div>
</div>

The CSS:

.wrapper {
  display: table;
  width: 100%;
}

.left {
  width: 20%;
  background: #cccccc;
  display: table-cell;
}

.main {
  width: 80%;
  background: gray;
  display: inline;
}

.main > textarea {
  width: inherit;
}

How to set the max value and min value of <input> in html5 by javascript or jquery?

Try this:

<input type="number" max="???" min="???" step="0.5" id="myInput"/>

$("#myInput").attr({
   "max" : 10,
   "min" : 2
});

Note:This will set max and min value only to single input

Routing with multiple Get methods in ASP.NET Web API

Also you will specify route on action for set route

[HttpGet]
[Route("api/customers/")]
public List<Customer> Get()
{
   //gets all customer logic
}

[HttpGet]
[Route("api/customers/currentMonth")]
public List<Customer> GetCustomerByCurrentMonth()
{
     //gets some customer 
}

[HttpGet]
[Route("api/customers/{id}")]
public Customer GetCustomerById(string id)
{
  //gets a single customer by specified id
}
[HttpGet]
[Route("api/customers/customerByUsername/{username}")]
public Customer GetCustomerByUsername(string username)
{
    //gets customer by its username
}

Unzipping files

I wrote "Binary Tools for JavaScript", an open source project that includes the ability to unzip, unrar and untar: https://github.com/codedread/bitjs

Used in my comic book reader: https://github.com/codedread/kthoom (also open source).

HTH!

Populating a dictionary using for loops (python)

dicts = {}
keys = range(4)
values = ["Hi", "I", "am", "John"]
for i in keys:
        dicts[i] = values[i]
print(dicts)

alternatively

In [7]: dict(list(enumerate(values)))
Out[7]: {0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}

Routing with Multiple Parameters using ASP.NET MVC

You can pass arbitrary parameters through the query string, but you can also set up custom routes to handle it in a RESTful way:

http://ws.audioscrobbler.com/2.0/?method=artist.getimages&artist=cher&
                                  api_key=b25b959554ed76058ac220b7b2e0a026

That could be:

routes.MapRoute(
    "ArtistsImages",
    "{ws}/artists/{artist}/{action}/{*apikey}",
    new { ws = "2.0", controller="artists" artist = "", action="", apikey="" }
    );

So if someone used the following route:

ws.audioscrobbler.com/2.0/artists/cher/images/b25b959554ed76058ac220b7b2e0a026/

It would take them to the same place your example querystring did.

The above is just an example, and doesn't apply the business rules and constraints you'd have to set up to make sure people didn't 'hack' the URL.

How to specify a local file within html using the file: scheme?

I had similar issue before and in my case the file was in another machine so i have mapped network drive z to the folder location where my file is then i created a context in tomcat so in my web project i could access the HTML file via context

How can I add a Google search box to my website?

No need to embed! Just simply send the user to google and add the var in the search like this: (Remember, code might not work on this, so try in a browser if it doesn't.) Hope it works!

<textarea id="Blah"></textarea><button onclick="search()">Search</button>
<script>
function search() {
var Blah = document.getElementById("Blah").value;
location.replace("https://www.google.com/search?q=" + Blah + "");
}
</script>

_x000D_
_x000D_
    function search() {_x000D_
    var Blah = document.getElementById("Blah").value;_x000D_
    location.replace("https://www.google.com/search?q=" + Blah + "");_x000D_
    }
_x000D_
<textarea id="Blah"></textarea><button onclick="search()">Search</button>
_x000D_
_x000D_
_x000D_

ALTER TABLE DROP COLUMN failed because one or more objects access this column

In addition to accepted answer, if you're using Entity Migrations for updating database, you should add this line at the beggining of the Up() function in your migration file:

Sql("alter table dbo.CompanyTransactions drop constraint [df__CompanyTr__Creat__0cdae408];");

You can find the constraint name in the error at nuget packet manager console which starts with FK_dbo.

Reading PDF documents in .Net

PDFClown might help, but I would not recommend it for a big or heavy use application.

Bash command line and input limit

The limit for the length of a command line is not imposed by the shell, but by the operating system. This limit is usually in the range of hundred kilobytes. POSIX denotes this limit ARG_MAX and on POSIX conformant systems you can query it with

$ getconf ARG_MAX    # Get argument limit in bytes

E.g. on Cygwin this is 32000, and on the different BSDs and Linux systems I use it is anywhere from 131072 to 2621440.

If you need to process a list of files exceeding this limit, you might want to look at the xargs utility, which calls a program repeatedly with a subset of arguments not exceeding ARG_MAX.

To answer your specific question, yes, it is possible to attempt to run a command with too long an argument list. The shell will error with a message along "argument list too long".

Note that the input to a program (as read on stdin or any other file descriptor) is not limited (only by available program resources). So if your shell script reads a string into a variable, you are not restricted by ARG_MAX. The restriction also does not apply to shell-builtins.

Add Header and Footer for PDF using iTextsharp

As already answered by @Bruno you need to use pageEvents.

Please check out the sample code below:

private void CreatePDF()
{
    string fileName = string.Empty;    
    DateTime fileCreationDatetime = DateTime.Now;    
    fileName = string.Format("{0}.pdf", fileCreationDatetime.ToString(@"yyyyMMdd") + "_" + fileCreationDatetime.ToString(@"HHmmss"));    
    string pdfPath = Server.MapPath(@"~\PDFs\") +   fileName;

    using (FileStream msReport = new FileStream(pdfPath, FileMode.Create))
    {
        //step 1
        using (Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 140f, 10f))
        {
            try
            {
                // step 2
                PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, msReport);
                pdfWriter.PageEvent = new Common.ITextEvents();

                //open the stream 
                pdfDoc.Open();

                for (int i = 0; i < 10; i++)
                {
                    Paragraph para = new Paragraph("Hello world. Checking Header Footer", new Font(Font.FontFamily.HELVETICA, 22));    
                    para.Alignment = Element.ALIGN_CENTER;    
                    pdfDoc.Add(para);    
                    pdfDoc.NewPage();
                }

                pdfDoc.Close();    
            }
            catch (Exception ex)
            {
                //handle exception
            }    
            finally
            { 
            }    
        }    
    }
}

And create one class file named ITextEvents.cs and add following code:

public class ITextEvents : PdfPageEventHelper
{    
    // This is the contentbyte object of the writer
    PdfContentByte cb;

    // we will put the final number of pages in a template
    PdfTemplate headerTemplate, footerTemplate;

    // this is the BaseFont we are going to use for the header / footer
    BaseFont bf = null;

    // This keeps track of the creation time
    DateTime PrintTime = DateTime.Now;    

    #region Fields
    private string _header;
    #endregion

    #region Properties
    public string Header
    {
        get { return _header; }
        set { _header = value; }
    }
    #endregion    

    public override void OnOpenDocument(PdfWriter writer, Document document)
    {
        try
        {
            PrintTime = DateTime.Now;
            bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            cb = writer.DirectContent;
            headerTemplate = cb.CreateTemplate(100, 100);
            footerTemplate = cb.CreateTemplate(50, 50);
        }
        catch (DocumentException de)
        {    
        }
        catch (System.IO.IOException ioe)
        {    
        }
    }

    public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document)
    {
        base.OnEndPage(writer, document);    
        iTextSharp.text.Font baseFontNormal = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);    
        iTextSharp.text.Font baseFontBig = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);    
        Phrase p1Header = new Phrase("Sample Header Here", baseFontNormal);

        //Create PdfTable object
        PdfPTable pdfTab = new PdfPTable(3);

        //We will have to create separate cells to include image logo and 2 separate strings
        //Row 1
        PdfPCell pdfCell1 = new PdfPCell();
        PdfPCell pdfCell2 = new PdfPCell(p1Header);
        PdfPCell pdfCell3 = new PdfPCell();
        String text = "Page " + writer.PageNumber + " of ";    

        //Add paging to header
        {
            cb.BeginText();
            cb.SetFontAndSize(bf, 12);
            cb.SetTextMatrix(document.PageSize.GetRight(200), document.PageSize.GetTop(45));
            cb.ShowText(text);
            cb.EndText();
            float len = bf.GetWidthPoint(text, 12);
            //Adds "12" in Page 1 of 12
            cb.AddTemplate(headerTemplate, document.PageSize.GetRight(200) + len, document.PageSize.GetTop(45));
        }
        //Add paging to footer
        {
            cb.BeginText();
            cb.SetFontAndSize(bf, 12);
            cb.SetTextMatrix(document.PageSize.GetRight(180), document.PageSize.GetBottom(30));
            cb.ShowText(text);
            cb.EndText();
            float len = bf.GetWidthPoint(text, 12);
            cb.AddTemplate(footerTemplate, document.PageSize.GetRight(180) + len, document.PageSize.GetBottom(30));
        }

        //Row 2
        PdfPCell pdfCell4 = new PdfPCell(new Phrase("Sub Header Description", baseFontNormal));

        //Row 3 
        PdfPCell pdfCell5 = new PdfPCell(new Phrase("Date:" + PrintTime.ToShortDateString(), baseFontBig));
        PdfPCell pdfCell6 = new PdfPCell();
        PdfPCell pdfCell7 = new PdfPCell(new Phrase("TIME:" + string.Format("{0:t}", DateTime.Now), baseFontBig));    

        //set the alignment of all three cells and set border to 0
        pdfCell1.HorizontalAlignment = Element.ALIGN_CENTER;
        pdfCell2.HorizontalAlignment = Element.ALIGN_CENTER;
        pdfCell3.HorizontalAlignment = Element.ALIGN_CENTER;
        pdfCell4.HorizontalAlignment = Element.ALIGN_CENTER;
        pdfCell5.HorizontalAlignment = Element.ALIGN_CENTER;
        pdfCell6.HorizontalAlignment = Element.ALIGN_CENTER;
        pdfCell7.HorizontalAlignment = Element.ALIGN_CENTER;    

        pdfCell2.VerticalAlignment = Element.ALIGN_BOTTOM;
        pdfCell3.VerticalAlignment = Element.ALIGN_MIDDLE;
        pdfCell4.VerticalAlignment = Element.ALIGN_TOP;
        pdfCell5.VerticalAlignment = Element.ALIGN_MIDDLE;
        pdfCell6.VerticalAlignment = Element.ALIGN_MIDDLE;
        pdfCell7.VerticalAlignment = Element.ALIGN_MIDDLE;    

        pdfCell4.Colspan = 3;  

        pdfCell1.Border = 0;
        pdfCell2.Border = 0;
        pdfCell3.Border = 0;
        pdfCell4.Border = 0;
        pdfCell5.Border = 0;
        pdfCell6.Border = 0;
        pdfCell7.Border = 0;    

        //add all three cells into PdfTable
        pdfTab.AddCell(pdfCell1);
        pdfTab.AddCell(pdfCell2);
        pdfTab.AddCell(pdfCell3);
        pdfTab.AddCell(pdfCell4);
        pdfTab.AddCell(pdfCell5);
        pdfTab.AddCell(pdfCell6);
        pdfTab.AddCell(pdfCell7);

        pdfTab.TotalWidth = document.PageSize.Width - 80f;
        pdfTab.WidthPercentage = 70;
        //pdfTab.HorizontalAlignment = Element.ALIGN_CENTER;    

        //call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable
        //first param is start row. -1 indicates there is no end row and all the rows to be included to write
        //Third and fourth param is x and y position to start writing
        pdfTab.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 30, writer.DirectContent);
        //set pdfContent value

        //Move the pointer and draw line to separate header section from rest of page
        cb.MoveTo(40, document.PageSize.Height - 100);
        cb.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 100);
        cb.Stroke();

        //Move the pointer and draw line to separate footer section from rest of page
        cb.MoveTo(40, document.PageSize.GetBottom(50) );
        cb.LineTo(document.PageSize.Width - 40, document.PageSize.GetBottom(50));
        cb.Stroke();
    }

    public override void OnCloseDocument(PdfWriter writer, Document document)
    {
        base.OnCloseDocument(writer, document);

        headerTemplate.BeginText();
        headerTemplate.SetFontAndSize(bf, 12);
        headerTemplate.SetTextMatrix(0, 0);
        headerTemplate.ShowText((writer.PageNumber - 1).ToString());
        headerTemplate.EndText();

        footerTemplate.BeginText();
        footerTemplate.SetFontAndSize(bf, 12);
        footerTemplate.SetTextMatrix(0, 0);
        footerTemplate.ShowText((writer.PageNumber - 1).ToString());
        footerTemplate.EndText();  
    }
}

I hope it helps!

Why do we need to use flatMap?

An Observable is an object that emits a stream of events: Next, Error and Completed.

When your function returns an Observable, it is not returning a stream, but an instance of Observable. The flatMap operator simply maps that instance to a stream.

That is the behaviour of flatMap when compared to map: Execute the given function and flatten the resulting object into a stream.

websocket.send() parameter

As I understand it, you want the server be able to send messages through from client 1 to client 2. You cannot directly connect two clients because one of the two ends of a WebSocket connection needs to be a server.

This is some pseudocodish JavaScript:

Client:

var websocket = new WebSocket("server address");

websocket.onmessage = function(str) {
  console.log("Someone sent: ", str);
};

// Tell the server this is client 1 (swap for client 2 of course)
websocket.send(JSON.stringify({
  id: "client1"
}));

// Tell the server we want to send something to the other client
websocket.send(JSON.stringify({
  to: "client2",
  data: "foo"
}));

Server:

var clients = {};

server.on("data", function(client, str) {
  var obj = JSON.parse(str);

  if("id" in obj) {
    // New client, add it to the id/client object
    clients[obj.id] = client;
  } else {
    // Send data to the client requested
    clients[obj.to].send(obj.data);
  }
});

How to count digits, letters, spaces for a string in Python?

sample = ("Python 3.2 is very easy") #sample string  
letters = 0  # initiating the count of letters to 0
numeric = 0  # initiating the count of numbers to 0

        for i in sample:  
            if i.isdigit():      
                numeric +=1      
            elif i.isalpha():    
                letters +=1    
            else:    
               pass  
letters  
numeric  

How to copy a string of std::string type in C++?

Caesar's solution is the best in my opinion, but if you still insist to use the strcpy function, then after you have your strings ready:

string a = "text";
string b = "image";

You can try either:

strcpy(a.data(), b.data());

or

strcpy(a.c_str(), b.c_str());

Just call either the data() or c_str() member functions of the std::string class, to get the char* pointer of the string object.

The strcpy() function doesn't have overload to accept two std::string objects as parameters. It has only one overload to accept two char* pointers as parameters.

Both data and c_str return what does strcpy() want exactly.

Shell - How to find directory of some command?

PATH is an environment variable, and can be displayed with the echo command:

echo $PATH

It's a list of paths separated by the colon character ':'

The which command tells you which file gets executed when you run a command:

which lshw

sometimes what you get is a path to a symlink; if you want to trace that link to where the actual executable lives, you can use readlink and feed it the output of which:

readlink -f $(which lshw)

The -f parameter instructs readlink to keep following the symlink recursively.

Here's an example from my machine:

$ which firefox
/usr/bin/firefox

$ readlink -f $(which firefox)
/usr/lib/firefox-3.6.3/firefox.sh

How to remove constraints from my MySQL table?

  1. Go to structure view of the table
  2. You will see 2 option at top a.Table structure b.Relation view.
  3. Now click on Relation view , here you can drop your foreign key constraint. You will get all relation here.

Java and SSL - java.security.NoSuchAlgorithmException

Try javax.net.ssl.keyStorePassword instead of javax.net.ssl.keyPassword: the latter isn't mentioned in the JSSE ref guide.

The algorithms you mention should be there by default using the default security providers. NoSuchAlgorithmExceptions are often cause by other underlying exceptions (file not found, wrong password, wrong keystore type, ...). It's useful to look at the full stack trace.

You could also use -Djavax.net.debug=ssl, or at least -Djavax.net.debug=ssl,keymanager, to get more debugging information, if the information in the stack trace isn't sufficient.

Is there a list of screen resolutions for all Android based phones and tablets?

You can see a lot of screen sizes on this site.

Parsed list of screens:

From http://www.emirweb.com/ScreenDeviceStatistics.php

####################################################################################################
#    Filter out same-sized same-dp screens and width/height swap.
####################################################################################################
Size: 2560 x 1600 px (1280 x 800 dp) xhdpi
Size: 2048 x 1536 px (1024 x 768 dp) xhdpi
Size: 1920 x 1200 px (1442 x 901 dp) tvdpi
Size: 1920 x 1200 px (1280 x 800 dp) hdpi
Size: 1920 x 1200 px (960 x 600 dp) xhdpi
Size: 1920 x 1200 px (640 x 400 dp) xxhdpi
Size: 1920 x 1152 px (640 x 384 dp) xxhdpi
Size: 1920 x 1080 px (1920 x 1080 dp) mdpi
Size: 1920 x 1080 px (1280 x 720 dp) hdpi
Size: 1920 x 1080 px (960 x 540 dp) xhdpi
Size: 1920 x 1080 px (640 x 360 dp) xxhdpi
Size: 1600 x 1200 px (1066 x 800 dp) hdpi
Size: 1600 x 900 px (1600 x 900 dp) mdpi
Size: 1440 x 904 px (960 x 602 dp) hdpi
Size: 1366 x 768 px (1366 x 768 dp) mdpi
Size: 1360 x 768 px (1360 x 768 dp) mdpi
Size: 1280 x 960 px (640 x 480 dp) xhdpi
Size: 1280 x 800 px (1280 x 800 dp) mdpi
Size: 1280 x 800 px (961 x 600 dp) tvdpi
Size: 1280 x 800 px (853 x 533 dp) hdpi
Size: 1280 x 800 px (640 x 400 dp) xhdpi
Size: 1280 x 768 px (1280 x 768 dp) mdpi
Size: 1280 x 768 px (640 x 384 dp) xhdpi
Size: 1280 x 720 px (1280 x 720 dp) mdpi
Size: 1280 x 720 px (961 x 540 dp) tvdpi
Size: 1280 x 720 px (853 x 480 dp) hdpi
Size: 1280 x 720 px (640 x 360 dp) xhdpi
Size: 1279 x 720 px (639 x 360 dp) xhdpi
Size: 1152 x 720 px (1152 x 720 dp) mdpi
Size: 1080 x 607 px (720 x 404 dp) hdpi
Size: 1024 x 960 px (1024 x 960 dp) mdpi
Size: 1024 x 770 px (1024 x 770 dp) mdpi
Size: 1024 x 768 px (1365 x 1024 dp) ldpi
Size: 1024 x 768 px (1024 x 768 dp) mdpi
Size: 1024 x 768 px (512 x 384 dp) xhdpi
Size: 1024 x 600 px (1365 x 800 dp) ldpi
Size: 1024 x 600 px (1024 x 600 dp) mdpi
Size: 1024 x 600 px (682 x 400 dp) hdpi
Size: 960 x 640 px (480 x 320 dp) xhdpi
Size: 960 x 600 px (960 x 600 dp) ldpi
Size: 960 x 540 px (640 x 360 dp) hdpi
Size: 864 x 480 px (576 x 320 dp) hdpi
Size: 854 x 480 px (569 x 320 dp) hdpi
Size: 800 x 600 px (1066 x 800 dp) ldpi
Size: 800 x 480 px (1066 x 640 dp) ldpi
Size: 800 x 480 px (800 x 480 dp) mdpi
Size: 800 x 480 px (600 x 360 dp) tvdpi
Size: 800 x 480 px (533 x 320 dp) hdpi
Size: 800 x 480 px (266 x 160 dp) xxhdpi
Size: 768 x 576 px (768 x 576 dp) mdpi
Size: 640 x 480 px (640 x 480 dp) mdpi
Size: 640 x 360 px (426 x 240 dp) hdpi
Size: 480 x 320 px (480 x 320 dp) mdpi
Size: 480 x 320 px (320 x 213 dp) hdpi
Size: 432 x 240 px (576 x 320 dp) ldpi
Size: 400 x 240 px (533 x 320 dp) ldpi
Size: 320 x 240 px (426 x 320 dp) ldpi
Size: 280 x 280 px (186 x 186 dp) hdpi

####################################################################################################
#    Sorted by smallest width.
####################################################################################################
sw800dp:
Size: 1920 x 1080 px (1920 x 1080 dp) mdpi
Size: 1024 x 768 px (1365 x 1024 dp) ldpi
Size: 1024 x 960 px (1024 x 960 dp) mdpi
Size: 1920 x 1200 px (1442 x 901 dp) tvdpi
Size: 1600 x 900 px (1600 x 900 dp) mdpi
Size: 800 x 600 px (1066 x 800 dp) ldpi
Size: 1920 x 1200 px (1280 x 800 dp) hdpi
Size: 1024 x 600 px (1365 x 800 dp) ldpi
Size: 2560 x 1600 px (1280 x 800 dp) xhdpi
Size: 1280 x 800 px (1280 x 800 dp) mdpi
Size: 1600 x 1200 px (1066 x 800 dp) hdpi

sw720dp:
Size: 1024 x 770 px (1024 x 770 dp) mdpi
Size: 1366 x 768 px (1366 x 768 dp) mdpi
Size: 1280 x 768 px (1280 x 768 dp) mdpi
Size: 2048 x 1536 px (1024 x 768 dp) xhdpi
Size: 1360 x 768 px (1360 x 768 dp) mdpi
Size: 1024 x 768 px (1024 x 768 dp) mdpi
Size: 1152 x 720 px (1152 x 720 dp) mdpi
Size: 1280 x 720 px (1280 x 720 dp) mdpi
Size: 1920 x 1080 px (1280 x 720 dp) hdpi

sw600dp:
Size: 800 x 480 px (1066 x 640 dp) ldpi
Size: 1440 x 904 px (960 x 602 dp) hdpi
Size: 960 x 600 px (960 x 600 dp) ldpi
Size: 1280 x 800 px (961 x 600 dp) tvdpi
Size: 1024 x 600 px (1024 x 600 dp) mdpi
Size: 1920 x 1200 px (960 x 600 dp) xhdpi

sw480dp:
Size: 768 x 576 px (768 x 576 dp) mdpi
Size: 1920 x 1080 px (960 x 540 dp) xhdpi
Size: 1280 x 720 px (961 x 540 dp) tvdpi
Size: 1280 x 800 px (853 x 533 dp) hdpi
Size: 1280 x 720 px (853 x 480 dp) hdpi
Size: 800 x 480 px (800 x 480 dp) mdpi
Size: 1280 x 960 px (640 x 480 dp) xhdpi
Size: 640 x 480 px (640 x 480 dp) mdpi

sw320dp:
Size: 1080 x 607 px (720 x 404 dp) hdpi
Size: 1024 x 600 px (682 x 400 dp) hdpi
Size: 1280 x 800 px (640 x 400 dp) xhdpi
Size: 1920 x 1200 px (640 x 400 dp) xxhdpi
Size: 1280 x 768 px (640 x 384 dp) xhdpi
Size: 1024 x 768 px (512 x 384 dp) xhdpi
Size: 1920 x 1152 px (640 x 384 dp) xxhdpi
Size: 1279 x 720 px (639 x 360 dp) xhdpi
Size: 800 x 480 px (600 x 360 dp) tvdpi
Size: 960 x 540 px (640 x 360 dp) hdpi
Size: 1920 x 1080 px (640 x 360 dp) xxhdpi
Size: 1280 x 720 px (640 x 360 dp) xhdpi
Size: 432 x 240 px (576 x 320 dp) ldpi
Size: 800 x 480 px (533 x 320 dp) hdpi
Size: 960 x 640 px (480 x 320 dp) xhdpi
Size: 864 x 480 px (576 x 320 dp) hdpi
Size: 854 x 480 px (569 x 320 dp) hdpi
Size: 480 x 320 px (480 x 320 dp) mdpi
Size: 400 x 240 px (533 x 320 dp) ldpi
Size: 320 x 240 px (426 x 320 dp) ldpi

sw240dp:
Size: 640 x 360 px (426 x 240 dp) hdpi

lower:
Size: 480 x 320 px (320 x 213 dp) hdpi
Size: 280 x 280 px (186 x 186 dp) hdpi
Size: 800 x 480 px (266 x 160 dp) xxhdpi

####################################################################################################
#    Different size in px only.
####################################################################################################
2560 x 1600 px
2048 x 1536 px
1920 x 1200 px
1920 x 1152 px
1920 x 1080 px
1600 x 1200 px
1600 x 900 px
1440 x 904 px
1366 x 768 px
1360 x 768 px
1280 x 960 px
1280 x 800 px
1280 x 768 px
1280 x 720 px
1279 x 720 px
1152 x 720 px
1080 x 607 px
1024 x 960 px
1024 x 770 px
1024 x 768 px
1024 x 600 px
960 x 640 px
960 x 600 px
960 x 540 px
864 x 480 px
854 x 480 px
800 x 600 px
800 x 480 px
768 x 576 px
640 x 480 px
640 x 360 px
480 x 320 px
432 x 240 px
400 x 240 px
320 x 240 px
280 x 280 px

####################################################################################################
#    Different size in dp only.
####################################################################################################
1920 x 1080 dp
1600 x 900 dp
1442 x 901 dp
1366 x 768 dp
1365 x 1024 dp
1365 x 800 dp
1360 x 768 dp
1280 x 800 dp
1280 x 768 dp
1280 x 720 dp
1152 x 720 dp
1066 x 800 dp
1066 x 640 dp
1024 x 960 dp
1024 x 770 dp
1024 x 768 dp
1024 x 600 dp
961 x 600 dp
961 x 540 dp
960 x 602 dp
960 x 600 dp
960 x 540 dp
853 x 533 dp
853 x 480 dp
800 x 480 dp
768 x 576 dp
720 x 404 dp
682 x 400 dp
640 x 480 dp
640 x 400 dp
640 x 384 dp
640 x 360 dp
639 x 360 dp
600 x 360 dp
576 x 320 dp
569 x 320 dp
533 x 320 dp
512 x 384 dp
480 x 320 dp
426 x 320 dp
426 x 240 dp
320 x 213 dp
266 x 160 dp
186 x 186 dp

I drop a lot of same-sized same-dp screens, ignore height/width swap and include some sorting results.

How do I activate C++ 11 in CMake?

As it turns out, SET(CMAKE_CXX_FLAGS "-std=c++0x") does activate many C++11 features. The reason it did not work was that the statement looked like this:

set(CMAKE_CXX_FLAGS "-std=c++0x ${CMAKE_CXX_FLAGS} -g -ftest-coverage -fprofile-arcs")

Following this approach, somehow the -std=c++0x flag was overwritten and it did not work. Setting the flags one by one or using a list method is working.

list( APPEND CMAKE_CXX_FLAGS "-std=c++0x ${CMAKE_CXX_FLAGS} -g -ftest-coverage -fprofile-arcs")

How do I start Mongo DB from Windows?

Create MongoDB Service in Windows. First Open cmd with administrator

mongod --port 27017 --dbpath "a mongodb storage actual path e.g: d:\mongo_storage\data" --logpath="a log path e.g: d:\mongo_storage\log\log.txt" --install --serviceName "MongoDB"

After that

Start Service

net start MongoDB

Stop Service

net stop MongoDB

jQuery datepicker years shown

au, nz, ie, etc. are the country codes for the countries whose national days are being displayed (Australia, New Zealand, Ireland, ...). As seen in the code, these values are combined with '_day' and passed back to be applied to that day as a CSS style. The corresponding styles are of the form show below, which moves the text for that day out of the way and replaces it with an image of the country's flag.

.au_day {
  text-indent: -9999px;
  background: #eee url(au.gif) no-repeat center;
}

The 'false' value that is passed back with the new style indicates that these days may not be selected.

How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor version

For me, I was getting this error on the com/sun/javadoc/Doclet class. After some digging, I found that I accidentally copied the tools.jar from Java 8 into my Java 7 folder.

Finding the tools.jar for Java 7 and putting it back into the folder fixed my issue. So something to try.

How to resolve "git pull,fatal: unable to access 'https://github.com...\': Empty reply from server"

I solved such a problem by replacing https part of my remote origin with http. It is also a workaround. I think it may help someone in the future.

How to Clone Objects

It couldn't be simpler than this:

    public SomeClass Clone () {

        var clonedJson = JsonConvert.SerializeObject (this);

        return JsonConvert.DeserializeObject<SomeClass> (clonedJson);
    }

Just serialize any object to a JSON string and then deserialize it. This will do a deep copy...

The POM for project is missing, no dependency information available

Change:

<!-- ANT4X -->
<dependency>
  <groupId>net.sourceforge</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

To:

<!-- ANT4X -->
<dependency>
  <groupId>net.sourceforge.ant4x</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

The groupId of net.sourceforge was incorrect. The correct value is net.sourceforge.ant4x.

Unable to connect to SQL Express "Error: 26-Error Locating Server/Instance Specified)

If you have done anything but in spite of all couldn't connecting?!! In my case i have changed connection part splitting port "," instead of this ":"

The corresponding TCP port or pipe name is not specified in the connection string (such as Srv1\SQL2008, 1433).

UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory'

The MySQL dependency should be like the following syntax in the pom.xml file.

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.21</version>
    </dependency>

Make sure the syntax, groupId, artifactId, Version has included in the dependancy.

How to change Screen buffer size in Windows Command Prompt from batch script

I created the following utility to set the console size and scroll buffers.

I compiled it using DEV C++ (http://www.bloodshed.net/devcpp.html).

An executable is included in https://sourceforge.net/projects/wa2l-wintools/.

#include <iostream>
#include <windows.h> 

using namespace std;


// SetWindow(Width,Height,WidthBuffer,HeightBuffer) -- set console size and buffer dimensions
//
void SetWindow(int Width, int Height, int WidthBuffer, int HeightBuffer) { 
    _COORD coord; 
    coord.X = WidthBuffer; 
    coord.Y = HeightBuffer; 

    _SMALL_RECT Rect; 
    Rect.Top = 0; 
    Rect.Left = 0; 
    Rect.Bottom = Height - 1; 
    Rect.Right = Width - 1; 

    HANDLE Handle = GetStdHandle(STD_OUTPUT_HANDLE);      // Get Handle 
    SetConsoleScreenBufferSize(Handle, coord);            // Set Buffer Size 
    SetConsoleWindowInfo(Handle, TRUE, &Rect);            // Set Window Size 
}  // SetWindow



// main(Width,Height,WidthBuffer,HeightBuffer) -- main
//
int main(int argc, char *argv[]) {     
    int width = 80;
    int height = 25;
    int wbuffer = width + 200;
    int hbuffer = height + 1000;

    if ( argc == 5 ){
        width = atoi(argv[1]);
        height = atoi(argv[2]);
        wbuffer = atoi(argv[3]);
        hbuffer = atoi(argv[4]);
    } else if ( argc > 1 ) {
        cout << "Usage: " << argv[0] << " [ width height bufferwidth bufferheight ]" << endl << endl;
        cout << "  Where" << endl;
        cout << "    width            console width" << endl;
        cout << "    height           console height" << endl;
        cout << "    bufferwidth      scroll buffer width" << endl;
        cout << "    bufferheight     scroll buffer height" << endl;
        return 4;
    }    

    SetWindow(width,height,wbuffer,hbuffer);
    return 0;
} 

What is the difference between Spring, Struts, Hibernate, JavaServer Faces, Tapestry?

Spring is an application framework which deals with IOC (Inversion of Control).

Struts 2 is a web application MVC framework which deals with actions.

Hibernate is an ORM (Object-Relational Mapping) that deals with persistent data.

How to add bootstrap in angular 6 project?

npm install --save bootstrap

afterwards, inside angular.json (previously .angular-cli.json) inside the project's root folder, find styles and add the bootstrap css file like this:

for angular 6

"styles": [
          "../node_modules/bootstrap/dist/css/bootstrap.min.css",
          "styles.css"
],

for angular 7

"styles": [
          "node_modules/bootstrap/dist/css/bootstrap.min.css",
          "src/styles.css"
],

Invariant Violation: Could not find "store" in either the context or props of "Connect(SportsDatabase)"

This happened to me when I upgraded. I had to downgrade back.

react-redux ^5.0.6 ? ^7.1.3

How to add a spinner icon to button when it's in the Loading state?

Here is a full-fledged css solution inspired by Bulma. Just add

    .button {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      position: relative;
      min-width: 200px;
      max-width: 100%;
      min-height: 40px;
      text-align: center;
      cursor: pointer;
    }

    @-webkit-keyframes spinAround {
      from {
        -webkit-transform: rotate(0deg);
        transform: rotate(0deg);
      }
      to {
        -webkit-transform: rotate(359deg);
        transform: rotate(359deg);
      }
    }
    @keyframes spinAround {
      from {
        -webkit-transform: rotate(0deg);
        transform: rotate(0deg);
      }
      to {
        -webkit-transform: rotate(359deg);
        transform: rotate(359deg);
      }
    }

    .button.is-loading {
      text-indent: -9999px;
      box-shadow: none;
      font-size: 1rem;
      height: 2.25em;
      line-height: 1.5;
      vertical-align: top;
      padding-bottom: calc(0.375em - 1px);
      padding-left: 0.75em;
      padding-right: 0.75em;
      padding-top: calc(0.375em - 1px);
      white-space: nowrap;
    }

    .button.is-loading::after  {
      -webkit-animation: spinAround 500ms infinite linear;
      animation: spinAround 500ms infinite linear;
      border: 2px solid #dbdbdb;
      border-radius: 290486px;
      border-right-color: transparent;
      border-top-color: transparent;
      content: "";
      display: block;
      height: 1em;
      position: relative;
      width: 1em;
    }

How to find where gem files are installed

You can trick gem open into displaying the gem path:

VISUAL=echo gem open gem-name

Example:

VISUAL=echo gem open rails
=> /usr/local/opt/asdf/installs/ruby/2.4.3/lib/ruby/gems/2.4.0/gems/rails-5.1.4

It just works, and no third party gem is necessary.

Passing parameters on button action:@selector

UIButton responds to addTarget:action:forControlEvents: since it inherits from UIControl. But it does not respond to addTarget:action:withObject:forControlEvents:

see reference for the method and for UIButton

You could extend UIButton with a category to implement that method, thought.

How do I create a SQL table under a different schema?

  1. Right-click on the tables node and choose New Table...
  2. With the table designer open, open the properties window (view -> Properties Window).
  3. You can change the schema that the table will be made in by choosing a schema in the properties window.

Formatting floats without trailing zeros

What about trying the easiest and probably most effective approach? The method normalize() removes all the rightmost trailing zeros.

from decimal import Decimal

print (Decimal('0.001000').normalize())
# Result: 0.001

Works in Python 2 and Python 3.

-- Updated --

The only problem as @BobStein-VisiBone pointed out, is that numbers like 10, 100, 1000... will be displayed in exponential representation. This can be easily fixed using the following function instead:

from decimal import Decimal


def format_float(f):
    d = Decimal(str(f));
    return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()

warning: incompatible implicit declaration of built-in function ‘xyz’

Here is some C code that produces the above mentioned error:

int main(int argc, char **argv) {
  exit(1);
}

Compiled like this on Fedora 17 Linux 64 bit with gcc:

el@defiant ~/foo2 $ gcc -o n n2.c                                                               
n2.c: In function ‘main’:
n2.c:2:3: warning: incompatible implicit declaration of built-in 
function ‘exit’ [enabled by default]
el@defiant ~/foo2 $ ./n 
el@defiant ~/foo2 $ 

To make the warning go away, add this declaration to the top of the file:

#include <stdlib.h>

Making an iframe responsive

check out this solution... works for me >> https://jsfiddle.net/y49jpdns/

<html lang="en" class="no-js">
   <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width,initial-scale=1.0">
      <style>
      html body {width: 100%;height: 100%;padding: 0px;margin: 0px;overflow: hidden;font-family: arial;font-size: 10px;color: #6e6e6e;background-color: #000;} #preview-frame {width: 100%;background-color: #fff;}</style>
      <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
      <script>
         var calcHeight = function() {
           $('#preview-frame').height($(window).height());
         }

         $(document).ready(function() {
           calcHeight();
         }); 

         $(window).resize(function() {
           calcHeight();
         }).load(function() {
           calcHeight();
         });
      </script>
   </head>
   <body>
      <iframe id="preview-frame" src="http://leowebguy.com/" name="preview-frame" frameborder="0" noresize="noresize">
      </iframe>
   </body>
</html>

How do you replace double quotes with a blank space in Java?

You don't need regex for this. Just a character-by-character replace is sufficient. You can use String#replace() for this.

String replaced = original.replace("\"", " ");

Note that you can also use an empty string "" instead to replace with. Else the spaces would double up.

String replaced = original.replace("\"", "");

How to run binary file in Linux

:-) If not typo, why are you using ./commonRT instead of ./commonKT ??

Android Studio how to run gradle sync manually?

gradle --recompile-scripts

seems to do a sync without building anything. you can enable automatic building by

gradle --recompile-scripts --continuous

Please refer the docs for more info:

https://docs.gradle.org/current/userguide/gradle_command_line.html

How can I check if a string is null or empty in PowerShell?

If it is a parameter in a function, you can validate it with ValidateNotNullOrEmpty as you can see in this example:

Function Test-Something
{
    Param(
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [string]$UserName
    )

    #stuff todo
}

How to empty/destroy a session in rails?

add this code to your ApplicationController

def reset_session
  @_request.reset_session
end

( Dont know why no one above just mention this code as it fixed my problem ) http://apidock.com/rails/ActionController/RackDelegation/reset_session

Gson: Directly convert String to JsonObject (no POJO)

com.google.gson.JsonParser#parse(java.lang.String) is now deprecated

so use com.google.gson.JsonParser#parseString, it works pretty well

Kotlin Example:

val mJsonObject = JsonParser.parseString(myStringJsonbject).asJsonObject

Java Example:

JsonObject mJsonObject = JsonParser.parseString(myStringJsonbject).getAsJsonObject();

SQL Server: combining multiple rows into one row

I believe for databases which support listagg function, you can do:

select id, issue, customfield, parentkey, listagg(stingvalue, ',') within group (order by id)
from jira.customfieldvalue
where customfield = 12534 and issue = 19602
group by id, issue, customfield, parentkey

Fastest way to get the first n elements of a List into an Array

Assumption:

list - List<String>

Using Java 8 Streams,

  • to get first N elements from a list into a list,

    List<String> firstNElementsList = list.stream().limit(n).collect(Collectors.toList());

  • to get first N elements from a list into an Array,

    String[] firstNElementsArray = list.stream().limit(n).collect(Collectors.toList()).toArray(new String[n]);

How do I see which checkbox is checked?

If the checkbox is checked, then the checkbox's value will be passed. Otherwise, the field is not passed in the HTTP post.

if (isset($_POST['mycheckbox'])) {
    echo "checked!";
}

How to hide image broken Icon using only CSS/HTML?

Use the object tag. Add alternative text between the tags like this:

<object data="img/failedToLoad.png" type="image/png">Alternative Text</object>

http://www.w3schools.com/tags/tag_object.asp

jQuery, checkboxes and .is(":checked")

As of June 2016 (using jquery 2.1.4) none of the other suggested solutions work. Checking attr('checked') always returns undefined and is('checked) always returns false.

Just use the prop method:

$("#checkbox").change(function(e) {

  if ($(this).prop('checked')){
    console.log('checked');
  }
});

Move view with keyboard using Swift

For Swift 3, I made a UIViewController subclass since I needed constant behavior in all View Controllers.

class SomeClassVC: UIViewController {

  //MARK: - Lifecycle
  override func viewDidLoad() {
    super.viewDidLoad()

    addKeyboardObservers()
  }

  override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    removeKeyboardObservers()
  }

  //MARK: - Overrides
  override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    view.endEditing(true)
  }

  //MARK: - Help
  func addKeyboardObservers() {
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
  }

  func removeKeyboardObservers() {
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: self.view.window)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: self.view.window)
  }

  func keyboardWillShow(notification: NSNotification) {
    let keyboardHeight = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.height
    UIView.animate(withDuration: 0.1, animations: { () -> Void in
      self.view.window?.frame.origin.y = -1 * keyboardHeight!
      self.view.layoutIfNeeded()
    })
  }

  func keyboardWillHide(notification: NSNotification) {
    UIView.animate(withDuration: 0.1, animations: { () -> Void in
      self.view.window?.frame.origin.y = 0
      self.view.layoutIfNeeded()
    })
  }

  func resignTextFieldFirstResponders() {
    for textField in self.view.subviews where textField is UITextField {
      textField.resignFirstResponder()
    }
  }

  func resignAllFirstResponders() {
      view.endEditing(true)
  }
}

Can an Android NFC phone act as an NFC tag?

yes you can. Android kitkat boosts of this functionality here

Check if Python Package is installed

As an extension of this answer:

For Python 2.*, pip show <package_name> will perform the same task.

For example pip show numpy will return the following or alike:

Name: numpy
Version: 1.11.1
Summary: NumPy: array processing for numbers, strings, records, and objects.
Home-page: http://www.numpy.org
Author: NumPy Developers
Author-email: [email protected]
License: BSD
Location: /home/***/anaconda2/lib/python2.7/site-packages
Requires: 
Required-by: smop, pandas, tables, spectrum, seaborn, patsy, odo, numpy-stl, numba, nfft, netCDF4, MDAnalysis, matplotlib, h5py, GridDataFormats, dynd, datashape, Bottleneck, blaze, astropy

How to insert date values into table

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

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

Reducing video size with same format and reducing frame size

Instead of chosing fixed bit rates, with the H.264 codec, you can also chose a different preset as described at https://trac.ffmpeg.org/wiki/x264EncodingGuide. I also found Video encoder comparison at KeyJ's blog (archived version) an interesting read, it compares H.264 against Theora and others.

Following is a comparison of various options I tried. The recorded video was originally 673M in size, taken on an iPad using RecordMyScreen. It has a duration of about 20 minutes with a resolution of 1024x768 (with half of the video being blank, so I cropped it to 768x768). In order to reduce size, I lowered the resolution to 480x480. There is no audio.

The results, taking the same 1024x768 as base (and applying cropping, scaling and a filter):

  • With no special options: 95M (encoding time: 1m19s).
  • With only -b 512k added, the size dropped to 77M (encoding time: 1m17s).
  • With only -preset veryslow (and no -b), it became 70M (encoding time: 6m14s)
  • With both -b 512k and -preset veryslow, the size becomes 77M (100K smaller than just -b 512k).
  • With -preset veryslow -crf 28, I get a file of 39M which took 5m47s (with no visual quality difference to me).

N=1, so take the results with a grain of salt and perform your own tests.

Javascript: set label text

InnerHTML should be innerHTML:

document.getElementById('LblAboutMeCount').innerHTML = charsleft;

You should bind your checkLength function to your textarea with jQuery rather than calling it inline and rather intrusively:

$(document).ready(function() {
    $('textarea[name=text]').keypress(function(e) {
        checkLength($(this),512,$('#LblTextCount'));
    }).focus(function() {
        checkLength($(this),512,$('#LblTextCount'));
    });
});

You can neaten up checkLength by using more jQuery, and I wouldn't use 'object' as a formal parameter:

function checkLength(obj, maxlength, label) {
    charsleft = (maxlength - obj.val().length);
    // never allow to exceed the specified limit
    if( charsleft < 0 ) {
        obj.val(obj.val().substring(0, maxlength-1));
    }
    // I'm trying to set the value of charsleft into the label
    label.text(charsleft);
    $('#LblAboutMeCount').html(charsleft);
}

So if you apply the above, you can change your markup to:

<textarea name="text"></textarea>

bash string compare to multiple correct values

Instead of saying:

if [ "$cms" != "wordpress" && "$cms" != "meganto" && "$cms" != "typo3" ]; then

say:

if [[ "$cms" != "wordpress" && "$cms" != "meganto" && "$cms" != "typo3" ]]; then

You might also want to refer to Conditional Constructs.

Validate fields after user has left a field

To pick up further on the given answers, you can simplify input tagging by using CSS3 pseudo-classes and only marking visited fields with a class to delay displaying validation errors until the user lost focus on the field:

(Example requires jQuery)

JavaScript

module = angular.module('app.directives', []);
module.directive('lateValidateForm', function () {
    return {
        restrict: 'AC',
        link: function (scope, element, attrs) {
            $inputs = element.find('input, select, textarea');

            $inputs.on('blur', function () {
                $(this).addClass('has-visited');
            });

            element.on('submit', function () {
                $inputs.addClass('has-visited');
            });
        }
    };
});

CSS

input.has-visited:not(:focus):required:invalid,
textarea.has-visited:not(:focus):required:invalid,
select.has-visited:not(:focus):required:invalid {
  color: #b94a48;
  border-color: #ee5f5b;
}

HTML

<form late-validate-form name="userForm">
  <input type="email" name="email" required />
</form>

Removing double quotes from variables in batch file creates problems with CMD environment

Spent a lot of time trying to do this in a simple way. After looking at FOR loop carefully, I realized I can do this with just one line of code:

FOR /F "delims=" %%I IN (%Quoted%) DO SET Unquoted=%%I

Example:

@ECHO OFF
SET Quoted="Test string"

FOR /F "delims=" %%I IN (%Quoted%) DO SET Unquoted=%%I

ECHO %Quoted%
ECHO %Unquoted%

Output:

"Test string"
Test string

What is the correct XPath for choosing attributes that contain "foo"?

For the code above... //*[contains(@prop,'foo')]

How to detect READ_COMMITTED_SNAPSHOT is enabled?

  1. As per https://msdn.microsoft.com/en-us/library/ms180065.aspx, "DBCC USEROPTIONS reports an isolation level of 'read committed snapshot' when the database option READ_COMMITTED_SNAPSHOT is set to ON and the transaction isolation level is set to 'read committed'. The actual isolation level is read committed."

  2. Also in SQL Server Management Studio, in database properties under Options->Miscellaneous there is "Is Read Committed Snapshot On" option status

Turn off iPhone/Safari input element rounding

I had the same problem but only for the submit button. Needed to remove the inner shadow and rounded corners -

input[type="submit"] { -webkit-appearance:none; -webkit-border-radius:0; }

Using CSS for a fade-in effect on page load

Method 1:

If you are looking for a self-invoking transition then you should use CSS 3 Animations. They aren't supported either, but this is exactly the kind of thing they were made for.

CSS

#test p {
    margin-top: 25px;
    font-size: 21px;
    text-align: center;

    -webkit-animation: fadein 2s; /* Safari, Chrome and Opera > 12.1 */
       -moz-animation: fadein 2s; /* Firefox < 16 */
        -ms-animation: fadein 2s; /* Internet Explorer */
         -o-animation: fadein 2s; /* Opera < 12.1 */
            animation: fadein 2s;
}

@keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Firefox < 16 */
@-moz-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Safari, Chrome and Opera > 12.1 */
@-webkit-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Internet Explorer */
@-ms-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Opera < 12.1 */
@-o-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

Demo

Browser Support

All modern browsers and Internet Explorer 10 (and later): http://caniuse.com/#feat=css-animation


Method 2:

Alternatively, you can use jQuery (or plain JavaScript; see the third code block) to change the class on load:

jQuery

$("#test p").addClass("load");?

CSS

#test p {
    opacity: 0;
    font-size: 21px;
    margin-top: 25px;
    text-align: center;

    -webkit-transition: opacity 2s ease-in;
       -moz-transition: opacity 2s ease-in;
        -ms-transition: opacity 2s ease-in;
         -o-transition: opacity 2s ease-in;
            transition: opacity 2s ease-in;
}

#test p.load {
    opacity: 1;
}

Plain JavaScript (not in the demo)

document.getElementById("test").children[0].className += " load";

Demo

Browser Support

All modern browsers and Internet Explorer 10 (and later): http://caniuse.com/#feat=css-transitions


Method 3:

Or, you can use the method that .Mail uses:

jQuery

$("#test p").delay(1000).animate({ opacity: 1 }, 700);?

CSS

#test p {
    opacity: 0;
    font-size: 21px;
    margin-top: 25px;
    text-align: center;
}

Demo

Browser Support

jQuery 1.x: All modern browsers and Internet Explorer 6 (and later): http://jquery.com/browser-support/
jQuery 2.x: All modern browsers and Internet Explorer 9 (and later): http://jquery.com/browser-support/

This method is the most cross-compatible as the target browser does not need to support CSS 3 transitions or animations.

How do I iterate through children elements of a div using jQuery?

Use children() and each(), you can optionally pass a selector to children

$('#mydiv').children('input').each(function () {
    alert(this.value); // "this" is the current element in the loop
});

You could also just use the immediate child selector:

$('#mydiv > input').each(function () { /* ... */ });

How can I get an object's absolute position on the page in Javascript?

I would definitely suggest using element.getBoundingClientRect().

https://developer.mozilla.org/en-US/docs/Web/API/element.getBoundingClientRect

Summary

Returns a text rectangle object that encloses a group of text rectangles.

Syntax

var rectObject = object.getBoundingClientRect();

Returns

The returned value is a TextRectangle object which is the union of the rectangles returned by getClientRects() for the element, i.e., the CSS border-boxes associated with the element.

The returned value is a TextRectangle object, which contains read-only left, top, right and bottom properties describing the border-box, in pixels, with the top-left relative to the top-left of the viewport.

Here's a browser compatibility table taken from the linked MDN site:

+---------------+--------+-----------------+-------------------+-------+--------+
|    Feature    | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
+---------------+--------+-----------------+-------------------+-------+--------+
| Basic support | 1.0    | 3.0 (1.9)       | 4.0               | (Yes) | 4.0    |
+---------------+--------+-----------------+-------------------+-------+--------+

It's widely supported, and is really easy to use, not to mention that it's really fast. Here's a related article from John Resig: http://ejohn.org/blog/getboundingclientrect-is-awesome/

You can use it like this:

var logo = document.getElementById('hlogo');
var logoTextRectangle = logo.getBoundingClientRect();

console.log("logo's left pos.:", logoTextRectangle.left);
console.log("logo's right pos.:", logoTextRectangle.right);

Here's a really simple example: http://jsbin.com/awisom/2 (you can view and edit the code by clicking "Edit in JS Bin" in the upper right corner).

Or here's another one using Chrome's console: Using element.getBoundingClientRect() in Chrome

Note:

I have to mention that the width and height attributes of the getBoundingClientRect() method's return value are undefined in Internet Explorer 8. It works in Chrome 26.x, Firefox 20.x and Opera 12.x though. Workaround in IE8: for width, you could subtract the return value's right and left attributes, and for height, you could subtract bottom and top attributes (like this).

How do I tell what type of value is in a Perl variable?

I like polymorphism instead of manually checking for something:

use MooseX::Declare;

class Foo {
    use MooseX::MultiMethods;

    multi method foo (ArrayRef $arg){ say "arg is an array" }
    multi method foo (HashRef $arg) { say "arg is a hash" }
    multi method foo (Any $arg)     { say "arg is something else" }
}

Foo->new->foo([]); # arg is an array
Foo->new->foo(40); # arg is something else

This is much more powerful than manual checking, as you can reuse your "checks" like you would any other type constraint. That means when you want to handle arrays, hashes, and even numbers less than 42, you just write a constraint for "even numbers less than 42" and add a new multimethod for that case. The "calling code" is not affected.

Your type library:

package MyApp::Types;
use MooseX::Types -declare => ['EvenNumberLessThan42'];
use MooseX::Types::Moose qw(Num);

subtype EvenNumberLessThan42, as Num, where { $_ < 42 && $_ % 2 == 0 };

Then make Foo support this (in that class definition):

class Foo {
    use MyApp::Types qw(EvenNumberLessThan42);

    multi method foo (EvenNumberLessThan42 $arg) { say "arg is an even number less than 42" }
}

Then Foo->new->foo(40) prints arg is an even number less than 42 instead of arg is something else.

Maintainable.

How to remove commits from a pull request

If you're removing a commit and don't want to keep its changes @ferit has a good solution.

If you want to add that commit to the current branch, but doesn't make sense to be part of the current pr, you can do the following instead:

  1. use git rebase -i HEAD~n
  2. Swap the commit you want to remove to the bottom (most recent) position
  3. Save and exit
  4. use git reset HEAD^ --soft to uncommit the changes and get them back in a staged state.
  5. use git push --force to update the remote branch without your removed commit.

Now you'll have removed the commit from your remote, but will still have the changes locally.

What does this thread join code mean?

Simply put:
t1.join() returns after t1 is completed.
It doesn't do anything to thread t1, except wait for it to finish.
Naturally, code following t1.join() will be executed only after t1.join() returns.

ini_set("memory_limit") in PHP 5.3.3 is not working at all

Ubuntu 10.04 comes with the Suhosin patch only, which does not give you configuration options. But you can install php5-suhosin to solve this:

apt-get update
apt-get install php5-suhosin

Now you can edit /etc/php5/conf.d/suhosin.ini and set:

suhosin.memory_limit = 1G

Then using ini_set will work in a script:

ini_set('memory_limit', '256M');

Storing and retrieving datatable from session

A simple solution for a very common problem

                 // DECLARATION
                HttpContext context = HttpContext.Current;
                DataTable dt_ShoppingBasket = context.Session["Shopping_Basket"] as DataTable;

                // TRY TO ADD rows with the info into the DataTable
                try
                {
                    // Add new Serial Code into DataTable dt_ShoppingBasket
                    dt_ShoppingBasket.Rows.Add(new_SerialCode.ToString());

                    // Assigns new DataTable to Session["Shopping_Basket"]
                    context.Session["Shopping_Basket"] = dt_ShoppingBasket;
                }
                catch (Exception)
                {
                    // IF FAIL (EMPTY OR DOESN'T EXIST) - 
                    // Create new Instance, 
                    DataTable dt_ShoppingBasket= new DataTable();

                    // Add column and Row with the info
                    dt_ShoppingBasket.Columns.Add("Serial");
                    dt_ShoppingBasket.Rows.Add(new_SerialCode.ToString());

                    // Assigns new DataTable to Session["Shopping_Basket"]
                    context.Session["Shopping_Basket"] = dt_PanierCommande;
                }



                // PRINT TESTS
                DataTable dt_To_Print = context.Session["Shopping_Basket"] as DataTable;

                foreach (DataRow row in dt_To_Print.Rows)
                {
                    foreach (var item in row.ItemArray)
                    {
                        Debug.WriteLine("DATATABLE IN SESSION: " + item);
                    }
                }

Detecting when Iframe content has loaded (Cross browser)

to detect when the iframe has loaded and its document is ready?

It's ideal if you can get the iframe to tell you itself from a script inside the frame. For example it could call a parent function directly to tell it it's ready. Care is always required with cross-frame code execution as things can happen in an order you don't expect. Another alternative is to set ‘var isready= true;’ in its own scope, and have the parent script sniff for ‘contentWindow.isready’ (and add the onload handler if not).

If for some reason it's not practical to have the iframe document co-operate, you've got the traditional load-race problem, namely that even if the elements are right next to each other:

<img id="x" ... />
<script type="text/javascript">
    document.getElementById('x').onload= function() {
        ...
    };
</script>

there is no guarantee that the item won't already have loaded by the time the script executes.

The ways out of load-races are:

  1. on IE, you can use the ‘readyState’ property to see if something's already loaded;

  2. if having the item available only with JavaScript enabled is acceptable, you can create it dynamically, setting the ‘onload’ event function before setting source and appending to the page. In this case it cannot be loaded before the callback is set;

  3. the old-school way of including it in the markup:

    <img onload="callback(this)" ... />

Inline ‘onsomething’ handlers in HTML are almost always the wrong thing and to be avoided, but in this case sometimes it's the least bad option.

how to remove time from datetime

First thing's first, if your dates are in varchar format change that, store dates as dates it will save you a lot of headaches and it is something that is best done sooner rather than later. The problem will only get worse.

Secondly, once you have a date DO NOT convert the date to a varchar! Keep it in date format and use formatting on the application side to get the required date format.

There are various methods to do this depending on your DBMS:


SQL-Server 2008 and later:

SELECT  CAST(CURRENT_TIMESTAMP AS DATE)

SQL-Server 2005 and Earlier

SELECT  DATEADD(DAY, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP), 0)

SQLite

SELECT  DATE(NOW())

Oracle

SELECT  TRUNC(CURRENT_TIMESTAMP)

Postgresql

SELECT  CURRENT_TIMESTAMP::DATE

If you need to use culture specific formatting in your report you can either explicitly state the format of the receiving text box (e.g. dd/MM/yyyy), or you can set the language so that it shows the relevant date format for that language.

Either way this is much better handled outside of SQL as converting to varchar within SQL will impact any sorting you may do in your report.

If you cannot/will not change the datatype to DATETIME, then still convert it to a date within SQL (e.g. CONVERT(DATETIME, yourField)) before sending to report services and handle it as described above.

How to compare arrays in JavaScript?

On the same lines as JSON.encode is to use join().

function checkArrays( arrA, arrB ){

    //check if lengths are different
    if(arrA.length !== arrB.length) return false;


    //slice so we do not effect the original
    //sort makes sure they are in order
    //join makes it a string so we can do a string compare
    var cA = arrA.slice().sort().join(","); 
    var cB = arrB.slice().sort().join(",");

    return cA===cB;

}

var a = [1,2,3,4,5];
var b = [5,4,3,2,1];
var c = [1,2,3,4];
var d = [1,2,3,4,6];
var e = ["1","2","3","4","5"];  //will return true

console.log( checkArrays(a,b) );  //true
console.log( checkArrays(a,c) );  //false
console.log( checkArrays(a,d) );  //false
console.log( checkArrays(a,e) );  //true

Only problem is if you care about types which the last comparison tests. If you care about types, you will have to loop.

function checkArrays( arrA, arrB ){

    //check if lengths are different
    if(arrA.length !== arrB.length) return false;

    //slice so we do not effect the orginal
    //sort makes sure they are in order
    var cA = arrA.slice().sort(); 
    var cB = arrB.slice().sort();

    for(var i=0;i<cA.length;i++){
         if(cA[i]!==cB[i]) return false;
    }

    return true;

}

var a = [1,2,3,4,5];
var b = [5,4,3,2,1];
var c = [1,2,3,4];
var d = [1,2,3,4,6];
var e = ["1","2","3","4","5"];

console.log( checkArrays(a,b) );  //true
console.log( checkArrays(a,c) );  //false
console.log( checkArrays(a,d) );  //false
console.log( checkArrays(a,e) );  //false

If the order should remain the same, than it is just a loop, no sort is needed.

function checkArrays( arrA, arrB ){

    //check if lengths are different
    if(arrA.length !== arrB.length) return false;


    for(var i=0;i<arrA.length;i++){
         if(arrA[i]!==arrB[i]) return false;
    }

    return true;

}

var a = [1,2,3,4,5];
var b = [5,4,3,2,1];
var c = [1,2,3,4];
var d = [1,2,3,4,6];
var e = ["1","2","3","4","5"];

console.log( checkArrays(a,a) );  //true
console.log( checkArrays(a,b) );  //false
console.log( checkArrays(a,c) );  //false
console.log( checkArrays(a,d) );  //false
console.log( checkArrays(a,e) );  //false

How to convert std::string to lower case?

This is a follow-up to Stefan Mai's response: if you'd like to place the result of the conversion in another string, you need to pre-allocate its storage space prior to calling std::transform. Since STL stores transformed characters at the destination iterator (incrementing it at each iteration of the loop), the destination string will not be automatically resized, and you risk memory stomping.

#include <string>
#include <algorithm>
#include <iostream>

int main (int argc, char* argv[])
{
  std::string sourceString = "Abc";
  std::string destinationString;

  // Allocate the destination space
  destinationString.resize(sourceString.size());

  // Convert the source string to lower case
  // storing the result in destination string
  std::transform(sourceString.begin(),
                 sourceString.end(),
                 destinationString.begin(),
                 ::tolower);

  // Output the result of the conversion
  std::cout << sourceString
            << " -> "
            << destinationString
            << std::endl;
}

Override browser form-filling and input highlighting with HTML/CSS

This fixes the problem on both Safari and Chrome

if(navigator.userAgent.toLowerCase().indexOf("chrome") >= 0 || navigator.userAgent.toLowerCase().indexOf("safari") >= 0){
window.setInterval(function(){
    $('input:-webkit-autofill').each(function(){
        var clone = $(this).clone(true, true);
        $(this).after(clone).remove();
    });
}, 20);
}

How to change a PG column to NULLABLE TRUE?

From the fine manual:

ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;

There's no need to specify the type when you're just changing the nullability.

CSS rotation cross browser with jquery.animate()

Without plugin cross browser with setInterval:

                        function rotatePic() {
                            jQuery({deg: 0}).animate(
                               {deg: 360},  
                               {duration: 3000, easing : 'linear', 
                                 step: function(now, fx){
                                   jQuery("#id").css({
                                      '-moz-transform':'rotate('+now+'deg)',
                                      '-webkit-transform':'rotate('+now+'deg)',
                                      '-o-transform':'rotate('+now+'deg)',
                                      '-ms-transform':'rotate('+now+'deg)',
                                      'transform':'rotate('+now+'deg)'
                                  });
                              }
                            });
                        }

                        var sec = 3;
                        rotatePic();
                        var timerInterval = setInterval(function() {
                            rotatePic();
                            sec+=3;
                            if (sec > 30) {
                                clearInterval(timerInterval);
                            }
                        }, 3000);

Trying to embed newline in a variable in bash

var="a b c"
for i in $var
do
   p=`echo -e "$p"'\n'$i`
done
echo "$p"

The solution was simply to protect the inserted newline with a "" during current iteration when variable substitution happens.

How do I convert date/time from 24-hour format to 12-hour AM/PM?

I think you can use date() function to achive this

$date = '19:24:15 06/13/2013'; 
echo date('h:i:s a m/d/Y', strtotime($date));

This will output

07:24:15 pm 06/13/2013

Live Sample

h is used for 12 digit time
i stands for minutes
s seconds
a will return am or pm (use in uppercase for AM PM)
m is used for months with digits
d is used for days in digit
Y uppercase is used for 4 digit year (use it lowercase for two digit)

Updated

This is with DateTime

$date = new DateTime('19:24:15 06/13/2013');
echo $date->format('h:i:s a m/d/Y') ;

Live Sample

How to set time to midnight for current day?

Related, so I thought I would post for others. If you want to find the UTC of the start of today (for your timezone) the following code works for any UTC offset (-23.5 thru +23.5). This looks like we add X hours then subtract X hours, but the important thing is the ".Date" after the add.

double utcOffset= 10.0;  // Set to your UTC offset in hours (eg. Melbourne Australia)
var now = DateTime.UtcNow;

var startOfToday = now.AddHours(utcOffset - 24.0).Date;
startOfToday = startOfToday.AddHours(24.0 - utcOffset);

Process list on Linux via Python

The sanctioned way of creating and using child processes is through the subprocess module.

import subprocess
pl = subprocess.Popen(['ps', '-U', '0'], stdout=subprocess.PIPE).communicate()[0]
print pl

The command is broken down into a python list of arguments so that it does not need to be run in a shell (By default the subprocess.Popen does not use any kind of a shell environment it just execs it). Because of this we cant simply supply 'ps -U 0' to Popen.

Path to MSBuild

The Registry locations

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\2.0
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\3.5

give the location for the executable.

But if you need the location where to save the Task extensions, it's on

%ProgramFiles%\MSBuild

Add JavaScript object to JavaScript object

// Merge object2 into object1, recursively

$.extend( true, object1, object2 );

// Merge object2 into object1

$.extend( object1, object2 );

https://api.jquery.com/jquery.extend/

PHP: date function to get month of the current date

To compare with an int do this:

<?php
$date = date("m");
$dateToCompareTo = 05;
if (strval($date) == strval($dateToCompareTo)) {
    echo "They are the same";
}
?>

Change the location of the ~ directory in a Windows install of Git Bash

I don't understand, why you don't want to set the $HOME environment variable since that solves exactly what you're asking for.

cd ~ doesn't mean change to the root directory, but change to the user's home directory, which is set by the $HOME environment variable.

Quick'n'dirty solution

Edit C:\Program Files (x86)\Git\etc\profile and set $HOME variable to whatever you want (add it if it's not there). A good place could be for example right after a condition commented by # Set up USER's home directory. It must be in the MinGW format, for example:

HOME=/c/my/custom/home

Save it, open Git Bash and execute cd ~. You should be in a directory /c/my/custom/home now.

Everything that accesses the user's profile should go into this directory instead of your Windows' profile on a network drive.

Note: C:\Program Files (x86)\Git\etc\profile is shared by all users, so if the machine is used by multiple users, it's a good idea to set the $HOME dynamically:

HOME=/c/Users/$USERNAME

Cleaner solution

Set the environment variable HOME in Windows to whatever directory you want. In this case, you have to set it in Windows path format (with backslashes, e.g. c:\my\custom\home), Git Bash will load it and convert it to its format.

If you want to change the home directory for all users on your machine, set it as a system environment variable, where you can use for example %USERNAME% variable so every user will have his own home directory, for example:

HOME=c:\custom\home\%USERNAME%

If you want to change the home directory just for yourself, set it as a user environment variable, so other users won't be affected. In this case, you can simply hard-code the whole path:

HOME=c:\my\custom\home

Android Studio AVD - Emulator: Process finished with exit code 1

I am using flutter and installed virtual device using the terminal

flutter emulator --launch {avd_name} -v

will print a more detailed output, making it easier for debugging the specific errors

Enabling the virtualization options in BIOS worked in my particular case (VDT)

How can I write to the console in PHP?

By default, all output goes to stdout, which is the HTTP response or the console, depending on whether your script is run by Apache or manually on the command line. But you can use error_log for logging and various I/O streams can be written to with fwrite.

Install specific version using laravel installer

From Laravel 6, Now It's working with the following command:

composer create-project --prefer-dist laravel/laravel:^7.0 blog

hidden field in php

Can I use a field of the type ... and retrieve it after the GET / POST method ...

Yes (haven't you tried?)

Are there any other ways of using hidden fields in PHP?

You mean other ways of retrieving the value? No.
Of course you can use hidden fields for what ever you want.


Btw. input fiels have no end tag. So write either just <input ...> or as self-closing tag <input .../>.

How do I combine the first character of a cell with another cell in Excel?

Use following formula:

=CONCATENATE(LOWER(MID(A1,1,1)),LOWER( B1))

for

Josh Smith = jsmith

note that A1 contains name and B1 contains surname

Error in Process.Start() -- The system cannot find the file specified

You can use the folowing to get the full path to your program like this:

Environment.CurrentDirectory

Best way to reset an Oracle sequence to the next value in an existing column?

In my case I have a sequence called PS_LOG_SEQ which had a LAST_NUMBER = 3920.

I then imported some data from PROD to my local machine and inserted into the PS_LOG table. Production data had more than 20000 rows with the latest LOG_ID (primary key) being 20070. After importing I tried to insert new rows in this table but when saving I got an exception like this one:

ORA-00001: unique constraint (LOG.PS_LOG_PK) violated

Surely this has to do with the Sequence PS_LOG_SEQ associated with the PS_LOG table. The LAST_NUMBER was colliding with data I imported which had already used the next ID value from the PS_LOG_SEQ.

To solve that I used this command to update the sequence to the latest \ max(LOG_ID) + 1:

alter sequence PS_LOG_SEQ restart start with 20071;

This command reset the LAST_NUMBER value and I could then insert new rows into the table. No more collision. :)

Note: this alter sequence command is new in Oracle 12c.

Note: this blog post documents the ALTER SEQUENCE RESTART option does exist, but as of 18c, is not documented. Its apparently intended for internal Oracle use.

Gradient borders

try this code

.gradientBoxesWithOuterShadows { 
height: 200px;
width: 400px; 
padding: 20px;
background-color: white; 

/* outer shadows  (note the rgba is red, green, blue, alpha) */
-webkit-box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.4); 
-moz-box-shadow: 0px 1px 6px rgba(23, 69, 88, .5);

/* rounded corners */
-webkit-border-radius: 12px;
-moz-border-radius: 7px; 
border-radius: 7px;

/* gradients */
background: -webkit-gradient(linear, left top, left bottom, 
color-stop(0%, white), color-stop(15%, white), color-stop(100%, #D7E9F5)); 
background: -moz-linear-gradient(top, white 0%, white 55%, #D5E4F3 130%); 
}

or maybe refer to this fiddle: http://jsfiddle.net/necolas/vqnk9/

Changing background color of selected item in recyclerview

Create a selector into Drawable folder:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
<item android:state_pressed="true">
   <shape>
         <solid android:color="@color/blue" />
   </shape>
</item>

<item android:state_pressed="false">
    <shape>
       <solid android:color="@android:color/transparent" />
    </shape>
</item>
</selector>

Add the property into your xml (where you declare the RecyclerView):

android:background="@drawable/selector"

How to search a Git repository by commit message?

For anyone who wants to pass in arbitrary strings which are exact matches (And not worry about escaping regex special characters), git log takes a --fixed-strings option

git log --fixed-strings --grep "$SEARCH_TERM" 

Javascript to stop HTML5 video playback on modal window close

I managed to stop the video using "get(0)" (Retrieve the DOM elements matched by the jQuery object):

$("#closeSimple").click(function() {
    $("div#simpleModal").removeClass("show");
    $("#videoContainer").get(0).pause();
    return false;
});

how to end ng serve or firebase serve

Exit the IDE and boots up IDE again , try it.

jQuery get textarea text

You should have a div that just contains the console messages, that is, previous commands and their output. And underneath put an input or textarea that just holds the command you are typing.

-------------------------------
| consle output ...           |
| more output                 |
| prevous commands and data   |
-------------------------------
> This is an input box.

That way you just send the value of the input box to the server for processing, and append the result to the console messages div.

How do I convert datetime.timedelta to minutes, hours in Python?

Another alternative for this (older) question:

import datetime
import pytz
import time

pacific=pytz.timezone('US/Pacific')
now=datetime.datetime.now()
# pacific.dst(now).total_seconds() yields 3600 secs. [aka 1 hour]
time.strftime("%-H", time.gmtime(pacific.dst(now).total_seconds()))
'1'

The above is a good way to tell if your current time zone is actually in daylight savings time or not. (It provides an offset of 0 or 1.) Anyway, the real work is being done by time.strftime("%H:%M:%S", time.gmtime(36901)) which does work on the output of gmtime().

>>> time.strftime("%H:%M:%S",time.gmtime(36901))  # secs = 36901
'10:15:01'

And, that's it! (NOTE: Here's a link to format specifiers for time.strftime(). ...)

ImportError: No module named 'selenium'

Windows:

pip install selenium

Unix:

sudo pip install selenium

Removing highcharts.com credits link

add

credits: {
    enabled: false
}

[NOTE] that it is in the same line with xAxis: {} and yAxis: {}

How to convert a ruby hash object to JSON?

You should include json in your file

For Example,

require 'json'

your_hash = {one: "1", two: "2"}
your_hash.to_json

For more knowledge about json you can visit below link. Json Learning

Can I set an opacity only to the background image of a div?

None of the solutions worked for me. If everything else fails, get the picture to Photoshop and apply some effect. 5 minutes versus so much time on this...

Find closing HTML tag in Sublime Text

None of the above worked on Sublime Text 3 on Windows 10, Ctrl + Shift + ' with the Emmet Sublime Text 3 plugin works great and was the only working solution for me. Ctrl + Shift + T re-opens the last closed item and to my knowledge of Sublime, has done so since early builds of ST3 or late builds of ST2.

jquery validate check at least one checkbox

$("#idform").validate({
    rules: {            
        'roles': {
            required: true,
        },
    },
    messages: {            
        'roles': {
            required: "One Option please",
        },
    }
});

Java Try and Catch IOException Problem

Initializer block is just like any bits of code; it's not "attached" to any field/method preceding it. To assign values to fields, you have to explicitly use the field as the lhs of an assignment statement.

private int lineCount; {
    try{
        lineCount = LineCounter.countLines(sFileName);
        /*^^^^^^^*/
    }
    catch(IOException ex){
        System.out.println (ex.toString());
        System.out.println("Could not find file " + sFileName);
    }
}

Also, your countLines can be made simpler:

  public static int countLines(String filename) throws IOException {
    LineNumberReader reader  = new LineNumberReader(new FileReader(filename));
    while (reader.readLine() != null) {}
    reader.close();
    return reader.getLineNumber();
  }

Based on my test, it looks like you can getLineNumber() after close().

Order a List (C#) by many fields?

Yes, you can do it by specifying the comparison method. The advantage is the sorted object don't have to be IComparable

   aListOfObjects.Sort((x, y) =>
   {
       int result = x.A.CompareTo(y.A);
       return result != 0 ? result : x.B.CompareTo(y.B);
   });

Is there a need for range(len(a))?

Very simple example:

def loadById(self, id):
    if id in range(len(self.itemList)):
        self.load(self.itemList[id])

I can't think of a solution that does not use the range-len composition quickly.

But probably instead this should be done with try .. except to stay pythonic i guess..

How to get UTC+0 date in Java 8?

With Java 8 you can write:

OffsetDateTime utc = OffsetDateTime.now(ZoneOffset.UTC);

To answer your comment, you can then convert it to a Date (unless you depend on legacy code I don't see any reason why) or to millis since the epochs:

Date date = Date.from(utc.toInstant());
long epochMillis = utc.toInstant().toEpochMilli();

CSS On hover show another element

It is indeed possible with the following code

 <div href="#" id='a'>
     Hover me
 </div>

<div id='b'>
    Show me
</div>

and css

#a {
  display: block;
}

#a:hover + #b {
  display:block;
}

#b {
  display:none;
  }

Now by hovering on element #a shows element #b.

html select scroll bar

One options will be to show the selected option above (or below) the select list like following:

HTML

<div id="selText"><span>&nbsp;</span></div><br/>
<select size="4" id="mySelect" style="width:65px;color:#f98ad3;">
    <option value="1" selected>option 1 The Long Option</option>
    <option value="2">option 2</option>
    <option value="3">option 3</option>
    <option value="4">option 4</option>
    <option value="5">option 5 Another Longer than the Long Option ;)</option>
    <option value="6">option 6</option>
</select>

JavaScript

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"   
  type="text/javascript"></script> 
<script type="text/javascript">
$(document).ready(function(){        
    $("select#mySelect").change(function(){
      //$("#selText").html($($(this).children("option:selected")[0]).text());
       var txt = $($(this).children("option:selected")[0]).text();
       $("<span>" + txt + "<br/></span>").appendTo($("#selText span:last"));
    });
});
</script>

PS:- Set height of div#selText otherwise it will keep shifting select list downward.