Programs & Examples On #Constants

Constants in programming are definitions whose value is fixed throughout a program's execution. Literals in most languages are constants, for example. In referentially transparent programming styles, all definitions are constant.

Constant pointer vs Pointer to constant

1) Constant Pointers : These type of pointers are the one which cannot change address they are pointing to. This means that suppose there is a pointer which points to a variable (or stores the address of that variable). Now if we try to point the pointer to some other variable (or try to make the pointer store address of some other variable), then constant pointers are incapable of this.

A constant pointer is declared as : int *const ptr ( the location of 'const' make the pointer 'ptr' as constant pointer)

2) Pointer to Constant : These type of pointers are the one which cannot change the value they are pointing to. This means they cannot change the value of the variable whose address they are holding.

A pointer to a constant is declared as : const int *ptr (the location of 'const' makes the pointer 'ptr' as a pointer to constant.

Example

Constant Pointer

#include<stdio.h>

int main(void)
{
    int a[] = {10,11};
    int* const ptr = a;

    *ptr = 11;

    printf("\n value at ptr is  : [%d]\n",*ptr);
    printf("\n Address pointed by ptr  : [%p]\n",(unsigned int*)ptr);

    ptr++;
    printf("\n Address pointed by ptr  : [%p]\n",(unsigned int*)ptr);

    return 0;
}

Now, when we compile the above code, compiler complains :

practice # gcc -Wall constant_pointer.c -o constant_pointer
constant_pointer.c: In function ‘main’:
constant_pointer.c:13: error: increment of read-only variable ‘ptr’

Hence we see very clearly above that compiler complains that we cannot changes the address held by a constant pointer.

Pointer to Constants

#include<stdio.h>

int main(void)
{
    int a = 10;
    const int* ptr = &a;


    printf("\n value at ptr is  : [%d]\n",*ptr);
    printf("\n Address pointed by ptr  : [%p]\n",(unsigned int*)ptr);

    *ptr = 11;

    return 0;
}

Now, when the above code is compiled, the compiler complains :

practice # gcc -Wall pointer_to_constant.c -o pointer_to_constant
pointer_to_constant.c: In function ‘main’:
pointer_to_constant.c:12: error: assignment of read-only location ‘*ptr’

Hence here too we see that compiler does not allow the pointer to a constant to change the value of the variable being pointed.

Quotation

Declare a const array

I believe you can only make it readonly.

How to select multiple rows filled with constants?

In MySQL, you can do: values (1,2), (3, 4);

mysql> values (1,2), (3, 4);
+---+---+
| 1 | 2 |
+---+---+
| 1 | 2 |
| 3 | 4 |
+---+---+
2 rows in set (0.004 sec)

With MySQL 8, it is also possible to give the column names:

mysql> SELECT * FROM (SELECT 1, 2, 3, 4) AS dt (a, b, c, d);
+---+---+---+---+
| a | b | c | d |
+---+---+---+---+
| 1 | 2 | 3 | 4 |
+---+---+---+---+

Are there constants in JavaScript?

Okay, this is ugly, but it gives me a constant in Firefox and Chromium, an inconstant constant (WTF?) in Safari and Opera, and a variable in IE.

Of course eval() is evil, but without it, IE throws an error, preventing scripts from running.

Safari and Opera support the const keyword, but you can change the const's value.

In this example, server-side code is writing JavaScript to the page, replacing {0} with a value.

try{
    // i can haz const?
    eval("const FOO='{0}';");
    // for reals?
    var original=FOO;
    try{
        FOO='?NO!';
    }catch(err1){
        // no err from Firefox/Chrome - fails silently
        alert('err1 '+err1);
    }
    alert('const '+FOO);
    if(FOO=='?NO!'){
        // changed in Sf/Op - set back to original value
        FOO=original;
    }
}catch(err2){
    // IE fail
    alert('err2 '+err2);
    // set var (no var keyword - Chrome/Firefox complain about redefining const)
    FOO='{0}';
    alert('var '+FOO);
}
alert('FOO '+FOO);

What is this good for? Not much, since it's not cross-browser. At best, maybe a little peace of mind that at least some browsers won't let bookmarklets or third-party script modify the value.

Tested with Firefox 2, 3, 3.6, 4, Iron 8, Chrome 10, 12, Opera 11, Safari 5, IE 6, 9.

How to declare string constants in JavaScript?

Many browsers' implementations (and Node) have constants, used with const.

const SOME_VALUE = "Your string";

This const means that you can't reassign it to any other value.

Check the compatibility notes to see if your targeted browsers are supported.

Alternatively, you could also modify the first example, using defineProperty() or its friends and make the writable property false. This will mean the variable's contents can not be changed, like a constant.

Declaring static constants in ES6 classes?

You can create a way to define static constants on a class using an odd feature of ES6 classes. Since statics are inherited by their subclasses, you can do the following:

const withConsts = (map, BaseClass = Object) => {
  class ConstClass extends BaseClass { }
  Object.keys(map).forEach(key => {
    Object.defineProperty(ConstClass, key, {
      value: map[key],
      writable : false,
      enumerable : true,
      configurable : false
    });
  });
  return ConstClass;
};

class MyClass extends withConsts({ MY_CONST: 'this is defined' }) {
  foo() {
    console.log(MyClass.MY_CONST);
  }
}

Storing integer values as constants in Enum manner in java

Well, you can't quite do it that way. PAGE.SIGN_CREATE will never return 1; it will return PAGE.SIGN_CREATE. That's the point of enumerated types.

However, if you're willing to add a few keystrokes, you can add fields to your enums, like this:


    public enum PAGE{
        SIGN_CREATE(0),
        SIGN_CREATE_BONUS(1),
        HOME_SCREEN(2),
        REGISTER_SCREEN(3);

        private final int value;

        PAGE(final int newValue) {
            value = newValue;
        }

        public int getValue() { return value; }
    }

And then you call PAGE.SIGN_CREATE.getValue() to get 0.

"static const" vs "#define" vs "enum"

Although the question was about integers, it's worth noting that #define and enums are useless if you need a constant structure or string. These are both usually passed to functions as pointers. (With strings it's required; with structures it's much more efficient.)

As for integers, if you're in an embedded environment with very limited memory, you might need to worry about where the constant is stored and how accesses to it are compiled. The compiler might add two consts at run time, but add two #defines at compile time. A #define constant may be converted into one or more MOV [immediate] instructions, which means the constant is effectively stored in program memory. A const constant will be stored in the .const section in data memory. In systems with a Harvard architecture, there could be differences in performance and memory usage, although they'd likely be small. They might matter for hard-core optimization of inner loops.

PHP - define constant inside a class

See Class Constants:

class MyClass
{
    const MYCONSTANT = 'constant value';

    function showConstant() {
        echo  self::MYCONSTANT. "\n";
    }
}

echo MyClass::MYCONSTANT. "\n";

$classname = "MyClass";
echo $classname::MYCONSTANT. "\n"; // As of PHP 5.3.0

$class = new MyClass();
$class->showConstant();

echo $class::MYCONSTANT."\n"; // As of PHP 5.3.0

In this case echoing MYCONSTANT by itself would raise a notice about an undefined constant and output the constant name converted to a string: "MYCONSTANT".


EDIT - Perhaps what you're looking for is this static properties / variables:

class MyClass
{
    private static $staticVariable = null;

    public static function showStaticVariable($value = null)
    {
        if ((is_null(self::$staticVariable) === true) && (isset($value) === true))
        {
            self::$staticVariable = $value;
        }

        return self::$staticVariable;
    }
}

MyClass::showStaticVariable(); // null
MyClass::showStaticVariable('constant value'); // "constant value"
MyClass::showStaticVariable('other constant value?'); // "constant value"
MyClass::showStaticVariable(); // "constant value"

What is the difference between char s[] and char *s?

In the case of:

char *x = "fred";

x is an lvalue -- it can be assigned to. But in the case of:

char x[] = "fred";

x is not an lvalue, it is an rvalue -- you cannot assign to it.

What is the difference between char * const and const char *?

const char* is a pointer to a constant character
char* const is a constant pointer to a character
const char* const is a constant pointer to a constant character

C++ style cast from unsigned char * to const char *

Try reinterpret_cast

unsigned char *foo();
std::string str;
str.append(reinterpret_cast<const char*>(foo()));

What's the best way to store a group of constants that my program uses?

Yes, a static class for storing constants would be just fine, except for constants that are related to specific types.

Importing a long list of constants to a Python file

Python isn't preprocessed. You can just create a file myconstants.py:

MY_CONSTANT = 50

And importing them will just work:

import myconstants
print myconstants.MY_CONSTANT * 2

How to declare a static const char* in your header file?

To answer the why question, integral types are special in that they are not a reference to an allocated object but rather values that are duplicated and copied. It's just an implementation decision made when the language was defined, which was to handle values outside the object system and in as efficient and "inline" a fashion as possible.

This doesn't exactly explain why they are allowed as initializors in a type, but think of it as essentially a #define and then it will make sense as part of the type and not part of the object.

Ruby on Rails: Where to define global constants?

Try to keep all constant at one place, In my application I have created constants folder inside initializers as follows:

enter image description here

and I usually keep all constant in these files.

In your case you can create file under constants folder as colors_constant.rb

colors_constant.rb

enter image description here

Don't forgot to restart server

const vs constexpr on variables

I believe there is a difference. Let's rename them so that we can talk about them more easily:

const     double PI1 = 3.141592653589793;
constexpr double PI2 = 3.141592653589793;

Both PI1 and PI2 are constant, meaning you can not modify them. However only PI2 is a compile-time constant. It shall be initialized at compile time. PI1 may be initialized at compile time or run time. Furthermore, only PI2 can be used in a context that requires a compile-time constant. For example:

constexpr double PI3 = PI1;  // error

but:

constexpr double PI3 = PI2;  // ok

and:

static_assert(PI1 == 3.141592653589793, "");  // error

but:

static_assert(PI2 == 3.141592653589793, "");  // ok

As to which you should use? Use whichever meets your needs. Do you want to ensure that you have a compile time constant that can be used in contexts where a compile-time constant is required? Do you want to be able to initialize it with a computation done at run time? Etc.

Const in JavaScript: when to use it and is it necessary?

There are two aspects to your questions: what are the technical aspects of using const instead of var and what are the human-related aspects of doing so.

The technical difference is significant. In compiled languages, a constant will be replaced at compile-time and its use will allow for other optimizations like dead code removal to further increase the runtime efficiency of the code. Recent (loosely used term) JavaScript engines actually compile JS code to get better performance, so using the const keyword would inform them that the optimizations described above are possible and should be done. This results in better performance.

The human-related aspect is about the semantics of the keyword. A variable is a data structure that contains information that is expected to change. A constant is a data structure that contains information that will never change. If there is room for error, var should always be used. However, not all information that never changes in the lifetime of a program needs to be declared with const. If under different circumstances the information should change, use var to indicate that, even if the actual change doesn't appear in your code.

Differences Between vbLf, vbCrLf & vbCr Constants

The three constants have similar functions nowadays, but different historical origins, and very occasionally you may be required to use one or the other.

You need to think back to the days of old manual typewriters to get the origins of this. There are two distinct actions needed to start a new line of text:

  1. move the typing head back to the left. In practice in a typewriter this is done by moving the roll which carries the paper (the "carriage") all the way back to the right -- the typing head is fixed. This is a carriage return.
  2. move the paper up by the width of one line. This is a line feed.

In computers, these two actions are represented by two different characters - carriage return is CR, ASCII character 13, vbCr; line feed is LF, ASCII character 10, vbLf. In the old days of teletypes and line printers, the printer needed to be sent these two characters -- traditionally in the sequence CRLF -- to start a new line, and so the CRLF combination -- vbCrLf -- became a traditional line ending sequence, in some computing environments.

The problem was, of course, that it made just as much sense to only use one character to mark the line ending, and have the terminal or printer perform both the carriage return and line feed actions automatically. And so before you knew it, we had 3 different valid line endings: LF alone (used in Unix and Macintoshes), CR alone (apparently used in older Mac OSes) and the CRLF combination (used in DOS, and hence in Windows). This in turn led to the complications of DOS / Windows programs having the option of opening files in text mode, where any CRLF pair read from the file was converted to a single CR (and vice versa when writing).

So - to cut a (much too) long story short - there are historical reasons for the existence of the three separate line separators, which are now often irrelevant: and perhaps the best course of action in .NET is to use Environment.NewLine which means someone else has decided for you which to use, and future portability issues should be reduced.

What is the difference between a static and const variable?

Constant variables cannot be changed. Static variable are private to the file and only accessible within the program code and not to anyone else.

Declare a constant array

An array isn't immutable by nature; you can't make it constant.

The nearest you can get is:

var letter_goodness = [...]float32 {.0817, .0149, .0278, .0425, .1270, .0223, .0202, .0609, .0697, .0015, .0077, .0402, .0241, .0675, .0751, .0193, .0009, .0599, .0633, .0906, .0276, .0098, .0236, .0015, .0197, .0007 }

Note the [...] instead of []: it ensures you get a (fixed size) array instead of a slice. So the values aren't fixed but the size is.

Assigning a variable NaN in python without numpy

A more consistent (and less opaque) way to generate inf and -inf is to again use float():

>> positive_inf = float('inf')
>> positive_inf
inf
>> negative_inf = float('-inf')
>> negative_inf
-inf

Note that the size of a float varies depending on the architecture, so it probably best to avoid using magic numbers like 9e999, even if that is likely to work.

import sys
sys.float_info
sys.float_info(max=1.7976931348623157e+308,
               max_exp=1024, max_10_exp=308,
               min=2.2250738585072014e-308, min_exp=-1021,
               min_10_exp=-307, dig=15, mant_dig=53,
               epsilon=2.220446049250313e-16, radix=2, rounds=1)

C++ where to initialize static const

In a translation unit within the same namespace, usually at the top:

// foo.h
struct foo
{
    static const std::string s;
};

// foo.cpp
const std::string foo::s = "thingadongdong"; // this is where it lives

// bar.h
namespace baz
{
    struct bar
    {
        static const float f;
    };
}

// bar.cpp
namespace baz
{
    const float bar::f = 3.1415926535;
}

How can I get a resource content from a static context?

if you have a context, i mean inside;

public void onReceive(Context context, Intent intent){

}

you can use this code to get resources:

context.getResources().getString(R.string.app_name);

Meaning of 'const' last in a function declaration of a class?

Meaning of a Const Member Function in C++ Common Knowledge: Essential Intermediate Programming gives a clear explanation:

The type of the this pointer in a non-const member function of a class X is X * const. That is, it’s a constant pointer to a non-constant X (see Const Pointers and Pointers to Const [7, 21]). Because the object to which this refers is not const, it can be modified. The type of this in a const member function of a class X is const X * const. That is, it’s a constant pointer to a constant X. Because the object to which this refers is const, it cannot be modified. That’s the difference between const and non-const member functions.

So in your code:

class foobar
{
  public:
     operator int () const;
     const char* foo() const;
};

You can think it as this:

class foobar
{
  public:
     operator int (const foobar * const this) const;
     const char* foo(const foobar * const this) const;
};

Difference between const reference and normal parameter

The first method passes n by value, i.e. a copy of n is sent to the function. The second one passes n by reference which basically means that a pointer to the n with which the function is called is sent to the function.

For integral types like int it doesn't make much sense to pass as a const reference since the size of the reference is usually the same as the size of the reference (the pointer). In the cases where making a copy is expensive it's usually best to pass by const reference.

Why can't I have "public static const string S = "stuff"; in my Class?

A const member is considered static by the compiler, as well as implying constant value semantics, which means references to the constant might be compiled into the using code as the value of the constant member, instead of a reference to the member.

In other words, a const member containing the value 10, might get compiled into code that uses it as the number 10, instead of a reference to the const member.

This is different from a static readonly field, which will always be compiled as a reference to the field.

Note, this is pre-JIT. When the JIT'ter comes into play, it might compile both these into the target code as values.

Why can't I initialize non-const static member or static array in class?

static variables are specific to a class . Constructors initialize attributes ESPECIALY for an instance.

define() vs. const

With define keyword constant, you will get the facilities of case insensitive but with const keyword you did not.

define("FOO", 1, true);
echo foo; //1
echo "<br/>";
echo FOO; //1
echo "<br/>";

class A {
  const FOO = 1;
}

echo A::FOO; //valid
echo "<br/>";

//but

class B {
  define FOO = 1; //syntax error, unexpected 'define'
}

echo B::FOO; //invalid

Why does JSHint throw a warning if I am using const?

I got this same warning when using an export statement. I'm using VS Code and used a similar approach to Wenlong Jiang's solution.

  1. User Settings

  2. JSHint config

  3. "jshint.config": {} (Edit)

  4. Use double quotes when specifying "esversion"

    Or copy this snippet into User Settings:

    "jshint.options": {
      "esversion": 6,
    }
    

Creating a .jshintrc file isn't necessary if you want to configure the global jshint settings for your editor

How do I turn off PHP Notices?

by not causing the errors:

defined('DIR_FS_CATALOG') || define('DIR_FS_CATALOG', 'whatever');

If you really have to, then change error reporting using error_reporting() to E_ALL^E_NOTICE.

How to define constants in Visual C# like #define in C?

Check How to: Define Constants in C# on MSDN:

In C# the #define preprocessor directive cannot be used to define constants in the way that is typically used in C and C++.

Constants in Kotlin -- what's a recommended way to create them?

There are a few ways you can define constants in Kotlin,

Using companion object

    companion object {
        const val ITEM1 = "item1"
        const val ITEM2 = "item2"
    }

you can use above companion object block inside any class and define all your fields inside this block itself. But there is a problem with this approach, the documentation says,

even though the members of companion objects look like static members in other languages, at runtime those are still instance members of real objects, and can, for example, implement interfaces.

When you create your constants using companion object, and see the decompiled bytecode, you'll something like below,

  ClassName.Companion Companion = ClassName.Companion.$$INSTANCE;
  @NotNull
  String ITEM1 = "item1";
  @NotNull
  String ITEM2 = "item2";

  public static final class Companion {
     @NotNull
     private static final String ITEM1 = "item1";
     @NotNull
     public static final String ITEM2 = "item2";

     // $FF: synthetic field
     static final ClassName.Companion $$INSTANCE;

     private Companion() {
     }

     static {
        ClassName.Companion var0 = new ClassName.Companion();
        $$INSTANCE = var0;
     }
  }

From here you can easily see what the documentation said, even though the members of companion objects look like static members in other languages, at runtime those are still instance members of real objects It's doing extra work than required.

Now comes another way, where we don't need to use companion object like below,

object ApiConstants {
      val ITEM1: String = "item1"
 }

Again if you see the decompiled version of the byte code of above snippet, you'll find something like this,

public final class ApiConstants {
     private static final String ITEM1 = "item1";

     public static final ApiConstants INSTANCE;

     public final String getITEM1() {
           return ITEM1;
      }

     private ApiConstants() {
      }

     static {
         ApiConstants var0 = new ApiConstants();
         INSTANCE = var0;
         CONNECT_TIMEOUT = "item1";
      }
    }

Now if you see the above decompiled code, it's creating get method for each variable. This get method is not required at all.

To get rid of these get methods, you should use const before val like below,

object ApiConstants {
     const val ITEM1: String = "item1"
 }

Now if you see the decompiled code of above snippet, you'll find it easier to read as it does the least background conversion for your code.

public final class ApiConstants {
    public static final String ITEM1 = "item1";
    public static final ApiConstants INSTANCE;

    private ApiConstants() {
     }

    static {
        ApiConstants var0 = new ApiConstants();
        INSTANCE = var0;
      }
    }

So this is the best way to create constants.

Proper use of const for defining functions in JavaScript

There are some very important benefits to the use of const and some would say it should be used wherever possible because of how deliberate and indicative it is.

It is, as far as I can tell, the most indicative and predictable declaration of variables in JavaScript, and one of the most useful, BECAUSE of how constrained it is. Why? Because it eliminates some possibilities available to var and let declarations.

What can you infer when you read a const? You know all of the following just by reading the const declaration statement, AND without scanning for other references to that variable:

  • the value is bound to that variable (although its underlying object is not deeply immutable)
  • it can’t be accessed outside of its immediately containing block
  • the binding is never accessed before declaration, because of Temporal Dead Zone (TDZ) rules.

The following quote is from an article arguing the benefits of let and const. It also more directly answers your question about the keyword's constraints/limits:

Constraints such as those offered by let and const are a powerful way of making code easier to understand. Try to accrue as many of these constraints as possible in the code you write. The more declarative constraints that limit what a piece of code could mean, the easier and faster it is for humans to read, parse, and understand a piece of code in the future.

Granted, there’s more rules to a const declaration than to a var declaration: block-scoped, TDZ, assign at declaration, no reassignment. Whereas var statements only signal function scoping. Rule-counting, however, doesn’t offer a lot of insight. It is better to weigh these rules in terms of complexity: does the rule add or subtract complexity? In the case of const, block scoping means a narrower scope than function scoping, TDZ means that we don’t need to scan the scope backwards from the declaration in order to spot usage before declaration, and assignment rules mean that the binding will always preserve the same reference.

The more constrained statements are, the simpler a piece of code becomes. As we add constraints to what a statement might mean, code becomes less unpredictable. This is one of the biggest reasons why statically typed programs are generally easier to read than dynamically typed ones. Static typing places a big constraint on the program writer, but it also places a big constraint on how the program can be interpreted, making its code easier to understand.

With these arguments in mind, it is recommended that you use const where possible, as it’s the statement that gives us the least possibilities to think about.

Source: https://ponyfoo.com/articles/var-let-const

'const int' vs. 'int const' as function parameters in C++ and C

They are the same, but in C++ there's a good reason to always use const on the right. You'll be consistent everywhere because const member functions must be declared this way:

int getInt() const;

It changes the this pointer in the function from Foo * const to Foo const * const. See here.

Creating a constant Dictionary in C#

enum Constants
{
    Abc = 1,
    Def = 2,
    Ghi = 3
}

...

int i = (int)Enum.Parse(typeof(Constants), "Def");

How do I create a constant in Python?

In Python instead of language enforcing something, people use naming conventions e.g __method for private methods and using _method for protected methods.

So in same manner you can simply declare the constant as all caps e.g.

MY_CONSTANT = "one"

If you want that this constant never changes, you can hook into attribute access and do tricks, but a simpler approach is to declare a function

def MY_CONSTANT():
    return "one"

Only problem is everywhere you will have to do MY_CONSTANT(), but again MY_CONSTANT = "one" is the correct way in python(usually).

You can also use namedtuple to create constants:

>>> from collections import namedtuple
>>> Constants = namedtuple('Constants', ['pi', 'e'])
>>> constants = Constants(3.14, 2.718)
>>> constants.pi
3.14
>>> constants.pi = 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute

What is the best way to implement constants in Java?

I wouldn't call the class the same (aside from casing) as the constant ... I would have at a minimum one class of "Settings", or "Values", or "Constants", where all the constants would live. If I have a large number of them, I'd group them up in logical constant classes (UserSettings, AppSettings, etc.)

Variably modified array at file scope

If you're going to use the preprocessor anyway, as per the other answers, then you can make the compiler determine the value of NUM_TYPES automagically:

#define NUM_TYPES (sizeof types / sizeof types[0])
static int types[] = { 
  1,
  2, 
  3, 
  4 };

Is it better in C++ to pass by value or pass by constant reference?

As a rule of thumb, value for non-class types and const reference for classes. If a class is really small it's probably better to pass by value, but the difference is minimal. What you really want to avoid is passing some gigantic class by value and having it all duplicated - this will make a huge difference if you're passing, say, a std::vector with quite a few elements in it.

How to initialize a private static const map in C++?

#include <map>
using namespace std;

struct A{
    static map<int,int> create_map()
        {
          map<int,int> m;
          m[1] = 2;
          m[3] = 4;
          m[5] = 6;
          return m;
        }
    static const map<int,int> myMap;

};

const map<int,int> A:: myMap =  A::create_map();

int main() {
}

PHP Constants Containing Arrays?

Since PHP 5.6, you can declare an array constant with const:

<?php
const DEFAULT_ROLES = array('guy', 'development team');

The short syntax works too, as you'd expect:

<?php
const DEFAULT_ROLES = ['guy', 'development team'];

If you have PHP 7, you can finally use define(), just as you had first tried:

<?php
define('DEFAULT_ROLES', array('guy', 'development team'));

'Static readonly' vs. 'const'

One thing to note is const is restricted to primitive/value types (the exception being strings).

How to set python variables to true or false?

you have to use capital True and False not true and false

How can I specify a [DllImport] path at runtime?

If you need a .dll file that is not on the path or on the application's location, then I don't think you can do just that, because DllImport is an attribute, and attributes are only metadata that is set on types, members and other language elements.

An alternative that can help you accomplish what I think you're trying, is to use the native LoadLibrary through P/Invoke, in order to load a .dll from the path you need, and then use GetProcAddress to get a reference to the function you need from that .dll. Then use these to create a delegate that you can invoke.

To make it easier to use, you can then set this delegate to a field in your class, so that using it looks like calling a member method.

EDIT

Here is a code snippet that works, and shows what I meant.

class Program
{
    static void Main(string[] args)
    {
        var a = new MyClass();
        var result = a.ShowMessage();
    }
}

class FunctionLoader
{
    [DllImport("Kernel32.dll")]
    private static extern IntPtr LoadLibrary(string path);

    [DllImport("Kernel32.dll")]
    private static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

    public static Delegate LoadFunction<T>(string dllPath, string functionName)
    {
        var hModule = LoadLibrary(dllPath);
        var functionAddress = GetProcAddress(hModule, functionName);
        return Marshal.GetDelegateForFunctionPointer(functionAddress, typeof (T));
    }
}

public class MyClass
{
    static MyClass()
    {
        // Load functions and set them up as delegates
        // This is just an example - you could load the .dll from any path,
        // and you could even determine the file location at runtime.
        MessageBox = (MessageBoxDelegate) 
            FunctionLoader.LoadFunction<MessageBoxDelegate>(
                @"c:\windows\system32\user32.dll", "MessageBoxA");
    }

    private delegate int MessageBoxDelegate(
        IntPtr hwnd, string title, string message, int buttons); 

    /// <summary>
    /// This is the dynamic P/Invoke alternative
    /// </summary>
    static private MessageBoxDelegate MessageBox;

    /// <summary>
    /// Example for a method that uses the "dynamic P/Invoke"
    /// </summary>
    public int ShowMessage()
    {
        // 3 means "yes/no/cancel" buttons, just to show that it works...
        return MessageBox(IntPtr.Zero, "Hello world", "Loaded dynamically", 3);
    }
}

Note: I did not bother to use FreeLibrary, so this code is not complete. In a real application, you should take care to release the loaded modules to avoid a memory leak.

const to Non-const Conversion in C++

Changing a constant type will lead to an Undefined Behavior.

However, if you have an originally non-const object which is pointed to by a pointer-to-const or referenced by a reference-to-const then you can use const_cast to get rid of that const-ness.

Casting away constness is considered evil and should not be avoided. You should consider changing the type of the pointers you use in vector to non-const if you want to modify the data through it.

static const vs #define

If you are defining a constant to be shared among all the instances of the class, use static const. If the constant is specific to each instance, just use const (but note that all constructors of the class must initialize this const member variable in the initialization list).

Difference between `constexpr` and `const`

As @0x499602d2 already pointed out, const only ensures that a value cannot be changed after initialization where as constexpr (introduced in C++11) guarantees the variable is a compile time constant.
Consider the following example(from LearnCpp.com):

cout << "Enter your age: ";
int age;
cin >> age;

const int myAge{age};        // works
constexpr int someAge{age};  // error: age can only be resolved at runtime

invalid use of non-static member function

You must make Foo::comparator static or wrap it in a std::mem_fun class object. This is because lower_bounds() expects the comparer to be a class of object that has a call operator, like a function pointer or a functor object. Also, if you are using C++11 or later, you can also do as dwcanillas suggests and use a lambda function. C++11 also has std::bind too.

Examples:

// Binding:
std::lower_bounds(first, last, value, std::bind(&Foo::comparitor, this, _1, _2));
// Lambda:
std::lower_bounds(first, last, value, [](const Bar & first, const Bar & second) { return ...; });

How to declare a constant in Java

final means that the value cannot be changed after initialization, that's what makes it a constant. static means that instead of having space allocated for the field in each object, only one instance is created for the class.

So, static final means only one instance of the variable no matter how many objects are created and the value of that variable can never change.

Static constant string (class member)

Inside class definitions you can only declare static members. They have to be defined outside of the class. For compile-time integral constants the standard makes the exception that you can "initialize" members. It's still not a definition, though. Taking the address would not work without definition, for example.

I'd like to mention that I don't see the benefit of using std::string over const char[] for constants. std::string is nice and all but it requires dynamic initialization. So, if you write something like

const std::string foo = "hello";

at namespace scope the constructor of foo will be run right before execution of main starts and this constructor will create a copy of the constant "hello" in the heap memory. Unless you really need RECTANGLE to be a std::string you could just as well write

// class definition with incomplete static member could be in a header file
class A {
    static const char RECTANGLE[];
};

// this needs to be placed in a single translation unit only
const char A::RECTANGLE[] = "rectangle";

There! No heap allocation, no copying, no dynamic initialization.

Cheers, s.

How to initialize const member variable in a class?

Another solution is

class T1
{
    enum
    {
        t = 100
    };

    public:
    T1();
};

So t is initialised to 100 and it cannot be changed and it is private.

Purpose of returning by const value?

It could be used as a wrapper function for returning a reference to a private constant data type. For example in a linked list you have the constants tail and head, and if you want to determine if a node is a tail or head node, then you can compare it with the value returned by that function.

Though any optimizer would most likely optimize it out anyway...

How to convert a std::string to const char* or char*?

If you just want to pass a std::string to a function that needs const char* you can use

std::string str;
const char * c = str.c_str();

If you want to get a writable copy, like char *, you can do that with this:

std::string str;
char * writable = new char[str.size() + 1];
std::copy(str.begin(), str.end(), writable);
writable[str.size()] = '\0'; // don't forget the terminating 0

// don't forget to free the string after finished using it
delete[] writable;

Edit: Notice that the above is not exception safe. If anything between the new call and the delete call throws, you will leak memory, as nothing will call delete for you automatically. There are two immediate ways to solve this.

boost::scoped_array

boost::scoped_array will delete the memory for you upon going out of scope:

std::string str;
boost::scoped_array<char> writable(new char[str.size() + 1]);
std::copy(str.begin(), str.end(), writable.get());
writable[str.size()] = '\0'; // don't forget the terminating 0

// get the char* using writable.get()

// memory is automatically freed if the smart pointer goes 
// out of scope

std::vector

This is the standard way (does not require any external library). You use std::vector, which completely manages the memory for you.

std::string str;
std::vector<char> writable(str.begin(), str.end());
writable.push_back('\0');

// get the char* using &writable[0] or &*writable.begin()

Why Is `Export Default Const` invalid?

To me this is just one of many idiosyncracies (emphasis on the idio(t) ) of typescript that causes people to pull out their hair and curse the developers. Maybe they could work on coming up with more understandable error messages.

What does the PHP error message "Notice: Use of undefined constant" mean?

Am not sure if there is any difference am using code igniter and i use "" for the names and it works great.

$department = mysql_real_escape_string($_POST["department"]);
$name = mysql_real_escape_string($_POST["name"]);
$email = mysql_real_escape_string($_POST["email"]);
$message = mysql_real_escape_string($_POST["message"]);

regards,

Jorge.

What is the difference between const int*, const int * const, and int const *?

The C and C++ declaration syntax has repeatedly been described as a failed experiment, by the original designers.

Instead, let's name the type “pointer to Type”; I’ll call it Ptr_:

template< class Type >
using Ptr_ = Type*;

Now Ptr_<char> is a pointer to char.

Ptr_<const char> is a pointer to const char.

And const Ptr_<const char> is a const pointer to const char.

There.

enter image description here

C# naming convention for constants?

In its article Constants (C# Programming Guide), Microsoft gives the following example:

class Calendar3
{
    const int months = 12;
    const int weeks = 52;
    const int days = 365;

    const double daysPerWeek = (double) days / (double) weeks;
    const double daysPerMonth = (double) days / (double) months;
}

So, for constants, it appears that Microsoft is recommending the use of camelCasing. But note that these constants are defined locally.

Arguably, the naming of externally-visible constants is of greater interest. In practice, Microsoft documents its public constants in the .NET class library as fields. Here are some examples:

The first two are examples of PascalCasing. The third appears to follow Microsoft's Capitalization Conventions for a two-letter acronym (although pi is not an acryonym). And the fourth one seems to suggest that the rule for a two-letter acryonym extends to a single letter acronym or identifier such as E (which represents the mathematical constant e).

Furthermore, in its Capitalization Conventions document, Microsoft very directly states that field identifiers should be named via PascalCasing and gives the following examples for MessageQueue.InfiniteTimeout and UInt32.Min:

public class MessageQueue
{
    public static readonly TimeSpan InfiniteTimeout;
}

public struct UInt32
{
    public const Min = 0;
}

Conclusion: Use PascalCasing for public constants (which are documented as const or static readonly fields).

Finally, as far as I know, Microsoft does not advocate specific naming or capitalization conventions for private identifiers as shown in the examples presented in the question.

Constants in Objective-C

Try using a class method:

+(NSString*)theMainTitle
{
    return @"Hello World";
}

I use it sometimes.

What is meant with "const" at end of function declaration?

Bar is guaranteed not to change the object it is being invoked on. See the section about const correctness in the C++ FAQ, for example.

What is the difference between const and readonly in C#?

  • when to use const or readonly

    • const

      • compile-time constant: absolute constant, value is set during declaration, is in the IL code itself
    • readonly

      • run-time constant: can be set in the constructor/init via config file i.e. App.config, but once it initializes it can't be changed

Difference between char* and const char*?

char mystring[101] = "My sample string";
const char * constcharp = mystring; // (1)
char const * charconstp = mystring; // (2) the same as (1)
char * const charpconst = mystring; // (3)

constcharp++; // ok
charconstp++; // ok
charpconst++; // compile error

constcharp[3] = '\0'; // compile error
charconstp[3] = '\0'; // compile error
charpconst[3] = '\0'; // ok

// String literals
char * lcharp = "My string literal";
const char * lconstcharp = "My string literal";

lcharp[0] = 'X';      // Segmentation fault (crash) during run-time
lconstcharp[0] = 'X'; // compile error

// *not* a string literal
const char astr[101] = "My mutable string";
astr[0] = 'X';          // compile error
((char*)astr)[0] = 'X'; // ok

How to sort with a lambda?

Can the problem be with the "a.mProperty > b.mProperty" line? I've gotten the following code to work:

#include <algorithm>
#include <vector>
#include <iterator>
#include <iostream>
#include <sstream>

struct Foo
{
    Foo() : _i(0) {};

    int _i;

    friend std::ostream& operator<<(std::ostream& os, const Foo& f)
    {
        os << f._i;
        return os;
    };
};

typedef std::vector<Foo> VectorT;

std::string toString(const VectorT& v)
{
    std::stringstream ss;
    std::copy(v.begin(), v.end(), std::ostream_iterator<Foo>(ss, ", "));
    return ss.str();
};

int main()
{

    VectorT v(10);
    std::for_each(v.begin(), v.end(),
            [](Foo& f)
            {
                f._i = rand() % 100;
            });

    std::cout << "before sort: " << toString(v) << "\n";

    sort(v.begin(), v.end(),
            [](const Foo& a, const Foo& b)
            {
                return a._i > b._i;
            });

    std::cout << "after sort:  " << toString(v) << "\n";
    return 1;
};

The output is:

before sort: 83, 86, 77, 15, 93, 35, 86, 92, 49, 21,
after sort:  93, 92, 86, 86, 83, 77, 49, 35, 21, 15,

constant pointer vs pointer on a constant value

Trying to answer in simple way:

char * const a;  => a is (const) constant (*) pointer of type char {L <- R}. =>( Constant Pointer )
const char * a;  => a is (*) pointer to char constant             {L <- R}. =>( Pointer to Constant)

Constant Pointer:

pointer is constant !!. i.e, the address it is holding can't be changed. It will be stored in read only memory.

Let's try to change the address of pointer to understand more:

char * const a = &b; 
char c;
a = &c; // illegal , you can't change the address. `a` is const at L-value, so can't change. `a` is read-only variable.

It means once constant pointer points some thing it is forever.

pointer a points only b.

However you can change the value of b eg:

char b='a';
char * const a =&b;

printf("\n print a  : [%c]\n",*a);
*a = 'c';
printf("\n now print a  : [%c]\n",*a);

Pointer to Constant:

Value pointed by the pointer can't be changed.

const char *a;
char b = 'b';
const char * a =&b;
char c;
a=&c; //legal

*a = 'c'; // illegal , *a is pointer to constant can't change!.

Use of 'const' for function parameters

Extra Superfluous const are bad from an API stand-point:

Putting extra superfluous const's in your code for intrinsic type parameters passed by value clutters your API while making no meaningful promise to the caller or API user (it only hampers the implementation).

Too many 'const' in an API when not needed is like "crying wolf", eventually people will start ignoring 'const' because it's all over the place and means nothing most of the time.

The "reductio ad absurdum" argument to extra consts in API are good for these first two points would be is if more const parameters are good, then every argument that can have a const on it, SHOULD have a const on it. In fact, if it were truly that good, you'd want const to be the default for parameters and have a keyword like "mutable" only when you want to change the parameter.

So lets try putting in const whereever we can:

void mungerum(char * buffer, const char * mask, int count);

void mungerum(char * const buffer, const char * const mask, const int count);

Consider the line of code above. Not only is the declaration more cluttered and longer and harder to read but three of the four 'const' keywords can be safely ignored by the API user. However, the extra use of 'const' has made the second line potentially DANGEROUS!

Why?

A quick misread of the first parameter char * const buffer might make you think that it will not modify the memory in data buffer that is passed in -- however, this is not true! Superfluous 'const' can lead to dangerous and incorrect assumptions about your API when scanned or misread quickly.


Superfluous const are bad from a Code Implementation stand-point as well:

#if FLEXIBLE_IMPLEMENTATION
       #define SUPERFLUOUS_CONST
#else
       #define SUPERFLUOUS_CONST             const
#endif

void bytecopy(char * SUPERFLUOUS_CONST dest,
   const char *source, SUPERFLUOUS_CONST int count);

If FLEXIBLE_IMPLEMENTATION is not true, then the API is “promising” not to implement the function the first way below.

void bytecopy(char * SUPERFLUOUS_CONST dest,
   const char *source, SUPERFLUOUS_CONST int count)
{
       // Will break if !FLEXIBLE_IMPLEMENTATION
       while(count--)
       {
              *dest++=*source++;
       }
}

void bytecopy(char * SUPERFLUOUS_CONST dest,
   const char *source, SUPERFLUOUS_CONST int count)
{
       for(int i=0;i<count;i++)
       {
              dest[i]=source[i];
       }
}

That’s a very silly promise to make. Why should you make a promise that gives no benefit at all to your caller and only limits your implementation?

Both of these are perfectly valid implementations of the same function though so all you’ve done is tied one hand behind your back unnecessarily.

Furthermore, it’s a very shallow promise that is easily (and legally circumvented).

inline void bytecopyWrapped(char * dest,
   const char *source, int count)
{
       while(count--)
       {
              *dest++=*source++;
       }
}
void bytecopy(char * SUPERFLUOUS_CONST dest,
   const char *source,SUPERFLUOUS_CONST int count)
{
    bytecopyWrapped(dest, source, count);
}

Look, I implemented it that way anyhow even though I promised not to – just using a wrapper function. It’s like when the bad guy promises not to kill someone in a movie and orders his henchman to kill them instead.

Those superfluous const’s are worth no more than a promise from a movie bad-guy.


But the ability to lie gets even worse:

I have been enlightened that you can mismatch const in header (declaration) and code (definition) by using spurious const. The const-happy advocates claim this is a good thing since it lets you put const only in the definition.

// Example of const only in definition, not declaration
struct foo { void test(int *pi); };
void foo::test(int * const pi) { }

However, the converse is true... you can put a spurious const only in the declaration and ignore it in the definition. This only makes superfluous const in an API more of a terrible thing and a horrible lie - see this example:

struct foo
{
    void test(int * const pi);
};

void foo::test(int *pi) // Look, the const in the definition is so superfluous I can ignore it here
{
    pi++;  // I promised in my definition I wouldn't modify this
}

All the superfluous const actually does is make the implementer's code less readable by forcing him to use another local copy or a wrapper function when he wants to change the variable or pass the variable by non-const reference.

Look at this example. Which is more readable ? Is it obvious that the only reason for the extra variable in the second function is because some API designer threw in a superfluous const ?

struct llist
{
    llist * next;
};

void walkllist(llist *plist)
{
    llist *pnext;
    while(plist)
    {
        pnext=plist->next;
        walk(plist);
        plist=pnext;    // This line wouldn't compile if plist was const
    }
}

void walkllist(llist * SUPERFLUOUS_CONST plist)
{
    llist * pnotconst=plist;
    llist *pnext;
    while(pnotconst)
    {
        pnext=pnotconst->next;
        walk(pnotconst);
        pnotconst=pnext;
    }
}

Hopefully we've learned something here. Superfluous const is an API-cluttering eyesore, an annoying nag, a shallow and meaningless promise, an unnecessary hindrance, and occasionally leads to very dangerous mistakes.

Java constant examples (Create a java file having only constants)

This question is old. But I would like to mention an other approach. Using Enums for declaring constant values. Based on the answer of Nandkumar Tekale, the Enum can be used as below:

Enum:

public enum Planck {
    REDUCED();
    public static final double PLANCK_CONSTANT = 6.62606896e-34;
    public static final double PI = 3.14159;
    public final double REDUCED_PLANCK_CONSTANT;

    Planck() {
        this.REDUCED_PLANCK_CONSTANT = PLANCK_CONSTANT / (2 * PI);
    }

    public double getValue() {
        return REDUCED_PLANCK_CONSTANT;
    }
}

Client class:

public class PlanckClient {

    public static void main(String[] args) {
        System.out.println(getReducedPlanckConstant());
        // or using Enum itself as below:
        System.out.println(Planck.REDUCED.getValue());
    }

    public static double getReducedPlanckConstant() {
        return Planck.PLANCK_CONSTANT / (2 * Planck.PI);
    }

}

Reference : The usage of Enums for declaring constant fields is suggested by Joshua Bloch in his Effective Java book.

Define constant variables in C++ header

You could simply define a series of const ints in a header file:

// Constants.h
#if !defined(MYLIB_CONSTANTS_H)
#define MYLIB_CONSTANTS_H 1

const int a = 100;
const int b = 0x7f;

#endif

This works because in C++ a name at namespace scope (including the global namespace) that is explicitly declared const and not explicitly declared extern has internal linkage, so these variables would not cause duplicate symbols when you link together translation units. Alternatively you could explicitly declare the constants as static.

static const int a = 100;
static const int b = 0x7f;

This is more compatible with C and more readable for people that may not be familiar with C++ linkage rules.

If all the constants are ints then another method you could use is to declare the identifiers as enums.

enum mylib_constants {
    a = 100;
    b = 0x7f;
};

All of these methods use only a header and allow the declared names to be used as compile time constants. Using extern const int and a separate implementation file prevents the names from being used as compile time constants.


Note that the rule that makes certain constants implicitly internal linkage does apply to pointers, exactly like constants of other types. The tricky thing though is that marking a pointer as const requires syntax a little different that most people use to make variables of other types const. You need to do:

int * const ptr;

to make a constant pointer, so that the rule will apply to it.

Also note that this is one reason I prefer to consistently put const after the type: int const instead of const int. I also put the * next to the variable: i.e. int *ptr; instead of int* ptr; (compare also this discussion).

I like to do these sorts of things because they reflect the general case of how C++ really works. The alternatives (const int, int* p) are just special cased to make some simple things more readable. The problem is that when you step out of those simple cases, the special cased alternatives become actively misleading.

So although the earlier examples show the common usage of const, I would actually recommend people write them like this:

int const a = 100;
int const b = 0x7f;

and

static int const a = 100;
static int const b = 0x7f;

Class constants in python

Since Horse is a subclass of Animal, you can just change

print(Animal.SIZES[1])

with

print(self.SIZES[1])

Still, you need to remember that SIZES[1] means "big", so probably you could improve your code by doing something like:

class Animal:
    SIZE_HUGE="Huge"
    SIZE_BIG="Big"
    SIZE_MEDIUM="Medium"
    SIZE_SMALL="Small"

class Horse(Animal):
    def printSize(self):
        print(self.SIZE_BIG)

Alternatively, you could create intermediate classes: HugeAnimal, BigAnimal, and so on. That would be especially helpful if each animal class will contain different logic.

Why is there no Constant feature in Java?

const in C++ does not mean that a value is a constant.

const in C++ implies that the client of a contract undertakes not to alter its value.

Whether the value of a const expression changes becomes more evident if you are in an environment which supports thread based concurrency.

As Java was designed from the start to support thread and lock concurrency, it didn't add to confusion by overloading the term to have the semantics that final has.

eg:

#include <iostream>

int main ()
{
    volatile const int x = 42;

    std::cout << x << std::endl;

    *const_cast<int*>(&x) = 7;

    std::cout << x << std::endl;

    return 0;
}

outputs 42 then 7.

Although x marked as const, as a non-const alias is created, x is not a constant. Not every compiler requires volatile for this behaviour (though every compiler is permitted to inline the constant)

With more complicated systems you get const/non-const aliases without use of const_cast, so getting into the habit of thinking that const means something won't change becomes more and more dangerous. const merely means that your code can't change it without a cast, not that the value is constant.

What is a constant reference? (not a reference to a constant)

The clearest answer. Does “X& const x” make any sense?

No, it is nonsense

To find out what the above declaration means, read it right-to-left: “x is a const reference to a X”. But that is redundant — references are always const, in the sense that you can never reseat a reference to make it refer to a different object. Never. With or without the const.

In other words, “X& const x” is functionally equivalent to “X& x”. Since you’re gaining nothing by adding the const after the &, you shouldn’t add it: it will confuse people — the const will make some people think that the X is const, as if you had said “const X& x”.

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

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

#include <vector>

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

Your third call

int size = v.size();

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

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

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

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

Create a GUID in Java

The other Answers are correct, especially this one by Stephen C.

Reaching Outside Java

Generating a UUID value within Java is limited to Version 4 (random) because of security concerns.

If you want other versions of UUIDs, one avenue is to have your Java app reach outside the JVM to generate UUIDs by calling on:

  • Command-line utility
    Bundled with nearly every operating system.
    For example, uuidgen found in Mac OS X, BSD, and Linux.
  • Database server
    Use JDBC to retrieve a UUID generated on the database server.
    For example, the uuid-ossp extension often bundled with Postgres. That extension can generates Versions 1, 3, and 4 values and additionally a couple variations:
    • uuid_generate_v1mc() – generates a version 1 UUID but uses a random multicast MAC address instead of the real MAC address of the computer.
    • uuid_generate_v5(namespace uuid, name text) – generates a version 5 UUID, which works like a version 3 UUID except that SHA-1 is used as a hashing method.
  • Web Service
    For example, UUID Generator creates Versions 1 & 3 as well as nil values and GUID.

Pass array to ajax request in $.ajax()

NOTE: Doesn't work on newer versions of jQuery.

Since you are using jQuery please use it's seralize function to serialize data and then pass it into the data parameter of ajax call:

info[0] = 'hi';
info[1] = 'hello';

var data_to_send = $.serialize(info);

$.ajax({
    type: "POST",
    url: "index.php",
    data: data_to_send,
    success: function(msg){
        $('.answer').html(msg);
    }
});

The APK file does not exist on disk

In Android Studio 3.1.1 select File | Sync Project with Gradle Files.

In Android Studio 3, select File | Synchronize.

Then run your project again.

Expand/collapse section in UITableView in iOS

So, based on the 'button in header' solution, here is a clean and minimalist implementation:

  • you keep track of collapsed (or expanded) sections in a property
  • you tag the button with the section index
  • you set a selected state on that button to change the arrow direction (like ? and ?)

Here is the code:

@interface MyTableViewController ()
@property (nonatomic, strong) NSMutableIndexSet *collapsedSections;
@end

...

@implementation MyTableViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (!self)
        return;
    self.collapsedSections = [NSMutableIndexSet indexSet];
    return self;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // if section is collapsed
    if ([self.collapsedSections containsIndex:section])
        return 0;

    // if section is expanded
#warning incomplete implementation
    return [super tableView:tableView numberOfRowsInSection:section];
}

- (IBAction)toggleSectionHeader:(UIView *)sender
{
    UITableView *tableView = self.tableView;
    NSInteger section = sender.tag;

    MyTableViewHeaderFooterView *headerView = (MyTableViewHeaderFooterView *)[self tableView:tableView viewForHeaderInSection:section];

    if ([self.collapsedSections containsIndex:section])
    {
        // section is collapsed
        headerView.button.selected = YES;
        [self.collapsedSections removeIndex:section];
    }
    else
    {
        // section is expanded
        headerView.button.selected = NO;
        [self.collapsedSections addIndex:section];
    }

    [tableView beginUpdates];
    [tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationAutomatic];
    [tableView endUpdates];
}

@end

Calculating text width

Slight change to Nico's, since .children() will return an empty set if we're referencing a text element like an h1 or p. So we'll use .contents() instead, and use this instead of $(this) since we're creating a method on a jQuery object.

$.fn.textWidth = function(){
    var contents = this.contents(),
        wrapper  = '<span style="display: inline-block;" />',
        width    = '';

    contents.wrapAll(wrapper);
    width = contents.parent().width(); // parent is now the wrapper
    contents.unwrap();
    return width;
    };

Jquery/Ajax call with timer

If you want to set something on a timer, you can use JavaScript's setTimeout or setInterval methods:

setTimeout ( expression, timeout );
setInterval ( expression, interval );

Where expression is a function and timeout and interval are integers in milliseconds. setTimeout runs the timer once and runs the expression once whereas setInterval will run the expression every time the interval passes.

So in your case it would work something like this:

setInterval(function() {
    //call $.ajax here
}, 5000); //5 seconds

As far as the Ajax goes, see jQuery's ajax() method. If you run an interval, there is nothing stopping you from calling the same ajax() from other places in your code.


If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:

setInterval() returns an integer which is the ID of the interval.

var id = setInterval(function() {
    //call $.ajax here
}, 30000); // 30 seconds

If you store that ID in a variable, you can then call clearInterval(id) which will stop the progression.

Then you can reinstantiate the setInterval() call after you've completed your ajax form submission.

(change) vs (ngModelChange) in angular

As I have found and wrote in another topic - this applies to angular < 7 (not sure how it is in 7+)

Just for the future

we need to observe that [(ngModel)]="hero.name" is just a short-cut that can be de-sugared to: [ngModel]="hero.name" (ngModelChange)="hero.name = $event".

So if we de-sugar code we would end up with:

<select (ngModelChange)="onModelChange()" [ngModel]="hero.name" (ngModelChange)="hero.name = $event">

or

<[ngModel]="hero.name" (ngModelChange)="hero.name = $event" select (ngModelChange)="onModelChange()">

If you inspect the above code you will notice that we end up with 2 ngModelChange events and those need to be executed in some order.

Summing up: If you place ngModelChange before ngModel, you get the $event as the new value, but your model object still holds previous value. If you place it after ngModel, the model will already have the new value.

SOURCE

IFrame: This content cannot be displayed in a frame

The X-Frame-Options is defined in the Http Header and not in the <head> section of the page you want to use in the iframe.

Accepted values are: DENY, SAMEORIGIN and ALLOW-FROM "url"

getch and arrow codes

getch () function returns two keycodes for arrow keys (and some other special keys), as mentioned in the comment by FatalError. It returns either 0 (0x00) or 224 (0xE0) first, and then returns a code identifying the key that was pressed.

For the arrow keys, it returns 224 first followed by 72 (up), 80 (down), 75 (left) and 77 (right). If the num-pad arrow keys (with NumLock off) are pressed, getch () returns 0 first instead of 224.

Please note that getch () is not standardized in any way, and these codes might vary from compiler to compiler. These codes are returned by MinGW and Visual C++ on Windows.

A handy program to see the action of getch () for various keys is:

#include <stdio.h>
#include <conio.h>

int main ()
{
    int ch;

    while ((ch = _getch()) != 27) /* 27 = Esc key */
    {
        printf("%d", ch);
        if (ch == 0 || ch == 224)
            printf (", %d", _getch ()); 
        printf("\n");
    }

    printf("ESC %d\n", ch);

    return (0);
}

This works for MinGW and Visual C++. These compilers use the name _getch () instead of getch () to indicate that it is a non-standard function.

So, you may do something like:

ch = _getch ();
if (ch == 0 || ch == 224)
{
    switch (_getch ())
    {
        case 72:
            /* Code for up arrow handling */
            break;

        case 80:
            /* Code for down arrow handling */
            break;

        /* ... etc ... */
    }
}

(413) Request Entity Too Large | uploadReadAheadSize

In my case, I was getting this error message because I was changed the service's namespace and services tag was pointed to the older namespace. I refreshed the namespace and the error disapear:

<services>
  <service name="My.Namespace.ServiceName"> <!-- Updated name -->
    <endpoint address="" 
              binding="wsHttpBinding" 
              bindingConfiguration="MyBindingConfiguratioName" 
              contract="My.Namespace.Interface" <!-- Updated contract -->
    />
  </service>
</services>

How to toggle (hide / show) sidebar div using jQuery

$(document).ready(function () {
    $(".trigger").click(function () {
        $("#sidebar").toggle("fast");
        $("#sidebar").toggleClass("active");
        return false;
    });
});


<div>
    <a class="trigger" href="#">
        <img id="icon-menu" alt='menu' height='50' src="Images/Push Pin.png" width='50' />
    </a>
</div>
<div id="sidebar">
</div>

Instead #sidebar give the id of ur div.

Code for Greatest Common Divisor in Python

I had to do something like this for a homework assignment using while loops. Not the most efficient way, but if you don't want to use a function this works:

num1 = 20
num1_list = []
num2 = 40
num2_list = []
x = 1
y = 1
while x <= num1:
    if num1 % x == 0:
        num1_list.append(x)
    x += 1
while y <= num2:
    if num2 % y == 0:
        num2_list.append(y)
    y += 1
xy = list(set(num1_list).intersection(num2_list))
print(xy[-1])

List files in local git repo?

This command:

git ls-tree --full-tree -r --name-only HEAD

lists all of the already committed files being tracked by your git repo.

Add carriage return to a string

string s2 = s1.Replace(",", ",\r\n");

How to convert an NSTimeInterval (seconds) into minutes

Brian Ramsay’s code, de-pseudofied:

- (NSString*)formattedStringForDuration:(NSTimeInterval)duration
{
    NSInteger minutes = floor(duration/60);
    NSInteger seconds = round(duration - minutes * 60);
    return [NSString stringWithFormat:@"%d:%02d", minutes, seconds];
}

Dependency Walker reports IESHIMS.DLL and WER.DLL missing?

ieshims.dll is an artefact of Vista/7 where a shim DLL is used to proxy certain calls (such as CreateProcess) to handle protected mode IE, which doesn't exist on XP, so it is unnecessary. wer.dll is related to Windows Error Reporting and again is probably unused on Windows XP which has a slightly different error reporting system than Vista and above.

I would say you shouldn't need either of them to be present on XP and would normally be delay loaded anyway.

Hide html horizontal but not vertical scrollbar

selector{
 overflow-y: scroll;
 overflow-x: hidden;
}

Working example with snippet and jsfiddle link https://jsfiddle.net/sx8u82xp/3/

enter image description here

_x000D_
_x000D_
.container{_x000D_
  height:100vh;_x000D_
  overflow-y:scroll;_x000D_
  overflow-x: hidden;_x000D_
  background:yellow;_x000D_
}
_x000D_
<div class="container">_x000D_
_x000D_
<p>_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
_x000D_
Why do we use it?_x000D_
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like)._x000D_
</p>_x000D_
_x000D_
<p>_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
_x000D_
Why do we use it?_x000D_
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like)._x000D_
</p>_x000D_
_x000D_
<p>_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
_x000D_
Why do we use it?_x000D_
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like)._x000D_
</p>_x000D_
_x000D_
<p>_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
_x000D_
Why do we use it?_x000D_
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like)._x000D_
</p>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the difference between MacVim and regular Vim?

