Programs & Examples On #Null

Null means *nothing* or *unknown*, depending on context.

Null vs. False vs. 0 in PHP

Null is nothing, False is a bit, and 0 is (probably) 32 bits.

Not a PHP expert, but in some of the more modern languages those aren't interchangeable. I kind of miss having 0 and false be interchangeable, but with boolean being an actual type you can have methods and objects associated with it so that's just a tradeoff. Null is null though, the absence of anything essentially.

Return zero if no record is found

You can also try: (I tried this and it worked for me)

SELECT ISNULL((SELECT SUM(columnA) FROM my_table WHERE columnB = 1),0)) INTO res;

Checking if an object is null in C#

Here are some extensions I use:

/// <summary>
/// Extensions to the object class
/// </summary>
public static class ObjectExtensions
{
    /// <summary>
    /// True if the object is null, else false
    /// </summary>
    public static bool IsNull(this object input) => input is null;

    /// <summary>
    /// False if the object is null, else true
    /// </summary>
    public static bool NotNull(this object input) => !IsNull(input);
}

How to remove all the null elements inside a generic list in one go?

There is another simple and elegant option:

parameters.OfType<EmailParameterClass>();

This will remove all elements that are not of type EmailParameterClass which will obviously filter out any elements of type null.

Here's a test:

class Test { }
class Program
{
    static void Main(string[] args)
    {
        var list = new List<Test>();
        list.Add(null);
        Console.WriteLine(list.OfType<Test>().Count());// 0
        list.Add(new Test());
        Console.WriteLine(list.OfType<Test>().Count());// 1
        Test test = null;
        list.Add(test);
        Console.WriteLine(list.OfType<Test>().Count());// 1
        Console.ReadKey();
    }
}

How to check a Long for null in java

As mentioned already primitives can not be set to the Object type null.

What I do in such cases is just to use -1 or Long.MIN_VALUE.

DateTime "null" value

I always set the time to DateTime.MinValue. This way I do not get any NullErrorException and I can compare it to a date that I know isn't set.

SQL QUERY replace NULL value in a row with a value from the previous known value

I know it is a very old forum, but I came across this while troubleshooting my problem :) just realised that the other guys have given bit complex solution to the above problem. Please see my solution below:

DECLARE @A TABLE(ID INT, Val INT)

INSERT INTO @A(ID,Val) SELECT 1, 3
INSERT INTO @A(ID,Val) SELECT 2, NULL
INSERT INTO @A(ID,Val) SELECT 3, 5
INSERT INTO @A(ID,Val) SELECT 4, NULL
INSERT INTO @A(ID,Val) SELECT 5, NULL
INSERT INTO @A(ID,Val) SELECT 6, 2

UPDATE D
    SET D.VAL = E.VAL
    FROM (SELECT A.ID C_ID, MAX(B.ID) P_ID
          FROM  @A AS A
           JOIN @A AS B ON A.ID > B.ID
          WHERE A.Val IS NULL
            AND B.Val IS NOT NULL
          GROUP BY A.ID) AS C
    JOIN @A AS D ON C.C_ID = D.ID
    JOIN @A AS E ON C.P_ID = E.ID

SELECT * FROM @A

Hope this may help someone:)

Method call if not null in C#

I have made this generic extension that I use.

public static class ObjectExtensions {
    public static void With<T>(this T value, Action<T> todo) {
        if (value != null) todo(value);
    }
}

Then I use it like below.

string myString = null;
myString.With((value) => Console.WriteLine(value)); // writes nothing
myString = "my value";
myString.With((value) => Console.WriteLine(value)); // Writes `my value`

Java null check why use == instead of .equals()

You code breaks Demeter's law. That's why it's better to refactor the design itself. As a workaround, you can use Optional

   obj = Optional.ofNullable(object1)
    .map(o -> o.getIdObject11())
    .map(o -> o.getIdObject111())
    .map(o -> o.getDescription())
    .orElse("")

above is to check to hierarchy of a object so simply use

Optional.ofNullable(object1) 

if you have only one object to check

Hope this helps !!!!

How to I say Is Not Null in VBA

you can do like follows. Remember, IsNull is a function which returns TRUE if the parameter passed to it is null, and false otherwise.

Not IsNull(Fields!W_O_Count.Value)

how to check if a datareader is null or empty

I haven't used DataReaders for 3+ years, so I wanted to confirm my memory and found this. Anyway, for anyone who happens upon this post like I did and wants a method to test IsDBNull using the column name instead of ordinal number, and you are using VS 2008+ (& .NET 3.5 I think), you can write an extension method so that you can pass the column name in:

public static class DataReaderExtensions
{
    public static bool IsDBNull( this IDataReader dataReader, string columnName )
    {
        return dataReader[columnName] == DBNull.Value;
    }
}

Kevin

getActivity() returns null in Fragment function

Do as follows. I think it will be helpful to you.

private boolean isVisibleToUser = false;
private boolean isExecutedOnce = false;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View root = inflater.inflate(R.layout.fragment_my, container, false);
    if (isVisibleToUser && !isExecutedOnce) {
        executeWithActivity(getActivity());
    }
    return root;
}

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    this.isVisibleToUser = isVisibleToUser;
    if (isVisibleToUser && getActivity()!=null) {
        isExecutedOnce =true;
        executeWithActivity(getActivity());
    }
}


private void executeWithActivity(Activity activity){
    //Do what you have to do when page is loaded with activity

}

What is the `zero` value for time.Time in Go?

The zero value for time.Time is 0001-01-01 00:00:00 +0000 UTC See http://play.golang.org/p/vTidOlmb9P

php is null or empty?

No it's not a bug. Have a look at the Loose comparisons with == table (second table), which shows the result of comparing each value in the first column with the values in the other columns:

    TRUE    FALSE   1       0       -1      "1"     "0"     "-1"    NULL    array() "php"   ""

    [...]    

""  FALSE   TRUE    FALSE   TRUE    FALSE   FALSE   FALSE   FALSE   TRUE    FALSE   FALSE   TRUE

There you can see that an empty string "" compared with false, 0, NULL or "" will yield true.

You might want to use is_null [docs] instead, or strict comparison (third table).

Nullable types: better way to check for null or zero in c#

I agree with using the ?? operator.

If you're dealing with strings use if(String.IsNullOrEmpty(myStr))

How to do ToString for a possibly null object?

I had the same problem and solved it by simply casting the object to string. This works for null objects too because strings can be nulls. Unless you absolutely don't want to have a null string, this should work just fine:

string myStr = (string)myObj; // string in a object disguise or a null

Why can't I check if a 'DateTime' is 'Nothing'?

DateTime is a value type, which means it always has some value.

It's like an integer - it can be 0, or 1, or less than zero, but it can never be "nothing".

If you want a DateTime that can take the value Nothing, use a Nullable DateTime.

How to set null value to int in c#?

Use Null.NullInteger ex: private int _ReservationID = Null.NullInteger;

null vs empty string in Oracle

This is because Oracle internally changes empty string to NULL values. Oracle simply won't let insert an empty string.

On the other hand, SQL Server would let you do what you are trying to achieve.

There are 2 workarounds here:

  1. Use another column that states whether the 'description' field is valid or not
  2. Use some dummy value for the 'description' field where you want it to store empty string. (i.e. set the field to be 'stackoverflowrocks' assuming your real data will never encounter such a description value)

Both are, of course, stupid workarounds :)

How to filter empty or NULL names in a QuerySet?

this is another simple way to do it .

Name.objects.exclude(alias=None)

When is null or undefined used in JavaScript?

I find that some of these answers are vague and complicated, I find the best way to figure out these things for sure is to just open up the console and test it yourself.

var x;

x == null            // true
x == undefined       // true
x === null           // false
x === undefined      // true

var y = null;

y == null            // true
y == undefined       // true
y === null           // true
y === undefined      // false

typeof x             // 'undefined'
typeof y             // 'object'

var z = {abc: null};

z.abc == null        // true
z.abc == undefined   // true
z.abc === null       // true
z.abc === undefined  // false

z.xyz == null        // true
z.xyz == undefined   // true
z.xyz === null       // false
z.xyz === undefined  // true

null = 1;            // throws error: invalid left hand assignment
undefined = 1;       // works fine: this can cause some problems

So this is definitely one of the more subtle nuances of JavaScript. As you can see, you can override the value of undefined, making it somewhat unreliable compared to null. Using the == operator, you can reliably use null and undefined interchangeably as far as I can tell. However, because of the advantage that null cannot be redefined, I might would use it when using ==.

For example, variable != null will ALWAYS return false if variable is equal to either null or undefined, whereas variable != undefined will return false if variable is equal to either null or undefined UNLESS undefined is reassigned beforehand.

You can reliably use the === operator to differentiate between undefined and null, if you need to make sure that a value is actually undefined (rather than null).

According to the ECMAScript 5 spec:

  • Both Null and Undefined are two of the six built in types.

4.3.9 undefined value

primitive value used when a variable has not been assigned a value

4.3.11 null value

primitive value that represents the intentional absence of any object value

Null check in VB

Change your Ands to AndAlsos

A standard And will test both expressions. If comp.Container is Nothing, then the second expression will raise a NullReferenceException because you're accessing a property on a null object.

AndAlso will short-circuit the logical evaluation. If comp.Container is Nothing, then the 2nd expression will not be evaluated.

how do you insert null values into sql server

INSERT INTO atable (x,y,z) VALUES ( NULL,NULL,NULL)

How to set enum to null

If this is C#, it won't work: enums are value types, and can't be null.

The normal options are to add a None member:

public enum Color
{
  None,
  Red,
  Green,
  Yellow
}

Color color = Color.None;

...or to use Nullable:

Color? color = null;

Error checking for NULL in VBScript

From your code, it looks like provider is a variant or some other variable, and not an object.

Is Nothing is for objects only, yet later you say it's a value that should either be NULL or NOT NULL, which would be handled by IsNull.

Try using:

If Not IsNull(provider) Then 
    url = url & "&provider=" & provider 
End if

Alternately, if that doesn't work, try:

If provider <> "" Then 
    url = url & "&provider=" & provider 
End if

Select rows which are not present in other table

There are basically 4 techniques for this task, all of them standard SQL.

NOT EXISTS

Often fastest in Postgres.

SELECT ip 
FROM   login_log l 
WHERE  NOT EXISTS (
   SELECT  -- SELECT list mostly irrelevant; can just be empty in Postgres
   FROM   ip_location
   WHERE  ip = l.ip
   );

Also consider:

LEFT JOIN / IS NULL

Sometimes this is fastest. Often shortest. Often results in the same query plan as NOT EXISTS.

SELECT l.ip 
FROM   login_log l 
LEFT   JOIN ip_location i USING (ip)  -- short for: ON i.ip = l.ip
WHERE  i.ip IS NULL;

EXCEPT

Short. Not as easily integrated in more complex queries.

SELECT ip 
FROM   login_log

EXCEPT ALL  -- "ALL" keeps duplicates and makes it faster
SELECT ip
FROM   ip_location;

Note that (per documentation):

duplicates are eliminated unless EXCEPT ALL is used.

Typically, you'll want the ALL keyword. If you don't care, still use it because it makes the query faster.

NOT IN

Only good without NULL values or if you know to handle NULL properly. I would not use it for this purpose. Also, performance can deteriorate with bigger tables.

SELECT ip 
FROM   login_log
WHERE  ip NOT IN (
   SELECT DISTINCT ip  -- DISTINCT is optional
   FROM   ip_location
   );

NOT IN carries a "trap" for NULL values on either side:

Similar question on dba.SE targeted at MySQL:

How to simplify a null-safe compareTo() implementation?

You can extract method:

public int cmp(String txt, String otherTxt)
{
    if ( txt == null )
        return otjerTxt == null ? 0 : 1;

    if ( otherTxt == null )
          return 1;

    return txt.compareToIgnoreCase(otherTxt);
}

public int compareTo(Metadata other) {
   int result = cmp( name, other.name); 
   if ( result != 0 )  return result;
   return cmp( value, other.value); 

}

SQL query, if value is null then return 1

SELECT orderhed.ordernum, orderhed.orderdate, currrate.currencycode,  

case(currrate.currentrate) when null then 1 else currrate.currentrate end

FROM orderhed LEFT OUTER JOIN currrate ON orderhed.company = currrate.company AND orderhed.orderdate = currrate.effectivedate  

Undefined or null for AngularJS

You can always add it exactly for your application

angular.isUndefinedOrNull = function(val) {
    return angular.isUndefined(val) || val === null 
}

IllegalArgumentException or NullPointerException for a null parameter?

If it's a "setter", or somewhere I'm getting a member to use later, I tend to use IllegalArgumentException.

If it's something I'm going to use (dereference) right now in the method, I throw a NullPointerException proactively. I like this better than letting the runtime do it, because I can provide a helpful message (seems like the runtime could do this too, but that's a rant for another day).

If I'm overriding a method, I use whatever the overridden method uses.

Check if a string is null or empty in XSLT

test="categoryName != ''"

Edit: This covers the most likely interpretation, in my opinion, of "[not] null or empty" as inferred from the question, including it's pseudo-code and my own early experience with XSLT. I.e., "What is the equivalent of the following Java?":

!(categoryName == null || categoryName.equals(""))

For more details e.g., distinctly identifying null vs. empty, see johnvey's answer below and/or the XSLT 'fiddle' I've adapted from that answer, which includes the option in Michael Kay's comment as well as the sixth possible interpretation.

How to check if a double is null?

I believe Double.NaN might be able to cover this. That is the only 'null' value double contains.

Check if a parameter is null or empty in a stored procedure

If you want a "Null, empty or white space" check, you can avoid unnecessary string manipulation with LTRIM and RTRIM like this.

IF COALESCE(PATINDEX('%[^ ]%', @parameter), 0) > 0
    RAISERROR ...

where to place CASE WHEN column IS NULL in this query

Thanks for all your help! @Svetoslav Tsolov had it very close, but I was still getting an error, until I figured out the closing parenthesis was in the wrong place. Here's the final query that works:

SELECT dbo.AdminID.CountryID, dbo.AdminID.CountryName, dbo.AdminID.RegionID, 
dbo.AdminID.[Region name], dbo.AdminID.DistrictID, dbo.AdminID.DistrictName,
dbo.AdminID.ADMIN3_ID, dbo.AdminID.ADMIN3,
(CASE WHEN dbo.EU_Admin3.EUID IS NULL THEN dbo.EU_Admin2.EUID ELSE dbo.EU_Admin3.EUID END) AS EUID
FROM dbo.AdminID 

LEFT OUTER JOIN dbo.EU_Admin2
ON dbo.AdminID.DistrictID = dbo.EU_Admin2.DistrictID

LEFT OUTER JOIN dbo.EU_Admin3
ON dbo.AdminID.ADMIN3_ID = dbo.EU_Admin3.ADMIN3_ID

return, return None, and no return at all?

In terms of functionality these are all the same, the difference between them is in code readability and style (which is important to consider)

Best way to check if column returns a null value (from database to .net application)

Use DBNull.Value.Equals on the object without converting it to a string.

Here's an example:

   if (! DBNull.Value.Equals(row[fieldName])) 
   {
      //not null
   }
   else
   {
      //null
   }

SQL is null and = null

First is correct way of checking whether a field value is null while later won't work the way you expect it to because null is special value which does not equal anything, so you can't use equality comparison using = for it.

So when you need to check if a field value is null or not, use:

where x is null

instead of:

where x = null

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

Note that the "if ($str)" and "IsNullOrEmpty" tests don't work comparably in all instances: an assignment of $str=0 produces false for both, and depending on intended program semantics, this could yield a surprise.

Is it possible in Java to check if objects fields are null and then add default value to all those attributes?

Non-reflective solution for Java 8, without using a series of if's, would be to stream all fields and check for nullness:

return Stream.of(id, name).allMatch(Objects::isNull);

This remains quite easy to maintain while avoiding the reflection hammer. This will return true for null attributes.

Avoiding NullPointerException in Java

Null object pattern can be used as a solution for this problem. For that, the class of the someObject should be modified.

public abstract class SomeObject {
   public abstract boolean isNil();
}

public class NullObject extends SomeObject {
   @Override
   public boolean isNil() {
      return true;
   }
}
public class RealObject extends SomeObject {
   @Override
   public boolean isNil() {
      return false;
   }
}

Now istead of checking,

 if (someobject != null) {
    someobject.doCalc();
}

We can use,

if (!someObject.isNil()) {
   someobject.doCalc();
}

Reference : https://www.tutorialspoint.com/design_pattern/null_object_pattern.htm

How to use NULL or empty string in SQL

my best solution :

 WHERE  
 COALESCE(char_length(fieldValue), 0) = 0

COALESCE returns the first non-null expr in the expression list().

if the fieldValue is null or empty string then: we will return the second element then 0.

so 0 is equal to 0 then this fieldValue is a null or empty string.

in python for exemple:

def coalesce(fieldValue):
    if fieldValue in (null,''):
        return 0

good luck

What is the difference between NULL, '\0' and 0?

What is the difference between NULL, ‘\0’ and 0

"null character (NUL)" is easiest to rule out. '\0' is a character literal. In C, it is implemented as int, so, it's the same as 0, which is of INT_TYPE_SIZE. In C++, character literal is implemented as char, which is 1 byte. This is normally different from NULL or 0.

Next, NULL is a pointer value that specifies that a variable does not point to any address space. Set aside the fact that it is usually implemented as zeros, it must be able to express the full address space of the architecture. Thus, on a 32-bit architecture NULL (likely) is 4-byte and on 64-bit architecture 8-byte. This is up to the implementation of C.

Finally, the literal 0 is of type int, which is of size INT_TYPE_SIZE. The default value of INT_TYPE_SIZE could be different depending on architecture.

Apple wrote:

The 64-bit data model used by Mac OS X is known as "LP64". This is the common data model used by other 64-bit UNIX systems from Sun and SGI as well as 64-bit Linux. The LP64 data model defines the primitive types as follows:

  • ints are 32-bit
  • longs are 64-bit
  • long-longs are also 64-bit
  • pointers are 64-bit

Wikipedia 64-bit:

Microsoft's VC++ compiler uses the LLP64 model.

64-bit data models
Data model short int long  long long pointers Sample operating systems
LLP64      16    32  32    64        64       Microsoft Win64 (X64/IA64)
LP64       16    32  64    64        64       Most Unix and Unix-like systems (Solaris, Linux, etc.)
ILP64      16    64  64    64        64       HAL
SILP64     64    64  64    64        64       ?

Edit: Added more on the character literal.

#include <stdio.h>

int main(void) {
    printf("%d", sizeof('\0'));
    return 0;
}

The above code returns 4 on gcc and 1 on g++.

Hibernate: How to set NULL query-parameter value with HQL?

this seems to work as wel ->

@Override
public List<SomeObject> findAllForThisSpecificThing(String thing) {
    final Query query = entityManager.createQuery(
            "from " + getDomain().getSimpleName() + " t  where t.thing = " + ((thing == null) ? " null" : " :thing"));
    if (thing != null) {
        query.setParameter("thing", thing);
    }
    return query.getResultList();
}

Btw, I'm pretty new at this, so if for any reason this isn't a good idea, let me know. Thanks.

Why use Optional.of over Optional.ofNullable?

Optional should mainly be used for results of Services anyway. In the service you know what you have at hand and return Optional.of(someValue) if you have a result and return Optional.empty() if you don't. In this case, someValue should never be null and still, you return an Optional.

How to store NULL values in datetime fields in MySQL?

It depends on how you declare your table. NULL would not be allowed in:

create table MyTable (col1 datetime NOT NULL);

But it would be allowed in:

create table MyTable (col1 datetime NULL);

The second is the default, so someone must've actively decided that the column should not be nullable.

Best way to check if a character array is empty

The second one is fastest. Using strlen will be close if the string is indeed empty, but strlen will always iterate through every character of the string, so if it is not empty, it will do much more work than you need it to.

As James mentioned, the third option wipes the string out before checking, so the check will always succeed but it will be meaningless.

What is null in Java?

Null in Java(tm)

In C and C++, "NULL" is a constant defined in a header file, with a value like:

    0

or:

    0L

or:

    ((void*)0)

depending on the compiler and memory model options. NULL is not, strictly speaking, part of C/C++ itself.

In Java(tm), "null" is not a keyword, but a special literal of the null type. It can be cast to any reference type, but not to any primitive type such as int or boolean. The null literal doesn't necessarily have value zero. And it is impossible to cast to the null type or declare a variable of this type.

Checking for a null int value from a Java ResultSet

For convenience, you can create a wrapper class around ResultSet that returns null values when ResultSet ordinarily would not.

public final class ResultSetWrapper {

    private final ResultSet rs;

    public ResultSetWrapper(ResultSet rs) {
        this.rs = rs;
    }

    public ResultSet getResultSet() {
        return rs;
    }

    public Boolean getBoolean(String label) throws SQLException {
        final boolean b = rs.getBoolean(label);
        if (rs.wasNull()) {
            return null;
        }
        return b;
    }

    public Byte getByte(String label) throws SQLException {
        final byte b = rs.getByte(label);
        if (rs.wasNull()) {
            return null;
        }
        return b;
    }

    // ...

}

How to tell if a string is not defined in a Bash shell script

call set without any arguments.. it outputs all the vars defined..
the last ones on the list would be the ones defined in your script..
so you could pipe its output to something that could figure out what things are defined and whats not

Check if object exists in JavaScript

If that's a global object, you can use if (!window.maybeObject)

How to check for empty value in Javascript?

Comment as an answer:

if (timetime[0].value)

This works because any variable in JS can be evaluated as a boolean, so this will generally catch things that are empty, null, or undefined.

Using Thymeleaf when the value is null

Also worth to look at documentation for #objects build-in helper: https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#objects

There is useful: ${#objects.nullSafe(obj, default)}

SQL Inner Join On Null Values

Are you committed to using the Inner join syntax?

If not you could use this alternative syntax:

SELECT * 
FROM Y,X
WHERE (X.QID=Y.QID) or (X.QUID is null and Y.QUID is null)

How to replace blank (null ) values with 0 for all records?

I just had this same problem, and I ended up finding the simplest solution which works for my needs. In the table properties, I set the default value to 0 for the fields that I don't want to show nulls. Super easy.

Do you use NULL or 0 (zero) for pointers in C++?

There are a few arguments (one of which is relatively recent) which I believe contradict Bjarne's position on this.

  1. Documentation of intent

    Using NULL allows for searches on its use and it also highlights that the developer wanted to use a NULL pointer, irrespective of whether it is being interpreted by the compiler as NULL or not.

  2. Overload of pointer and 'int' is relatively rare

    The example that everybody quotes is:

     void foo(int*);
     void foo (int);
    
     void bar() {
       foo (NULL);  // Calls 'foo(int)'
     }
    

    However, at least in my opinion, the problem with the above is not that we're using NULL for the null pointer constant: it's that we have overloads of foo() which take very different kinds of arguments. The parameter must be an int too, as any other type will result in an ambiguous call and so generate a helpful compiler warning.

  3. Analysis tools can help TODAY!

    Even in the absence of C++0x, there are tools available today that verify that NULL is being used for pointers, and that 0 is being used for integral types.

  4. C++ 11 will have a new std::nullptr_t type.

    This is the newest argument to the table. The problem of 0 and NULL is being actively addressed for C++0x, and you can guarantee that for every implementation that provides NULL, the very first thing that they will do is:

     #define NULL  nullptr
    

    For those who use NULL rather than 0, the change will be an improvement in type-safety with little or no effort - if anything it may also catch a few bugs where they've used NULL for 0. For anybody using 0 today... well, hopefully they have a good knowledge of regular expressions...

How do I assign a null value to a variable in PowerShell?

These are automatic variables, like $null, $true, $false etc.

about_Automatic_Variables, see https://technet.microsoft.com/en-us/library/hh847768.aspx?f=255&MSPPError=-2147217396

$NULL
$null is an automatic variable that contains a NULL or empty value. You can use this variable to represent an absent or undefined value in commands and scripts.

Windows PowerShell treats $null as an object with a value, that is, as an explicit placeholder, so you can use $null to represent an empty value in a series of values.

For example, when $null is included in a collection, it is counted as one of the objects.

C:\PS> $a = ".dir", $null, ".pdf"
C:\PS> $a.count
3

If you pipe the $null variable to the ForEach-Object cmdlet, it generates a value for $null, just as it does for the other objects.

PS C:\ps-test> ".dir", $null, ".pdf" | Foreach {"Hello"}
Hello
Hello
Hello

As a result, you cannot use $null to mean "no parameter value." A parameter value of $null overrides the default parameter value.

However, because Windows PowerShell treats the $null variable as a placeholder, you can use it scripts like the following one, which would not work if $null were ignored.

$calendar = @($null, $null, “Meeting”, $null, $null, “Team Lunch”, $null)
$days = Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"
$currentDay = 0

foreach($day in $calendar)
{
    if($day –ne $null)
    {
        "Appointment on $($days[$currentDay]): $day"
    }

    $currentDay++
}

output:

Appointment on Tuesday: Meeting
Appointment on Friday: Team lunch

Check if AJAX response data is empty/blank/null/undefined/0

//if(data="undefined"){

This is an assignment statement, not a comparison. Also, "undefined" is a string, it's a property. Checking it is like this: if (data === undefined) (no quotes, otherwise it's a string value)

If it's not defined, you may be returning an empty string. You could try checking for a falsy value like if (!data) as well

What is the use of adding a null key or value to a HashMap in Java?

I'm not positive what you're asking, but if you're looking for an example of when one would want to use a null key, I use them often in maps to represent the default case (i.e. the value that should be used if a given key isn't present):

