Programs & Examples On #Iostream

The C++ iostream library is an object-oriented library that provides input and output functionality using streams. The iostreams classes support type-safe I/O of built-in types and can be extended to support user-defined types by overloading the >> and << operators.

Reading from text file until EOF repeats last line

There's an alternative approach to this:

#include <iterator>
#include <algorithm>

// ...

    copy(istream_iterator<int>(iFile), istream_iterator<int>(),
         ostream_iterator<int>(cerr, "\n"));

Why std::cout instead of simply cout?

In the C++ standard, cout is defined in the std namespace, so you need to either say std::cout or put

using namespace std;

in your code in order to get at it.

However, this was not always the case, and in the past cout was just in the global namespace (or, later on, in both global and std). I would therefore conclude that your classes used an older C++ compiler.

'printf' vs. 'cout' in C++

I'm not a programmer, but I have been a human factors engineer. I feel a programming language should be easy to learn, understand and use, and this requires that it have a simple and consistent linguistic structure. Although all the languages is symbolic and thus, at its core, arbitrary, there are conventions and following them makes the language easier to learn and use.

There are a vast number of functions in C++ and other languages written as function(parameter), a syntax that was originally used for functional relationships in mathematics in the pre-computer era. printf() follows this syntax and if the writers of C++ wanted to create any logically different method for reading and writing files they could have simply created a different function using a similar syntax.

In Python we of course can print using the also fairly standard object.method syntax, i.e. variablename.print, since variables are objects, but in C++ they are not.

I'm not fond of the cout syntax because the << operator does not follow any rules. It is a method or function, i.e. it takes a parameter and does something to it. However it is written as though it were a mathematical comparison operator. This is a poor approach from a human factors standpoint.

How to print Unicode character in C++?

When compiling with -std=c++11, one can simply

  const char *s  = u8"\u0444";
  cout << s << endl;

How to print (using cout) a number in binary form?

Here is the true way to get binary representation of a number:

unsigned int i = *(unsigned int*) &x;

How do I print a double value with full precision using cout?

Here is how to display a double with full precision:

double d = 100.0000000000005;
int precision = std::numeric_limits<double>::max_digits10;
std::cout << std::setprecision(precision) << d << std::endl;

This displays:

100.0000000000005


max_digits10 is the number of digits that are necessary to uniquely represent all distinct double values. max_digits10 represents the number of digits before and after the decimal point.


Don't use set_precision(max_digits10) with std::fixed.
On fixed notation, set_precision() sets the number of digits only after the decimal point. This is incorrect as max_digits10 represents the number of digits before and after the decimal point.

double d = 100.0000000000005;
int precision = std::numeric_limits<double>::max_digits10;
std::cout << std::fixed << std::setprecision(precision) << d << std::endl;

This displays incorrect result:

100.00000000000049738

Note: Header files required

#include <iomanip>
#include <limits>

How to read until EOF from cin in C++

Probable simplest and generally efficient:

#include <iostream>
int main()
{
    std::cout << std::cin.rdbuf();
}

If needed, use stream of other types like std::ostringstream as buffer instead of standard output stream here.

How to output to the console in C++/Windows

If you're using Visual Studio, it should work just fine!

Here's a code example:

#include <iostream>

using namespace std;

int main (int) {
    cout << "This will print to the console!" << endl;
}

Make sure you chose a Win32 console application when creating a new project. Still you can redirect the output of your project to a file by using the console switch (>>). This will actually redirect the console pipe away from the stdout to your file. (for example, myprog.exe >> myfile.txt).

I wish I'm not mistaken!

How to solve "Unresolved inclusion: <iostream>" in a C++ file in Eclipse CDT?

Make sure that your file has .cpp extension and not .c, I just had this problem

'cout' was not declared in this scope

Use std::cout, since cout is defined within the std namespace. Alternatively, add a using std::cout; directive.

How to read line by line or a whole text file at once?

I think you could use istream .read() function. You can just loop with reasonable chunk size and read directly to memory buffer, then append it to some sort of arbitrary memory container (such as std::vector). I could write an example, but I doubt you want a complete solution; please let me know if you shall need any additional information.

How to properly overload the << operator for an ostream?

Just telling you about one other possibility: I like using friend definitions for that:

namespace Math
{
    class Matrix
    {
    public:

        [...]

        friend std::ostream& operator<< (std::ostream& stream, const Matrix& matrix) {
            [...]
        }
    };
}

The function will be automatically targeted into the surrounding namespace Math (even though its definition appears within the scope of that class) but will not be visible unless you call operator<< with a Matrix object which will make argument dependent lookup find that operator definition. That can sometimes help with ambiguous calls, since it's invisible for argument types other than Matrix. When writing its definition, you can also refer directly to names defined in Matrix and to Matrix itself, without qualifying the name with some possibly long prefix and providing template parameters like Math::Matrix<TypeA, N>.

"std::endl" vs "\n"

I recalled reading about this in the standard, so here goes:

See C11 standard which defines how the standard streams behave, as C++ programs interface the CRT, the C11 standard should govern the flushing policy here.

ISO/IEC 9899:201x

7.21.3 §7

At program startup, three text streams are predefined and need not be opened explicitly — standard input (for reading conventional input), standard output (for writing conventional output), and standard error (for writing diagnostic output). As initially opened, the standard error stream is not fully buffered; the standard input and standard output streams are fully buffered if and only if the stream can be determined not to refer to an interactive device.

7.21.3 §3

When a stream is unbuffered, characters are intended to appear from the source or at the destination as soon as possible. Otherwise characters may be accumulated and transmitted to or from the host environment as a block. When a stream is fully buffered, characters are intended to be transmitted to or from the host environment as a block when a buffer is filled. When a stream is line buffered, characters are intended to be transmitted to or from the host environment as a block when a new-line character is encountered. Furthermore, characters are intended to be transmitted as a block to the host environment when a buffer is filled, when input is requested on an unbuffered stream, or when input is requested on a line buffered stream that requires the transmission of characters from the host environment. Support for these characteristics is implementation-defined, and may be affected via the setbuf and setvbuf functions.

This means that std::cout and std::cin are fully buffered if and only if they are referring to a non-interactive device. In other words, if stdout is attached to a terminal then there is no difference in behavior.

However, if std::cout.sync_with_stdio(false) is called, then '\n' will not cause a flush even to interactive devices. Otherwise '\n' is equivalent to std::endl unless piping to files: c++ ref on std::endl.

operator << must take exactly one argument

If you define operator<< as a member function it will have a different decomposed syntax than if you used a non-member operator<<. A non-member operator<< is a binary operator, where a member operator<< is a unary operator.

// Declarations
struct MyObj;
std::ostream& operator<<(std::ostream& os, const MyObj& myObj);

struct MyObj
{
    // This is a member unary-operator, hence one argument
    MyObj& operator<<(std::ostream& os) { os << *this; return *this; }

    int value = 8;
};

// This is a non-member binary-operator, 2 arguments
std::ostream& operator<<(std::ostream& os, const MyObj& myObj)
{
    return os << myObj.value;
}

So.... how do you really call them? Operators are odd in some ways, I'll challenge you to write the operator<<(...) syntax in your head to make things make sense.

MyObj mo;

// Calling the unary operator
mo << std::cout;

// which decomposes to...
mo.operator<<(std::cout);

Or you could attempt to call the non-member binary operator:

MyObj mo;

// Calling the binary operator
std::cout << mo;

// which decomposes to...
operator<<(std::cout, mo);

You have no obligation to make these operators behave intuitively when you make them into member functions, you could define operator<<(int) to left shift some member variable if you wanted to, understand that people may be a bit caught off guard, no matter how many comments you may write.

Almost lastly, there may be times where both decompositions for an operator call are valid, you may get into trouble here and we'll defer that conversation.

Lastly, note how odd it might be to write a unary member operator that is supposed to look like a binary operator (as you can make member operators virtual..... also attempting to not devolve and run down this path....)

struct MyObj
{
    // Note that we now return the ostream
    std::ostream& operator<<(std::ostream& os) { os << *this; return os; }

    int value = 8;
};

This syntax will irritate many coders now....

MyObj mo;

mo << std::cout << "Words words words";

// this decomposes to...
mo.operator<<(std::cout) << "Words words words";

// ... or even further ...
operator<<(mo.operator<<(std::cout), "Words words words");

Note how the cout is the second argument in the chain here.... odd right?

Why would we call cin.clear() and cin.ignore() after reading input?

Why do we use:

1) cin.ignore

2) cin.clear

?

Simply:

1) To ignore (extract and discard) values that we don't want on the stream

2) To clear the internal state of stream. After using cin.clear internal state is set again back to goodbit, which means that there are no 'errors'.

Long version:

If something is put on 'stream' (cin) then it must be taken from there. By 'taken' we mean 'used', 'removed', 'extracted' from stream. Stream has a flow. The data is flowing on cin like water on stream. You simply cannot stop the flow of water ;)

Look at the example:

string name; //line 1
cout << "Give me your name and surname:"<<endl;//line 2
cin >> name;//line 3
int age;//line 4
cout << "Give me your age:" <<endl;//line 5
cin >> age;//line 6

What happens if the user answers: "Arkadiusz Wlodarczyk" for first question?

Run the program to see for yourself.

You will see on console "Arkadiusz" but program won't ask you for 'age'. It will just finish immediately right after printing "Arkadiusz".

And "Wlodarczyk" is not shown. It seems like if it was gone (?)*

What happened? ;-)

Because there is a space between "Arkadiusz" and "Wlodarczyk".

"space" character between the name and surname is a sign for computer that there are two variables waiting to be extracted on 'input' stream.

The computer thinks that you are tying to send to input more than one variable. That "space" sign is a sign for him to interpret it that way.

So computer assigns "Arkadiusz" to 'name' (2) and because you put more than one string on stream (input) computer will try to assign value "Wlodarczyk" to variable 'age' (!). The user won't have a chance to put anything on the 'cin' in line 6 because that instruction was already executed(!). Why? Because there was still something left on stream. And as I said earlier stream is in a flow so everything must be removed from it as soon as possible. And the possibility came when computer saw instruction cin >> age;

Computer doesn't know that you created a variable that stores age of somebody (line 4). 'age' is merely a label. For computer 'age' could be as well called: 'afsfasgfsagasggas' and it would be the same. For him it's just a variable that he will try to assign "Wlodarczyk" to because you ordered/instructed computer to do so in line (6).

It's wrong to do so, but hey it's you who did it! It's your fault! Well, maybe user, but still...


All right all right. But how to fix it?!

Let's try to play with that example a bit before we fix it properly to learn a few more interesting things :-)

I prefer to make an approach where we understand things. Fixing something without knowledge how we did it doesn't give satisfaction, don't you think? :)

string name;
cout << "Give me your name and surname:"<<endl;
cin >> name;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << cin.rdstate(); //new line is here :-)

After invoking above code you will notice that the state of your stream (cin) is equal to 4 (line 7). Which means its internal state is no longer equal to goodbit. Something is messed up. It's pretty obvious, isn't it? You tried to assign string type value ("Wlodarczyk") to int type variable 'age'. Types doesn't match. It's time to inform that something is wrong. And computer does it by changing internal state of stream. It's like: "You f**** up man, fix me please. I inform you 'kindly' ;-)"

You simply cannot use 'cin' (stream) anymore. It's stuck. Like if you had put big wood logs on water stream. You must fix it before you can use it. Data (water) cannot be obtained from that stream(cin) anymore because log of wood (internal state) doesn't allow you to do so.

Oh so if there is an obstacle (wood logs) we can just remove it using tools that is made to do so?

Yes!

internal state of cin set to 4 is like an alarm that is howling and making noise.

cin.clear clears the state back to normal (goodbit). It's like if you had come and silenced the alarm. You just put it off. You know something happened so you say: "It's OK to stop making noise, I know something is wrong already, shut up (clear)".

All right let's do so! Let's use cin.clear().

Invoke below code using "Arkadiusz Wlodarczyk" as first input:

string name;
cout << "Give me your name and surname:"<<endl;
cin >> name;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << cin.rdstate() << endl; 
cin.clear(); //new line is here :-)
cout << cin.rdstate()<< endl;  //new line is here :-)

We can surely see after executing above code that the state is equal to goodbit.

Great so the problem is solved?

Invoke below code using "Arkadiusz Wlodarczyk" as first input:

string name;
cout << "Give me your name and surname:"<<endl;
cin >> name;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << cin.rdstate() << endl;; 
cin.clear(); 
cout << cin.rdstate() << endl; 
cin >> age;//new line is here :-)

Even tho the state is set to goodbit after line 9 the user is not asked for "age". The program stops.

WHY?!

Oh man... You've just put off alarm, what about the wood log inside a water?* Go back to text where we talked about "Wlodarczyk" how it supposedly was gone.

You need to remove "Wlodarczyk" that piece of wood from stream. Turning off alarms doesn't solve the problem at all. You've just silenced it and you think the problem is gone? ;)

So it's time for another tool:

cin.ignore can be compared to a special truck with ropes that comes and removes the wood logs that got the stream stuck. It clears the problem the user of your program created.

So could we use it even before making the alarm goes off?

Yes:

string name;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
int age;
cout << "Give me your age:" << endl;
cin >> age;

The "Wlodarczyk" is gonna be removed before making the noise in line 7.

What is 10000 and '\n'?

It says remove 10000 characters (just in case) until '\n' is met (ENTER). BTW It can be done better using numeric_limits but it's not the topic of this answer.


So the main cause of problem is gone before noise was made...

Why do we need 'clear' then?

What if someone had asked for 'give me your age' question in line 6 for example: "twenty years old" instead of writing 20?

Types doesn't match again. Computer tries to assign string to int. And alarm starts. You don't have a chance to even react on situation like that. cin.ignore won't help you in case like that.

So we must use clear in case like that:

string name;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
int age;
cout << "Give me your age:" << endl;
cin >> age;
cin.clear();
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow

But should you clear the state 'just in case'?

Of course not.

If something goes wrong (cin >> age;) instruction is gonna inform you about it by returning false.

So we can use conditional statement to check if the user put wrong type on the stream

int age;
if (cin >> age) //it's gonna return false if types doesn't match
    cout << "You put integer";
else
    cout << "You bad boy! it was supposed to be int";

All right so we can fix our initial problem like for example that:

string name;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow

int age;
cout << "Give me your age:" << endl;
if (cin >> age)
  cout << "Your age is equal to:" << endl;
else
{
 cin.clear();
 cin.ignore(10000, '\n'); //time to remove "Wlodarczyk" the wood log and make the stream flow
 cout << "Give me your age name as string I dare you";
 cin >> age;
}

Of course this can be improved by for example doing what you did in question using loop while.

BONUS:

You might be wondering. What about if I wanted to get name and surname in the same line from the user? Is it even possible using cin if cin interprets each value separated by "space" as different variable?

Sure, you can do it two ways:

1)

string name, surname;
cout << "Give me your name and surname:"<< endl;
cin >> name;
cin >> surname;

cout << "Hello, " << name << " " << surname << endl;

2) or by using getline function.

getline(cin, nameOfStringVariable);

and that's how to do it:

string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);

cout << "Hello, " << nameAndSurname << endl;

The second option might backfire you in case you use it after you use 'cin' before the getline.

Let's check it out:

a)

int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << "Your age is" << age << endl;

string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);

cout << "Hello, " << nameAndSurname << endl;

If you put "20" as age you won't be asked for nameAndSurname.

But if you do it that way:

b)

string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);

cout << "Hello, " << nameAndSurname << endl;
int age;
cout << "Give me your age:" <<endl;
cin >> age;
cout << "Your age is" << age << endll

everything is fine.

WHAT?!

Every time you put something on input (stream) you leave at the end white character which is ENTER ('\n') You have to somehow enter values to console. So it must happen if the data comes from user.

b) cin characteristics is that it ignores whitespace, so when you are reading in information from cin, the newline character '\n' doesn't matter. It gets ignored.

a) getline function gets the entire line up to the newline character ('\n'), and when the newline char is the first thing the getline function gets '\n', and that's all to get. You extract newline character that was left on stream by user who put "20" on stream in line 3.

So in order to fix it is to always invoke cin.ignore(); each time you use cin to get any value if you are ever going to use getline() inside your program.

So the proper code would be:

int age;
cout << "Give me your age:" <<endl;
cin >> age;
cin.ignore(); // it ignores just enter without arguments being sent. it's same as cin.ignore(1, '\n') 
cout << "Your age is" << age << endl;


string nameAndSurname;
cout << "Give me your name and surname:"<< endl;
getline(cin, nameAndSurname);

cout << "Hello, " << nameAndSurname << endl;

I hope streams are more clear to you know.

Hah silence me please! :-)

Reading a file character by character in C

I think the most significant problem is that you're incrementing code as you read stuff in, and then returning the final value of code, i.e. you'll be returning a pointer to the end of the string. You probably want to make a copy of code before the loop, and return that instead.

Also, C strings need to be null-terminated. You need to make sure that you place a '\0' directly after the final character that you read in.

Note: You could just use fgets() to get the entire line in one hit.

No mapping found for HTTP request with URI Spring MVC

First check whether the java classes are compiled or not in your [PROJECT_NAME]\target\classes directory.

If not you have some compilation errors in your java classes.

jQuery replace one class with another

You can use .removeClass and .addClass. More in http://api.jquery.com.

How to make a parent div auto size to the width of its children divs

The parent div (I assume the outermost div) is display: block and will fill up all available area of its container (in this case, the body) that it can. Use a different display type -- inline-block is probably what you are going for:

http://jsfiddle.net/a78xy/

Convert a python UTC datetime to a local datetime using only python standard library?

In Python 3.3+:

from datetime import datetime, timezone

def utc_to_local(utc_dt):
    return utc_dt.replace(tzinfo=timezone.utc).astimezone(tz=None)

In Python 2/3:

import calendar
from datetime import datetime, timedelta

def utc_to_local(utc_dt):
    # get integer timestamp to avoid precision lost
    timestamp = calendar.timegm(utc_dt.timetuple())
    local_dt = datetime.fromtimestamp(timestamp)
    assert utc_dt.resolution >= timedelta(microseconds=1)
    return local_dt.replace(microsecond=utc_dt.microsecond)