The one reason I have which made switching to MacVim worth it: Yank uses the system clipboard.

I can finally copy paste between MacVim on my terminal and the rest of my applications.

Changing the image source using jQuery

In case you update the image multiple times and it gets CACHED and does not update, add a random string at the end:

// update image in dom
$('#target').attr('src', 'https://example.com/img.jpg?rand=' + Math.random());

Set color of text in a Textbox/Label to Red and make it bold in asp.net C#

Try using the property ForeColor. Like this :

TextBox1.ForeColor = Color.Red;

What is the 'realtime' process priority setting for?

Like all other answers before real time gives that program the utmost priority class. Nothing is processed until that program has been processed.
On my pentium 4 machine I set minecraft to real time a lot since it increases the game performance a lot, and the system seems completely stable. so realtime isn't as bad as it seems, just if you have a multi-core set a program's affinity to a specific core or cores (just not all of them, just to let everything else be able to run in case the real time set programs gets hung up) and set the priority to real time.

Get the value of checked checkbox?

None of the above worked for me but simply use this:

document.querySelector('.messageCheckbox').checked;

Happy coding.

PDF Blob - Pop up window not showing content

You need to set the responseType to arraybuffer if you would like to create a blob from your response data:

$http.post('/fetchBlobURL',{myParams}, {responseType: 'arraybuffer'})
   .success(function (data) {
       var file = new Blob([data], {type: 'application/pdf'});
       var fileURL = URL.createObjectURL(file);
       window.open(fileURL);
});