Map<A, B> foo;
A search;
B val = foo.containsKey(search) ? foo.get(search) : foo.get(null);

HashMap handles null keys specially (since it can't call .hashCode() on a null object), but null values aren't anything special, they're stored in the map like anything else

MySQL CONCAT returns NULL if any field contain NULL

SELECT CONCAT(isnull(`affiliate_name`,''),'-',isnull(`model`,''),'-',isnull(`ip`,''),'-',isnull(`os_type`,''),'-',isnull(`os_version`,'')) AS device_name
FROM devices

error: ‘NULL’ was not declared in this scope

NULL isn't a keyword; it's a macro substitution for 0, and comes in stddef.h or cstddef, I believe. You haven't #included an appropriate header file, so g++ sees NULL as a regular variable name, and you haven't declared it.

HashMaps and Null values?

Its a good programming practice to avoid having null values in a Map.

If you have an entry with null value, then it is not possible to tell whether an entry is present in the map or has a null value associated with it.

You can either define a constant for such cases (Example: String NOT_VALID = "#NA"), or you can have another collection storing keys which have null values.

Please check this link for more details.

Null or empty check for a string variable

Yes, that code does exactly that.

You can also use:

if (@value is null or @value = '')

Edit:

With the added information that @value is an int value, you need instead:

if (@value is null)

An int value can never contain the value ''.

IsNull function in DB2 SQL?

I think COALESCE function partially similar to the isnull, but try it.

Why don't you go for null handling functions through application programs, it is better alternative.

Why does NULL = NULL evaluate to false in SQL server

The confusion arises from the level of indirection (abstraction) that comes about from using NULL.

Going back to the "what's under the Christmas tree" analogy, "Unknown" describes the state of knowledge about what is in Box A.

So if you don't know what's in Box A, you say it's "Unknown", but that doesn't mean that "Unknown" is inside the box. Something other than unknown is in the box, possibly some kind of object, or possibly nothing is in the box.

Similarly, if you don't know what's in Box B, you can label your state of knowledge about the contents as being "Unknown".

So here's the kicker: Your state of knowledge about Box A is equal to your state of knowledge about Box B. (Your state of knowledge in both cases is "Unknown" or "I don't know what's in the Box".) But the contents of the boxes may or may not be equal.

Going back to SQL, ideally you should only be able to compare values when you know what they are. Unfortunately, the label that describes a lack of knowledge is stored in the cell itself, so we're tempted to use it as a value. But we should not use that as a value, because it would lead to "the content of Box A equals the content of Box B when we don't know what's in Box A and/or we don't know what's in Box B. (Logically, the implication "if I don't know what's in Box A and if I don't know what's in Box B, then what's in Box A = What's in Box B" is false.)

Yay, Dead Horse.

Check if returned value is not null and if so assign it, in one line, with one method call

Using Java 1.8 you can use Optional

public class Main  {

    public static void main(String[] args) {

        //example call, the methods are just dumb templates, note they are static
        FutureMeal meal = getChicken().orElse(getFreeRangeChicken());

        //another possible way to call this having static methods is
        FutureMeal meal = getChicken().orElseGet(Main::getFreeRangeChicken); //method reference

        //or if you would use a Instance of Main and call getChicken and getFreeRangeChicken
        // as nonstatic methods (assume static would be replaced with public for this)
        Main m = new Main();
        FutureMeal meal = m.getChicken().orElseGet(m::getFreeRangeChicken); //method reference

        //or
        FutureMeal meal = m.getChicken().orElse(m.getFreeRangeChicken()); //method call


    }

    static Optional<FutureMeal> getChicken(){

        //instead of returning null, you would return Optional.empty() 
        //here I just return it to demonstrate
        return Optional.empty();

        //if you would return a valid object the following comment would be the code
        //FutureMeal ret = new FutureMeal(); //your return object
        //return Optional.of(ret);            

    }

    static FutureMeal getFreeRangeChicken(){
        return new FutureMeal();
    }
}

You would implement a logic for getChicken to return either Optional.empty() instead of null, or Optional.of(myReturnObject), where myReturnObject is your chicken.

Then you can call getChicken() and if it would return Optional.empty() the orElse(fallback) would give you whatever the fallback would be, in your case the second method.

Difference between null and empty ("") Java String

enter image description here

This image might help you to understand the differences.

The image was collected from ProgrammerHumor

What is the difference between null and undefined in JavaScript?

Check this out. The output is worth thousand words.

_x000D_
_x000D_
var b1 = document.getElementById("b1");_x000D_
_x000D_
checkif("1, no argument"                        );_x000D_
checkif("2, undefined explicitly",     undefined);_x000D_
checkif("3, null explicitly",               null);_x000D_
checkif("4, the 0",                            0);_x000D_
checkif("5, empty string",                    '');_x000D_
checkif("6, string",                    "string");_x000D_
checkif("7, number",                      123456);_x000D_
_x000D_
function checkif (a1, a2) {_x000D_
 print("\ncheckif(), " + a1 + ":");_x000D_
 if (a2 == undefined) {_x000D_
  print("==undefined:    YES");_x000D_
 } else {_x000D_
  print("==undefined:    NO");_x000D_
 }_x000D_
 if (a2 === undefined) {_x000D_
  print("===undefined:   YES");_x000D_
 } else {_x000D_
  print("===undefined:   NO");_x000D_
 }_x000D_
 if (a2 == null) {_x000D_
  print("==null:         YES");_x000D_
 } else {_x000D_
  print("==null:         NO");_x000D_
 }_x000D_
 if (a2 === null) {_x000D_
  print("===null:        YES");_x000D_
 } else {_x000D_
  print("===null:        NO");_x000D_
 }_x000D_
 if (a2 == '') {_x000D_
  print("=='':           YES");_x000D_
 } else {_x000D_
  print("=='':           NO");_x000D_
 }_x000D_
 if (a2 === '') {_x000D_
  print("==='':          YES");_x000D_
 } else {_x000D_
  print("==='':          NO");_x000D_
 }_x000D_
 if (isNaN(a2)) {_x000D_
  print("isNaN():        YES");_x000D_
 } else {_x000D_
  print("isNaN():        NO");_x000D_
 }_x000D_
 if (a2) {_x000D_
  print("if-?:           YES");_x000D_
 } else {_x000D_
  print("if-?:           NO");_x000D_
 }_x000D_
  print("typeof():       " + typeof(a2));_x000D_
}_x000D_
_x000D_
function print(v) {_x000D_
 b1.innerHTML += v + "\n";_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
<pre id="b1"></pre>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

See also:

Cheers!

What is the difference between null and System.DBNull.Value?

DataRow has a method that is called IsNull() that you can use to test the column if it has a null value - regarding to the null as it's seen by the database.

DataRow["col"]==null will allways be false.

use

DataRow r;
if (r.IsNull("col")) ...

instead.

JavaScript checking for null vs. undefined and difference between == and ===

undefined

It means the variable is not yet intialized .

Example :

var x;
if(x){ //you can check like this
   //code.
}

equals(==)

It only check value is equals not datatype .

Example :

var x = true;
var y = new Boolean(true);
x == y ; //returns true

Because it checks only value .

Strict Equals(===)

Checks the value and datatype should be same .

Example :

var x = true;
var y = new Boolean(true);
x===y; //returns false.

Because it checks the datatype x is a primitive type and y is a boolean object .

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.

MySQL: selecting rows where a column is null

SELECT pid FROM planets WHERE userid is null;

Removing "NUL" characters

Click Search --> Replace --> Find What: \0 Replace with: "empty" Search mode: Extended --> Replace all

How to convert empty spaces into null values, using SQL Server?

This code generates some SQL which can achieve this on every table and column in the database:

SELECT
   'UPDATE ['+T.TABLE_SCHEMA+'].[' + T.TABLE_NAME + '] SET [' + COLUMN_NAME + '] = NULL 
   WHERE [' + COLUMN_NAME + '] = '''''
FROM 
    INFORMATION_SCHEMA.columns C
INNER JOIN
    INFORMATION_SCHEMA.TABLES T ON C.TABLE_NAME=T.TABLE_NAME AND C.TABLE_SCHEMA=T.TABLE_SCHEMA
WHERE 
    DATA_TYPE IN ('char','nchar','varchar','nvarchar')
AND C.IS_NULLABLE='YES'
AND T.TABLE_TYPE='BASE TABLE'

Unable to cast object of type 'System.DBNull' to type 'System.String`

I use an extension to eliminate this problem for me, which may or may not be what you are after.

It goes like this:

public static class Extensions
{

    public String TrimString(this object item)
    {
        return String.Format("{0}", item).Trim();
    }

}

Note:

This extension does not return null values! If the item is null or DBNull.Value, it will return an empty String.

Usage:

public string GetCustomerNumber(Guid id)
{
    var obj = 
        DBSqlHelperFactory.ExecuteScalar(
            connectionStringSplendidmyApp, 
            CommandType.StoredProcedure, 
            "GetCustomerNumber", 
            new SqlParameter("@id", id)
        );
    return obj.TrimString();
}

object==null or null==object?

As others have said, it's a habit learned from C to avoid typos - although even in C I'd expect decent compilers at high enough warning levels to give a warning. As Chandru says, comparing against null in Java in this way would only cause problems if you were using a variable of type Boolean (which you're not in the sample code). I'd say that's a pretty rare situation, and not one for which it's worth changing the way you write code everywhere else. (I wouldn't bother reversing the operands even in this case; if I'm thinking clearly enough to consider reversing them, I'm sure I can count the equals signs.)

What hasn't been mentioned is that many people (myself certainly included) find the if (variable == constant) form to be more readable - it's a more natural way of expressing yourself. This is a reason not to blindly copy a convention from C. You should always question practices (as you're doing here :) before assuming that what may be useful in one environment is useful in another.

Referring to the null object in Python

None, Python's null?

There's no null in Python; instead there's None. As stated already, the most accurate way to test that something has been given None as a value is to use the is identity operator, which tests that two variables refer to the same object.

>>> foo is None
True
>>> foo = 'bar'
>>> foo is None
False

The basics

There is and can only be one None

None is the sole instance of the class NoneType and any further attempts at instantiating that class will return the same object, which makes None a singleton. Newcomers to Python often see error messages that mention NoneType and wonder what it is. It's my personal opinion that these messages could simply just mention None by name because, as we'll see shortly, None leaves little room to ambiguity. So if you see some TypeError message that mentions that NoneType can't do this or can't do that, just know that it's simply the one None that was being used in a way that it can't.

Also, None is a built-in constant. As soon as you start Python, it's available to use from everywhere, whether in module, class, or function. NoneType by contrast is not, you'd need to get a reference to it first by querying None for its class.

>>> NoneType
NameError: name 'NoneType' is not defined
>>> type(None)
NoneType

You can check None's uniqueness with Python's identity function id(). It returns the unique number assigned to an object, each object has one. If the id of two variables is the same, then they point in fact to the same object.

>>> NoneType = type(None)
>>> id(None)
10748000
>>> my_none = NoneType()
>>> id(my_none)
10748000
>>> another_none = NoneType()
>>> id(another_none)
10748000
>>> def function_that_does_nothing(): pass
>>> return_value = function_that_does_nothing()
>>> id(return_value)
10748000

None cannot be overwritten

In much older versions of Python (before 2.4) it was possible to reassign None, but not any more. Not even as a class attribute or in the confines of a function.

# In Python 2.7
>>> class SomeClass(object):
...     def my_fnc(self):
...             self.None = 'foo'
SyntaxError: cannot assign to None
>>> def my_fnc():
        None = 'foo'
SyntaxError: cannot assign to None

# In Python 3.5
>>> class SomeClass:
...     def my_fnc(self):
...             self.None = 'foo'
SyntaxError: invalid syntax
>>> def my_fnc():
        None = 'foo'
SyntaxError: cannot assign to keyword

It's therefore safe to assume that all None references are the same. There isn't any "custom" None.

To test for None use the is operator

When writing code you might be tempted to test for Noneness like this:

if value==None:
    pass

Or to test for falsehood like this

if not value:
    pass

You need to understand the implications and why it's often a good idea to be explicit.

Case 1: testing if a value is None

Why do

value is None

rather than

value==None

?

The first is equivalent to:

id(value)==id(None)

Whereas the expression value==None is in fact applied like this

value.__eq__(None)

If the value really is None then you'll get what you expected.

>>> nothing = function_that_does_nothing()
>>> nothing.__eq__(None)
True

In most common cases the outcome will be the same, but the __eq__() method opens a door that voids any guarantee of accuracy, since it can be overridden in a class to provide special behavior.

Consider this class.

>>> class Empty(object):
...     def __eq__(self, other):
...         return not other

So you try it on None and it works

>>> empty = Empty()
>>> empty==None
True

But then it also works on the empty string

>>> empty==''
True

And yet

>>> ''==None
False
>>> empty is None
False

Case 2: Using None as a boolean

The following two tests

if value:
    # Do something

if not value:
    # Do something

are in fact evaluated as

if bool(value):
    # Do something

if not bool(value):
    # Do something

None is a "falsey", meaning that if cast to a boolean it will return False and if applied the not operator it will return True. Note however that it's not a property unique to None. In addition to False itself, the property is shared by empty lists, tuples, sets, dicts, strings, as well as 0, and all objects from classes that implement the __bool__() magic method to return False.

>>> bool(None)
False
>>> not None
True

>>> bool([])
False
>>> not []
True

>>> class MyFalsey(object):
...     def __bool__(self):
...         return False
>>> f = MyFalsey()
>>> bool(f)
False
>>> not f
True

So when testing for variables in the following way, be extra aware of what you're including or excluding from the test:

def some_function(value=None):
    if not value:
        value = init_value()

In the above, did you mean to call init_value() when the value is set specifically to None, or did you mean that a value set to 0, or the empty string, or an empty list should also trigger the initialization? Like I said, be mindful. As it's often the case, in Python explicit is better than implicit.

None in practice

None used as a signal value

None has a special status in Python. It's a favorite baseline value because many algorithms treat it as an exceptional value. In such scenarios it can be used as a flag to signal that a condition requires some special handling (such as the setting of a default value).

You can assign None to the keyword arguments of a function and then explicitly test for it.

def my_function(value, param=None):
    if param is None:
        # Do something outrageous!

You can return it as the default when trying to get to an object's attribute and then explicitly test for it before doing something special.

value = getattr(some_obj, 'some_attribute', None)
if value is None:
    # do something spectacular!

By default a dictionary's get() method returns None when trying to access a non-existing key:

>>> some_dict = {}
>>> value = some_dict.get('foo')
>>> value is None
True

If you were to try to access it by using the subscript notation a KeyError would be raised

>>> value = some_dict['foo']
KeyError: 'foo'

Likewise if you attempt to pop a non-existing item

>>> value = some_dict.pop('foo')
KeyError: 'foo'

which you can suppress with a default value that is usually set to None

value = some_dict.pop('foo', None)
if value is None:
    # Booom!

None used as both a flag and valid value

The above described uses of None apply when it is not considered a valid value, but more like a signal to do something special. There are situations however where it sometimes matters to know where None came from because even though it's used as a signal it could also be part of the data.

When you query an object for its attribute with getattr(some_obj, 'attribute_name', None) getting back None doesn't tell you if the attribute you were trying to access was set to None or if it was altogether absent from the object. The same situation when accessing a key from a dictionary, like some_dict.get('some_key'), you don't know if some_dict['some_key'] is missing or if it's just set to None. If you need that information, the usual way to handle this is to directly attempt accessing the attribute or key from within a try/except construct:

try:
    # Equivalent to getattr() without specifying a default
    # value = getattr(some_obj, 'some_attribute')
    value = some_obj.some_attribute
    # Now you handle `None` the data here
    if value is None:
        # Do something here because the attribute was set to None
except AttributeError:
    # We're now handling the exceptional situation from here.
    # We could assign None as a default value if required.
    value = None
    # In addition, since we now know that some_obj doesn't have the
    # attribute 'some_attribute' we could do something about that.
    log_something(some_obj)

Similarly with dict:

try:
    value = some_dict['some_key']
    if value is None:
        # Do something here because 'some_key' is set to None
except KeyError:
    # Set a default
    value = None
    # And do something because 'some_key' was missing
    # from the dict.
    log_something(some_dict)

The above two examples show how to handle object and dictionary cases. What about functions? The same thing, but we use the double asterisks keyword argument to that end:

def my_function(**kwargs):
    try:
        value = kwargs['some_key']
        if value is None:
            # Do something because 'some_key' is explicitly
            # set to None
    except KeyError:
        # We assign the default
        value = None
        # And since it's not coming from the caller.
        log_something('did not receive "some_key"')

None used only as a valid value

If you find that your code is littered with the above try/except pattern simply to differentiate between None flags and None data, then just use another test value. There's a pattern where a value that falls outside the set of valid values is inserted as part of the data in a data structure and is used to control and test special conditions (e.g. boundaries, state, etc.). Such a value is called a sentinel and it can be used the way None is used as a signal. It's trivial to create a sentinel in Python.

undefined = object()

The undefined object above is unique and doesn't do much of anything that might be of interest to a program, it's thus an excellent replacement for None as a flag. Some caveats apply, more about that after the code.

With function

def my_function(value, param1=undefined, param2=undefined):
    if param1 is undefined:
        # We know nothing was passed to it, not even None
        log_something('param1 was missing')
        param1 = None


    if param2 is undefined:
        # We got nothing here either
        log_something('param2 was missing')
        param2 = None

With dict

value = some_dict.get('some_key', undefined)
if value is None:
    log_something("'some_key' was set to None")

if value is undefined:
    # We know that the dict didn't have 'some_key'
    log_something("'some_key' was not set at all")
    value = None

With an object

value = getattr(obj, 'some_attribute', undefined)
if value is None:
    log_something("'obj.some_attribute' was set to None")
if value is undefined:
    # We know that there's no obj.some_attribute
    log_something("no 'some_attribute' set on obj")
    value = None

As I mentioned earlier, custom sentinels come with some caveats. First, they're not keywords like None, so Python doesn't protect them. You can overwrite your undefined above at any time, anywhere in the module it's defined, so be careful how you expose and use them. Next, the instance returned by object() is not a singleton. If you make that call 10 times you get 10 different objects. Finally, usage of a sentinel is highly idiosyncratic. A sentinel is specific to the library it's used in and as such its scope should generally be limited to the library's internals. It shouldn't "leak" out. External code should only become aware of it, if their purpose is to extend or supplement the library's API.

Passing null arguments to C# methods

Yes. There are two kinds of types in .NET: reference types and value types.

References types (generally classes) are always referred to by references, so they support null without any extra work. This means that if a variable's type is a reference type, the variable is automatically a reference.

Value types (e.g. int) by default do not have a concept of null. However, there is a wrapper for them called Nullable. This enables you to encapsulate the non-nullable value type and include null information.

The usage is slightly different, though.

// Both of these types mean the same thing, the ? is just C# shorthand.
private void Example(int? arg1, Nullable<int> arg2)
{
    if (arg1.HasValue)
        DoSomething();

    arg1 = null; // Valid.
    arg1 = 123;  // Also valid.

    DoSomethingWithInt(arg1); // NOT valid!
    DoSomethingWithInt(arg1.Value); // Valid.
}

MySql Query Replace NULL with Empty String in Select

The original form is nearly perfect, you just have to omit prereq after CASE:

SELECT
  CASE
    WHEN prereq IS NULL THEN ' '
    ELSE prereq
  END AS prereq
FROM test;

JavaScript check if value is only undefined, null or false

One way to do it is like that:

var acceptable = {"undefined": 1, "boolean": 1, "object": 1};

if(!val && acceptable[typeof val]){
  // ...
}

I think it minimizes the number of operations given your restrictions making the check fast.

What is a 'NoneType' object?

NoneType is the type for the None object, which is an object that indicates no value. None is the return value of functions that "don't return anything". It is also a common default return value for functions that search for something and may or may not find it; for example, it's returned by re.search when the regex doesn't match, or dict.get when the key has no entry in the dict. You cannot add None to strings or other objects.

One of your variables is None, not a string. Maybe you forgot to return in one of your functions, or maybe the user didn't provide a command-line option and optparse gave you None for that option's value. When you try to add None to a string, you get that exception:

send_command(child, SNMPGROUPCMD + group + V3PRIVCMD)

One of group or SNMPGROUPCMD or V3PRIVCMD has None as its value.

Javascript document.getElementById("id").value returning null instead of empty string when the element is an empty text box

try this...    
<script type="text/javascript">
    function test(){
    var av=document.getElementById("mytext").value;
    alert(av);
    }
    </script>

    <input type="text" value="" id="mytext">
    <input type="button" onclick="test()" value="go" />

How to select rows where column value IS NOT NULL using CodeIgniter's ActiveRecord?

CodeIgniter 3

Only:

$this->db->where('archived IS NOT NULL');

The generated query is:

WHERE archived IS NOT NULL;

$this->db->where('archived IS NOT NULL',null,false); << Not necessary

Inverse:

$this->db->where('archived');

The generated query is:

WHERE archived IS NULL;

Which @NotNull Java annotation should I use?

If you are building your application using Spring Framework I would suggest using javax.validation.constraints.NotNull comming from Beans Validation packaged in following dependency:

    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.1.0.Final</version>
    </dependency>

The main advantage of this annotation is that Spring provides support for both method parameters and class fields annotated with javax.validation.constraints.NotNull. All you need to do to enable support is:

  1. supply the api jar for beans validation and jar with implementation of validator of jsr-303/jsr-349 annotations (which comes with Hibernate Validator 5.x dependency):

    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.1.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.4.1.Final</version>
    </dependency>
    
  2. provide MethodValidationPostProcessor to spring's context

      @Configuration
      @ValidationConfig
      public class ValidationConfig implements MyService {
    
            @Bean
            public MethodValidationPostProcessor providePostProcessor() {
                  return new MethodValidationPostProcessor()
            }
      }
    
  3. finally you annotate your classes with Spring's org.springframework.validation.annotation.Validated and validation will be automatically handled by Spring.

Example:

@Service
@Validated
public class MyServiceImpl implements MyService {

  @Override
  public Something doSomething(@NotNull String myParameter) {
        // No need to do something like assert myParameter != null  
  }
}

When you try calling method doSomething and pass null as the parameter value, spring (by means of HibernateValidator) will throw ConstraintViolationException. No need for manuall work here.

You can also validate return values.

Another important benefit of javax.validation.constraints.NotNull comming for Beans Validation Framework is that at the moment it is still developed and new features are planned for new version 2.0.

What about @Nullable? There is nothing like that in Beans Validation 1.1. Well, I could arguee that if you decide to use @NotNull than everything which is NOT annotated with @NonNull is effectively "nullable", so the @Nullable annotation is useless.

PHP Check for NULL

Use is_null or === operator.

is_null($result['column'])

$result['column'] === NULL

How to select rows with one or more nulls from a pandas DataFrame without listing columns explicitly?

.any() and .all() are great for the extreme cases, but not when you're looking for a specific number of null values. Here's an extremely simple way to do what I believe you're asking. It's pretty verbose, but functional.

import pandas as pd
import numpy as np

# Some test data frame
df = pd.DataFrame({'num_legs':          [2, 4,      np.nan, 0, np.nan],
                   'num_wings':         [2, 0,      np.nan, 0, 9],
                   'num_specimen_seen': [10, np.nan, 1,     8, np.nan]})

# Helper : Gets NaNs for some row
def row_nan_sums(df):
    sums = []
    for row in df.values:
        sum = 0
        for el in row:
            if el != el: # np.nan is never equal to itself. This is "hacky", but complete.
                sum+=1
        sums.append(sum)
    return sums

# Returns a list of indices for rows with k+ NaNs
def query_k_plus_sums(df, k):
    sums = row_nan_sums(df)
    indices = []
    i = 0
    for sum in sums:
        if (sum >= k):
            indices.append(i)
        i += 1
    return indices

# test
print(df)
print(query_k_plus_sums(df, 2))

Output

   num_legs  num_wings  num_specimen_seen
0       2.0        2.0               10.0
1       4.0        0.0                NaN
2       NaN        NaN                1.0
3       0.0        0.0                8.0
4       NaN        9.0                NaN
[2, 4]

Then, if you're like me and want to clear those rows out, you just write this:

# drop the rows from the data frame
df.drop(query_k_plus_sums(df, 2),inplace=True)
# Reshuffle up data (if you don't do this, the indices won't reset)
df = df.sample(frac=1).reset_index(drop=True)
# print data frame
print(df)

Output:

   num_legs  num_wings  num_specimen_seen
0       4.0        0.0                NaN
1       0.0        0.0                8.0
2       2.0        2.0               10.0

Checking for NULL pointer in C/C++

if (foo) is clear enough. Use it.

Can I use if (pointer) instead of if (pointer != NULL)?

Explicitly checking for NULL could provide a hint to the compiler on what you are trying to do, ergo leading to being less error-prone.

enter image description here

Best way to check if a Data Table has a null value in it

DataTable dt = new DataTable();
foreach (DataRow dr in dt.Rows)
{
    if (dr["Column_Name"] == DBNull.Value)
    {
        //Do something
    }
    else
    {
        //Do something
    }
}

Using NULL in C++?

In C++ NULL expands to 0 or 0L. See this quote from Stroustrup's FAQ:

Should I use NULL or 0?

In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days.

If you have to name the null pointer, call it nullptr; that's what it's called in C++11. Then, "nullptr" will be a keyword.

Should a retrieval method return 'null' or throw an exception when it can't produce the return value?

If not finding it is an exceptional event (i.e. it should be there under normal circumstances), then throw. Otherwise, return a "not found" value (can be null, but does not have to), or even have the method return a boolean for found/notfound and an out parameter for the actual object.

MySQL and PHP - insert NULL rather than empty string

you can do it for example with

UPDATE `table` SET `date`='', `newdate`=NULL WHERE id='$id'

ALTER TABLE, set null in not null column, PostgreSQL 9.1

Execute the command in this format:

ALTER [ COLUMN ] column { SET | DROP } NOT NULL

Returning null in a method whose signature says return int?

Do you realy want to return null ? Something you can do, is maybe initialise savedkey with 0 value and return 0 as a null value. It can be more simple.

How to check if String is null

To sure, you should use function to check is null and empty as below:

string str = ...
if (!String.IsNullOrEmpty(str))
{
...
}

Output a NULL cell value in Excel

I've been frustrated by this problem as well. Find/Replace can be helpful though, because if you don't put anything in the "replace" field it will replace with an -actual- NULL. So the steps would be something along the lines of:

1: Place some unique string in your formula in place of the NULL output (i like to use a password-like string)

2: Run your formula

3: Open Find/Replace, and fill in the unique string as the search value. Leave "replace with" blank

4: Replace All

Obviously, this has limitations. It only works when the context allows you to do a find/replace, so for more dynamic formulas this won't help much. But, I figured I'd put it up here anyway.

Create unique constraint with null columns

You can store favourites with no associated menu in a separate table:

CREATE TABLE FavoriteWithoutMenu
(
  FavoriteWithoutMenuId uuid NOT NULL, --Primary key
  UserId uuid NOT NULL,
  RecipeId uuid NOT NULL,
  UNIQUE KEY (UserId, RecipeId)
)

Checking for a null object in C++

As everyone said, references can't be null. That is because, a reference refers to an object. In your code:

// this compiles, but doesn't work, and does this even mean anything?
if (&str == NULL)

you are taking the address of the object str. By definition, str exists, so it has an address. So, it cannot be NULL. So, syntactically, the above is correct, but logically, the if condition is always going to be false.

About your questions: it depends upon what you want to do. Do you want the function to be able to modify the argument? If yes, pass a reference. If not, don't (or pass reference to const). See this C++ FAQ for some good details.

In general, in C++, passing by reference is preferred by most people over passing a pointer. One of the reasons is exactly what you discovered: a reference can't be NULL, thus avoiding you the headache of checking for it in the function.

javax.persistence.NoResultException: No entity found for query

When you don't know whether there are any results, use getResultList().

List<User> foundUsers = (List<User>) query.getResultList();
        if (foundUsers == null || foundUsers.isEmpty()) {
            return false;
        }
User foundUser = foundUsers.get(0);

MongoDB: How to query for records where field is null or not set?

You can also try this:

db.emails.find($and:[{sent_at:{$exists:true},'sent_at':null}]).count()

What is the PHP syntax to check "is not null" or an empty string?

Use empty(). It checks for both empty strings and null.

if (!empty($_POST['user'])) {
  // do stuff
}

From the manual:

The following things are considered to be empty:

"" (an empty string)  
0 (0 as an integer)  
0.0 (0 as a float)  
"0" (0 as a string)    
NULL  
FALSE  
array() (an empty array)  
var $var; (a variable declared, but without a value in a class)  

Remove characters from NSString?

Taken from NSString

stringByReplacingOccurrencesOfString:withString:

Returns a new string in which all occurrences of a target string in the receiver are replaced by another given string.

- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement

Parameters

target

The string to replace.

replacement

The string with which to replace target.

Return Value

A new string in which all occurrences of target in the receiver are replaced by replacement.

Finding three elements in an array whose sum is closest to a given number

Here is the program in java which is O(N^2)

import java.util.Stack;


public class GetTripletPair {

    /** Set a value for target sum */
    public static final int TARGET_SUM = 32;

    private Stack<Integer> stack = new Stack<Integer>();

    /** Store the sum of current elements stored in stack */
    private int sumInStack = 0;
    private int count =0 ;


    public void populateSubset(int[] data, int fromIndex, int endIndex) {

        /*
        * Check if sum of elements stored in Stack is equal to the expected
        * target sum.
        * 
        * If so, call print method to print the candidate satisfied result.
        */
        if (sumInStack == TARGET_SUM) {
            print(stack);
        }

        for (int currentIndex = fromIndex; currentIndex < endIndex; currentIndex++) {

            if (sumInStack + data[currentIndex] <= TARGET_SUM) {
                ++count;
                stack.push(data[currentIndex]);
                sumInStack += data[currentIndex];

                /*
                * Make the currentIndex +1, and then use recursion to proceed
                * further.
                */
                populateSubset(data, currentIndex + 1, endIndex);
                --count;
                sumInStack -= (Integer) stack.pop();
            }else{
            return;
        }
        }
    }

    /**
    * Print satisfied result. i.e. 15 = 4+6+5
    */

    private void print(Stack<Integer> stack) {
        StringBuilder sb = new StringBuilder();
        sb.append(TARGET_SUM).append(" = ");
        for (Integer i : stack) {
            sb.append(i).append("+");
        }
        System.out.println(sb.deleteCharAt(sb.length() - 1).toString());
    }

    private static final int[] DATA = {4,13,14,15,17};

    public static void main(String[] args) {
        GetAllSubsetByStack get = new GetAllSubsetByStack();
        get.populateSubset(DATA, 0, DATA.length);
    }
}

Reloading submodules in IPython

IPython comes with some automatic reloading magic:

%load_ext autoreload
%autoreload 2

It will reload all changed modules every time before executing a new line. The way this works is slightly different than dreload. Some caveats apply, type %autoreload? to see what can go wrong.


If you want to always enable this settings, modify your IPython configuration file ~/.ipython/profile_default/ipython_config.py[1] and appending:

c.InteractiveShellApp.extensions = ['autoreload']     
c.InteractiveShellApp.exec_lines = ['%autoreload 2']

Credit to @Kos via a comment below.

[1] If you don't have the file ~/.ipython/profile_default/ipython_config.py, you need to call ipython profile create first. Or the file may be located at $IPYTHONDIR.

Using PHP Replace SPACES in URLS with %20

No need for a regex here, if you just want to replace a piece of string by another: using str_replace() should be more than enough :

$new = str_replace(' ', '%20', $your_string);


But, if you want a bit more than that, and you probably do, if you are working with URLs, you should take a look at the urlencode() function.

How to change color in circular progress bar?

check this answer out:

for me, these two lines had to be there for it to work and change the color:

android:indeterminateTint="@color/yourColor"
android:indeterminateTintMode="src_in"

PS: but its only available from android 21

JUnit assertEquals(double expected, double actual, double epsilon)

Epsilon is your "fuzz factor," since doubles may not be exactly equal. Epsilon lets you describe how close they have to be.

If you were expecting 3.14159 but would take anywhere from 3.14059 to 3.14259 (that is, within 0.001), then you should write something like

double myPi = 22.0d / 7.0d; //Don't use this in real life!
assertEquals(3.14159, myPi, 0.001);

(By the way, 22/7 comes out to 3.1428+, and would fail the assertion. This is a good thing.)

Change the color of glyphicons to blue in some- but not at all places using Bootstrap 2

For bootstrap 3.0, this worked for me:

.myclass .glyphicon {color:blue !important;}

How can I pop-up a print dialog box using Javascript?

If you just have a link without a click event handler:

<a href="javascript:window.print();">Print Page</a>

How to draw vertical lines on a given plot in matplotlib

The standard way to add vertical lines that will cover your entire plot window without you having to specify their actual height is plt.axvline

import matplotlib.pyplot as plt

plt.axvline(x=0.22058956)
plt.axvline(x=0.33088437)
plt.axvline(x=2.20589566)

OR

xcoords = [0.22058956, 0.33088437, 2.20589566]
for xc in xcoords:
    plt.axvline(x=xc)

You can use many of the keywords available for other plot commands (e.g. color, linestyle, linewidth ...). You can pass in keyword arguments ymin and ymax if you like in axes corrdinates (e.g. ymin=0.25, ymax=0.75 will cover the middle half of the plot). There are corresponding functions for horizontal lines (axhline) and rectangles (axvspan).

How to create a simple proxy in C#?

You can build one with the HttpListener class to listen for incoming requests and the HttpWebRequest class to relay the requests.

How to change Apache Tomcat web server port number

You need to edit the Tomcat/conf/server.xml and change the connector port. The connector setting should look something like this:

<Connector port="8080" maxHttpHeaderSize="8192"
           maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
           enableLookups="false" redirectPort="8443" acceptCount="100"
           connectionTimeout="20000" disableUploadTimeout="true" />

Just change the connector port from default 8080 to another valid port number.

How to convert array values to lowercase in PHP?

AIO Solution / Recursive / Unicode|UTF-8|Multibyte supported!

/**
 * Change array values case recursively (supports utf8/multibyte)
 * @param array $array The array
 * @param int $case Case to transform (\CASE_LOWER | \CASE_UPPER)
 * @return array Final array
 */
function changeValuesCase ( array $array, $case = \CASE_LOWER ) : array {
    if ( !\is_array ($array) ) {
        return [];
    }

    /** @var integer $theCase */
    $theCase = ($case === \CASE_LOWER)
        ? \MB_CASE_LOWER
        : \MB_CASE_UPPER;

    foreach ( $array as $key => $value ) {
        $array[$key] = \is_array ($value)
            ? changeValuesCase ($value, $case)
            : \mb_convert_case($array[$key], $theCase, 'UTF-8');
    }

    return $array;
}

Example:

$food = [
    'meat' => ['chicken', 'fish'],
    'vegetables' => [
        'leafy' => ['collard greens', 'kale', 'chard', 'spinach', 'lettuce'],
        'root'  => ['radish', 'turnip', 'potato', 'beet'],
        'other' => ['brocolli', 'green beans', 'corn', 'tomatoes'],
    ],
    'grains' => ['wheat', 'rice', 'oats'],
];

$newArray = changeValuesCase ($food, \CASE_UPPER);

Output

    [
    'meat' => [
        0 => 'CHICKEN'
        1 => 'FISH'
    ]
    'vegetables' => [
        'leafy' => [
            0 => 'COLLARD GREENS'
            1 => 'KALE'
            2 => 'CHARD'
            3 => 'SPINACH'
            4 => 'LETTUCE'
        ]
        'root' => [
            0 => 'RADISH'
            1 => 'TURNIP'
            2 => 'POTATO'
            3 => 'BEET'
        ]
        'other' => [
            0 => 'BROCOLLI'
            1 => 'GREEN BEANS'
            2 => 'CORN'
            3 => 'TOMATOES'
        ]
    ]
    'grains' => [
        0 => 'WHEAT'
        1 => 'RICE'
        2 => 'OATS'
    ]
]

Ansible: deploy on multiple hosts in the same time

Ansible supports patterns which can be used for one/multiple hosts,groups and also can exclude/include groups. Here is the link for official document.

ADB error: cannot connect to daemon

I face this problem on daily basis, so to resolve this I kill adb.exe by executing following command :

taskkill /f /im adb.exe

Note : You should have administrative rights to execute the above command.

How do I get indices of N maximum values in a NumPy array?

Use:

>>> import heapq
>>> import numpy
>>> a = numpy.array([1, 3, 2, 4, 5])
>>> heapq.nlargest(3, range(len(a)), a.take)
[4, 3, 1]

For regular Python lists:

>>> a = [1, 3, 2, 4, 5]
>>> heapq.nlargest(3, range(len(a)), a.__getitem__)
[4, 3, 1]

If you use Python 2, use xrange instead of range.

Source: heapq — Heap queue algorithm

Check string for palindrome

import java.util.Scanner;


public class Palindrom {

    public static void main(String []args)
    {
        Scanner in = new Scanner(System.in);
        String str= in.nextLine();
        int x= str.length();

        if(x%2!=0)
        {
            for(int i=0;i<x/2;i++)
            {

                if(str.charAt(i)==str.charAt(x-1-i))
                {
                    continue;
                }
                else 
                {
                    System.out.println("String is not a palindrom");
                    break;
                }
            }
        }
        else
        {
            for(int i=0;i<=x/2;i++)
            {
                if(str.charAt(i)==str.charAt(x-1-i))
                {
                    continue;
                }
                else 
                {
                    System.out.println("String is not a palindrom");
                    break;
                }

            }
        }
    }

}

How to use OAuth2RestTemplate?

You can find examples for writing OAuth clients here:

In your case you can't just use default or base classes for everything, you have a multiple classes Implementing OAuth2ProtectedResourceDetails. The configuration depends of how you configured your OAuth service but assuming from your curl connections I would recommend:

@EnableOAuth2Client
@Configuration
class MyConfig{

    @Value("${oauth.resource:http://localhost:8082}")
    private String baseUrl;
    @Value("${oauth.authorize:http://localhost:8082/oauth/authorize}")
    private String authorizeUrl;
    @Value("${oauth.token:http://localhost:8082/oauth/token}")
    private String tokenUrl;

    @Bean
    protected OAuth2ProtectedResourceDetails resource() {
        ResourceOwnerPasswordResourceDetails resource;
        resource = new ResourceOwnerPasswordResourceDetails();

        List scopes = new ArrayList<String>(2);
        scopes.add("write");
        scopes.add("read");
        resource.setAccessTokenUri(tokenUrl);
        resource.setClientId("restapp");
        resource.setClientSecret("restapp");
        resource.setGrantType("password");
        resource.setScope(scopes);
        resource.setUsername("**USERNAME**");
        resource.setPassword("**PASSWORD**");
        return resource;
    }

    @Bean
    public OAuth2RestOperations restTemplate() {
        AccessTokenRequest atr = new DefaultAccessTokenRequest();
        return new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(atr));
    }
}

@Service
@SuppressWarnings("unchecked")
class MyService {

    @Autowired
    private OAuth2RestOperations restTemplate;

    public MyService() {
        restTemplate.getAccessToken();
    }
}

Do not forget about @EnableOAuth2Client on your config class, also I would suggest to try that the urls you are using are working with curl first, also try to trace it with the debugger because lot of exceptions are just consumed and never printed out due security reasons, so it gets little hard to find where the issue is. You should use logger with debug enabled set. Good luck

I uploaded sample springboot app on github https://github.com/mariubog/oauth-client-sample to depict your situation because I could not find any samples for your scenario .

Check if string matches pattern

import re
pattern = re.compile("^([A-Z][0-9]+)+$")
pattern.search(string)

R: Comment out block of code

I have dealt with this at talkstats.com in posts 94, 101 & 103 found in the thread: Share Your Code. As others have said Rstudio may be a better way to go. I store these functions in my .Rprofile and actually use them a but to automatically block out lines of code quickly.

Not quite as nice as you were hoping for but may be an approach.

SQL Server IIF vs CASE

IIF is the same as CASE WHEN <Condition> THEN <true part> ELSE <false part> END. The query plan will be the same. It is, perhaps, "syntactical sugar" as initially implemented.

CASE is portable across all SQL platforms whereas IIF is SQL SERVER 2012+ specific.

Jquery change <p> text programmatically

"saving" is something wholly different from changing paragraph content with jquery.

If you need to save changes you will have to write them to your server somehow (likely form submission along with all the security and input sanitizing that entails). If you have information that is saved on the server then you are no longer changing the content of a paragraph, you are drawing a paragraph with dynamic content (either from a database or a file which your server altered when you did the "saving").

Judging by your question, this is a topic on which you will have to do MUCH more research.

Input page (input.html):

<form action="/saveMyParagraph.php">
    <input name="pContent" type="text"></input>
</form>

Saving page (saveMyParagraph.php) and Ouput page (output.php):

Inserting Data Into a MySQL Database using PHP

Setting value of active workbook in Excel VBA

This is all you need

Set wbOOR = ActiveWorkbook

CSS disable hover effect

Add the following to add hover effect on disabled button:

.buttonDisabled:hover
  {
    /*your code goes here*/     
  }

Converting 'ArrayList<String> to 'String[]' in Java

You can convert List to String array by using this method:

 Object[] stringlist=list.toArray();

The complete example:

ArrayList<String> list=new ArrayList<>();
    list.add("Abc");
    list.add("xyz");

    Object[] stringlist=list.toArray();

    for(int i = 0; i < stringlist.length ; i++)
    {
          Log.wtf("list data:",(String)stringlist[i]);
    }

How to efficiently remove duplicates from an array without using Set

Heres a simpler, better way to do this using arraylists instead:

public static final <T> ArrayList<T> removeDuplicates(ArrayList<T> in){
    ArrayList<T> out = new ArrayList<T>();
    for(T t : in) 
        if(!out.contains(t)) 
            out.add(t);
    return out;
}

What is Model in ModelAndView from Spring MVC?

It is all explained by the javadoc for the constructor. It is a convenience constructor that populates the model with one attribute / value pair.

So ...

   new ModelAndView(view, name, value);

is equivalent to:

   Map model = ...
   model.put(name, value);
   new ModelAndView(view, model);

How to import an existing project from GitHub into Android Studio

In Github click the "Clone or download" button of the project you want to import --> download the ZIP file and unzip it. In Android Studio Go to File -> New Project -> Import Project and select the newly unzipped folder -> press OK. It will build the Gradle automatically.

Good Luck with your project

Avoiding "resource is out of sync with the filesystem"

A little hint. The message often appears during rename operation. The quick workaround for me is pressing Ctrl-Y (redo shortcut) after message confirmation. It works only if the renaming affects a single file.

How to resolve a Java Rounding Double issue

Any time you do calculations with doubles, this can happen. This code would give you 877.85:

double answer = Math.round(dCommission * 100000) / 100000.0;

SQL Server: How to use UNION with two queries that BOTH have a WHERE clause?

The basic premise of the question and the answers are wrong. Every Select in a union can have a where clause. It's the ORDER BY in the first query that's giving yo the error.

How to get table cells evenly spaced?

You could always just set the width of each td to 100%/N columns.

<td width="x%"></td>

How to replace a whole line with sed?

This might work for you:

cat <<! | sed '/aaa=\(bbb\|ccc\|ddd\)/!s/\(aaa=\).*/\1xxx/'
> aaa=bbb
> aaa=ccc
> aaa=ddd
> aaa=[something else]
!
aaa=bbb
aaa=ccc
aaa=ddd
aaa=xxx

Exception thrown in catch and finally clause

The easiest way to think of this is imagine that there is a variable global to the entire application that is holding the current exception.

Exception currentException = null;

As each exception is thrown, "currentException" is set to that exception. When the application ends, if currentException is != null, then the runtime reports the error.

Also, the finally blocks always run before the method exits. You could then requite the code snippet to:

public class C1 {

    public static void main(String [] argv) throws Exception {
        try {
            System.out.print(1);
            q();

        }
        catch ( Exception i ) {
            // <-- currentException = Exception, as thrown by q()'s finally block
            throw( new MyExc2() ); // <-- currentException = MyExc2
        }
        finally {
             // <-- currentException = MyExc2, thrown from main()'s catch block
            System.out.print(2);
            throw( new MyExc1() ); // <-- currentException = MyExc1
        }

    }  // <-- At application exit, currentException = MyExc1, from main()'s finally block. Java now dumps that to the console.

    static void q() throws Exception {
        try {
            throw( new MyExc1() ); // <-- currentException = MyExc1
        }
        catch( Exception y ) {
           // <-- currentException = null, because the exception is caught and not rethrown
        }
        finally {
            System.out.print(3);
            throw( new Exception() ); // <-- currentException = Exception
        }
    }
}

The order in which the application executes is:

main()
{
  try
    q()
    {
      try
      catch
      finally
    }
  catch
  finally
}

Select distinct values from a list using LINQ in C#

I was curious about which method would be faster:

  1. Using Distinct with a custom IEqualityComparer or
  2. Using the GroupBy method described by Cuong Le.

I found that depending on the size of the input data and the number of groups, the Distinct method can be a lot more performant. (as the number of groups tends towards the number of elements in the list, distinct runs faster).

Code runs in LinqPad!

    void Main()
    {
        List<C> cs = new List<C>();
        foreach(var i in Enumerable.Range(0,Int16.MaxValue*1000))
        {
            int modValue = Int16.MaxValue; //vary this value to see how the size of groups changes performance characteristics. Try 1, 5, 10, and very large numbers
            int j = i%modValue; 
            cs.Add(new C{I = i, J = j});
        }
        cs.Count ().Dump("Size of input array");

        TestGrouping(cs);
        TestDistinct(cs);
    }

    public void TestGrouping(List<C> cs)
    {
        Stopwatch sw = Stopwatch.StartNew();
        sw.Restart();
        var groupedCount  = cs.GroupBy (o => o.J).Select(s => s.First()).Count();
        groupedCount.Dump("num groups");
        sw.ElapsedMilliseconds.Dump("elapsed time for using grouping");
    }

    public void TestDistinct(List<C> cs)
    {
        Stopwatch sw = Stopwatch.StartNew();
        var distinctCount = cs.Distinct(new CComparerOnJ()).Count ();
        distinctCount.Dump("num distinct");
        sw.ElapsedMilliseconds.Dump("elapsed time for using distinct");
    }

    public class C
    {
        public int I {get; set;}
        public int J {get; set;}
    }

    public class CComparerOnJ : IEqualityComparer<C>
    {
        public bool Equals(C x, C y)
        {
            return x.J.Equals(y.J);
        }

        public int GetHashCode(C obj)
        {
            return obj.J.GetHashCode();
        }
    }

Do I need a content-type header for HTTP GET requests?

Short answer: Most likely, no you do not need a content-type header for HTTP GET requests. But the specs does not seem to rule out a content-type header for HTTP GET, either.

Supporting materials:

  1. "Content-Type" is part of the representation (i.e. payload) metadata. Quoted from RFC 7231 section 3.1:

    3.1. Representation Metadata

    Representation header fields provide metadata about the representation. When a message includes a payload body, the representation header fields describe how to interpret the representation data enclosed in the payload body. ...

    The following header fields convey representation metadata:

    +-------------------+-----------------+
    | Header Field Name | Defined in...   |
    +-------------------+-----------------+
    | Content-Type      | Section 3.1.1.5 |
    | ...               | ...             |
    

    Quoted from RFC 7231 section 3.1.1.5(by the way, the current chosen answer had a typo in the section number):

    The "Content-Type" header field indicates the media type of the associated representation

  2. In that sense, a Content-Type header is not really about an HTTP GET request (or a POST or PUT request, for that matter). It is about the payload inside such a whatever request. So, if there will be no payload, there needs no Content-Type. In practice, some implementation went ahead and made that understandable assumption. Quoted from Adam's comment:

    "While ... the spec doesn't say you can't have Content-Type on a GET, .Net seems to enforce it in it's HttpClient. See this SO q&a."

  3. However, strictly speaking, the specs itself does not rule out the possibility of HTTP GET contains a payload. Quoted from RFC 7231 section 4.3.1:

    4.3.1 GET

    ...

    A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request.

    So, if your HTTP GET happens to include a payload for whatever reason, a Content-Type header is probably reasonable, too.

Java 8 lambdas, Function.identity() or t->t

In your example there is no big difference between str -> str and Function.identity() since internally it is simply t->t.

But sometimes we can't use Function.identity because we can't use a Function. Take a look here:

List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);

this will compile fine

int[] arrayOK = list.stream().mapToInt(i -> i).toArray();

but if you try to compile

int[] arrayProblem = list.stream().mapToInt(Function.identity()).toArray();

you will get compilation error since mapToInt expects ToIntFunction, which is not related to Function. Also ToIntFunction doesn't have identity() method.

How do I import material design library to Android Studio?

The latest as of release of API 23 is

compile 'com.android.support:design:23.2.1'

Oracle SQL: Use sequence in insert with Select Statement

I tested and the script run ok!

INSERT INTO HISTORICAL_CAR_STATS (HISTORICAL_CAR_STATS_ID, YEAR,MONTH,MAKE,MODEL,REGION,AVG_MSRP,COUNT) 
WITH DATA AS
(
    SELECT '2010' YEAR,'12' MONTH ,'ALL' MAKE,'ALL' MODEL,REGION,sum(AVG_MSRP*COUNT)/sum(COUNT) AVG_MSRP,sum(Count) COUNT
    FROM HISTORICAL_CAR_STATS
    WHERE YEAR = '2010' AND MONTH = '12'
    AND MAKE != 'ALL' GROUP BY REGION
)
SELECT MY_SEQ.NEXTVAL, YEAR,MONTH,MAKE,MODEL,REGION,AVG_MSRP,COUNT
FROM DATA;

you can read this article to understand more! http://www.orafaq.com/wiki/ORA-02287

using where and inner join in mysql

    SELECT `locations`.`name`
      FROM `locations`
INNER JOIN `school_locations`
        ON `locations`.`id` = `school_locations`.`location_id`
INNER JOIN `schools`
        ON `school_locations`.`school_id` = `schools_id`
     WHERE `type` = 'coun';

the WHERE clause has to be at the end of the statement

Put current changes in a new Git branch

You can simply check out a new branch, and then commit:

git checkout -b my_new_branch
git commit

Checking out the new branch will not discard your changes.

C99 stdint.h header and MS Visual Studio

Update: Visual Studio 2010 and Visual C++ 2010 Express both have stdint.h. It can be found in C:\Program Files\Microsoft Visual Studio 10.0\VC\include

Iterate over object keys in node.js

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

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

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

What is the difference between linear regression and logistic regression?

In case of Linear Regression the outcome is continuous while in case of Logistic Regression outcome is discrete (not continuous)

To perform Linear regression we require a linear relationship between the dependent and independent variables. But to perform Logistic regression we do not require a linear relationship between the dependent and independent variables.

Linear Regression is all about fitting a straight line in the data while Logistic Regression is about fitting a curve to the data.

Linear Regression is a regression algorithm for Machine Learning while Logistic Regression is a classification Algorithm for machine learning.

Linear regression assumes gaussian (or normal) distribution of dependent variable. Logistic regression assumes binomial distribution of dependent variable.

Tomcat 7 "SEVERE: A child container failed during start"

This same issue occurred for me and stack trace

SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[/XXXXSearch]]
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.util.concurrent.FutureTask.get(FutureTask.java:192)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:800)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[/XXXXSearch]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    ... 6 more
Caused by: java.lang.IllegalStateException: Unable to complete the scan for annotations for web application [/XXXXSearch]. Possible root causes include a too low setting for -Xss and illegal cyclic inheritance dependencies
    at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:2109)
    at org.apache.catalina.startup.ContextConfig.processAnnotationsJar(ContextConfig.java:1981)
    at org.apache.catalina.startup.ContextConfig.processAnnotationsUrl(ContextConfig.java:1947)
    at org.apache.catalina.startup.ContextConfig.processAnnotations(ContextConfig.java:1932)
    at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1326)
    at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:878)
    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:369)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5179)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more
Caused by: java.lang.StackOverflowError
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)
    at org.apache.catalina.startup.ContextConfig.populateSCIsForCacheEntry(ContextConfig.java:2269)

In my analysis what i found was, this issue is occurred when illegal cyclic inheritance dependencies caused for Tomcat startup annotation processing.

But my project had lot of dependency JARs, and couldn't found which one is responsible for this.

After trying so many unhappy approaches What i did was , I have updated my tomcat plugin to following and ran the same scenario,

<plugin>
    <groupId>org.apache.tomcat.maven</groupId>
    <artifactId>tomcat8-maven-plugin</artifactId>
    <version>3.0-r1756463</version>
<\plugin>

Then i was able to find which JAR is caused to this issue ,

Aug 23, 2017 2:32:12 PM org.apache.catalina.startup.ContextConfig processAnnotationsJar
SEVERE: Unable to process Jar entry [cryptix/test/TestLOKI91.class] from Jar [jar:file:/C:/Users/Tharinda/.m2/repository/cryptix/cryptix/1.2.2/cryptix-1.2.2.jar!/] for annotations
java.io.EOFException
    at org.apache.tomcat.util.bcel.classfile.FastDataInputStream.readUnsignedShort(FastDataInputStream.java:120)
    at org.apache.tomcat.util.bcel.classfile.ClassParser.readAttributes(ClassParser.java:110)
    at org.apache.tomcat.util.bcel.classfile.ClassParser.parse(ClassParser.java:94)
    at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:1994)
    at org.apache.catalina.startup.ContextConfig.processAnnotationsJar(ContextConfig.java:1944)
    at org.apache.catalina.startup.ContextConfig.processAnnotationsUrl(ContextConfig.java:1919)
    at org.apache.catalina.startup.ContextConfig.processAnnotations(ContextConfig.java:1880)
    at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1149)
    at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:771)
    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:305)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5120)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Then just solving the issue with cryptix-1.2.2.jar solved this problem.

I strongly recommend to move tomcat8-maven-plugin which seems stable and less buggy at the moment.

How to call a button click event from another method

Add it to the instance of the Click delegate:

ChildNode.Click += SubGraphButton_Click

which is inkeeping with the pattern .NET events follow (Observer).

How to get text of an element in Selenium WebDriver, without including child element text?

Unfortunately, Selenium was only built to work with Elements, not Text nodes.

If you try to use a function like get_element_by_xpath to target the text nodes, Selenium will throw an InvalidSelectorException.

One workaround is to grab the relevant HTML with Selenium and then use an HTML parsing library like BeautifulSoup that can handle text nodes more elegantly.

import bs4
from bs4 import BeautifulSoup

inner_html = driver.find_elements_by_css_selector('#a')[0].get_attribute("innerHTML")
inner_soup = BeautifulSoup(inner_html, 'html.parser')

outer_html = driver.find_elements_by_css_selector('#a')[0].get_attribute("outerHTML")
outer_soup = BeautifulSoup(outer_html, 'html.parser')

From there, there are several ways to search for the Text content. You'll have to experiment to see what works best for your use case.

Here's a simple one-liner that may be sufficient:

inner_soup.find(text=True)

If that doesn't work, then you can loop through the element's child nodes with .contents() and check their object type.

BeautifulSoup has four types of elements, and the one that you'll be interested in is the NavigableString type, which is produced by Text nodes. By contrast, Elements will have a type of Tag.

contents = inner_soup.contents

for bs4_object in contents:

    if (type(bs4_object) == bs4.Tag):
        print("This object is an Element.")

    elif (type(bs4_object) == bs4.NavigableString):
        print("This object is a Text node.")

Note that BeautifulSoup doesn't support Xpath expressions. If you need those, then you can use some of the workarounds in this thread.

Strange Jackson exception being thrown when serializing Hibernate object

i got the same error, but with no relation to Hibernate. I got scared here from all frightening suggestions, which i guess relevant in case of Hibernate and lazy loading... However, in my case i got the error since in an inner class i had no getters/setters, so the BeanSerializer could not serialize the data...

Adding getters & setters resolved the problem.

What is copy-on-write?

I was going to write up my own explanation but this Wikipedia article pretty much sums it up.

Here is the basic concept:

Copy-on-write (sometimes referred to as "COW") is an optimization strategy used in computer programming. The fundamental idea is that if multiple callers ask for resources which are initially indistinguishable, you can give them pointers to the same resource. This function can be maintained until a caller tries to modify its "copy" of the resource, at which point a true private copy is created to prevent the changes becoming visible to everyone else. All of this happens transparently to the callers. The primary advantage is that if a caller never makes any modifications, no private copy need ever be created.

Also here is an application of a common use of COW:

The COW concept is also used in maintenance of instant snapshot on database servers like Microsoft SQL Server 2005. Instant snapshots preserve a static view of a database by storing a pre-modification copy of data when underlaying data are updated. Instant snapshots are used for testing uses or moment-dependent reports and should not be used to replace backups.

How do I generate a stream from a string?

If you need to change the encoding I vote for @ShaunBowe's solution. But every answer here copies the whole string in memory at least once. The answers with ToCharArray + BlockCopy combo do it twice.

If that matters here is a simple Stream wrapper for the raw UTF-16 string. If used with a StreamReader select Encoding.Unicode for it:

public class StringStream : Stream
{
    private readonly string str;

    public override bool CanRead => true;
    public override bool CanSeek => true;
    public override bool CanWrite => false;
    public override long Length => str.Length * 2;
    public override long Position { get; set; } // TODO: bounds check

    public StringStream(string s) => str = s ?? throw new ArgumentNullException(nameof(s));

    public override long Seek(long offset, SeekOrigin origin)
    {
        switch (origin)
        {
            case SeekOrigin.Begin:
                Position = offset;
                break;
            case SeekOrigin.Current:
                Position += offset;
                break;
            case SeekOrigin.End:
                Position = Length - offset;
                break;
        }

        return Position;
    }

    private byte this[int i] => (i & 1) == 0 ? (byte)(str[i / 2] & 0xFF) : (byte)(str[i / 2] >> 8);

    public override int Read(byte[] buffer, int offset, int count)
    {
        // TODO: bounds check
        var len = Math.Min(count, Length - Position);
        for (int i = 0; i < len; i++)
            buffer[offset++] = this[(int)(Position++)];
        return (int)len;
    }

    public override int ReadByte() => Position >= Length ? -1 : this[(int)Position++];
    public override void Flush() { }
    public override void SetLength(long value) => throw new NotSupportedException();
    public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
    public override string ToString() => str; // ;)     
}

And here is a more complete solution with necessary bound checks (derived from MemoryStream so it has ToArray and WriteTo methods as well).

Add my custom http header to Spring RestTemplate request / extend RestTemplate

Here's a method I wrote to check if an URL exists or not. I had a requirement to add a request header. It's Groovy but should be fairly simple to adapt to Java. Essentially I'm using the org.springframework.web.client.RestTemplate#execute(java.lang.String, org.springframework.http.HttpMethod, org.springframework.web.client.RequestCallback, org.springframework.web.client.ResponseExtractor<T>, java.lang.Object...) API method. I guess the solution you arrive at depends at least in part on the HTTP method you want to execute. The key take away from example below is that I'm passing a Groovy closure (The third parameter to method restTemplate.execute(), which is more or less, loosely speaking a Lambda in Java world) that is executed by the Spring API as a callback to be able to manipulate the request object before Spring executes the command,

boolean isUrlExists(String url) {
    try {
      return (restTemplate.execute(url, HttpMethod.HEAD,
              { ClientHttpRequest request -> request.headers.add('header-name', 'header-value') },
              { ClientHttpResponse response -> response.headers }) as HttpHeaders)?.get('some-response-header-name')?.contains('some-response-header-value')
    } catch (Exception e) {
      log.warn("Problem checking if $url exists", e)
    }
    false
  }

Query to get the names of all tables in SQL Server 2008 Database

Try this:

SELECT s.NAME + '.' + t.NAME AS TableName
FROM sys.tables t
INNER JOIN sys.schemas s
    ON t.schema_id = s.schema_id

it will display the schema+table name for all tables in the current database.

Here is a version that will list every table in every database on the current server. it allows a search parameter to be used on any part or parts of the server+database+schema+table names:

SET NOCOUNT ON
DECLARE @AllTables table (CompleteTableName nvarchar(4000))
DECLARE @Search nvarchar(4000)
       ,@SQL   nvarchar(4000)
SET @Search=null --all rows
SET @SQL='select @@SERVERNAME+''.''+''?''+''.''+s.name+''.''+t.name from [?].sys.tables t inner join sys.schemas s on t.schema_id=s.schema_id WHERE @@SERVERNAME+''.''+''?''+''.''+s.name+''.''+t.name LIKE ''%'+ISNULL(@SEARCH,'')+'%'''

INSERT INTO @AllTables (CompleteTableName)
    EXEC sp_msforeachdb @SQL
SET NOCOUNT OFF
SELECT * FROM @AllTables ORDER BY 1

set @Search to NULL for all tables, set it to things like 'dbo.users' or 'users' or '.master.dbo' or even include wildcards like '.master.%.u', etc.

How to concatenate two IEnumerable<T> into a new IEnumerable<T>?

// The answer that I was looking for when searching
public void Answer()
{
    IEnumerable<YourClass> first = this.GetFirstIEnumerableList();
    // Assign to empty list so we can use later
    IEnumerable<YourClass> second = new List<YourClass>();

    if (IwantToUseSecondList)
    {
        second = this.GetSecondIEnumerableList();  
    }
    IEnumerable<SchemapassgruppData> concatedList = first.Concat(second);
}

SQL Query for Selecting Multiple Records

Try the following code:

SELECT *
FROM users
WHERE firstname IN ('joe','jane');

C# Regex for Guid

For C# .Net to find and replace any guid looking string from the given text,

Use this RegEx:

[({]?[a-fA-F0-9]{8}[-]?([a-fA-F0-9]{4}[-]?){3}[a-fA-F0-9]{12}[})]?

Example C# code:

var result = Regex.Replace(
      source, 
      @"[({]?[a-fA-F0-9]{8}[-]?([a-fA-F0-9]{4}[-]?){3}[a-fA-F0-9]{12}[})]?", 
      @"${ __UUID}", 
      RegexOptions.IgnoreCase
);

Surely works! And it matches & replaces the following styles, which are all equivalent and acceptable formats for a GUID.

"aa761232bd4211cfaacd00aa0057b243" 
"AA761232-BD42-11CF-AACD-00AA0057B243" 
"{AA761232-BD42-11CF-AACD-00AA0057B243}" 
"(AA761232-BD42-11CF-AACD-00AA0057B243)" 

How to free memory from char array in C

You don't free anything at all. Since you never acquired any resources dynamically, there is nothing you have to, or even are allowed to, free.

(It's the same as when you say int n = 10;: There are no dynamic resources involved that you have to manage manually.)

Make Vim show ALL white spaces as a character

If you set:

:highlight Search cterm=underline gui=underline ctermbg=none guibg=none ctermfg=none guifg=none

and then perform a search for a space, every space character will be shown as an underline character.

You can use this command in a handy function that toggles "underscoring" of spaces.

set hls
let g:HLSpace = 1
let g:HLColorScheme = g:colors_name
function ToggleSpaceUnderscoring()
    if g:HLSpace
        highlight Search cterm=underline gui=underline ctermbg=none guibg=none ctermfg=none guifg=none
        let @/ = " "
    else
        highlight clear
        silent colorscheme "".g:HLColorScheme
        let @/ = ""
    endif
    let g:HLSpace = !g:HLSpace
endfunction

Map the function to a shortcut key with:

nmap <silent> <F3> <Esc>:call ToggleSpaceUnderscoring()<CR>

NB: Define the function in vimrc after the colorscheme has been set.

Return the characters after Nth character in a string

Another formula option is to use REPLACE function to replace the first n characters with nothing, e.g. if n = 4

=REPLACE(A1,1,4,"")

Selenium IDE - Command to wait for 5 seconds

One that I've found works for the site I test is this one:

waitForCondition | selenium.browserbot.getUserWindow().$.active==0 | 20000

Klendathu

MVVM Passing EventArgs As Command Parameter

I've always come back here for the answer so I wanted to make a short simple one to go to.

There are multiple ways of doing this:

1. Using WPF Tools. Easiest.

Add Namespaces:

  • System.Windows.Interactivitiy
  • Microsoft.Expression.Interactions

XAML:

Use the EventName to call the event you want then specify your Method name in the MethodName.

<Window>
    xmlns:wi="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions">

    <wi:Interaction.Triggers>
        <wi:EventTrigger EventName="SelectionChanged">
            <ei:CallMethodAction
                TargetObject="{Binding}"
                MethodName="ShowCustomer"/>
        </wi:EventTrigger>
    </wi:Interaction.Triggers>
</Window>

Code:

public void ShowCustomer()
{
    // Do something.
}

2. Using MVVMLight. Most difficult.

Install GalaSoft NuGet package.

enter image description here

Get the namespaces:

  • System.Windows.Interactivity
  • GalaSoft.MvvmLight.Platform

XAML:

Use the EventName to call the event you want then specify your Command name in your binding. If you want to pass the arguments of the method, mark PassEventArgsToCommand to true.

<Window>
    xmlns:wi="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    xmlns:cmd="http://www.galasoft.ch/mvvmlight">

    <wi:Interaction.Triggers>
       <wi:EventTrigger EventName="Navigated">
           <cmd:EventToCommand Command="{Binding CommandNameHere}"
               PassEventArgsToCommand="True" />
       </wi:EventTrigger>
    </wi:Interaction.Triggers>
</Window>

Code Implementing Delegates: Source

You must get the Prism MVVM NuGet package for this.

enter image description here

using Microsoft.Practices.Prism.Commands;

// With params.
public DelegateCommand<string> CommandOne { get; set; }
// Without params.
public DelegateCommand CommandTwo { get; set; }

public MainWindow()
{
    InitializeComponent();

    // Must initialize the DelegateCommands here.
    CommandOne = new DelegateCommand<string>(executeCommandOne);
    CommandTwo = new DelegateCommand(executeCommandTwo);
}

private void executeCommandOne(string param)
{
    // Do something here.
}

private void executeCommandTwo()
{
    // Do something here.
}

Code Without DelegateCommand: Source

using GalaSoft.MvvmLight.CommandWpf

public MainWindow()
{
    InitializeComponent();

    CommandOne = new RelayCommand<string>(executeCommandOne);
    CommandTwo = new RelayCommand(executeCommandTwo);
}

public RelayCommand<string> CommandOne { get; set; }

public RelayCommand CommandTwo { get; set; }

private void executeCommandOne(string param)
{
    // Do something here.
}

private void executeCommandTwo()
{
    // Do something here.
}

3. Using Telerik EventToCommandBehavior. It's an option.

You'll have to download it's NuGet Package.

XAML:

<i:Interaction.Behaviors>
    <telerek:EventToCommandBehavior
         Command="{Binding DropCommand}"
         Event="Drop"
         PassArguments="True" />
</i:Interaction.Behaviors>

Code:

public ActionCommand<DragEventArgs> DropCommand { get; private set; }

this.DropCommand = new ActionCommand<DragEventArgs>(OnDrop);

private void OnDrop(DragEventArgs e)
{
    // Do Something
}

Switching to a TabBar tab view programmatically?

My issue is a little different, I need to switch from one childViewController in 1st tabBar to home viewController of 2nd tabBar. I simply use the solution provided in the upstairs:

tabBarController.selectedIndex = 2

However when it switched to the home page of 2nd tabBar, the content is invisible. And when I debug, viewDidAppear, viewWillAppear, viewDidLoad, none of them is called. My solutions is to add the following code in the UITabBarController:

override var shouldAutomaticallyForwardAppearanceMethods: Bool 
{
    return true
}

How to set thymeleaf th:field value from other variable

You could approach this method.

Instead of using th:field use html id & name. Set value using th:value

<input class="form-control"
           type="text"
           th:value="${client.name}" id="clientName" name="clientName" />

Hope this will help you

Print values for multiple variables on the same line from within a for-loop

As an additional note, there is no need for the for loop because of R's vectorization.

This:

P <- 243.51
t <- 31 / 365
n <- 365

for (r in seq(0.15, 0.22, by = 0.01))    
     A <- P * ((1 + (r/ n))^ (n * t))
     interest <- A - P
}

is equivalent to:

P <- 243.51
t <- 31 / 365
n <- 365
r <- seq(0.15, 0.22, by = 0.01)
A <- P * ((1 + (r/ n))^ (n * t))
interest <- A - P

Because r is a vector, the expression above containing it is performed for all values of the vector.

New Array from Index Range Swift

#1. Using Array subscript with range

With Swift 5, when you write…

let newNumbers = numbers[0...position]

newNumbers is not of type Array<Int> but is of type ArraySlice<Int>. That's because Array's subscript(_:?) returns an ArraySlice<Element> that, according to Apple, presents a view onto the storage of some larger array.

Besides, Swift also provides Array an initializer called init(_:?) that allows us to create a new array from a sequence (including ArraySlice).

Therefore, you can use subscript(_:?) with init(_:?) in order to get a new array from the first n elements of an array:

let array = Array(10...14) // [10, 11, 12, 13, 14]
let arraySlice = array[0..<3] // using Range
//let arraySlice = array[0...2] // using ClosedRange also works
//let arraySlice = array[..<3] // using PartialRangeUpTo also works
//let arraySlice = array[...2] // using PartialRangeThrough also works
let newArray = Array(arraySlice)
print(newArray) // prints [10, 11, 12]

#2. Using Array's prefix(_:) method

Swift provides a prefix(_:) method for types that conform to Collection protocol (including Array). prefix(_:) has the following declaration:

func prefix(_ maxLength: Int) -> ArraySlice<Element>

Returns a subsequence, up to maxLength in length, containing the initial elements.

Apple also states:

If the maximum length exceeds the number of elements in the collection, the result contains all the elements in the collection.

Therefore, as an alternative to the previous example, you can use the following code in order to create a new array from the first elements of another array:

let array = Array(10...14) // [10, 11, 12, 13, 14]
let arraySlice = array.prefix(3)
let newArray = Array(arraySlice)
print(newArray) // prints [10, 11, 12]

How to draw a custom UIView that is just a circle - iPhone app

Swift 3 class:

import UIKit

class CircleView: UIView {

    override func draw(_ rect: CGRect) {
        guard let context = UIGraphicsGetCurrentContext() else {return}
        
        context.addEllipse(in: rect)
        context.setFillColor(UIColor.blue.cgColor)
        context.fillPath()
    }           
}

Spring .properties file: get element as an Array

If you define your array in properties file like:

base.module.elementToSearch=1,2,3,4,5,6

You can load such array in your Java class like this:

  @Value("${base.module.elementToSearch}")
  private String[] elementToSearch;

How to correctly link php-fpm and Nginx Docker containers?

New Answer

Docker Compose has been updated. They now have a version 2 file format.

Version 2 files are supported by Compose 1.6.0+ and require a Docker Engine of version 1.10.0+.

They now support the networking feature of Docker which when run sets up a default network called myapp_default

From their documentation your file would look something like the below:

version: '2'

services:
  web:
    build: .
    ports:
      - "8000:8000"
  fpm:
    image: phpfpm
  nginx
    image: nginx

As these containers are automatically added to the default myapp_default network they would be able to talk to each other. You would then have in the Nginx config:

fastcgi_pass fpm:9000;

Also as mentioned by @treeface in the comments remember to ensure PHP-FPM is listening on port 9000, this can be done by editing /etc/php5/fpm/pool.d/www.conf where you will need listen = 9000.

Old Answer

I have kept the below here for those using older version of Docker/Docker compose and would like the information.

I kept stumbling upon this question on google when trying to find an answer to this question but it was not quite what I was looking for due to the Q/A emphasis on docker-compose (which at the time of writing only has experimental support for docker networking features). So here is my take on what I have learnt.

Docker has recently deprecated its link feature in favour of its networks feature

Therefore using the Docker Networks feature you can link containers by following these steps. For full explanations on options read up on the docs linked previously.

First create your network

docker network create --driver bridge mynetwork

Next run your PHP-FPM container ensuring you open up port 9000 and assign to your new network (mynetwork).

docker run -d -p 9000 --net mynetwork --name php-fpm php:fpm

The important bit here is the --name php-fpm at the end of the command which is the name, we will need this later.

Next run your Nginx container again assign to the network you created.

docker run --net mynetwork --name nginx -d -p 80:80 nginx:latest

For the PHP and Nginx containers you can also add in --volumes-from commands etc as required.

Now comes the Nginx configuration. Which should look something similar to this:

server {
    listen 80;
    server_name localhost;

    root /path/to/my/webroot;

    index index.html index.htm index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass php-fpm:9000; 
        fastcgi_index index.php;
        include fastcgi_params;
    }
}

Notice the fastcgi_pass php-fpm:9000; in the location block. Thats saying contact container php-fpm on port 9000. When you add containers to a Docker bridge network they all automatically get a hosts file update which puts in their container name against their IP address. So when Nginx sees that it will know to contact the PHP-FPM container you named php-fpm earlier and assigned to your mynetwork Docker network.

You can add that Nginx config either during the build process of your Docker container or afterwards its up to you.

How do you display JavaScript datetime in 12 hour AM/PM format?

Please find the solution below

var d = new Date();
var amOrPm = (d.getHours() < 12) ? "AM" : "PM";
var hour = (d.getHours() < 12) ? d.getHours() : d.getHours() - 12;
return   d.getDate() + ' / ' + d.getMonth() + ' / ' + d.getFullYear() + ' ' + hour + ':' + d.getMinutes() + ' ' + amOrPm;

Uncaught TypeError: Cannot read property 'top' of undefined

I had the same problem ("Uncaught TypeError: Cannot read property 'top' of undefined")

I tried every solution I could find and noting helped. But then I've spotted that my DIV had two IDs.

So, I removed second ID and it worked.

I just wish somebody told me to check my IDs earlier))