Using pytz (both Python 2/3):

import pytz

local_tz = pytz.timezone('Europe/Moscow') # use your local timezone name here
# NOTE: pytz.reference.LocalTimezone() would produce wrong result here

## You could use `tzlocal` module to get local timezone on Unix and Win32
# from tzlocal import get_localzone # $ pip install tzlocal

# # get local timezone    
# local_tz = get_localzone()

def utc_to_local(utc_dt):
    local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz)
    return local_tz.normalize(local_dt) # .normalize might be unnecessary

Example

def aslocaltimestr(utc_dt):
    return utc_to_local(utc_dt).strftime('%Y-%m-%d %H:%M:%S.%f %Z%z')

print(aslocaltimestr(datetime(2010,  6, 6, 17, 29, 7, 730000)))
print(aslocaltimestr(datetime(2010, 12, 6, 17, 29, 7, 730000)))
print(aslocaltimestr(datetime.utcnow()))

Output

Python 3.3
2010-06-06 21:29:07.730000 MSD+0400
2010-12-06 20:29:07.730000 MSK+0300
2012-11-08 14:19:50.093745 MSK+0400
Python 2
2010-06-06 21:29:07.730000 
2010-12-06 20:29:07.730000 
2012-11-08 14:19:50.093911 
pytz
2010-06-06 21:29:07.730000 MSD+0400
2010-12-06 20:29:07.730000 MSK+0300
2012-11-08 14:19:50.146917 MSK+0400

Note: it takes into account DST and the recent change of utc offset for MSK timezone.

I don't know whether non-pytz solutions work on Windows.

SQL Server command line backup statement

Here's an example you can run as a batch script (copy-paste into a .bat file), using the SQLCMD utility in Sql Server client tools:

BACKUP:

echo off
cls
echo -- BACKUP DATABASE --
set /p DATABASENAME=Enter database name:

:: filename format Name-Date (eg MyDatabase-2009.5.19.bak)
set DATESTAMP=%DATE:~-4%.%DATE:~7,2%.%DATE:~4,2%
set BACKUPFILENAME=%CD%\%DATABASENAME%-%DATESTAMP%.bak
set SERVERNAME=your server name here
echo.

sqlcmd -E -S %SERVERNAME% -d master -Q "BACKUP DATABASE [%DATABASENAME%] TO DISK = N'%BACKUPFILENAME%' WITH INIT , NOUNLOAD , NAME = N'%DATABASENAME% backup', NOSKIP , STATS = 10, NOFORMAT"
echo.
pause

RESTORE:

echo off
cls
echo -- RESTORE DATABASE --
set /p BACKUPFILENAME=Enter backup file name:%CD%\
set /p DATABASENAME=Enter database name:
set SERVERNAME=your server name here
sqlcmd -E -S %SERVERNAME% -d master -Q "ALTER DATABASE [%DATABASENAME%] SET SINGLE_USER WITH ROLLBACK IMMEDIATE"

:: WARNING - delete the database, suits me
:: sqlcmd -E -S %SERVERNAME% -d master -Q "IF EXISTS (SELECT * FROM sysdatabases WHERE name=N'%DATABASENAME%' ) DROP DATABASE [%DATABASENAME%]"
:: sqlcmd -E -S %SERVERNAME% -d master -Q "CREATE DATABASE [%DATABASENAME%]"

:: restore
sqlcmd -E -S %SERVERNAME% -d master -Q "RESTORE DATABASE [%DATABASENAME%] FROM DISK = N'%CD%\%BACKUPFILENAME%' WITH REPLACE"

:: remap user/login (http://msdn.microsoft.com/en-us/library/ms174378.aspx)
sqlcmd -E -S %SERVERNAME% -d %DATABASENAME% -Q "sp_change_users_login 'Update_One', 'login-name', 'user-name'"
sqlcmd -E -S %SERVERNAME% -d master -Q "ALTER DATABASE [%DATABASENAME%] SET MULTI_USER"
echo.
pause

Android - drawable with rounded corners at the top only

Try giving these values:

 <corners android:topLeftRadius="6dp" android:topRightRadius="6dp"
         android:bottomLeftRadius="0.1dp" android:bottomRightRadius="0.1dp"/>

Note that I have changed 0dp to 0.1dp.

EDIT: See Aleks G comment below for a cleaner version

calculating the difference in months between two dates

Old question I know, but might help someone. I've used @Adam accepted answer above, but then checked if the difference is 1 or -1 then check to see if it is a full calendar month's difference. So 21/07/55 and 20/08/55 would not be a full month, but 21/07/55 and 21/07/55 would be.

/// <summary>
/// Amended date of birth cannot be greater than or equal to one month either side of original date of birth.
/// </summary>
/// <param name="dateOfBirth">Date of birth user could have amended.</param>
/// <param name="originalDateOfBirth">Original date of birth to compare against.</param>
/// <returns></returns>
public JsonResult ValidateDateOfBirth(string dateOfBirth, string originalDateOfBirth)
{
    DateTime dob, originalDob;
    bool isValid = false;

    if (DateTime.TryParse(dateOfBirth, out dob) && DateTime.TryParse(originalDateOfBirth, out originalDob))
    {
        int diff = ((dob.Month - originalDob.Month) + 12 * (dob.Year - originalDob.Year));

        switch (diff)
        {
            case 0:
                // We're on the same month, so ok.
                isValid = true;
                break;
            case -1:
                // The month is the previous month, so check if the date makes it a calendar month out.
                isValid = (dob.Day > originalDob.Day);
                break;
            case 1:
                // The month is the next month, so check if the date makes it a calendar month out.
                isValid = (dob.Day < originalDob.Day);
                break;
            default:
                // Either zero or greater than 1 month difference, so not ok.
                isValid = false;
                break;
        }
        if (!isValid)
            return Json("Date of Birth cannot be greater than one month either side of the date we hold.", JsonRequestBehavior.AllowGet);
    }
    else
    {
        return Json("Date of Birth is invalid.", JsonRequestBehavior.AllowGet);
    }
    return Json(true, JsonRequestBehavior.AllowGet);
}

How to show hidden divs on mouseover?

Option 1 Each div is specifically identified, so any other div (without the specific IDs) on the page will not obey the :hover pseudo-class.

<style type="text/css">
  #div1, #div2, #div3{  
    display:none;  
  }  
  #div1:hover, #div2:hover, #div3:hover{  
    display:block;  
  }
</style>

Option 2 All divs on the page, regardless of IDs, have the hover effect.

<style type="text/css">
  div{  
    display:none;  
  }  
  div:hover{  
    display:block;  
  }
</style>

How do I deal with "signed/unsigned mismatch" warnings (C4018)?

You can use:

  1. size_t type, to remove warning messages
  2. iterators + distance (like are first hint)
  3. only iterators
  4. function object

For example:

// simple class who output his value
class ConsoleOutput
{
public:
  ConsoleOutput(int value):m_value(value) { }
  int Value() const { return m_value; }
private:
  int m_value;
};

// functional object
class Predicat
{
public:
  void operator()(ConsoleOutput const& item)
  {
    std::cout << item.Value() << std::endl;
  }
};

void main()
{
  // fill list
  std::vector<ConsoleOutput> list;
  list.push_back(ConsoleOutput(1));
  list.push_back(ConsoleOutput(8));

  // 1) using size_t
  for (size_t i = 0; i < list.size(); ++i)
  {
    std::cout << list.at(i).Value() << std::endl;
  }

  // 2) iterators + distance, for std::distance only non const iterators
  std::vector<ConsoleOutput>::iterator itDistance = list.begin(), endDistance = list.end();
  for ( ; itDistance != endDistance; ++itDistance)
  {
    // int or size_t
    int const position = static_cast<int>(std::distance(list.begin(), itDistance));
    std::cout << list.at(position).Value() << std::endl;
  }

  // 3) iterators
  std::vector<ConsoleOutput>::const_iterator it = list.begin(), end = list.end();
  for ( ; it != end; ++it)
  {
    std::cout << (*it).Value() << std::endl;
  }
  // 4) functional objects
  std::for_each(list.begin(), list.end(), Predicat());
}

How to delete from multiple tables in MySQL?

Use this

DELETE FROM `articles`, `comments` 
USING `articles`,`comments` 
WHERE `comments`.`article_id` = `articles`.`id` AND `articles`.`id` = 4

or

DELETE `articles`, `comments` 
FROM `articles`, `comments` 
WHERE `comments`.`article_id` = `articles`.`id` AND `articles`.`id` = 4

AWS : The config profile (MyName) could not be found

Use as follows

[profilename]
region=us-east-1
output=text

Example cmd

aws --profile myname CMD opts

Get device information (such as product, model) from adb command

Why don't you try to grep the return of your command ? Something like :

adb devices -l | grep 123abc12

It should return only the line you want to.

How to increase space between dotted border dots

This trick works for both horizontal and vertical borders:

/*Horizontal*/
background-image: linear-gradient(to right, black 33%, rgba(255,255,255,0) 0%);
background-position: bottom;
background-size: 3px 1px;
background-repeat: repeat-x;

/*Vertical*/
background-image: linear-gradient(black 33%, rgba(255,255,255,0) 0%);
background-position: right;
background-size: 1px 3px;
background-repeat: repeat-y;

You can adjust the size with background-size and the proportion with the linear-gradient percentages. In this example I have a dotted line of 1px dots and 2px spacing. This way you can have multiple dotted borders too using multiple backgrounds.

Try it in this JSFiddle or take a look at the code snippet example:

_x000D_
_x000D_
div {_x000D_
  padding: 10px 50px;_x000D_
}_x000D_
.dotted {_x000D_
  border-top: 1px #333 dotted;_x000D_
}_x000D_
.dotted-gradient {_x000D_
  background-image: linear-gradient(to right, #333 40%, rgba(255, 255, 255, 0) 20%);_x000D_
  background-position: top;_x000D_
  background-size: 3px 1px;_x000D_
  background-repeat: repeat-x;_x000D_
}_x000D_
.dotted-spaced {_x000D_
  background-image: linear-gradient(to right, #333 10%, rgba(255, 255, 255, 0) 0%);_x000D_
  background-position: top;_x000D_
  background-size: 10px 1px;_x000D_
  background-repeat: repeat-x;_x000D_
}_x000D_
.left {_x000D_
  float: left;_x000D_
  padding: 40px 10px;_x000D_
  background-color: #F0F0DA;_x000D_
}_x000D_
.left.dotted {_x000D_
  border-left: 1px #333 dotted;_x000D_
  border-top: none;_x000D_
}_x000D_
.left.dotted-gradient {_x000D_
  background-image: linear-gradient(to bottom, #333 40%, rgba(255, 255, 255, 0) 20%);_x000D_
  background-position: left;_x000D_
  background-size: 1px 3px;_x000D_
  background-repeat: repeat-y;_x000D_
}_x000D_
.left.dotted-spaced {_x000D_
  background-image: linear-gradient(to bottom, #333 10%, rgba(255, 255, 255, 0) 0%);_x000D_
  background-position: left;_x000D_
  background-size: 1px 10px;_x000D_
  background-repeat: repeat-y;_x000D_
}
_x000D_
<div>no_x000D_
  <br>border</div>_x000D_
<div class='dotted'>dotted_x000D_
  <br>border</div>_x000D_
<div class='dotted-gradient'>dotted_x000D_
  <br>with gradient</div>_x000D_
<div class='dotted-spaced'>dotted_x000D_
  <br>spaced</div>_x000D_
_x000D_
<div class='left'>no_x000D_
  <br>border</div>_x000D_
<div class='dotted left'>dotted_x000D_
  <br>border</div>_x000D_
<div class='dotted-gradient left'>dotted_x000D_
  <br>with gradient</div>_x000D_
<div class='dotted-spaced left'>dotted_x000D_
  <br>spaced</div>
_x000D_
_x000D_
_x000D_

How does database indexing work?

An index is just a data structure that makes the searching faster for a specific column in a database. This structure is usually a b-tree or a hash table but it can be any other logic structure.

Getting binary (base64) data from HTML5 Canvas (readAsBinaryString)

Short answer:

const base64Canvas = canvas.toDataURL("image/jpeg").split(';base64,')[1];

How can I easily convert DataReader to List<T>?

I would (and have) started to use Dapper. To use your example would be like (written from memory):

public List<CustomerEntity> GetCustomerList()
{
    using (DbConnection connection = CreateConnection())
    {
        return connection.Query<CustomerEntity>("procToReturnCustomers", commandType: CommandType.StoredProcedure).ToList();
    }
}

CreateConnection() would handle accessing your db and returning a connection.

Dapper handles mapping datafields to properties automatically. It also supports multiple types and result sets and is very fast.

Query returns IEnumerable hence the ToList().

Not unique table/alias

 select persons.personsid,name,info.id,address
    -> from persons
    -> inner join persons on info.infoid = info.info.id;

Bulk Insert Correctly Quoted CSV File in SQL Server

I had this same problem, and I didn't want to have to go the SSIS route, so I found a PowerShell script that is easy to run and handles the case of the quotes with the comma in that particular field:

Source Code and DLL for the PowerShell Script: https://github.com/billgraziano/CsvDataReader

Here's a blog that explains the usage: http://www.sqlteam.com/article/fast-csv-import-in-powershell-to-sql-server

Start a fragment via Intent within a Fragment

The answer to your problem is easy: replace the current Fragment with the new Fragment and push transaction onto the backstack. This preserves back button behaviour...

Creating a new Activity really defeats the whole purpose to use fragments anyway...very counter productive.

@Override
public void onClick(View v) {
    // Create new fragment and transaction
    Fragment newFragment = new chartsFragment(); 
    // consider using Java coding conventions (upper first char class names!!!)
    FragmentTransaction transaction = getFragmentManager().beginTransaction();

    // Replace whatever is in the fragment_container view with this fragment,
    // and add the transaction to the back stack
    transaction.replace(R.id.fragment_container, newFragment);
    transaction.addToBackStack(null);

    // Commit the transaction
    transaction.commit(); 
}

http://developer.android.com/guide/components/fragments.html#Transactions

How to get a float result by dividing two integer values using T-SQL?

The suggestions from stb and xiowl are fine if you're looking for a constant. If you need to use existing fields or parameters which are integers, you can cast them to be floats first:

SELECT CAST(1 AS float) / CAST(3 AS float)

or

SELECT CAST(MyIntField1 AS float) / CAST(MyIntField2 AS float)

Vue.js: Conditional class style binding

Use the object syntax.

v-bind:class="{'fa-checkbox-marked': content['cravings'],  'fa-checkbox-blank-outline': !content['cravings']}"

When the object gets more complicated, extract it into a method.

v-bind:class="getClass()"

methods:{
    getClass(){
        return {
            'fa-checkbox-marked': this.content['cravings'],  
            'fa-checkbox-blank-outline': !this.content['cravings']}
    }
}

Finally, you could make this work for any content property like this.

v-bind:class="getClass('cravings')"

methods:{
  getClass(property){
    return {
      'fa-checkbox-marked': this.content[property],
      'fa-checkbox-blank-outline': !this.content[property]
    }
  }
}

HTML inside Twitter Bootstrap popover

You can change the 'template/popover/popover.html' in file 'ui-bootstrap-tpls-0.11.0.js' Write: "bind-html-unsafe" instead of "ng-bind"

It will show all popover with html. *its unsafe html. Use only if you trust the html.

How to uninstall jupyter

In my case, I have installed it via pip3 on mac.

pip3 uninstall notebook

What is difference between Axios and Fetch?

Benefits of axios:

  • Transformers: allow performing transforms on data before request is made or after response is received
  • Interceptors: allow you to alter the request or response entirely (headers as well). also perform async operations before request is made or before Promise settles
  • Built-in XSRF protection

Advantages of axios over fetch

Allowed memory size of 262144 bytes exhausted (tried to allocate 24576 bytes)

See if this answer can help you. Particularly the fact that CLI ini could be different than when the script is running through a browser.

Allowed memory size of X bytes exhausted

Check if decimal value is null

A decimal will always have some default value. If you need to have a nullable type decimal, you can use decimal?. Then you can do myDecimal.HasValue

git remote add with other SSH port

For those of you editing the ./.git/config

[remote "external"]                                                                                                                                                                                                                                                            
  url = ssh://[email protected]:11720/aaa/bbb/ccc                                                                                                                                                                                                               
  fetch = +refs/heads/*:refs/remotes/external/* 

How do I escape ampersands in XML so they are rendered as entities in HTML?

In my case I had to change it to %26.

I needed to escape & in a URL. So &amp; did not work out for me. The urlencode function changes & to %26. This way neither XML nor the browser URL mechanism complained about the URL.

How to bind a List<string> to a DataGridView control?

Try this :

//i have a 
List<string> g_list = new List<string>();

//i put manually the values... (for this example)
g_list.Add("aaa");
g_list.Add("bbb");
g_list.Add("ccc");

//for each string add a row in dataGridView and put the l_str value...
foreach (string l_str in g_list)
{
    dataGridView1.Rows.Add(l_str);
}

Should I set max pool size in database connection string? What happens if I don't?

Currently your application support 100 connections in pool. Here is what conn string will look like if you want to increase it to 200:

public static string srConnectionString = 
                "server=localhost;database=mydb;uid=sa;pwd=mypw;Max Pool Size=200;";

You can investigate how many connections with database your application use, by executing sp_who procedure in your database. In most cases default connection pool size will be enough.

What are the most common naming conventions in C?

Coding in C#, java, C, C++ and objective C at the same time, I've adopted a very simple and clear naming convention to simplify my life.

First of all, it relies on the power of modern IDEs (such as eclipse, Xcode...), with the possibility to get fast information by hovering or ctrl click... Accepting that, I suppressed the use of any prefix, suffix and other markers that are simply given by the IDE.

Then, the convention:

  • Any names MUST be a readable sentence explaining what you have. Like "this is my convention".
  • Then, 4 methods to get a convention out of a sentence:
    1. THIS_IS_MY_CONVENTION for macros, enum members
    2. ThisIsMyConvention for file name, object name (class, struct, enum, union...), function name, method name, typedef
    3. this_is_my_convention global and local variables,
      parameters, struct and union elements
    4. thisismyconvention [optional] very local and temporary variables (such like a for() loop index)

And that's it.

It gives

class MyClass {
    enum TheEnumeration {
        FIRST_ELEMENT,
        SECOND_ELEMENT,
    }

    int class_variable;

    int MyMethod(int first_param, int second_parameter) {
        int local_variable;
        TheEnumeration local_enum;
        for(int myindex=0, myindex<class_variable, myindex++) {
             localEnum = FIRST_ELEMENT;
        }
    }
}

What event handler to use for ComboBox Item Selected (Selected Item not necessarily changed)

It's easy, just add if (e.AddedItems.Count == 0) return; in the beggining of function like:

        private  void ComboBox_Symbols_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (e.AddedItems.Count == 0) 
        return;
        //Some Other Codes
    }

Set color of TextView span in Android

Here is a little help function. Great for when you have multiple languages!

private void setColor(TextView view, String fulltext, String subtext, int color) {
    view.setText(fulltext, TextView.BufferType.SPANNABLE);
    Spannable str = (Spannable) view.getText();
    int i = fulltext.indexOf(subtext);
    str.setSpan(new ForegroundColorSpan(color), i, i + subtext.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}

Regex for Mobile Number Validation

This regex is very short and sweet for working.

/^([+]\d{2})?\d{10}$/

Ex: +910123456789 or 0123456789

-> /^ and $/ is for starting and ending
-> The ? mark is used for conditional formatting where before question mark is available or not it will work
-> ([+]\d{2}) this indicates that the + sign with two digits '\d{2}' here you can place digit as per country
-> after the ? mark '\d{10}' this says that the digits must be 10 of length change as per your country mobile number length

This is how this regex for mobile number is working.
+ sign is used for world wide matching of number.

if you want to add the space between than you can use the

[ ]

here the square bracket represents the character sequence and a space is character for searching in regex.
for the space separated digit you can use this regex

/^([+]\d{2}[ ])?\d{10}$/

Ex: +91 0123456789

Thanks ask any question if you have.

Get div to take up 100% body height, minus fixed-height header and footer

This still came up as the top Google result when I was trying to find an answer to this question. I didn't have to support older browsers in my project and I feel like I found a better, simpler solution in flex-box. The CSS snippet below is all that is necessary.

I have also shown how to make the main content scrollable if the screen height is too small.

_x000D_
_x000D_
html,_x000D_
body {_x000D_
  height: 100%;_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
header {_x000D_
  min-height: 60px;_x000D_
}_x000D_
main {_x000D_
  flex-grow: 1;_x000D_
  overflow: auto;_x000D_
}_x000D_
footer {_x000D_
  min-height: 30px;_x000D_
}
_x000D_
<body style="margin: 0px; font-family: Helvetica; font-size: 18px;">_x000D_
  <header style="background-color: lightsteelblue; padding: 2px;">Hello</header>_x000D_
  <main style="overflow: auto; background-color: lightgrey; padding: 2px;">_x000D_
    <article style="height: 400px;">_x000D_
      Goodbye_x000D_
    </article>_x000D_
  </main>_x000D_
  <footer style="background-color: lightsteelblue; padding: 2px;">I don't know why you say, "Goodbye"; I say, "Hello."</footer>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Phone validation regex

Here is the regex for Ethiopian Phone Number. For my fellow Ethiopian developers ;)

phoneExp = /^(^\+251|^251|^0)?9\d{8}$/;

It matches the following (restrict any unwanted character in start and end position)

  • +251912345678
  • 251912345678
  • 0912345678
  • 912345678

You can test it on this site regexr.

Exchange Powershell - How to invoke Exchange 2010 module from inside script?

I know this is an old question, but rather than adding the snapin which is apparently unsupported, I just looked at the EMS shortcut properties and copied those commands.

The full shortcut target is:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noexit -command ". 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto"

So I put the following at the start of my script and it seemed to function as expected:

. 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'
Connect-ExchangeServer -auto

Notes:

  • Has to be run in 64bit PS
  • This was tested on a server with just the Management Tools installed. It automatically connected to our existing Exchange infrastructure.
  • No extensive testing has been done, so I do not know if this method is viable. I will edit this post if I run into any issues.

Find all controls in WPF Window by type

To get a list of all childs of a specific type you can use:

private static IEnumerable<DependencyObject> FindInVisualTreeDown(DependencyObject obj, Type type)
{
    if (obj != null)
    {
        if (obj.GetType() == type)
        {
            yield return obj;
        }

        for (var i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
        {
            foreach (var child in FindInVisualTreeDown(VisualTreeHelper.GetChild(obj, i), type))
            {
                if (child != null)
                {
                    yield return child;
                }
            }
        }
    }

    yield break;
}

How can I determine the status of a job?

This is an old question, but I just had a similar situation where I needed to check on the status of jobs on SQL Server. A lot of people mentioned the sysjobactivity table and pointed to the MSDN documentation which is great. However, I'd also like to highlight the Job Activity Monitor which provides the status on all jobs that are defined on your server.

How to get the current directory in a C program?

Use getcwd

#include <stdio.h>  /* defines FILENAME_MAX */
//#define WINDOWS  /* uncomment this line to use it for windows.*/
#ifdef WINDOWS
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif

int main(){
  char buff[FILENAME_MAX];
  GetCurrentDir( buff, FILENAME_MAX );
  printf("Current working dir: %s\n", buff);
  return 1;
}

OR

#include<stdio.h>
#include<unistd.h> 
#include<stdlib.h>

main() {
char *buf;
buf=(char *)malloc(100*sizeof(char));
getcwd(buf,100);
printf("\n %s \n",buf);
}

Finding row index containing maximum value using R

See ?which.max

> which.max( matrix[,2] )
[1] 2

int to hex string

Try C# string interpolation introduced in C# 6:

var id = 100;
var hexid = $"0x{id:X}";

hexid value:

"0x64"

Rails: Can't verify CSRF token authenticity when making a POST request

If you want to exclude the sample controller's sample action

class TestController < ApplicationController
  protect_from_forgery :except => [:sample]

  def sample
     render json: @hogehoge
  end
end

You can to process requests from outside without any problems.

How to set app icon for Electron / Atom Shell App

For windows use Resource Hacker

Download and Install: :D

http://www.angusj.com/resourcehacker/

  • Run It
  • Select open and select exe file
  • On your left open a folder called Icon Group
  • Right click 1: 1033
  • Click replace icon
  • Select the icon of your choice
  • Then select replace icon
  • Save then close

You should have build the app

Creating SVG elements dynamically with javascript inside HTML

Add this to html:

<svg id="mySVG" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"/>

Try this function and adapt for you program:

var svgNS = "http://www.w3.org/2000/svg";  

function createCircle()
{
    var myCircle = document.createElementNS(svgNS,"circle"); //to create a circle. for rectangle use "rectangle"
    myCircle.setAttributeNS(null,"id","mycircle");
    myCircle.setAttributeNS(null,"cx",100);
    myCircle.setAttributeNS(null,"cy",100);
    myCircle.setAttributeNS(null,"r",50);
    myCircle.setAttributeNS(null,"fill","black");
    myCircle.setAttributeNS(null,"stroke","none");

    document.getElementById("mySVG").appendChild(myCircle);
}     

How to add text to an existing div with jquery

You need to define the button text and have valid HTML for the button. I would also suggest using .on for the click handler of the button

_x000D_
_x000D_
$(function () {_x000D_
  $('#Add').on('click', function () {_x000D_
    $('<p>Text</p>').appendTo('#Content');_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="Content">_x000D_
    <button id="Add">Add Text</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Also I would make sure the jquery is at the bottom of the page just before the closing </body> tag. Doing so will make it so you do not have to have the whole thing wrapped in $(function but I would still do that. Having your javascript load at the end of the page makes it so the rest of the page loads incase there is a slow down in your javascript somewhere.

.NET - How do I retrieve specific items out of a Dataset?

The DataSet object has a Tables array. If you know the table you want, it will have a Row array, each object of which has an ItemArray array. In your case the code would most likely be

int var1 = int.Parse(ds.Tables[0].Rows[0].ItemArray[4].ToString());

and so forth. This would give you the 4th item in the first row. You can also use Columns instead of ItemArray and specify the column name as a string instead of remembering it's index. That approach can be easier to keep up with if the table structure changes. So that would be

int var1 = int.Parse(ds.Tables[0].Rows[0]["MyColumnName"].ToString());

How to restore to a different database in sql server?

You can create a new db then use the "Restore Wizard" enabling the Overwrite option or;

View the content;

RESTORE FILELISTONLY FROM DISK='c:\your.bak'

note the logical names of the .mdf & .ldf from the results, then;

RESTORE DATABASE MyTempCopy FROM DISK='c:\your.bak'
WITH 
   MOVE 'LogicalNameForTheMDF' TO 'c:\MyTempCopy.mdf',
   MOVE 'LogicalNameForTheLDF' TO 'c:\MyTempCopy_log.ldf'

To create the database MyTempCopy with the contents of your.bak.

Example (restores a backup of a db called 'creditline' to 'MyTempCopy';

RESTORE FILELISTONLY FROM DISK='e:\mssql\backup\creditline.bak'

>LogicalName
>--------------
>CreditLine
>CreditLine_log

RESTORE DATABASE MyTempCopy FROM DISK='e:\mssql\backup\creditline.bak'
WITH 
   MOVE 'CreditLine' TO 'e:\mssql\MyTempCopy.mdf',
   MOVE 'CreditLine_log' TO 'e:\mssql\MyTempCopy_log.ldf'

>RESTORE DATABASE successfully processed 186 pages in 0.010 seconds (144.970 MB/sec).

Python Requests - No connection adapters

You need to include the protocol scheme:

'http://192.168.1.61:8080/api/call'

Without the http:// part, requests has no idea how to connect to the remote server.

Note that the protocol scheme must be all lowercase; if your URL starts with HTTP:// for example, it won’t find the http:// connection adapter either.

Do Java arrays have a maximum size?

Actually it's java limitation caping it at 2^30-4 being 1073741820. Not 2^31-1. Dunno why but i tested it manually on jdk. 2^30-3 still throwing vm except

Edit: fixed -1 to -4, checked on windows jvm

findViewById in Fragment

The easiest way to use such things is to use butterknife By this you can add as many Onclciklisteners just by @OnClick() as described below:

public class TestClass extends Fragment {
    @BindView(R.id.my_image) ImageView imageView;
    @OnClick(R.id.my_image)
    public void my_image_click(){
        yourMethod();
    }
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.testclassfragment, container, false);
        ButterKnife.bind(getActivity,view);
        return view;
    }
}

Upload files with HTTPWebrequest (multipart/form-data)

Client use convert File to ToBase64String, after use Xml to promulgate to Server call, this server use File.WriteAllBytes(path,Convert.FromBase64String(dataFile_Client_sent)).

Good lucky!

"for" vs "each" in Ruby

It looks like there is no difference, for uses each underneath.

$ irb
>> for x in nil
>> puts x
>> end
NoMethodError: undefined method `each' for nil:NilClass
    from (irb):1
>> nil.each {|x| puts x}
NoMethodError: undefined method `each' for nil:NilClass
    from (irb):4

Like Bayard says, each is more idiomatic. It hides more from you and doesn't require special language features. Per Telemachus's Comment

for .. in .. sets the iterator outside the scope of the loop, so

for a in [1,2]
  puts a
end

leaves a defined after the loop is finished. Where as each doesn't. Which is another reason in favor of using each, because the temp variable lives a shorter period.

Pause Console in C++ program

The best way depends a lot on the platform(s) being targeted, debug vs. release usage etc.

I don't think there is one best way, but to "force" a wait on enter type scenario in a fairly generic way, especially when debugging (typically this is either compiled in or out based on NDEBUG or _DEBUG), you could try std::getline as follows

inline void wait_on_enter()
{
    std::string dummy;
    std::cout << "Enter to continue..." << std::endl;
    std::getline(std::cin, dummy);
}

With our without the "enter to continue", as needed.

jQuery select change show/hide div event

<script>  
$(document).ready(function(){
    $('#colorselector').on('change', function() {
      if ( this.value == 'red')
      {
        $("#divid").show();
      }
      else
      {
        $("#divid").hide();
      }
    });
});
</script>

Do like this for every value Also change the values... as per your parameters

Array of char* should end at '\0' or "\0"?

According to the C99 spec,

  • NULL expands to a null pointer constant, which is not required to be, but typically is of type void *
  • '\0' is a character constant; character constants are of type int, so it's equivalen to plain 0
  • "\0" is a null-terminated string literal and equivalent to the compound literal (char [2]){ 0, 0 }

NULL, '\0' and 0 are all null pointer constants, so they'll all yield null pointers on conversion, whereas "\0" yields a non-null char * (which should be treated as const as modification is undefined); as this pointer may be different for each occurence of the literal, it can't be used as sentinel value.

Although you may use any integer constant expression of value 0 as a null pointer constant (eg '\0' or sizeof foo - sizeof foo + (int)0.0), you should use NULL to make your intentions clear.

SQL update trigger only when column is modified

Whenever a record has updated a record is "deleted". Here is my example:

ALTER TRIGGER [dbo].[UpdatePhyDate]
   ON  [dbo].[M_ContractDT1]
   AFTER UPDATE
AS 
BEGIN
    -- on ContarctDT1 PhyQty is updated 
    -- I want system date in Phytate automatically saved
    SET NOCOUNT ON;

    declare @dt1ky as int   

    if(update(Phyqty))
    begin
        select @dt1ky = dt1ky from deleted

        update M_ContractDT1 set PhyDate=GETDATE() where Dt1Ky=  @dt1ky     

    end

END

It works fine

PostgreSQL "DESCRIBE TABLE"

The psql equivalent of DESCRIBE TABLE is \d table.

See the psql portion of the PostgreSQL manual for more details.

textarea's rows, and cols attribute in CSS

I don't think you can. I always go with height and width.

textarea{
width:400px;
height:100px;
}

the nice thing about doing it the CSS way is that you can completely style it up. Now you can add things like:

textarea{
width:400px;
height:100px;
border:1px solid #000000;
background-color:#CCCCCC;
}

Spring 3 MVC resources and tag <mvc:resources />

Found the error:

Final xxx-servlet.xml config:

<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />

Image in src/webapp/resources/logo.png

Works!

Add class to <html> with Javascript?

With Jquery... You can add class to html elements like this:

$(".divclass").find("p,h1,h2,h3,figure,span,a").addClass('nameclassorid');

nameclassorid no point or # at the beginning

Printing Lists as Tabular Data

I would try to loop through the list and use a CSV formatter to represent the data you want.

You can specify tabs, commas, or any other char as the delimiter.

Otherwise, just loop through the list and print "\t" after each element

http://docs.python.org/library/csv.html

how to use jQuery ajax calls with node.js

If your simple test page is located on other protocol/domain/port than your hello world node.js example you are doing cross-domain requests and violating same origin policy therefore your jQuery ajax calls (get and load) are failing silently. To get this working cross-domain you should use JSONP based format. For example node.js code:

var http = require('http');

http.createServer(function (req, res) {
    console.log('request received');
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('_testcb(\'{"message": "Hello world!"}\')');
}).listen(8124);

and client side JavaScript/jQuery:

$(document).ready(function() {
    $.ajax({
        url: 'http://192.168.1.103:8124/',
        dataType: "jsonp",
        jsonpCallback: "_testcb",
        cache: false,
        timeout: 5000,
        success: function(data) {
            $("#test").append(data);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert('error ' + textStatus + " " + errorThrown);
        }
    });
});

There are also other ways how to get this working, for example by setting up reverse proxy or build your web application entirely with framework like express.

Bash command to sum a column of numbers

[a followup to ghostdog74s comments]

bash-2.03$ uname -sr
SunOS 5.8

bash-2.03$ perl -le 'print for 1..49999998' > infile

bash-2.03$ wc -l infile
 49999998 infile

bash-2.03$  time paste -sd+ infile | bc
bundling space exceeded on line 1, teletype
Broken Pipe

real    0m0.062s
user    0m0.010s
sys     0m0.010s

bash-2.03$ time nawk '{s+=$1}END{print s}' infile
1249999925000001

real    2m0.042s
user    1m59.220s
sys     0m0.590s
bash-2.03$ time /usr/xpg4/bin/awk '{s+=$1}END{print s}' infile
1249999925000001

real    2m27.260s
user    2m26.230s
sys     0m0.660s

bash-2.03$ time perl -nle'
  $s += $_; END { print $s }
   ' infile
1.249999925e+15

real    1m34.663s
user    1m33.710s
sys     0m0.650s

Disable activity slide-in animation when launching new activity?

To clear things up: FLAG_ACTIVITY_NO_ANIMATION (or android:windowAnimationStyle = @null in the theme) work perfectly fine for both, enter and exit. The problem is, that the enter animation checks if the animation is enabled in the one activity and the exit animation checks it for the other one. So make sure to disable it in both activities.

Auto height of div

Here is the Latest solution of the problem:

In your CSS file write the following class called .clearfix along with the pseudo selector :after

.clearfix:after {
content: "";
display: table;
clear: both;
}

Then, in your HTML, add the .clearfix class to your parent Div. For example:

<div class="clearfix">
    <div></div>
    <div></div>
</div>

It should work always. You can call the class name as .group instead of .clearfix , as it will make the code more semantic. Note that, it is Not necessary to add the dot or even a space in the value of Content between the double quotation "".

Source: http://css-snippets.com/page/2/

How to put a Scanner input into an array... for example a couple of numbers

public static void main (String[] args)
{
    Scanner s = new Scanner(System.in);
    System.out.println("Please enter size of an array");
    int n=s.nextInt();
    double arr[] = new double[n];
    System.out.println("Please enter elements of array:");
    for (int i=0; i<n; i++)
    {
        arr[i] = s.nextDouble();
    }
}

how can I Update top 100 records in sql server

update tb set  f1=1 where id in (select top 100 id from tb where f1=0)

How to stop PHP code execution?

You could try to kill the PHP process:

exec('kill -9 ' . getmypid());

Setting PATH environment variable in OSX permanently

For setting up path in Mac two methods can be followed.

  1. Creating a file for variable name and paste the path there under /etc/paths.d and source the file to profile_bashrc.
  2. Export path variable in ~/.profile_bashrc as

    export VARIABLE_NAME = $(PATH_VALUE)

AND source the the path. Its simple and stable.

You can set any path variable by Mac terminal or in linux also.

Assembly Language - How to do Modulo?

If you don't care too much about performance and want to use the straightforward way, you can use either DIV or IDIV.

DIV or IDIV takes only one operand where it divides a certain register with this operand, the operand can be register or memory location only.

When operand is a byte: AL = AL / operand, AH = remainder (modulus).

Ex:

MOV AL,31h ; Al = 31h

DIV BL ; Al (quotient)= 08h, Ah(remainder)= 01h

when operand is a word: AX = (AX) / operand, DX = remainder (modulus).

Ex:

MOV AX,9031h ; Ax = 9031h

DIV BX ; Ax=1808h & Dx(remainder)= 01h

Create Elasticsearch curl query for not null and not empty("")

You need to use bool query with must/must_not and exists

To get where place is null

{
  "query": {
    "bool": {
      "must_not": {
        "exists": {
          "field": "place"
        }
      }
    }
  }
}

To get where place is not null

{
  "query": {
    "bool": {
      "must": {
        "exists": {
          "field": "place"
        }
      }
    }
  }
}

Single vs Double quotes (' vs ")

It makes no difference to the html but if you are generating html dynamically with another programming language then one way may be easier than another.

For example in Java the double quote is used to indicate the start and end of a String, so if you want to include a doublequote within the String you have to escape it with a backslash.

String s = "<a href=\"link\">a Link</a>"

You don't have such a problem with the single quote, therefore use of the single quote makes for more readable code in Java.

String s = "<a href='link'>a Link</a>"

Especially if you have to write html elements with many attributes.(Note I usually use a library such as jhtml to write html in Java, but not always practical to do so)

Class has no initializers Swift

You have to use implicitly unwrapped optionals so that Swift can cope with circular dependencies (parent <-> child of the UI components in this case) during the initialization phase.

@IBOutlet var imgBook: UIImageView!
@IBOutlet var titleBook: UILabel!
@IBOutlet var pageBook: UILabel!

Read this doc, they explain it all nicely.

correct way to define class variables in Python

I think this sample explains the difference between the styles:

james@bodacious-wired:~$cat test.py 
#!/usr/bin/env python

class MyClass:
    element1 = "Hello"

    def __init__(self):
        self.element2 = "World"

obj = MyClass()

print dir(MyClass)
print "--"
print dir(obj)
print "--"
print obj.element1 
print obj.element2
print MyClass.element1 + " " + MyClass.element2
james@bodacious-wired:~$./test.py 
['__doc__', '__init__', '__module__', 'element1']
--
['__doc__', '__init__', '__module__', 'element1', 'element2']
--
Hello World
Hello
Traceback (most recent call last):
  File "./test.py", line 17, in <module>
    print MyClass.element2
AttributeError: class MyClass has no attribute 'element2'

element1 is bound to the class, element2 is bound to an instance of the class.

Use JSTL forEach loop's varStatus as an ID

Its really helped me to dynamically generate ids of showDetailItem for the below code.

<af:forEach id="fe1" items="#{viewScope.bean.tranTypeList}" var="ttf" varStatus="ttfVs" > 
<af:showDetailItem  id ="divIDNo${ttfVs.count}" text="#{ttf.trandef}"......>

if you execute this line <af:outputText value="#{ttfVs}"/> prints the below:

{index=3, count=4, last=false, first=false, end=8, step=1, begin=0}

What's the best way to select the minimum value from several columns?

select *,
case when column1 < columnl2 And column1 < column3 then column1
when columnl2 < column1 And columnl2 < column3 then columnl2
else column3
end As minValue
from   tbl_example

how to loop through rows columns in excel VBA Macro

I'd recommend the Range object's AutoFill method for this:

rngSource.AutoFill Destination:=rngDest

Specify the Source range that contains the values or formulas you want to fill down, and the Destination range as the whole range that you want the cells filled to. The Destination range must include the Source range. You can fill across as well as down.

It works exactly the same way as it would if you manually "dragged" the cells at the corner with the mouse; absolute and relative formulas work as expected.

Here's an example:

'Set some example values'
Range("A1").Value = "1"
Range("B1").Formula = "=NOW()"
Range("C1").Formula = "=B1+A1"

'AutoFill the values / formulas to row 20'
Range("A1:C1").AutoFill Destination:=Range("A1:C20")

Hope this helps.

Convert Python dict into a dataframe

d = {'Date': list(yourDict.keys()),'Date_Values': list(yourDict.values())}
df = pandas.DataFrame(data=d)

If you don't encapsulate yourDict.keys() inside of list() , then you will end up with all of your keys and values being placed in every row of every column. Like this:

Date \ 0 (2012-06-08, 2012-06-09, 2012-06-10, 2012-06-1...
1 (2012-06-08, 2012-06-09, 2012-06-10, 2012-06-1...
2 (2012-06-08, 2012-06-09, 2012-06-10, 2012-06-1...
3 (2012-06-08, 2012-06-09, 2012-06-10, 2012-06-1...
4 (2012-06-08, 2012-06-09, 2012-06-10, 2012-06-1...

But by adding list() then the result looks like this:

Date Date_Values 0 2012-06-08 388 1 2012-06-09 388 2 2012-06-10 388 3 2012-06-11 389 4 2012-06-12 389 ...

Valid values for android:fontFamily and what they map to?

Where do these values come from? The documentation for android:fontFamily does not list this information in any place

These are indeed not listed in the documentation. But they are mentioned here under the section 'Font families'. The document lists every new public API for Android Jelly Bean 4.1.

In the styles.xml file in the application I'm working on somebody listed this as the font family, and I'm pretty sure it's wrong:

Yes, that's wrong. You don't reference the font file, you have to use the font name mentioned in the linked document above. In this case it should have been this:

<item name="android:fontFamily">sans-serif</item>

Like the linked answer already stated, 12 variants are possible:

Added in Android Jelly Bean (4.1) - API 16 :

Regular (default):

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">normal</item> 

Italic:

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">italic</item>

Bold:

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold</item>

Bold-italic:

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold|italic</item>

Light:

<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">normal</item>

Light-italic:

<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">italic</item>

Thin :

<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">normal</item>

Thin-italic :

<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">italic</item>

Condensed regular:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">normal</item>

Condensed italic:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">italic</item>

Condensed bold:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold</item>

Condensed bold-italic:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold|italic</item>

Added in Android Lollipop (v5.0) - API 21 :

Medium:

<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">normal</item>

Medium-italic:

<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">italic</item>

Black:

<item name="android:fontFamily">sans-serif-black</item>
<item name="android:textStyle">italic</item>

For quick reference, this is how they all look like:

correct way of comparing string jquery operator =

No. = sets somevar to have that value. use === to compare value and type which returns a boolean that you need.

Never use or suggest == instead of ===. its a recipe for disaster. e.g 0 == "" is true but "" == '0' is false and many more.

More information also in this great answer

How does Python manage int and long?

This PEP should help.

Bottom line is that you really shouldn't have to worry about it in python versions > 2.4

How to randomly select rows in SQL?

In order to shuffle the SQL result set, you need to use a database-specific function call.

Note that sorting a large result set using a RANDOM function might turn out to be very slow, so make sure you do that on small result sets.

If you have to shuffle a large result set and limit it afterward, then it's better to use something like the Oracle SAMPLE(N) or the TABLESAMPLE in SQL Server or PostgreSQL instead of a random function in the ORDER BY clause.

So, assuming we have the following database table:

Song database table

And the following rows in the song table:

| id | artist                          | title                              |
|----|---------------------------------|------------------------------------|
| 1  | Miyagi & ???????? ft. ??? ????? | I Got Love                         |
| 2  | HAIM                            | Don't Save Me (Cyril Hahn Remix)   |
| 3  | 2Pac ft. DMX                    | Rise Of A Champion (GalilHD Remix) |
| 4  | Ed Sheeran & Passenger          | No Diggity (Kygo Remix)            |
| 5  | JP Cooper ft. Mali-Koa          | All This Love                      |

Oracle

On Oracle, you need to use the DBMS_RANDOM.VALUE function, as illustrated by the following example:

SELECT
    artist||' - '||title AS song
FROM song
ORDER BY DBMS_RANDOM.VALUE

When running the aforementioned SQL query on Oracle, we are going to get the following result set:

| song                                              |
|---------------------------------------------------|
| JP Cooper ft. Mali-Koa - All This Love            |
| 2Pac ft. DMX - Rise Of A Champion (GalilHD Remix) |
| HAIM - Don't Save Me (Cyril Hahn Remix)           |
| Ed Sheeran & Passenger - No Diggity (Kygo Remix)  |
| Miyagi & ???????? ft. ??? ????? - I Got Love      |

Notice that the songs are being listed in random order, thanks to the DBMS_RANDOM.VALUE function call used by the ORDER BY clause.

SQL Server

On SQL Server, you need to use the NEWID function, as illustrated by the following example:

SELECT
    CONCAT(CONCAT(artist, ' - '), title) AS song
FROM song
ORDER BY NEWID()

When running the aforementioned SQL query on SQL Server, we are going to get the following result set:

| song                                              |
|---------------------------------------------------|
| Miyagi & ???????? ft. ??? ????? - I Got Love      |
| JP Cooper ft. Mali-Koa - All This Love            |
| HAIM - Don't Save Me (Cyril Hahn Remix)           |
| Ed Sheeran & Passenger - No Diggity (Kygo Remix)  |
| 2Pac ft. DMX - Rise Of A Champion (GalilHD Remix) |

Notice that the songs are being listed in random order, thanks to the NEWID function call used by the ORDER BY clause.

PostgreSQL

On PostgreSQL, you need to use the random function, as illustrated by the following example:

SELECT
    artist||' - '||title AS song
FROM song
ORDER BY random()

When running the aforementioned SQL query on PostgreSQL, we are going to get the following result set:

| song                                              |
|---------------------------------------------------|
| 2Pac ft. DMX - Rise Of A Champion (GalilHD Remix) |
| JP Cooper ft. Mali-Koa - All This Love            |
| Ed Sheeran & Passenger - No Diggity (Kygo Remix)  |
| HAIM - Don't Save Me (Cyril Hahn Remix)           |
| Miyagi & ???????? ft. ??? ????? - I Got Love      |

Notice that the songs are being listed in random order, thanks to the random function call used by the ORDER BY clause.

MySQL

On MySQL, you need to use the RAND function, as illustrated by the following example:

SELECT
  CONCAT(CONCAT(artist, ' - '), title) AS song
FROM song
ORDER BY RAND()

When running the aforementioned SQL query on MySQL, we are going to get the following result set:

| song                                              |
|---------------------------------------------------|
| HAIM - Don't Save Me (Cyril Hahn Remix)           |
| Ed Sheeran & Passenger - No Diggity (Kygo Remix)  |
| Miyagi & ???????? ft. ??? ????? - I Got Love      |
| 2Pac ft. DMX - Rise Of A Champion (GalilHD Remix) |
| JP Cooper ft. Mali-Koa - All This Love            |

Notice that the songs are being listed in random order, thanks to the RAND function call used by the ORDER BY clause.

Python Script to convert Image into Byte array

This works for me

# Convert image to bytes
import PIL.Image as Image
pil_im = Image.fromarray(image)
b = io.BytesIO()
pil_im.save(b, 'jpeg')
im_bytes = b.getvalue()
return im_bytes

Basic http file downloading and saving to disk in python?

As mentioned here:

import urllib
urllib.urlretrieve ("http://randomsite.com/file.gz", "file.gz")

EDIT: If you still want to use requests, take a look at this question or this one.

How to restart a node.js server

I understand that my comment relate with windows, but may be someone be useful. For win run in cmd:

wmic process  where "commandline like '%my_app.js%' AND name='node.exe' " CALL Terminate

then you can run your app again:

node my_app.js

Also you can use it in batch file, with escape quotes:

wmic process  where "commandline like '%%my_app.js%%' AND name='node.exe' " CALL Terminate
node my_app.js

User Get-ADUser to list all properties and export to .csv

This can be simplified by completely skipping the where object and the $users declaration. All you need is:

Code

get-content c:\scripts\users.txt | get-aduser -properties * | select displayname, office | export-csv c:\path\to\your.csv

How can I detect the touch event of an UIImageView?

A UIImageView is derived from a UIView which is derived from UIResponder so it's ready to handle touch events. You'll want to provide the touchesBegan, touchesMoved, and touchesEnded methods and they'll get called if the user taps the image. If all you want is a tap event, it's easier to just use a custom button with the image set as the button image. But if you want finer-grain control over taps, moves, etc. this is the way to go.

You'll also want to look at a few more things:

  • Override canBecomeFirstResponder and return YES to indicate that the view can become the focus of touch events (the default is NO).

  • Set the userInteractionEnabled property to YES. The default for UIViews is YES, but for UIImageViews is NO so you have to explicitly turn it on.

  • If you want to respond to multi-touch events (i.e. pinch, zoom, etc) you'll want to set multipleTouchEnabled to YES.

Setting table column width

Add colgroup after your table tag. Define width and number of column here. and add tbody tag. Put your tr inside of tbody.

<table>
    <colgroup>
       <col span="1" style="width: 30%;">
       <col span="1" style="width: 70%;">
    </colgroup>


    <tbody>
        <tr>
            <td>First column</td>
            <td>Second column</td>
        </tr>
    </tbody>
</table>

What is the use of the @Temporal annotation in Hibernate?

If you're looking for short answer:

In the case of using java.util.Date, Java doesn't really know how to directly relate to SQL types. This is when @Temporal comes into play. It's used to specify the desired SQL type.

Source: Baeldung

Using sed, Insert a line above or below the pattern?

The following adds one line after SearchPattern.

sed -i '/SearchPattern/aNew Text' SomeFile.txt

It inserts New Text one line below each line that contains SearchPattern.

To add two lines, you can use a \ and enter a newline while typing New Text.

POSIX sed requires a \ and a newline after the a sed function. [1] Specifying the text to append without the newline is a GNU sed extension (as documented in the sed info page), so its usage is not as portable.

[1] https://unix.stackexchange.com/questions/52131/sed-on-osx-insert-at-a-certain-line/

Image comparison - fast algorithm

I believe that dropping the size of the image down to an almost icon size, say 48x48, then converting to greyscale, then taking the difference between pixels, or Delta, should work well. Because we're comparing the change in pixel color, rather than the actual pixel color, it won't matter if the image is slightly lighter or darker. Large changes will matter since pixels getting too light/dark will be lost. You can apply this across one row, or as many as you like to increase the accuracy. At most you'd have 47x47=2,209 subtractions to make in order to form a comparable Key.

How to ignore parent css style

There are a bunch of values that can be used to undo CSS rules: initial, unset & revert. More details from the CSS Working Group at W3C:

https://drafts.csswg.org/css-cascade/#defaulting-keywords

As this is 'draft' not all are fully supported, but unset and initial are in most major browsers, revert has less support.

Skip over a value in the range function in python

what you could do, is put an if statement around everything inside the loop that you want kept away from the 50. e.g.

for i in range(0, len(list)):
    if i != 50:
        x= listRow(list, i)
        for j in range (#0 to len(list) not including x#)

Spring AMQP + RabbitMQ 3.3.5 ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN

I am sure what Artem Bilan has explained here might be one of the reasons for this error:

Caused by: com.rabbitmq.client.AuthenticationFailureException: 
ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN. 
For details see the

but the solution for me was that I logged in to rabbitMQ admin page (http://localhost:15672/#/users) with the default user name and password which is guest/guest then added a new user and for that new user I enabled the permission to access it from virtual host and then used the new user name and password instead of default guest and that cleared the error.

enter image description here

Python find elements in one list that are not in the other

If you want a one-liner solution (ignoring imports) that only requires O(max(n, m)) work for inputs of length n and m, not O(n * m) work, you can do so with the itertools module:

from itertools import filterfalse

main_list = list(filterfalse(set(list_1).__contains__, list_2))

This takes advantage of the functional functions taking a callback function on construction, allowing it to create the callback once and reuse it for every element without needing to store it somewhere (because filterfalse stores it internally); list comprehensions and generator expressions can do this, but it's ugly.†

That gets the same results in a single line as:

main_list = [x for x in list_2 if x not in list_1]

with the speed of:

set_1 = set(list_1)
main_list = [x for x in list_2 if x not in set_1]

Of course, if the comparisons are intended to be positional, so:

list_1 = [1, 2, 3]
list_2 = [2, 3, 4]

should produce:

main_list = [2, 3, 4]

(because no value in list_2 has a match at the same index in list_1), you should definitely go with Patrick's answer, which involves no temporary lists or sets (even with sets being roughly O(1), they have a higher "constant" factor per check than simple equality checks) and involves O(min(n, m)) work, less than any other answer, and if your problem is position sensitive, is the only correct solution when matching elements appear at mismatched offsets.

†: The way to do the same thing with a list comprehension as a one-liner would be to abuse nested looping to create and cache value(s) in the "outermost" loop, e.g.:

main_list = [x for set_1 in (set(list_1),) for x in list_2 if x not in set_1]

which also gives a minor performance benefit on Python 3 (because now set_1 is locally scoped in the comprehension code, rather than looked up from nested scope for each check; on Python 2 that doesn't matter, because Python 2 doesn't use closures for list comprehensions; they operate in the same scope they're used in).

How to make two plots side-by-side using Python?

Check this page out: http://matplotlib.org/examples/pylab_examples/subplots_demo.html

plt.subplots is similar. I think it's better since it's easier to set parameters of the figure. The first two arguments define the layout (in your case 1 row, 2 columns), and other parameters change features such as figure size:

import numpy as np
import matplotlib.pyplot as plt

x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)

fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(5, 3))
axes[0].plot(x1, y1)
axes[1].plot(x2, y2)
fig.tight_layout()

enter image description here

Split Java String by New Line

There is new boy in the town, so you need not to deal with all above complexities. From JDK 11 onward, just need to write as single line of code, it will split lines and returns you Stream of String.

public class MyClass {
public static void main(String args[]) {
   Stream<String> lines="foo \n bar \n baz".lines();
   //Do whatever you want to do with lines
}}

Some references. https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#lines() https://www.azul.com/90-new-features-and-apis-in-jdk-11/

I hope this will be helpful to someone. Happy coding.

Ionic android build Error - Failed to find 'ANDROID_HOME' environment variable

To add ANDROID_HOME value permanently,

gedit ~/.bashrc

and add the following lines

export ANDROID_HOME=/root/Android/Sdk
PATH=$PATH:$ANDROID_HOME/tools

Save the file and you need not update ANDROID_HOME value everytime.

Set margins in a LinearLayout programmatically

To add margins directly to items (some items allow direct editing of margins), you can do:

LayoutParams lp = ((ViewGroup) something).getLayoutParams();
if( lp instanceof MarginLayoutParams )
{
    ((MarginLayoutParams) lp).topMargin = ...;
    ((MarginLayoutParams) lp).leftMargin = ...;
    //... etc
}
else
    Log.e("MyApp", "Attempted to set the margins on a class that doesn't support margins: "+something.getClass().getName() );

...this works without needing to know about / edit the surrounding layout. Note the "instanceof" check in case you try and run this against something that doesn't support margins.

how to make div click-able?

add the onclick attribute

<div onclick="myFunction( event );"><span>shanghai</span><span>male</span></div>

To get the cursor to change use css's cursor rule.

div[onclick] {
  cursor: pointer;
}

The selector uses an attribute selector which does not work in some versions of IE. If you want to support those versions, add a class to your div.

Shrinking navigation bar when scrolling down (bootstrap3)

I am using this code for my project

$(window).scroll ( function() {
    if ($(document).scrollTop() > 50) {
        document.getElementById('your-div').style.height = '100px'; //For eg
    } else {
        document.getElementById('your-div').style.height = '150px';
    }    
}
);

Probably this will help

How to downgrade to older version of Gradle

Got to

gradle-wrapper.properties

Change the version of the below mentioned distribution (gradle-5.6.4-bin.zip)

distributionUrl=https://services.gradle.org/distributions/gradle-5.6.4-bin.zip

DataAdapter.Fill(Dataset)

DataSet ds = new DataSet();

using (OleDbConnection connection = new OleDbConnection(connectionString))
using (OleDbCommand command = new OleDbCommand(query, connection))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
    adapter.Fill(ds);
}

return ds;

Server Client send/receive simple text

    static void Main(string[] args)
    {
        //---listen at the specified IP and port no.---
        IPAddress localAdd = IPAddress.Parse(SERVER_IP);
        TcpListener listener = new TcpListener(localAdd, PORT_NO);
        Console.WriteLine("Listening...");
        listener.Start();
        while (true)
        {
            //---incoming client connected---
            TcpClient client = listener.AcceptTcpClient();

            //---get the incoming data through a network stream---
            NetworkStream nwStream = client.GetStream();
            byte[] buffer = new byte[client.ReceiveBufferSize];

            //---read incoming stream---
            int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);

            //---convert the data received into a string---
            string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
            Console.WriteLine("Received : " + dataReceived);

            //---write back the text to the client---
            Console.WriteLine("Sending back : " + dataReceived);
            nwStream.Write(buffer, 0, bytesRead);
            client.Close();
        }
        listener.Stop();
        Console.ReadLine();
    }

In addition to @Nudier Mena answer, keep a while loop to keep the server in listening mode. So that we can have multiple instance of client connected.

Include another JSP file

You can use Include Directives

<%
 if(request.getParameter("p")!=null)
 { 
   String p = request.getParameter("p");
%>    

<%@include file="<%="includes/" + p +".jsp"%>"%>

<% 
 }
%>

or JSP Include Action

<%
 if(request.getParameter("p")!=null)
 { 
   String p = request.getParameter("p");
%>    

<jsp:include page="<%="includes/"+p+".jsp"%>"/>

<% 
 }
%>

the different is include directive includes a file during the translation phase. while JSP Include Action includes a file at the time the page is requested

I recommend Spring MVC Framework as your controller to manipulate things. use url pattern instead of parameter.

example:

www.yourwebsite.com/products

instead of

www.yourwebsite.com/?p=products

Watch this video Spring MVC Framework

What browsers support HTML5 WebSocket API?

Client side

  • Hixie-75:
    • Chrome 4.0 + 5.0
    • Safari 5.0.0
  • HyBi-00/Hixie-76:
  • HyBi-07+:
  • HyBi-10:
    • Chrome 14.0 + 15.0
    • Firefox 7.0 + 8.0 + 9.0 + 10.0 - prefixed: MozWebSocket
    • IE 10 (from Windows 8 developer preview)
  • HyBi-17/RFC 6455
    • Chrome 16
    • Firefox 11
    • Opera 12.10 / Opera Mobile 12.1

Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.

See caniuse for the current status of WebSockets support in desktop and mobile browsers.

See the test reports from the WS testsuite included in Autobahn WebSockets for feature/protocol conformance tests.


Server side

It depends on which language you use.

In Java/Java EE:

Some other Java implementations:

In C#:

In PHP:

In Python:

In C:

In Node.js:

  • Socket.io : Socket.io also has serverside ports for Python, Java, Google GO, Rack
  • sockjs : sockjs also has serverside ports for Python, Java, Erlang and Lua
  • WebSocket-Node - Pure JavaScript Client & Server implementation of HyBi-10.

Vert.x (also known as Node.x) : A node like polyglot implementation running on a Java 7 JVM and based on Netty with :

  • Support for Ruby(JRuby), Java, Groovy, Javascript(Rhino/Nashorn), Scala, ...
  • True threading. (unlike Node.js)
  • Understands multiple network protocols out of the box including: TCP, SSL, UDP, HTTP, HTTPS, Websockets, SockJS as fallback for WebSockets

Pusher.com is a Websocket cloud service accessible through a REST API.

DotCloud cloud platform supports Websockets, and Java (Jetty Servlet Container), NodeJS, Python, Ruby, PHP and Perl programming languages.

Openshift cloud platform supports websockets, and Java (Jboss, Spring, Tomcat & Vertx), PHP (ZendServer & CodeIgniter), Ruby (ROR), Node.js, Python (Django & Flask) plateforms.

For other language implementations, see the Wikipedia article for more information.

The RFC for Websockets : RFC6455

Insert into C# with SQLCommand

You can use dapper library:

conn2.Execute(@"INSERT INTO klant(klant_id,naam,voornaam) VALUES (@p1,@p2,@p3)", 
                new { p1 = klantId, p2 = klantNaam, p3 = klantVoornaam });

BTW Dapper is a Stack Overflow project :)

UPDATE: I believe you can't do it simpler without something like EF. Also try to use using statements when you are working with database connections. This will close connection automatically, even in case of exception. And connection will be returned to connections pool.

private readonly string _spionshopConnectionString;

private void Form1_Load(object sender, EventArgs e)
{            
    _spionshopConnectionString = ConfigurationManager
          .ConnectionStrings["connSpionshopString"].ConnectionString;
}

private void button4_Click(object sender, EventArgs e)
{
    using(var connection = new SqlConnection(_spionshopConnectionString))
    {
         connection.Execute(@"INSERT INTO klant(klant_id,naam,voornaam) 
                              VALUES (@klantId,@klantNaam,@klantVoornaam)",
                              new { 
                                      klantId = Convert.ToInt32(textBox1.Text), 
                                      klantNaam = textBox2.Text, 
                                      klantVoornaam = textBox3.Text 
                                  });
    }
}

T-SQL CASE Clause: How to specify WHEN NULL

Use the CONCAT function available in SQL Server 2012 onward.

SELECT CONCAT([FirstName], ' , ' , [LastName]) FROM YOURTABLE

Open Source Alternatives to Reflector?

Well, Reflector itself is a .NET assembly so you can open Reflector.exe in Reflector to check out how it's built.

How can I scale the content of an iframe?

Thought I'd share what I came up with, using much of what was given above. I haven't checked Chrome, but it works in IE, Firefox and Safari, so far as I can tell.

The specifics offsets and zoom factor in this example worked for shrinking and centering two websites in iframes for Facebook tabs (810px width).

The two sites used were a wordpress site and a ning network. I'm not very good with html, so this could probably have been done better, but the result seems good.

<style>
    #wrap { width: 1620px; height: 3500px; padding: 0; position:relative; left:-100px; top:0px; overflow: hidden; }
    #frame { width: 1620px; height: 3500px; position:relative; left:-65px; top:0px; }
    #frame { -ms-zoom: 0.7; -moz-transform: scale(0.7); -moz-transform-origin: 0px 0; -o-transform: scale(0.7); -o-transform-origin: 0 0; -webkit-transform: scale(0.7); -webkit-transform-origin: 0 0; }
</style>
<div id="wrap">
    <iframe id="frame" src="http://www.example.com"></iframe>
</div>

Combine multiple JavaScript files into one JS file

Just combine the text files and then use something like the YUI Compressor.

Files can be easily combined using the command cat *.js > main.js and main.js can then be run through the YUI compressor using java -jar yuicompressor-x.y.z.jar -o main.min.js main.js.

Update Aug 2014

I've now migrated to using Gulp for javascript concatenation and compression as with various plugins and some minimal configuration you can do things like set up dependencies, compile coffeescript etc as well as compressing your JS.

Clearing _POST array fully

To unset the $_POST variable, redeclare it as an empty array:

$_POST = array();

Does C++ support 'finally' blocks? (And what's this 'RAII' I keep hearing about?)

As pointed out in the other answers, C++ can support finally-like functionality. The implementation of this functionality that is probably closest to being part of the standard language is the one accompanying the C++ Core Guidelines, a set of best practices for using C++ edited by Bjarne Stoustrup and Herb Sutter. An implementation of finally is part of the Guidelines Support Library (GSL). Throughout the Guidelines, use of finally is recommended when dealing with old-style interfaces, and it also has a guideline of its own, titled Use a final_action object to express cleanup if no suitable resource handle is available.

So, not only does C++ support finally, it is actually recommended to use it in a lot of common use-cases.

An example use of the GSL implementation would look like:

#include <gsl/gsl_util.h>

void example()
{
    int handle = get_some_resource();
    auto handle_clean = gsl::finally([&handle] { clean_that_resource(handle); });

    // Do a lot of stuff, return early and throw exceptions.
    // clean_that_resource will always get called.
}

The GSL implementation and usage is very similar to the one in Paolo.Bolzoni's answer. One difference is that the object created by gsl::finally() lacks the disable() call. If you need that functionality (say, to return the resource once it's assembled and no exceptions are bound to happen), you might prefer Paolo's implementation. Otherwise, using GSL is as close to using standardized features as you will get.

how to start stop tomcat server using CMD?

You can use the following command c:\path of you tomcat directory\bin>catalina run

JavaScript to scroll long page to DIV

scrollTop (IIRC) is where in the document the top of the page is scrolled to. scrollTo scrolls the page so that the top of the page is where you specify.

What you need here is some Javascript manipulated styles. Say if you wanted the div off-screen and scroll in from the right you would set the left attribute of the div to the width of the page and then decrease it by a set amount every few seconds until it is where you want.

This should point you in the right direction.

Additional: I'm sorry, I thought you wanted a separate div to 'pop out' from somewhere (sort of like this site does sometimes), and not move the entire page to a section. Proper use of anchors would achieve that effect.

Post multipart request with Android SDK

For posterity, I didn't see okhttp mentioned. Related post.

Basically you build up the body using a MultipartBody.Builder, and then post this in a request.

Example in kotlin:

    val body = MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart(
                "file", 
                file.getName(),
                RequestBody.create(MediaType.parse("image/png"), file)
            )
            .addFormDataPart("timestamp", Date().time.toString())
            .build()

    val request = Request.Builder()
            .url(url)
            .post(body)
            .build()

    httpClient.newCall(request).enqueue(object : okhttp3.Callback {
        override fun onFailure(call: Call?, e: IOException?) {
            ...
        }

        override fun onResponse(call: Call?, response: Response?) {
            ...
        }
    })

Only using @JsonIgnore during serialization, but not deserialization

Since version 2.6: a more intuitive way is to use the com.fasterxml.jackson.annotation.JsonProperty annotation on the field:

@JsonProperty(access = Access.WRITE_ONLY)
private String myField;

Even if a getter exists, the field value is excluded from serialization.

JavaDoc says:

/**
 * Access setting that means that the property may only be written (set)
 * for deserialization,
 * but will not be read (get) on serialization, that is, the value of the property
 * is not included in serialization.
 */
WRITE_ONLY

In case you need it the other way around, just use Access.READ_ONLY.

What's NSLocalizedString equivalent in Swift?

This is an improvement on the ".localized" approach. Start with adding the class extension as this will help with any strings you were setting programatically:

extension String {
    func localized (bundle: Bundle = .main, tableName: String = "Localizable") -> String {
        return NSLocalizedString(self, tableName: tableName, value: "\(self)", comment: "")
    }
}

Example use for strings you set programmatically:

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

Now Xcode's storyboard translation files make the file manager messy and don't handle updates to the storyboard well either. A better approach is to create a new basic label class and assign it to all your storyboard labels:

class BasicLabel: UILabel {
    //initWithFrame to init view from code
    override init(frame: CGRect) {
      super.init(frame: frame)
      setupView()
    }

    //initWithCode to init view from xib or storyboard
    required init?(coder aDecoder: NSCoder) {
      super.init(coder: aDecoder)
      setupView()
    }

    //common func to init our view
    private func setupView() {
        let storyboardText = self.text
        text = storyboardText?.localized()
    }
}

Now every label you add and provide default default for in the storyboard will automatically get translated, assuming you've provide a translation for it.

You could do the same for UIButton:

class BasicBtn: UIButton {
    //initWithFrame to init view from code
    override init(frame: CGRect) {
      super.init(frame: frame)
      setupView()
    }

    //initWithCode to init view from xib or storyboard
    required init?(coder aDecoder: NSCoder) {
      super.init(coder: aDecoder)
      setupView()
    }

    //common func to init our view
    private func setupView() {
        let storyboardText = self.titleLabel?.text
        let lclTxt = storyboardText?.localized()
        setTitle(lclTxt, for: .normal)
    }
}

nullable object must have a value

You should change the line this.MyDateTime = myNewDT.MyDateTime.Value; to just this.MyDateTime = myNewDT.MyDateTime;

The exception you were receiving was thrown in the .Value property of the Nullable DateTime, as it is required to return a DateTime (since that's what the contract for .Value states), but it can't do so because there's no DateTime to return, so it throws an exception.

In general, it is a bad idea to blindly call .Value on a nullable type, unless you have some prior knowledge that that variable MUST contain a value (i.e. through a .HasValue check).

EDIT

Here's the code for DateTimeExtended that does not throw an exception:

class DateTimeExtended
{
    public DateTime? MyDateTime;
    public int? otherdata;

    public DateTimeExtended() { }

    public DateTimeExtended(DateTimeExtended other)
    {
        this.MyDateTime = other.MyDateTime;
        this.otherdata = other.otherdata;
    }
}

I tested it like this:

DateTimeExtended dt1 = new DateTimeExtended();
DateTimeExtended dt2 = new DateTimeExtended(dt1);

Adding the .Value on other.MyDateTime causes an exception. Removing it gets rid of the exception. I think you're looking in the wrong place.

MySQL count occurrences greater than 2

SELECT count(word) as count 
FROM words 
GROUP BY word
HAVING count >= 2;

How to convert DateTime to/from specific string format (both ways, e.g. given Format is "yyyyMMdd")?

Simply just do in this way.

string yourFormat = DateTime.Now.ToString("yyyyMMdd");

Happy coding :)

Make REST API call in Swift

Here is the complete code for REST API requests using NSURLSession in swift

For GET Request

 let configuration = NSURLSessionConfiguration .defaultSessionConfiguration()
    let session = NSURLSession(configuration: configuration)


    let urlString = NSString(format: "your URL here")

    print("get wallet balance url string is \(urlString)")
    //let url = NSURL(string: urlString as String)
    let request : NSMutableURLRequest = NSMutableURLRequest()
    request.URL = NSURL(string: NSString(format: "%@", urlString) as String)
    request.HTTPMethod = "GET"
    request.timeoutInterval = 30

    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    let dataTask = session.dataTaskWithRequest(request) {
        (let data: NSData?, let response: NSURLResponse?, let error: NSError?) -> Void in

        // 1: Check HTTP Response for successful GET request
        guard let httpResponse = response as? NSHTTPURLResponse, receivedData = data
            else {
                print("error: not a valid http response")
                return
        }

        switch (httpResponse.statusCode)
        {
        case 200:

            let response = NSString (data: receivedData, encoding: NSUTF8StringEncoding)
            print("response is \(response)")


            do {
                let getResponse = try NSJSONSerialization.JSONObjectWithData(receivedData, options: .AllowFragments)

                EZLoadingActivity .hide()

               // }
            } catch {
                print("error serializing JSON: \(error)")
            }

            break
        case 400:

            break
        default:
            print("wallet GET request got response \(httpResponse.statusCode)")
        }
    }
    dataTask.resume()

For POST request ...

let configuration = NSURLSessionConfiguration .defaultSessionConfiguration()
    let session = NSURLSession(configuration: configuration)

    let params = ["username":bindings .objectForKey("username"), "provider":"walkingcoin", "securityQuestion":securityQuestionField.text!, "securityAnswer":securityAnswerField.text!] as Dictionary<String, AnyObject>

    let urlString = NSString(format: “your URL”);
    print("url string is \(urlString)")
    let request : NSMutableURLRequest = NSMutableURLRequest()
    request.URL = NSURL(string: NSString(format: "%@", urlString)as String)
    request.HTTPMethod = "POST"
    request.timeoutInterval = 30
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")      
    request.HTTPBody  = try! NSJSONSerialization.dataWithJSONObject(params, options: [])

    let dataTask = session.dataTaskWithRequest(request)
        {
            (let data: NSData?, let response: NSURLResponse?, let error: NSError?) -> Void in
            // 1: Check HTTP Response for successful GET request
            guard let httpResponse = response as? NSHTTPURLResponse, receivedData = data
                else {
                    print("error: not a valid http response")
                    return
            }

            switch (httpResponse.statusCode)
            {
            case 200:

                let response = NSString (data: receivedData, encoding: NSUTF8StringEncoding)


                if response == "SUCCESS"
                {

                }

            default:
                print("save profile POST request got response \(httpResponse.statusCode)")
            }
    }
    dataTask.resume()

I hope it works.

What causes "Unable to access jarfile" error?

Rename the jar file and try

Explanation : yes, I know there are many answers still I want to add one point here which I faced.

I built the jar and I moved it into the server where I deploy (This is the normal process) here the file name which I moved already existed in the server, here the file will override obviously right. In this case, I faced this issue. maybe at the time of overriding there can be a permission copy issue.

Hope this will help someone.

Find the least number of coins required that can make any change from 1 to 99 cents

For this problem, Greedy approach gives a better solution than DP or others. Greedy approach: Find the largest denomination that is lesser than the required value and add it to the set of coins to be delivered. Lower the required cents by the denomination just added and repeat until the required cents becomes zero.

My solution (greedy approach) in java solution:

public class MinimumCoinDenomination {

    private static final int[] coinsDenominations = {1, 5, 10, 25, 50, 100};

    public static Map<Integer, Integer> giveCoins(int requiredCents) {
        if(requiredCents <= 0) {
            return null;
        }
        Map<Integer, Integer> denominations = new HashMap<Integer, Integer>();

        int dollar = requiredCents/100;
        if(dollar>0) {
            denominations.put(100, dollar);
        }
        requiredCents = requiredCents - (dollar * 100);

        //int sum = 0;
        while(requiredCents > 0) {
            for(int i = 1; i<coinsDenominations.length; i++) {
                if(requiredCents < coinsDenominations[i]) {
                    //sum = sum +coinsDenominations[i-1];
                    if(denominations.containsKey(coinsDenominations[i-1])) {
                        int c = denominations.get(coinsDenominations[i-1]);
                        denominations.put(coinsDenominations[i-1], c+1);
                    } else {
                        denominations.put(coinsDenominations[i-1], 1);
                    }
                    requiredCents = requiredCents - coinsDenominations[i-1];
                    break;
                }
            }
        }
        return denominations;
    }

    public static void main(String[] args) {
        System.out.println(giveCoins(199));
    }

}

How to check if a variable is set in Bash?

To check for non-null/non-zero string variable, i.e. if set, use

if [ -n "$1" ]

It's the opposite of -z. I find myself using -n more than -z.

You would use it like:

if [ -n "$1" ]; then
  echo "You supplied the first parameter!"
else
  echo "First parameter not supplied."
fi

Easiest way to mask characters in HTML(5) text input

A little late, but a useful plugin that will actually use a mask to give a bit more restriction on user input.

<div class="col-sm-3 col-md-6 col-lg-4">
  <div class="form-group">
     <label for="addPhone">Phone Number *</label>
      <input id="addPhone" name="addPhone" type="text" class="form-control 
       required" data-mask="(999) 999-9999"placeholder>
    <span class="help-block">(999) 999-9999</span>
  </div>
</div>

 <!-- Input Mask -->
 <script src="js/plugins/jasny/jasny-bootstrap.min.js"></script>

enter image description here

More info on the plugin https://www.jasny.net/bootstrap/2.3.1/javascript.html#inputmask

How can I create an executable JAR with dependencies using Maven?

Use the maven-shade-plugin to package all dependencies into one uber-jar. It can also be used to build an executable jar by specifying the main class. After trying to use maven-assembly and maven-jar , I found that this plugin best suited my needs.

I found this plugin particularly useful as it merges content of specific files instead of overwriting them. This is needed when there are resource files that are have the same name across the jars and the plugin tries to package all the resource files

See example below

      <plugins>
    <!-- This plugin provides the capability to package the artifact in an uber-jar, including its dependencies and to shade - i.e. rename - the packages of some of the dependencies. -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>1.4</version>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                    <configuration>
                        <artifactSet>
                        <!-- signed jars-->
                            <excludes>
                                <exclude>bouncycastle:bcprov-jdk15</exclude>
                            </excludes>
                        </artifactSet>

                         <transformers>
                            <transformer
                                implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                <!-- Main class -->
                                <mainClass>com.main.MyMainClass</mainClass>
                            </transformer>
                            <!-- Use resource transformers to prevent file overwrites -->
                            <transformer 
                                 implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                                <resource>properties.properties</resource>
                            </transformer>
                            <transformer
                                implementation="org.apache.maven.plugins.shade.resource.XmlAppendingTransformer">
                                <resource>applicationContext.xml</resource>
                            </transformer>
                            <transformer
                                implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                                <resource>META-INF/cxf/cxf.extension</resource>
                            </transformer>
                            <transformer
                                implementation="org.apache.maven.plugins.shade.resource.XmlAppendingTransformer">
                                <resource>META-INF/cxf/bus-extensions.xml</resource>
                            </transformer>
                     </transformers>
                    </configuration>
                </execution>
            </executions>
        </plugin>

    </plugins>

Error 0x80005000 and DirectoryServices

Spent a day on my similar issue, but all these answers didn't help.

Turned out in my case, I didn't enable Windows Authentication in IIS setting...

img onclick call to JavaScript function

In response to the good solution from macek. The solution didn't work for me. I have to bind the values of the datas to the export function. This solution works for me:

function exportToForm(a, b, c, d, e) {
  console.log(a, b, c, d, e);
}

var images = document.getElementsByTagName("img");

for (var i=0, len=images.length, img; i<len; i++) {
  var img = images[i];
  var boundExportToForm = exportToForm.bind(undefined, 
          img.getAttribute("data-a"), 
            img.getAttribute("data-b"),
            img.getAttribute("data-c"),
            img.getAttribute("data-d"),
            img.getAttribute("data-e"))

  img.addEventListener("click", boundExportToForm);
  }

Test credit card numbers for use with PayPal sandbox

It turns out, after messing around with all of the settings in the test business account, that one (or more) of the fraud related settings in the payment receiving preferences / security settings screens were causing the test payments to fail (without any useful error).

nodejs - first argument must be a string or Buffer - when using response.write with http.request

And there is another possibility (not in this case) when working with ajax(XMLhttpRequest), while sending information back to the client end you should use res.send(responsetext) instead of res.end(responsetext)

How to terminate a python subprocess launched with shell=True

I could do it using

from subprocess import Popen

process = Popen(command, shell=True)
Popen("TASKKILL /F /PID {pid} /T".format(pid=process.pid))

it killed the cmd.exe and the program that i gave the command for.

(On Windows)

numpy: most efficient frequency counts for unique values in an array

This is by far the most general and performant solution; surprised it hasn't been posted yet.

import numpy as np

def unique_count(a):
    unique, inverse = np.unique(a, return_inverse=True)
    count = np.zeros(len(unique), np.int)
    np.add.at(count, inverse, 1)
    return np.vstack(( unique, count)).T

print unique_count(np.random.randint(-10,10,100))

Unlike the currently accepted answer, it works on any datatype that is sortable (not just positive ints), and it has optimal performance; the only significant expense is in the sorting done by np.unique.

Using getopts to process long and short command line options

The built-in getopts command is still, AFAIK, limited to single-character options only.

There is (or used to be) an external program getopt that would reorganize a set of options such that it was easier to parse. You could adapt that design to handle long options too. Example usage:

aflag=no
bflag=no
flist=""
set -- $(getopt abf: "$@")
while [ $# -gt 0 ]
do
    case "$1" in
    (-a) aflag=yes;;
    (-b) bflag=yes;;
    (-f) flist="$flist $2"; shift;;
    (--) shift; break;;
    (-*) echo "$0: error - unrecognized option $1" 1>&2; exit 1;;
    (*)  break;;
    esac
    shift
done

# Process remaining non-option arguments
...

You could use a similar scheme with a getoptlong command.

Note that the fundamental weakness with the external getopt program is the difficulty of handling arguments with spaces in them, and in preserving those spaces accurately. This is why the built-in getopts is superior, albeit limited by the fact it only handles single-letter options.

Run script on mac prompt "Permission denied"

You should run the script as 'superuser', just add 'sudo' in front of the command and type your password when prompted.

So try:

sudo /dvtcolorconvert.rb ~/Themes/ObsidianCode.xccolortheme

If this doesn't work, try adapting the permissions:

sudo chmod 755 /dvtcolorconvert.rb
sudo chmod 755 ~/Themes/ObsidianCode.xccolortheme

Easiest way to split a string on newlines in .NET?

string[] lines = text.Split(
  Environment.NewLine.ToCharArray(), 
  StringSplitOptions.RemoveEmptyStrings);

The RemoveEmptyStrings option will make sure you don't have empty entries due to \n following a \r

(Edit to reflect comments:) Note that it will also discard genuine empty lines in the text. This is usually what I want but it might not be your requirement.

Edit a commit message in SourceTree Windows (already pushed to remote)

On Version 1.9.6.1. For UnPushed commit.

  1. Click on previously committed description
  2. Click Commit icon
  3. Enter new commit message, and choose "Ammend latest commit" from the Commit options dropdown.
  4. Commit your message.

combining results of two select statements

You can use a Union.

This will return the results of the queries in separate rows.

First you must make sure that both queries return identical columns.

Then you can do :

SELECT tableA.Id, tableA.Name, [tableB].Username AS Owner, [tableB].ImageUrl, [tableB].CompanyImageUrl, COUNT(tableD.UserId) AS Number
FROM tableD 
RIGHT OUTER JOIN [tableB] 
INNER JOIN tableA ON [tableB].Id = tableA.Owner ON tableD.tableAId = tableA.Id 
GROUP BY tableA.Name, [tableB].Username, [tableB].ImageUrl, [tableB].CompanyImageUrl

UNION

SELECT tableA.Id, tableA.Name,  '' AS Owner, '' AS ImageUrl, '' AS CompanyImageUrl, COUNT([tableC].Id) AS Number
FROM 
[tableC] 
RIGHT OUTER JOIN tableA ON [tableC].tableAId = tableA.Id GROUP BY tableA.Id, tableA.Name

As has been mentioned, both queries return quite different data. You would probably only want to do this if both queries return data that could be considered similar.

SO

You can use a Join

If there is some data that is shared between the two queries. This will put the results of both queries into a single row joined by the id, which is probably more what you want to be doing here...

You could do :

SELECT tableA.Id, tableA.Name, [tableB].Username AS Owner, [tableB].ImageUrl, [tableB].CompanyImageUrl, COUNT(tableD.UserId) AS NumberOfUsers, query2.NumberOfPlans
FROM tableD 
RIGHT OUTER JOIN [tableB] 
INNER JOIN tableA ON [tableB].Id = tableA.Owner ON tableD.tableAId = tableA.Id 


INNER JOIN 
  (SELECT tableA.Id, COUNT([tableC].Id) AS NumberOfPlans 
   FROM [tableC] 
   RIGHT OUTER JOIN tableA ON [tableC].tableAId = tableA.Id 
   GROUP BY tableA.Id, tableA.Name) AS query2 
ON query2.Id = tableA.Id

GROUP BY tableA.Name, [tableB].Username, [tableB].ImageUrl, [tableB].CompanyImageUrl

First Heroku deploy failed `error code=H10`

I just had a similar issue with my app, I got the issue after a migration of the DB, after trying many options, the one that helped me was this:

heroku restart

(Using Heroku toolbelt for mac)

Error sending json in POST to web API service

Please check if you are were passing method as POST instead as GET. if so you will get same error as a you posted above.

$http({               
 method: 'GET',

The request entity's media type 'text/plain' is not supported for this resource.

What is the max size of VARCHAR2 in PL/SQL and SQL?

As per official documentation link shared by Andre Kirpitch, Oracle 10g gives a maximum size of 4000 bytes or characters for varchar2. If you are using a higher version of oracle (for example Oracle 12c), you can get a maximum size upto 32767 bytes or characters for varchar2. To utilize the extended datatype feature of oracle 12, you need to start oracle in upgrade mode. Follow the below steps in command prompt:

1) Login as sysdba (sqlplus / as sysdba)

2) SHUTDOWN IMMEDIATE;

3) STARTUP UPGRADE;

4) ALTER SYSTEM SET max_string_size=extended;

5) Oracle\product\12.1.0.2\rdbms\admin\utl32k.sql

6) SHUTDOWN IMMEDIATE;

7) STARTUP;

JQuery create a form and add elements to it programmatically

Using Jquery

Rather than creating temp variables it can be written in a continuous flow pattern as follows:

$('</form>', { action: url, method: 'POST' }).append(
    $('<input>', {type: 'hidden', id: 'id_field_1', name: 'name_field_1', value: val_field_1}),
    $('<input>', {type: 'hidden', id: 'id_field_2', name: 'name_field_2', value: val_field_2}),
).appendTo('body').submit();

How to load json into my angular.js ng-model?

Here's a simple example of how to load JSON data into an Angular model.

I have a JSON 'GET' web service which returns a list of Customer details, from an online copy of Microsoft's Northwind SQL Server database.

http://www.iNorthwind.com/Service1.svc/getAllCustomers

It returns some JSON data which looks like this:

{ 
    "GetAllCustomersResult" : 
        [
            {
              "CompanyName": "Alfreds Futterkiste",
              "CustomerID": "ALFKI"
            },
            {
              "CompanyName": "Ana Trujillo Emparedados y helados",
              "CustomerID": "ANATR"
            },
            {
              "CompanyName": "Antonio Moreno Taquería",
              "CustomerID": "ANTON"
            }
        ]
    }

..and I want to populate a drop down list with this data, to look like this...

Angular screenshot

I want the text of each item to come from the "CompanyName" field, and the ID to come from the "CustomerID" fields.

How would I do it ?

My Angular controller would look like this:

function MikesAngularController($scope, $http) {

    $scope.listOfCustomers = null;

    $http.get('http://www.iNorthwind.com/Service1.svc/getAllCustomers')
         .success(function (data) {
             $scope.listOfCustomers = data.GetAllCustomersResult;
         })
         .error(function (data, status, headers, config) {
             //  Do some error handling here
         });
}

... which fills a "listOfCustomers" variable with this set of JSON data.

Then, in my HTML page, I'd use this:

<div ng-controller='MikesAngularController'>
    <span>Please select a customer:</span>
    <select ng-model="selectedCustomer" ng-options="customer.CustomerID as customer.CompanyName for customer in listOfCustomers" style="width:350px;"></select>
</div>

And that's it. We can now see a list of our JSON data on a web page, ready to be used.

The key to this is in the "ng-options" tag:

customer.CustomerID as customer.CompanyName for customer in listOfCustomers

It's a strange syntax to get your head around !

When the user selects an item in this list, the "$scope.selectedCustomer" variable will be set to the ID (the CustomerID field) of that Customer record.

The full script for this example can be found here:

JSON data with Angular

Mike

Is it possible to reference one CSS rule within another?

You can easily do so with SASS pre-processor by using @extend.

someDiv {
    @extend .opacity;
    @extend .radius;
}

Ohterwise, you could use JavaScript (jQuery) as well:

$('someDiv').addClass('opacity radius')

The easiest is of course to add multiple classes right in the HTML

<div class="opacity radius">

How does JPA orphanRemoval=true differ from the ON DELETE CASCADE DML clause

The equivalent JPA mapping for the DDL ON DELETE CASCADE is cascade=CascadeType.REMOVE. Orphan removal means that dependent entities are removed when the relationship to their "parent" entity is destroyed. For example if a child is removed from a @OneToMany relationship without explicitely removing it in the entity manager.

How to check if directory exists in %PATH%?

First I will point out a number of issues that make this problem difficult to solve perfectly. Then I will present the most bullet-proof solution I have been able to come up with.

For this discussion I will use lower case path to represent a single folder path in the file system, and upper case PATH to represent the PATH environment variable.

From a practical standpoint, most people want to know if PATH contains the logical equivalent of a given path, not whether PATH contains an exact string match of a given path. This can be problematic because:

  1. The trailing \ is optional in a path
    Most paths work equally well both with and without the trailing \. The path logically points to the same location either way. The PATH frequently has a mixture of paths both with and without the trailing \. This is probably the most common practical issue when searching a PATH for a match.

    • There is one exception: The relative path C: (meaning the current working directory of drive C) is very different than C:\ (meaning the root directory of drive C)

  2. Some paths have alternate short names
    Any path that does not meet the old 8.3 standard has an alternate short form that does meet the standard. This is another PATH issue that I have seen with some frequency, particularly in business settings.

  3. Windows accepts both / and \ as folder separators within a path.
    This is not seen very often, but a path can be specified using / instead of \ and it will function just fine within PATH (as well as in many other Windows contexts)

  4. Windows treats consecutive folder separators as one logical separator.
    C:\FOLDER\\ and C:\FOLDER\ are equivalent. This actually helps in many contexts when dealing with a path because a developer can generally append \ to a path without bothering to check if the trailing \ already exists. But this obviously can cause problems if trying to perform an exact string match.

    • Exceptions: Not only is C:, different than C:\, but C:\ (a valid path), is different than C:\\ (an invalid path).

  5. Windows trims trailing dots and spaces from file and directory names.
    "C:\test. " is equivalent to "C:\test".

  6. The current .\ and parent ..\ folder specifiers may appear within a path
    Unlikely to be seen in real life, but something like C:\.\parent\child\..\.\child\ is equivalent to C:\parent\child

  7. A path can optionally be enclosed within double quotes.
    A path is often enclosed in quotes to protect against special characters like <space> , ; ^ & =. Actually any number of quotes can appear before, within, and/or after the path. They are ignored by Windows except for the purpose of protecting against special characters. The quotes are never required within PATH unless a path contains a ;, but the quotes may be present never-the-less.

  8. A path may be fully qualified or relative.
    A fully qualified path points to exactly one specific location within the file system. A relative path location changes depending on the value of current working volumes and directories. There are three primary flavors of relative paths:

    • D: is relative to the current working directory of volume D:
    • \myPath is relative to the current working volume (could be C:, D: etc.)
    • myPath is relative to the current working volume and directory

    It is perfectly legal to include a relative path within PATH. This is very common in the Unix world because Unix does not search the current directory by default, so a Unix PATH will often contain .\. But Windows does search the current directory by default, so relative paths are rare in a Windows PATH.

So in order to reliably check if PATH already contains a path, we need a way to convert any given path into a canonical (standard) form. The ~s modifier used by FOR variable and argument expansion is a simple method that addresses issues 1 - 6, and partially addresses issue 7. The ~s modifier removes enclosing quotes, but preserves internal quotes. Issue 7 can be fully resolved by explicitly removing quotes from all paths prior to comparison. Note that if a path does not physically exist then the ~s modifier will not append the \ to the path, nor will it convert the path into a valid 8.3 format.

The problem with ~s is it converts relative paths into fully qualified paths. This is problematic for Issue 8 because a relative path should never match a fully qualified path. We can use FINDSTR regular expressions to classify a path as either fully qualified or relative. A normal fully qualified path must start with <letter>:<separator> but not <letter>:<separator><separator>, where <separator> is either \ or /. UNC paths are always fully qualified and must start with \\. When comparing fully qualified paths we use the ~s modifier. When comparing relative paths we use the raw strings. Finally, we never compare a fully qualified path to a relative path. This strategy provides a good practical solution for Issue 8. The only limitation is two logically equivalent relative paths could be treated as not matching, but this is a minor concern because relative paths are rare in a Windows PATH.

There are some additional issues that complicate this problem:

9) Normal expansion is not reliable when dealing with a PATH that contains special characters.
Special characters do not need to be quoted within PATH, but they could be. So a PATH like C:\THIS & THAT;"C:\& THE OTHER THING" is perfectly valid, but it cannot be expanded safely using simple expansion because both "%PATH%" and %PATH% will fail.

10) The path delimiter is also valid within a path name
A ; is used to delimit paths within PATH, but ; can also be a valid character within a path, in which case the path must be quoted. This causes a parsing issue.

jeb solved both issues 9 and 10 at 'Pretty print' windows %PATH% variable - how to split on ';' in CMD shell

So we can combine the ~s modifier and path classification techniques along with my variation of jeb's PATH parser to get this nearly bullet proof solution for checking if a given path already exists within PATH. The function can be included and called from within a batch file, or it can stand alone and be called as its own inPath.bat batch file. It looks like a lot of code, but over half of it is comments.

@echo off
:inPath pathVar
::
::  Tests if the path stored within variable pathVar exists within PATH.
::
::  The result is returned as the ERRORLEVEL:
::    0 if the pathVar path is found in PATH.
::    1 if the pathVar path is not found in PATH.
::    2 if pathVar is missing or undefined or if PATH is undefined.
::
::  If the pathVar path is fully qualified, then it is logically compared
::  to each fully qualified path within PATH. The path strings don't have
::  to match exactly, they just need to be logically equivalent.
::
::  If the pathVar path is relative, then it is strictly compared to each
::  relative path within PATH. Case differences and double quotes are
::  ignored, but otherwise the path strings must match exactly.
::
::------------------------------------------------------------------------
::
:: Error checking
if "%~1"=="" exit /b 2
if not defined %~1 exit /b 2
if not defined path exit /b 2
::
:: Prepare to safely parse PATH into individual paths
setlocal DisableDelayedExpansion
set "var=%path:"=""%"
set "var=%var:^=^^%"
set "var=%var:&=^&%"
set "var=%var:|=^|%"
set "var=%var:<=^<%"
set "var=%var:>=^>%"
set "var=%var:;=^;^;%"
set var=%var:""="%
set "var=%var:"=""Q%"
set "var=%var:;;="S"S%"
set "var=%var:^;^;=;%"
set "var=%var:""="%"
setlocal EnableDelayedExpansion
set "var=!var:"Q=!"
set "var=!var:"S"S=";"!"
::
:: Remove quotes from pathVar and abort if it becomes empty
set "new=!%~1:"=!"
if not defined new exit /b 2
::
:: Determine if pathVar is fully qualified
echo("!new!"|findstr /i /r /c:^"^^\"[a-zA-Z]:[\\/][^\\/]" ^
                           /c:^"^^\"[\\][\\]" >nul ^
  && set "abs=1" || set "abs=0"
::
:: For each path in PATH, check if path is fully qualified and then do
:: proper comparison with pathVar.
:: Exit with ERRORLEVEL 0 if a match is found.
:: Delayed expansion must be disabled when expanding FOR variables
:: just in case the value contains !
for %%A in ("!new!\") do for %%B in ("!var!") do (
  if "!!"=="" endlocal
  for %%C in ("%%~B\") do (
    echo(%%B|findstr /i /r /c:^"^^\"[a-zA-Z]:[\\/][^\\/]" ^
                           /c:^"^^\"[\\][\\]" >nul ^
      && (if %abs%==1 if /i "%%~sA"=="%%~sC" exit /b 0) ^
      || (if %abs%==0 if /i "%%~A"=="%%~C" exit /b 0)
  )
)
:: No match was found so exit with ERRORLEVEL 1
exit /b 1

The function can be used like so (assuming the batch file is named inPath.bat):

set test=c:\mypath
call inPath test && (echo found) || (echo not found)



Typically the reason for checking if a path exists within PATH is because you want to append the path if it isn't there. This is normally done simply by using something like path %path%;%newPath%. But Issue 9 demonstrates how this is not reliable.

Another issue is how to return the final PATH value across the ENDLOCAL barrier at the end of the function, especially if the function could be called with delayed expansion enabled or disabled. Any unescaped ! will corrupt the value if delayed expansion is enabled.

These problems are resolved using an amazing safe return technique that jeb invented here: http://www.dostips.com/forum/viewtopic.php?p=6930#p6930

@echo off
:addPath pathVar /B
::
::  Safely appends the path contained within variable pathVar to the end
::  of PATH if and only if the path does not already exist within PATH.
::
::  If the case insensitive /B option is specified, then the path is
::  inserted into the front (Beginning) of PATH instead.
::
::  If the pathVar path is fully qualified, then it is logically compared
::  to each fully qualified path within PATH. The path strings are
::  considered a match if they are logically equivalent.
::
::  If the pathVar path is relative, then it is strictly compared to each
::  relative path within PATH. Case differences and double quotes are
::  ignored, but otherwise the path strings must match exactly.
::
::  Before appending the pathVar path, all double quotes are stripped, and
::  then the path is enclosed in double quotes if and only if the path
::  contains at least one semicolon.
::
::  addPath aborts with ERRORLEVEL 2 if pathVar is missing or undefined
::  or if PATH is undefined.
::
::------------------------------------------------------------------------
::
:: Error checking
if "%~1"=="" exit /b 2
if not defined %~1 exit /b 2
if not defined path exit /b 2
::
:: Determine if function was called while delayed expansion was enabled
setlocal
set "NotDelayed=!"
::
:: Prepare to safely parse PATH into individual paths
setlocal DisableDelayedExpansion
set "var=%path:"=""%"
set "var=%var:^=^^%"
set "var=%var:&=^&%"
set "var=%var:|=^|%"
set "var=%var:<=^<%"
set "var=%var:>=^>%"
set "var=%var:;=^;^;%"
set var=%var:""="%
set "var=%var:"=""Q%"
set "var=%var:;;="S"S%"
set "var=%var:^;^;=;%"
set "var=%var:""="%"
setlocal EnableDelayedExpansion
set "var=!var:"Q=!"
set "var=!var:"S"S=";"!"
::
:: Remove quotes from pathVar and abort if it becomes empty
set "new=!%~1:"^=!"
if not defined new exit /b 2
::
:: Determine if pathVar is fully qualified
echo("!new!"|findstr /i /r /c:^"^^\"[a-zA-Z]:[\\/][^\\/]" ^
                           /c:^"^^\"[\\][\\]" >nul ^
  && set "abs=1" || set "abs=0"
::
:: For each path in PATH, check if path is fully qualified and then
:: do proper comparison with pathVar. Exit if a match is found.
:: Delayed expansion must be disabled when expanding FOR variables
:: just in case the value contains !
for %%A in ("!new!\") do for %%B in ("!var!") do (
  if "!!"=="" setlocal disableDelayedExpansion
  for %%C in ("%%~B\") do (
    echo(%%B|findstr /i /r /c:^"^^\"[a-zA-Z]:[\\/][^\\/]" ^
                           /c:^"^^\"[\\][\\]" >nul ^
      && (if %abs%==1 if /i "%%~sA"=="%%~sC" exit /b 0) ^
      || (if %abs%==0 if /i %%A==%%C exit /b 0)
  )
)
::
:: Build the modified PATH, enclosing the added path in quotes
:: only if it contains ;
setlocal enableDelayedExpansion
if "!new:;=!" neq "!new!" set new="!new!"
if /i "%~2"=="/B" (set "rtn=!new!;!path!") else set "rtn=!path!;!new!"
::
:: rtn now contains the modified PATH. We need to safely pass the
:: value accross the ENDLOCAL barrier
::
:: Make rtn safe for assignment using normal expansion by replacing
:: % and " with not yet defined FOR variables
set "rtn=!rtn:%%=%%A!"
set "rtn=!rtn:"=%%B!"
::
:: Escape ^ and ! if function was called while delayed expansion was enabled.
:: The trailing ! in the second assignment is critical and must not be removed.
if not defined NotDelayed set "rtn=!rtn:^=^^^^!"
if not defined NotDelayed set "rtn=%rtn:!=^^^!%" !
::
:: Pass the rtn value accross the ENDLOCAL barrier using FOR variables to
:: restore the % and " characters. Again the trailing ! is critical.
for /f "usebackq tokens=1,2" %%A in ('%%^ ^"') do (
  endlocal & endlocal & endlocal & endlocal & endlocal
  set "path=%rtn%" !
)
exit /b 0

Found a swap file by the name

Looks like you have an open git commit or git merge going on, and an editor is still open editing the commit message.

Two choices:

  1. Find the session and finish it (preferable).
  2. Delete the .swp file (if you're sure the other git session has gone away).

Clarification from comments:

  • The session is the editing session.
  • You can see what .swp is being used by entering the command :sw within the editing session, but generally it's a hidden file in the same directory as the file you are using, with a .swp file suffix (i.e. ~/myfile.txt would be ~/.myfile.txt.swp).

How to select rows that have current day's timestamp?

use DATE and CURDATE()

SELECT * FROM `table` WHERE DATE(`timestamp`) = CURDATE()

Warning! This query doesn't use an index efficiently. For the more efficient solution see the answer below

see the execution plan on the DEMO

How to send POST request?

If you really want to handle with HTTP using Python, I highly recommend Requests: HTTP for Humans. The POST quickstart adapted to your question is:

>>> import requests
>>> r = requests.post("http://bugs.python.org", data={'number': 12524, 'type': 'issue', 'action': 'show'})
>>> print(r.status_code, r.reason)
200 OK
>>> print(r.text[:300] + '...')

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>
Issue 12524: change httplib docs POST example - Python tracker

</title>
<link rel="shortcut i...
>>> 

How do I pause my shell script for a second before continuing?

On Mac OSX, sleep does not take minutes/etc, only seconds. So for two minutes,

sleep 120

Git commit in terminal opens VIM, but can't get back to terminal

not really the answer to the VIM problem but you could use the command line to also enter the commit message:

git commit -m "This is the first commit"

Under what circumstances can I call findViewById with an Options Menu / Action Bar item?

I am trying to obtain a handle on one of the views in the Action Bar

I will assume that you mean something established via android:actionLayout in your <item> element of your <menu> resource.

I have tried calling findViewById(R.id.menu_item)

To retrieve the View associated with your android:actionLayout, call findItem() on the Menu to retrieve the MenuItem, then call getActionView() on the MenuItem. This can be done any time after you have inflated the menu resource.

Regex to validate date format dd/mm/yyyy

import re
expression = "Nov 05 20:10:09 2020"
reg_ex = r'((Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ([0-2][0-9]|(3)[0-1]) (([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])) (\d{4}))'
assert re.fullmatch(reg_ex, expression), True

Expaination with respect to given Example

  • Nov = A group of possible months i.e. (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)
  • 05 = A group of valid days i.e. ([0-2][0-9]|(3)[0-1])
  • 20:10:09 = A group for getting valid Hours : ([0-1][0-9]|2[0-3]), Minutes : ([0-5][0-9]) and Seconds : ([0-5][0-9])
  • 2020 = A group for getting year i.e (\d{4}))

Attaching click to anchor tag in angular

I have encountered this issue in Angular 5 which still followed the link. The solution was to have the function return false in order to prevent the page being refreshed:

html

<a href="" (click)="openChangePasswordForm()">Change expired password</a>

ts

openChangePasswordForm(): boolean {
  console.log("openChangePasswordForm called!");
  return false;
}

URL Encode a string in jQuery for an AJAX request

try this one

var query = "{% url accounts.views.instasearch  %}?q=" + $('#tags').val().replace(/ /g, '+');

How do I find out what is hammering my SQL Server?

Run either of these a few second apart. You'll detect the high CPU connection. Or: stored CPU in a local variable, WAITFOR DELAY, compare stored and current CPU values

select * from master..sysprocesses
where status = 'runnable' --comment this out
order by CPU
desc

select * from master..sysprocesses
order by CPU
desc

May not be the most elegant but it'd effective and quick.

response.sendRedirect() from Servlet to JSP does not seem to work

Since you already have sent some data,

System.out.println("going to demo.jsp");

you won't be able to send a redirect.

Difference between dict.clear() and assigning {} in Python

If you have another variable also referring to the same dictionary, there is a big difference:

>>> d = {"stuff": "things"}
>>> d2 = d
>>> d = {}
>>> d2
{'stuff': 'things'}
>>> d = {"stuff": "things"}
>>> d2 = d
>>> d.clear()
>>> d2
{}

This is because assigning d = {} creates a new, empty dictionary and assigns it to the d variable. This leaves d2 pointing at the old dictionary with items still in it. However, d.clear() clears the same dictionary that d and d2 both point at.

Counting how many times a certain char appears in a string before any other char appears

You could use the Count method

var count = mystring.Count(x => x == '$')

How to draw a rounded Rectangle on HTML Canvas?

I needed to do the same thing and created a method to do it.

_x000D_
_x000D_
// Now you can just call
var ctx = document.getElementById("rounded-rect").getContext("2d");
// Draw using default border radius, 
// stroke it but no fill (function's default values)
roundRect(ctx, 5, 5, 50, 50);
// To change the color on the rectangle, just manipulate the context
ctx.strokeStyle = "rgb(255, 0, 0)";
ctx.fillStyle = "rgba(255, 255, 0, .5)";
roundRect(ctx, 100, 5, 100, 100, 20, true);
// Manipulate it again
ctx.strokeStyle = "#0f0";
ctx.fillStyle = "#ddd";
// Different radii for each corner, others default to 0
roundRect(ctx, 300, 5, 200, 100, {
  tl: 50,
  br: 25
}, true);

/**
 * Draws a rounded rectangle using the current state of the canvas.
 * If you omit the last three params, it will draw a rectangle
 * outline with a 5 pixel border radius
 * @param {CanvasRenderingContext2D} ctx
 * @param {Number} x The top left x coordinate
 * @param {Number} y The top left y coordinate
 * @param {Number} width The width of the rectangle
 * @param {Number} height The height of the rectangle
 * @param {Number} [radius = 5] The corner radius; It can also be an object 
 *                 to specify different radii for corners
 * @param {Number} [radius.tl = 0] Top left
 * @param {Number} [radius.tr = 0] Top right
 * @param {Number} [radius.br = 0] Bottom right
 * @param {Number} [radius.bl = 0] Bottom left
 * @param {Boolean} [fill = false] Whether to fill the rectangle.
 * @param {Boolean} [stroke = true] Whether to stroke the rectangle.
 */
function roundRect(ctx, x, y, width, height, radius, fill, stroke) {
  if (typeof stroke === 'undefined') {
    stroke = true;
  }
  if (typeof radius === 'undefined') {
    radius = 5;
  }
  if (typeof radius === 'number') {
    radius = {tl: radius, tr: radius, br: radius, bl: radius};
  } else {
    var defaultRadius = {tl: 0, tr: 0, br: 0, bl: 0};
    for (var side in defaultRadius) {
      radius[side] = radius[side] || defaultRadius[side];
    }
  }
  ctx.beginPath();
  ctx.moveTo(x + radius.tl, y);
  ctx.lineTo(x + width - radius.tr, y);
  ctx.quadraticCurveTo(x + width, y, x + width, y + radius.tr);
  ctx.lineTo(x + width, y + height - radius.br);
  ctx.quadraticCurveTo(x + width, y + height, x + width - radius.br, y + height);
  ctx.lineTo(x + radius.bl, y + height);
  ctx.quadraticCurveTo(x, y + height, x, y + height - radius.bl);
  ctx.lineTo(x, y + radius.tl);
  ctx.quadraticCurveTo(x, y, x + radius.tl, y);
  ctx.closePath();
  if (fill) {
    ctx.fill();
  }
  if (stroke) {
    ctx.stroke();
  }

}
_x000D_
<canvas id="rounded-rect" width="500" height="200">
  <!-- Insert fallback content here -->
</canvas>
_x000D_
_x000D_
_x000D_

How to Serialize a list in java?

List is just an interface. The question is: is your actual List implementation serializable? Speaking about the standard List implementations (ArrayList, LinkedList) from the Java run-time, most of them actually are already.

Bypass invalid SSL certificate errors when calling web services in .Net

Alternatively you can register a call back delegate which ignores the certification error:

...
ServicePointManager.ServerCertificateValidationCallback = MyCertHandler;
...

static bool MyCertHandler(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors error)
{
// Ignore errors
return true;
}

How to quickly clear a JavaScript Object?

ES5

ES5 solution can be:

// for enumerable and non-enumerable properties
Object.getOwnPropertyNames(obj).forEach(function (prop) {
  delete obj[prop];
});

ES6

And ES6 solution can be:

// for enumerable and non-enumerable properties
for (const prop of Object.getOwnPropertyNames(obj)) {
  delete obj[prop];
}

Performance

Regardless of the specs, the quickest solutions will generally be:

// for enumerable and non-enumerable of an object with proto chain
var props = Object.getOwnPropertyNames(obj);
for (var i = 0; i < props.length; i++) {
  delete obj[props[i]];
}

// for enumerable properties of shallow/plain object
for (var key in obj) {
  // this check can be safely omitted in modern JS engines
  // if (obj.hasOwnProperty(key))
    delete obj[key];
}

The reason why for..in should be performed only on shallow or plain object is that it traverses the properties that are prototypically inherited, not just own properties that can be deleted. In case it isn't known for sure that an object is plain and properties are enumerable, for with Object.getOwnPropertyNames is a better choice.

Adding a directory to PATH in Ubuntu

Actually I would advocate .profile if you need it to work from scripts, and in particular, scripts run by /bin/sh instead of Bash. If this is just for your own private interactive use, .bashrc is fine, though.

Chrome & Safari Error::Not allowed to load local resource: file:///D:/CSS/Style.css

It is today possible to configure Safari to access local files.

  • By default Safari doesn't allow access to local files.
  • To enable this option: First you need to enable the develop menu.
  • Click on the Develop menu Select Disable Local File Restrictions.

Source: http://ccm.net/faq/36342-safari-how-to-enable-local-file-access

Does Python have a string 'contains' substring method?

You can use the in operator:

if "blah" not in somestring: 
    continue

Finding the source code for built-in Python functions?

enter image description here

I had to dig a little to find the source of the following Built-in Functions as the search would yield thousands of results. (Good luck searching for any of those to find where it's source is)

Anyway, all those functions are defined in bltinmodule.c Functions start with builtin_{functionname}

Built-in Source: https://github.com/python/cpython/blob/master/Python/bltinmodule.c

For Built-in Types: https://github.com/python/cpython/tree/master/Objects

Excel 2007 - Compare 2 columns, find matching values

VLOOKUP deosnt work for String literals

How to update a record using sequelize for node?

You can use Model.update() method.

With async/await:

try{
  const result = await Project.update(
    { title: "Updated Title" }, //what going to be updated
    { where: { id: 1 }} // where clause
  )  
} catch (error) {
  // error handling
}

With .then().catch():

Project.update(
    { title: "Updated Title" }, //what going to be updated
    { where: { id: 1 }} // where clause
)
.then(result => {
  // code with result
})
.catch(error => {
  // error handling
})

Get login username in java

Below is a solution for WINDOWS ONLY

In cases where the application (like Tomcat) is started as a windows service, the System.getProperty("user.name") or System.getenv().get("USERNAME") return the user who started the service and not the current logged in user name.

Also in Java 9 the NTSystem etc classes will not be accessible

So workaround for windows: You can use wmic, so you have to run the below command

wmic ComputerSystem get UserName

If available, this will return output of the form:

UserName
{domain}\{logged-in-user-name}

Note: For windows you need to use cmd /c as a prefix, so below is a crude program as an example:

    Process exec = Runtime.getRuntime().exec("cmd /c wmic ComputerSystem get UserName".split(" "));
    System.out.println(exec.waitFor());
    try (BufferedReader bw = new BufferedReader(new InputStreamReader(exec.getInputStream()))) {
        System.out.println(bw.readLine() + "\n" + bw.readLine()+ "\n" + bw.readLine());
    }

substring of an entire column in pandas dataframe

I needed to convert a single column of strings of form nn.n% to float. I needed to remove the % from the element in each row. The attend data frame has two columns.

attend.iloc[:,1:2]=attend.iloc[:,1:2].applymap(lambda x: float(x[:-1]))

Its an extenstion to the original answer. In my case it takes a dataframe and applies a function to each value in a specific column. The function removes the last character and converts the remaining string to float.

How can I render inline JavaScript with Jade / Pug?

No use script tag only.

Solution with |:

script
  | if (10 == 10) {
  |   alert("working")
  | }

Or with a .:

script.
  if (10 == 10) {
    alert("working")
  }

What is the most efficient way of finding all the factors of a number in Python?

An alternative approach to agf's answer:

def factors(n):    
    result = set()
    for i in range(1, int(n ** 0.5) + 1):
        div, mod = divmod(n, i)
        if mod == 0:
            result |= {i, div}
    return result

How to create a list of objects?

Storing a list of object instances is very simple

class MyClass(object):
    def __init__(self, number):
        self.number = number

my_objects = []

for i in range(100):
    my_objects.append(MyClass(i))

# later

for obj in my_objects:
    print obj.number

Best way to convert string to bytes in Python 3?

The absolutely best way is neither of the 2, but the 3rd. The first parameter to encode defaults to 'utf-8' ever since Python 3.0. Thus the best way is

b = mystring.encode()

This will also be faster, because the default argument results not in the string "utf-8" in the C code, but NULL, which is much faster to check!

Here be some timings:

In [1]: %timeit -r 10 'abc'.encode('utf-8')
The slowest run took 38.07 times longer than the fastest. 
This could mean that an intermediate result is being cached.
10000000 loops, best of 10: 183 ns per loop

In [2]: %timeit -r 10 'abc'.encode()
The slowest run took 27.34 times longer than the fastest. 
This could mean that an intermediate result is being cached.
10000000 loops, best of 10: 137 ns per loop

Despite the warning the times were very stable after repeated runs - the deviation was just ~2 per cent.


Using encode() without an argument is not Python 2 compatible, as in Python 2 the default character encoding is ASCII.

>>> 'äöä'.encode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

How do I get row id of a row in sql server

There is a pseudocolumn called %%physloc%% that shows the physical address of the row.

See Equivalent of Oracle's RowID in SQL Server

Python "string_escape" vs "unicode_escape"

According to my interpretation of the implementation of unicode-escape and the unicode repr in the CPython 2.6.5 source, yes; the only difference between repr(unicode_string) and unicode_string.encode('unicode-escape') is the inclusion of wrapping quotes and escaping whichever quote was used.

They are both driven by the same function, unicodeescape_string. This function takes a parameter whose sole function is to toggle the addition of the wrapping quotes and escaping of that quote.

What does this expression language ${pageContext.request.contextPath} exactly do in JSP EL?

Include <%@ page isELIgnored="false"%> on top of your jsp page.

How to center a (background) image within a div?

#doit {
    background: url(url) no-repeat center;
}

Add days Oracle SQL

It's Simple.You can use

select (sysdate+2) as new_date from dual;

This will add two days from current date.

In javascript, how do you search an array for a substring match

I've created a simple to use library (ss-search) which is designed to handle objects, but could also work in your case:

search(windowArray.map(x => ({ key: x }), ["key"], "SEARCH_TEXT").map(x => x.key)

The advantage of using this search function is that it will normalize the text before executing the search to return more accurate results.

What is the best way to implement a "timer"?

By using System.Windows.Forms.Timer class you can achieve what you need.

System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();


t.Interval = 15000; // specify interval time as you want
t.Tick += new EventHandler(timer_Tick);
t.Start();

void timer_Tick(object sender, EventArgs e)
{
      //Call method
}

By using stop() method you can stop timer.

t.Stop();

How to call function on child component on parent events

Calling child component in parent

<component :is="my_component" ref="my_comp"></component>
<v-btn @click="$refs.my_comp.alertme"></v-btn>

in Child component

mycomp.vue

    methods:{     
    alertme(){
            alert("alert")
            }
    }

How to install a specific version of package using Composer?

Suppose you want to install Laravel Collective. It's currently at version 6.x but you want version 5.8. You can run the following command:

composer require "laravelcollective/html":"^5.8.0"

A good example is shown here in the documentation: https://laravelcollective.com/docs/5.5/html

Setting unique Constraint with fluent API?

As an addition to Yorro's answer, it can also be done by using attributes.

Sample for int type unique key combination:

[Index("IX_UniqueKeyInt", IsUnique = true, Order = 1)]
public int UniqueKeyIntPart1 { get; set; }

[Index("IX_UniqueKeyInt", IsUnique = true, Order = 2)]
public int UniqueKeyIntPart2 { get; set; }

If the data type is string, then MaxLength attribute must be added:

[Index("IX_UniqueKeyString", IsUnique = true, Order = 1)]
[MaxLength(50)]
public string UniqueKeyStringPart1 { get; set; }

[Index("IX_UniqueKeyString", IsUnique = true, Order = 2)]
[MaxLength(50)]
public string UniqueKeyStringPart2 { get; set; }

If there is a domain/storage model separation concern, using Metadatatype attribute/class can be an option: https://msdn.microsoft.com/en-us/library/ff664465%28v=pandp.50%29.aspx?f=255&MSPPError=-2147217396


A quick console app example:

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;

namespace EFIndexTest
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var context = new AppDbContext())
            {
                var newUser = new User { UniqueKeyIntPart1 = 1, UniqueKeyIntPart2 = 1, UniqueKeyStringPart1 = "A", UniqueKeyStringPart2 = "A" };
                context.UserSet.Add(newUser);
                context.SaveChanges();
            }
        }
    }

    [MetadataType(typeof(UserMetadata))]
    public class User
    {
        public int Id { get; set; }
        public int UniqueKeyIntPart1 { get; set; }
        public int UniqueKeyIntPart2 { get; set; }
        public string UniqueKeyStringPart1 { get; set; }
        public string UniqueKeyStringPart2 { get; set; }
    }

    public class UserMetadata
    {
        [Index("IX_UniqueKeyInt", IsUnique = true, Order = 1)]
        public int UniqueKeyIntPart1 { get; set; }

        [Index("IX_UniqueKeyInt", IsUnique = true, Order = 2)]
        public int UniqueKeyIntPart2 { get; set; }

        [Index("IX_UniqueKeyString", IsUnique = true, Order = 1)]
        [MaxLength(50)]
        public string UniqueKeyStringPart1 { get; set; }

        [Index("IX_UniqueKeyString", IsUnique = true, Order = 2)]
        [MaxLength(50)]
        public string UniqueKeyStringPart2 { get; set; }
    }

    public class AppDbContext : DbContext
    {
        public virtual DbSet<User> UserSet { get; set; }
    }
}

Is there a command line utility for rendering GitHub flavored Markdown?

Based on Jim Lim's answer, I installed the GitHub Markdown gem. That included a script called gfm that takes a filename on the command line and writes the equivalent HTML to standard output. I modified that slightly to save the file to disk and then to open the standard browser with launchy:

#!/usr/bin/env ruby

HELP = <<-help
  Usage: gfm [--readme | --plaintext] [<file>]
  Convert a GitHub-Flavored Markdown file to HTML and write to standard output.
  With no <file> or when <file> is '-', read Markdown source text from standard input.
  With `--readme`, the files are parsed like README.md files in GitHub.com. By default,
  the files are parsed with all the GFM extensions.
help

if ARGV.include?('--help')
  puts HELP
  exit 0
end

root = File.expand_path('../../', __FILE__)
$:.unshift File.expand_path('lib', root)

require 'github/markdown'
require 'tempfile'
require 'launchy'

mode = :gfm
mode = :markdown if ARGV.delete('--readme')
mode = :plaintext if ARGV.delete('--plaintext')

outputFilePath = File.join(Dir.tmpdir, File.basename(ARGF.path))  + ".html"

File.open(outputFilePath, "w") do |outputFile |
    outputFile.write(GitHub::Markdown.to_html(ARGF.read, mode))
end

outputFileUri = 'file:///' + outputFilePath

Launchy.open(outputFileUri)

DOUBLE vs DECIMAL in MySQL

Actually it's quite different. DOUBLE causes rounding issues. And if you do something like 0.1 + 0.2 it gives you something like 0.30000000000000004. I personally would not trust financial data that uses floating point math. The impact may be small, but who knows. I would rather have what I know is reliable data than data that were approximated, especially when you are dealing with money values.

Hide header in stack navigator React navigation

UPDATE as of version 5

As of version 5 it is the option headerShown in screenOptions

Example of usage:

<Stack.Navigator
  screenOptions={{
    headerShown: false
  }}
>
  <Stack.Screen name="route-name" component={ScreenComponent} />
</Stack.Navigator>

If you want only to hide the header on 1 screen you can do this by setting the screenOptions on the screen component see below for example:

<Stack.Screen options={{headerShown: false}} name="route-name" component={ScreenComponent} />

See also the blog about version 5

UPDATE
As of version 2.0.0-alpha.36 (2019-11-07),
there is a new navigationOption: headershown

      navigationOptions: {
        headerShown: false,
      }

https://reactnavigation.org/docs/stack-navigator#headershown

https://github.com/react-navigation/react-navigation/commit/ba6b6ae025de2d586229fa8b09b9dd5732af94bd

Old answer

I use this to hide the stack bar (notice this is the value of the second param):

{
    headerMode: 'none',
    navigationOptions: {
        headerVisible: false,
    }
}

When you use the this method it will be hidden on all screens.

In your case it will look like this:

const MainNavigation = StackNavigator({
  otp: { screen: OTPlogin },
  otpverify: { screen: OTPverification },
  userVerified: {
    screen: TabNavigator({
    List: { screen: List },
    Settings: { screen: Settings }
   }),
 }
},
{
  headerMode: 'none',
  navigationOptions: {
    headerVisible: false,
  }
 }
);

Force div element to stay in same place, when page is scrolled

Change position:absolute to position:fixed;.

Example can be found in this jsFiddle.

join on multiple columns

The other queries are all going base on any ONE of the conditions qualifying and it will return a record... if you want to make sure the BOTH columns of table A are matched, you'll have to do something like...

select 
      tA.Col1,
      tA.Col2,
      tB.Val
   from
      TableA tA
         join TableB tB
            on  ( tA.Col1 = tB.Col1 OR tA.Col1 = tB.Col2 )
            AND ( tA.Col2 = tB.Col1 OR tA.Col2 = tB.Col2 )

C pointers and arrays: [Warning] assignment makes pointer from integer without a cast

What are you doing: (I am using bytes instead of in for better reading)

You start with int *ap and so on, so your (your computers) memory looks like this:

-------------- memory used by some one else --------
000: ?
001: ?
...
098: ?
099: ?
-------------- your memory  --------
100: something          <- here is *ap
101: 41                 <- here starts a[] 
102: 42
103: 43
104: 44
105: 45
106: something          <- here waits x

lets take a look waht happens when (print short cut for ...print("$d", ...)

print a[0]  -> 41   //no surprise
print a     -> 101  // because a points to the start of the array
print *a    -> 41   // again the first element of array
print a+1   -> guess? 102
print *(a+1)    -> whats behind 102? 42 (we all love this number)

and so on, so a[0] is the same as *a, a[1] = *(a+1), ....

a[n] just reads easier.

now, what happens at line 9?

ap=a[4] // we know a[4]=*(a+4) somehow *105 ==>  45 
// warning! converting int to pointer!
-------------- your memory  --------
100: 45         <- here is *ap now 45

x = *ap;   // wow ap is 45 -> where is 45 pointing to?
-------------- memory used by some one else --------
bang!      // dont touch neighbours garden

So the "warning" is not just a warning it's a severe error.

How to delete row based on cell value

You can loop through each the cells in your range and use the InStr function to check if a cell contains a string, in your case; a hyphen.

Sub DeleteRowsWithHyphen()

    Dim rng As Range

    For Each rng In Range("A2:A10") 'Range of values to loop through

        If InStr(1, rng.Value, "-") > 0 Then 'InStr returns an integer of the position, if above 0 - It contains the string
            rng.Delete
        End If

    Next rng

End Sub

SQL: Alias Column Name for Use in CASE Statement

I use CTEs to help compose complicated SQL queries but not all RDBMS' support them. You can think of them as query scope views. Here is an example in t-sql on SQL server.

With localView1 as (
 select c1,
        c2,
        c3,
        c4,
        ((c2-c4)*(3))+c1 as "complex"
   from realTable1) 
   , localView2 as (
 select case complex WHEN 0 THEN 'Empty' ELSE 'Not Empty' end as formula1,
        complex * complex as formula2    
   from localView1)
select *
from localView2

Monitor the Graphics card usage

From Unix.SE: A simple command-line utility called gpustat now exists: https://github.com/wookayin/gpustat.

It is free software (MIT license) and is packaged in pypi. It is a wrapper of nvidia-smi.

How do I set a textbox's text to bold at run time?

You could use Extension method to switch between Regular Style and Bold Style as below:

static class Helper
    {
        public static void SwtichToBoldRegular(this TextBox c)
        {
            if (c.Font.Style!= FontStyle.Bold)
                c.Font = new Font(c.Font, FontStyle.Bold);
            else
                c.Font = new Font(c.Font, FontStyle.Regular);
        }
    }

And usage:

textBox1.SwtichToBoldRegular();

CentOS: Enabling GD Support in PHP Installation

Put the command

yum install php-gd

and restart the server (httpd, nginx, etc)

service httpd restart

How to increase the Java stack size?

The only way to control the size of stack within process is start a new Thread. But you can also control by creating a self-calling sub Java process with the -Xss parameter.

public class TT {
    private static int level = 0;

    public static long fact(int n) {
        level++;
        return n < 2 ? n : n * fact(n - 1);
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(null, null, "TT", 1000000) {
            @Override
            public void run() {
                try {
                    level = 0;
                    System.out.println(fact(1 << 15));
                } catch (StackOverflowError e) {
                    System.err.println("true recursion level was " + level);
                    System.err.println("reported recursion level was "
                            + e.getStackTrace().length);
                }
            }

        };
        t.start();
        t.join();
        try {
            level = 0;
            System.out.println(fact(1 << 15));
        } catch (StackOverflowError e) {
            System.err.println("true recursion level was " + level);
            System.err.println("reported recursion level was "
                    + e.getStackTrace().length);
        }
    }

}