more information: Sending_and_Receiving_Binary_Data

Add Class to Object on Page Load

This should work:

window.onload = function() {
  document.getElementById('about').className = 'expand';
};

Or if you're using jQuery:

$(function() {
  $('#about').addClass('expand');
});

no debugging symbols found when using gdb

You should also try -ggdb instead of -g if you're compiling for Android!

HTML5 Video // Completely Hide Controls

document.addEventListener("DOMContentLoaded", function() { initialiseMediaPlayer(); }, false);


function initialiseMediaPlayer() {

    mediaPlayer = document.getElementById('media-video');

    mediaPlayer.controls = false;

    mediaPlayer.addEventListener('volumechange', function(e) { 
        // Update the button to be mute/unmute
        if (mediaPlayer.muted) changeButtonType(muteBtn, 'unmute');
        else changeButtonType(muteBtn, 'mute');
    }, false);  
    mediaPlayer.addEventListener('ended', function() { this.pause(); }, false); 
}

Read input stream twice

In case anyone is running in a Spring Boot app, and you want to read the response body of a RestTemplate (which is why I want to read a stream twice), there is a clean(er) way of doing this.

First of all, you need to use Spring's StreamUtils to copy the stream to a String:

String text = StreamUtils.copyToString(response.getBody(), Charset.defaultCharset()))