Difference between angle bracket < > and double quotes " " while including header files in C++?

It's compiler dependent. That said, in general using " prioritizes headers in the current working directory over system headers. <> usually is used for system headers. From to the specification (Section 6.10.2):

A preprocessing directive of the form

  # include <h-char-sequence> new-line

searches a sequence of implementation-defined places for a header identified uniquely by the specified sequence between the < and > delimiters, and causes the replacement of that directive by the entire contents of the header. How the places are specified or the header identified is implementation-defined.

A preprocessing directive of the form

  # include "q-char-sequence" new-line

causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters. The named source file is searched for in an implementation-defined manner. If this search is not supported, or if the search fails, the directive is reprocessed as if it read

  # include <h-char-sequence> new-line

with the identical contained sequence (including > characters, if any) from the original directive.

So on most compilers, using the "" first checks your local directory, and if it doesn't find a match then moves on to check the system paths. Using <> starts the search with system headers.

How to move the layout up when the soft keyboard is shown android

When the softkeyboard appears, it changes the size of main layout, and what you need do is to make a listener for that mainlayout and within that listener, add the code scrollT0(x,y) to scroll up.

Cannot find name 'require' after upgrading to Angular4

Will work in Angular 7+


I was facing the same issue, I was adding

"types": ["node"]

to tsconfig.json of root folder.

There was one more tsconfig.app.json under src folder and I got solved this by adding

"types": ["node"]

to tsconfig.app.json file under compilerOptions

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "types": ["node"]  ----------------------< added node to the array
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ]
}

Generate random string/characters in JavaScript

Assuming you use underscorejs it's possible to elegantly generate random string in just two lines:

var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var random = _.sample(possible, 5).join('');

linux: kill background task

There's a special variable for this in bash:

kill $!

$! expands to the PID of the last process executed in the background.

What does "both" mean in <div style="clear:both">

Both means "every item in a set of two things". The two things being "left" and "right"

Integer division with remainder in JavaScript?

Calculating number of pages may be done in one step: Math.ceil(x/y)

mysql alphabetical order

MySQL solution:

select Name from Employee order by Name ;

Order by will order the names from a to z.

PHP case-insensitive in_array function

you can use preg_grep():

$a= array(
 'one',
 'two',
 'three',
 'four'
);

print_r( preg_grep( "/ONe/i" , $a ) );

Warning: #1265 Data truncated for column 'pdd' at row 1

As the message error says, you need to Increase the length of your column to fit the length of the data you are trying to insert (0000-00-00)

EDIT 1:

Following your comment, I run a test table:

mysql> create table testDate(id int(2) not null auto_increment, pdd date default null, primary key(id));
Query OK, 0 rows affected (0.20 sec)