But that's not all. You also need to use a request factory that can buffer the stream for you, like so:

ClientHttpRequestFactory factory = new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory());
RestTemplate restTemplate = new RestTemplate(factory);

Or, if you're using the factory bean, then (this is Kotlin but nevertheless):

@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
fun createRestTemplate(): RestTemplate = RestTemplateBuilder()
  .requestFactory { BufferingClientHttpRequestFactory(SimpleClientHttpRequestFactory()) }
  .additionalInterceptors(loggingInterceptor)
  .build()

Source: https://objectpartners.com/2018/03/01/log-your-resttemplate-request-and-response-without-destroying-the-body/

tkinter: how to use after method

You need to give a function to be called after the time delay as the second argument to after:

after(delay_ms, callback=None, *args)

Registers an alarm callback that is called after a given time.

So what you really want to do is this:

tiles_letter = ['a', 'b', 'c', 'd', 'e']

def add_letter():
    rand = random.choice(tiles_letter)
    tile_frame = Label(frame, text=rand)
    tile_frame.pack()
    root.after(500, add_letter)
    tiles_letter.remove(rand)  # remove that tile from list of tiles


root.after(0, add_letter)  # add_letter will run as soon as the mainloop starts.
root.mainloop()

You also need to schedule the function to be called again by repeating the call to after inside the callback function, since after only executes the given function once. This is also noted in the documentation:

The callback is only called once for each call to this method. To keep calling the callback, you need to reregister the callback inside itself

Note that your example will throw an exception as soon as you've exhausted all the entries in tiles_letter, so you need to change your logic to handle that case whichever way you want. The simplest thing would be to add a check at the beginning of add_letter to make sure the list isn't empty, and just return if it is:

def add_letter():
    if not tiles_letter:
        return
    rand = random.choice(tiles_letter)
    tile_frame = Label(frame, text=rand)
    tile_frame.pack()
    root.after(500, add_letter)
    tiles_letter.remove(rand)  # remove that tile from list of tiles

Live-Demo: repl.it

How do I clear all variables in the middle of a Python script?

If you write a function then once you leave it all names inside disappear.

The concept is called namespace and it's so good, it made it into the Zen of Python:

Namespaces are one honking great idea -- let's do more of those!

The namespace of IPython can likewise be reset with the magic command %reset -f. (The -f means "force"; in other words, "don't ask me if I really want to delete all the variables, just do it.")

HtmlSpecialChars equivalent in Javascript?

Reversed one:

function decodeHtml(text) {
    return text
        .replace(/&amp;/g, '&')
        .replace(/&lt;/ , '<')
        .replace(/&gt;/, '>')
        .replace(/&quot;/g,'"')
        .replace(/&#039;/g,"'");
}

Linux Process States

A process performing I/O will be put in D state (uninterruptable sleep), which frees the CPU until there is a hardware interrupt which tells the CPU to return to executing the program. See man ps for the other process states.

Depending on your kernel, there is a process scheduler, which keeps track of a runqueue of processes ready to execute. It, along with a scheduling algorithm, tells the kernel which process to assign to which CPU. There are kernel processes and user processes to consider. Each process is allocated a time-slice, which is a chunk of CPU time it is allowed to use. Once the process uses all of its time-slice, it is marked as expired and given lower priority in the scheduling algorithm.

In the 2.6 kernel, there is a O(1) time complexity scheduler, so no matter how many processes you have up running, it will assign CPUs in constant time. It is more complicated though, since 2.6 introduced preemption and CPU load balancing is not an easy algorithm. In any case, it’s efficient and CPUs will not remain idle while you wait for the I/O.

make: Nothing to be done for `all'

Make is behaving correctly. hello already exists and is not older than the .c files, and therefore there is no more work to be done. There are four scenarios in which make will need to (re)build:

  • If you modify one of your .c files, then it will be newer than hello, and then it will have to rebuild when you run make.
  • If you delete hello, then it will obviously have to rebuild it
  • You can force make to rebuild everything with the -B option. make -B all
  • make clean all will delete hello and require a rebuild. (I suggest you look at @Mat's comment about rm -f *.o hello

HashMap to return default value for non-found keys?

It does this by default. It returns null.

How to increment a number by 2 in a PHP For Loop

Simple solution

<?php
   $x = 1;
     for($x = 1; $x < 8; $x++) {
        $x = $x + 1;
       echo $x;
     };    
?>

How to hide underbar in EditText

What I did was to create a Shape drawable and set that as the background:

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <padding
        android:top="8dp"
        android:bottom="8dp"
        android:left="8dp"
        android:right="8dp" />

    <solid android:color="#fff" />

</shape>

Note: I actually used @dimen and @color values for the firelds, but I've simplified the shape file here for clarity.

What is dtype('O'), in pandas?

'O' stands for object.

#Loading a csv file as a dataframe
import pandas as pd 
train_df = pd.read_csv('train.csv')
col_name = 'Name of Employee'

#Checking the datatype of column name
train_df[col_name].dtype

#Instead try printing the same thing
print train_df[col_name].dtype

The first line returns: dtype('O')

The line with the print statement returns the following: object

How do you completely remove the button border in wpf?

Programmatically, you can do this:

btn.BorderBrush = new SolidColorBrush(Colors.Transparent);

Convert base class to derived class

No it is not possible. The only way that is possible is

static void Main(string[] args)
{
    BaseClass myBaseObject = new DerivedClass();
    DerivedClass myDerivedObject = myBaseObject as DerivedClass;

    myDerivedObject.MyDerivedProperty = true;
}

Update with two tables?

For Microsoft Access

UPDATE TableA A
    INNER JOIN TableB B
    ON A.ID = B.ID
SET A.Name = B.Name

How do I get rid of the "cannot empty the clipboard" error?

Good answers by Paul Simon and Steve Homer, I shut down team viewer and that did the trick. Skype or other programs may trigger the same glitch, but in this instance, I recalled the problem occurred when I tried to cut n paste a 2MB file from remote system through windows right click rather than using "File Transfer function in TV. An error message appeared, then the problem with Excel "'Cannot empty clipboard' message.

This problem occurs when you are working on a remote system. After copying and pasting a huge amount of data it shows the error. I have found the solution to this problem.

Go to remote systems task manager and perform the following task

Go to Task Manager > Processes Look for "rdpclip.exe" End that process

Your problem will be solved.

Android - Using Custom Font

Yes, downloadable fonts are so easy, as Dipali s said.

This is how you do it...

  1. Place a TextView.
  2. In the properties pane, select the fontFamily dropdown. If it isn't there, find the caret thingy (the > and click on it to expand textAppearance) under the.
  3. Expand the font-family drop down.
  4. In the little list, scroll all the way down till you see more fonts
  5. This will open up a dialog box where you can search from Google Fonts
  6. Search for the font you like with the search bar at the top
  7. Select your font.
  8. Select the style of the font you like (i.e. bold, normal, italic, etc)
  9. In the right pane, choose the radio button that says Add font to project
  10. Click okay. Now your TextView has the font you like!

BONUS: If you would like to style EVERYTHING with text in your application with chosen font, just add <item name="android:fontfamily">@font/fontnamehere</item> into your styles.xml

Why is the jquery script not working?

if you have some other scripts that conflicts with jQuery wrap your code with this

(function($) {
    //here is your code
})(jQuery);

numpy get index where value is true

To get the row numbers where at least one item is larger than 15:

>>> np.where(np.any(e>15, axis=1))
(array([1, 2], dtype=int64),)

Rethrowing exceptions in Java without losing the stack trace

I would prefer:

try
{
    ...
}
catch (FooException fe){
   throw fe;
}
catch (Exception e)
{
    // Note: don't catch all exceptions like this unless you know what you
    // are doing.
    ...
}

Using Address Instead Of Longitude And Latitude With Google Maps API

Thought I'd share this code snippet that I've used before, this adds multiple addresses via Geocode and adds these addresses as Markers...

_x000D_
_x000D_
var addressesArray = [_x000D_
  'Address Str.No, Postal Area/city',_x000D_
  //follow this structure_x000D_
]_x000D_
var map = new google.maps.Map(document.getElementById('map'), {_x000D_
  center: {_x000D_
    lat: 12.7826,_x000D_
    lng: 105.0282_x000D_
  },_x000D_
  zoom: 6,_x000D_
  gestureHandling: 'cooperative'_x000D_
});_x000D_
var geocoder = new google.maps.Geocoder();_x000D_
for (i = 0; i < addressArray.length; i++) {_x000D_
  var address = addressArray[i];_x000D_
  geocoder.geocode({_x000D_
    'address': address_x000D_
  }, function(results, status) {_x000D_
    if (status === 'OK') {_x000D_
      var marker = new google.maps.Marker({_x000D_
        map: map,_x000D_
        position: results[0].geometry.location,_x000D_
        center: {_x000D_
          lat: 12.7826,_x000D_
          lng: 105.0282_x000D_
        },_x000D_
      });_x000D_
    } else {_x000D_
      alert('Geocode was not successful for the following reason: ' + status);_x000D_
    }_x000D_
  });_x000D_
}
_x000D_
_x000D_
_x000D_

Type or namespace name does not exist

I encountered this problem while using Visual Studio's Git integration to manage the project. For some reason the Windows Phone 8 project would compile just fine when targeting x86, but when I set it to target ARM, it would fail compiling with an error indicating that "Advertising" didn't exist in the Microsoft namespace.

I ended up resolving the issue by removing the Microsoft.Advertising.*.dll reference and adding it again.

What are the benefits of learning Vim?

I learned Vim. It wasn't too much effort. Now I absolutely love ci" ci( cw V:s/from/to/g

What design patterns are used in Spring framework?

Factory Method patter: BeanFactory for creating instance of an object Singleton : instance type can be singleton for a context Prototype : instance type can be prototype. Builder pattern: you can also define a method in a class who will be responsible for creating complex instance.

How to create unit tests easily in eclipse

Any unit test you could create by just pressing a button would not be worth anything. How is the tool to know what parameters to pass your method and what to expect back? Unless I'm misunderstanding your expectations.

Close to that is something like FitNesse, where you can set up tests, then separately you set up a wiki page with your test data, and it runs the tests with that data, publishing the results as red/greens.

If you would be happy to make test writing much faster, I would suggest Mockito, a mocking framework that lets you very easily mock the classes around the one you're testing, so there's less setup/teardown, and you know you're really testing that one class instead of a dependent of it.

How can I make the Android emulator show the soft keyboard?

Settings > Language & input > Current keyboard > Hardware Switch ON.
It allows you to use your physical keyboard for input while at the same time showing the soft keyboard. I just tested it on Android Lollipop and it works.

How to execute only one test spec with angular-cli

Each of your .spec.ts file have all its tests grouped in describe block like this:

describe('SomeComponent', () => {...}

You can easily run just this single block, by prefixing the describe function name with f:

fdescribe('SomeComponent', () => {...}

If you have such function, no other describe blocks will run. Btw. you can do similar thing with it => fit and there is also a "blacklist" version - x. So:

  • fdescribe and fit causes only functions marked this way to run
  • xdescribe and xit causes all but functions marked this way to run

Reading column names alone in a csv file

I am just mentioning how to get all the column names from a csv file. I am using pandas library.

First we read the file.

import pandas as pd
file = pd.read_csv('details.csv')

Then, in order to just get all the column names as a list from input file use:-

columns = list(file.head(0))

How to create a readonly textbox in ASP.NET MVC3 Razor

The solution with TextBoxFor is OK, but if you don't want to see the field like EditBox stylish (it might be a little confusing for the user) involve changes as follows:

  1. Razor code before changes

    <div class="editor-field">
         @Html.EditorFor(model => model.Text)
         @Html.ValidationMessageFor(model => model.Text)
    </div>
    
  2. After changes

    <!-- New div display-field (after div editor-label) -->
    <div class="display-field">
        @Html.DisplayFor(model => model.Text)
    </div>
    
    <div class="editor-field">
        <!-- change to HiddenFor in existing div editor-field -->
        @Html.HiddenFor(model => model.Text)
        @Html.ValidationMessageFor(model => model.Text)
    </div>
    

Generally, this solution prevents field from editing, but shows value of it. There is no need for code-behind modifications.

How to specify a port number in SQL Server connection string?

Use a comma to specify a port number with SQL Server:

mycomputer.test.xxx.com,1234

It's not necessary to specify an instance name when specifying the port.

Lots more examples at http://www.connectionstrings.com/. It's saved me a few times.

jQuery: How can I show an image popup onclick of the thumbnail?

prettyPhoto is a jQuery lightbox clone. Not only does it support images, it also support for videos, flash, YouTube, iframes and ajax. It’s a full blown media lightbox

Ripple effect on Android Lollipop CardView

If there is a root layout like RelativeLayout or LinearLayout which contain all of the adapter item's component in CardView, you have to set background attribute in that root layout. like:

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="122dp"
android:layout_marginBottom="6dp"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
card_view:cardCornerRadius="4dp">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/touch_bg"/>
</android.support.v7.widget.CardView>

Url to a google maps page to show a pin given a latitude / longitude?

You should be able to do something like this:

http://maps.google.com/maps?q=24.197611,120.780512

Some more info on the query parameters available at this location

Here's another link to an SO thread

How to fix "Attempted relative import in non-package" even with __init__.py

Old thread. I found out that adding an __all__= ['submodule', ...] to the __init__.py file and then using the from <CURRENT_MODULE> import * in the target works fine.

How to sleep for five seconds in a batch file/cmd

I use the following method entirely based on Windows XP capabilities to do a delay in a batch file:

File DELAY.BAT

@ECHO OFF
REM DELAY seconds

REM GET ENDING SECOND
FOR /F "TOKENS=1-3 DELIMS=:." %%A IN ("%TIME%") DO SET /A H=%%A, M=1%%B%%100,     S=1%%C%%100, ENDING=(H*60+M)*60+S+%1

REM WAIT FOR SUCH A SECOND
:WAIT
FOR /F "TOKENS=1-3 DELIMS=:." %%A IN ("%TIME%") DO SET /A H=%%A, M=1%%B%%100, S=1%%C%%100, CURRENT=(H*60+M)*60+S
IF %CURRENT% LSS %ENDING% GOTO WAIT

You may also insert the day in the calculation so the method also works when the delay interval pass over midnight.

How can I check what version/edition of Visual Studio is installed programmatically?

You can get the VS product version by running the following command.

"C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe" -property catalog_productDisplayVersion

Reference — What does this symbol mean in PHP?

Bitwise Operator

What is a bit? A bit is a representation of 1 or 0. Basically OFF(0) and ON(1)

What is a byte? A byte is made up of 8 bits and the highest value of a byte is 255, which would mean every bit is set. We will look at why a byte's maximum value is 255.

-------------------------------------------
|      1 Byte ( 8 bits )                  |
-------------------------------------------
|Place Value | 128| 64| 32| 16| 8| 4| 2| 1|     
-------------------------------------------

This representation of 1 Byte

1 + 2 + 4 + 8 + 16 + 32 + 64 + 128 = 255 (1 Byte)

A few examples for better understanding

The "AND" operator: &

$a =  9;
$b = 10;
echo $a & $b;

This would output the number 8. Why? Well let's see using our table example.

-------------------------------------------
|      1 Byte ( 8 bits )                  |
-------------------------------------------
|Place Value | 128| 64| 32| 16| 8| 4| 2| 1|     
-------------------------------------------
|      $a    |   0|  0|  0|  0| 1| 0| 0| 1|    
-------------------------------------------
|      $b    |   0|  0|  0|  0| 1| 0| 1| 0|
------------------------------------------- 
|      &     |   0|  0|  0|  0| 1| 0| 0| 0|
------------------------------------------- 

So you can see from the table the only bit they share together is the 8 bit.

Second example

$a =  36;
$b = 103;
echo $a & $b; // This would output the number 36.
$a = 00100100
$b = 01100111

The two shared bits are 32 and 4, which when added together return 36.

The "Or" operator: |

$a =  9;
$b = 10;
echo $a | $b;

This would output the number 11. Why?

-------------------------------------------
|      1 Byte ( 8 bits )                  |
-------------------------------------------
|Place Value | 128| 64| 32| 16| 8| 4| 2| 1|     
-------------------------------------------
|      $a    |   0|  0|  0|  0| 1| 0| 0| 1|    
-------------------------------------------
|      $b    |   0|  0|  0|  0| 1| 0| 1| 0|
------------------------------------------- 
|      |     |   0|  0|  0|  0| 1| 0| 1| 1|
-------------------------------------------

You will notice that we have 3 bits set, in the 8, 2, and 1 columns. Add those up: 8+2+1=11.

Could not create the Java virtual machine

Just be careful. You will get this message if you try to enter a command that doesn't exist like this

/usr/bin/java -v

PowerShell: how to grep command output?

There are two problems. As in the question, select-string needs to operate on the output string, which can be had from "out-string". Also, select-string doesn't operate linewise on strings that are piped to it. Here is a generic solution

(alias|out-string) -split "`n" | select-string Write 

Contains case insensitive

Add .toUpperCase() after referrer. This method turns the string into an upper case string. Then, use .indexOf() using RAL instead of Ral.

if (referrer.toUpperCase().indexOf("RAL") === -1) { 

The same can also be achieved using a Regular Expression (especially useful when you want to test against dynamic patterns):

if (!/Ral/i.test(referrer)) {
   //    ^i = Ignore case flag for RegExp

Where can I view Tomcat log files in Eclipse?

I'm not sure if you were after catalina.out or one of the other logs produced by Tomcat.

But, if you're after the catalina.out log file then follow the directions below:

  • In the servers tab, double-click on the Tomcat Server. You will get a screen called Overview.

  • Click on "Open launch configuration". Click on the "Common" tab.

  • Towards the bottom of the screen you can check the "File" checkbox and then specify a file that can be used to log your console (catalina.out) output.

  • Finally, restart the Tomcat server.

@Directive vs @Component in Angular

A component is a directive-with-a-template and the @Component decorator is actually a @Directive decorator extended with template-oriented features.

How to sort List of objects by some property

As mentioned you can sort by:

  • Making your object implement Comparable
  • Or pass a Comparator to Collections.sort

If you do both, the Comparable will be ignored and Comparator will be used. This helps that the value objects has their own logical Comparable which is most reasonable sort for your value object, while each individual use case has its own implementation.

swift 3.0 Data to String?

I came looking for the answer to the Swift 3 Data to String question and never got a good answer. After some fooling around I came up with this:

var testString = "This is a test string"
var somedata = testString.data(using: String.Encoding.utf8)
var backToString = String(data: somedata!, encoding: String.Encoding.utf8) as String!

NOW() function in PHP

You can use the PHP date function with the correct format as the parameter,

echo date("Y-m-d H:i:s");

How add items(Text & Value) to ComboBox & read them in SelectedIndexChanged (SelectedValue = null)

You can take the SelectedItem and cast it back to your class and access its properties.

 MessageBox.Show(((ComboboxItem)ComboBox_Countries_In_Silvers.SelectedItem).Value);

Edit You can try using DataTextField and DataValueField, I used it with DataSource.

ComboBox_Servers.DataTextField = "Text";
ComboBox_Servers.DataValueField = "Value";

How to see the proxy settings on windows?

An update to @rleelr:
It's possible to view proxy settings in Google Chrome:

chrome://net-internals/#http2

Then select

View live HTTP/2 sessions

Then select one of the live sessions (you need to have some tabs open). There you find:

[...]
t=504112 [st= 0] +HTTP2_SESSION  [dt=?]
                  --> host = "play.google.com:443"
                  --> proxy = "PROXY www.xxx.yyy.zzz:8080"
[...]
                              ============================

Copy rows from one Datatable to another DataTable?

Try This

    String matchString="ID0001"//assuming we have to find rows having key=ID0001
    DataTable dtTarget = new DataTable();
    dtTarget = dtSource.Clone();
    DataRow[] rowsToCopy;
    rowsToCopy = dtSource.Select("key='" + matchString + "'");
    foreach (DataRow temp in rowsToCopy)
    {
        dtTarget.ImportRow(temp);
    }

How do I know if jQuery has an Ajax request pending?

 $(function () {
        function checkPendingRequest() {
            if ($.active > 0) {
                window.setTimeout(checkPendingRequest, 1000);
                //Mostrar peticiones pendientes ejemplo: $("#control").val("Peticiones pendientes" + $.active);
            }
            else {

                alert("No hay peticiones pendientes");

            }
        };

        window.setTimeout(checkPendingRequest, 1000);
 });

View a specific Git commit

git show <revhash>

Documentation here. Or if that doesn't work, try Google Code's GIT Documentation

What's the best way to break from nested loops in JavaScript?

Already mentioned previously by swilliams, but with an example below (Javascript):

// Function wrapping inner for loop
function CriteriaMatch(record, criteria) {
  for (var k in criteria) {
    if (!(k in record))
      return false;

    if (record[k] != criteria[k])
      return false;
  }

  return true;
}

// Outer for loop implementing continue if inner for loop returns false
var result = [];

for (var i = 0; i < _table.length; i++) {
  var r = _table[i];

  if (!CriteriaMatch(r[i], criteria))
    continue;

  result.add(r);
}

Tooltip with HTML content without JavaScript

This one is very interesting,

HTML and CSS only

_x000D_
_x000D_
.help-tip {_x000D_
  position: absolute;_x000D_
  top: 18px;_x000D_
  left: 18px;_x000D_
  text-align: center;_x000D_
  background-color: #BCDBEA;_x000D_
  border-radius: 50%;_x000D_
  width: 24px;_x000D_
  height: 24px;_x000D_
  font-size: 14px;_x000D_
  line-height: 26px;_x000D_
  cursor: default;_x000D_
}_x000D_
_x000D_
.help-tip:before {_x000D_
  content: '?';_x000D_
  font-weight: bold;_x000D_
  color: #fff;_x000D_
}_x000D_
_x000D_
.help-tip:hover span {_x000D_
  display: block;_x000D_
  transform-origin: 100% 0%;_x000D_
  -webkit-animation: fadeIn 0.3s ease-in-out;_x000D_
  animation: fadeIn 0.3s ease-in-out;_x000D_
}_x000D_
_x000D_
.help-tip span {_x000D_
  display: none;_x000D_
  text-align: left;_x000D_
  background-color: #1E2021;_x000D_
  padding: 5px;_x000D_
  width: 200px;_x000D_
  position: absolute;_x000D_
  border-radius: 3px;_x000D_
  box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.2);_x000D_
  left: -4px;_x000D_
  color: #FFF;_x000D_
  font-size: 13px;_x000D_
  line-height: 1.4;_x000D_
}_x000D_
_x000D_
.help-tip span:before {_x000D_
  position: absolute;_x000D_
  content: '';_x000D_
  width: 0;_x000D_
  height: 0;_x000D_
  border: 6px solid transparent;_x000D_
  border-bottom-color: #1E2021;_x000D_
  left: 10px;_x000D_
  top: -12px;_x000D_
}_x000D_
_x000D_
.help-tip span:after {_x000D_
  width: 100%;_x000D_
  height: 40px;_x000D_
  content: '';_x000D_
  position: absolute;_x000D_
  top: -40px;_x000D_
  left: 0;_x000D_
}
_x000D_
<span class="help-tip">_x000D_
     <span > This is the inline help tip! </span>_x000D_
</span>
_x000D_
_x000D_
_x000D_

Select Multiple Fields from List in Linq

Given List<MyType1> internalUsers and List<MyType2> externalUsers, based on the shared key of an email address...


For C# 7.0+:

var matches = (
    from i in internalUsers
    join e in externalUsers
    on i.EmailAddress.ToUpperInvariant() equals e.Email.ToUpperInvariant()
    select (internalUser:i, externalUser:e)
).ToList();

Which gives you matches as a List<(MyType1, MyType2)>.

From there you can compare them if you wish:

var internal_in_external = matches.Select(m => m.internalUser).ToList();
var external_in_internal = matches.Select(m => m.externalUser).ToList();

var internal_notIn_external = internalUsers.Except(internal_in_external).ToList();
var external_notIn_internal = externalUsers.Except(external_in_internal).ToList();

internal_in_external and internal_notIn_external will be of type List<MyType1>.

external_in_internal and external_notIn_internal will be of type List<MyType2>


For versions of C# prior to 7.0:

var matches = (
    from i in internalUsers
    join e in externalUsers
    on i.EmailAddress.ToUpperInvariant() equals e.Email.ToUpperInvariant()
    select new Tuple<MyType1, MyType2>(i, e)
).ToList();

Which gives you matches as a List<Tuple<MyType1, MyType2>>.

From there you can compare them if you wish:

var internal_in_external = matches.Select(m => m.Item1).ToList();
var external_in_internal = matches.Select(m => m.Item2).ToList();

var internal_notIn_external = internalUsers.Except(internal_in_external).ToList();
var external_notIn_internal = externalUsers.Except(external_in_internal).ToList();

internal_in_external and internal_notIn_external will be of type List<MyType1>.

external_in_internal and external_notIn_internal will be of type List<MyType2>

How to check if Location Services are enabled?

public class LocationUtil {
private static final String TAG = LocationUtil.class.getSimpleName();

public static LocationManager getLocationManager(final Context context) {
    return (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}

public static boolean isNetworkProviderEnabled(final Context context) {
    return getLocationManager(context).isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}

public static boolean isGpsProviderEnabled(final Context context) {
    return getLocationManager(context).isProviderEnabled(LocationManager.GPS_PROVIDER);
}

// Returns true even if the location services are disabled. Do not use this method to detect location services are enabled.
private static boolean isPassiveProviderEnabled(final Context context) {
    return getLocationManager(context).isProviderEnabled(LocationManager.PASSIVE_PROVIDER);
}

public static boolean isLocationModeOn(final Context context) throws Exception {
    int locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
    return locationMode != Settings.Secure.LOCATION_MODE_OFF;
}

public static boolean isLocationEnabled(final Context context) {
    try {
        return isNetworkProviderEnabled(context) || isGpsProviderEnabled(context)  || isLocationModeOn(context);
    } catch (Exception e) {
        Log.e(TAG, "[isLocationEnabled] error:", e);
    }
    return false;
}

public static void gotoLocationSettings(final Activity activity, final int requestCode) {
    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    activity.startActivityForResult(intent, requestCode);
}

public static String getEnabledProvidersLogMessage(final Context context){
    try{
        return "[getEnabledProvidersLogMessage] isNetworkProviderEnabled:"+isNetworkProviderEnabled(context) +
                ", isGpsProviderEnabled:" + isGpsProviderEnabled(context) +
                ", isLocationModeOn:" + isLocationModeOn(context) +
                ", isPassiveProviderEnabled(ignored):" + isPassiveProviderEnabled(context);
    }catch (Exception e){
        Log.e(TAG, "[getEnabledProvidersLogMessage] error:", e);
        return "provider error";
    }
}

}

Use isLocationEnabled method to detect the location services are enabled.

https://github.com/Polidea/RxAndroidBle/issues/327# page will give more information why not to use passive provider, instead use location mode.

Convert a number range to another range, maintaining ratio

List comprehension one liner solution

color_array_new = [int((((x - min(node_sizes)) * 99) / (max(node_sizes) - min(node_sizes))) + 1) for x in node_sizes]

Longer version

def colour_specter(waste_amount):
color_array = []
OldRange = max(waste_amount) - min(waste_amount)
NewRange = 99
for number_value in waste_amount:
    NewValue = int((((number_value - min(waste_amount)) * NewRange) / OldRange) + 1)
    color_array.append(NewValue)
print(color_array)
return color_array

jQuery UI tabs. How to select a tab based on its id not based on index

Note: Due to changes made to jQuery 1.9 and jQuery UI, this answer is no longer the correct one. Please see @stankovski's answer below.

You need to find the tab's index first (which is just its position in a list) and then specifically select the tab using jQuery UI's provided select event (tabs->select).

var index = $('#tabs ul').index($('#tabId'));
$('#tabs ul').tabs('select', index);

Update: BTW - I do realize that this is (ultimately) still selecting by index. But, it doesn't require that you know the specific position of the tabs (particularly when they are dynamically generated as asked in the question).

Set value of hidden input with jquery

This worked for me:

$('input[name="sort_order"]').attr('value','XXX');

Assembly code vs Machine code vs Object code?

The source files of your programs are compiled into object files, and then the linker links those object files together, producing an executable file including your architecture's machine codes.

Both object file and executable file involves architecture's machine code in the form of printable and non-printable characters when it's opened by a text editor.

Nonetheless, the dichotomy between the files is that the object file(s) may contain unresolved external references (such as printf, for instance). So, it may need to be linked against other object files.. That is to say, the unresolved external references are needed to be resolved in order to get the decent runnable executable file by linking with other object files such as C/C++ runtime library's.

Android: How to create a Dialog without a title?

Use like this:

Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); 

This will remove any title bar from dialog window.

Simplest way to restart service on a remote computer

This is what I do when I have restart a service remotely with different account

Open a CMD with different login

runas /noprofile /user:DOMAIN\USERNAME cmd

Use SC to stop and start

sc \\SERVERNAME query Tomcat8
sc \\SERVERNAME stop Tomcat8
sc \\SERVERNAME start Tomcat8

How can I set a proxy server for gem?

When setting http_proxy and https_proxy, you are also probably going to need no_proxy for URLs on the same side of the proxy. https://msdn.microsoft.com/en-us/library/hh272656(v=vs.120).aspx

Which is fastest? SELECT SQL_CALC_FOUND_ROWS FROM `table`, or SELECT COUNT(*)

When choosing the "best" approach, a more important consideration than speed might be the maintainability and correctness of your code. If so, SQL_CALC_FOUND_ROWS is preferable because you only need to maintain a single query. Using a single query completely precludes the possibility of a subtle difference between the main and count queries, which may lead to an inaccurate COUNT.

postgres: upgrade a user to be a superuser?

alter user username superuser;

Is it possible to use the instanceof operator in a switch statement?

Nope, there is no way to do this. What you might want to do is however to consider Polymorphism as a way to handle these kind of problems.

Proper way to declare custom exceptions in modern Python?

"Proper way to declare custom exceptions in modern Python?"

This is fine, unless your exception is really a type of a more specific exception:

class MyException(Exception):
    pass

Or better (maybe perfect), instead of pass give a docstring:

class MyException(Exception):
    """Raise for my specific kind of exception"""

Subclassing Exception Subclasses

From the docs

Exception

All built-in, non-system-exiting exceptions are derived from this class. All user-defined exceptions should also be derived from this class.

That means that if your exception is a type of a more specific exception, subclass that exception instead of the generic Exception (and the result will be that you still derive from Exception as the docs recommend). Also, you can at least provide a docstring (and not be forced to use the pass keyword):

class MyAppValueError(ValueError):
    '''Raise when my specific value is wrong'''

Set attributes you create yourself with a custom __init__. Avoid passing a dict as a positional argument, future users of your code will thank you. If you use the deprecated message attribute, assigning it yourself will avoid a DeprecationWarning:

class MyAppValueError(ValueError):
    '''Raise when a specific subset of values in context of app is wrong'''
    def __init__(self, message, foo, *args):
        self.message = message # without this you may get DeprecationWarning
        # Special attribute you desire with your Error, 
        # perhaps the value that caused the error?:
        self.foo = foo         
        # allow users initialize misc. arguments as any other builtin Error
        super(MyAppValueError, self).__init__(message, foo, *args) 

There's really no need to write your own __str__ or __repr__. The builtin ones are very nice, and your cooperative inheritance ensures that you use it.

Critique of the top answer

Maybe I missed the question, but why not:

class MyException(Exception):
    pass

Again, the problem with the above is that in order to catch it, you'll either have to name it specifically (importing it if created elsewhere) or catch Exception, (but you're probably not prepared to handle all types of Exceptions, and you should only catch exceptions you are prepared to handle). Similar criticism to the below, but additionally that's not the way to initialize via super, and you'll get a DeprecationWarning if you access the message attribute:

Edit: to override something (or pass extra args), do this:

class ValidationError(Exception):
    def __init__(self, message, errors):

        # Call the base class constructor with the parameters it needs
        super(ValidationError, self).__init__(message)

        # Now for your custom code...
        self.errors = errors

That way you could pass dict of error messages to the second param, and get to it later with e.errors

It also requires exactly two arguments to be passed in (aside from the self.) No more, no less. That's an interesting constraint that future users may not appreciate.

To be direct - it violates Liskov substitutability.

I'll demonstrate both errors:

>>> ValidationError('foo', 'bar', 'baz').message

Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    ValidationError('foo', 'bar', 'baz').message
TypeError: __init__() takes exactly 3 arguments (4 given)

>>> ValidationError('foo', 'bar').message
__main__:1: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6
'foo'

Compared to:

>>> MyAppValueError('foo', 'FOO', 'bar').message
'foo'

Increase max_execution_time in PHP?

For increasing execution time and file size, you need to mention below values in your .htaccess file. It will work.

php_value upload_max_filesize 80M
php_value post_max_size 80M
php_value max_input_time 18000
php_value max_execution_time 18000

How to create a circle icon button in Flutter?

RawMaterialButton is better suited I think.

RawMaterialButton(
  onPressed: () {},
  elevation: 2.0,
  fillColor: Colors.white,
  child: Icon(
    Icons.pause,
    size: 35.0,
  ),
  padding: EdgeInsets.all(15.0),
  shape: CircleBorder(),
)

An efficient way to transpose a file in Bash

I normally use this little awk snippet for this requirement:

  awk '{for (i=1; i<=NF; i++) a[i,NR]=$i
        max=(max<NF?NF:max)}
        END {for (i=1; i<=max; i++)
              {for (j=1; j<=NR; j++) 
                  printf "%s%s", a[i,j], (j==NR?RS:FS)
              }
        }' file