Insertion:

mysql> insert into testDate values(1,'0000-00-00');
Query OK, 1 row affected (0.06 sec)

EDIT 2:

So, aparently you want to insert a NULL value to pdd field as your comment states ? You can do that in 2 ways like this:

Method 1:

mysql> insert into testDate values(2,'');
Query OK, 1 row affected, 1 warning (0.06 sec)

Method 2:

mysql> insert into testDate values(3,NULL);
Query OK, 1 row affected (0.07 sec)

EDIT 3:

You failed to change the default value of pdd field. Here is the syntax how to do it (in my case, I set it to NULL in the start, now I will change it to NOT NULL)

mysql> alter table testDate modify pdd date not null;
Query OK, 3 rows affected, 1 warning (0.60 sec)
Records: 3  Duplicates: 0  Warnings: 1

What's the best way to determine the location of the current PowerShell script?

Maybe I'm missing something here... but if you want the present working directory you can just use this: (Get-Location).Path for a string, or Get-Location for an object.

Unless you're referring to something like this, which I understand after reading the question again.

function Get-Script-Directory
{
    $scriptInvocation = (Get-Variable MyInvocation -Scope 1).Value
    return Split-Path $scriptInvocation.MyCommand.Path
}

How to remove a character at the end of each line in unix

This Perl code removes commas at the end of the line:

perl -pe 's/,$//' file > file.nocomma

This variation still works if there is whitespace after the comma:

perl -lpe 's/,\s*$//' file > file.nocomma

This variation edits the file in-place:

perl -i -lpe 's/,\s*$//' file

This variation edits the file in-place, and makes a backup file.bak:

perl -i.bak -lpe 's/,\s*$//' file

All possible array initialization syntaxes

Enumerable.Repeat(String.Empty, count).ToArray()

Will create array of empty strings repeated 'count' times. In case you want to initialize array with same yet special default element value. Careful with reference types, all elements will refer same object.

Conditional HTML Attributes using Razor MVC3

You didn't hear it from me, the PM for Razor, but in Razor 2 (Web Pages 2 and MVC 4) we'll have conditional attributes built into Razor(as of MVC 4 RC tested successfully), so you can just say things like this...

<input type="text" id="@strElementID" class="@strCSSClass" />