This just loads all the data into a bidimensional array a[line,column] and then prints it back as a[column,line], so that it transposes the given input.

This needs to keep track of the maximum amount of columns the initial file has, so that it is used as the number of rows to print back.

Why do I keep getting Delete 'cr' [prettier/prettier]?

I know this is old but I just encountered the issue in my team (some mac, some linux, some windows , all vscode).

solution was to set the line ending in vscode's settings:

.vscode/settings.json

{
    "files.eol": "\n",
}

https://qvault.io/2020/06/18/how-to-get-consistent-line-breaks-in-vs-code-lf-vs-crlf/

Move cursor to end of file in vim

This is quicker. Just use this

:$

how to avoid a new line with p tag?

Flexbox works.

_x000D_
_x000D_
.box{_x000D_
  display: flex;_x000D_
  flex-flow: row nowrap;_x000D_
  justify-content: center;_x000D_
  align-content: center;_x000D_
  align-items:center;_x000D_
  border:1px solid #e3f2fd;_x000D_
}_x000D_
.item{_x000D_
  flex: 1 1 auto;_x000D_
  border:1px solid #ffebee;_x000D_
}
_x000D_
<div class="box">_x000D_
  <p class="item">A</p>_x000D_
  <p class="item">B</p>_x000D_
  <p class="item">C</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Is there a way to make a PowerShell script work by double clicking a .ps1 file?

Or if you want all PS1 files to work the way VBS files do, you can edit the registry like this:

HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\open\command

Edit the Default value to be something like so...

"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -noLogo -ExecutionPolicy unrestricted -file "%1"

Then you can just double click all your .PS1 files like you would like to. in my humble opinion, be able to out of the box.

I'm going to call this "The Powershell De-castration Hack". LOL enjoy!

Add items to comboBox in WPF

You can fill it from XAML or from .cs. There are few ways to fill controls with data. It would be best for You to read more about WPF technology, it allows to do many things in many ways, depending on Your needs. It's more important to choose method based on Your project needs. You can start here. It's an easy article about creating combobox, and filling it with some data.

How does one target IE7 and IE8 with valid CSS?

I would recommend looking into conditional comments and making a separate sheet for the IEs you are having problems with.

 <!--[if IE 7]>
   <link rel="stylesheet" type="text/css" href="ie7.css" />
 <![endif]-->

Linux delete file with size 0

This works for plain BSD so it should be universally compatible with all flavors. Below.e.g in pwd ( . )

find . -size 0 |  xargs rm

Random number c++ in some range

float RandomFloat(float min, float max)
{
    float r = (float)rand() / (float)RAND_MAX;
    return min + r * (max - min);
}

How to add header data in XMLHttpRequest when using formdata?

Your error

InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable

appears because you must call setRequestHeader after calling open. Simply move your setRequestHeader line below your open line (but before send):

xmlhttp.open("POST", url);
xmlhttp.setRequestHeader("x-filename", photoId);
xmlhttp.send(formData);

java.lang.UnsupportedClassVersionError Unsupported major.minor version 51.0

I encountered the same issue, when jdk 1.7 was used to compile then jre 1.4 was used for execution.

My solution was to set environment variable PATH by adding pathname C:\glassfish3\jdk7\bin in front of the existing PATH setting. The updated value is "C:\glassfish3\jdk7\bin;C:\Sun\SDK\bin". After the update, the problem was gone.

failed to open stream: HTTP wrapper does not support writeable connections

it is because of using web address, You can not use http to write data. don't use : http:// or https:// in your location for upload files or save data or somting like that. instead of of using $_SERVER["HTTP_REFERER"] use $_SERVER["DOCUMENT_ROOT"]. for example :

wrong :

move_uploaded_file($_FILES["File"]["tmp_name"],$_SERVER["HTTP_REFERER"].'/uploads/images/1.jpg')

correct:

move_uploaded_file($_FILES["File"]["tmp_name"],$_SERVER["DOCUMENT_ROOT"].'/uploads/images/1.jpg')

Removing multiple files from a Git repo that have already been deleted from disk

(Yet another variation)

I wanted to delete all the already deleted from the disk files but from one specific folder, leaving the other folders untouched. The following worked for me:

git ls-files --deleted  | grep <folder-name> | xargs git rm

How do I convert a string to a number in PHP?

Just a little note to the answers that can be useful and safer in some cases. You may want to check if the string actually contains a valid numeric value first and only then convert it to a numeric type (for example if you have to manipulate data coming from a db that converts ints to strings). You can use is_numeric() and then floatval():

$a = "whatever"; // any variable

if (is_numeric($a)) 
    var_dump(floatval($a)); // type is float
else 
    var_dump($a); // any type

How can I create a unique constraint on my column (SQL Server 2008 R2)?

One thing not clearly covered is that microsoft sql is creating in the background an unique index for the added constraint

create table Customer ( id int primary key identity (1,1) , name nvarchar(128) ) 

--Commands completed successfully.

sp_help Customer

---> index
--index_name    index_description   index_keys
--PK__Customer__3213E83FCC4A1DFA    clustered, unique, primary key located on PRIMARY   id

---> constraint
--constraint_type   constraint_name delete_action   update_action   status_enabled  status_for_replication  constraint_keys
--PRIMARY KEY (clustered)   PK__Customer__3213E83FCC4A1DFA  (n/a)   (n/a)   (n/a)   (n/a)   id


---- now adding the unique constraint

ALTER TABLE Customer ADD CONSTRAINT U_Name UNIQUE(Name)

-- Commands completed successfully.

sp_help Customer

---> index
---index_name   index_description   index_keys
---PK__Customer__3213E83FCC4A1DFA   clustered, unique, primary key located on PRIMARY   id
---U_Name   nonclustered, unique, unique key located on PRIMARY name

---> constraint
---constraint_type  constraint_name delete_action   update_action   status_enabled  status_for_replication  constraint_keys
---PRIMARY KEY (clustered)  PK__Customer__3213E83FCC4A1DFA  (n/a)   (n/a)   (n/a)   (n/a)   id
---UNIQUE (non-clustered)   U_Name  (n/a)   (n/a)   (n/a)   (n/a)   name

as you can see , there is a new constraint and a new index U_Name

Do HTTP POST methods send data as a QueryString?

If your post try to reach the following URL

mypage.php?id=1

you will have the POST data but also GET data.

Create a copy of a table within the same database DB2

Two steps works fine:

create table bu_x as (select a,b,c,d from x ) WITH no data;

insert into bu_x (a,b,c,d) select select a,b,c,d from x ;

Android dependency has different version for the compile and runtime

You should be able to see exactly which dependency is pulling in the odd version as a transitive dependency by running the correct gradle -q dependencies command for your project as described here:

https://docs.gradle.org/current/userguide/userguide_single.html#sec:listing_dependencies

Once you track down what's pulling it in, you can add an exclude to that specific dependency in your gradle file with something like:

implementation("XXXXX") {
    exclude group: 'com.android.support', module: 'support-compat'
}

How do I format a date in Jinja2?

Google App Engine users : If you're moving from Django to Jinja2, and looking to replace the date filter, note that the % formatting codes are different.

The strftime % codes are here: http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior

remove white space from the end of line in linux

Try this:

sed -i 's/\s*$//' youfile.txt

How to initialize private static members in C++?

One "old-school" way to define constants is to replace them by a enum:

class foo
{
    private:
        enum {i = 0}; // default type = int
        enum: int64_t {HUGE = 1000000000000}; // may specify another type
};

This way doesn't require providing a definition, and avoids making the constant lvalue, which can save you some headaches, e.g. when you accidentally ODR-use it.

Getting the object's property name

To get the property of the object or the "array key" or "array index" depending on what your native language is..... Use the Object.keys() method.

Important, this is only compatible with "Modern browsers":

So if your object is called, myObject...

var c = 0;
for(c in myObject) {
    console.log(Object.keys(myObject[c]));
}

Walla! This will definitely work in the latest firefox and ie11 and chrome...

Here is some documentation at MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

PHP string concatenation

I think this code should work fine

while ($personCount < 10) {
$result = $personCount . "people ';
$personCount++;
}
// do not understand why do you need the (+) with the result.
echo $result;

Mapping composite keys using EF code first

Through Configuration, you can do this:

Model1
{
    int fk_one,
    int fk_two
}

Model2
{
    int pk_one,
    int pk_two,
}

then in the context config

public class MyContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Model1>()
            .HasRequired(e => e.Model2)
            .WithMany(e => e.Model1s)
            .HasForeignKey(e => new { e.fk_one, e.fk_two })
            .WillCascadeOnDelete(false);
    }
}

Random numbers with Math.random() in Java

Yours: Lowest possible is min, highest possible is max+min-1

Google: Lowest possible is min, highest possible is max-1

Dynamically converting java object of Object class to a given class when class name is known

@SuppressWarnings("unchecked")
private static <T extends Object> T cast(Object obj) {
    return (T) obj;
}

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

[Ljava.lang.Object; cannot be cast to

Your query execution will return list of Object[].

List result_source = LoadSource.list();
for(Object[] objA : result_source) {
    // read it all
}

Getting the class of the element that fired an event using JQuery

Careful as target might not work with all browsers, it works well with Chrome, but I reckon Firefox (or IE/Edge, can't remember) is a bit different and uses srcElement. I usually do something like

var t = ev.srcElement || ev.target;

thus leading to

$(document).ready(function() {
    $("a").click(function(ev) {
        // get target depending on what API's in use
        var t = ev.srcElement || ev.target;

        alert(t.id+" and "+$(t).attr('class'));
    });
});

Thx for the nice answers!

Favorite Visual Studio keyboard shortcuts

Alt+Shift+arrow keys(,,,)

This allow you to select things in a block. Like you could select all of the "int" in the block and then search and replace to double for example.

**int** x = 1;
**int** y = 2;
**int** z = 3;

'^M' character at end of lines

od -a $file is useful to explore those types of question on Linux (similar to dumphex in the above).

How does += (plus equal) work?

To be precise a+=b not actually equals to a = a + b. It actually is a = a + (b). How so? Let me show you a demo,

_x000D_
_x000D_
a = 1;
console.log('a += 1<<2: ', a += 1<<2); // results in 5

a = 1;
// If a += b is equal to a = a + b then this would be 5. But as you see this is not. The result is 8.
console.log('a + 1 << 2: ', a + 1 << 2); // results in 8


a = 1;
// As you can see this results in 5.
console.log('a + (1<<2): ', a + (1<<2)); // results in 5
_x000D_
_x000D_
_x000D_

Because this += or *= or -= or /= etc operators implicitly groups the right hand side.

jquery, find next element by class

To find the next element with the same class:

$(".class").eq( $(".class").index( $(element) ) + 1 )

Calling multiple JavaScript functions on a button click

It isn't getting called because you have a return statement above it. In the following code:

function test(){
  return 1;
  doStuff();
}

doStuff() will never be called. What I would suggest is writing a wrapper function

function wrapper(){
   if (validateView()){
     showDiv();
     return true;
   }
}

and then call the wrapper function from your onclick handler.

Error: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK - Android

None of the solutions worked for me as of today. My situation was that I got my Android studio updated. The most popular thing to replace the tools folder with the latest one wouldn't work for me. Infact is not required in some cases.

npm update -g cordova did the trick for me.

Then I removed the platform and added it again.

ionic platform remove android

ionic platform add android

This works for me in Ionic. I am surecordova platform remove/add android will do the same stuff. Not tested though.

Working again !

When to choose mouseover() and hover() function?

You can try it out http://api.jquery.com/mouseover/ on the jQuery doc page. It's a nice little, interactive demo that makes it very clear and you can actually see for yourself.

In short, you'll notice that a mouse over event occurs on an element when you are over it - coming from either its child OR parent element, but a mouse enter event only occurs when the mouse moves from the parent element to the element.

In CSS what is the difference between "." and "#" when declaring a set of styles?

.class targets the following element:

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

#class targets the following element:

<div id="class"></div>

Note that the id MUST be unique throughout the document, whilst any number of elements may share a class.

What does the "On Error Resume Next" statement do?

It enables error handling. The following is partly from https://msdn.microsoft.com/en-us/library/5hsw66as.aspx

' Enable error handling. When a run-time error occurs, control goes to the statement 
' immediately following the statement where the error occurred, and execution
' continues from that point.
On Error Resume Next

SomeCodeHere

If Err.Number = 0 Then
    WScript.Echo "No Error in SomeCodeHere."
Else
  WScript.Echo "Error in SomeCodeHere: " & Err.Number & ", " & Err.Source & ", " & Err.Description
  ' Clear the error or you'll see it again when you test Err.Number
  Err.Clear
End If

SomeMoreCodeHere

If Err.Number <> 0 Then
  WScript.Echo "Error in SomeMoreCodeHere:" & Err.Number & ", " & Err.Source & ", " & Err.Description
  ' Clear the error or you'll see it again when you test Err.Number
  Err.Clear
End If

' Disables enabled error handler in the current procedure and resets it to Nothing.
On Error Goto 0

' There are also `On Error Goto -1`, which disables the enabled exception in the current 
' procedure and resets it to Nothing, and `On Error Goto line`, 
' which enables the error-handling routine that starts at the line specified in the 
' required line argument. The line argument is any line label or line number. If a run-time 
' error occurs, control branches to the specified line, making the error handler active. 
' The specified line must be in the same procedure as the On Error statement, 
' or a compile-time error will occur.

How to edit .csproj file

For Visual Studio-version: 8.1.5,

  1. Right click on the project folder.
  2. Click "Tools", then "Edit File".

.Net System.Mail.Message adding multiple "To" addresses

Thanks for spotting this I was about to add strings thinking the same as you that they'd get added to end of collection. It appears the params are:

msg.to.Add(<MailAddress>) adds MailAddress to the end of the collection
msg.to.Add(<string>) add a list of emails to the collection

Slightly different actions depending on param type, I think this is pretty bad form i'd have prefered split methods AddStringList of something.

How can I download HTML source in C#

basically:

using System.Net;
using System.Net.Http;  // in LINQPad, also add a reference to System.Net.Http.dll

WebRequest req = HttpWebRequest.Create("http://google.com");
req.Method = "GET";

string source;
using (StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream()))
{
    source = reader.ReadToEnd();
}

Console.WriteLine(source);

How to perform grep operation on all files in a directory?

Use find. Seriously, it is the best way because then you can really see what files it's operating on:

find . -name "*.sql" -exec grep -H "slow" {} \;

Note, the -H is mac-specific, it shows the filename in the results.

Programmatically go back to previous ViewController in Swift

Swift 3

I might be late in the answer but for swift 3 you can do it this way:

override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "< Back", style: .plain, target: self, action: #selector(backAction))

    // Do any additional setup if required.
}

func backAction(){
    //print("Back Button Clicked")
    dismiss(animated: true, completion: nil)
}

"CASE" statement within "WHERE" clause in SQL Server 2008

Try the following:

select * From emp_master 
where emp_last_name= 
case emp_first_name 
 when 'test'    then 'test' 
 when 'Mr name' then 'name'
end

How to add Drop-Down list (<select>) programmatically?

Here's an ES6 version, conversion to vanilla JS shouldn't be too hard but I already have jQuery anyways:

_x000D_
_x000D_
function select(options, selected) {_x000D_
  return Object.entries(options).reduce((r, [k, v]) => r.append($('<option>').val(k).text(v)), $('<select>')).val(selected);_x000D_
}_x000D_
$('body').append(select({'option1': 'label 1', 'option2': 'label 2'}, 'option2'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Pyinstaller setting icons don't change

The below command can set the icon on an executable file.

Remember the ".ico" file should present in the place of the path given in "Path_of_.ico_file".

pyinstaller.exe --onefile --windowed --icon="Path_of_.ico_file" app.py

For example:

If the app.py file is present in the current directory and app.ico is present inside the Images folder within the current directory.

Then the command should be as below. The final executable file will be generated inside the dist folder

pyinstaller.exe --onefile --windowed --icon=Images\app.ico app.py

django: TypeError: 'tuple' object is not callable

You're missing comma (,) inbetween:

>>> ((1,2) (2,3))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable

Put comma:

>>> ((1,2), (2,3))
((1, 2), (2, 3))

What does the exclamation mark do before the function?

It returns whether the statement can evaluate to false. eg:

!false      // true
!true       // false
!isValid()  // is not valid

You can use it twice to coerce a value to boolean:

!!1    // true
!!0    // false

So, to more directly answer your question:

var myVar = !function(){ return false; }();  // myVar contains true

Edit: It has the side effect of changing the function declaration to a function expression. E.g. the following code is not valid because it is interpreted as a function declaration that is missing the required identifier (or function name):

function () { return false; }();  // syntax error

Detect if string contains any spaces

function hasSpaces(str) {
  if (str.indexOf(' ') !== -1) {
    return true
  } else {
    return false
  }
}

Groovy / grails how to determine a data type?

Simple groovy way to check object type:

somObject in Date

Can be applied also to interfaces.

What is the difference between const int*, const int * const, and int const *?

This question shows precisely why I like to do things the way I mentioned in my question is const after type id acceptable?

In short, I find the easiest way to remember the rule is that the "const" goes after the thing it applies to. So in your question, "int const *" means that the int is constant, while "int * const" would mean that the pointer is constant.

If someone decides to put it at the very front (eg: "const int *"), as a special exception in that case it applies to the thing after it.

Many people like to use that special exception because they think it looks nicer. I dislike it, because it is an exception, and thus confuses things.

Unexpected character encountered while parsing value

I had a similar error and thought I'd answer in case anyone was having something similar. I was looping over a directory of json files and deserializing them but was getting this same error.

The problem was that it was trying to grab hidden files as well. Make sure the file you're passing in is a .json file. I'm guessing it'll handle text as well. Hope this helps.

Manually Set Value for FormBuilder Control

  let cloneObj = Object.assign({}, this.form.getRawValue(), someClass);
  this.form.complexForm.patchValue(cloneObj);

If you don't want manually set each field.

How to make a floated div 100% height of its parent?

If you're prepared to use a little jQuery, the answer is simple!

$(function() {
    $('.parent').find('.child').css('height', $('.parent').innerHeight());
});

This works well for floating a single element to a side with 100% height of it's parent while other floated elements which would normally wrap around are kept to one side.

Hope this helps fellow jQuery fans.

Removing an item from a select box

To Remove an Item

$("select#mySelect option[value='option1']").remove(); 

To Add an item

$("#mySelect").append('<option value="option1">Option</option>');

To Check for an option

$('#yourSelect option[value=yourValue]').length > 0;

To remove a selected option

$('#mySelect :selected').remove(); 

Finding local maxima/minima with Numpy in a 1D numpy array

Another solution using essentially a dilate operator:

import numpy as np
from scipy.ndimage import rank_filter

def find_local_maxima(x):
   x_dilate = rank_filter(x, -1, size=3)
   return x_dilate == x

and for the minima:

def find_local_minima(x):
   x_erode = rank_filter(x, -0, size=3)
   return x_erode == x

Also, from scipy.ndimage you can replace rank_filter(x, -1, size=3) with grey_dilation and rank_filter(x, 0, size=3) with grey_erosion. This won't require a local sort, so it is slightly faster.

Laravel 5 How to switch from Production mode

In Laravel the default environment is always production.

What you need to do is to specify correct hostname in bootstrap/start.php for your enviroments eg.:

/*
|--------------------------------------------------------------------------
| Detect The Application Environment
|--------------------------------------------------------------------------
|
| Laravel takes a dead simple approach to your application environments
| so you can just specify a machine name for the host that matches a
| given environment, then we will automatically detect it for you.
|
*/

$env = $app->detectEnvironment(array(
    'local' => array('homestead'),
    'profile_1' => array('hostname_for_profile_1')
));

Permission denied when launch python script via bash

#strace ./scripts/replace-md5sums.py

AccessDenied for ListObjects for S3 bucket when permissions are s3:*

If you wanted to copy all s3 bucket objects using the command "aws s3 cp s3://bucket-name/data/all-data/ . --recursive" as you mentioned, here is a safe and minimal policy to do that:

{
  "Version": "2012-10-17",
  "Statement": [
      {
          "Effect": "Allow",
          "Action": [
              "s3:ListBucket"
          ],
          "Resource": [
              "arn:aws:s3:::bucket-name"
          ],
          "Condition": {
              "StringLike": {
                  "s3:prefix": "data/all-data/*"
              }
          }
      },
      {
          "Effect": "Allow",
          "Action": [
              "s3:GetObject"
          ],
          "Resource": [
              "arn:aws:s3:::bucket-name/data/all-data/*"
          ]
      }
  ]
}

The first statement in this policy allows for listing objects inside a specific bucket's sub directory. The resource needs to be the arn of the S3 bucket, and to limit listing to only a sub-directory in that bucket you can edit the "s3:prefix" value.

The second statement in this policy allows for getting objects inside of the bucket at a specific sub-directory. This means that anything inside the "s3://bucket-name/data/all-data/" path you will be able to copy. Be aware that this doesn't allow you to copy from parent paths such as "s3://bucket-name/data/".

This solution is specific to limiting use for AWS CLI commands; if you need to limit S3 access through the AWS console or API, then more policies will be needed. I suggest taking a look here: https://aws.amazon.com/blogs/security/writing-iam-policies-grant-access-to-user-specific-folders-in-an-amazon-s3-bucket/.

A similar issue to this can be found here which led me to the solution I am giving. https://github.com/aws/aws-cli/issues/2408

Hope this helps!

Order a List (C#) by many fields?

Yes, you can do it by specifying the comparison method. The advantage is the sorted object don't have to be IComparable

   aListOfObjects.Sort((x, y) =>
   {
       int result = x.A.CompareTo(y.A);
       return result != 0 ? result : x.B.CompareTo(y.B);
   });

When does a process get SIGABRT (signal 6)?

The GNU libc will print out information to /dev/tty regarding some fatal conditions before it calls abort() (which then triggers SIGABRT), but if you are running your program as a service or otherwise not in a real terminal window, these message can get lost, because there is no tty to display the messages.

See my post on redirecting libc to write to stderr instead of /dev/tty:

Catching libc error messages, redirecting from /dev/tty

Get index of a key/value pair in a C# dictionary based on the value

    You can find index by key/values in dictionary
Dictionary<string, string> myDictionary = new Dictionary<string, string>();
myDictionary.Add("a", "x");
myDictionary.Add("b", "y");
int i = Array.IndexOf(myDictionary.Keys.ToArray(), "a");
int j = Array.IndexOf(myDictionary.Values.ToArray(), "y");

Is there a way to specify how many characters of a string to print out using printf()?

In addition to specify a fixed amount of characters, you can also use * which means that printf takes the number of characters from an argument:

#include <stdio.h>

int main(int argc, char *argv[])
{
        const char hello[] = "Hello world";
        printf("message: '%.3s'\n", hello);
        printf("message: '%.*s'\n", 3, hello);
        printf("message: '%.*s'\n", 5, hello);
        return 0;
}

Prints:

message: 'Hel'
message: 'Hel'
message: 'Hello'

How to find prime numbers between 0 - 100?

<html>
<head>
<script type="text/javascript">
function primeNumber() {
 x=document.getElementById('txt_field').value;
  for (i=1; i<=parseInt(x); i++) {
  var flag=0,flag1=0; 
    for (j=2; j<i; j++) {
      if(i%j==0){
       flag=1;
      if(i==x)
       flag1=1;
      }
    }
   if(flag==0)
    document.write(i+'<br>');
  }
   if(flag1==0) 
    document.write('Its a prime number.');
   else 
    document.write('Its not a prime number.');
}
</script>
</head>

<body>
 <input id="txt_field" type="text" name="field" />
 <input type="button" name="submit" value="Submit" onclick="primeNumber();" />
</body>
</html>

How do you remove an invalid remote branch reference from Git?

You might be needing a cleanup:

git gc --prune=now

or you might be needing a prune:

git remote prune public

prune

Deletes all stale tracking branches under <name>. These stale branches have already been removed from the remote repository referenced by <name>, but are still locally available in "remotes/<name>".

With --dry-run option, report what branches will be pruned, but do no actually prune them.

However, it appears these should have been cleaned up earlier with

git remote rm public 

rm

Remove the remote named <name>. All remote tracking branches and configuration settings for the remote are removed.

So it might be you hand-edited your config file and this did not occur, or you have privilege problems.

Maybe run that again and see what happens.


Advice Context

If you take a look in the revision logs, you'll note I suggested more "correct" techniques, which for whatever reason didn't want to work on their repository.

I suspected the OP had done something that left their tree in an inconsistent state that caused it to behave a bit strangely, and git gc was required to fix up the left behind cruft.

Usually git branch -rd origin/badbranch is sufficient for nuking a local tracking branch , or git push origin :badbranch for nuking a remote branch, and usually you will never need to call git gc

How do I perform query filtering in django templates

You can't do this, which is by design. The Django framework authors intended a strict separation of presentation code from data logic. Filtering models is data logic, and outputting HTML is presentation logic.

So you have several options. The easiest is to do the filtering, then pass the result to render_to_response. Or you could write a method in your model so that you can say {% for object in data.filtered_set %}. Finally, you could write your own template tag, although in this specific case I would advise against that.

MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

I just run into this problem too, with all the MySQL re-config mentioned above the error still appears. It turns out that I misspelled the database name.

So be sure you're connecting with the right database name especially the case.

How to join two tables by multiple columns in SQL?

No, just include the different fields in the "ON" clause of 1 inner join statement:

SELECT * from Evalulation e JOIN Value v ON e.CaseNum = v.CaseNum
    AND e.FileNum = v.FileNum AND e.ActivityNum = v.ActivityNum

How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?

import React, { useRef, useState } from 'react'
...
const inputRef = useRef()
....
function chooseFile() {
  const { current } = inputRef
  (current || { click: () => {}}).click()
}
...
<input
   onChange={e => {
     setFile(e.target.files)
    }}
   id="select-file"
   type="file"
   ref={inputRef}
/>
<Button onClick={chooseFile} shadow icon="/upload.svg">
   Choose file
</Button>

the unique code that works to me using next.js enter image description here

What's the difference between Unicode and UTF-8?

UTF-16 and UTF-8 are both encodings of Unicode. They are both Unicode; one is not more Unicode than the other.

Don't let an unfortunate historical artifact from Microsoft confuse you.

z-index not working with fixed positioning

This question can be solved in a number of ways, but really, knowing the stacking rules allows you to find the best answer that works for you.

Solutions

The <html> element is your only stacking context, so just follow the stacking rules inside a stacking context and you will see that elements are stacked in this order

  1. The stacking context’s root element (the <html> element in this case)
  2. Positioned elements (and their children) with negative z-index values (higher values are stacked in front of lower values; elements with the same value are stacked according to appearance in the HTML)
  3. Non-positioned elements (ordered by appearance in the HTML)
  4. Positioned elements (and their children) with a z-index value of auto (ordered by appearance in the HTML)
  5. Positioned elements (and their children) with positive z-index values (higher values are stacked in front of lower values; elements with the same value are stacked according to appearance in the HTML)

So you can

  1. set a z-index of -1, for #under positioned -ve z-index appear behind non-positioned #over element
  2. set the position of #over to relative so that rule 5 applies to it

The Real Problem

Developers should know the following before trying to change the stacking order of elements.

  1. When a stacking context is formed
    • By default, the <html> element is the root element and is the first stacking context
  2. Stacking order within a stacking context

The Stacking order and stacking context rules below are from this link

When a stacking context is formed

  • When an element is the root element of a document (the <html> element)
  • When an element has a position value other than static and a z-index value other than auto
  • When an element has an opacity value less than 1
  • Several newer CSS properties also create stacking contexts. These include: transforms, filters, css-regions, paged media, and possibly others. https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context
  • As a general rule, it seems that if a CSS property requires rendering in an offscreen context, it must create a new stacking context.

Stacking Order within a Stacking Context

The order of elements:

  1. The stacking context’s root element (the <html> element is the only stacking context by default, but any element can be a root element for a stacking context, see rules above)
    • You cannot put a child element behind a root stacking context element
  2. Positioned elements (and their children) with negative z-index values (higher values are stacked in front of lower values; elements with the same value are stacked according to appearance in the HTML)
  3. Non-positioned elements (ordered by appearance in the HTML)
  4. Positioned elements (and their children) with a z-index value of auto (ordered by appearance in the HTML)
  5. Positioned elements (and their children) with positive z-index values (higher values are stacked in front of lower values; elements with the same value are stacked according to appearance in the HTML)

Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]

I had the same problem. The only thing that solved it was merge the content of META-INF/spring.handler and META-INF/spring.schemas of each spring jar file into same file names under my META-INF project.

This two threads explain it better:

How to add an image in Tkinter?

There is no "Syntax Error" in the code above - it either ocurred in some other line (the above is not all of your code, as there are no imports, neither the declaration of your path variable) or you got some other error type.

The example above worked fine for me, testing on the interactive interpreter.

Convert Java string to Time, NOT Date

try...

 java.sql.Time.valueOf("10:30:54");

VBA - Run Time Error 1004 'Application Defined or Object Defined Error'

Solution #1: Your statement

.Range(Cells(RangeStartRow, RangeStartColumn), Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues

does not refer to a proper Range to act upon. Instead,

.Range(.Cells(RangeStartRow, RangeStartColumn), .Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues

does (and similarly in some other cases).

Solution #2: Activate Worksheets("Cable Cards") prior to using its cells.

Explanation: Cells(RangeStartRow, RangeStartColumn) (e.g.) gives you a Range, that would be ok, and that is why you often see Cells used in this way. But since it is not applied to a specific object, it applies to the ActiveSheet. Thus, your code attempts using .Range(rng1, rng2), where .Range is a method of one Worksheet object and rng1 and rng2 are in a different Worksheet.

There are two checks that you can do to make this quite evident:

  1. Activate your Worksheets("Cable Cards") prior to executing your Sub and it will start working (now you have well-formed references to Ranges). For the code you posted, adding .Activate right after With... would indeed be a solution, although you might have a similar problem somewhere else in your code when referring to a Range in another Worksheet.

  2. With a sheet other than Worksheets("Cable Cards") active, set a breakpoint at the line throwing the error, start your Sub, and when execution breaks, write at the immediate window

    Debug.Print Cells(RangeStartRow, RangeStartColumn).Address(external:=True)

    Debug.Print .Cells(RangeStartRow, RangeStartColumn).Address(external:=True)

    and see the different outcomes.

Conclusion: Using Cells or Range without a specified object (e.g., Worksheet, or Range) might be dangerous, especially when working with more than one Sheet, unless one is quite sure about what Sheet is active.

How to ftp with a batch file?

Use

ftp -s:FileName 

as decribed in Windows XP Professional Product Documentation.

The file name that you have to specify in place of FileName must contain FTP commands that you want to send to the server. Among theses commands are

  • open Computer [Port] to connect to an FTP server,
  • user UserName [Password] [Account] to authenticate with the FTP server,
  • get RemoteFile [LocalFile] to retrieve a file,
  • quit to end the FTP session and terminate the ftp program.

More commands can be found under Ftp subcommands.

How to include external Python code to use in other files?

Just write the "include" command :

import os

def include(filename):
    if os.path.exists(filename): 
        execfile(filename)


include('myfile.py')

@Deleet :

@bfieck remark is correct, for python 2 and 3 compatibility, you need either :

Python 2 and 3: alternative 1

from past.builtins import execfile

execfile('myfile.py')

Python 2 and 3: alternative 2

exec(compile(open('myfile.py').read()))

Can the Twitter Bootstrap Carousel plugin fade in and out on slide transition

Yes. Bootstrap uses CSS transitions so it can be done easily without any Javascript. Just use CSS3. Please take a look at

carousel.carousel-fade

in the CSS of the following examples:

Convert string[] to int[] in one line of code using LINQ

EDIT: to convert to array

int[] asIntegers = arr.Select(s => int.Parse(s)).ToArray();

This should do the trick:

var asIntegers = arr.Select(s => int.Parse(s));

How to make 'submit' button disabled?

As seen in this Angular example, there is a way to disable a button until the whole form is valid:

<button type="submit" [disabled]="!ngForm.valid">Submit</button>

Seeing if data is normally distributed in R

library(DnE)
x<-rnorm(1000,0,1)
is.norm(x,10,0.05)

How can I initialize an ArrayList with all zeroes in Java?

It's not like that. ArrayList just uses array as internal respentation. If you add more then 60 elements then underlaying array will be exapanded. How ever you can add as much elements to this array as much RAM you have.

Disallow Twitter Bootstrap modal window from closing

The best I found is add this code to the link

<!-- Link -->
<a href="#mdl" role="button"  data-backdrop="static" data-keyboard="false" data-toggle="modal" id_team="" ></a>
<-- Div -->
<div id="mdl" class="modal hide fade" tabindex="-1" role="dialog" data-keyboard="false" data-backdrop="static"></div>

Do sessions really violate RESTfulness?

HTTP transaction, basic access authentication, is not suitable for RBAC, because basic access authentication uses the encrypted username:password every time to identify, while what is needed in RBAC is the Role the user wants to use for a specific call. RBAC does not validate permissions on username, but on roles.

You could tric around to concatenate like this: usernameRole:password, but this is bad practice, and it is also inefficient because when a user has more roles, the authentication engine would need to test all roles in concatenation, and that every call again. This would destroy one of the biggest technical advantages of RBAC, namely a very quick authorization-test.

So that problem cannot be solved using basic access authentication.

To solve this problem, session-maintaining is necessary, and that seems, according to some answers, in contradiction with REST.

That is what I like about the answer that REST should not be treated as a religion. In complex business cases, in healthcare, for example, RBAC is absolutely common and necessary. And it would be a pity if they would not be allowed to use REST because all REST-tools designers would treat REST as a religion.

For me there are not many ways to maintain a session over HTTP. One can use cookies, with a sessionId, or a header with a sessionId.

If someone has another idea I will be glad to hear it.

Call a python function from jinja2

Use a lambda to connect the template to your main code

return render_template("clever_template", clever_function=lambda x: clever_function x)

Then you can seamlessly call the function in the template

{{clever_function(value)}}

Comprehensive beginner's virtualenv tutorial?

Virtualenv is a tool to create isolated Python environments.

Let's say you're working in 2 different projects, A and B. Project A is a web project and the team is using the following packages:

  • Python 2.8.x
  • Django 1.6.x

The project B is also a web project but your team is using:

  • Python 2.7.x
  • Django 1.4.x

The machine that you're working doesn't have any version of django, what should you do? Install django 1.4? django 1.6? If you install django 1.4 globally would be easy to point to django 1.6 to work in project A?

Virtualenv is your solution! You can create 2 different virtualenv's, one for project A and another for project B. Now, when you need to work in project A, just activate the virtualenv for project A, and vice-versa.

A better tip when using virtualenv is to install virtualenvwrapper to manage all the virtualenv's that you have, easily. It's a wrapper for creating, working, removing virtualenv's.

exclude @Component from @ComponentScan

In case of excluding test component or test configuration, Spring Boot 1.4 introduced new testing annotations @TestComponent and @TestConfiguration.

Is there a way to detect if a browser window is not currently active?

For angular.js, here is a directive (based on the accepted answer) that will allow your controller to react to a change in visibility:

myApp.directive('reactOnWindowFocus', function($parse) {
    return {
        restrict: "A",
        link: function(scope, element, attrs) {
            var hidden = "hidden";
            var currentlyVisible = true;
            var functionOrExpression = $parse(attrs.reactOnWindowFocus);

          // Standards:
          if (hidden in document)
            document.addEventListener("visibilitychange", onchange);
          else if ((hidden = "mozHidden") in document)
            document.addEventListener("mozvisibilitychange", onchange);
          else if ((hidden = "webkitHidden") in document)
            document.addEventListener("webkitvisibilitychange", onchange);
          else if ((hidden = "msHidden") in document)
            document.addEventListener("msvisibilitychange", onchange);
          else if ("onfocusin" in document) {
                // IE 9 and lower:
            document.onfocusin = onshow;
                document.onfocusout = onhide;
          } else {
                // All others:
            window.onpageshow = window.onfocus = onshow;
                window.onpagehide = window.onblur = onhide;
            }

          function onchange (evt) {
                //occurs both on leaving and on returning
                currentlyVisible = !currentlyVisible;
                doSomethingIfAppropriate();
          }

            function onshow(evt) {
                //for older browsers
                currentlyVisible = true;
                doSomethingIfAppropriate();
            }

            function onhide(evt) {
                //for older browsers
                currentlyVisible = false;
                doSomethingIfAppropriate();
            }

            function doSomethingIfAppropriate() {
                if (currentlyVisible) {
                    //trigger angular digest cycle in this scope
                    scope.$apply(function() {
                        functionOrExpression(scope);
                    });
                }
            }
        }
    };

});

You can use it like this example: <div react-on-window-focus="refresh()">, where refresh() is a scope function in the scope of whatever Controller is in scope.

Merging two arrayLists into a new arrayList, with no duplicates and in order, in Java

Instead of the code you wrote, you may use ArrayList.addAll() to merge the lists, Collections.sort() to sort it and finally traverse of the resulting ArrayList to remove duplicates. The aggregate complexity is thus O(n)+O(n*log(n))+O(n) which is equivalent to O(n*log(n)).

CSS hide scroll bar if not needed

.selected-elementClass{
    overflow-y:auto;
}

Creating stored procedure with declare and set variables

You should try this syntax - assuming you want to have @OrderID as a parameter for your stored procedure:

CREATE PROCEDURE dbo.YourStoredProcNameHere
   @OrderID INT
AS
BEGIN
 DECLARE @OrderItemID AS INT
 DECLARE @AppointmentID AS INT
 DECLARE @PurchaseOrderID AS INT
 DECLARE @PurchaseOrderItemID AS INT
 DECLARE @SalesOrderID AS INT
 DECLARE @SalesOrderItemID AS INT

 SELECT @OrderItemID = OrderItemID 
 FROM [OrderItem] 
 WHERE OrderID = @OrderID

 SELECT @AppointmentID = AppoinmentID 
 FROM [Appointment] 
 WHERE OrderID = @OrderID

 SELECT @PurchaseOrderID = PurchaseOrderID 
 FROM [PurchaseOrder] 
 WHERE OrderID = @OrderID

END

OF course, that only works if you're returning exactly one value (not multiple values!)

Does Python support short-circuiting?

Short-circuiting behavior in operator and, or:

Let's first define a useful function to determine if something is executed or not. A simple function that accepts an argument, prints a message and returns the input, unchanged.

>>> def fun(i):
...     print "executed"
...     return i
... 

One can observe the Python's short-circuiting behavior of and, or operators in the following example:

>>> fun(1)
executed
1
>>> 1 or fun(1)    # due to short-circuiting  "executed" not printed
1
>>> 1 and fun(1)   # fun(1) called and "executed" printed 
executed
1
>>> 0 and fun(1)   # due to short-circuiting  "executed" not printed 
0

Note: The following values are considered by the interpreter to mean false:

        False    None    0    ""    ()    []     {}

Short-circuiting behavior in function: any(), all():

Python's any() and all() functions also support short-circuiting. As shown in the docs; they evaluate each element of a sequence in-order, until finding a result that allows an early exit in the evaluation. Consider examples below to understand both.

The function any() checks if any element is True. It stops executing as soon as a True is encountered and returns True.

>>> any(fun(i) for i in [1, 2, 3, 4])   # bool(1) = True
executed
True
>>> any(fun(i) for i in [0, 2, 3, 4])   
executed                               # bool(0) = False
executed                               # bool(2) = True
True
>>> any(fun(i) for i in [0, 0, 3, 4])
executed
executed
executed
True

The function all() checks all elements are True and stops executing as soon as a False is encountered:

>>> all(fun(i) for i in [0, 0, 3, 4])
executed
False
>>> all(fun(i) for i in [1, 0, 3, 4])
executed
executed
False

Short-circuiting behavior in Chained Comparison:

Additionally, in Python

Comparisons can be chained arbitrarily; for example, x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

>>> 5 > 6 > fun(3)    # same as:  5 > 6 and 6 > fun(3)
False                 # 5 > 6 is False so fun() not called and "executed" NOT printed
>>> 5 < 6 > fun(3)    # 5 < 6 is True 
executed              # fun(3) called and "executed" printed
True
>>> 4 <= 6 > fun(7)   # 4 <= 6 is True  
executed              # fun(3) called and "executed" printed
False
>>> 5 < fun(6) < 3    # only prints "executed" once
executed
False
>>> 5 < fun(6) and fun(6) < 3 # prints "executed" twice, because the second part executes it again
executed
executed
False

Edit:
One more interesting point to note :- Logical and, or operators in Python returns an operand's value instead of a Boolean (True or False). For example:

Operation x and y gives the result if x is false, then x, else y

Unlike in other languages e.g. &&, || operators in C that return either 0 or 1.

Examples:

>>> 3 and 5    # Second operand evaluated and returned 
5                   
>>> 3  and ()
()
>>> () and 5   # Second operand NOT evaluated as first operand () is  false
()             # so first operand returned 

Similarly or operator return left most value for which bool(value) == True else right most false value (according to short-circuiting behavior), examples:

>>> 2 or 5    # left most operand bool(2) == True
2    
>>> 0 or 5    # bool(0) == False and bool(5) == True
5
>>> 0 or ()
()

So, how is this useful? One example is given in Practical Python By Magnus Lie Hetland:
Let’s say a user is supposed to enter his or her name, but may opt to enter nothing, in which case you want to use the default value '<Unknown>'. You could use an if statement, but you could also state things very succinctly:

In [171]: name = raw_input('Enter Name: ') or '<Unknown>'
Enter Name: 

In [172]: name
Out[172]: '<Unknown>'

In other words, if the return value from raw_input is true (not an empty string), it is assigned to name (nothing changes); otherwise, the default '<Unknown>' is assigned to name.

Check whether values in one data frame column exist in a second data frame

Use %in% as follows

A$C %in% B$C

Which will tell you which values of column C of A are in B.

What is returned is a logical vector. In the specific case of your example, you get:

A$C %in% B$C
# [1]  TRUE FALSE  TRUE  TRUE

Which you can use as an index to the rows of A or as an index to A$C to get the actual values:

# as a row index
A[A$C %in% B$C,  ]  # note the comma to indicate we are indexing rows

# as an index to A$C
A$C[A$C %in% B$C]
[1] 1 3 4  # returns all values of A$C that are in B$C

We can negate it too:

A$C[!A$C %in% B$C]
[1] 2   # returns all values of A$C that are NOT in B$C



If you want to know if a specific value is in B$C, use the same function:

  2 %in% B$C   # "is the value 2 in B$C ?"  
  # FALSE

  A$C[2] %in% B$C  # "is the 2nd element of A$C in B$C ?"  
  # FALSE

Creating runnable JAR with Gradle

Thank you Konstantin, it worked like a charm with few nuances. For some reason, specifying main class as part of jar manifest did not quite work and it wanted the mainClassName attribute instead. Here is a snippet from build.gradle that includes everything to make it work:

plugins {
  id 'java' 
  id 'com.github.johnrengelman.shadow' version '1.2.2'
}
...
...
apply plugin: 'application'
apply plugin: 'com.github.johnrengelman.shadow'
...
...
mainClassName = 'com.acme.myapp.MyClassMain'
...
...
...
shadowJar {
    baseName = 'myapp'
}

After running gradle shadowJar you get myapp-{version}-all.jar in your build folder which can be run as java -jar myapp-{version}-all.jar.

How do you check if a variable is an array in JavaScript?

If you're only dealing with EcmaScript 5 and above then you can use the built in Array.isArray function

e.g.,

Array.isArray([])    // true
Array.isArray("foo") // false
Array.isArray({})    // false

Web colors in an Android color xml resource file

I change all code to lower case for mono android

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
    <color name="white">#FFFFFF</color>
    <color name="ivory">#FFFFF0</color>
    <color name="lightyellow">#FFFFE0</color>
    <color name="yellow">#FFFF00</color>
    <color name="snow">#FFFAFA</color>
    <color name="floralwhite">#FFFAF0</color>
    <color name="lemonchiffon">#FFFACD</color>
    <color name="cornsilk">#FFF8DC</color>
    <color name="seashell">#FFF5EE</color>
    <color name="lavenderblush">#FFF0F5</color>
    <color name="papayawhip">#FFEFD5</color>
    <color name="blanchedalmond">#FFEBCD</color>
    <color name="mistyrose">#FFE4E1</color>
    <color name="bisque">#FFE4C4</color>
    <color name="moccasin">#FFE4B5</color>
    <color name="navajowhite">#FFDEAD</color>
    <color name="peachpuff">#FFDAB9</color>
    <color name="gold">#FFD700</color>
    <color name="pink">#FFC0CB</color>
    <color name="lightpink">#FFB6C1</color>
    <color name="orange">#FFA500</color>
    <color name="lightsalmon">#FFA07A</color>
    <color name="darkorange">#FF8C00</color>
    <color name="coral">#FF7F50</color>
    <color name="hotpink">#FF69B4</color>
    <color name="tomato">#FF6347</color>
    <color name="orangered">#FF4500</color>
    <color name="deeppink">#FF1493</color>
    <color name="fuchsia">#FF00FF</color>
    <color name="magenta">#FF00FF</color>
    <color name="red">#FF0000</color>
    <color name="oldlace">#FDF5E6</color>
    <color name="lightgoldenrodyellow">#FAFAD2</color>
    <color name="linen">#FAF0E6</color>
    <color name="antiquewhite">#FAEBD7</color>
    <color name="salmon">#FA8072</color>
    <color name="ghostwhite">#F8F8FF</color>
    <color name="mintcream">#F5FFFA</color>
    <color name="whitesmoke">#F5F5F5</color>
    <color name="beige">#F5F5DC</color>
    <color name="wheat">#F5DEB3</color>
    <color name="sandybrown">#F4A460</color>
    <color name="azure">#F0FFFF</color>
    <color name="honeydew">#F0FFF0</color>
    <color name="aliceblue">#F0F8FF</color>
    <color name="khaki">#F0E68C</color>
    <color name="lightcoral">#F08080</color>
    <color name="palegoldenrod">#EEE8AA</color>
    <color name="violet">#EE82EE</color>
    <color name="darksalmon">#E9967A</color>
    <color name="lavender">#E6E6FA</color>
    <color name="lightcyan">#E0FFFF</color>
    <color name="burlywood">#DEB887</color>
    <color name="plum">#DDA0DD</color>
    <color name="gainsboro">#DCDCDC</color>
    <color name="crimson">#DC143C</color>
    <color name="palevioletred">#DB7093</color>
    <color name="goldenrod">#DAA520</color>
    <color name="orchid">#DA70D6</color>
    <color name="thistle">#D8BFD8</color>
    <color name="lightgrey">#D3D3D3</color>
    <color name="tan">#D2B48C</color>
    <color name="chocolate">#D2691E</color>
    <color name="peru">#CD853F</color>
    <color name="indianred">#CD5C5C</color>
    <color name="mediumvioletred">#C71585</color>
    <color name="silver">#C0C0C0</color>
    <color name="darkkhaki">#BDB76B</color>
    <color name="rosybrown">#BC8F8F</color>
    <color name="mediumorchid">#BA55D3</color>
    <color name="darkgoldenrod">#B8860B</color>
    <color name="firebrick">#B22222</color>
    <color name="powderblue">#B0E0E6</color>
    <color name="lightsteelblue">#B0C4DE</color>
    <color name="paleturquoise">#AFEEEE</color>
    <color name="greenyellow">#ADFF2F</color>
    <color name="lightblue">#ADD8E6</color>
    <color name="darkgray">#A9A9A9</color>
    <color name="brown">#A52A2A</color>
    <color name="sienna">#A0522D</color>
    <color name="yellowgreen">#9ACD32</color>
    <color name="darkorchid">#9932CC</color>
    <color name="palegreen">#98FB98</color>
    <color name="darkviolet">#9400D3</color>
    <color name="mediumpurple">#9370DB</color>
    <color name="lightgreen">#90EE90</color>
    <color name="darkseagreen">#8FBC8F</color>
    <color name="saddlebrown">#8B4513</color>
    <color name="darkmagenta">#8B008B</color>
    <color name="darkred">#8B0000</color>
    <color name="blueviolet">#8A2BE2</color>
    <color name="lightskyblue">#87CEFA</color>
    <color name="skyblue">#87CEEB</color>
    <color name="gray">#808080</color>
    <color name="olive">#808000</color>
    <color name="purple">#800080</color>
    <color name="maroon">#800000</color>
    <color name="aquamarine">#7FFFD4</color>
    <color name="chartreuse">#7FFF00</color>
    <color name="lawngreen">#7CFC00</color>
    <color name="mediumslateblue">#7B68EE</color>
    <color name="lightslategray">#778899</color>
    <color name="slategray">#708090</color>
    <color name="olivedrab">#6B8E23</color>
    <color name="slateblue">#6A5ACD</color>
    <color name="dimgray">#696969</color>
    <color name="mediumaquamarine">#66CDAA</color>
    <color name="cornflowerblue">#6495ED</color>
    <color name="cadetblue">#5F9EA0</color>
    <color name="darkolivegreen">#556B2F</color>
    <color name="indigo">#4B0082</color>
    <color name="mediumturquoise">#48D1CC</color>
    <color name="darkslateblue">#483D8B</color>
    <color name="steelblue">#4682B4</color>
    <color name="royalblue">#4169E1</color>
    <color name="turquoise">#40E0D0</color>
    <color name="mediumseagreen">#3CB371</color>
    <color name="limegreen">#32CD32</color>
    <color name="darkslategray">#2F4F4F</color>
    <color name="seagreen">#2E8B57</color>
    <color name="forestgreen">#228B22</color>
    <color name="lightseagreen">#20B2AA</color>
    <color name="dodgerblue">#1E90FF</color>
    <color name="midnightblue">#191970</color>
    <color name="aqua">#00FFFF</color>
    <color name="cyan">#00FFFF</color>
    <color name="springgreen">#00FF7F</color>
    <color name="lime">#00FF00</color>
    <color name="mediumspringgreen">#00FA9A</color>
    <color name="darkturquoise">#00CED1</color>
    <color name="deepskyblue">#00BFFF</color>
    <color name="darkcyan">#008B8B</color>
    <color name="teal">#008080</color>
    <color name="green">#008000</color>
    <color name="darkgreen">#006400</color>
    <color name="blue">#0000FF</color>
    <color name="mediumblue">#0000CD</color>
    <color name="darkblue">#00008B</color>
    <color name="navy">#000080</color>
    <color name="black">#000000</color>
    </resources>

Using setDate in PreparedStatement

❐ Using java.sql.Date

If your table has a column of type DATE:

  • java.lang.String

    The method java.sql.Date.valueOf(java.lang.String) received a string representing a date in the format yyyy-[m]m-[d]d. e.g.:

    ps.setDate(2, java.sql.Date.valueOf("2013-09-04"));
    
  • java.util.Date

    Suppose you have a variable endDate of type java.util.Date, you make the conversion thus:

    ps.setDate(2, new java.sql.Date(endDate.getTime());
    
  • Current

    If you want to insert the current date:

    ps.setDate(2, new java.sql.Date(System.currentTimeMillis()));
    
    // Since Java 8
    ps.setDate(2, java.sql.Date.valueOf(java.time.LocalDate.now()));
    

❐ Using java.sql.Timestamp

If your table has a column of type TIMESTAMP or DATETIME:

  • java.lang.String

    The method java.sql.Timestamp.valueOf(java.lang.String) received a string representing a date in the format yyyy-[m]m-[d]d hh:mm:ss[.f...]. e.g.:

    ps.setTimestamp(2, java.sql.Timestamp.valueOf("2013-09-04 13:30:00");
    
  • java.util.Date

    Suppose you have a variable endDate of type java.util.Date, you make the conversion thus:

    ps.setTimestamp(2, new java.sql.Timestamp(endDate.getTime()));
    
  • Current

    If you require the current timestamp:

    ps.setTimestamp(2, new java.sql.Timestamp(System.currentTimeMillis()));
    
    // Since Java 8
    ps.setTimestamp(2, java.sql.Timestamp.from(java.time.Instant.now()));
    ps.setTimestamp(2, java.sql.Timestamp.valueOf(java.time.LocalDateTime.now()));
    

How to include NA in ifelse?

@AnandaMahto has addressed why you're getting these results and provided the clearest way to get what you want. But another option would be to use identical instead of ==.

test$ID <- ifelse(is.na(test$time) | sapply(as.character(test$type), identical, "A"), NA, "1")

Or use isTRUE:

test$ID <- ifelse(is.na(test$time) | Vectorize(isTRUE)(test$type == "A"), NA, "1")

Cell color changing in Excel using C#

For text:

[RangeObject].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

For cell background

[RangeObject].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

How to use auto-layout to move other views when a view is hidden?

I think this is the most simple answer. Please verify that it works:

        StackFullView.layer.isHidden = true
        Task_TopSpaceSections.constant = 0.   //your constraint of top view

check here https://www.youtube.com/watch?v=EBulMWMoFuw

How to COUNT rows within EntityFramework without loading contents?

This is my code:

IQueryable<AuctionRecord> records = db.AuctionRecord;
var count = records.Count();

Make sure the variable is defined as IQueryable then when you use Count() method, EF will execute something like

select count(*) from ...

Otherwise, if the records is defined as IEnumerable, the sql generated will query the entire table and count rows returned.

How to create PDF files in Python

I suggest pyPdf. It works really nice. I also wrote a blog post some while ago, you can find it here.

Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

I had to set

C:\ProgramData\MySQL\MySQL Server 8.0/my.ini  secure-file-priv=""

When I commented line with secure-file-priv, secure-file-priv was null and I couldn't download data.

cc1plus: error: unrecognized command line option "-std=c++11" with g++

Quoting from the gcc website:

C++11 features are available as part of the "mainline" GCC compiler in the trunk of GCC's Subversion repository and in GCC 4.3 and later. To enable C++0x support, add the command-line parameter -std=c++0x to your g++ command line. Or, to enable GNU extensions in addition to C++0x extensions, add -std=gnu++0x to your g++ command line. GCC 4.7 and later support -std=c++11 and -std=gnu++11 as well.

So probably you use a version of g++ which doesn't support -std=c++11. Try -std=c++0x instead.

Availability of C++11 features is for versions >= 4.3 only.

Javascript Equivalent to PHP Explode()

If you like php, take a look at php.JS - JavaScript explode

Or in normal JavaScript functionality: `

var vInputString = "0000000020C90037:TEMP:data";
var vArray = vInputString.split(":");
var vRes = vArray[1] + ":" + vArray[2]; `