If strCSSClass is null then the class attribute won't render at all.

SSSHHH...don't tell. :)

modal View controllers - how to display and dismiss

I wanted this:

MapVC is a Map in full screen.

When I press a button, it opens PopupVC (not in full screen) above the map.

When I press a button in PopupVC, it returns to MapVC, and then I want to execute viewDidAppear.

I did this:

MapVC.m: in the button action, a segue programmatically, and set delegate

- (void) buttonMapAction{
   PopupVC *popvc = [self.storyboard instantiateViewControllerWithIdentifier:@"popup"];
   popvc.delegate = self;
   [self presentViewController:popvc animated:YES completion:nil];
}

- (void)dismissAndPresentMap {
  [self dismissViewControllerAnimated:NO completion:^{
    NSLog(@"dismissAndPresentMap");
    //When returns of the other view I call viewDidAppear but you can call to other functions
    [self viewDidAppear:YES];
  }];
}

PopupVC.h: before @interface, add the protocol

@protocol PopupVCProtocol <NSObject>
- (void)dismissAndPresentMap;
@end

after @interface, a new property

@property (nonatomic,weak) id <PopupVCProtocol> delegate;

PopupVC.m:

- (void) buttonPopupAction{
  //jump to dismissAndPresentMap on Map view
  [self.delegate dismissAndPresentMap];
}

PHP - concatenate or directly insert variables in string

Do not concatenate. It's not needed, us commas as echo can take multiple parameters

echo "Welcome ", $name, "!";

Regarding using single or double quotes the difference is negligible, you can do tests with large numbers of strings to test for yourself.

Determining Referer in PHP

The REFERER is sent by the client's browser as part of the HTTP protocol, and is therefore unreliable indeed. It might not be there, it might be forged, you just can't trust it if it's for security reasons.

If you want to verify if a request is coming from your site, well you can't, but you can verify the user has been to your site and/or is authenticated. Cookies are sent in AJAX requests so you can rely on that.

SQL Server table creation date query

For SQL Server 2005 upwards:

SELECT [name] AS [TableName], [create_date] AS [CreatedDate] FROM sys.tables

For SQL Server 2000 upwards:

SELECT so.[name] AS [TableName], so.[crdate] AS [CreatedDate]
FROM INFORMATION_SCHEMA.TABLES AS it, sysobjects AS so 
WHERE it.[TABLE_NAME] = so.[name]

Spark - repartition() vs coalesce()

One additional point to note here is that, as the basic principle of Spark RDD is immutability. The repartition or coalesce will create new RDD. The base RDD will continue to have existence with its original number of partitions. In case the use case demands to persist RDD in cache, then the same has to be done for the newly created RDD.

scala> pairMrkt.repartition(10)
res16: org.apache.spark.rdd.RDD[(String, Array[String])] =MapPartitionsRDD[11] at repartition at <console>:26

scala> res16.partitions.length
res17: Int = 10

scala>  pairMrkt.partitions.length
res20: Int = 2

window.location.reload with clear cache

In my case reload() doesn't work because the asp.net controls behavior. So, to solve this issue I've used this approach, despite seems a work around.

self.clear = function () {
    //location.reload(true); Doesn't work to IE neither Firefox;
    //also, hash tags must be removed or no postback will occur.
    window.location.href = window.location.href.replace(/#.*$/, '');
};

How to .gitignore all files/folder in a folder, but not the folder itself?

You can't commit empty folders in git. If you want it to show up, you need to put something in it, even just an empty file.

For example, add an empty file called .gitkeep to the folder you want to keep, then in your .gitignore file write:

# exclude everything
somefolder/*

# exception to the rule
!somefolder/.gitkeep 

Commit your .gitignore and .gitkeep files and this should resolve your issue.

element with the max height from a set of elements

_x000D_
_x000D_
ul, li {_x000D_
  list-style: none;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
ul {_x000D_
  display: flex;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
ul li {_x000D_
  width: calc(100% / 3);_x000D_
}_x000D_
_x000D_
img {_x000D_
  width: 100%;_x000D_
  height: auto;_x000D_
}
_x000D_
<ul>_x000D_
  <li>_x000D_
    <img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_sddu7-2560x1600.jpg" alt="">_x000D_
    <br> Line 1_x000D_
    <br> Line 2_x000D_
  </li>_x000D_
  <li>_x000D_
    <img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_mixwall66-2560x1600.jpg" alt="">_x000D_
    <br> Line 1_x000D_
    <br> Line 2_x000D_
    <br> Line 3_x000D_
    <br> Line 4_x000D_
  </li>_x000D_
  <li>_x000D_
    <img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_sddu7-2560x1600.jpg" alt="">_x000D_
    <br> Line 1_x000D_
  </li>_x000D_
  <li>_x000D_
    <img src="http://img2.vetton.ru//upl/1000/346/138/vetton_ru_mixwall66-2560x1600.jpg" alt="">_x000D_
    <br> Line 1_x000D_
    <br> Line 2_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Origin http://localhost is not allowed by Access-Control-Allow-Origin

You've got two ways to go forward:

JSONP


If this API supports JSONP, the easiest way to fix this issue is to add &callback to the end of the URL. You can also try &callback=. If that doesn't work, it means the API does not support JSONP, so you must try the other solution.

Proxy Script


You can create a proxy script on the same domain as your website in order to avoid the cross-origin issues. This will only work with HTTP URLs, not HTTPS URLs, but it shouldn't be too difficult to modify if you need that.

<?php
// File Name: proxy.php
if (!isset($_GET['url'])) {
    die(); // Don't do anything if we don't have a URL to work with
}
$url = urldecode($_GET['url']);
$url = 'http://' . str_replace('http://', '', $url); // Avoid accessing the file system
echo file_get_contents($url); // You should probably use cURL. The concept is the same though

Then you just call this script with jQuery. Be sure to urlencode the URL.

$.ajax({
    url      : 'proxy.php?url=http%3A%2F%2Fapi.master18.tiket.com%2Fsearch%2Fautocomplete%2Fhotel%3Fq%3Dmah%26token%3D90d2fad44172390b11527557e6250e50%26secretkey%3D83e2f0484edbd2ad6fc9888c1e30ea44%26output%3Djson',
    type     : 'GET',
    dataType : 'json'
}).done(function(data) {
    console.log(data.results.result[1].category); // Do whatever you want here
});

The Why


You're getting this error because of XMLHttpRequest same origin policy, which basically boils down to a restriction of ajax requests to URLs with a different port, domain or protocol. This restriction is in place to prevent cross-site scripting (XSS) attacks.

More Information

Our solutions by pass these problems in different ways.

JSONP uses the ability to point script tags at JSON (wrapped in a javascript function) in order to receive the JSON. The JSONP page is interpreted as javascript, and executed. The JSON is passed to your specified function.

The proxy script works by tricking the browser, as you're actually requesting a page on the same origin as your page. The actual cross-origin requests happen server-side.

error: This is probably not a problem with npm. There is likely additional logging output above

Delete your package-lock.json file and node_modules folder. Then do npm cache clean

npm cache clean --force

do npm install

again and run

creating custom tableview cells in swift

Last Updated Version is with xCode 6.1

class StampInfoTableViewCell: UITableViewCell{


@IBOutlet weak var stampDate: UILabel!
@IBOutlet weak var numberText: UILabel!


override init?(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
}

required init(coder aDecoder: NSCoder) {
    //fatalError("init(coder:) has not been implemented")
    super.init(coder: aDecoder)
}

override func awakeFromNib() {
    super.awakeFromNib()
}

override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
}
}

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>

Objective-C: Extract filename from path string

If you're displaying a user-readable file name, you do not want to use lastPathComponent. Instead, pass the full path to NSFileManager's displayNameAtPath: method. This basically does does the same thing, only it correctly localizes the file name and removes the extension based on the user's preferences.

Check if a record exists in the database

You can write as follows:

SqlCommand check_User_Name = new SqlCommand("SELECT * FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "') ", conn);
if (check_User_Name.ExecuteScalar()!=null)
{
    int UserExist = (int)check_User_Name.ExecuteScalar();
    if (UserExist > 0)
    {
        //Username Exist
    }
}

How to retrieve raw post data from HttpServletRequest in java

We had a situation where IE forced us to post as text/plain, so we had to manually parse the parameters using getReader. The servlet was being used for long polling, so when AsyncContext::dispatch was executed after a delay, it was literally reposting the request empty handed.

So I just stored the post in the request when it first appeared by using HttpServletRequest::setAttribute. The getReader method empties the buffer, where getParameter empties the buffer too but stores the parameters automagically.

    String input = null;

    // we have to store the string, which can only be read one time, because when the
    // servlet awakens an AsyncContext, it reposts the request and returns here empty handed
    if ((input = (String) request.getAttribute("com.xp.input")) == null) {
        StringBuilder buffer = new StringBuilder();
        BufferedReader reader = request.getReader();

        String line;
        while((line = reader.readLine()) != null){
            buffer.append(line);
        }
        // reqBytes = buffer.toString().getBytes();

        input = buffer.toString();
        request.setAttribute("com.xp.input", input);
    }

    if (input == null) {
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        out.print("{\"act\":\"fail\",\"msg\":\"invalid\"}");
    }       

Creating a div element in jQuery

If it is just an empty div, this is sufficient:

$("#foo").append("<div>")

or

$("#foo").append("<div/>")

It gives the same result.

How to frame two for loops in list comprehension python

This should do it:

[entry for tag in tags for entry in entries if tag in entry]

java.util.Date and getYear()

Don't use Date, use Calendar:

// Beware: months are zero-based and no out of range errors are reported
Calendar date = new GregorianCalendar(2012, 9, 5);
int year = date.get(Calendar.YEAR);  // 2012
int month = date.get(Calendar.MONTH);  // 9 - October!!!
int day = date.get(Calendar.DAY_OF_MONTH);  // 5

It supports time as well:

Calendar dateTime = new GregorianCalendar(2012, 3, 4, 15, 16, 17);
int hour = dateTime.get(Calendar.HOUR_OF_DAY);  // 15
int minute = dateTime.get(Calendar.MINUTE);  // 16
int second = dateTime.get(Calendar.SECOND);  // 17

data type not understood

Try:

mmatrix = np.zeros((nrows, ncols))

Since the shape parameter has to be an int or sequence of ints

http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html

Otherwise you are passing ncols to np.zeros as the dtype.

Centering a Twitter Bootstrap button

If you don't mind a bit more markup, this would work:

<div class="centered">
    <button class="btn btn-large btn-primary" type="button">Submit</button>
</div>

With the corresponding CSS rule:

.centered
{
    text-align:center;
}

I have to look at the CSS rules for the btn class, but I don't think it specifies a width, so auto left & right margins wouldn't work. If you added one of the span or input- rules to the button, auto margins would work, though.

Edit:

Confirmed my initial thought; the btn classes do not have a width defined, so you can't use auto side margins. Also, as @AndrewM notes, you could simply use the text-center class instead of creating a new ruleset.

Animate background image change with jQuery

building on XGreen's approach above, with a few tweaks you can have an animated looping background. See here for example:

http://jsfiddle.net/srd76/36/

$(document).ready(function(){

var images = Array("http://placekitten.com/500/200",
               "http://placekitten.com/499/200",
               "http://placekitten.com/501/200",
               "http://placekitten.com/500/199");
var currimg = 0;


function loadimg(){

   $('#background').animate({ opacity: 1 }, 500,function(){

        //finished animating, minifade out and fade new back in           
        $('#background').animate({ opacity: 0.7 }, 100,function(){

            currimg++;

            if(currimg > images.length-1){

                currimg=0;

            }

            var newimage = images[currimg];

            //swap out bg src                
            $('#background').css("background-image", "url("+newimage+")"); 

            //animate fully back in
            $('#background').animate({ opacity: 1 }, 400,function(){

                //set timer for next
                setTimeout(loadimg,5000);

            });

        });

    });

  }
  setTimeout(loadimg,5000);

});

How to print a date in a regular format?

The date, datetime, and time objects all support a strftime(format) method, to create a string representing the time under the control of an explicit format string.

Here is a list of the format codes with their directive and meaning.

    %a  Locale’s abbreviated weekday name.
    %A  Locale’s full weekday name.      
    %b  Locale’s abbreviated month name.     
    %B  Locale’s full month name.
    %c  Locale’s appropriate date and time representation.   
    %d  Day of the month as a decimal number [01,31].    
    %f  Microsecond as a decimal number [0,999999], zero-padded on the left
    %H  Hour (24-hour clock) as a decimal number [00,23].    
    %I  Hour (12-hour clock) as a decimal number [01,12].    
    %j  Day of the year as a decimal number [001,366].   
    %m  Month as a decimal number [01,12].   
    %M  Minute as a decimal number [00,59].      
    %p  Locale’s equivalent of either AM or PM.
    %S  Second as a decimal number [00,61].
    %U  Week number of the year (Sunday as the first day of the week)
    %w  Weekday as a decimal number [0(Sunday),6].   
    %W  Week number of the year (Monday as the first day of the week)
    %x  Locale’s appropriate date representation.    
    %X  Locale’s appropriate time representation.    
    %y  Year without century as a decimal number [00,99].    
    %Y  Year with century as a decimal number.   
    %z  UTC offset in the form +HHMM or -HHMM.
    %Z  Time zone name (empty string if the object is naive).    
    %%  A literal '%' character.

This is what we can do with the datetime and time modules in Python

    import time
    import datetime

    print "Time in seconds since the epoch: %s" %time.time()
    print "Current date and time: ", datetime.datetime.now()
    print "Or like this: ", datetime.datetime.now().strftime("%y-%m-%d-%H-%M")


    print "Current year: ", datetime.date.today().strftime("%Y")
    print "Month of year: ", datetime.date.today().strftime("%B")
    print "Week number of the year: ", datetime.date.today().strftime("%W")
    print "Weekday of the week: ", datetime.date.today().strftime("%w")
    print "Day of year: ", datetime.date.today().strftime("%j")
    print "Day of the month : ", datetime.date.today().strftime("%d")
    print "Day of week: ", datetime.date.today().strftime("%A")

That will print out something like this:

    Time in seconds since the epoch:    1349271346.46
    Current date and time:              2012-10-03 15:35:46.461491
    Or like this:                       12-10-03-15-35
    Current year:                       2012
    Month of year:                      October
    Week number of the year:            40
    Weekday of the week:                3
    Day of year:                        277
    Day of the month :                  03
    Day of week:                        Wednesday

How do I select between the 1st day of the current month and current day in MySQL?

The key here is to get the first day of the month. For that, there are several options. In terms of performance, our tests show that there isn't a significant difference between them - we wrote a whole blog article on the topic. Our findings show that what really matters is whether you need the result to be VARCHAR, DATETIME, or DATE.

The fastest solution to the real problem of getting the first day of the month returns VARCHAR:

SELECT CONCAT(LEFT(CURRENT_DATE, 7), '-01') AS first_day_of_month;

The second fastest solution gives a DATETIME result - this runs about 3x slower than the previous:

SELECT TIMESTAMP(CONCAT(LEFT(CURRENT_DATE, 7), '-01')) AS first_day_of_month;

The slowest solutions return DATE objects. Don't believe me? Run this SQL Fiddle and see for yourself

In your case, since you need to compare the value with other DATE values in your table, it doesn't really matter what methodology you use because MySQL will do the conversion implicitly even if your formula doesn't return a DATE object.

So really, take your pick. Which is most readable for you? I'd pick the first since it's the shortest and arguably the simplest:

SELECT * FROM table_name 
WHERE date BETWEEN CONCAT(LEFT(CURRENT_DATE, 7), '-01') AND CURDATE;

SELECT * FROM table_name 
WHERE date BETWEEN DATE(CONCAT(LEFT(CURRENT_DATE, 7), '-01')) AND CURDATE;

SELECT * FROM table_name 
WHERE date BETWEEN (LAST_DAY(CURRENT_DATE) + INTERVAL 1 DAY - INTERVAL 1 MONTH) AND CURDATE;

SELECT * FROM table_name 
WHERE date BETWEEN (DATE(CURRENT_DATE) - INTERVAL (DAYOFMONTH(CURRENT_DATE) - 1) DAY) AND CURDATE;

SELECT * FROM table_name 
WHERE date BETWEEN (DATE(CURRENT_DATE) - INTERVAL (DAYOFMONTH(CURRENT_DATE)) DAY + INTERVAL 1 DAY) AND CURDATE;

SELECT * FROM table_name 
WHERE date BETWEEN DATE_FORMAT(CURRENT_DATE,'%Y-%m-01') AND CURDATE;

Trigger a Travis-CI rebuild without pushing a commit?

Log in to Travis and go to the build page. You will see a "Restart Build" button on the top-right corner, next to the gear icon:

screengrab

Note: you need to have write access to the linked GitHub repo for this to work.

MySQL limit from descending order

Let's say we have a table with a column time and you want the last 5 entries, but you want them returned to you in asc order, not desc, this is how you do it:

select * from ( select * from `table` order by `time` desc limit 5 ) t order by `time` asc

How do I make an asynchronous GET request in PHP?

Here is my own PHP function when I do POST to a specific URL of any page....

Sample: * usage of my Function...

<?php
    parse_str("[email protected]&subject=this is just a test");
    $_POST['email']=$email;
    $_POST['subject']=$subject;
    echo HTTP_Post("http://example.com/mail.php",$_POST);***

    exit;
?>
<?php
    /*********HTTP POST using FSOCKOPEN **************/
    // by ArbZ

    function HTTP_Post($URL,$data, $referrer="") {

    // parsing the given URL
    $URL_Info=parse_url($URL);

    // Building referrer
    if($referrer=="") // if not given use this script as referrer
      $referrer=$_SERVER["SCRIPT_URI"];

    // making string from $data
    foreach($data as $key=>$value)
      $values[]="$key=".urlencode($value);
    $data_string=implode("&",$values);

    // Find out which port is needed - if not given use standard (=80)
    if(!isset($URL_Info["port"]))
      $URL_Info["port"]=80;

    // building POST-request: HTTP_HEADERs
    $request.="POST ".$URL_Info["path"]." HTTP/1.1\n";
    $request.="Host: ".$URL_Info["host"]."\n";
    $request.="Referer: $referer\n";
    $request.="Content-type: application/x-www-form-urlencoded\n";
    $request.="Content-length: ".strlen($data_string)."\n";
    $request.="Connection: close\n";
    $request.="\n";
    $request.=$data_string."\n";

    $fp = fsockopen($URL_Info["host"],$URL_Info["port"]);
    fputs($fp, $request);
    while(!feof($fp)) {
        $result .= fgets($fp, 128);
    }
    fclose($fp); //$eco = nl2br();

    function getTextBetweenTags($string, $tagname) {
        $pattern = "/<$tagname ?.*>(.*)<\/$tagname>/";
        preg_match($pattern, $string, $matches);
        return $matches[1]; }
    //STORE THE FETCHED CONTENTS to a VARIABLE, because its way better and fast...
    $str = $result;
    $txt = getTextBetweenTags($str, "span"); $eco = $txt;  $result = explode("&",$result);
    return $result[1];
<span style=background-color:LightYellow;color:blue>".trim($_GET['em'])."</span>
</pre> "; 
}
</pre>

How to specify a editor to open crontab file? "export EDITOR=vi" does not work

Very probable that your VISUAL environment variable is set to something else. Try:

export VISUAL=vi

How can I switch to a tag/branch in hg?

Once you have cloned the repo, you have everything: you can then hg up branchname or hg up tagname to update your working copy.

UP: hg up is a shortcut of hg update, which also has hg checkout alias for people with git habits.

How to avoid pressing Enter with getchar() for reading a single character only?

yes you can do this on windows too, here's the code below, using the conio.h library

#include <iostream> //basic input/output
#include <conio.h>  //provides non standard getch() function
using namespace std;

int main()
{  
  cout << "Password: ";  
  string pass;
  while(true)
  {
             char ch = getch();    

             if(ch=='\r'){  //when a carriage return is found [enter] key
             cout << endl << "Your password is: " << pass <<endl; 
             break;
             }

             pass+=ch;             
             cout << "*";
             }
  getch();
  return 0;
}

What is the difference between HAVING and WHERE in SQL?

HAVING specifies a search condition for a group or an aggregate function used in SELECT statement.

Source

How to replace a character with a newline in Emacs?

There are four ways I've found to put a newline into the minibuffer.

  1. C-o

  2. C-q C-j

  3. C-q 12 (12 is the octal value of newline)

  4. C-x o to the main window, kill a newline with C-k, then C-x o back to the minibuffer, yank it with C-y

Console logging for react?

If you want to log inside JSX you can create a dummy component
which plugs where you wish to log:

_x000D_
_x000D_
const Console = prop => (
  console[Object.keys(prop)[0]](...Object.values(prop))
  ,null // ? React components must return something 
)

// Some component with JSX and a logger inside
const App = () => 
  <div>
    <p>imagine this is some component</p>
    <Console log='foo' />
    <p>imagine another component</p>
    <Console warn='bar' />
  </div>

// Render 
ReactDOM.render(
  <App />,
  document.getElementById("react")
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>
_x000D_
_x000D_
_x000D_

Clear dropdownlist with JQuery

Just use .empty():

// snip...
}).done(function (data) {
    // Clear drop down list
    $(dropdown).empty(); // <<<<<< No more issue here
    // Fill drop down list with new data
    $(data).each(function () {
        // snip...

There's also a more concise way to build up the options:

// snip...
$(data).each(function () {
    $("<option />", {
        val: this.value,
        text: this.text
    }).appendTo(dropdown);
});

How to upload a file in Django?

I also had the similar requirement. Most of the examples on net are asking to create models and create forms which I did not wanna use. Here is my final code.

if request.method == 'POST':
    file1 = request.FILES['file']
    contentOfFile = file1.read()
    if file1:
        return render(request, 'blogapp/Statistics.html', {'file': file1, 'contentOfFile': contentOfFile})

And in HTML to upload I wrote:

{% block content %}
    <h1>File content</h1>
    <form action="{% url 'blogapp:uploadComplete'%}" method="post" enctype="multipart/form-data">
         {% csrf_token %}
        <input id="uploadbutton" type="file" value="Browse" name="file" accept="text/csv" />
        <input type="submit" value="Upload" />
    </form>
    {% endblock %}

Following is the HTML which displays content of file:

{% block content %}
    <h3>File uploaded successfully</h3>
    {{file.name}}
    </br>content = {{contentOfFile}}
{% endblock %}

How to use cookies in Python Requests

You can use a session object. It stores the cookies so you can make requests, and it handles the cookies for you

s = requests.Session() 
# all cookies received will be stored in the session object

s.post('http://www...',data=payload)
s.get('http://www...')

Docs: https://requests.readthedocs.io/en/master/user/advanced/#session-objects

You can also save the cookie data to an external file, and then reload them to keep session persistent without having to login every time you run the script:

How to save requests (python) cookies to a file?

Python: "Indentation Error: unindent does not match any outer indentation level"

I would recommend checking your indentation levels all the way through. Make sure that you are using either tabs all the way or spaces all the way, with no mixture. I have had odd indentation problems in the past which have been caused by a mixture.

Docker is installed but Docker Compose is not ? why?

I suggest using the official pkg on Mac. I guess docker-compose is no longer included with docker by default: https://docs.docker.com/toolbox/toolbox_install_mac/

SQL split values to multiple rows

CREATE PROCEDURE `getVal`()
BEGIN
        declare r_len integer;
        declare r_id integer;
        declare r_val varchar(20);
        declare i integer;
        DECLARE found_row int(10);
        DECLARE row CURSOR FOR select length(replace(val,"|","")),id,val from split;
        create table x(id int,name varchar(20));
      open row;
            select FOUND_ROWS() into found_row ;
            read_loop: LOOP
                IF found_row = 0 THEN
                         LEAVE read_loop;
                END IF;
            set i = 1;  
            FETCH row INTO r_len,r_id,r_val;
            label1: LOOP        
                IF i <= r_len THEN
                  insert into x values( r_id,SUBSTRING(replace(r_val,"|",""),i,1));
                  SET i = i + 1;
                  ITERATE label1;
                END IF;
                LEAVE label1;
            END LOOP label1;
            set found_row = found_row - 1;
            END LOOP;
        close row;
        select * from x;
        drop table x;
END

How to load up CSS files using Javascript?

I'd like to share one more way to load not only css but all the assets (js, css, images) and handle onload event for the bunch of files. It's async-assets-loader. See the example below:

<script src="https://unpkg.com/async-assets-loader"></script>
<script>
var jsfile = "https://code.jquery.com/jquery-3.4.1.min.js";
var cssfile = "https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css";
var imgfile = "https://logos.keycdn.com/keycdn-logo-black.png";
var assetsLoader = new asyncAssetsLoader();
assetsLoader.load([
      {uri: jsfile, type: "script"},
      {uri: cssfile, type: "style"},
      {uri: imgfile, type: "img"}
    ], function () {
      console.log("Assets are loaded");
      console.log("Img width: " + assetsLoader.getLoadedTags()[imgfile].width);
    });
</script> 

According to the async-assets-loader docs

Using TortoiseSVN how do I merge changes from the trunk to a branch and vice versa?

Take a look at svnmerge.py. It's command-line, can't be invoked by TortoiseSVN, but it's more powerful. From the FAQ:

Traditional subversion will let you merge changes, but it doesn't "remember" what you've already merged. It also doesn't provide a convenient way to exclude a change set from being merged. svnmerge.py automates some of the work, and simplifies it. Svnmerge also creates a commit message with the log messages from all of the things it merged.

How can I concatenate a string within a loop in JSTL/JSP?

You're using JSTL 2.0 right? You don't need to put <c:out/> around all variables. Have you tried something like this?

<c:forEach items="${myParams.items}" var="currentItem" varStatus="stat">
  <c:set var="myVar" value="${myVar}${currentItem}" />
</c:forEach>

Edit: Beaten by the above

The application may be doing too much work on its main thread

this usually happens when you are executing huge processes in main thread. it's OK to skip frames less than 200. but if you have more than 200 skipped frames, it can slow down your application UI thread. what you can do is to do these processes in a new thread called worker thread and after that, when you want to access and do something with UI thread(ex: do something with views, findView etc...) you can use handler or runOnUiThread(I like this more) in order to display the processing results. this absolutely solves the problem. using worker threads are very useful or even must be used when it comes to this cases.

client denied by server configuration

I have servers with proper lists of hosts and IPs. None of that allow all stuff. My fix was to put the hostname of my new workstation into the list. So the advise is:

Make sure the computer you're using is ACTUALLY on the list of allowed IPs. Look at IPs from logmessages, resolve names, check ifconfig / ipconfig etc.

*Google sent me due to the error-message.

Spring MVC - HttpMediaTypeNotAcceptableException

Try to add "jackson-databind" jars to pom.xml

`<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>${jackson.databind-version}</version>
</dependency>`

And produces ={MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE} to @RequestMapping

Es. @RequestMapping(value = "/api/xxx/{akey}/{md5}", produces ={MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE} @RequestMapping(value = "/api/contrassegno/{akey}/{md5}", produces ={MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE},...

Nesting await in Parallel.ForEach

Here is a simple generic implementation of a ForEachAsync method, based on an ActionBlock from the TPL Dataflow library, now embedded in the .NET 5 platform:

public static Task ForEachAsync<T>(this IEnumerable<T> source,
    Func<T, Task> action, int dop)
{
    // Arguments validation omitted
    var block = new ActionBlock<T>(action,
        new ExecutionDataflowBlockOptions() { MaxDegreeOfParallelism = dop });
    try
    {
        foreach (var item in source) block.Post(item);
        block.Complete();
    }
    catch (Exception ex) { ((IDataflowBlock)block).Fault(ex); }
    return block.Completion;
}

This solution enumerates eagerly the supplied IEnumerable, and sends immediately all its elements to the ActionBlock. So it is not very suitable for enumerables with huge number of elements. Below is a more sophisticated approach, that enumerates the source lazily, and sends its elements to the ActionBlock one by one:

public static async Task ForEachAsync<T>(this IEnumerable<T> source,
    Func<T, Task> action, int dop)
{
    // Arguments validation omitted
    var block = new ActionBlock<T>(action, new ExecutionDataflowBlockOptions()
    { MaxDegreeOfParallelism = dop, BoundedCapacity = dop });
    try
    {
        foreach (var item in source)
            if (!await block.SendAsync(item).ConfigureAwait(false)) break;
        block.Complete();
    }
    catch (Exception ex) { ((IDataflowBlock)block).Fault(ex); }
    try { await block.Completion.ConfigureAwait(false); }
    catch { block.Completion.Wait(); } // Propagate AggregateException
}

These two methods have different behavior in case of exceptions. The first¹ propagates an AggregateException containing the exceptions directly in its InnerExceptions property. The second propagates an AggregateException that contains another AggregateException with the exceptions. Personally I find the behavior of the second method more convenient in practice, because awaiting it eliminates automatically a level of nesting, and so I can simply catch (AggregateException aex) and handle the aex.InnerExceptions inside the catch block. The first method requires to store the Task before awaiting it, so that I can gain access the task.Exception.InnerExceptions inside the catch block. For more info about propagating exceptions from async methods, look here or here.

Both implementations handle gracefully any errors that may occur during the enumeration of the source. The ForEachAsync method does not complete before all pending operations are completed. No tasks are left behind unobserved (in fire-and-forget fashion).

¹ The first implementation elides async and await.

jQuery AJAX file upload PHP

and this is the php file to receive the uplaoded files

<?
$data = array();
    //check with your logic
    if (isset($_FILES)) {
        $error = false;
        $files = array();

        $uploaddir = $target_dir;
        foreach ($_FILES as $file) {
            if (move_uploaded_file($file['tmp_name'], $uploaddir . basename( $file['name']))) {
                $files[] = $uploaddir . $file['name'];
            } else {
                $error = true;
            }
        }
        $data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
    } else {
        $data = array('success' => 'NO FILES ARE SENT','formData' => $_REQUEST);
    }

    echo json_encode($data);
?>

Can't include C++ headers like vector in Android NDK

In android NDK go to android-ndk-r9b>/sources/cxx-stl/gnu-libstdc++/4.X/include in linux machines

I've found solution from the below link http://osdir.com/ml/android-ndk/2011-09/msg00336.html

If list index exists, do X

len(nams) should be equal to n in your code. All indexes 0 <= i < n "exist".

Jquery - How to make $.post() use contentType=application/json?

For some reason, setting the content type on the ajax request as @Adrien suggested didn't work in my case. However, you actually can change content type using $.post by doing this before:

$.ajaxSetup({
    'beforeSend' : function(xhr) {
        xhr.overrideMimeType('application/json; charset=utf-8');
    },
});

Then make your $.post call:

$.post(url, data, function(), "json")

I had trouble with jQuery + IIS, and this was the only solution that helped jQuery understand to use windows-1252 encoding for ajax requests.

Clearing content of text file using php

//create a file handler by opening the file
$myTextFileHandler = @fopen("filelist.txt","r+");

//truncate the file to zero
//or you could have used the write method and written nothing to it
@ftruncate($myTextFileHandler, 0);

//use location header to go back to index.html
header("Location:index.html");

I don't exactly know where u want to show the result.

Node.js console.log() not logging anything

In a node.js server console.log outputs to the terminal window, not to the browser's console window.

How are you running your server? You should see the output directly after you start it.

Is the ternary operator faster than an "if" condition in Java

For the example given, I prefer the ternary or condition operator (?) for a specific reason: I can clearly see that assigning a is not optional. With a simple example, it's not too hard to scan the if-else block to see that a is assigned in each clause, but imagine several assignments in each clause:

if (i == 0)
{
    a = 10;
    b = 6;
    c = 3;
}
else
{
    a = 5;
    b = 4;
    d = 1;
}

a = (i == 0) ? 10 : 5;
b = (i == 0) ? 6  : 4;
c = (i == 0) ? 3  : 9;
d = (i == 0) ? 12 : 1;

I prefer the latter so that you know you haven't missed an assignment.

Is there a way to get the source code from an APK file?

Use this tool http://www.javadecompilers.com/

But recently, a new wave of decompilers has forayed onto the market: Procyon, CFR, JD, Fernflower, Krakatau, Candle.

Here's a list of decompilers presented on this site:

CFR - Free, no source-code available, http://www.benf.org/other/cfr/ Author: Lee Benfield

Very well-updated decompiler! CFR is able to decompile modern Java features - Java 9 modules, Java 8 lambdas, Java 7 String switches etc. It'll even make a decent go of turning class files from other JVM langauges back into java!

JD - free for non-commercial use only, http://jd.benow.ca/ Author: Emmanuel Dupuy

Updated in 2015. Has its own visual interface and plugins to Eclipse and IntelliJ . Written in C++, so very fast. Supports Java 5.

Procyon - open-source, https://bitbucket.org/mstrobel/procyon/wiki/Java%20Decompiler Author: Mike Strobel

Fernflower - open-source, https://github.com/fesh0r/fernflower Author: Egor Ushakov

Updated in 2015. Very promising analytical Java decompiler, now becomes an integral part of IntelliJ 14. (https://github.com/JetBrains/intellij-community/tree/master/plugins/java-decompiler) Supports Java up to version 6 (Annotations, generics, enums)

JAD - given here only for historical reason. Free, no source-code available, jad download mirror Author: Pavel Kouznetsov

Hash function that produces short hashes?

You can use any commonly available hash algorithm (eg. SHA-1), which will give you a slightly longer result than what you need. Simply truncate the result to the desired length, which may be good enough.

For example, in Python:

>>> import hashlib
>>> hash = hashlib.sha1("my message".encode("UTF-8")).hexdigest()
>>> hash
'104ab42f1193c336aa2cf08a2c946d5c6fd0fcdb'
>>> hash[:10]
'104ab42f11'

Pushing value of Var into an Array

.val() does not return an array from a DOM element: $('#fruit') is going to find the element in the document with an ID of #fruit and get its value (if it has a value).

How to make a HTTP request using Ruby on Rails?

require 'net/http'
result = Net::HTTP.get(URI.parse('http://www.example.com/about.html'))
# or
result = Net::HTTP.get(URI.parse('http://www.example.com'), '/about.html')

Excel is not updating cells, options > formula > workbook calculation set to automatic

the ctrl alt f9 , is the temporary solution , going to options-formula-auto calculate is the right way, that option turned manual, because some shortcut key on being pressed by mistake turns automatic to manual

Is it possible to import a whole directory in sass using @import?

You can generate SASS file which imports everything automatically, I use this Gulp task:

concatFilenames = require('gulp-concat-filenames')

let concatFilenamesOptions = {
    root: './',
    prepend: "@import '",
    append: "'"
}
gulp.task('sass-import', () => {
    gulp.src(path_src_sass)
        .pipe(concatFilenames('app.sass', concatFilenamesOptions))
        .pipe(gulp.dest('./build'))
})

You can also control importing order by ordering the folders like this:

path_src_sass = [
    './style/**/*.sass', // mixins, variables - import first
    './components/**/*.sass', // singule components
    './pages/**/*.sass' // higher-level templates that could override components settings if necessary
]

WebView and Cookies on Android

My problem is cookies are not working "within" the same session. –

Burak: I had the same problem. Enabling cookies fixed the issue.

CookieManager.getInstance().setAcceptCookie(true);

Debugging with command-line parameters in Visual Studio

In Visual Studio 2010, right click the project, choose Properties, click the configuring properties section on the left pane, then click Debugging, then on the right pane there is a box for command arguments.

In that enter the command line arguments. You are good to go. Now debug and see the result. If you are tired of changing in the properties then temporarily give the input directly in the program.

Get path of executable

For Windows, you have the problem of how to strip the executable from the result of GetModuleFileName(). The Windows API call PathRemoveFileSpec() that Nate used for that purpose in his answer changed between Windows 8 and its predecessors. So how to remain compatible with both and safe? Luckily, there's C++17 (or Boost, if you're using an older compiler). I do this:

#include <windows.h>
#include <string>
#include <filesystem>
namespace fs = std::experimental::filesystem;

// We could use fs::path as return type, but if you're not aware of
// std::experimental::filesystem, you probably handle filenames
// as strings anyway in the remainder of your code.  I'm on Japanese
// Windows, so wide chars are a must.
std::wstring getDirectoryWithCurrentExecutable()
{
    int size = 256;
    std::vector<wchar_t> charBuffer;
    // Let's be safe, and find the right buffer size programmatically.
    do {
        size *= 2;
        charBuffer.resize(size);
        // Resize until filename fits.  GetModuleFileNameW returns the
        // number of characters written to the buffer, so if the
        // return value is smaller than the size of the buffer, it was
        // large enough.
    } while (GetModuleFileNameW(NULL, charBuffer.data(), size) == size);
    // Typically: c:/program files (x86)/something/foo/bar/exe/files/win64/baz.exe
    // (Note that windows supports forward and backward slashes as path
    // separators, so you have to be careful when searching through a path
    // manually.)

    // Let's extract the interesting part:
    fs::path path(charBuffer.data());  // Contains the full path including .exe
    return path.remove_filename()  // Extract the directory ...
               .w_str();           // ... and convert to a string.
}

What is a lambda (function)?

It refers to lambda calculus, which is a formal system that just has lambda expressions, which represent a function that takes a function for its sole argument and returns a function. All functions in the lambda calculus are of that type, i.e., ? : ? ? ?.

Lisp used the lambda concept to name its anonymous function literals. This lambda represents a function that takes two arguments, x and y, and returns their product:

(lambda (x y) (* x y)) 

It can be applied in-line like this (evaluates to 50):

((lambda (x y) (* x y)) 5 10)

How to access a RowDataPacket object

db.query('select * from login',(err, results, fields)=>{
    if(err){
        console.log('error in fetching data')
    }
    var string=JSON.stringify(results);
    console.log(string);
    var json =  JSON.parse(string);
   // to get one value here is the option
    console.log(json[0].name);
})

How to avoid variable substitution in Oracle SQL Developer with 'trinidad & tobago'

this will work as you asked without CHAR(38):

update t set country = 'Trinidad and Tobago' where country = 'trinidad & '|| 'tobago';

create table table99(col1 varchar(40));
insert into table99 values('Trinidad &' || '  Tobago');
insert into table99 values('Trinidad &' || '  Tobago');
insert into table99 values('Trinidad &' || '  Tobago');
insert into table99 values('Trinidad &' || '  Tobago');
SELECT * FROM table99;

update table99 set col1 = 'Trinidad and Tobago' where col1 = 'Trinidad &'||'  Tobago';

What's the difference between nohup and ampersand

Most of the time we login to remote server using ssh. If you start a shell script and you logout then the process is killed. Nohup helps to continue running the script in background even after you log out from shell.

Nohup command name &
eg: nohup sh script.sh &

Nohup catches the HUP signals. Nohup doesn't put the job automatically in the background. We need to tell that explicitly using &

PHP if not statements

No matter what $action is, it will always either not be "add" OR not be "delete", which is why the if condition always passes. What you want is to use && instead of ||:

(!isset($action)) || ($action !="add" && $action !="delete"))

What is the difference between Double.parseDouble(String) and Double.valueOf(String)?

If you want to convert string to double data type then most choose parseDouble() method. See the example code:

String str = "123.67";
double d = parseDouble(str);

You will get the value in double. See the StringToDouble tutorial at tutorialData.

Android : Check whether the phone is dual SIM

I am able to read both the IMEI's from OnePlus 2 Phone

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                TelephonyManager manager = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
                Log.i(TAG, "Single or Dual Sim " + manager.getPhoneCount());
                Log.i(TAG, "Default device ID " + manager.getDeviceId());
                Log.i(TAG, "Single 1 " + manager.getDeviceId(0));
                Log.i(TAG, "Single 2 " + manager.getDeviceId(1));
            }

Format numbers in thousands (K) in Excel

[>=1000]#,##0,"K";[<=-1000]-#,##0,"K";0

teylyn's answer is great. This just adds negatives beyond -1000 following the same format.

"Debug certificate expired" error in Eclipse Android plugins

H-m-m-m. Interesting how so many people have had slightly different experiences with this. I remember the days when this was considered a sign that the software was not ready for release, and the team would actually fix it BEFORE users started seeing these problems:(

My own experience was just a little different. I had already tried Project>Clean, but still got the same build failure. Then I deleted the debug.keystore (under .android) just as the first answer said. Still got the same problem. Then I did a clean again, and wonder of wonders, it worked!

Now don't get me wrong, I am glad that I got it working thanks to the hints in this thread. But clearly clean isn't working right, and how did it find an expired key after I deleted the keystore??? Clearly something is wrong with Eclipse or the ADT -- not so sure which.

What is the difference between DAO and Repository patterns?

in a very simple sentence: The significant difference being that Repositories represent collections, whilst DAOs are closer to the database, often being far more table-centric.

Rename a file in C#

None of the answers mention writing a unit testable solution. You could use System.IO.Abstractions as it provides a testable wrapper around FileSystem operations, using which you can create a mocked file system objects and write unit tests.

using System.IO.Abstractions;

IFileInfo fileInfo = _fileSystem.FileInfo.FromFileName("filePathAndName");
fileInfo.MoveTo(Path.Combine(fileInfo.DirectoryName, newName));

It was tested, and it is working code to rename a file.

Eclipse/Maven error: "No compiler is provided in this environment"

  1. Uninstall older Java(JDK/JRE) from the system( Keep one (latest) java version), Also remove if any old java jre/jdk entries in environment variables PATH/CLASSPATH
  2. Eclipse->Window->Preferences->Installed JREs->Add/Edit JDK from the latest installation
  3. Eclipse->Window->Preferences->Installed JREs->Execution Environment->Select the desired java version on left and click the check box on right
  4. If you are using maven include the following tag in pom.xml (update versions as needed) inside plugins tag.

    <plugin>  
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    
  5. Right click on eclipse project Maven - > Update Project

How do I resolve "Cannot find module" error using Node.js?

This happens when a first npm install has crashed for some reason (SIGINT of npm), or that the delay was too long, or data is corrupted. Trying an npm install again won't save the problem.

Something got wrong on the npm first check, so the best choice is to remove the file and to restart npm install.

Django {% with %} tags within {% if %} {% else %} tags?

if you want to stay DRY, use an include.

{% if foo %}
  {% with a as b %}
    {% include "snipet.html" %}
  {% endwith %} 
{% else %}
  {% with bar as b %}
    {% include "snipet.html" %}
  {% endwith %} 
{% endif %}

or, even better would be to write a method on the model that encapsulates the core logic:

def Patient(models.Model):
    ....
    def get_legally_responsible_party(self):
       if self.age > 18:
          return self
       else:
          return self.parent

Then in the template:

{% with patient.get_legally_responsible_party as p %}
  Do html stuff
{% endwith %} 

Then in the future, if the logic for who is legally responsible changes you have a single place to change the logic -- far more DRY than having to change if statements in a dozen templates.

PostgreSQL next value of the sequences?

I tried this and it works perfectly

@Entity
public class Shipwreck {
  @Id
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq")
  @Basic(optional = false)
  @SequenceGenerator(name = "seq", sequenceName = "shipwreck_seq", allocationSize = 1)
  Long id;

....

CREATE SEQUENCE public.shipwreck_seq
    INCREMENT 1
    START 110
    MINVALUE 1
    MAXVALUE 9223372036854775807
    CACHE 1;

How to check if a div is visible state or not?

You can use .css() to get the value of "visibility":

 if( ! ( $("#singlechatpanel-1").css('visibility') === "hidden")){
 }

http://api.jquery.com/css/

Can't bind to 'ngIf' since it isn't a known property of 'div'

Just for anyone who still has an issue, I also had an issue where I typed ngif rather than ngIf (notice the capital 'I').

How to play a notification sound on websites?

As of 2016, the following will suffice (you don't even need to embed):

let src = 'https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_700KB.mp3';
let audio = new Audio(src);
audio.play();

See more here.

How to get day of the month?

The following method would help you in finding day of any specified date :

public static int getDayOfMonth(Date aDate) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(aDate);
    return cal.get(Calendar.DAY_OF_MONTH);
}

Running a Python script from PHP

Inspired by Alejandro Quiroz:

<?php 

$command = escapeshellcmd('python test.py');
$output = shell_exec($command);
echo $output;

?>

Need to add Python, and don't need the path.

g++ ld: symbol(s) not found for architecture x86_64

finally solved my problem.

I created a new project in XCode with the sources and changed the C++ Standard Library from the default libc++ to libstdc++ as in this and this.

Styling Password Fields in CSS

The best I can find is to set input[type="password"] {font:small-caption;font-size:16px}

Demo:

_x000D_
_x000D_
input {_x000D_
  font: small-caption;_x000D_
  font-size: 16px;_x000D_
}
_x000D_
<input type="password">
_x000D_
_x000D_
_x000D_

How to get the id of the element clicked using jQuery

You can get the id of clicked one by this code

$("span").on("click",function(e){
    console.log(e.target.Id);
});

Use .on() event for future compatibility

Actionbar notification count icon (badge) like Google has

Try looking at the answers to these questions, particularly the second one which has sample code:

How to implement dynamic values on menu item in Android

How to get text on an ActionBar Icon?

From what I see, You'll need to create your own custom ActionView implementation. An alternative might be a custom Drawable. Note that there appears to be no native implementation of a notification count for the Action Bar.

EDIT: The answer you were looking for, with code: Custom Notification View with sample implementation

How do I read a text file of about 2 GB?

I always use 010 Editor to open huge files. It can handle 2 GB easily. I was manipulating files with 50 GB with 010 Editor :-)

It's commercial now, but it has a trial version.

How to retrieve all keys (or values) from a std::map and put them into a vector?

With the structured binding (“destructuring”) declaration syntax of C++17,

you can do this, which is easier to understand.

// To get the keys
std::map<int, double> map;
std::vector<int> keys;
keys.reserve(map.size());
for(const auto& [key, value] : map) {
    keys.push_back(key);
}
// To get the values
std::map<int, double> map;
std::vector<double> values;
values.reserve(map.size());
for(const auto& [key, value] : map) {
    values.push_back(value);
}

How to connect to Oracle 11g database remotely

Its quite easy on computer a you don't need to do anything just make sure both system are on same network if its not internet access(for this you need static ip). Okay now on computer b go to start menu find configuration under oracle folder click Net Configuration Assistant under that folder when window pop up click Local net configuration option it must be third option.

Now click add and click next in next screen it will ask service name here you need to add oracle global database name of computer A(Normally I use oracle86 for my installation) now click next next screen choose protocol normally its tcp click next in host name enter computer A's name you can found that in my computer properties. Click next don't change port untill you have changed that in Computer A click next and choose test connection now here you can check your connection working or not if the error is username and password not correct then click login credential button and fill correct username and password. If its saying unable to reach computer ot target not found than you must add exception in firewall for 1521 port or just disable firewall on computer A.

What's the difference between a mock & stub?

Foreword

There are several definitions of objects, that are not real. The general term is test double. This term encompasses: dummy, fake, stub, mock.

Reference

According to Martin Fowler's article:

  • Dummy objects are passed around but never actually used. Usually they are just used to fill parameter lists.
  • Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production (an in memory database is a good example).
  • Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it 'sent', or maybe only how many messages it 'sent'.
  • Mocks are what we are talking about here: objects pre-programmed with expectations which form a specification of the calls they are expected to receive.

Style

Mocks vs Stubs = Behavioral testing vs State testing

Principle

According to the principle of Test only one thing per test, there may be several stubs in one test, but generally there is only one mock.

Lifecycle

Test lifecycle with stubs:

  1. Setup - Prepare object that is being tested and its stubs collaborators.
  2. Exercise - Test the functionality.
  3. Verify state - Use asserts to check object's state.
  4. Teardown - Clean up resources.

Test lifecycle with mocks:

  1. Setup data - Prepare object that is being tested.
  2. Setup expectations - Prepare expectations in mock that is being used by primary object.
  3. Exercise - Test the functionality.
  4. Verify expectations - Verify that correct methods has been invoked in mock.
  5. Verify state - Use asserts to check object's state.
  6. Teardown - Clean up resources.

Summary

Both mocks and stubs testing give an answer for the question: What is the result?

Testing with mocks are also interested in: How the result has been achieved?

How to convert int to string on Arduino?

Use like this:

String myString = String(n);

You can find more examples here.

How to iterate std::set?

Just use the * before it:

set<unsigned long>::iterator it;
for (it = myset.begin(); it != myset.end(); ++it) {
    cout << *it;
}

This dereferences it and allows you to access the element the iterator is currently on.

Android studio 3.0: Unable to resolve dependency for :app@dexOptions/compileClasspath': Could not resolve project :animators

This may also happen when you add a reference to the feature module that uses the incorrect plugin type. Simply change com.android.application to com.android.feature or com.android.library

https://i.stack.imgur.com/NDjnG.png

How to serialize an object to XML without getting xmlns="..."?

If you want to get rid of the extra xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" and xmlns:xsd="http://www.w3.org/2001/XMLSchema", but still keep your own namespace xmlns="http://schemas.YourCompany.com/YourSchema/", you use the same code as above except for this simple change:

//  Add lib namespace with empty prefix  
ns.Add("", "http://schemas.YourCompany.com/YourSchema/");   

Getting the parameters of a running JVM

JConsole can do it. Also you can use a powerful jvisualVM tool, which also is included in JDK since 1.6.0.8.

MySQL: Quick breakdown of the types of joins

Based on your comment, simple definitions of each is best found at W3Schools The first line of each type gives a brief explanation of the join type

  • JOIN: Return rows when there is at least one match in both tables
  • LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table
  • RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table
  • FULL JOIN: Return rows when there is a match in one of the tables

END EDIT

In a nutshell, the comma separated example you gave of

SELECT * FROM a, b WHERE b.id = a.beeId AND ...

is selecting every record from tables a and b with the commas separating the tables, this can be used also in columns like

SELECT a.beeName,b.* FROM a, b WHERE b.id = a.beeId AND ...

It is then getting the instructed information in the row where the b.id column and a.beeId column have a match in your example. So in your example it will get all information from tables a and b where the b.id equals a.beeId. In my example it will get all of the information from the b table and only information from the a.beeName column when the b.id equals the a.beeId. Note that there is an AND clause also, this will help to refine your results.

For some simple tutorials and explanations on mySQL joins and left joins have a look at Tizag's mySQL tutorials. You can also check out Keith J. Brown's website for more information on joins that is quite good also.

I hope this helps you

Make more than one chart in same IPython Notebook cell

You can also call the show() function after each plot. e.g

   plt.plot(a)
   plt.show()
   plt.plot(b)
   plt.show()

Objective-C - Remove last character from string

If it's an NSMutableString (which I would recommend since you're changing it dynamically), you can use:

[myString deleteCharactersInRange:NSMakeRange([myRequestString length]-1, 1)];

Unix shell script find out which directory the script file resides?

INTRODUCTION

This answer corrects the very broken but shockingly top voted answer of this thread (written by TheMarko):

#!/usr/bin/env bash

BASEDIR=$(dirname "$0")
echo "$BASEDIR"

WHY DOES USING dirname "$0" ON IT'S OWN NOT WORK?

dirname $0 will only work if user launches script in a very specific way. I was able to find several situations where this answer fails and crashes the script.

First of all, let's understand how this answer works. He's getting the script directory by doing

dirname "$0"

$0 represents the first part of the command calling the script (it's basically the inputted command without the arguments:

/some/path/./script argument1 argument2

$0="/some/path/./script"

dirname basically finds the last / in a string and truncates it there. So if you do:

  dirname /usr/bin/sha256sum

you'll get: /usr/bin

This example works well because /usr/bin/sha256sum is a properly formatted path but

  dirname "/some/path/./script"

wouldn't work well and would give you:

  BASENAME="/some/path/." #which would crash your script if you try to use it as a path

Say you're in the same dir as your script and you launch it with this command

./script   

$0 in this situation will be ./script and dirname $0 will give:

. #or BASEDIR=".", again this will crash your script

Using:

sh script

Without inputting the full path will also give a BASEDIR="."

Using relative directories:

 ../some/path/./script

Gives a dirname $0 of:

 ../some/path/.

If you're in the /some directory and you call the script in this manner (note the absence of / in the beginning, again a relative path):

 path/./script.sh

You'll get this value for dirname $0:

 path/. 

and ./path/./script (another form of the relative path) gives:

 ./path/.

The only two situations where basedir $0 will work is if the user use sh or touch to launch a script because both will result in $0:

 $0=/some/path/script

which will give you a path you can use with dirname.

THE SOLUTION

You'd have account for and detect every one of the above mentioned situations and apply a fix for it if it arises:

#!/bin/bash
#this script will only work in bash, make sure it's installed on your system.

#set to false to not see all the echos
debug=true

if [ "$debug" = true ]; then echo "\$0=$0";fi


#The line below detect script's parent directory. $0 is the part of the launch command that doesn't contain the arguments
BASEDIR=$(dirname "$0") #3 situations will cause dirname $0 to fail: #situation1: user launches script while in script dir ( $0=./script)
                                                                     #situation2: different dir but ./ is used to launch script (ex. $0=/path_to/./script)
                                                                     #situation3: different dir but relative path used to launch script
if [ "$debug" = true ]; then echo 'BASEDIR=$(dirname "$0") gives: '"$BASEDIR";fi                                 

if [ "$BASEDIR" = "." ]; then BASEDIR="$(pwd)";fi # fix for situation1

_B2=${BASEDIR:$((${#BASEDIR}-2))}; B_=${BASEDIR::1}; B_2=${BASEDIR::2}; B_3=${BASEDIR::3} # <- bash only
if [ "$_B2" = "/." ]; then BASEDIR=${BASEDIR::$((${#BASEDIR}-1))};fi #fix for situation2 # <- bash only
if [ "$B_" != "/" ]; then  #fix for situation3 #<- bash only
        if [ "$B_2" = "./" ]; then
                #covers ./relative_path/(./)script
                if [ "$(pwd)" != "/" ]; then BASEDIR="$(pwd)/${BASEDIR:2}"; else BASEDIR="/${BASEDIR:2}";fi
        else
                #covers relative_path/(./)script and ../relative_path/(./)script, using ../relative_path fails if current path is a symbolic link
                if [ "$(pwd)" != "/" ]; then BASEDIR="$(pwd)/$BASEDIR"; else BASEDIR="/$BASEDIR";fi
        fi
fi

if [ "$debug" = true ]; then echo "fixed BASEDIR=$BASEDIR";fi

How to use continue in jQuery each() loop?

We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration. -- jQuery.each() | jQuery API Documentation

how to bold words within a paragraph in HTML/CSS?

<style type="text/css">
p.boldpara {font-weight:bold;}
</style>
</head>

<body>
<p class="boldpara">Stack overflow is good site for developers. I really like this site </p>

</body>

</html>

http://www.tutorialspoint.com

Angular 4: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'

I found another solution to get the data. according to the documentation Please check documentation link

In service file add following.

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';

@Injectable()
export class MoviesService {

  constructor(private db: AngularFireDatabase) {}
  getMovies() {
    this.db.list('/movies').valueChanges();
  }
}

In Component add following.

import { Component, OnInit } from '@angular/core';
import { MoviesService } from './movies.service';

@Component({
  selector: 'app-movies',
  templateUrl: './movies.component.html',
  styleUrls: ['./movies.component.css']
})
export class MoviesComponent implements OnInit {
  movies$;

  constructor(private moviesDb: MoviesService) { 
   this.movies$ = moviesDb.getMovies();
 }

In your html file add following.

<li  *ngFor="let m of movies$ | async">{{ m.name }} </li>

Singleton: How should it be used

The problem with singletons is not their implementation. It is that they conflate two different concepts, neither of which is obviously desirable.

1) Singletons provide a global access mechanism to an object. Although they might be marginally more threadsafe or marginally more reliable in languages without a well-defined initialization order, this usage is still the moral equivalent of a global variable. It's a global variable dressed up in some awkward syntax (foo::get_instance() instead of g_foo, say), but it serves the exact same purpose (a single object accessible across the entire program) and has the exact same drawbacks.

2) Singletons prevent multiple instantiations of a class. It's rare, IME, that this kind of feature should be baked into a class. It's normally a much more contextual thing; a lot of the things that are regarded as one-and-only-one are really just happens-to-be-only-one. IMO a more appropriate solution is to just create only one instance--until you realize that you need more than one instance.

How to display HTML <FORM> as inline element?

Just use the style float: left in this way:

<p style="float: left"> Lorem Ipsum </p> 
<form style="float: left">
   <input  type='submit'/>
</form>
<p style="float: left"> Lorem Ipsum </p>

JavaScript and Threads

In raw Javascript, the best that you can do is using the few asynchronous calls (xmlhttprequest), but that's not really threading and very limited. Google Gears adds a number of APIs to the browser, some of which can be used for threading support.

How do you remove an array element in a foreach loop?

foreach($display_related_tags as $key => $tag_name)
{
    if($tag_name == $found_tag['name'])
        unset($display_related_tags[$key];
}

How to display loading image while actual image is downloading

Just add a background image to all images using css:

img {
  background: url('loading.gif') no-repeat;
}

Could not find method compile() for arguments Gradle

Just for the record: I accidentally enabled Offline work under Preferences -> Build,Execution,Deployment -> Gradle -> uncheck Offline Work, but the error message was misleading

Max length UITextField

You can use in swift 5 or swift 4 like image look like bellow enter image description here

  1. Add textField in View Controller
  2. Connect to text to ViewController
  3. add the code in view ViewController

     class ViewController: UIViewController , UITextFieldDelegate {
    
      @IBOutlet weak var txtName: UITextField!
    
      var maxLen:Int = 8;
    
     override func viewDidLoad() {
        super.viewDidLoad()
    
        txtName.delegate = self
       }
    
     func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
         if(textField == txtName){
            let currentText = textField.text! + string
            return currentText.count <= maxLen
         }
    
         return true;
       }
    }
    

You can download Full Source form GitHub: https://github.com/enamul95/TextFieldMaxLen

Interview Question: Merge two sorted singly linked lists without creating new nodes

A simple iterative solution.

Node* MergeLists(Node* A, Node* B)
{
    //handling the corner cases

    //if both lists are empty
    if(!A && !B)
    {
        cout << "List is empty" << endl;
        return 0;
    }
    //either of list is empty
    else if(!A) return B;
    else if(!B) return A;
    else
    {
        Node* head = NULL;//this will be the head of the newList
        Node* previous = NULL;//this will act as the

        /* In this algorithm we will keep the
         previous pointer that will point to the last node of the output list.
         And, as given we have A & B as pointer to the given lists.

         The algorithm will keep on going untill either one of the list become empty.
         Inside of the while loop, it will divide the algorithm in two parts:
            - First, if the head of the output list is not obtained yet
            - Second, if head is already there then we will just compare the values and keep appending to the 'previous' pointer.
         When one of the list become empty we will append the other 'left over' list to the output list.
         */
         while(A && B)
         {
             if(!head)
             {
                 if(A->data <= B->data)
                 {
                     head = A;//setting head of the output list to A
                     previous = A; //initializing previous
                     A = A->next;
                 }
                 else
                 {
                     head = B;//setting head of the output list to B
                     previous = B;//initializing previous
                     B = B->next;
                 }
             }
             else//when head is already set
             {
                 if(A->data <= B->data)
                 {
                     if(previous->next != A)
                         previous->next = A;
                     A = A->next;//Moved A forward but keeping B at the same position
                 }
                 else
                 {
                     if(previous->next != B)
                         previous->next = B;
                     B = B->next; //Moved B forward but keeping A at the same position
                 }
                 previous = previous->next;//Moving the Output list pointer forward
             }
         }
        //at the end either one of the list would finish
        //and we have to append the other list to the output list
        if(!A)
            previous->next = B;

        if(!B)
            previous->next = A;

        return head; //returning the head of the output list
    }
}

Drop multiple columns in pandas

You don't need to wrap it in a list with [..], just provide the subselection of the columns index:

df.drop(df.columns[[1, 69]], axis=1, inplace=True)

as the index object is already regarded as list-like.

Node.js: Python not found exception due to node-sass and node-gyp

The error message means that it cannot locate your python executable or binary.

In many cases, it's installed at c:\python27. if it's not installed yet, you can install it with npm install --global windows-build-tools, which will only work if it hasn't been installed yet.

Adding it to the environment variables does not always work. A better alternative, is to just set it in the npm config.

npm config set python c:\python27\python.exe

How do I alter the position of a column in a PostgreSQL database table?

I don't think you can at present: see this article on the Postgresql wiki.

The three workarounds from this article are:

  1. Recreate the table
  2. Add columns and move data
  3. Hide the differences with a view.

Forcing anti-aliasing using css: Is this a myth?

I found a really awkward solution using the zoom and filter ms-only properties Example (try with no aa, standard and cleartype): http://nadycoon.hu/special/archive/internet-explorer-force-antialias.html

How it works:

-zoom up text with zoom:x, x>1

-apply some blur(s) (or any other filter)

-zoom down with zoom:1/x

It's a bit slow, and very! memory-hungry method, and on non-white backgrounds it has some slight dark halo.

CSS:

.insane-aa-4b                  { zoom:0.25; }
.insane-aa-4b .insane-aa-inner { zoom:4; }
.insane-aa-4b .insane-aa-blur  { zoom:1;
  filter:progid:DXImageTransform.Microsoft.Blur(pixelRadius=2);
}

HTML:

<div class="insane-aa-4b">
<div class="insane-aa-blur">
<div class="insane-aa-inner">
  <div style="font-size:12px;">Lorem Ipsum</div>
</div></div></div>

You can use this short jQuery to force anti-aliasing, just add the ieaa class to anything:

$(function(){ $('.ieaa').wrap(
'<div style="zoom:0.25;"><div style="zoom:1;filter:progid:DXImageTransform.Microsoft.Blur(pixelRadius=2);"><div style="zoom:4;"><'+'/div><'+'/div><'+'/div>'
); });

relative path in BAT script

You can get all the required file properties by using the code below:

FOR %%? IN (file_to_be_queried) DO (
    ECHO File Name Only       : %%~n?
    ECHO File Extension       : %%~x?
    ECHO Name in 8.3 notation : %%~sn?
    ECHO File Attributes      : %%~a?
    ECHO Located on Drive     : %%~d?
    ECHO File Size            : %%~z?
    ECHO Last-Modified Date   : %%~t?
    ECHO Parent Folder        : %%~dp?
    ECHO Fully Qualified Path : %%~f?
    ECHO FQP in 8.3 notation  : %%~sf?
    ECHO Location in the PATH : %%~dp$PATH:?
)