Programs & Examples On #Constructor

A special type of subroutine called at the creation of an object.

What is this weird colon-member (" : ") syntax in the constructor?

Foo(int num): bar(num)    

This construct is called a Member Initializer List in C++.

Simply said, it initializes your member bar to a value num.


What is the difference between Initializing and Assignment inside a constructor?

Member Initialization:

Foo(int num): bar(num) {};

Member Assignment:

Foo(int num)
{
   bar = num;
}

There is a significant difference between Initializing a member using Member initializer list and assigning it an value inside the constructor body.

When you initialize fields via Member initializer list the constructors will be called once and the object will be constructed and initialized in one operation.

If you use assignment then the fields will be first initialized with default constructors and then reassigned (via assignment operator) with actual values.

As you see there is an additional overhead of creation & assignment in the latter, which might be considerable for user defined classes.

Cost of Member Initialization = Object Construction 
Cost of Member Assignment = Object Construction + Assignment

The latter is actually equivalent to:

Foo(int num) : bar() {bar = num;}

While the former is equivalent to just:

Foo(int num): bar(num){}

For an inbuilt (your code example) or POD class members there is no practical overhead.


When do you HAVE TO use Member Initializer list?

You will have(rather forced) to use a Member Initializer list if:

  • Your class has a reference member
  • Your class has a non static const member or
  • Your class member doesn't have a default constructor or
  • For initialization of base class members or
  • When constructor’s parameter name is same as data member(this is not really a MUST)

A code example:

class MyClass {
public:
  // Reference member, has to be Initialized in Member Initializer List
  int &i;
  int b;
  // Non static const member, must be Initialized in Member Initializer List
  const int k;

  // Constructor’s parameter name b is same as class data member
  // Other way is to use this->b to refer to data member
  MyClass(int a, int b, int c) : i(a), b(b), k(c) {
    // Without Member Initializer
    // this->b = b;
  }
};

class MyClass2 : public MyClass {
public:
  int p;
  int q;
  MyClass2(int x, int y, int z, int l, int m) : MyClass(x, y, z), p(l), q(m) {}
};

int main() {
  int x = 10;
  int y = 20;
  int z = 30;
  MyClass obj(x, y, z);

  int l = 40;
  int m = 50;
  MyClass2 obj2(x, y, z, l, m);

  return 0;
}
  • MyClass2 doesn't have a default constructor so it has to be initialized through member initializer list.
  • Base class MyClass does not have a default constructor, So to initialize its member one will need to use Member Initializer List.

Important points to Note while using Member Initializer Lists:

Class Member variables are always initialized in the order in which they are declared in the class.

They are not initialized in the order in which they are specified in the Member Initializer List.
In short, Member initialization list does not determine the order of initialization.

Given the above it is always a good practice to maintain the same order of members for Member initialization as the order in which they are declared in the class definition. This is because compilers do not warn if the two orders are different but a relatively new user might confuse member Initializer list as the order of initialization and write some code dependent on that.

C++: Where to initialize variables in constructor

Although it doesn't apply to this specific example, Option 1 allows you to initialize member variables of reference type (or const type, as pointed out below). Option 2 doesn't. In general, Option 1 is the more powerful approach.

What is the best way to give a C# auto-property an initial value?

Use the constructor because "When the constructor is finished, Construction should be finished". properties are like states your classes hold, if you had to initialize a default state, you would do that in your constructor.

How do I call one constructor from another in Java?

Yes, you can call constructors from another constructor. For example:

public class Animal {
    private int animalType;

    public Animal() {
        this(1); //here this(1) internally make call to Animal(1);
    }

    public Animal(int animalType) {
        this.animalType = animalType;
    }
}

you can also read in details from Constructor Chaining in Java

Two constructors

The first line of a constructor is always an invocation to another constructor. You can choose between calling a constructor from the same class with "this(...)" or a constructor from the parent clas with "super(...)". If you don't include either, the compiler includes this line for you: super();

C# constructors overloading

Maybe your class isn't quite complete. Personally, I use a private init() function with all of my overloaded constructors.

class Point2D {

  double X, Y;

  public Point2D(double x, double y) {
    init(x, y);
  }

  public Point2D(Point2D point) {
    if (point == null)
      throw new ArgumentNullException("point");
    init(point.X, point.Y);
  }

  void init(double x, double y) {
    // ... Contracts ...
    X = x;
    Y = y;
  }
}

Constructor overload in TypeScript

It sounds like you want the object parameter to be optional, and also each of the properties in the object to be optional. In the example, as provided, overload syntax isn't needed. I wanted to point out some bad practices in some of the answers here. Granted, it's not the smallest possible expression of essentially writing box = { x: 0, y: 87, width: 4, height: 0 }, but this provides all the code hinting niceties you could possibly want from the class as described. This example allows you to call a function with one, some, all, or none of the parameters and still get default values.

 /** @class */
 class Box {
     public x?: number;
     public y?: number;
     public height?: number;
     public width?: number;     

     constructor(params: Box = {} as Box) {

         // Define the properties of the incoming `params` object here. 
         // Setting a default value with the `= 0` syntax is optional for each parameter
         let {
             x = 0,
             y = 0,
             height = 1,
             width = 1
         } = params;
         
         //  If needed, make the parameters publicly accessible
         //  on the class ex.: 'this.var = var'.
         /**  Use jsdoc comments here for inline ide auto-documentation */
         this.x = x;
         this.y = y;
         this.height = height;
         this.width = width;
     }
 }

Need to add methods? A verbose but more extendable alternative: The Box class above can work double-duty as the interface since they are identical. If you choose to modify the above class, you will need to define and reference a new interface for the incoming parameters object since the Box class no longer would look exactly like the incoming parameters. Notice where the question marks (?:) denoting optional properties move in this case. Since we're setting default values within the class, they are guaranteed to be present, yet they are optional within the incoming parameters object:

    interface BoxParams {
        x?: number;
         // Add Parameters ...
    }

    class Box {
         public x: number;
         // Copy Parameters ...
         constructor(params: BoxParams = {} as BoxParams) {
         let { x = 0 } = params;
         this.x = x;
    }
    doSomething = () => {
        return this.x + this.x;
        }
    }

Whichever way you choose to define your class, this technique offers the guardrails of type safety, yet the flexibility write any of these:

const box1 = new Box();
const box2 = new Box({});
const box3 = new Box({x:0});
const box4 = new Box({x:0, height:10});
const box5 = new Box({x:0, y:87,width:4,height:0});

 // Correctly reports error in TypeScript, and in js, box6.z is undefined
const box6 = new Box({z:0});  

Compiled, you see how the default settings are only used if an optional value is undefined; it avoids the pitfalls of a widely used (but error-prone) fallback syntax of var = isOptional || default; by checking against void 0, which is shorthand for undefined:

The Compiled Output

var Box = (function () {
    function Box(params) {
        if (params === void 0) { params = {}; }
        var _a = params.x, x = _a === void 0 ? 0 : _a, _b = params.y, y = _b === void 0 ? 0 : _b, _c = params.height, height = _c === void 0 ? 1 : _c, _d = params.width, width = _d === void 0 ? 1 : _d;
        this.x = x;
        this.y = y;
        this.height = height;
        this.width = width;
    }
    return Box;
}());

Addendum: Setting default values: the wrong way

The || (or) operator

Consider the danger of ||/or operators when setting default fallback values as shown in some other answers. This code below illustrates the wrong way to set defaults. You can get unexpected results when evaluating against falsey values like 0, '', null, undefined, false, NaN:

var myDesiredValue = 0;
var result = myDesiredValue || 2;

// This test will correctly report a problem with this setup.
console.assert(myDesiredValue === result && result === 0, 'Result should equal myDesiredValue. ' + myDesiredValue + ' does not equal ' + result);

Object.assign(this,params)

In my tests, using es6/typescript destructured object can be 15-90% faster than Object.assign. Using a destructured parameter only allows methods and properties you've assigned to the object. For example, consider this method:

class BoxTest {
    public x?: number = 1;

    constructor(params: BoxTest = {} as BoxTest) {
        Object.assign(this, params);
    }
}

If another user wasn't using TypeScript and attempted to place a parameter that didn't belong, say, they might try putting a z property

var box = new BoxTest({x: 0, y: 87, width: 4, height: 0, z: 7});

// This test will correctly report an error with this setup. `z` was defined even though `z` is not an allowed property of params.
console.assert(typeof box.z === 'undefined')

How do I declare an array with a custom class?

You need a parameterless constructor to be able to create an instance of your class. Your current constructor requires two input string parameters.

Normally C++ implies having such a constructor (=default parameterless constructor) if there is no other constructor declared. By declaring your first constructor with two parameters you overwrite this default behaviour and now you have to declare this constructor explicitly.

Here is the working code:

#include <iostream> 
#include <string>  // <-- you need this if you want to use string type

using namespace std; 

class name { 
  public: 
    string first; 
    string last; 

  name(string a, string b){ 
    first = a; 
    last = b; 

  }

  name ()  // <-- this is your explicit parameterless constructor
  {}

}; 

int main (int argc, const char * argv[]) 
{ 

  const int howManyNames = 3; 

  name someName[howManyNames]; 

  return 0; 
}

(BTW, you need to include to make the code compilable.)

An alternative way is to initialize your instances explicitly on declaration

  name someName[howManyNames] = { {"Ivan", "The Terrible"}, {"Catherine", "The Great"} };

Inheritance with base class constructor with parameters

The problem is that the base class foo has no parameterless constructor. So you must call constructor of the base class with parameters from constructor of the derived class:

public bar(int a, int b) : base(a, b)
{
    c = a * b;
}

How do I call the base class constructor?

Regarding the alternative to super; you'd in most cases use use the base class either in the initialization list of the derived class, or using the Base::someData syntax when you are doing work elsewhere and the derived class redefines data members.

struct Base
{
    Base(char* name) { }
    virtual ~Base();
    int d;
};

struct Derived : Base
{
    Derived() : Base("someString") { }
    int d;
    void foo() { d = Base::d; }
};

Calling the base constructor in C#

If you need to call the base constructor but not right away because your new (derived) class needs to do some data manipulation, the best solution is to resort to factory method. What you need to do is to mark private your derived constructor, then make a static method in your class that will do all the necessary stuff and later call the constructor and return the object.

public class MyClass : BaseClass
{
    private MyClass(string someString) : base(someString)
    {
        //your code goes in here
    }

    public static MyClass FactoryMethod(string someString)
    {
        //whatever you want to do with your string before passing it in
        return new MyClass(someString);
    }
}

Call one constructor from another

Error handling and making your code reusable is key. I added string to int validation and it is possible to add other types if needed. Solving this problem with a more reusable solution could be this:

public class Sample
{
    public Sample(object inputToInt)
    {
        _intField = objectToInt(inputToInt);
    }

    public int IntProperty => _intField;

    private readonly int _intField;
}

public static int objectToInt(object inputToInt)
{
    switch (inputToInt)
        {
            case int inputInt:
                return inputInt;
            break;
            case string inputString:
            if (!int.TryParse(inputString, out int parsedInt))
            {
                throw new InvalidParameterException($"The input {inputString} could not be parsed to int");
            }
            return parsedInt;

            default:
                throw new InvalidParameterException($"Constructor do not support {inputToInt.GetType().Name}");
            break;
        }
}

no default constructor exists for class

You declared the constructor blowfish as this:

Blowfish(BlowfishAlgorithm algorithm);

So this line cannot exist (without further initialization later):

Blowfish _blowfish;

since you passed no parameter. It does not understand how to handle a parameter-less declaration of object "BlowFish" - you need to create another constructor for that.

best way to create object

Or you can use a data file to put many person objects in to a list or array. You do need to use the System.IO for this. And you need a data file which contains all the information about the objects.

A method for it would look something like this:

static void ReadFile()
{
    using(StreamWriter writer = new StreamWriter(@"Data.csv"))
    {
        string line = null;
        line = reader.ReadLine();
        while(null!= (line = reader.ReadLine())
                {
                    string[] values = line.Split(',');
                    string name = values[0];
                    int age = int.Parse(values[1]);
                }
        Person person = new Person(name, age);
    }
}

Hide Utility Class Constructor : Utility classes should not have a public or default constructor

I use an enum with no instances

public enum MyUtils { 
    ; // no instances
    // class is final and the constructor is private

    public static int myUtilityMethod(int x) {
        return x * x;
    }
}

you can call this using

int y = MyUtils.myUtilityMethod(5); // returns 25.

How to inherit constructors?

Another simple solution could be to use a structure or simple data class that contains the parameters as properties; that way you can have all the default values and behaviors set up ahead of time, passing the "parameter class" in as the single constructor parameter:

public class FooParams
{
    public int Size...
    protected myCustomStruct _ReasonForLife ...
}
public class Foo
{
    private FooParams _myParams;
    public Foo(FooParams myParams)
    {
          _myParams = myParams;
    }
}

This avoids the mess of multiple constructors (sometimes) and gives strong typing, default values, and other benefits not provided by a parameter array. It also makes it easy to carry forward since anything that inherits from Foo can still get to, or even add to, FooParams as needed. You still need to copy the constructor, but you always (most of the time) only (as a general rule) ever (at least, for now) need one constructor.

public class Bar : Foo
{
    public Bar(FooParams myParams) : base(myParams) {}
}

I really like the overloaded Initailize() and Class Factory Pattern approaches better, but sometimes you just need to have a smart constructor. Just a thought.

Can I call an overloaded constructor from another constructor of the same class in C#?

If you mean if you can do ctor chaining in C#, the answer is yes. The question has already been asked.

However it seems from the comments, it seems what you really intend to ask is 'Can I call an overloaded constructor from within another constructor with pre/post processing?'
Although C# doesn't have the syntax to do this, you could do this with a common initialization function (like you would do in C++ which doesn't support ctor chaining)

class A
{
  //ctor chaining
  public A() : this(0)
  {  
      Console.WriteLine("default ctor"); 
  }

  public A(int i)
  {  
      Init(i); 
  }

  // what you want
  public A(string s)
  {  
      Console.WriteLine("string ctor overload" );
      Console.WriteLine("pre-processing" );
      Init(Int32.Parse(s));
      Console.WriteLine("post-processing" );
  }

   private void Init(int i)
   {
      Console.WriteLine("int ctor {0}", i);
   }
}

How to invoke the super constructor in Python?

With Python 2.x old-style classes it would be this:

class A: 
 def __init__(self): 
   print "world" 

class B(A): 
 def __init__(self): 
   print "hello" 
   A.__init__(self)

Can a constructor in Java be private?

Private Constructors can be defnied in the Java for the following reasons

  1. To have control on the instantiation of the Java objects, it wont allow you to create an instance of an object.

  2. It wont allow the class to be Subclassed

  3. This has a special advantage when implementing the singleton Pattern, Private contstructors are used for it and have a control on the creating the instance for the whole application.

  4. when you want to have a class with all constants defined and Does not require its instance any more, then we declare that class as a private constructor.

Can I use Class.newInstance() with constructor arguments?

Do not use Class.newInstance(); see this thread: Why is Class.newInstance() evil?

Like other answers say, use Constructor.newInstance() instead.

Can I call methods in constructor in Java?

You can. But by placing this in the constructor you are making your object hard to test.

Instead you should:

  • provide the configuration with a setter
  • have a separate init() method

Dependency injection frameworks give you these options.

public class ConfigurableObject {
   private Map<String, String> configuration;
   public ConfigurableObject() {

   }

   public void setConfiguration(..) {
       //...simply set the configuration
   }
}

An example of the 2nd option (best used when the object is managed by a container):

public class ConfigurableObject {
   private File configFile;
   private Map<String, String> configuration;
   public ConfigurableObject(File configFile) {
       this.configFile = configFile;
   }

   public void init() {
       this.configuration = parseConfig(); // implement
   }
}

This, of course, can be written by just having the constructor

public ConfigurableObject(File configfile) {
    this.configuration = parseConfig(configFile);
}

But then you won't be able to provide mock configurations.

I know the 2nd opttion sounds more verbose and prone to error (if you forget to initialize). And it won't really hurt you that much if you do it in a constructor. But making your code more dependency-injection oriented is generally a good practice.

The 1st option is best - it can be used with both DI framework and with manual DI.

What's wrong with overridable method calls in constructors?

On invoking overridable method from constructors

Simply put, this is wrong because it unnecessarily opens up possibilities to MANY bugs. When the @Override is invoked, the state of the object may be inconsistent and/or incomplete.

A quote from Effective Java 2nd Edition, Item 17: Design and document for inheritance, or else prohibit it:

There are a few more restrictions that a class must obey to allow inheritance. Constructors must not invoke overridable methods, directly or indirectly. If you violate this rule, program failure will result. The superclass constructor runs before the subclass constructor, so the overriding method in the subclass will be invoked before the subclass constructor has run. If the overriding method depends on any initialization performed by the subclass constructor, the method will not behave as expected.

Here's an example to illustrate:

public class ConstructorCallsOverride {
    public static void main(String[] args) {

        abstract class Base {
            Base() {
                overrideMe();
            }
            abstract void overrideMe(); 
        }

        class Child extends Base {

            final int x;

            Child(int x) {
                this.x = x;
            }

            @Override
            void overrideMe() {
                System.out.println(x);
            }
        }
        new Child(42); // prints "0"
    }
}

Here, when Base constructor calls overrideMe, Child has not finished initializing the final int x, and the method gets the wrong value. This will almost certainly lead to bugs and errors.

Related questions

See also


On object construction with many parameters

Constructors with many parameters can lead to poor readability, and better alternatives exist.

Here's a quote from Effective Java 2nd Edition, Item 2: Consider a builder pattern when faced with many constructor parameters:

Traditionally, programmers have used the telescoping constructor pattern, in which you provide a constructor with only the required parameters, another with a single optional parameters, a third with two optional parameters, and so on...

The telescoping constructor pattern is essentially something like this:

public class Telescope {
    final String name;
    final int levels;
    final boolean isAdjustable;

    public Telescope(String name) {
        this(name, 5);
    }
    public Telescope(String name, int levels) {
        this(name, levels, false);
    }
    public Telescope(String name, int levels, boolean isAdjustable) {       
        this.name = name;
        this.levels = levels;
        this.isAdjustable = isAdjustable;
    }
}

And now you can do any of the following:

new Telescope("X/1999");
new Telescope("X/1999", 13);
new Telescope("X/1999", 13, true);

You can't, however, currently set only the name and isAdjustable, and leaving levels at default. You can provide more constructor overloads, but obviously the number would explode as the number of parameters grow, and you may even have multiple boolean and int arguments, which would really make a mess out of things.

As you can see, this isn't a pleasant pattern to write, and even less pleasant to use (What does "true" mean here? What's 13?).

Bloch recommends using a builder pattern, which would allow you to write something like this instead:

Telescope telly = new Telescope.Builder("X/1999").setAdjustable(true).build();

Note that now the parameters are named, and you can set them in any order you want, and you can skip the ones that you want to keep at default values. This is certainly much better than telescoping constructors, especially when there's a huge number of parameters that belong to many of the same types.

See also

Related questions

Is it good practice to make the constructor throw an exception?

I've always considered throwing checked exceptions in the constructor to be bad practice, or at least something that should be avoided.

The reason for this is that you cannot do this :

private SomeObject foo = new SomeObject();

Instead you must do this :

private SomeObject foo;
public MyObject() {
    try {
        foo = new SomeObject()
    } Catch(PointlessCheckedException e) {
       throw new RuntimeException("ahhg",e);
    }
}

At the point when I'm constructing SomeObject I know what it's parameters are so why should I be expected to wrap it in a try catch? Ahh you say but if I'm constructing an object from dynamic parameters I don't know if they're valid or not. Well, you could... validate the parameters before passing them to the constructor. That would be good practice. And if all you're concerned about is whether the parameters are valid then you can use IllegalArgumentException.

So instead of throwing checked exceptions just do

public SomeObject(final String param) {
    if (param==null) throw new NullPointerException("please stop");
    if (param.length()==0) throw new IllegalArgumentException("no really, please stop");
}

Of course there are cases where it might just be reasonable to throw a checked exception

public SomeObject() {
    if (todayIsWednesday) throw new YouKnowYouCannotDoThisOnAWednesday();
}

But how often is that likely?

Default parameters with C++ constructors

I'd go with the default arguments, especially since C++ doesn't let you chain constructors (so you end up having to duplicate the initialiser list, and possibly more, for each overload).

That said, there are some gotchas with default arguments, including the fact that constants may be inlined (and thereby become part of your class' binary interface). Another to watch out for is that adding default arguments can turn an explicit multi-argument constructor into an implicit one-argument constructor:

class Vehicle {
public:
  Vehicle(int wheels, std::string name = "Mini");
};

Vehicle x = 5;  // this compiles just fine... did you really want it to?

What is the function __construct used for?

__construct is a method for initializing of new object before it is used.
http://php.net/manual/en/language.oop5.decon.php#object.construct

Can an abstract class have a constructor?

Yes it can have a constructor and it is defined and behaves just like any other class's constructor. Except that abstract classes can't be directly instantiated, only extended, so the use is therefore always from a subclass's constructor.

Inheriting constructors

Constructors are not inherited. They are called implicitly or explicitly by the child constructor.

The compiler creates a default constructor (one with no arguments) and a default copy constructor (one with an argument which is a reference to the same type). But if you want a constructor that will accept an int, you have to define it explicitly.

class A
{
public: 
    explicit A(int x) {}
};

class B: public A
{
public:
    explicit B(int x) : A(x) { }
};

UPDATE: In C++11, constructors can be inherited. See Suma's answer for details.

How to start an Intent by passing some parameters to it?

I think you want something like this:

Intent foo = new Intent(this, viewContacts.class);
foo.putExtra("myFirstKey", "myFirstValue");
foo.putExtra("mySecondKey", "mySecondValue");
startActivity(foo);

or you can combine them into a bundle first. Corresponding getExtra() routines exist for the other side. See the intent topic in the dev guide for more information.

Calling the base class constructor from the derived class constructor

The constructor of PetStore will call a constructor of Farm; there's no way you can prevent it. If you do nothing (as you've done), it will call the default constructor (Farm()); if you need to pass arguments, you'll have to specify the base class in the initializer list:

PetStore::PetStore()
    : Farm( neededArgument )
    , idF( 0 )
{
}

(Similarly, the constructor of PetStore will call the constructor of nameF. The constructor of a class always calls the constructors of all of its base classes and all of its members.)

How can I initialize C++ object member variables in the constructor?

You're trying to create a ThingOne by using operator= which isn't going to work (incorrect syntax). Also, you're using a class name as a variable name, that is, ThingOne* ThingOne. Firstly, let's fix the variable names:

private:
    ThingOne* t1;
    ThingTwo* t2;

Since these are pointers, they must point to something. If the object hasn't been constructed yet, you'll need to do so explicitly with new in your BigMommaClass constructor:

BigMommaClass::BigMommaClass(int n1, int n2)
{
    t1 = new ThingOne(100);
    t2 = new ThingTwo(n1, n2);
}

Generally initializer lists are preferred for construction however, so it will look like:

BigMommaClass::BigMommaClass(int n1, int n2)
    : t1(new ThingOne(100)), t2(new ThingTwo(n1, n2))
{ }

Java Constructor Inheritance

David's answer is correct. I'd like to add that you might be getting a sign from God that your design is messed up, and that "Son" ought not to be a subclass of "Super", but that, instead, Super has some implementation detail best expressed by having the functionality that Son provides, as a strategy of sorts.

EDIT: Jon Skeet's answer is awesomest.

Object array initialization without default constructor

You can create an array of pointers.

Car** mycars = new Car*[userInput];
for (int i=0; i<userInput; i++){
    mycars[i] = new Car(...);
}

...

for (int i=0; i<userInput; i++){
    delete mycars[i];
}
delete [] mycars;

or

Car() constructor does not need to be public. Add a static method to your class that builds an array:

static Car* makeArray(int length){
    return new Car[length];
}

Why do this() and super() have to be the first statement in a constructor?

So, it is not stopping you from executing logic before the call to super. It is just stopping you from executing logic that you can't fit into a single expression.

Actually you can execute logic with several expessions, you just have to wrap your code in a static function and call it in the super statement.

Using your example:

public class MySubClassC extends MyClass {
    public MySubClassC(Object item) {
        // Create a list that contains the item, and pass the list to super
        super(createList(item));  // OK
    }

    private static List createList(item) {
        List list = new ArrayList();
        list.add(item);
        return list;
    }
}

Constructor overloading in Java - best practice

If you have a very complex class with a lot of options of which only some combinations are valid, consider using a Builder. Works very well both codewise but also logically.

The Builder is a nested class with methods only designed to set fields, and then the ComplexClass constructor only takes such a Builder as an argument.


Edit: The ComplexClass constructor can ensure that the state in the Builder is valid. This is very hard to do if you just use setters on ComplexClass.

How to do constructor chaining in C#

What is usage of "Constructor Chain"?
You use it for calling one constructor from another constructor.

How can implement "Constructor Chain"?
Use ": this (yourProperties)" keyword after definition of constructor. for example:

Class MyBillClass
{
    private DateTime requestDate;
    private int requestCount;

    public MyBillClass()
    {
        /// ===== we naming "a" constructor ===== ///
        requestDate = DateTime.Now;
    }
    public MyBillClass(int inputCount) : this()
    {
        /// ===== we naming "b" constructor ===== ///
        /// ===== This method is "Chained Method" ===== ///
        this.requestCount= inputCount;
    }
}

Why is it useful?
Important reason is reduce coding, and prevention of duplicate code. such as repeated code for initializing property Suppose some property in class must be initialized with specific value (In our sample, requestDate). And class have 2 or more constructor. Without "Constructor Chain", you must repeat initializaion code in all constractors of class.

How it work? (Or, What is execution sequence in "Constructor Chain")?
in above example, method "a" will be executed first, and then instruction sequence will return to method "b". In other word, above code is equal with below:

Class MyBillClass
{
    private DateTime requestDate;
    private int requestCount;

    public MyBillClass()
    {
        /// ===== we naming "a" constructor ===== ///
        requestDate = DateTime.Now;
    }
    public MyBillClass(int inputCount) : this()
    {
        /// ===== we naming "b" constructor ===== ///
        // ===== This method is "Chained Method" ===== ///

        /// *** --- > Compiler execute "MyBillClass()" first, And then continue instruction sequence from here
        this.requestCount= inputCount;
    }
}

Using C++ base class constructors?

Prefer initialization:

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

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

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


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

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

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

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

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

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

    return 0;
}

C++: constructor initializer for arrays

in visual studio 2012 or above, you can do like this

struct Foo { Foo(int x) { /* ... */  } };

struct Baz { 
     Foo foo[3];

     Baz() : foo() { }
};

__init__() missing 1 required positional argument

Your constructor is expecting one parameter (data). You're not passing it in the call. I guess you wanted to initialise a field in the object. That would look like this:

class DHT:
    def __init__(self):
        self.data = {}
        self.data['one'] = '1'
        self.data['two'] = '2'
        self.data['three'] = '3'
    def showData(self):
        print(self.data)

if __name__ == '__main__':
    DHT().showData()

Or even just:

class DHT:
    def __init__(self):
        self.data = {'one': '1', 'two': '2', 'three': '3'}
    def showData(self):
        print(self.data)

Purpose of a constructor in Java?

A Java constructor has the same name as the name of the class to which it belongs.

Constructor’s syntax does not include a return type, since constructors never return a value.

Constructor is always called when object is created. example:- Default constructor

class Student3{  
    int id;  
    String name;  
    void display(){System.out.println(id+" "+name);}  
    public static void main(String args[]){  
        Student3 s1=new Student3();  
        Student3 s2=new Student3();  
        s1.display();  
        s2.display();  
    }  
} 

Output:

0 null
0 null

Explanation: In the above class,you are not creating any constructor so compiler provides you a default constructor.Here 0 and null values are provided by default constructor.

Example of parameterized constructor

In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor.

class Student4{  
    int id;  
    String name;  
    Student4(int i,String n){  
        id = i;  
        name = n;  
    }  
    void display(){System.out.println(id+" "+name);}  
    public static void main(String args[]){  
        Student4 s1 = new Student4(111,"Karan");  
        Student4 s2 = new Student4(222,"Aryan");  
        s1.display();  
        s2.display();  
    }  
}  

Output:

111 Karan
222 Aryan

What is the difference between using constructor vs getInitialState in React / React Native?

The two approaches are not interchangeable. You should initialize state in the constructor when using ES6 classes, and define the getInitialState method when using React.createClass.

See the official React doc on the subject of ES6 classes.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { /* initial state */ };
  }
}

is equivalent to

var MyComponent = React.createClass({
  getInitialState() {
    return { /* initial state */ };
  },
});

Is it not possible to define multiple constructors in Python?

For the example you gave, use default values:

class City:
    def __init__(self, name="Default City Name"):
        ...
    ...

In general, you have two options:

1) Do if-elif blocks based on the type:

def __init__(self, name):
    if isinstance(name, str):
        ...
    elif isinstance(name, City):
        ...
    ...

2) Use duck typing --- that is, assume the user of your class is intelligent enough to use it correctly. This is typically the preferred option.

undefined reference to 'vtable for class' constructor

You're declaring a virtual function and not defining it:

virtual void calculateCredits();

Either define it or declare it as:

virtual void calculateCredits() = 0;

Or simply:

virtual void calculateCredits() { };

Read more about vftable: http://en.wikipedia.org/wiki/Virtual_method_table

Why do abstract classes in Java have constructors?

Two reasons for this:

1) Abstract classes have constructors and those constructors are always invoked when a concrete subclass is instantiated. We know that when we are going to instantiate a class, we always use constructor of that class. Now every constructor invokes the constructor of its super class with an implicit call to super().

2) We know constructor are also used to initialize fields of a class. We also know that abstract classes may contain fields and sometimes they need to be initialized somehow by using constructor.

Creating an instance of class

  1. Allocates some dynamic memory from the free store, and creates an object in that memory using its default constructor. You never delete it, so the memory is leaked.
  2. Does exactly the same as 1; in the case of user-defined types, the parentheses are optional.
  3. Allocates some automatic memory, and creates an object in that memory using its default constructor. The memory is released automatically when the object goes out of scope.
  4. Similar to 3. Notionally, the named object foo4 is initialised by default-constructing, copying and destroying a temporary object; usually, this is elided giving the same result as 3.
  5. Allocates a dynamic object, then initialises a second by copying the first. Both objects are leaked; and there's no way to delete the first since you don't keep a pointer to it.
  6. Does exactly the same as 5.
  7. Does not compile. Foo foo5 is a declaration, not an expression; function (and constructor) arguments must be expressions.
  8. Creates a temporary object, and initialises a dynamic object by copying it. Only the dynamic object is leaked; the temporary is destroyed automatically at the end of the full expression. Note that you can create the temporary with just Foo() rather than the equivalent Foo::Foo() (or indeed Foo::Foo::Foo::Foo::Foo())

When do I use each?

  1. Don't, unless you like unnecessary decorations on your code.
  2. When you want to create an object that outlives the current scope. Remember to delete it when you've finished with it, and learn how to use smart pointers to control the lifetime more conveniently.
  3. When you want an object that only exists in the current scope.
  4. Don't, unless you think 3 looks boring and what to add some unnecessary decoration.
  5. Don't, because it leaks memory with no chance of recovery.
  6. Don't, because it leaks memory with no chance of recovery.
  7. Don't, because it won't compile
  8. When you want to create a dynamic Bar from a temporary Foo.

What is the use of static constructors?

Why and when would we create a static constructor ...?

One specific reason to use a static constructor is to create a 'super enum' class. Here's a (simple, contrived) example:

public class Animals
{
    private readonly string _description;
    private readonly string _speciesBinomialName;

    public string Description { get { return _description; } }
    public string SpeciesBinomialName { get { return _speciesBinomialName; } }

    private Animals(string description, string speciesBinomialName)
    {
        _description = description;
        _speciesBinomialName = speciesBinomialName;
    }

    private static readonly Animals _dog;
    private static readonly Animals _cat;
    private static readonly Animals _boaConstrictor;

    public static Animals Dog { get { return _dog; } }
    public static Animals Cat { get { return _cat; } }
    public static Animals BoaConstrictor { get { return _boaConstrictor; } }

    static Animals()
    {
        _dog = new Animals("Man's best friend", "Canis familiaris");
        _cat = new Animals("Small, typically furry, killer", "Felis catus");
        _boaConstrictor = new Animals("Large, heavy-bodied snake", "Boa constrictor");
    }
}

You'd use it very similarly (in syntactical appearance) to any other enum:

Animals.Dog

The advantage of this over a regular enum is that you can encapsulate related info easily. One disadvantage is that you can't use these values in a switch statement (because it requires constant values).

Java default constructor

A default constructor is created if you don't define any constructors in your class. It simply is a no argument constructor which does nothing. Edit: Except call super()

public Module(){
}

Constructor of an abstract class in C#

It's there to enforce some initialization logic required by all implementations of your abstract class, or any methods you have implemented on your abstract class (not all the methods on your abstract class have to be abstract, some can be implemented).

Any class which inherits from your abstract base class will be obliged to call the base constructor.

Using "Object.create" instead of "new"

Summary:

  • Object.create() is a Javascript function which takes 2 arguments and returns a new object.
  • The first argument is an object which will be the prototype of the newly created object
  • The second argument is an object which will be the properties of the newly created object

Example:

_x000D_
_x000D_
const proto = {_x000D_
  talk : () => console.log('hi')_x000D_
}_x000D_
_x000D_
const props = {_x000D_
  age: {_x000D_
    writable: true,_x000D_
    configurable: true,_x000D_
    value: 26_x000D_
  }_x000D_
}_x000D_
_x000D_
_x000D_
let Person = Object.create(proto, props)_x000D_
_x000D_
console.log(Person.age);_x000D_
Person.talk();
_x000D_
_x000D_
_x000D_

Practical applications:

  1. The main advantage of creating an object in this manner is that the prototype can be explicitly defined. When using an object literal, or the new keyword you have no control over this (however, you can overwrite them of course).
  2. If we want to have a prototype The new keyword invokes a constructor function. With Object.create() there is no need for invoking or even declaring a constructor function.
  3. It can Basically be a helpful tool when you want create objects in a very dynamic manner. We can make an object factory function which creates objects with different prototypes depending on the arguments received.

Call asynchronous method in constructor?

A quick way to execute some time-consuming operation in any constructor is by creating an action and run them asynchronously.

new Action( async() => await InitializeThingsAsync())();

Running this piece of code will neither block your UI nor leave you with any loose threads. And if you need to update any UI (considering you are not using MVVM approach), you can use the Dispatcher to do so as many have suggested.

A Note: This option only provides you a way to start an execution of a method from the constructor if you don't have any init or onload or navigated overrides. Most likely this will keep on running even after the construction has been completed. Hence the result of this method call may NOT be available in the constructor itself.

Do the parentheses after the type name make a difference with new?

Assuming that Test is a class with a defined constructor, there's no difference. The latter form makes it a little clearer that Test's constructor is running, but that's about it.

Class constructor type in typescript?

How can I declare a class type, so that I ensure the object is a constructor of a general class?

A Constructor type could be defined as:

 type AConstructorTypeOf<T> = new (...args:any[]) => T;

 class A { ... }

 function factory(Ctor: AConstructorTypeOf<A>){
   return new Ctor();
 }

const aInstance = factory(A);

C# static class constructor

Yes, a static class can have static constructor, and the use of this constructor is initialization of static member.

static class Employee1
{
    static int EmpNo;
    static Employee1()
    {
        EmpNo = 10;
        // perform initialization here
    }
    public static void Add()
    { 

    }
    public static void Add1()
    { 

    }
}

and static constructor get called only once when you have access any type member of static class with class name Class1

Suppose you are accessing the first EmployeeName field then constructor get called this time, after that it will not get called, even if you will access same type member.

 Employee1.EmployeeName = "kumod";
        Employee1.Add();
        Employee1.Add();

What are the rules for calling the superclass constructor?

In C++ there is a concept of constructor's initialization list, which is where you can and should call the base class' constructor and where you should also initialize the data members. The initialization list comes after the constructor signature following a colon, and before the body of the constructor. Let's say we have a class A:


class A : public B
{
public:
  A(int a, int b, int c);
private:
  int b_, c_;
};

Then, assuming B has a constructor which takes an int, A's constructor may look like this:


A::A(int a, int b, int c) 
  : B(a), b_(b), c_(c) // initialization list
{
  // do something
}

As you can see, the constructor of the base class is called in the initialization list. Initializing the data members in the initialization list, by the way, is preferable to assigning the values for b_, and c_ inside the body of the constructor, because you are saving the extra cost of assignment.

Keep in mind, that data members are always initialized in the order in which they are declared in the class definition, regardless of their order in the initialization list. To avoid strange bugs, which may arise if your data members depend on each other, you should always make sure that the order of the members is the same in the initialization list and the class definition. For the same reason the base class constructor must be the first item in the initialization list. If you omit it altogether, then the default constructor for the base class will be called automatically. In that case, if the base class does not have a default constructor, you will get a compiler error.

Struct Constructor in C++?

As the other answers mention, a struct is basically treated as a class in C++. This allows you to have a constructor which can be used to initialise the struct with default values. Below, the constructor takes sz and b as arguments, and initializes the other variables to some default values.

struct blocknode
{
    unsigned int bsize;
    bool free;
    unsigned char *bptr;
    blocknode *next;
    blocknode *prev;

    blocknode(unsigned int sz, unsigned char *b, bool f = true,
              blocknode *p = 0, blocknode *n = 0) :
              bsize(sz), free(f), bptr(b), prev(p), next(n) {}
};

Usage:

unsigned char *bptr = new unsigned char[1024];
blocknode *fblock = new blocknode(1024, btpr);

Java. Implicit super constructor Employee() is undefined. Must explicitly invoke another constructor

An explicit call to a parent class constructor is required any time the parent class lacks a no-argument constructor. You can either add a no-argument constructor to the parent class or explicitly call the parent class constructor in your child class.

How to overload __init__ method based on argument type?

A much neater way to get 'alternate constructors' is to use classmethods. For instance:

>>> class MyData:
...     def __init__(self, data):
...         "Initialize MyData from a sequence"
...         self.data = data
...     
...     @classmethod
...     def fromfilename(cls, filename):
...         "Initialize MyData from a file"
...         data = open(filename).readlines()
...         return cls(data)
...     
...     @classmethod
...     def fromdict(cls, datadict):
...         "Initialize MyData from a dict's items"
...         return cls(datadict.items())
... 
>>> MyData([1, 2, 3]).data
[1, 2, 3]
>>> MyData.fromfilename("/tmp/foobar").data
['foo\n', 'bar\n', 'baz\n']
>>> MyData.fromdict({"spam": "ham"}).data
[('spam', 'ham')]

The reason it's neater is that there is no doubt about what type is expected, and you aren't forced to guess at what the caller intended for you to do with the datatype it gave you. The problem with isinstance(x, basestring) is that there is no way for the caller to tell you, for instance, that even though the type is not a basestring, you should treat it as a string (and not another sequence.) And perhaps the caller would like to use the same type for different purposes, sometimes as a single item, and sometimes as a sequence of items. Being explicit takes all doubt away and leads to more robust and clearer code.

Methods vs Constructors in Java

the difference r:

  1. Constructor must have the name same as class but method can be made by any name.
  2. Constructor are not inherited automatically by child classes while child inherit method from their parent class unless they r protected by private keyword.
  3. Constructor r called explicitly while methods implicitaly.
  4. Constructor doesnot have any return type while method have.

What is a clean, Pythonic way to have multiple constructors in Python?

One should definitely prefer the solutions already posted, but since no one mentioned this solution yet, I think it is worth mentioning for completeness.

The @classmethod approach can be modified to provide an alternative constructor which does not invoke the default constructor (__init__). Instead, an instance is created using __new__.

This could be used if the type of initialization cannot be selected based on the type of the constructor argument, and the constructors do not share code.

Example:

class MyClass(set):

    def __init__(self, filename):
        self._value = load_from_file(filename)

    @classmethod
    def from_somewhere(cls, somename):
        obj = cls.__new__(cls)  # Does not call __init__
        super(MyClass, obj).__init__()  # Don't forget to call any polymorphic base class initializers
        obj._value = load_from_somewhere(somename)
        return obj

Throwing exceptions from constructors

#include <iostream>

class bar
{
public:
  bar()
  {
    std::cout << "bar() called" << std::endl;
  }

  ~bar()
  {
    std::cout << "~bar() called" << std::endl;

  }
};
class foo
{
public:
  foo()
    : b(new bar())
  {
    std::cout << "foo() called" << std::endl;
    throw "throw something";
  }

  ~foo()
  {
    delete b;
    std::cout << "~foo() called" << std::endl;
  }

private:
  bar *b;
};


int main(void)
{
  try {
    std::cout << "heap: new foo" << std::endl;
    foo *f = new foo();
  } catch (const char *e) {
    std::cout << "heap exception: " << e << std::endl;
  }

  try {
    std::cout << "stack: foo" << std::endl;
    foo f;
  } catch (const char *e) {
    std::cout << "stack exception: " << e << std::endl;
  }

  return 0;
}

the output:

heap: new foo
bar() called
foo() called
heap exception: throw something
stack: foo
bar() called
foo() called
stack exception: throw something

the destructors are not called, so if a exception need to be thrown in a constructor, a lot of stuff(e.g. clean up?) to do.

Python constructor and default value

Let's illustrate what's happening here:

Python 3.1.2 (r312:79147, Sep 27 2010, 09:45:41) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo:
...     def __init__(self, x=[]):
...         x.append(1)
... 
>>> Foo.__init__.__defaults__
([],)
>>> f = Foo()
>>> Foo.__init__.__defaults__
([1],)
>>> f2 = Foo()
>>> Foo.__init__.__defaults__
([1, 1],)

You can see that the default arguments are stored in a tuple which is an attribute of the function in question. This actually has nothing to do with the class in question and goes for any function. In python 2, the attribute will be func.func_defaults.

As other posters have pointed out, you probably want to use None as a sentinel value and give each instance it's own list.

What does the explicit keyword mean?

It is always a good coding practice to make your one argument constructors (including those with default values for arg2,arg3,...) as already stated. Like always with C++: if you don't - you'll wish you did...

Another good practice for classes is to make copy construction and assignment private (a.k.a. disable it) unless you really need to implement it. This avoids having eventual copies of pointers when using the methods that C++ will create for you by default. An other way to do this is derive from boost::noncopyable.

Static class initializer in PHP

I am posting this as an answer because this is very important as of PHP 7.4.

The opcache.preload mechanism of PHP 7.4 makes it possible to preload opcodes for classes. If you use it to preload a file that contains a class definition and some side effects, then classes defined in that file will "exist" for all subsequent scripts executed by this FPM server and its workers, but the side effects will not be in effect, and the autoloader will not require the file containing them because the class already "exists". This completely defeats any and all static initialization techniques that rely on executing top-level code in the file that contains the class definition.

How to force deletion of a python object?

The way to close resources are context managers, aka the with statement:

class Foo(object):

  def __init__(self):
    self.bar = None

  def __enter__(self):
    if self.bar != 'open':
      print 'opening the bar'
      self.bar = 'open'
    return self # this is bound to the `as` part

  def close(self):
    if self.bar != 'closed':
      print 'closing the bar'
      self.bar = 'close'

  def __exit__(self, *err):
    self.close()

if __name__ == '__main__':
  with Foo() as foo:
    print foo, foo.bar

output:

opening the bar
<__main__.Foo object at 0x17079d0> open
closing the bar

2) Python's objects get deleted when their reference count is 0. In your example the del foo removes the last reference so __del__ is called instantly. The GC has no part in this.

class Foo(object):

    def __del__(self):
        print "deling", self

if __name__ == '__main__':
    import gc
    gc.disable() # no gc
    f = Foo()
    print "before"
    del f # f gets deleted right away
    print "after"

output:

before
deling <__main__.Foo object at 0xc49690>
after

The gc has nothing to do with deleting your and most other objects. It's there to clean up when simple reference counting does not work, because of self-references or circular references:

class Foo(object):
    def __init__(self, other=None):
        # make a circular reference
        self.link = other
        if other is not None:
            other.link = self

    def __del__(self):
        print "deling", self

if __name__ == '__main__':
    import gc
    gc.disable()   
    f = Foo(Foo())
    print "before"
    del f # nothing gets deleted here
    print "after"
    gc.collect()
    print gc.garbage # The GC knows the two Foos are garbage, but won't delete
                     # them because they have a __del__ method
    print "after gc"
    # break up the cycle and delete the reference from gc.garbage
    del gc.garbage[0].link, gc.garbage[:]
    print "done"

output:

before
after
[<__main__.Foo object at 0x22ed8d0>, <__main__.Foo object at 0x22ed950>]
after gc
deling <__main__.Foo object at 0x22ed950>
deling <__main__.Foo object at 0x22ed8d0>
done

3) Lets see:

class Foo(object):
    def __init__(self):

        raise Exception

    def __del__(self):
        print "deling", self

if __name__ == '__main__':
    f = Foo()

gives:

Traceback (most recent call last):
  File "asd.py", line 10, in <module>
    f = Foo()
  File "asd.py", line 4, in __init__
    raise Exception
Exception
deling <__main__.Foo object at 0xa3a910>

Objects are created with __new__ then passed to __init__ as self. After a exception in __init__, the object will typically not have a name (ie the f = part isn't run) so their ref count is 0. This means that the object is deleted normally and __del__ is called.

Is there a way to @Autowire a bean that requires constructor arguments?

Well, from time to time I run into the same question. As far as I know, one cannot do that when one wants to add dynamic parameters to the constructor. However, the factory pattern may help.

public interface MyBean {
    // here be my fancy stuff
}

public interface MyBeanFactory {
    public MyBean getMyBean(/* bean parameters */);
}

@Component
public class MyBeanFactoryImpl implements MyBeanFactory {
    @Autowired
    WhateverIWantToInject somethingInjected;

    public MyBean getMyBean(/* params */) {
        return new MyBeanImpl(/* params */);
    }

    private class MyBeanImpl implements MyBean {
        public MyBeanImpl(/* params */) {
            // let's do whatever one has to
        }
    }
}

@Component
public class MyConsumerClass {
    @Autowired
    private MyBeanFactory beanFactory;

    public void myMethod() {
        // here one has to prepare the parameters
        MyBean bean = beanFactory.getMyBean(/* params */);
    }
}

Now, MyBean is not a spring bean per se, but it is close enough. Dependency Injection works, although I inject the factory and not the bean itself - one has to inject a new factory on top of his own new MyBean implementation if one wants to replace it.

Further, MyBean has access to other beans - because it may have access to the factory's autowired stuff.

And one might apparently want to add some logic to the getMyBean function, which is extra effort I allow, but unfortunately I have no better solution. Since the problem usually is that the dynamic parameters come from an external source, like a database, or user interaction, therefore I must instantiate that bean only in mid-run, only when that info is readily available, so the Factory should be quite adequate.

Accessing constructor of an anonymous class

That is not possible, but you can add an anonymous initializer like this:

final int anInt = ...;
Object a = new Class1()
{
  {
    System.out.println(anInt);
  }

  void someNewMethod() {
  }
};

Don't forget final on declarations of local variables or parameters used by the anonymous class, as i did it for anInt.

Best way to handle multiple constructors in Java

You need to specify what are the class invariants, i.e. properties which will always be true for an instance of the class (for example, the title of a book will never be null, or the size of a dog will always be > 0).

These invariants should be established during construction, and be preserved along the lifetime of the object, which means that methods shall not break the invariants. The constructors can set these invariants either by having compulsory arguments, or by setting default values:

class Book {
    private String title; // not nullable
    private String isbn;  // nullable

    // Here we provide a default value, but we could also skip the 
    // parameterless constructor entirely, to force users of the class to
    // provide a title
    public Book()
    {
        this("Untitled"); 
    }

    public Book(String title) throws IllegalArgumentException
    {
        if (title == null) 
            throw new IllegalArgumentException("Book title can't be null");
        this.title = title;
        // leave isbn without value
    }
    // Constructor with title and isbn
}

However, the choice of these invariants highly depends on the class you're writing, how you'll use it, etc., so there's no definitive answer to your question.

Pass arguments to Constructor in VBA

Why not this way:

  1. In a class module »myClass« use Public Sub Init(myArguments) instead of Private Sub Class_Initialize()
  2. Instancing: Dim myInstance As New myClass: myInstance.Init myArguments

C# Error: Parent does not contain a constructor that takes 0 arguments

You can use a constructor with no parameters in your Parent class :

public parent() { } 

Creating an object: with or without `new`

The first allocates an object with automatic storage duration, which means it will be destructed automatically upon exit from the scope in which it is defined.

The second allocated an object with dynamic storage duration, which means it will not be destructed until you explicitly use delete to do so.

How to call Base Class's __init__ method from the child class?

You could use super(ChildClass, self).__init__()

class BaseClass(object):
    def __init__(self, *args, **kwargs):
        pass

class ChildClass(BaseClass):
    def __init__(self, *args, **kwargs):
        super(ChildClass, self).__init__(*args, **kwargs)

Your indentation is incorrect, here's the modified code:

class Car(object):
    condition = "new"

    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg

class ElectricCar(Car):
    def __init__(self, battery_type, model, color, mpg):
        self.battery_type=battery_type
        super(ElectricCar, self).__init__(model, color, mpg)

car = ElectricCar('battery', 'ford', 'golden', 10)
print car.__dict__

Here's the output:

{'color': 'golden', 'mpg': 10, 'model': 'ford', 'battery_type': 'battery'}

C# : assign data to properties via constructor vs. instantiating

Second approach is object initializer in C#

Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor.

The first approach

var albumData = new Album("Albumius", "Artistus", 2013);

explicitly calls the constructor, whereas in second approach constructor call is implicit. With object initializer you can leave out some properties as well. Like:

 var albumData = new Album
        {
            Name = "Albumius",
        };

Object initializer would translate into something like:

var albumData; 
var temp = new Album();
temp.Name = "Albumius";
temp.Artist = "Artistus";
temp.Year = 2013;
albumData = temp;

Why it uses a temporary object (in debug mode) is answered here by Jon Skeet.

As far as advantages for both approaches are concerned, IMO, object initializer would be easier to use specially if you don't want to initialize all the fields. As far as performance difference is concerned, I don't think there would any since object initializer calls the parameter less constructor and then assign the properties. Even if there is going to be performance difference it should be negligible.

Serialize JavaScript object into JSON string

I was having some issues using the above solutions with an "associative array" type object. These solutions seem to preserve the values, but they do not preserve the actual names of the objects that those values are associated with, which can cause some issues. So I put together the following functions which I am using instead:

function flattenAssocArr(object) {
  if(typeof object == "object") {
    var keys = [];
    keys[0] = "ASSOCARR";
    keys.push(...Object.keys(object));
    var outArr = [];
    outArr[0] = keys;
    for(var i = 1; i < keys.length; i++) {
        outArr[i] = flattenAssocArr(object[keys[i]])
    }
    return outArr;
  } else {
    return object;
  }
}

function expandAssocArr(object) {
    if(typeof object !== "object")
        return object;
    var keys = object[0];
    var newObj = new Object();
    if(keys[0] === "ASSOCARR") {
        for(var i = 1; i < keys.length; i++) {
            newObj[keys[i]] = expandAssocArr(object[i])
        }
    }
    return newObj;
}

Note that these can't be used with any arbitrary object -- basically it creates a new array, stores the keys as element 0, with the data following it. So if you try to load an array that isn't created with these functions having element 0 as a key list, the results might be...interesting :)

I'm using it like this:

var objAsString = JSON.stringify(flattenAssocArr(globalDataset));
var strAsObject = expandAssocArr(JSON.parse(objAsString));

expected constructor, destructor, or type conversion before ‘(’ token

This is not only a 'newbie' scenario. I just ran across this compiler message (GCC 5.4) when refactoring a class to remove some constructor parameters. I forgot to update both the declaration and definition, and the compiler spit out this unintuitive error.

The bottom line seems to be this: If the compiler can't match the definition's signature to the declaration's signature it thinks the definition is not a constructor and then doesn't know how to parse the code and displays this error. Which is also what happened for the OP: std::string is not the same type as string so the declaration's signature differed from the definition's and this message was spit out.

As a side note, it would be nice if the compiler looked for almost-matching constructor signatures and upon finding one suggested that the parameters didn't match rather than giving this message.

Can constructors throw exceptions in Java?

Yes, they can throw exceptions. If so, they will only be partially initialized and if non-final, subject to attack.

The following is from the Secure Coding Guidelines 2.0.

Partially initialized instances of a non-final class can be accessed via a finalizer attack. The attacker overrides the protected finalize method in a subclass, and attempts to create a new instance of that subclass. This attempt fails (in the above example, the SecurityManager check in ClassLoader's constructor throws a security exception), but the attacker simply ignores any exception and waits for the virtual machine to perform finalization on the partially initialized object. When that occurs the malicious finalize method implementation is invoked, giving the attacker access to this, a reference to the object being finalized. Although the object is only partially initialized, the attacker can still invoke methods on it (thereby circumventing the SecurityManager check).

Chain-calling parent initialisers in python

You can simply write :

class A(object):

    def __init__(self):
        print "Initialiser A was called"

class B(A):

    def __init__(self):
        A.__init__(self)
        # A.__init__(self,<parameters>) if you want to call with parameters
        print "Initialiser B was called"

class C(B):

    def __init__(self):
        # A.__init__(self) # if you want to call most super class...
        B.__init__(self)
        print "Initialiser C was called"

Best way to do multiple constructors in PHP

As has already been shown here, there are many ways of declaring multiple constructors in PHP, but none of them are the correct way of doing so (since PHP technically doesn't allow it). But it doesn't stop us from hacking this functionality... Here's another example:

<?php

class myClass {
    public function __construct() {
        $get_arguments       = func_get_args();
        $number_of_arguments = func_num_args();

        if (method_exists($this, $method_name = '__construct'.$number_of_arguments)) {
            call_user_func_array(array($this, $method_name), $get_arguments);
        }
    }

    public function __construct1($argument1) {
        echo 'constructor with 1 parameter ' . $argument1 . "\n";
    }

    public function __construct2($argument1, $argument2) {
        echo 'constructor with 2 parameter ' . $argument1 . ' ' . $argument2 . "\n";
    }

    public function __construct3($argument1, $argument2, $argument3) {
        echo 'constructor with 3 parameter ' . $argument1 . ' ' . $argument2 . ' ' . $argument3 . "\n";
    }
}

$object1 = new myClass('BUET');
$object2 = new myClass('BUET', 'is');
$object3 = new myClass('BUET', 'is', 'Best.');

Source: The easiest way to use and understand multiple constructors:

Hope this helps. :)

Calling virtual functions inside constructors

As has been pointed out, the objects are created base-down upon construction. When the base object is being constructed, the derived object does not exist yet, so a virtual function override cannot work.

However, this can be solved with polymorphic getters that use static polymorphism instead of virtual functions if your getters return constants, or otherwise can be expressed in a static member function, This example uses CRTP (https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern).

template<typename DerivedClass>
class Base
{
public:
    inline Base() :
    foo(DerivedClass::getFoo())
    {}

    inline int fooSq() {
        return foo * foo;
    }

    const int foo;
};

class A : public Base<A>
{
public:
    inline static int getFoo() { return 1; }
};

class B : public Base<B>
{
public:
    inline static int getFoo() { return 2; }
};

class C : public Base<C>
{
public:
    inline static int getFoo() { return 3; }
};

int main()
{
    A a;
    B b;
    C c;

    std::cout << a.fooSq() << ", " << b.fooSq() << ", " << c.fooSq() << std::endl;

    return 0;
}

With the use of static polymorphism, the base class knows which class' getter to call as the information is provided at compile-time.

Javascript "Not a Constructor" Exception while creating objects

In my case I was using the prototype name as the object name. For e.g.

function proto1()
{}

var proto1 = new proto1();

It was a silly mistake but might be of help to someone like me ;)

Interface defining a constructor signature?

you don't.

the constructor is part of the class that can implement an interface. The interface is just a contract of methods the class must implement.

Is Constructor Overriding Possible?

Constructors are not normal methods and they cannot be "overridden". Saying that a constructor can be overridden would imply that a superclass constructor would be visible and could be called to create an instance of a subclass. This isn't true... a subclass doesn't have any constructors by default (except a no-arg constructor if the class it extends has one). It has to explicitly declare any other constructors, and those constructors belong to it and not to its superclass, even if they take the same parameters that the superclass constructors take.

The stuff you mention about default no arg constructors is just an aspect of how constructors work and has nothing to do with overriding.

C++ template constructor

You could do this:

class C 
{
public:
    template <typename T> C(T*);
};
template <typename T> T* UseType() 
{
    static_cast<T*>(nullptr);
}

Then to create an object of type C using int as the template parameter to the constructor:

C obj(UseType<int>());

Since you can't pass template parameters to a constructor, this solution essentially converts the template parameter to a regular parameter. Using the UseType<T>() function when calling the constructor makes it clear to someone looking at the code that the purpose of that parameter is to tell the constructor what type to use.

One use case for this would be if the constructor creates a derived class object and assigns it to a member variable that is a base class pointer. (The constructor needs to know which derived class to use, but the class itself doesn't need to be templated since the same base class pointer type is always used.)

difference between variables inside and outside of __init__()

This is very easy to understand if you track class and instance dictionaries.

class C:
   one = 42
   def __init__(self,val):
        self.two=val
ci=C(50)
print(ci.__dict__)
print(C.__dict__)

The result will be like this:

{'two': 50}
{'__module__': '__main__', 'one': 42, '__init__': <function C.__init__ at 0x00000213069BF6A8>, '__dict__': <attribute '__dict__' of 'C' objects>, '__weakref__': <attribute '__weakref__' of 'C' objects>, '__doc__': None}

Note I set the full results in here but what is important that the instance ci dict will be just {'two': 50}, and class dictionary will have the 'one': 42 key value pair inside.

This is all you should know about that specific variables.

Getting error: ISO C++ forbids declaration of with no type

You forgot the return types in your member function definitions:

int ttTree::ttTreeInsert(int value) { ... }
^^^               

and so on.

Why do we not have a virtual constructor in C++?

Virtual functions basically provide polymorphic behavior. That is, when you work with an object whose dynamic type is different than the static (compile time) type with which it is referred to, it provides behavior that is appropriate for the actual type of object instead of the static type of the object.

Now try to apply that sort of behavior to a constructor. When you construct an object the static type is always the same as the actual object type since:

To construct an object, a constructor needs the exact type of the object it is to create [...] Furthermore [...]you cannot have a pointer to a constructor

(Bjarne Stroustup (P424 The C++ Programming Language SE))

Can I call a constructor from another constructor (do constructor chaining) in C++?

C++11: Yes!

C++11 and onwards has this same feature (called delegating constructors).

The syntax is slightly different from C#:

class Foo {
public: 
  Foo(char x, int y) {}
  Foo(int y) : Foo('a', y) {}
};

C++03: No

Unfortunately, there's no way to do this in C++03, but there are two ways of simulating this:

  1. You can combine two (or more) constructors via default parameters:

    class Foo {
    public:
      Foo(char x, int y=0);  // combines two constructors (char) and (char, int)
      // ...
    };
    
  2. Use an init method to share common code:

    class Foo {
    public:
      Foo(char x);
      Foo(char x, int y);
      // ...
    private:
      void init(char x, int y);
    };
    
    Foo::Foo(char x)
    {
      init(x, int(x) + 7);
      // ...
    }
    
    Foo::Foo(char x, int y)
    {
      init(x, y);
      // ...
    }
    
    void Foo::init(char x, int y)
    {
      // ...
    }
    

See the C++FAQ entry for reference.

How to initialize HashSet values by construction?

Collection literals were scheduled for Java 7, but didn't make it in. So nothing automatic yet.

You can use guava's Sets:

Sets.newHashSet("a", "b", "c")

Or you can use the following syntax, which will create an anonymous class, but it's hacky:

Set<String> h = new HashSet<String>() {{
    add("a");
    add("b");
}};

Constructors in Go

There are some equivalents of constructors for when the zero values can't make sensible default values or for when some parameter is necessary for the struct initialization.

Supposing you have a struct like this :

type Thing struct {
    Name  string
    Num   int
}

then, if the zero values aren't fitting, you would typically construct an instance with a NewThing function returning a pointer :

func NewThing(someParameter string) *Thing {
    p := new(Thing)
    p.Name = someParameter
    p.Num = 33 // <- a very sensible default value
    return p
}

When your struct is simple enough, you can use this condensed construct :

func NewThing(someParameter string) *Thing {
    return &Thing{someParameter, 33}
}

If you don't want to return a pointer, then a practice is to call the function makeThing instead of NewThing :

func makeThing(name string) Thing {
    return Thing{name, 33}
}

Reference : Allocation with new in Effective Go.

How do I get a PHP class constructor to call its parent's parent's constructor?

class Grandpa 
{
    public function __construct()
    {}
}

class Papa extends Grandpa
{
    public function __construct()
    {
        //call Grandpa's constructor
        parent::__construct();
    }
}

class Kiddo extends Papa
{
    public function __construct()
    {
        //this is not a bug, it works that way in php
        Grandpa::__construct();
    }
}

Can constructors be async?

I'm not familiar with the async keyword (is this specific to Silverlight or a new feature in the beta version of Visual Studio?), but I think I can give you an idea of why you can't do this.

If I do:

var o = new MyObject();
MessageBox(o.SomeProperty.ToString());

o may not be done initializing before the next line of code runs. An instantiation of your object cannot be assigned until your constructor is completed, and making the constructor asynchronous wouldn't change that so what would be the point? However, you could call an asynchronous method from your constructor and then your constructor could complete and you would get your instantiation while the async method is still doing whatever it needs to do to setup your object.

Virtual member call in a constructor

Beware of blindly following Resharper's advice and making the class sealed! If it's a model in EF Code First it will remove the virtual keyword and that would disable lazy loading of it's relationships.

    public **virtual** User User{ get; set; }

ReactJS: Warning: setState(...): Cannot update during an existing state transition

From react docs Passing arguments to event handlers

<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>

Java constructor/method with optional parameters?

Why do you want to do that?

However, You can do this:

public void foo(int param1)
{
    int param2 = 2;
    // rest of code
}

or:

public void foo(int param1, int param2)
{
    // rest of code
}

public void foo(int param1)
{
    foo(param1, 2);
}

how to inherit Constructor from super class to sub class

Superclass constructor CAN'T be inherited in extended class. Although it can be invoked in extended class constructor's with super() as the first statement.

App not setup: This app is still in development mode

Issue Log: App Not Setup. This app is still in development mode. and you dont have access to it. register test user or ask an app admin for permission

  1. The app are not in Live Mode
  2. You are not listed as admin or a tester in
    https://developers.facebook.com/app/yourapp
  3. Your App Hashkey are not set. if Facebook app cant be on Live Mode you need a hashkey to test it. because the app are not yet Live. Facebook wont allow an access.

HOW TO CHANGE TO LIVE MODE
1. go to : https://developers.facebook.com
2. select your app on "My Apps" List
3. toggle the switch from OFF to ON

enter image description hereenter image description here

HOW TO ADD AS TEST OR ADMIN
1. go to : https://developers.facebook.com
2. select your app on "My Apps" List
3. go to : Roles > Roles > Press Add for example administratorenter image description here 4. Search your new admin/tester Facebook account.
enter image description here 5. admin must enter facebook password to confirm.then submit enter image description here
the new admin must go to developer.facebook page and accept the request
6. go to : https://developers.facebook.com

7. Profile > Requests > Confirm
enter image description here List item 8. Congratulation you have been assign as new Admin

HOW TO GET AND SET HASHKEY FOR DEVELOPMENT
as Refer to Facebook Login Documentation
https://developers.facebook.com/docs/android/getting-started/#create_hash
The most preferable solution by me is by code ( Troubleshooting Sample Apps )
it will print out the hash key. you can update it on
https://developers.facebook.com/apps/yourFacebookappID/settings/basic/
on Android > Key Hashes section

a step by step process on how to get the hashKey.

  1. Firstly Add the code to any oncreate method enter image description here

  2. Run The app and Search the KeyHash at Logcat enter image description here

step by step process on how Update on Facebook Developer.

  1. Open Facebook Developer Page. You need access as to update the Facebook Developer page.
    https://developers.facebook.com

  2. Follow the step as follow.enter image description here

How can I hide a checkbox in html?

if you want your check box to keep its height and width but only be invisible:

.hiddenCheckBox{
    visibility: hidden;
}

if you want your check box to be invisible without any with and height:

.hiddenCheckBox{
    display: none;
}

CSS position:fixed inside a positioned element

You can use the position:fixed;, but without set left and top. Then you will push it to the right using margin-left, to position it in the right position you wish.

Check a demo here: http://jsbin.com/icili5

window.open with target "_blank" in Chrome

"_blank" is not guaranteed to be a new tab or window. It's implemented differently per-browser.

You can, however, put anything into target. I usually just say "_tab", and every browser I know of just opens it in a new tab.

Be aware that it means it's a named target, so if you try to open 2 URLs, they will use the same tab.

How to list AD group membership for AD users using input list?

Or add "sort name" to list alphabetically

Get-ADPrincipalGroupMembership username | select name | sort name

How to import set of icons into Android Studio project


Edit : After Android Studios 1.5 android support Vector Asset Studio.


Follow this, which says:

To start Vector Asset Studio:

  1. In Android Studio, open an Android app project.
  2. In the Project window, select the Android view.
  3. Right-click the res folder and select New > Vector Asset.

enter image description here


Old Answer

Go to Settings > Plugin > Browse Repository > Search Android Drawable Import

This plugin consists of 4 main features.

  1. AndroidIcons Drawable Import
  2. Material Icons Drawable Import
  3. Scaled Drawable
  4. Multisource-Drawable

How to Use Material Icons Drawable Import : (Android Studio 1.2)

  • Go to File > Setting > Other Settings > Android Drawable Import

enter image description here

  • Download Material Icon and select your downloaded path.

enter image description here

  • Now right click on project , New > Material Icon Import

enter image description here

  • Use your favorite drawable in your project.

enter image description here

How do I get the resource id of an image if I know its name?

With something like this:

String mDrawableName = "myappicon";
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());

Using CMake with GNU Make: How can I see the exact commands?

When you run make, add VERBOSE=1 to see the full command output. For example:

cmake .
make VERBOSE=1

Or you can add -DCMAKE_VERBOSE_MAKEFILE:BOOL=ON to the cmake command for permanent verbose command output from the generated Makefiles.

cmake -DCMAKE_VERBOSE_MAKEFILE:BOOL=ON .
make

To reduce some possibly less-interesting output you might like to use the following options. The option CMAKE_RULE_MESSAGES=OFF removes lines like [ 33%] Building C object..., while --no-print-directory tells make to not print out the current directory filtering out lines like make[1]: Entering directory and make[1]: Leaving directory.

cmake -DCMAKE_RULE_MESSAGES:BOOL=OFF -DCMAKE_VERBOSE_MAKEFILE:BOOL=ON .
make --no-print-directory

Get data from php array - AJAX - jQuery

you cannot access array (php array) from js try

<?php
$array = array(1,2,3,4,5,6);
echo json_encode($array);
?>

and js

$(document).ready( function() {
    $('#prev').click(function() {
        $.ajax({
            type: 'POST',
            url: 'ajax.php',
            data: 'id=testdata',
            dataType: 'json',
            cache: false,
            success: function(result) {
                $('#content1').html(result[0]);
            },
        });
    });
});

Time comparison

You can use the compareTo() method from Java Date class

public int result = date.compareTo(Date anotherDate); 

Return Value: The function gives three return values specified below:

It returns the value 0 if the argument Date is equal to this Date. It returns a value less than 0 if this Date is before the Date argument. It returns a value greater than 0 if this Date is after the Date argument.

How to rotate a 3D object on axis three.js?

I needed the rotateAroundWorldAxis function but the above code doesn't work with the newest release (r52). It looks like getRotationFromMatrix() was replaced by setEulerFromRotationMatrix()

function rotateAroundWorldAxis( object, axis, radians ) {

    var rotationMatrix = new THREE.Matrix4();

    rotationMatrix.makeRotationAxis( axis.normalize(), radians );
    rotationMatrix.multiplySelf( object.matrix );                       // pre-multiply
    object.matrix = rotationMatrix;
    object.rotation.setEulerFromRotationMatrix( object.matrix );
}

How to set a tkinter window to a constant size

If you want a window as a whole to have a specific size, you can just give it the size you want with the geometry command. That's really all you need to do.

For example:

mw.geometry("500x500")

Though, you'll also want to make sure that the widgets inside the window resize properly, so change how you add the frame to this:

back.pack(fill="both", expand=True)

jQuery 'each' loop with JSON array

My solutions in one of my own sites, with a table:

$.getJSON("sections/view_numbers_update.php", function(data) {
 $.each(data, function(index, objNumber) {
  $('#tr_' + objNumber.intID).find("td").eq(3).html(objNumber.datLastCalled);
  $('#tr_' + objNumber.intID).find("td").eq(4).html(objNumber.strStatus);
  $('#tr_' + objNumber.intID).find("td").eq(5).html(objNumber.intDuration);
  $('#tr_' + objNumber.intID).find("td").eq(6).html(objNumber.blnWasHuman);
 });
});

sections/view_numbers_update.php Returns something like:

[{"intID":"19","datLastCalled":"Thu, 10 Jan 13 08:52:20 +0000","strStatus":"Completed","intDuration":"0:04 secs","blnWasHuman":"Yes","datModified":1357807940},
{"intID":"22","datLastCalled":"Thu, 10 Jan 13 08:54:43 +0000","strStatus":"Completed","intDuration":"0:00 secs","blnWasHuman":"Yes","datModified":1357808079}]

HTML table:

<table id="table_numbers">
 <tr>
  <th>[...]</th>
  <th>[...]</th>
  <th>[...]</th>
  <th>Last Call</th>
  <th>Status</th>
  <th>Duration</th>
  <th>Human?</th>
  <th>[...]</th>
 </tr>
 <tr id="tr_123456">
  [...]
 </tr>
</table>

This essentially gives every row a unique id preceding with 'tr_' to allow for other numbered element ids, at server script time. The jQuery script then just gets this TR_[id] element, and fills the correct indexed cell with the json return.

The advantage is you could get the complete array from the DB, and either foreach($array as $record) to create the table html, OR (if there is an update request) you can die(json_encode($array)) before displaying the table, all in the same page, but same display code.

jQuery.click() vs onClick

Using $('#myDiv').click(function(){ is better as it follows standard event registration model. (jQuery internally uses addEventListener and attachEvent).

Basically registering an event in modern way is the unobtrusive way of handling events. Also to register more than one event listener for the target you can call addEventListener() for the same target.

var myEl = document.getElementById('myelement');

myEl.addEventListener('click', function() {
    alert('Hello world');
}, false);

myEl.addEventListener('click', function() {
    alert('Hello world again!!!');
}, false);

http://jsfiddle.net/aj55x/1/

Why use addEventListener? (From MDN)

addEventListener is the way to register an event listener as specified in W3C DOM. Its benefits are as follows:

  • It allows adding more than a single handler for an event. This is particularly useful for DHTML libraries or Mozilla extensions that need to work well even if other libraries/extensions are used.
  • It gives you finer-grained control of the phase when the listener gets activated (capturing vs. bubbling)
  • It works on any DOM element, not just HTML elements.

More about Modern event registration -> http://www.quirksmode.org/js/events_advanced.html

Other methods such as setting the HTML attributes, example:

<button onclick="alert('Hello world!')">

Or DOM element properties, example:

myEl.onclick = function(event){alert('Hello world');}; 

are old and they can be over written easily.

HTML attribute should be avoided as It makes the markup bigger and less readable. Concerns of content/structure and behavior are not well-separated, making a bug harder to find.

The problem with the DOM element properties method is that only one event handler can be bound to an element per event.

More about Traditional event handling -> http://www.quirksmode.org/js/events_tradmod.html

MDN Reference: https://developer.mozilla.org/en-US/docs/DOM/event

Simulate low network connectivity for Android

You are also able to test slow internet connectivity on an real android device:

Tested with Samsung Galaxy S8 + Android 8.0.0

Go to Settings -> Connection -> Mobile Network -> and under networkmode you can choose to only use 2G or 3G connections

What exactly is an instance in Java?

Objects, which are also called instances, are self-contained elements of a program with related features and data. For the most part, you use the class merely to create instances and then work with those instances.

-Definition taken from the book "Sams Teach Yourself Java in 21 days".

Say you have 2 Classes, public class MainClass and public class Class_2 and you want to make an instance of Class_2 in MainClass.

This is a very simple and basic way to do it:

public MainClass()      /*******this is the constructor of MainClass*******/

{

 Class_2 nameyouwant = new Class_2();

}

I hope this helps!

Test whether string is a valid integer

[[ $var =~ ^-?[0-9]+$ ]]
  • The ^ indicates the beginning of the input pattern
  • The - is a literal "-"
  • The ? means "0 or 1 of the preceding (-)"
  • The + means "1 or more of the preceding ([0-9])"
  • The $ indicates the end of the input pattern

So the regex matches an optional - (for the case of negative numbers), followed by one or more decimal digits.

References:

iOS Detection of Screenshot?

Looks like there are no direct way to do this to detect if user has tapped on home + power button. As per this, it was possible earlier by using darwin notification, but it doesn't work any more. Since snapchat is already doing it, my guess is that they are checking the iPhone photo album to detect if there is a new picture got added in between this 10 seconds, and in someway they are comparing with the current image displayed. May be some image processing is done for this comparison. Just a thought, probably you can try to expand this to make it work. Check this for more details.

Edit:

Looks like they might be detecting the UITouch cancel event(Screen capture cancels touches) and showing this error message to the user as per this blog: How to detect screenshots on iOS (like SnapChat)

In that case you can use – touchesCancelled:withEvent: method to sense the UITouch cancellation to detect this. You can remove the image in this delegate method and show an appropriate alert to the user.

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesCancelled:touches withEvent:event];

    NSLog(@"Touches cancelled");

    [self.imageView removeFromSuperView]; //and show an alert to the user
}

TypeError: string indices must be integers, not str // working with dict

Actually I think that more general approach to loop through dictionary is to use iteritems():

# get tuples of term, courses
for term, term_courses in courses.iteritems():
    # get tuples of course number, info
    for course, info in term_courses.iteritems():
        # loop through info
        for k, v in info.iteritems():
            print k, v

output:

assistant Peter C.
prereq cs101
...
name Programming a Robotic Car
teacher Sebastian

Or, as Matthias mentioned in comments, if you don't need keys, you can just use itervalues():

for term_courses in courses.itervalues():
    for info in term_courses.itervalues():
        for k, v in info.iteritems():
            print k, v

How to stop mysqld

Kill is definitly the wrong way! The PID will stay, Replicationsjobs will be killed etc. etc.

STOP MySQL Server

/sbin/service mysql stop

START MySQL Server

/sbin/service mysql start

RESTART MySQL Server

/sbin/service mysql restart

Perhaps sudo will be needed if you have not enough rights

How can I add an element after another element?

try

.insertAfter()

here

$(content).insertAfter('#bla');

jQuery - Redirect with post data

There is a JQuery plug-in that accomplishes pretty much what you're trying to do: https://github.com/mgalante/jquery.redirect/blob/master/jquery.redirect.js.

After including JQuery and the jquery.redirect.min.js plug-in, you can simply do something like this:

$().redirect('demo.php', {'arg1': 'value1', 'arg2': 'value2'});

Use the following code on newer JQuery versions instead:

$.redirect('demo.php', {'arg1': 'value1', 'arg2': 'value2'});

Hope this helps!

How to get current timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"

You can use the following

new java.sql.Timestamp(System.currentTimeMillis()).getTime()

Result : 1539594988651

Hope this will help. Just my suggestion and not for reward points.

Replace multiple strings at once

The top answer is equivalent to doing:

let text = find.reduce((acc, item, i) => {
  const regex = new RegExp(item, "g");
  return acc.replace(regex, replace[i]);
}, textarea);

Given this:

var textarea = $(this).val();
var find = ["<", ">", "\n"];
var replace = ["&lt;", "&gt;", "<br/>"];

In this case, no imperative programming is going on.

Convert String to int array in java

try this one, it might be helpful for you

String arr= "[1,2]";
int[] arr=Stream.of(str.replaceAll("[\\[\\]\\, ]", "").split("")).mapToInt(Integer::parseInt).toArray();

How do I keep track of pip-installed packages in an Anaconda (Conda) environment?

You can start by installing the below given command in the conda environment:

conda install pip

Followed by installing all pip packages you need in the environment.

After installing all the conda and pip packages to export the environment use:

conda env export -n <env-name> > environment.yml

This will create the required file in the folder

Angular and Typescript: Can't find names - Error: cannot find name

add typing.d.ts in main folder of the application and over there declare the varible which you want to use every time

declare var System: any;
declare var require: any;

after declaring this in typing.d.ts, error for require will not come in the application..

How to use PHP to connect to sql server

for further investigation: print out the mssql error message:

$dbhandle = mssql_connect($myServer, $myUser, $myPass) or die("Could not connect to database: ".mssql_get_last_message()); 

It is also important to specify the port: On MS SQL Server 2000, separate it with a comma:

$myServer = "10.85.80.229:1443";

or

$myServer = "10.85.80.229,1443";

How to download a file using a Java REST service and a data stream

Refer this:

@RequestMapping(value="download", method=RequestMethod.GET)
public void getDownload(HttpServletResponse response) {

// Get your file stream from wherever.
InputStream myStream = someClass.returnFile();

// Set the content type and attachment header.
response.addHeader("Content-disposition", "attachment;filename=myfilename.txt");
response.setContentType("txt/plain");

// Copy the stream to the response's output stream.
IOUtils.copy(myStream, response.getOutputStream());
response.flushBuffer();
}

Details at: https://twilblog.github.io/java/spring/rest/file/stream/2015/08/14/return-a-file-stream-from-spring-rest.html

AttributeError: 'str' object has no attribute

The problem is in your playerMovement method. You are creating the string name of your room variables (ID1, ID2, ID3):

letsago = "ID" + str(self.dirDesc.values())

However, what you create is just a str. It is not the variable. Plus, I do not think it is doing what you think its doing:

>>>str({'a':1}.values())
'dict_values([1])'

If you REALLY needed to find the variable this way, you could use the eval function:

>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'

or the globals function:

class Foo(object):
    def __init__(self):
        super(Foo, self).__init__()
    def test(self, name):
        print(globals()[name])

foo = Foo()
bar = 'Hello World!'
foo.text('bar')

However, instead I would strongly recommend you rethink you class(es). Your userInterface class is essentially a Room. It shouldn't handle player movement. This should be within another class, maybe GameManager or something like that.

Warning: Failed propType: Invalid prop `component` supplied to `Route`

Standardize your module's imports and exports then you won't risk hitting problems with misspelled property names.

module.exports = Component should become export default Component.

CommonJS uses module.exports as a convention, however, this means that you are just working with a regular Javascript object and you are able to set the value of any key you want (whether that's exports, exoprts or exprots). There are no runtime or compile-time checks to tell you that you've messed up.

If you use ES6 (ES2015) syntax instead, then you are working with syntax and keywords. If you accidentally type exoprt default Component then it will give you a compile error to let you know.

In your case, you can simplify the Speaker component.

import React from 'react';

export default React.createClass({
  render() {
    return (
      <h1>Speaker</h1>
    )
  }
});

Remove Unnamed columns in pandas dataframe

The approved solution doesn't work in my case, so my solution is the following one:

    ''' The column name in the example case is "Unnamed: 7"
 but it works with any other name ("Unnamed: 0" for example). '''

        df.rename({"Unnamed: 7":"a"}, axis="columns", inplace=True)

        # Then, drop the column as usual.

        df.drop(["a"], axis=1, inplace=True)

Hope it helps others.

How to force addition instead of concatenation in javascript

Your code concatenates three strings, then converts the result to a number.

You need to convert each variable to a number by calling parseFloat() around each one.

total = parseFloat(myInt1) + parseFloat(myInt2) + parseFloat(myInt3);

Change the maximum upload file size

I had the same problem. I have tried three ways that were usually suggested:

  1. functions.php
  2. php.ini
  3. .htaccess

none if which solved my problem. I am using godaddy and came across a suggested solution which was:

  1. got to Web Hosting, then Manage
  2. Under Software select Select PHP version
  3. Select Switch to PHP Options found on the top right corner of the table in font color: blue
  4. On the bottom most part, you'll probably have upload_max_filesize = 2M
  5. Now, feel free to change it
  6. Be sure to click the Save button!
  7. Now go to your wp-admin panel, select Media then Add

Voila! Now you have a different max upload file size :)

HTML table with fixed headers?

A lot of people seem to be looking for this answer. I found it buried in an answer to another question here: Syncing column width of between tables in two different frames, etc

Of the dozens of methods I have tried this is the only method I found that works reliably to allow you to have a scrolling bottom table with the header table having the same widths.

Here is how I did it, first I improved upon the jsfiddle above to create this function, which works on both td and th (in case that trips up others who use th for styling of their header rows).

var setHeaderTableWidth= function (headertableid,basetableid) {
            $("#"+headertableid).width($("#"+basetableid).width());
            $("#"+headertableid+" tr th").each(function (i) {
                $(this).width($($("#"+basetableid+" tr:first td")[i]).width());
            });
            $("#" + headertableid + " tr td").each(function (i) {
                $(this).width($($("#" + basetableid + " tr:first td")[i]).width());
            });
        }

Next, you need to create two tables, NOTE the header table should have an extra TD to leave room in the top table for the scrollbar, like this:

 <table id="headertable1" class="input-cells table-striped">
        <thead>
            <tr style="background-color:darkgray;color:white;"><th>header1</th><th>header2</th><th>header3</th><th>header4</th><th>header5</th><th>header6</th><th></th></tr>
        </thead>
     </table>
    <div id="resizeToBottom" style="overflow-y:scroll;overflow-x:hidden;">
        <table id="basetable1" class="input-cells table-striped">
            <tbody >
                <tr>
                    <td>testdata</td>
                    <td>2</td>
                    <td>3</td>
                    <td>4</span></td>
                    <td>55555555555555</td>
                    <td>test</td></tr>
            </tbody>
        </table>
    </div>

Then do something like:

        setHeaderTableWidth('headertable1', 'basetable1');
        $(window).resize(function () {
            setHeaderTableWidth('headertable1', 'basetable1');
        });

This is the only solution that I found on Stack Overflow that works out of many similar questions that have been posted, that works in all my cases.

For example, I tried the jQuery stickytables plugin which does not work with durandal, and the Google Code project here https://code.google.com/p/js-scroll-table-header/issues/detail?id=2

Other solutions involving cloning the tables, have poor performance, or suck and don't work in all cases.

There is no need for these overly complex solutions. Just make two tables like the examples below and call setHeaderTableWidth function like described here and boom, you are done.

If this does not work for you, you probably were playing with your CSS box-sizing property and you need to set it correctly. It is easy to screw up your CSS content by accident. There are many things that can go wrong, so just be aware/careful of that. This approach works for me.

MongoDB: update every document on one field

This code will be helpful for you

        Model.update({
            'type': "newuser"
        }, {
            $set: {
                email: "[email protected]",
                phoneNumber:"0123456789"
            }
        }, {
            multi: true
        },
        function(err, result) {
            console.log(result);
            console.log(err);
        })  

Can we cast a generic object to a custom object type in javascript?

This borrows from a few other answers here but I thought it might help someone. If you define the following function on your custom object, then you have a factory function that you can pass a generic object into and it will return for you an instance of the class.

CustomObject.create = function (obj) {
    var field = new CustomObject();
    for (var prop in obj) {
        if (field.hasOwnProperty(prop)) {
            field[prop] = obj[prop];
        }
    }

    return field;
}

Use like this

var typedObj = CustomObject.create(genericObj);

Dialog with transparent background in Android

dialog.getWindow().setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(ctx, android.R.color.transparent)));

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

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

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

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

How to get all count of mongoose model?

You should give an object as argument

userModel.count({name: "sam"});

or

userModel.count({name: "sam"}).exec(); //if you are using promise

or

userModel.count({}); // if you want to get all counts irrespective of the fields

On the recent version of mongoose, count() is deprecated so use

userModel.countDocuments({name: "sam"});

Convert string to hex-string in C#

According to this snippet here, this approach should be good for long strings:

private string StringToHex(string hexstring)
{
    StringBuilder sb = new StringBuilder();
    foreach (char t in hexstring)
    { 
        //Note: X for upper, x for lower case letters
        sb.Append(Convert.ToInt32(t).ToString("x")); 
    }
    return sb.ToString();
}

usage:

string result = StringToHex("Hello world"); //returns "48656c6c6f20776f726c64"

Another approach in one line

string input = "Hello world";
string result = String.Concat(input.Select(x => ((int)x).ToString("x")));

Get Hard disk serial Number

There is a simple way for @Sprunth's answer.

private void GetAllDiskDrives()
    {
        var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");

        foreach (ManagementObject wmi_HD in searcher.Get())
        {
            HardDrive hd = new HardDrive();
            hd.Model = wmi_HD["Model"].ToString();
            hd.InterfaceType = wmi_HD["InterfaceType"].ToString();
            hd.Caption = wmi_HD["Caption"].ToString();

            hd.SerialNo =wmi_HD.GetPropertyValue("SerialNumber").ToString();//get the serailNumber of diskdrive

            hdCollection.Add(hd);
        }

 }


public class HardDrive
{
    public string Model { get; set; }
    public string InterfaceType { get; set; }
    public string Caption { get; set; }
    public string SerialNo { get; set; }
}

How do you get current active/default Environment profile programmatically in Spring?

And if you neither want to use @Autowire nor injecting @Value you can simply do (with fallback included):

System.getProperty("spring.profiles.active", "unknown");

This will return any active profile (or fallback to 'unknown').

How to put a jpg or png image into a button in HTML

This may work for you, try it and see if it works:

<input type="image" src="/library/graphics/cecb2.gif">

calling server side event from html button control

just use this at the end of your button click event

protected void btnAddButton_Click(object sender, EventArgs e)
{
   ... save data routin 
     Response.Redirect(Request.Url.AbsoluteUri);
}

How to query a MS-Access Table from MS-Excel (2010) using VBA

The Provider piece must be Provider=Microsoft.ACE.OLEDB.12.0 if your target database is ACCDB format. Provider=Microsoft.Jet.OLEDB.4.0 only works for the older MDB format.

You shouldn't even need Access installed if you're running 32 bit Windows. Jet 4 is included as part of the operating system. If you're using 64 bit Windows, Jet 4 is not included, but you still wouldn't need Access itself installed. You can install the Microsoft Access Database Engine 2010 Redistributable. Make sure to download the matching version (AccessDatabaseEngine.exe for 32 bit Windows, or AccessDatabaseEngine_x64.exe for 64 bit).

You can avoid the issue about which ADO version reference by using late binding, which doesn't require any reference.

Dim conn As Object
Set conn = CreateObject("ADODB.Connection")

Then assign your ConnectionString property to the conn object. Here is a quick example which runs from a code module in Excel 2003 and displays a message box with the row count for MyTable. It uses late binding for the ADO connection and recordset objects, so doesn't require setting a reference.

Public Sub foo()
    Dim cn As Object
    Dim rs As Object
    Dim strSql As String
    Dim strConnection As String
    Set cn = CreateObject("ADODB.Connection")
    strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
        "Data Source=C:\Access\webforums\whiteboard2003.mdb"
    strSql = "SELECT Count(*) FROM MyTable;"
    cn.Open strConnection
    Set rs = cn.Execute(strSql)
    MsgBox rs.fields(0) & " rows in MyTable"
    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing
End Sub

If this answer doesn't resolve the problem, edit your question to show us the full connection string you're trying to use and the exact error message you get in response for that connection string.

How to compare timestamp dates with date-only parameter in MySQL?

 WHERE cast(timestamp as date) = '2012-05-05'

How to create a foreign key in phpmyadmin

To be able to create a relation, the table Storage Engine must be InnoDB. You can edit in Operations tab. Storage Engine Configuration

Then, you need to be sure that the id column in your main table has been indexed. It should appear at Index section in Structure tab.

Index list

Finally, you could see the option Relations View in Structure tab. When edditing, you will be able to select the parent column in foreign table to create the relation.

enter image description here

See attachments. I hope this could be useful for anyone.

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

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

Consider the following code:

/* WARNING: demonstration of bad coding technique!! */

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

FILE *Fopen(const char *path, const char *mode);

int main(int argc, char **argv)
{
    FILE *in;
    unsigned count;

    in = argc > 1 ? Fopen(argv[1], "r") : stdin;
    count = 0;

    /* WARNING: this is a bug */
    while( !feof(in) ) {  /* This is WRONG! */
        fgetc(in);
        count++;
    }
    printf("Number of characters read: %u\n", count);
    return EXIT_SUCCESS;
}

FILE * Fopen(const char *path, const char *mode)
{
    FILE *f = fopen(path, mode);
    if( f == NULL ) {
        perror(path);
        exit(EXIT_FAILURE);
    }
    return f;
}

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

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

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

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

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

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

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

gulp command not found - error after installing gulp

In my case, none of the approaches listed worked. I finally downloaded Rapid Environment Editor (ver 8).

It showed that my additions to the user environment variables weren't present. When I added them with REE, everything worked immediately.

(Running Windows 8.1)

How to access the SMS storage on Android?

Do the following, download SQLLite Database Browser from here:

Locate your db. file in your phone.

Then, as soon you install the program go to: "Browse Data", you will see all the SMS there!!

You can actually export the data to an excel file or SQL.

FileNotFoundException while getting the InputStream object from HttpURLConnection

To anyone with this problem in the future, the reason is because the status code was a 404 (or in my case was a 500). It appears the InpuStream function will throw an error when the status code is not 200.

In my case I control my own server and was returning a 500 status code to indicate an error occurred. Despite me also sending a body with a string message detailing the error, the inputstream threw an error regardless of the body being completely readable.

If you control your server I suppose this can be handled by sending yourself a 200 status code and then handling whatever the string error response was.

Regex - how to match everything except a particular pattern

The complement of a regular language is also a regular language, but to construct it you have to build the DFA for the regular language, and make any valid state change into an error. See this for an example. What the page doesn't say is that it converted /(ac|bd)/ into /(a[^c]?|b[^d]?|[^ab])/. The conversion from a DFA back to a regular expression is not trivial. It is easier if you can use the regular expression unchanged and change the semantics in code, like suggested before.

Unpacking a list / tuple of pairs into two lists / tuples

list1 = (x[0] for x in source_list)
list2 = (x[1] for x in source_list)

How to get rid of the "No bootable medium found!" error in Virtual Box?

Try this:

Go to virtual box > right click the OS > settings > under one of the many tab that I don't remember(sorry for this, i dont have vbox installed)> locate the VDI (virtual box disk image) file..

and save the settings.. then try to start the OS..

C# equivalent to Java's charAt()?

You can index into a string in C# like an array, and you get the character at that index.

Example:

In Java, you would say

str.charAt(8);

In C#, you would say

str[8];

Difference between using bean id and name in Spring configuration file

Is there difference in defining Id & name in ApplicationContext xml ? No As of 3.1(spring), id is also defined as an xsd:string type. It means whatever characters allowed in defining name are also allowed in Id. This was not possible prior to Spring 3.1.

Why to use name when it is same as Id ? It is useful for some situations, such as allowing each component in an application to refer to a common dependency by using a bean name that is specific to that component itself.

For example, the configuration metadata for subsystem A may refer to a DataSource via the name subsystemA-dataSource. The configuration metadata for subsystem B may refer to a DataSource via the name subsystemB-dataSource. When composing the main application that uses both these subsystems the main application refers to the DataSource via the name myApp-dataSource. To have all three names refer to the same object you add to the MyApp configuration metadata the following 

<bean id="myApp-dataSource" name="subsystemA-dataSource,subsystemB-dataSource" ..../>

Alternatively, You can have separate xml configuration files for each sub-system and then you can make use of
alias to define your own names.

<alias name="subsystemA-dataSource" alias="subsystemB-dataSource"/>
<alias name="subsystemA-dataSource" alias="myApp-dataSource" />

How to display the string html contents into webbrowser control?

The DisplayHtml(string html) recommended by m3z worked for me.

In case it helps somebody, I would also like to mention that initially there were some spaces in my HTML that invalidated the HTML and so the text appeared as a string. The spaces were introduced (around the angular brackets) when I pasted the HTML into Visual Studio. So if your text is still appearing as text after you try the solutions mentioned in this post, then it may be worth checking that the HTML syntax is correct.

Script not served by static file handler on IIS7.5

Just another possible solution I found having the same error message.

When trying to setup a .NET 4.0 web application to a new applicition pool I was receiving this strange error telling me it was trying to process my aspx file with the static file handler, which didn't make sense.

For some reason the ISAPI for .NET 4.0 was set to disabled in the ISAPI and CGI Restrictions area of the server level in the IIS manager. Setting it to enabled was all that was required, however the IIS 7.5 manager is so convoluted and hard to follow it took me a long time to figure this out.

I'm guessing that since it was a 4.0 Application that could not be processed by the 4.0 Engine the static file handler was being used by default.

How to change ReactJS styles dynamically?

Ok, finally found the solution.

Probably due to lack of experience with ReactJS and web development...

    var Task = React.createClass({
    render: function() {
      var percentage = this.props.children + '%';
      ....
        <div className="ui-progressbar-value ui-widget-header ui-corner-left" style={{width : percentage}}/>
      ...

I created the percentage variable outside in the render function.

Decimal precision and scale in EF Code First

Entity Framework Ver 6 (Alpha, rc1) has something called Custom Conventions. To set decimal precision:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Properties<decimal>().Configure(config => config.HasPrecision(18, 4));
}

Reference:

error: unknown type name ‘bool’

C99 does, if you have

#include <stdbool.h> 

If the compiler does not support C99, you can define it yourself:

// file : myboolean.h
#ifndef MYBOOLEAN_H
#define MYBOOLEAN_H

#define false 0
#define true 1
typedef int bool; // or #define bool int

#endif

(but note that this definition changes ABI for bool type so linking against external libraries which were compiled with properly defined bool may cause hard-to-diagnose runtime errors).

How to debug Spring Boot application with Eclipse?

Please see http://java.dzone.com/articles/how-debug-remote-java-applicat to enable the remote debugging. If you are using tomcat to run your application, start tomcat with remote debug parameters or you can start tomcat with JPDA support by using following command.

Windows

<tomcat bin dir>/startup.bat jpda

*nix

<tomcat bin dir>/startup.sh jpda

this will enable remote debugging on port 8000

How can I get the order ID in WooCommerce?

$order = new WC_Order( $post_id ); 

If you

echo $order->id;

then you'll be returned the id of the post from which the order is made. As you've already got that, it's probably not what you want.

echo $order->get_order_number();

will return the id of the order (with a # in front of it). To get rid of the #,

echo trim( str_replace( '#', '', $order->get_order_number() ) );

as per the accepted answer.

center MessageBox in parent form

But why stop with MessageBox-specific implementation? Use the class below like this:

    private void OnFormClosing(object sender, FormClosingEventArgs e)
    {
        DialogResult dg;
        using (DialogCenteringService centeringService = new DialogCenteringService(this)) // center message box
        {
            dg = MessageBox.Show(this, "Are you sure?", "Confirm exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
        }

        if (dg == DialogResult.No)
        {
            e.Cancel = true;
        }
    }

The code that you can use with anything that shows dialog windows, even if they're owned by another thread (our app has multiple UI threads):

(Here is the updated code which takes monitor working areas into account, so that the dialog isn't centered between two monitors or is partly off-screen. With it you'll need enum SetWindowPosFlags, which is below)

public class DialogCenteringService : IDisposable
{
    private readonly IWin32Window owner;
    private readonly HookProc hookProc;
    private readonly IntPtr hHook = IntPtr.Zero;

    public DialogCenteringService(IWin32Window owner)
    {
        if (owner == null) throw new ArgumentNullException("owner");

        this.owner = owner;
        hookProc = DialogHookProc;

        hHook = SetWindowsHookEx(WH_CALLWNDPROCRET, hookProc, IntPtr.Zero, GetCurrentThreadId());
    }

    private IntPtr DialogHookProc(int nCode, IntPtr wParam, IntPtr lParam)
    {
        if (nCode < 0)
        {
            return CallNextHookEx(hHook, nCode, wParam, lParam);
        }

        CWPRETSTRUCT msg = (CWPRETSTRUCT)Marshal.PtrToStructure(lParam, typeof(CWPRETSTRUCT));
        IntPtr hook = hHook;

        if (msg.message == (int)CbtHookAction.HCBT_ACTIVATE)
        {
            try
            {
                CenterWindow(msg.hwnd);
            }
            finally
            {
                UnhookWindowsHookEx(hHook);
            }
        }

        return CallNextHookEx(hook, nCode, wParam, lParam);
    }

    public void Dispose()
    {
        UnhookWindowsHookEx(hHook);
    }

    private void CenterWindow(IntPtr hChildWnd)
    {
        Rectangle recChild = new Rectangle(0, 0, 0, 0);
        bool success = GetWindowRect(hChildWnd, ref recChild);

        if (!success)
        {
            return;
        }

        int width = recChild.Width - recChild.X;
        int height = recChild.Height - recChild.Y;

        Rectangle recParent = new Rectangle(0, 0, 0, 0);
        success = GetWindowRect(owner.Handle, ref recParent);

        if (!success)
        {
            return;
        }

        Point ptCenter = new Point(0, 0);
        ptCenter.X = recParent.X + ((recParent.Width - recParent.X) / 2);
        ptCenter.Y = recParent.Y + ((recParent.Height - recParent.Y) / 2);


        Point ptStart = new Point(0, 0);
        ptStart.X = (ptCenter.X - (width / 2));
        ptStart.Y = (ptCenter.Y - (height / 2));

        //MoveWindow(hChildWnd, ptStart.X, ptStart.Y, width, height, false);
        Task.Factory.StartNew(() => SetWindowPos(hChildWnd, (IntPtr)0, ptStart.X, ptStart.Y, width, height, SetWindowPosFlags.SWP_ASYNCWINDOWPOS | SetWindowPosFlags.SWP_NOSIZE | SetWindowPosFlags.SWP_NOACTIVATE | SetWindowPosFlags.SWP_NOOWNERZORDER | SetWindowPosFlags.SWP_NOZORDER));
    }

    // some p/invoke

    // ReSharper disable InconsistentNaming
    public delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);

    public delegate void TimerProc(IntPtr hWnd, uint uMsg, UIntPtr nIDEvent, uint dwTime);

    private const int WH_CALLWNDPROCRET = 12;

    // ReSharper disable EnumUnderlyingTypeIsInt
    private enum CbtHookAction : int
    // ReSharper restore EnumUnderlyingTypeIsInt
    {
        // ReSharper disable UnusedMember.Local
        HCBT_MOVESIZE = 0,
        HCBT_MINMAX = 1,
        HCBT_QS = 2,
        HCBT_CREATEWND = 3,
        HCBT_DESTROYWND = 4,
        HCBT_ACTIVATE = 5,
        HCBT_CLICKSKIPPED = 6,
        HCBT_KEYSKIPPED = 7,
        HCBT_SYSCOMMAND = 8,
        HCBT_SETFOCUS = 9
        // ReSharper restore UnusedMember.Local
    }

    [DllImport("kernel32.dll")]
    static extern int GetCurrentThreadId();

    [DllImport("user32.dll")]
    private static extern bool GetWindowRect(IntPtr hWnd, ref Rectangle lpRect);

    [DllImport("user32.dll")]
    private static extern int MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, SetWindowPosFlags uFlags);

    [DllImport("User32.dll")]
    public static extern UIntPtr SetTimer(IntPtr hWnd, UIntPtr nIDEvent, uint uElapse, TimerProc lpTimerFunc);

    [DllImport("User32.dll")]
    public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);

    [DllImport("user32.dll")]
    public static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);

    [DllImport("user32.dll")]
    public static extern int UnhookWindowsHookEx(IntPtr idHook);

    [DllImport("user32.dll")]
    public static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, IntPtr wParam, IntPtr lParam);

    [DllImport("user32.dll")]
    public static extern int GetWindowTextLength(IntPtr hWnd);

    [DllImport("user32.dll")]
    public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int maxLength);

    [DllImport("user32.dll")]
    public static extern int EndDialog(IntPtr hDlg, IntPtr nResult);

    [StructLayout(LayoutKind.Sequential)]
    public struct CWPRETSTRUCT
    {
        public IntPtr lResult;
        public IntPtr lParam;
        public IntPtr wParam;
        public uint message;
        public IntPtr hwnd;
    };
    // ReSharper restore InconsistentNaming
}

[Flags]
public enum SetWindowPosFlags : uint
{
    // ReSharper disable InconsistentNaming

    /// <summary>
    ///     If the calling thread and the thread that owns the window are attached to different input queues, the system posts the request to the thread that owns the window. This prevents the calling thread from blocking its execution while other threads process the request.
    /// </summary>
    SWP_ASYNCWINDOWPOS = 0x4000,

    /// <summary>
    ///     Prevents generation of the WM_SYNCPAINT message.
    /// </summary>
    SWP_DEFERERASE = 0x2000,

    /// <summary>
    ///     Draws a frame (defined in the window's class description) around the window.
    /// </summary>
    SWP_DRAWFRAME = 0x0020,

    /// <summary>
    ///     Applies new frame styles set using the SetWindowLong function. Sends a WM_NCCALCSIZE message to the window, even if the window's size is not being changed. If this flag is not specified, WM_NCCALCSIZE is sent only when the window's size is being changed.
    /// </summary>
    SWP_FRAMECHANGED = 0x0020,

    /// <summary>
    ///     Hides the window.
    /// </summary>
    SWP_HIDEWINDOW = 0x0080,

    /// <summary>
    ///     Does not activate the window. If this flag is not set, the window is activated and moved to the top of either the topmost or non-topmost group (depending on the setting of the hWndInsertAfter parameter).
    /// </summary>
    SWP_NOACTIVATE = 0x0010,

    /// <summary>
    ///     Discards the entire contents of the client area. If this flag is not specified, the valid contents of the client area are saved and copied back into the client area after the window is sized or repositioned.
    /// </summary>
    SWP_NOCOPYBITS = 0x0100,

    /// <summary>
    ///     Retains the current position (ignores X and Y parameters).
    /// </summary>
    SWP_NOMOVE = 0x0002,

    /// <summary>
    ///     Does not change the owner window's position in the Z order.
    /// </summary>
    SWP_NOOWNERZORDER = 0x0200,

    /// <summary>
    ///     Does not redraw changes. If this flag is set, no repainting of any kind occurs. This applies to the client area, the nonclient area (including the title bar and scroll bars), and any part of the parent window uncovered as a result of the window being moved. When this flag is set, the application must explicitly invalidate or redraw any parts of the window and parent window that need redrawing.
    /// </summary>
    SWP_NOREDRAW = 0x0008,

    /// <summary>
    ///     Same as the SWP_NOOWNERZORDER flag.
    /// </summary>
    SWP_NOREPOSITION = 0x0200,

    /// <summary>
    ///     Prevents the window from receiving the WM_WINDOWPOSCHANGING message.
    /// </summary>
    SWP_NOSENDCHANGING = 0x0400,

    /// <summary>
    ///     Retains the current size (ignores the cx and cy parameters).
    /// </summary>
    SWP_NOSIZE = 0x0001,

    /// <summary>
    ///     Retains the current Z order (ignores the hWndInsertAfter parameter).
    /// </summary>
    SWP_NOZORDER = 0x0004,

    /// <summary>
    ///     Displays the window.
    /// </summary>
    SWP_SHOWWINDOW = 0x0040,

    // ReSharper restore InconsistentNaming
}

org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

If you are using this line:

sessionFactory.getHibernateProperties().put("hibernate.dialect", env.getProperty("hibernate.dialect"));

make sure that env.getProperty("hibernate.dialect") is not null.

get the latest fragment in backstack

You can use the getName() method of FragmentManager.BackStackEntry which was introduced in API level 14. This method will return a tag which was the one you used when you added the Fragment to the backstack with addTobackStack(tag).

int index = getActivity().getFragmentManager().getBackStackEntryCount() - 1
FragmentManager.BackStackEntry backEntry = getFragmentManager().getBackStackEntryAt(index);
String tag = backEntry.getName();
Fragment fragment = getFragmentManager().findFragmentByTag(tag);

You need to make sure that you added the fragment to the backstack like this:

fragmentTransaction.addToBackStack(tag);

Call js-function using JQuery timer

Might want to check out jQuery Timer to manage one or multiple timers.

http://code.google.com/p/jquery-timer/

var timer = $.timer(yourfunction, 10000);

function yourfunction() { alert('test'); }

Then you can control it with:

timer.play();
timer.pause();
timer.toggle();
timer.once();
etc...

Dynamically Add Images React Webpack

UPDATE: this only tested with server side rendering ( universal Javascript ) here is my boilerplate.

With only file-loader you can load images dynamically - the trick is to use ES6 template strings so that Webpack can pick it up:

This will NOT work. :

const myImg = './cute.jpg'
<img src={require(myImg)} />

To fix this, just use template strings instead :

const myImg = './cute.jpg'
<img src={require(`${myImg}`)} />

webpack.config.js :

var HtmlWebpackPlugin =  require('html-webpack-plugin')
var ExtractTextWebpackPlugin = require('extract-text-webpack-plugin')

module.exports = {
  entry : './src/app.js',
  output : {
    path : './dist',
    filename : 'app.bundle.js'
  },
  plugins : [
  new ExtractTextWebpackPlugin('app.bundle.css')],
  module : {
    rules : [{
      test : /\.css$/,
      use : ExtractTextWebpackPlugin.extract({
        fallback : 'style-loader',
        use: 'css-loader'
      })
    },{
      test: /\.js$/,
      exclude: /(node_modules)/,
      loader: 'babel-loader',
      query: {
        presets: ['react','es2015']
      }
    },{
      test : /\.jpg$/,
      exclude: /(node_modules)/,
      loader : 'file-loader'
    }]
  }
}

Detect element content changes with jQuery

I know this post is a year old, but I'd like to provide a different solution approach to those who have a similar issue:

  1. The jQuery change event is used only on user input fields because if anything else is manipulated (e.g., a div), that manipulation is coming from code. So, find where the manipulation occurs, and then add whatever you need to there.

  2. But if that's not possible for any reason (you're using a complicated plugin or can't find any "callback" possibilities) then the jQuery approach I'd suggest is:

    a. For simple DOM manipulation, use jQuery chaining and traversing, $("#content").html('something').end().find(whatever)....

    b. If you'd like to do something else, employ jQuery's bind with custom event and triggerHandler

    $("#content").html('something').triggerHandler('customAction');
    
    $('#content').unbind().bind('customAction', function(event, data) {
       //Custom-action
    });
    

Here's a link to jQuery trigger handler: http://api.jquery.com/triggerHandler/

Node Version Manager install - nvm command not found

Add the following lines to the files ~/.bashrc and ~/.bash_profile :

# NVM changes
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"

and restart the terminal or do source ~/.bashrc or source ~/.bash_profile. If you need command completion for nvm then also add the line:

[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"

Along with the above lines to ~/.bashrc and ~/.bash_profile.

Keyboard shortcut for Jump to Previous View Location (Navigate back/forward) in IntelliJ IDEA

The underlying problem is Ctrl+Alt+Left and Right are used by window managers to switch workspace and/or OEM utilities to change the screen orientation.

You can change the assignments using File / Settings / Keymap then Main Menu / Navigate find Back and Forward and right click to Add Keyboard Shortcut to set an alternative key chord.

Alt Graph+Left and Alt Graph+Right works well for me (IDEA 13.1.4 on Ubuntu under IceWM).

Passing properties by reference in C#

Another trick not yet mentioned is to have the class which implements a property (e.g. Foo of type Bar) also define a delegate delegate void ActByRef<T1,T2>(ref T1 p1, ref T2 p2); and implement a method ActOnFoo<TX1>(ref Bar it, ActByRef<Bar,TX1> proc, ref TX1 extraParam1) (and possibly versions for two and three "extra parameters" as well) which will pass its internal representation of Foo to the supplied procedure as a ref parameter. This has a couple of big advantages over other methods of working with the property:

  1. The property is updated "in place"; if the property is of a type that's compatible with `Interlocked` methods, or if it is a struct with exposed fields of such types, the `Interlocked` methods may be used to perform atomic updates to the property.
  2. If the property is an exposed-field structure, the fields of the structure may be modified without having to make any redundant copies of it.
  3. If the `ActByRef` method passes one or more `ref` parameters through from its caller to the supplied delegate, it may be possible to use a singleton or static delegate, thus avoiding the need to create closures or delegates at run-time.
  4. The property knows when it is being "worked with". While it is always necessary to use caution executing external code while holding a lock, if one can trust callers not to do too do anything in their callback that might require another lock, it may be practical to have the method guard the property access with a lock, such that updates which aren't compatible with `CompareExchange` could still be performed quasi-atomically.

Passing things be ref is an excellent pattern; too bad it's not used more.

How to check if element in groovy array/hash/collection/list?

For lists, use contains:

[1,2,3].contains(1) == true

SSL_connect: SSL_ERROR_SYSCALL in connection to github.com:443

same issue with KAV. Restart it solved the pb.

Do AJAX requests retain PHP Session info?

Well, not always. Using cookies, you are good. But the "can I safely rely on the id being present" urged me to extend the discussion with an important point (mostly for reference, as the visitor count of this page seems quite high).

PHP can be configured to maintain sessions by URL-rewriting, instead of cookies. (How it's good or bad (<-- see e.g. the topmost comment there) is a separate question, let's now stick to the current one, with just one side-note: the most prominent issue with URL-based sessions -- the blatant visibility of the naked session ID -- is not an issue with internal Ajax calls; but then, if it's turned on for Ajax, it's turned on for the rest of the site, too, so there...)

In case of URL-rewriting (cookieless) sessions, Ajax calls must take care of it themselves that their request URLs are properly crafted. (Or you can roll your own custom solution. You can even resort to maintaining sessions on the client side, in less demanding cases.) The point is the explicit care needed for session continuity, if not using cookies:

  1. If the Ajax calls just extract URLs verbatim from the HTML (as received from PHP), that should be OK, as they are already cooked (umm, cookified).

  2. If they need to assemble request URIs themselves, the session ID needs to be added to the URL manually. (Check here, or the page sources generated by PHP (with URL-rewriting on) to see how to do it.)


From OWASP.org:

Effectively, the web application can use both mechanisms, cookies or URL parameters, or even switch from one to the other (automatic URL rewriting) if certain conditions are met (for example, the existence of web clients without cookies support or when cookies are not accepted due to user privacy concerns).

From a Ruby-forum post:

When using php with cookies, the session ID will automatically be sent in the request headers even for Ajax XMLHttpRequests. If you use or allow URL-based php sessions, you'll have to add the session id to every Ajax request url.

Clearing a text field on button click

A simple JavaScript function will do the job.

function ClearFields() {

     document.getElementById("textfield1").value = "";
     document.getElementById("textfield2").value = "";
}

And just have your button call it:

<button type="button" onclick="ClearFields();">Clear</button>

Maven 3 Archetype for Project With Spring, Spring MVC, Hibernate, JPA

With appFuse framework, you can create an Spring MVC archetype with jpa support, etc ...

Take a look at it's quickStart guide to see how to create an archetype based on this Framework.

Foundational frameworks in AppFuse:

  • Bootstrap and jQuery
  • Maven, Hibernate, Spring and Spring Security
  • Java 7, Annotations, JSP 2.1, Servlet 3.0
  • Web Frameworks: JSF, Struts 2, Spring MVC, Tapestry 5, Wicket
  • JPA Support

For example to create an appFuse light archetype :

mvn archetype:generate -B -DarchetypeGroupId=org.appfuse.archetypes 
-DarchetypeArtifactId=appfuse-light-struts-archetype -DarchetypeVersion=2.2.1 
-DgroupId=com.mycompany -DartifactId=myproject

Save a subplot in matplotlib

While @Eli is quite correct that there usually isn't much of a need to do it, it is possible. savefig takes a bbox_inches argument that can be used to selectively save only a portion of a figure to an image.

Here's a quick example:

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

# Make an example plot with two subplots...
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')

ax2 = fig.add_subplot(2,1,2)
ax2.plot(range(20), 'r^')

# Save the full figure...
fig.savefig('full_figure.png')

# Save just the portion _inside_ the second axis's boundaries
extent = ax2.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)

# Pad the saved area by 10% in the x-direction and 20% in the y-direction
fig.savefig('ax2_figure_expanded.png', bbox_inches=extent.expanded(1.1, 1.2))

The full figure: Full Example Figure


Area inside the second subplot: Inside second subplot


Area around the second subplot padded by 10% in the x-direction and 20% in the y-direction: Full second subplot

PHP: maximum execution time when importing .SQL data file

1-make a search in your local drive and type "php.ini" 2-you may see many files named php.ini you should choose the one that fits with your php version (see localhost) 3-open the php.ini file make a search on "max_execution_time" then make it equal to "-1" to make it unlimited

Set a button group's width to 100% and make buttons equal width?

For bootstrap 4 just add this class:

w-100

How to use multiple LEFT JOINs in SQL?

Yes, but the syntax is different than what you have

SELECT
    <fields>
FROM
    <table1>
    LEFT JOIN <table2>
        ON <criteria for join>
        AND <other criteria for join>
    LEFT JOIN <table3> 
        ON <criteria for join>
        AND <other criteria for join>

Laravel 5 PDOException Could Not Find Driver

You should install PDO on your server. Edit your php.ini (look at your phpinfo(), "Loaded Configuration File" line, to find the php.ini file path). Find and uncomment the following line (remove the ; character):

;extension=pdo_mysql.so

Then, restart your Apache server. For more information, please read the documentation.

What is the right way to treat argparse.Namespace() as a dictionary?

You can access the namespace's dictionary with vars():

>>> import argparse
>>> args = argparse.Namespace()
>>> args.foo = 1
>>> args.bar = [1,2,3]
>>> d = vars(args)
>>> d
{'foo': 1, 'bar': [1, 2, 3]}

You can modify the dictionary directly if you wish:

>>> d['baz'] = 'store me'
>>> args.baz
'store me'

Yes, it is okay to access the __dict__ attribute. It is a well-defined, tested, and guaranteed behavior.

HTML5 LocalStorage: Checking if a key exists

Update:

if (localStorage.hasOwnProperty("username")) {
    //
}

Another way, relevant when value is not expected to be empty string, null or any other falsy value:

if (localStorage["username"]) {
    //
}

How can I expand and collapse a <div> using javascript?

Take a look at toggle() jQuery function :

http://api.jquery.com/toggle/

Also, innerHTML jQuery Function is .html().

Truncate/round whole number in JavaScript?

If you have a string, parse it as an integer:

var num = '20.536';
var result = parseInt(num, 10);  // 20

If you have a number, ECMAScript 6 offers Math.trunc for completely consistent truncation, already available in Firefox 24+ and Edge:

var num = -2147483649.536;
var result = Math.trunc(num);  // -2147483649

If you can’t rely on that and will always have a positive number, you can of course just use Math.floor:

var num = 20.536;
var result = Math.floor(num);  // 20

And finally, if you have a number in [−2147483648, 2147483647], you can truncate to 32 bits using any bitwise operator. | 0 is common, and >>> 0 can be used to obtain an unsigned 32-bit integer:

var num = -20.536;
var result = num | 0;  // -20

How to get a value of an element by name instead of ID

This works fine .. here btnAddCat is button id

$('#btnAddCat').click(function(){
        var eventCategory=$("input[name=txtCategory]").val();
        alert(eventCategory);
    });

Crystal Reports - Adding a parameter to a 'Command' query

Try this:

Select Project_Name, ReleaseDate, TaskName
From DB_Table
Where Project_Name like '{?Pm-?Proj_Name}'
  And ReleaseDate >= currentdate

currentdate should be a valid database function or field to work. If you are using MS SQL Server, use GETDATE() instead.

If all you want is to filter records in a subreport based on a parameter from the main report, it might be easier to simply add the table to the subreport, and then create a Project_Name link between the main report and subreport. You can then use the Select Expert to filter the ReleaseDate as well.

How to display a list of images in a ListView in Android?

File name should match the layout id which in this example is : items_list_item.xml in the layout folder of your application

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    >  

<ImageView android:id="@+id/R.id.list_item_image"
  android:layout_width="100dip"
  android:layout_height="wrap_content" />  
</LinearLayout>

How to select all columns, except one column in pandas?

I think the best way to do is the way mentioned by @Salvador Dali. Not that the others are wrong.

Because when you have a data set where you just want to select one column and put it into one variable and the rest of the columns into another for comparison or computational purposes. Then dropping the column of the data set might not help. Of course there are use cases for that as well.

x_cols = [x for x in data.columns if x != 'name of column to be excluded']

Then you can put those collection of columns in variable x_cols into another variable like x_cols1 for other computation.

ex: x_cols1 = data[x_cols]

How to concatenate items in a list to a single string?

Use join:

>>> sentence = ['this', 'is', 'a', 'sentence']
>>> '-'.join(sentence)
'this-is-a-sentence'
>>> ' '.join(sentence)
'this is a sentence'

How can I run PowerShell with the .NET 4 runtime?

The best solution I have found is in the blog post Using Newer Version(s) of .NET with PowerShell. This allows powershell.exe to run with .NET 4 assemblies.

Simply modify (or create) $pshome\powershell.exe.config so that it contains the following:

<?xml version="1.0"?> 
<configuration> 
    <startup useLegacyV2RuntimeActivationPolicy="true"> 
        <supportedRuntime version="v4.0.30319"/> 
        <supportedRuntime version="v2.0.50727"/> 
    </startup> 
</configuration> 

Additional, quick setup notes:

Locations and files are somewhat platform dependent; however will give you an inline gist of how to make the solution work for you.

  • You can find PowerShell's location on your computer by executing cd $pshome in the Powershell window (doesn't work from DOS prompt).
    • Path will be something like (example) C:\Windows\System32\WindowsPowerShell\v1.0\
  • The filename to put configuration in is: powershell.exe.config if your PowerShell.exe is being executed (create the config file if need be).
    • If PowerShellISE.Exe is running then you need to create its companion config file as PowerShellISE.Exe.config

Case insensitive 'in'

I think you have to write some extra code. For example:

if 'MICHAEL89' in map(lambda name: name.upper(), USERNAMES):
   ...

In this case we are forming a new list with all entries in USERNAMES converted to upper case and then comparing against this new list.

Update

As @viraptor says, it is even better to use a generator instead of map. See @Nathon's answer.

Nested rows with bootstrap grid system?

Adding to what @KyleMit said, consider using:

  • col-md-* classes for the larger outer columns
  • col-xs-* classes for the smaller inner columns

This will be useful when you view the page on different screen sizes.

On a small screen, the wrapping of larger outer columns will then happen while maintaining the smaller inner columns, if possible

How to install a Python module via its setup.py in Windows?

setup.py is designed to be run from the command line. You'll need to open your command prompt (In Windows 7, hold down shift while right-clicking in the directory with the setup.py file. You should be able to select "Open Command Window Here").

From the command line, you can type

python setup.py --help

...to get a list of commands. What you are looking to do is...

python setup.py install

How to configure Glassfish Server in Eclipse manually

For Eclipse Mars use the similar approach as harshit.

1) Help -> Install New Software
2) Use url: http://download.oracle.com/otn_software/oepe/mars repository Above is the OEPE tool provided by oracle for EE development.
3) From all the suggestions, select Glassfish Tools, (Oracle Weblogic Server Tools, Oracle Weblogic Scripting Tools, Oracle patches, Oracle Maven Tools).
4) Install it.
5) Restart eclipse

In point 3) are 4 tools are in braces, I don't know minimal combination, but only install Glassfish Tools has no effect.

During restart Oepe ask for Java 8 JDK if Eclipse run on on older version.

Eclipse 4.5.0 Mars JDK : 1.8

Angular2 Error: There is no directive with "exportAs" set to "ngForm"

In my case I had to add FormsModule and ReactiveFormsModule to the shared.module.ts too:

(thanks to @Undrium for the code example):

import { NgModule }                                 from '@angular/core';
import { CommonModule }                             from '@angular/common';
import { FormsModule, ReactiveFormsModule }         from '@angular/forms';

@NgModule({
  imports:      [
    CommonModule,
    ReactiveFormsModule
  ],
  declarations: [],
  exports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule
  ]
})
export class SharedModule { }

Pandas index column title or name

To just get the index column names df.index.names will work for both a single Index or MultiIndex as of the most recent version of pandas.

As someone who found this while trying to find the best way to get a list of index names + column names, I would have found this answer useful:

names = list(filter(None, df.index.names + df.columns.values.tolist()))

This works for no index, single column Index, or MultiIndex. It avoids calling reset_index() which has an unnecessary performance hit for such a simple operation. I'm surprised there isn't a built in method for this (that I've come across). I guess I run into needing this more often because I'm shuttling data from databases where the dataframe index maps to a primary/unique key, but is really just another column to me.

Logical operators ("and", "or") in DOS batch

The IF statement does not support logical operators AND and OR. Cascading IF statements make an implicit conjunction:

IF Exist File1.Dat IF Exist File2.Dat GOTO FILE12_EXIST_LABEL

If File1.Dat and File2.Dat exist then jump to the label FILE12_EXIST_LABEL.

See also: IF /?

DataTables warning: Requested unknown parameter '0' from the data source for row '0'

You're using an array of objects. Can you use a two dimensional array instead?

http://www.datatables.net/examples/data_sources/js_array.html

See this jsfiddle: http://jsfiddle.net/QhYse/

I used an array like this and it worked fine:

var data = [
    ["UpdateBootProfile","PASS","00:00:00",[]] ,
    ["NRB Boot","PASS","00:00:50.5000000",[{"TestName":"TOTAL_TURN_ON_TIME","Result":"PASS","Value":"50.5","LowerLimit":"NaN","UpperLimit":"NaN","ComparisonType":"nctLOG","Units":"SECONDS"}]] ,
    ["NvMgrCommit","PASS","00:00:00",[]] ,
    ["SyncNvToEFS","PASS","00:00:01.2500000",[]]
];

Edit to include array of objects

There's a possible solution from this question: jQuery DataTables fnrender with objects

This jsfiddle http://jsfiddle.net/j2C7j/ uses an array of objects. To not get the error I had to pad it with 3 blank values - less than optimal, I know. You may find a better way with fnRender, please post if you do.

var data = [
   ["","","", {"Name":"UpdateBootProfile","Result":"PASS","ExecutionTime":"00:00:00","Measurement":[]} ]

];

$(function() {
        var testsTable = $('#tests').dataTable({
                bJQueryUI: true,
                aaData: data,
                aoColumns: [
                        { mData: 'Name', "fnRender": function( oObj ) { return oObj.aData[3].Name}},
                        { mData: 'Result' ,"fnRender": function( oObj ) { return oObj.aData[3].Result }},
                        { mData: 'ExecutionTime',"fnRender": function( oObj ) { return oObj.aData[3].ExecutionTime } }
                ]
        });
});

How can I change the color of pagination dots of UIPageControl?

You can fix it with ease by adding the following code to your appdelegate.m file in your didFinishLaunchingWithOptions method:

UIPageControl *pageControl = [UIPageControl appearance];
pageControl.pageIndicatorTintColor = [UIColor darkGrayColor];
pageControl.currentPageIndicatorTintColor = [UIColor orangeColor];
pageControl.backgroundColor = [UIColor whiteColor]

"Least Astonishment" and the Mutable Default Argument

I sometimes exploit this behavior as an alternative to the following pattern:

singleton = None

def use_singleton():
    global singleton

    if singleton is None:
        singleton = _make_singleton()

    return singleton.use_me()

If singleton is only used by use_singleton, I like the following pattern as a replacement:

# _make_singleton() is called only once when the def is executed
def use_singleton(singleton=_make_singleton()):
    return singleton.use_me()

I've used this for instantiating client classes that access external resources, and also for creating dicts or lists for memoization.

Since I don't think this pattern is well known, I do put a short comment in to guard against future misunderstandings.

What is an NP-complete in computer science?

NP stands for Non-deterministic Polynomial time.

This means that the problem can be solved in Polynomial time using a Non-deterministic Turing machine (like a regular Turing machine but also including a non-deterministic "choice" function). Basically, a solution has to be testable in poly time. If that's the case, and a known NP problem can be solved using the given problem with modified input (an NP problem can be reduced to the given problem) then the problem is NP complete.

The main thing to take away from an NP-complete problem is that it cannot be solved in polynomial time in any known way. NP-Hard/NP-Complete is a way of showing that certain classes of problems are not solvable in realistic time.

Edit: As others have noted, there are often approximate solutions for NP-Complete problems. In this case, the approximate solution usually gives an approximation bound using special notation which tells us how close the approximation is.

Best way to get whole number part of a Decimal number

By the way guys, (int)Decimal.MaxValue will overflow. You can't get the "int" part of a decimal because the decimal is too friggen big to put in the int box. Just checked... its even too big for a long (Int64).

If you want the bit of a Decimal value to the LEFT of the dot, you need to do this:

Math.Truncate(number)

and return the value as... A DECIMAL or a DOUBLE.

edit: Truncate is definitely the correct function!

Mixing C# & VB In The Same Project

Right-click the Project. Choose Add Asp.Net Folder. Under The Folder, create two folders one named VBCodeFiles and the Other CSCodeFiles In Web.Config add a new element under compilation

<compilation debug="true" targetFramework="4.5.1">
      <codeSubDirectories>
        <add directoryName="VBCodeFiles"/>
        <add directoryName="CSCodeFiles"/>
      </codeSubDirectories>
</compilation>

Now, Create an cshtml page. Add a reference to the VBCodeFiles.Namespace.MyClassName using

@using DMH.VBCodeFiles.Utils.RCMHD
@model MyClassname

Where MyClassName is an class object found in the namespace above. now write out the object in razor using a cshtml file.

<p>@Model.FirstName</p>

Please note, the directoryName="CSCodeFiles" is redundant if this is a C# Project and the directoryName="VBCodeFiles" is redundant if this is a VB.Net project.

Difference between Python's Generators and Iterators

iterator is a more general concept: any object whose class has a __next__ method (next in Python 2) and an __iter__ method that does return self.

Every generator is an iterator, but not vice versa. A generator is built by calling a function that has one or more yield expressions (yield statements, in Python 2.5 and earlier), and is an object that meets the previous paragraph's definition of an iterator.

You may want to use a custom iterator, rather than a generator, when you need a class with somewhat complex state-maintaining behavior, or want to expose other methods besides __next__ (and __iter__ and __init__). Most often, a generator (sometimes, for sufficiently simple needs, a generator expression) is sufficient, and it's simpler to code because state maintenance (within reasonable limits) is basically "done for you" by the frame getting suspended and resumed.

For example, a generator such as:

def squares(start, stop):
    for i in range(start, stop):
        yield i * i

generator = squares(a, b)

or the equivalent generator expression (genexp)

generator = (i*i for i in range(a, b))

would take more code to build as a custom iterator:

class Squares(object):
    def __init__(self, start, stop):
       self.start = start
       self.stop = stop
    def __iter__(self): return self
    def __next__(self): # next in Python 2
       if self.start >= self.stop:
           raise StopIteration
       current = self.start * self.start
       self.start += 1
       return current

iterator = Squares(a, b)

But, of course, with class Squares you could easily offer extra methods, i.e.

    def current(self):
       return self.start

if you have any actual need for such extra functionality in your application.

Android Studio: Plugin with id 'android-library' not found

Use mavenCentral() or jcenter() adding in the build.gradle file the script:

buildscript {
    repositories {
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:1.5.0'   
    }
}

Return multiple values in JavaScript?

No, but you could return an array containing your values:

function getValues() {
    return [getFirstValue(), getSecondValue()];
}

Then you can access them like so:

var values = getValues();
var first = values[0];
var second = values[1];

With the latest ECMAScript 6 syntax*, you can also destructure the return value more intuitively:

const [first, second] = getValues();

If you want to put "labels" on each of the returned values (easier to maintain), you can return an object:

function getValues() {
    return {
        first: getFirstValue(),
        second: getSecondValue(),
    };
}

And to access them:

var values = getValues();
var first = values.first;
var second = values.second;

Or with ES6 syntax:

const {first, second} = getValues();

* See this table for browser compatibility. Basically, all modern browsers aside from IE support this syntax, but you can compile ES6 code down to IE-compatible JavaScript at build time with tools like Babel.

Check if a div does NOT exist with javascript

That works with :

 var element = document.getElementById('myElem');
 if (typeof (element) != undefined && typeof (element) != null && typeof (element) != 'undefined') {
     console.log('element exists');
 }
 else{
     console.log('element NOT exists');
 }

Oracle's default date format is YYYY-MM-DD, WHY?

If you are using this query to generate an input file for your Data Warehouse, then you need to format the data appropriately. Essentially in that case you are converting the date (which does have a time component) to a string. You need to explicitly format your string or change your nls_date_format to set the default. In your query you could simply do:

select to_char(some_date, 'yyyy-mm-dd hh24:mi:ss') my_date
  from some_table;

Define a global variable in a JavaScript function

To use the window object is not a good idea. As I see in comments,

'use strict';

function showMessage() {
    window.say_hello = 'hello!';
}

console.log(say_hello);

This will throw an error to use the say_hello variable we need to first call the showMessage function.

Gulp error: The following tasks did not complete: Did you forget to signal async completion?

You need to do one thing:

  • Add async before function.

_x000D_
_x000D_
const gulp = require('gulp');

gulp.task('message', async function() {
    console.log("Gulp is running...");
});
_x000D_
_x000D_
_x000D_

How to refer to relative paths of resources when working with a code repository

Try to use a filename relative to the current files path. Example for './my_file':

fn = os.path.join(os.path.dirname(__file__), 'my_file')

In Python 3.4+ you can also use pathlib:

fn = pathlib.Path(__file__).parent / 'my_file'

Merging two CSV files using Python

You need to store all of the extra rows in the files in your dictionary, not just one of them:

dict1 = {row[0]: row[1:] for row in r}
...
dict2 = {row[0]: row[1:] for row in r}

Then, since the values in the dictionaries are lists, you need to just concatenate the lists together:

w.writerows([[key] + dict1.get(key, []) + dict2.get(key, []) for key in keys])

How to test multiple variables against a value?

You can use dictionary :

x = 0
y = 1
z = 3
list=[]
dict = {0: 'c', 1: 'd', 2: 'e', 3: 'f'}
if x in dict:
    list.append(dict[x])
else:
    pass

if y in dict:
    list.append(dict[y])
else:
    pass
if z in dict:
    list.append(dict[z])
else:
    pass

print list

fatal: bad default revision 'HEAD'

This seems to occur when .git/HEAD refers to a branch which does not exist. I ran into this error in a repo that had nothing in .git/refs/heads. I have no idea how the repo got into that state, I inherited from someone that left the company.

Does not contain a definition for and no extension method accepting a first argument of type could be found

placeBets(betList, stakeAmt) is an instance method not a static method. You need to create an instance of CBetfairAPI first:

MyBetfair api = new MyBetfair();
ArrayList bets = api.placeBets(betList, stakeAmt);

How to convert dataframe into time series?

With library fpp, you can easily create time series with date format: time_ser=ts(data,frequency=4,start=c(1954,2))

here we start at the 2nd quarter of 1954 with quarter fequency.

DTO and DAO concepts and MVC

DTO is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.

  • DTO should only contain private fields for your data, getters, setters, and constructors.
  • DTO is not recommended to add business logic methods to such classes, but it is OK to add some util methods.

DAO is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).

Here is an example of how the DAO and DTO interfaces would look like:

interface PersonDTO {
    String getName();
    void setName(String name);
    //.....
}

interface PersonDAO {
    PersonDTO findById(long id);
    void save(PersonDTO person);
    //.....
}

The MVC is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.

As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.

Listing all extras of an Intent

I noticed in the Android source that almost every operation forces the Bundle to unparcel its data. So if (like me) you need to do this frequently for debugging purposes, the below is very quick to type:

Bundle extras = getIntent().getExtras();
extras.isEmpty(); // unparcel
System.out.println(extras);

How can you find out which process is listening on a TCP or UDP port on Windows?

You can get more information if you run the following command:

netstat -aon | find /i "listening" |find "port"

using the 'Find' command allows you to filter the results. find /i "listening" will display only ports that are 'Listening'. Note, you need the /i to ignore case, otherwise you would type find "LISTENING". | find "port" will limit the results to only those containing the specific port number. Note, on this it will also filter in results that have the port number anywhere in the response string.

jQuery .each() index?

$('#list option').each(function(intIndex){
//do stuff
});

Get current working directory in a Qt application

Just tested and QDir::currentPath() does return the path from which I called my executable.

And a symlink does not "exist". If you are executing an exe from that path you are effectively executing it from the path the symlink points to.

What's is the difference between include and extend in use case diagram?

To simplify,

for include

  1. When the base use case is executed, the included use case is executed EVERYTIME.
  2. The base use case required the completion of the included use case in order to be completed.

a typical example: between login and verify password

(login) --- << include >> ---> (verify password)

for the login process to success, "verify password" must be successful as well.


for extend

  1. When the base use case is executed, the extended use case is executed only SOMETIMES
  2. The extended use case will happen only when certain criteria are met.

a typical example: between login and show error message (only happened sometimes)

(login) <--- << extend >> --- (show error message)

"show error message" only happens sometimes when the login process failed.

if var == False

Since Python evaluates also the data type NoneType as False during the check, a more precise answer is:

var = False
if var is False:
    print('learnt stuff')

This prevents potentially unwanted behaviour such as:

var = []  # or None
if not var:
    print('learnt stuff') # is printed what may or may not be wanted

But if you want to check all cases where var will be evaluated to False, then doing it by using logical not keyword is the right thing to do.

Retrieving data from a POST method in ASP.NET

The data from the request (content, inputs, files, querystring values) is all on this object HttpContext.Current.Request
To read the posted content

StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream);
string requestFromPost = reader.ReadToEnd();

To navigate through the all inputs

foreach (string key in HttpContext.Current.Request.Form.AllKeys)
{
   string value = HttpContext.Current.Request.Form[key];
}

Stacked Tabs in Bootstrap 3

Left, Right and Below tabs were removed from Bootstrap 3, but you can add custom CSS to achieve this..

.tabs-below > .nav-tabs,
.tabs-right > .nav-tabs,
.tabs-left > .nav-tabs {
  border-bottom: 0;
}

.tab-content > .tab-pane,
.pill-content > .pill-pane {
  display: none;
}

.tab-content > .active,
.pill-content > .active {
  display: block;
}

.tabs-below > .nav-tabs {
  border-top: 1px solid #ddd;
}

.tabs-below > .nav-tabs > li {
  margin-top: -1px;
  margin-bottom: 0;
}

.tabs-below > .nav-tabs > li > a {
  -webkit-border-radius: 0 0 4px 4px;
     -moz-border-radius: 0 0 4px 4px;
          border-radius: 0 0 4px 4px;
}

.tabs-below > .nav-tabs > li > a:hover,
.tabs-below > .nav-tabs > li > a:focus {
  border-top-color: #ddd;
  border-bottom-color: transparent;
}

.tabs-below > .nav-tabs > .active > a,
.tabs-below > .nav-tabs > .active > a:hover,
.tabs-below > .nav-tabs > .active > a:focus {
  border-color: transparent #ddd #ddd #ddd;
}

.tabs-left > .nav-tabs > li,
.tabs-right > .nav-tabs > li {
  float: none;
}

.tabs-left > .nav-tabs > li > a,
.tabs-right > .nav-tabs > li > a {
  min-width: 74px;
  margin-right: 0;
  margin-bottom: 3px;
}

.tabs-left > .nav-tabs {
  float: left;
  margin-right: 19px;
  border-right: 1px solid #ddd;
}

.tabs-left > .nav-tabs > li > a {
  margin-right: -1px;
  -webkit-border-radius: 4px 0 0 4px;
     -moz-border-radius: 4px 0 0 4px;
          border-radius: 4px 0 0 4px;
}

.tabs-left > .nav-tabs > li > a:hover,
.tabs-left > .nav-tabs > li > a:focus {
  border-color: #eeeeee #dddddd #eeeeee #eeeeee;
}

.tabs-left > .nav-tabs .active > a,
.tabs-left > .nav-tabs .active > a:hover,
.tabs-left > .nav-tabs .active > a:focus {
  border-color: #ddd transparent #ddd #ddd;
  *border-right-color: #ffffff;
}

.tabs-right > .nav-tabs {
  float: right;
  margin-left: 19px;
  border-left: 1px solid #ddd;
}

.tabs-right > .nav-tabs > li > a {
  margin-left: -1px;
  -webkit-border-radius: 0 4px 4px 0;
     -moz-border-radius: 0 4px 4px 0;
          border-radius: 0 4px 4px 0;
}

.tabs-right > .nav-tabs > li > a:hover,
.tabs-right > .nav-tabs > li > a:focus {
  border-color: #eeeeee #eeeeee #eeeeee #dddddd;
}

.tabs-right > .nav-tabs .active > a,
.tabs-right > .nav-tabs .active > a:hover,
.tabs-right > .nav-tabs .active > a:focus {
  border-color: #ddd #ddd #ddd transparent;
  *border-left-color: #ffffff;
}

Working example: http://bootply.com/74926

UPDATE

If you don't need the exact look of a tab (bordered appropriately on the left or right as each tab is activated), you can simple use nav-stacked, along with Bootstrap col-* to float the tabs to the left or right...

nav-stacked demo: http://codeply.com/go/rv3Cvr0lZ4

<ul class="nav nav-pills nav-stacked col-md-3">
    <li><a href="#a" data-toggle="tab">1</a></li>
    <li><a href="#b" data-toggle="tab">2</a></li>
    <li><a href="#c" data-toggle="tab">3</a></li>
</ul>

pip not working in Python Installation in Windows 10

instead of typing in "python". try using "py". for ex:

py -m pip install    packagename
py -m pip --install  packagename
py -m pip --upgrade  packagename
py -m pip upgrade    packagename

note: this should be done in the command prompt "cmd" and not in python idle. also FYI pip is installed with python 3.6 automatically.

Is it possible to move/rename files in Git and maintain their history?

No.

The short answer is NO. It is not possible to rename a file in Git and remember the history. And it is a pain.

Rumor has it that git log --follow --find-copies-harder will work, but it does not work for me, even if there are zero changes to the file contents, and the moves have been made with git mv.

(Initially I used Eclipse to rename and update packages in one operation, which may have confused Git. But that is a very common thing to do. --follow does seem to work if only a mv is performed and then a commit and the mv is not too far.)

Linus says that you are supposed to understand the entire contents of a software project holistically, not needing to track individual files. Well, sadly, my small brain cannot do that.

It is really annoying that so many people have mindlessly repeated the statement that Git automatically tracks moves. They have wasted my time. Git does no such thing. By design(!) Git does not track moves at all.

My solution is to rename the files back to their original locations. Change the software to fit the source control. With Git you just seem to need to "git" it right the first time.

Unfortunately, that breaks Eclipse, which seems to use --follow. git log --follow sometimes does not show the full history of files with complicated rename histories even though git log does. (I do not know why.)

(There are some too clever hacks that go back and recommit old work, but they are rather frightening. See GitHub-Gist: emiller/git-mv-with-history.)

python requests get cookies

Alternatively, you can use requests.Session and observe cookies before and after a request:

>>> import requests
>>> session = requests.Session()
>>> print(session.cookies.get_dict())
{}
>>> response = session.get('http://google.com')
>>> print(session.cookies.get_dict())
{'PREF': 'ID=5514c728c9215a9a:FF=0:TM=1406958091:LM=1406958091:S=KfAG0U9jYhrB0XNf', 'NID': '67=TVMYiq2wLMNvJi5SiaONeIQVNqxSc2RAwVrCnuYgTQYAHIZAGESHHPL0xsyM9EMpluLDQgaj3db_V37NjvshV-eoQdA8u43M8UwHMqZdL-S2gjho8j0-Fe1XuH5wYr9v'}

CSS to keep element at "fixed" position on screen

Try this one:

p.pos_fixed {
    position:fixed;
    top:30px;
    right:5px;
}

How to apply box-shadow on all four sides?

The most simple solution and easiest way is to add shadow for all four side. CSS

box-shadow: 0 0 2px 2px #ccc; /* with blur shadow*/
box-shadow: 0 0 0 2px #ccc; /* without blur shadow*/

I get conflicting provisioning settings error when I try to archive to submit an iOS app

The problem is in the Cordova settings.

Note this:

iPhone Distribution has been manually specified

This didn’t make any sense to me, since I had set the project to auto sign in xcode. Like you, the check and uncheck didn’t work. But then I read the last file path given and followed it. The file path is APP > Platforms > ios > Cordova > build-release.xconfig

And in the file, iPhone Distribution is explicitly set for CODE_SIGN_IDENTITY.

Change:

CODE_SIGN_IDENTITY = iPhone Distribution
CODE_SIGN_IDENTITY[sdk=iphoneos*] = iPhone Distribution

To:

CODE_SIGN_IDENTITY = iPhone Developer
CODE_SIGN_IDENTITY[sdk=iphoneos*] = iPhone Developer

It a simple thing, and the error message does make it clear that iPhone Distribution has been manually specified, but it doesn’t really say where unless you follow the path. I looked and fiddled with xcode for about three hours trying to figure this out. Hopes this helps anyone in the future.

SimpleDateFormat returns 24-hour date: how to get 12-hour date?

SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss a");

use hh in place of HH

ActionController::InvalidAuthenticityToken

I had the same issue but with pages which were page cached. Pages got buffered with a stale authenticity token and all actions using the methods post/put/delete where recognized as forgery attempts. Error (422 Unprocessable Entity) was returned to the user.

The solution for Rails 3:
Add:

 skip_before_filter :verify_authenticity_token  

or as "sagivo" pointed out in Rails 4 add:

 skip_before_action :verify_authenticity_token

On pages which do caching.

As @toobulkeh commented this is not a vulnerability on :index, :show actions, but beware using this on :put, :post actions.

For example:

 caches_page :index, :show  
 skip_before_filter :verify_authenticity_token, :only => [:index, :show]

Reference: http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection/ClassMethods.html

Note added by barlop- Rails 4.2 deprecated skip_before_filter in favour of skip_before_action https://guides.rubyonrails.org/4_2_release_notes.html "The *_filter family of methods have been removed from the documentation. Their usage is discouraged in favor of the *_action family of methods"

For Rails 6 (as "collimarco" pointed out) you can use skip_forgery_protection and that it is safe to use it for a REST API that doesn't use session data.

Java 8 Lambda filter by Lists

Look this:

List<Client> result = clients
    .stream()
    .filter(c -> 
        (users.stream().map(User::getName).collect(Collectors.toList())).contains(c.getName()))
        .collect(Collectors.toList());

DLL and LIB files - what and why?

Another aspect is security (obfuscation). Once a piece of code is extracted from the main application and put in a "separated" Dynamic-Link Library, it is easier to attack, analyse (reverse-engineer) the code, since it has been isolated. When the same piece of code is kept in a LIB Library, it is part of the compiled (linked) target application, and this thus harder to isolate (differentiate) that piece of code from the rest of the target binaries.

How to debug Javascript with IE 8

I discovered today that we can now debug Javascript With the developer tool bar plugins integreted in IE 8.

  • Click ? Tools on the toolbar, to the right of the tabs.
  • Select Developer Tools. The Developer Tools dialogue should open.
  • Click the Script tab in the dialogue.
  • Click the Start Debugging button.

You can use watch, breakpoint, see the call stack etc, similarly to debuggers in professional browsers.

You can also use the statement debugger; in your JavaScript code the set a breakpoint.

How can I specify the schema to run an sql file against in the Postgresql command line

I was facing similar problems trying to do some dat import on an intermediate schema (that later we move on to the final one). As we rely on things like extensions (for example PostGIS), the "run_insert" sql file did not fully solved the problem.

After a while, we've found that at least with Postgres 9.3 the solution is far easier... just create your SQL script always specifying the schema when refering to the table:

CREATE TABLE "my_schema"."my_table" (...); COPY "my_schema"."my_table" (...) FROM stdin;

This way using psql -f xxxxx works perfectly, and you don't need to change search_paths nor use intermediate files (and won't hit extension schema problems).

How to select id with max date group by category in PostgreSQL?

SELECT id FROM tbl GROUP BY cat HAVING MAX(date)

How do I set the driver's python version in spark?

Helped in my case:

import os

os.environ["SPARK_HOME"] = "/usr/local/Cellar/apache-spark/1.5.1/"
os.environ["PYSPARK_PYTHON"]="/usr/local/bin/python3"

Convert an array to string

You probably want something like this overload of String.Join:

String.Join<T> Method (String, IEnumerable<T>)

Docs:

http://msdn.microsoft.com/en-us/library/dd992421.aspx

In your example, you'd use

String.Join("", Client);

Best way to detect Mac OS X or Windows computers with JavaScript or jQuery

Let me know if this works. Way to detect an Apple device (Mac computers, iPhones, etc.) with help from StackOverflow.com:
What is the list of possible values for navigator.platform as of today?

var deviceDetect = navigator.platform;
var appleDevicesArr = ['MacIntel', 'MacPPC', 'Mac68K', 'Macintosh', 'iPhone', 
'iPod', 'iPad', 'iPhone Simulator', 'iPod Simulator', 'iPad Simulator', 'Pike 
v7.6 release 92', 'Pike v7.8 release 517'];

// If on Apple device
if(appleDevicesArr.includes(deviceDetect)) {
    // Execute code
}
// If NOT on Apple device
else {
    // Execute code
}

How to list all users in a Linux group?

Here's a very simple awk script that takes into account all common pitfalls listed in the other answers:

getent passwd | awk -F: -v group_name="wheel" '
  BEGIN {
    "getent group " group_name | getline groupline;
    if (!groupline) exit 1;
    split(groupline, groupdef, ":");
    guid = groupdef[3];
    split(groupdef[4], users, ",");
    for (k in users) print users[k]
  }
  $4 == guid {print $1}'

I'm using this with my ldap-enabled setup, runs on anything with standards-compliant getent & awk, including solaris 8+ and hpux.

Replace NA with 0 in a data frame column

First, here's some sample data:

set.seed(1)
dat <- data.frame(one = rnorm(15),
                 two = sample(LETTERS, 15),
                 three = rnorm(15),
                 four = runif(15))
dat <- data.frame(lapply(dat, function(x) { x[sample(15, 5)] <- NA; x }))
head(dat)
#          one  two       three      four
# 1         NA    M  0.80418951 0.8921983
# 2  0.1836433    O -0.05710677        NA
# 3 -0.8356286    L  0.50360797 0.3899895
# 4         NA    E          NA        NA
# 5  0.3295078    S          NA 0.9606180
# 6 -0.8204684 <NA> -1.28459935 0.4346595

Here's our replacement:

dat[["four"]][is.na(dat[["four"]])] <- 0
head(dat)
#          one  two       three      four
# 1         NA    M  0.80418951 0.8921983
# 2  0.1836433    O -0.05710677 0.0000000
# 3 -0.8356286    L  0.50360797 0.3899895
# 4         NA    E          NA 0.0000000
# 5  0.3295078    S          NA 0.9606180
# 6 -0.8204684 <NA> -1.28459935 0.4346595

Alternatively, you can, of course, write dat$four[is.na(dat$four)] <- 0

How to sort an ArrayList?

With Eclipse Collections you could create a primitive double list, sort it and then reverse it to put it in descending order. This approach would avoid boxing the doubles.

MutableDoubleList doubleList =
    DoubleLists.mutable.with(
        0.5, 0.2, 0.9, 0.1, 0.1, 0.1, 0.54, 0.71,
        0.71, 0.71, 0.92, 0.12, 0.65, 0.34, 0.62)
        .sortThis().reverseThis();
doubleList.each(System.out::println);

If you want a List<Double>, then the following would work.

List<Double> objectList =
    Lists.mutable.with(
        0.5, 0.2, 0.9, 0.1, 0.1, 0.1, 0.54, 0.71,
        0.71, 0.71, 0.92, 0.12, 0.65, 0.34, 0.62)
        .sortThis(Collections.reverseOrder());
objectList.forEach(System.out::println);

If you want to keep the type as ArrayList<Double>, you can initialize and sort the list using the ArrayListIterate utility class as follows:

ArrayList<Double> arrayList =
    ArrayListIterate.sortThis(
            new ArrayList<>(objectList), Collections.reverseOrder());
arrayList.forEach(System.out::println);

Note: I am a committer for Eclipse Collections.

Testing web application on Mac/Safari when I don't own a Mac

If it's a major concern to start doing a lot of testing on a Mac, then I would definitely suggest buying a second hand Mac, or perhaps building a Hackintosh. The former gets you up and running quickly, the latter gives you a lot of power for the same price.

For just the odd piece of testing, running OS X in VMWare on your current PC is a cheaper option.

cv2.imshow command doesn't work properly in opencv-python

Doesn't need any additional methods after waitKey(0) (reply for above code)

import cv2
img=cv2.imread('C:/Python27/03323_HD.jpg')
cv2.imshow('ImageWindow',img)
cv2.waitKey(0)

Window appears -> Click on the Window & Click on Enter. Window will close.

Running code in main thread from another thread

One method I can think of is this:

1) Let the UI bind to the service.
2) Expose a method like the one below by the Binder that registers your Handler:

public void registerHandler(Handler handler) {
    mHandler = handler;
}

3) In the UI thread, call the above method after binding to the service:

mBinder.registerHandler(new Handler());

4) Use the handler in the Service's thread to post your task:

mHandler.post(runnable);

Java: Retrieving an element from a HashSet

One of the easiest ways is to convert to Array:

for(int i = 0; i < set.size(); i++) {
    System.out.println(set.toArray()[i]);
}

Twitter Bootstrap onclick event on buttons-radio

Don't use data-toggle attribute so that you can control the toggle behavior by yourself. So it will avoid 'race-condition'

my codes:

button group template (written in .erb, embedded ruby for ruby on rails):

<div class="btn-group" id="featuresFilter">
     <% _.each(features, function(feature) { %> <button class="btn btn-primary" data="<%= feature %>"><%= feature %></button> <% }); %>
</div>

and javascript:

onChangeFeatures = function(e){
        var el=e.target;
        $(el).button('toggle');

        var features=el.parentElement;
        var activeFeatures=$(features).find(".active");
        console.log(activeFeatures);
}

onChangeFeatures function will be triggered once the button is clicked.

Remove item from list based on condition

You could use Linq.

var prod = from p in prods
           where p.ID != 1
           select p;

Python: can't assign to literal

I got the same error: SyntaxError: can't assign to literal when I was trying to assign multiple variables in a single line.

I was assigning the values as shown below:

    score = 0, isDuplicate = None

When I shifted them to another line, it got resolved:

    score = 0
    isDuplicate = None

I don't know why python does not allow multiple assignments at the same line but that's how it is done.

There is one more way to asisgn it in single line ie. Separate them with a semicolon in place of comma. Check the code below:

score = 0 ; duplicate = None

Detecting EOF in C

Another issue is that you're reading with scanf("%f", &input); only. If the user types something that can't be interpreted as a C floating-point number, like "pi", the scanf() call will not assign anything to input, and won't progress from there. This means it would attempt to keep reading "pi", and failing.

Given the change to while(!feof(stdin)) which other posters are correctly recommending, if you typed "pi" in there would be an endless loop of printing out the former value of input and printing the prompt, but the program would never process any new input.

scanf() returns the number of assignments to input variables it made. If it made no assignment, that means it didn't find a floating-point number, and you should read through more input with something like char string[100];scanf("%99s", string);. This will remove the next string from the input stream (up to 99 characters, anyway - the extra char is for the null terminator on the string).

You know, this is reminding me of all the reasons I hate scanf(), and why I use fgets() instead and then maybe parse it using sscanf().

unsigned int vs. size_t

size_t is the size of a pointer.

So in 32 bits or the common ILP32 (integer, long, pointer) model size_t is 32 bits. and in 64 bits or the common LP64 (long, pointer) model size_t is 64 bits (integers are still 32 bits).

There are other models but these are the ones that g++ use (at least by default)

How to get the indexpath.row when an element is activated?

Swift 4 and 5

Method 1 using Protocol delegate

For example, you have a UITableViewCell with name MyCell

class MyCell: UITableViewCell {
    
    var delegate:MyCellDelegate!
    
    @IBAction private func myAction(_ sender: UIButton){
        delegate.didPressButton(cell: self)
    }
}

Now create a protocol

protocol MyCellDelegate {
    func didPressButton(cell: UITableViewCell)
}

Next step, create an Extension of UITableView

extension UITableView {
    func returnIndexPath(cell: UITableViewCell) -> IndexPath?{
        guard let indexPath = self.indexPath(for: cell) else {
            return nil
        }
        return indexPath
    }
}

In your UIViewController implement the protocol MyCellDelegate

class ViewController: UIViewController, MyCellDelegate {
     
    func didPressButton(cell: UITableViewCell) {
        if let indexpath = self.myTableView.returnIndexPath(cell: cell) {
              print(indexpath)
        }
    }
}

Method 2 using closures

In UIViewController

override func viewDidLoad() {
        super.viewDidLoad()
       //using the same `UITableView extension` get the IndexPath here
        didPressButton = { cell in
            if let indexpath = self.myTableView.returnIndexPath(cell: cell) {
                  print(indexpath)
            }
        }
    }
 var didPressButton: ((UITableViewCell) -> Void)

class MyCell: UITableViewCell {

    @IBAction private func myAction(_ sender: UIButton){
        didPressButton(self)
    }
}

Note:- if you want to get UICollectionView indexPath you can use this UICollectionView extension and repeat the above steps

extension UICollectionView {
    func returnIndexPath(cell: UICollectionViewCell) -> IndexPath?{
        guard let indexPath = self.indexPath(for: cell) else {
            return nil
        }
        return indexPath
    }
}

Split string into array

ES6 :

const array = [...entry]; // entry="i am" => array=["i"," ","a","m"]

Linq : select value in a datatable column

I notice others have given the non-lambda syntax so just to have this complete I'll put in the lambda syntax equivalent:

Non-lambda (as per James's post):

var name = from i in DataContext.MyTable
           where i.ID == 0
           select i.Name

Equivalent lambda syntax:

var name = DataContext.MyTable.Where(i => i.ID == 0)
                              .Select(i => new { Name = i.Name });

There's not really much practical difference, just personal opinion on which you prefer.

How can I wrap or break long text/word in a fixed width span?

Just to extend the pratical scope of the question and as an appendix to the given answers: Sometimes one might find it necessary to specify the selectors a little bit more.

By defining the the full span as display:inline-block you might have a hard time displaying images.

Therefore I prefer to define a span like so:

span {
  display:block;
  width:150px;
  word-wrap:break-word;      
}
p span, a span,
h1 span, h2 span, h3 span, h4 span, h5 span {
  display:inline-block;
}
img{
  display:block;
}

Jquery open popup on button click for bootstrap

Below mentioned link gives the clear explanation with example.

http://www.aspsnippets.com/Articles/Open-Show-jQuery-UI-Dialog-Modal-Popup-on-Button-Click.aspx

Code from the same link

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/blitzer/jquery-ui.css"
    rel="stylesheet" type="text/css" />
<script type="text/javascript">
    $(function () {
        $("#dialog").dialog({
            modal: true,
            autoOpen: false,
            title: "jQuery Dialog",
            width: 300,
            height: 150
        });
        $("#btnShow").click(function () {
            $('#dialog').dialog('open');
        });
    });
</script>
<input type="button" id="btnShow" value="Show Popup" />
<div id="dialog" style="display: none" align = "center">
    This is a jQuery Dialog.
</div>

Spring Boot: How can I set the logging level with application.properties?

For the records: the official documentation, as for Spring Boot v1.2.0.RELEASE and Spring v4.1.3.RELEASE:

If the only change you need to make to logging is to set the levels of various loggers then you can do that in application.properties using the "logging.level" prefix, e.g.

logging.level.org.springframework.web: DEBUG logging.level.org.hibernate: ERROR

You can also set the location of a file to log to (in addition to the console) using "logging.file".

To configure the more fine-grained settings of a logging system you need to use the native configuration format supported by the LoggingSystem in question. By default Spring Boot picks up the native configuration from its default location for the system (e.g. classpath:logback.xml for Logback), but you can set the location of the config file using the "logging.config" property.

Closing Applications

What role do they play when exiting an application in C#?

The same as every other application. Basically they get returned to the caller. Irrelvant if ythe start was an iicon double click. Relevant is the call is a batch file that decides whether the app worked on the return code. SO, unless you write a program that needs this, the return dcode IS irrelevant.

But what is the difference?

One comes from environment one from the System.Windows.Forms?.Application. Functionall there should not bbe a lot of difference.

Android studio 3.0: Unable to resolve dependency for :app@dexOptions/compileClasspath': Could not resolve project :animators

Solution:

Dowload the ultimate version of Gradle

http://services.gradle.org/distributions/

gradle-4.x-rc-1-all.zip.sha256 09-Jan-2018 01:15 +0000 64.00B

Unzip the distribution

Go to Android Studio -> File -> Settings -> Gradle -> Use local gradle distribution Search the file and OK

In the gradle:app write this, implementation(path: ':animators', configuration: 'default')

dependencies {
   .
   .
   .


    implementation project(path: ':animators', configuration: 'default')


}

Center a 'div' in the middle of the screen, even when the page is scrolled up or down?

Change the position attribute to fixed instead of absolute.

How do you embed binary data in XML?

While the other answers are mostly fine, you could try another, more space-efficient, encoding method like yEnc. (yEnc wikipedia link) With yEnc also get checksum capability right "out of the box". Read and links below. Of course, because XML does not have a native yEnc type your XML schema should be updated to properly describe the encoded node.

Why: Due to the encoding strategies base64/63, uuencode et al. encodings increase the amount of data (overhead) you need to store and transfer by roughly 40% (vs. yEnc's 1-2%). Depending on what you're encoding, 40% overhead could be/become an issue.


yEnc - Wikipedia abstract: https://en.wikipedia.org/wiki/YEnc yEnc is a binary-to-text encoding scheme for transferring binary files in messages on Usenet or via e-mail. ... An additional advantage of yEnc over previous encoding methods, such as uuencode and Base64, is the inclusion of a CRC checksum to verify that the decoded file has been delivered intact. ?

html/css buttons that scroll down to different div sections on a webpage

There is a much easier way to get the smooth scroll effect without javascript. In your CSS just target the entire html tag and give it scroll-behavior: smooth;

_x000D_
_x000D_
html {_x000D_
  scroll-behavior: smooth;_x000D_
 }_x000D_
 _x000D_
 a {_x000D_
  text-decoration: none;_x000D_
  color: black;_x000D_
 } _x000D_
 _x000D_
 #down {_x000D_
  margin-top: 100%;_x000D_
  padding-bottom: 25%;_x000D_
 } 
_x000D_
<html>_x000D_
  <a href="#down">Click Here to Smoothly Scroll Down</a>_x000D_
  <div id="down">_x000D_
    <h1>You are down!</h1>_x000D_
  </div>_x000D_
</html
_x000D_
_x000D_
_x000D_

The "scroll-behavior" is telling the page how it should scroll and is so much easier than using javascript. Javascript will give you more options on speed and the smoothness but this will deliver without all of the confusing code.

Laravel 5.1 API Enable Cors

barryvdh/laravel-cors works perfectly with Laravel 5.1 with just a few key points in enabling it.

  1. After adding it as a composer dependency, make sure you have published the CORS config file and adjusted the CORS headers as you want them. Here is how mine look in app/config/cors.php

    <?php
    
    return [
    
        'supportsCredentials' => true,
        'allowedOrigins' => ['*'],
        'allowedHeaders' => ['*'],
        'allowedMethods' => ['GET', 'POST', 'PUT',  'DELETE'],
        'exposedHeaders' => ['DAV', 'content-length', 'Allow'],
        'maxAge' => 86400,
        'hosts' => [],
    ];
    
  2. After this, there is one more step that's not mentioned in the documentation, you have to add the CORS handler 'Barryvdh\Cors\HandleCors' in the App kernel. I prefer to use it in the global middleware stack. Like this

    /**
     * The application's global HTTP middleware stack.
     *
     * @var array
     */
    protected $middleware = [
        'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
        'Illuminate\Cookie\Middleware\EncryptCookies',
        'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
        'Illuminate\Session\Middleware\StartSession',
        'Illuminate\View\Middleware\ShareErrorsFromSession',
    
        'Barryvdh\Cors\HandleCors',
    
    ];
    

    But its up to you to use it as a route middleware and place on specific routes.

This should make the package work with L5.1

How to discard local commits in Git?

I had to do a :

git checkout -b master

as git said that it doesn't exists, because it's been wipe with the

git -D master

MySQL 1062 - Duplicate entry '0' for key 'PRIMARY'

You need to specify the primary key as auto-increment

CREATE TABLE `momento_distribution`
  (
     `momento_id`       INT(11) NOT NULL AUTO_INCREMENT,
     `momento_idmember` INT(11) NOT NULL,
     `created_at`       DATETIME DEFAULT NULL,
     `updated_at`       DATETIME DEFAULT NULL,
     `unread`           TINYINT(1) DEFAULT '1',
     `accepted`         VARCHAR(10) NOT NULL DEFAULT 'pending',
     `ext_member`       VARCHAR(255) DEFAULT NULL,
     PRIMARY KEY (`momento_id`, `momento_idmember`),
     KEY `momento_distribution_FI_2` (`momento_idmember`),
     KEY `accepted` (`accepted`, `ext_member`)
  )
ENGINE=InnoDB
DEFAULT CHARSET=latin1$$

With regards to comment below, how about:

ALTER TABLE `momento_distribution`
  CHANGE COLUMN `id` `id` INT(11) NOT NULL AUTO_INCREMENT,
  DROP PRIMARY KEY,
  ADD PRIMARY KEY (`id`);

A PRIMARY KEY is a unique index, so if it contains duplicates, you cannot assign the column to be unique index, so you may need to create a new column altogether

Change a HTML5 input's placeholder color with CSS

try this code for different input element different style

your css selector::-webkit-input-placeholder { /*for webkit */
    color:#909090;
    opacity:1;
}
 your css selector:-moz-placeholder { /*for mozilla */
    color:#909090;
    opacity:1;
}
 your css selector:-ms-input-placeholder { /*for for internet exprolar */ 
   color:#909090;
   opacity:1;
}

example 1:

input[type="text"]::-webkit-input-placeholder { /*for webkit */
    color: red;
    opacity:1;
}
 input[type="text"]:-moz-placeholder { /*for mozilla */
    color: red;
    opacity:1;
}
 input[type="text"]:-ms-input-placeholder { /*for for internet exprolar */ 
   color: red;
   opacity:1;
}

example 2:

input[type="email"]::-webkit-input-placeholder { /*for webkit */
    color: gray;
    opacity:1;
}
 input[type="email"]:-moz-placeholder { /*for mozilla */
    color: gray;
    opacity:1;
}
 input[type="email"]:-ms-input-placeholder { /*for for internet exprolar */ 
   color: gray;
   }

Send file via cURL from form POST in PHP

It works for me when sending an attachment to Mercadolibre, through its messaging system.

The anwswer https://stackoverflow.com/a/35227055/7656744

$target_url = "http://server:port/xxxxx.php";           
$fname = 'file.txt';   
$cfile = new CURLFile(realpath($fname));

    $post = array (
              'file' => $cfile
              );    

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $target_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");   
curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type: multipart/form-data'));
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);   
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);  
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

$result = curl_exec ($ch);

if ($result === FALSE) {
    echo "Error sending" . $fname .  " " . curl_error($ch);
    curl_close ($ch);
}else{
    curl_close ($ch);
    echo  "Result: " . $result;
}   

Position Relative vs Absolute?

Relative vs Absolute:

  • Difference: relative to itself, relative to the nearest positioned ancestor.
  • Difference: Other elements arounds it honour its old existence, Other elements around it DO NOT honour its old existence.
  • Similarity: Other elements arounds it DO NOT honour its new existence, Other elements around it DO NOT honour its new existence.

Setting a property with an EventTrigger

Just create your own action.

namespace WpfUtil
{
    using System.Reflection;
    using System.Windows;
    using System.Windows.Interactivity;


    /// <summary>
    /// Sets the designated property to the supplied value. TargetObject
    /// optionally designates the object on which to set the property. If
    /// TargetObject is not supplied then the property is set on the object
    /// to which the trigger is attached.
    /// </summary>
    public class SetPropertyAction : TriggerAction<FrameworkElement>
    {
        // PropertyName DependencyProperty.

        /// <summary>
        /// The property to be executed in response to the trigger.
        /// </summary>
        public string PropertyName
        {
            get { return (string)GetValue(PropertyNameProperty); }
            set { SetValue(PropertyNameProperty, value); }
        }

        public static readonly DependencyProperty PropertyNameProperty
            = DependencyProperty.Register("PropertyName", typeof(string),
            typeof(SetPropertyAction));


        // PropertyValue DependencyProperty.

        /// <summary>
        /// The value to set the property to.
        /// </summary>
        public object PropertyValue
        {
            get { return GetValue(PropertyValueProperty); }
            set { SetValue(PropertyValueProperty, value); }
        }

        public static readonly DependencyProperty PropertyValueProperty
            = DependencyProperty.Register("PropertyValue", typeof(object),
            typeof(SetPropertyAction));


        // TargetObject DependencyProperty.

        /// <summary>
        /// Specifies the object upon which to set the property.
        /// </summary>
        public object TargetObject
        {
            get { return GetValue(TargetObjectProperty); }
            set { SetValue(TargetObjectProperty, value); }
        }

        public static readonly DependencyProperty TargetObjectProperty
            = DependencyProperty.Register("TargetObject", typeof(object),
            typeof(SetPropertyAction));


        // Private Implementation.

        protected override void Invoke(object parameter)
        {
            object target = TargetObject ?? AssociatedObject;
            PropertyInfo propertyInfo = target.GetType().GetProperty(
                PropertyName,
                BindingFlags.Instance|BindingFlags.Public
                |BindingFlags.NonPublic|BindingFlags.InvokeMethod);

            propertyInfo.SetValue(target, PropertyValue);
        }
    }
}

In this case I'm binding to a property called DialogResult on my viewmodel.

<Grid>

    <Button>
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="Click">
                <wpf:SetPropertyAction PropertyName="DialogResult" TargetObject="{Binding}"
                                       PropertyValue="{x:Static mvvm:DialogResult.Cancel}"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
        Cancel
    </Button>

</Grid>

Why do we always prefer using parameters in SQL statements?

Old post but wanted to ensure newcomers are aware of Stored procedures.

My 10¢ worth here is that if you are able to write your SQL statement as a stored procedure, that in my view is the optimum approach. I ALWAYS use stored procs and never loop through records in my main code. For Example: SQL Table > SQL Stored Procedures > IIS/Dot.NET > Class.

When you use stored procedures, you can restrict the user to EXECUTE permission only, thus reducing security risks.

Your stored procedure is inherently paramerised, and you can specify input and output parameters.

The stored procedure (if it returns data via SELECT statement) can be accessed and read in the exact same way as you would a regular SELECT statement in your code.

It also runs faster as it is compiled on the SQL Server.

Did I also mention you can do multiple steps, e.g. update a table, check values on another DB server, and then once finally finished, return data to the client, all on the same server, and no interaction with the client. So this is MUCH faster than coding this logic in your code.

android: how to align image in the horizontal center of an imageview?

Give width of image as match_parent and height as required, say 300 dp.

<ImageView
    android:id = "@+id/imgXYZ"
    android:layout_width = "match_parent"
    android:layout_height = "300dp"
    android:src="@drawable/imageXYZ"
    />

phantomjs not waiting for "full" page load

In my program, I use some logic to judge if it was onload: watching it's network request, if there was no new request on past 200ms, I treat it onload.

Use this, after onLoadFinish().

function onLoadComplete(page, callback){
    var waiting = [];  // request id
    var interval = 200;  //ms time waiting new request
    var timer = setTimeout( timeout, interval);
    var max_retry = 3;  //
    var counter_retry = 0;

    function timeout(){
        if(waiting.length && counter_retry < max_retry){
            timer = setTimeout( timeout, interval);
            counter_retry++;
            return;
        }else{
            try{
                callback(null, page);
            }catch(e){}
        }
    }

    //for debug, log time cost
    var tlogger = {};

    bindEvent(page, 'request', function(req){
        waiting.push(req.id);
    });

    bindEvent(page, 'receive', function (res) {
        var cT = res.contentType;
        if(!cT){
            console.log('[contentType] ', cT, ' [url] ', res.url);
        }
        if(!cT) return remove(res.id);
        if(cT.indexOf('application') * cT.indexOf('text') != 0) return remove(res.id);

        if (res.stage === 'start') {
            console.log('!!received start: ', res.id);
            //console.log( JSON.stringify(res) );
            tlogger[res.id] = new Date();
        }else if (res.stage === 'end') {
            console.log('!!received end: ', res.id, (new Date() - tlogger[res.id]) );
            //console.log( JSON.stringify(res) );
            remove(res.id);

            clearTimeout(timer);
            timer = setTimeout(timeout, interval);
        }

    });

    bindEvent(page, 'error', function(err){
        remove(err.id);
        if(waiting.length === 0){
            counter_retry = 0;
        }
    });

    function remove(id){
        var i = waiting.indexOf( id );
        if(i < 0){
            return;
        }else{
            waiting.splice(i,1);
        }
    }

    function bindEvent(page, evt, cb){
        switch(evt){
            case 'request':
                page.onResourceRequested = cb;
                break;
            case 'receive':
                page.onResourceReceived = cb;
                break;
            case 'error':
                page.onResourceError = cb;
                break;
            case 'timeout':
                page.onResourceTimeout = cb;
                break;
        }
    }
}

Key value pairs using JSON

A "JSON object" is actually an oxymoron. JSON is a text format describing an object, not an actual object, so data can either be in the form of JSON, or deserialised into an object.

The JSON for that would look like this:

{"KEY1":{"NAME":"XXXXXX","VALUE":100},"KEY2":{"NAME":"YYYYYYY","VALUE":200},"KEY3":{"NAME":"ZZZZZZZ","VALUE":500}}

Once you have parsed the JSON into a Javascript object (called data in the code below), you can for example access the object for KEY2 and it's properties like this:

var obj = data.KEY2;
alert(obj.NAME);
alert(obj.VALUE);

If you have the key as a string, you can use index notation:

var key = 'KEY3';
var obj = data[key];

How can I get the file name from request.FILES?

request.FILES['filename'].name

From the request documentation.

If you don't know the key, you can iterate over the files:

for filename, file in request.FILES.iteritems():
    name = request.FILES[filename].name

How to name variables on the fly?

FAQ says:

If you have

varname <- c("a", "b", "d")

you can do

get(varname[1]) + 2

for

a + 2

or

assign(varname[1], 2 + 2)

for

a <- 2 + 2

So it looks like you use GET when you want to evaluate a formula that uses a variable (such as a concatenate), and ASSIGN when you want to assign a value to a pre-declared variable.

Syntax for assign: assign(x, value)

x: a variable name, given as a character string. No coercion is done, and the first element of a character vector of length greater than one will be used, with a warning.

value: value to be assigned to x.

Android EditText for password with android:hint

android:hint="Enter your question" or something like this must work. I am using Relative layout with EditText as If you want to use password,say android:inputType="textPassword" for hiding characters and "textVisiblePassword" for showing what you enter as password.

Write to rails console

As other have said, you want to use either puts or p. Why? Is that magic?

Actually not. A rails console is, under the hood, an IRB, so all you can do in IRB you will be able to do in a rails console. Since for printing in an IRB we use puts, we use the same command for printing in a rails console.

You can actually take a look at the console code in the rails source code. See the require of irb? :)

Java 8 List<V> into Map<K, V>

This can be done in 2 ways. Let person be the class we are going to use to demonstrate it.

public class Person {

    private String name;
    private int age;

    public String getAge() {
        return age;
    }
}

Let persons be the list of Persons to be converted to the map

1.Using Simple foreach and a Lambda Expression on the List

Map<Integer,List<Person>> mapPersons = new HashMap<>();
persons.forEach(p->mapPersons.put(p.getAge(),p));

2.Using Collectors on Stream defined on the given List.

 Map<Integer,List<Person>> mapPersons = 
           persons.stream().collect(Collectors.groupingBy(Person::getAge));

Edit a text file on the console using Powershell

Well there are thousand ways to edit a Text file on windows 7. Usually people Install Sublime , Atom and Notepad++ as an editor. For command line , I think the Basic Edit command (by the way which does not work on 64 bit computers) is good;Alternatively I find type con > filename as a very Applaudable method.If windows is newly installed and One wants to avoid Notepad. This might be it!! The perfect usage of Type as an editor :)

reference of the Image:- https://www.codeproject.com/Articles/34280/How-to-Write-Applet-Code

How to do an update + join in PostgreSQL?

Here's a simple SQL that updates Mid_Name on the Name3 table using the Middle_Name field from Name:

update name3
set mid_name = name.middle_name
from name
where name3.person_id = name.person_id;

Where to install Android SDK on Mac OS X?

The easiest (and standard) way to install Android SDK under OS X is to use brew.

brew install android-sdk

If you do not have homebrew, here's how to get it.

This will install Android SDK into /usr/local/Cellar/android-sdk/ and, at this moment, this is the best location to install it.

How to find locked rows in Oracle

Rather than locks, I suggest you look at long-running transactions, using v$transaction. From there you can join to v$session, which should give you an idea about the UI (try the program and machine columns) as well as the user.

Most Pythonic way to provide global configuration variables in config.py?

please check out the IPython configuration system, implemented via traitlets for the type enforcement you are doing manually.

Cut and pasted here to comply with SO guidelines for not just dropping links as the content of links changes over time.

traitlets documentation

Here are the main requirements we wanted our configuration system to have:

Support for hierarchical configuration information.

Full integration with command line option parsers. Often, you want to read a configuration file, but then override some of the values with command line options. Our configuration system automates this process and allows each command line option to be linked to a particular attribute in the configuration hierarchy that it will override.

Configuration files that are themselves valid Python code. This accomplishes many things. First, it becomes possible to put logic in your configuration files that sets attributes based on your operating system, network setup, Python version, etc. Second, Python has a super simple syntax for accessing hierarchical data structures, namely regular attribute access (Foo.Bar.Bam.name). Third, using Python makes it easy for users to import configuration attributes from one configuration file to another. Fourth, even though Python is dynamically typed, it does have types that can be checked at runtime. Thus, a 1 in a config file is the integer ‘1’, while a '1' is a string.

A fully automated method for getting the configuration information to the classes that need it at runtime. Writing code that walks a configuration hierarchy to extract a particular attribute is painful. When you have complex configuration information with hundreds of attributes, this makes you want to cry.

Type checking and validation that doesn’t require the entire configuration hierarchy to be specified statically before runtime. Python is a very dynamic language and you don’t always know everything that needs to be configured when a program starts.

To acheive this they basically define 3 object classes and their relations to each other:

1) Configuration - basically a ChainMap / basic dict with some enhancements for merging.

2) Configurable - base class to subclass all things you'd wish to configure.

3) Application - object that is instantiated to perform a specific application function, or your main application for single purpose software.

In their words:

Application: Application

An application is a process that does a specific job. The most obvious application is the ipython command line program. Each application reads one or more configuration files and a single set of command line options and then produces a master configuration object for the application. This configuration object is then passed to the configurable objects that the application creates. These configurable objects implement the actual logic of the application and know how to configure themselves given the configuration object.

Applications always have a log attribute that is a configured Logger. This allows centralized logging configuration per-application. Configurable: Configurable

A configurable is a regular Python class that serves as a base class for all main classes in an application. The Configurable base class is lightweight and only does one things.

This Configurable is a subclass of HasTraits that knows how to configure itself. Class level traits with the metadata config=True become values that can be configured from the command line and configuration files.

Developers create Configurable subclasses that implement all of the logic in the application. Each of these subclasses has its own configuration information that controls how instances are created.

How to read PDF files using Java?

PDFBox is the best library I've found for this purpose, it's comprehensive and really quite easy to use if you're just doing basic text extraction. Examples can be found here.

It explains it on the page, but one thing to watch out for is that the start and end indexes when using setStartPage() and setEndPage() are both inclusive. I skipped over that explanation first time round and then it took me a while to realise why I was getting more than one page back with each call!

Itext is another alternative that also works with C#, though I've personally never used it. It's more low level than PDFBox, so less suited to the job if all you need is basic text extraction.

iOS detect if user is on an iPad

You can also use this

#define IPAD UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad
...
if (IPAD) {
   // iPad
} else {
   // iPhone / iPod Touch
}

No 'Access-Control-Allow-Origin' header is present on the requested resource error

If its calling spring boot service. you can handle it using below code.

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("*")
                    .allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS")
                    .allowedHeaders("*", "Access-Control-Allow-Headers", "origin", "Content-type", "accept", "x-requested-with", "x-requested-by") //What is this for?
                    .allowCredentials(true);
        }
    };
}

Jquery mouseenter() vs mouseover()

This example demonstrates the difference between the mousemove, mouseenter and mouseover events:

https://jsfiddle.net/z8g613yd/

HTML:

<div onmousemove="myMoveFunction()">
    <p>onmousemove: <br> <span id="demo">Mouse over me!</span></p>
</div>

<div onmouseenter="myEnterFunction()">
    <p>onmouseenter: <br> <span id="demo2">Mouse over me!</span></p>
</div>

<div onmouseover="myOverFunction()">
    <p>onmouseover: <br> <span id="demo3">Mouse over me!</span></p>
</div>

CSS:

div {
    width: 200px;
    height: 100px;
    border: 1px solid black;
    margin: 10px;
    float: left;
    padding: 30px;
    text-align: center;
    background-color: lightgray;
}

p {
    background-color: white;
    height: 50px;
}

p span {
    background-color: #86fcd4;
    padding: 0 20px;
}

JS:

var x = 0;
var y = 0;
var z = 0;

function myMoveFunction() {
    document.getElementById("demo").innerHTML = z += 1;
}

function myEnterFunction() {
    document.getElementById("demo2").innerHTML = x += 1;
}

function myOverFunction() {
    document.getElementById("demo3").innerHTML = y += 1;
}
  • onmousemove : occurs every time the mouse pointer is moved over the div element.
  • onmouseenter : only occurs when the mouse pointer enters the div element.
  • onmouseover : occurs when the mouse pointer enters the div element, and its child elements (p and span).

Get first 100 characters from string, respecting full words

Sure. The easiest is probably to write a wrapper around preg_match:

function limitString($string, $limit = 100) {
    // Return early if the string is already shorter than the limit
    if(strlen($string) < $limit) {return $string;}

    $regex = "/(.{1,$limit})\b/";
    preg_match($regex, $string, $matches);
    return $matches[1];
}

EDIT : Updated to not ALWAYS include a space as the last character in the string

Location of hibernate.cfg.xml in project?

try below code it will solve your problem.

Configuration  configuration = new Configuration().configure("/logic/hibernate.cfg.xml");

How do I draw a grid onto a plot in Python?

Here is a small example how to add a matplotlib grid in Gtk3 with Python 2 (not working in Python 3):

#!/usr/bin/env python
#-*- coding: utf-8 -*-

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from matplotlib.figure import Figure
from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas

win = Gtk.Window()
win.connect("delete-event", Gtk.main_quit)
win.set_title("Embedding in GTK3")

f = Figure(figsize=(1, 1), dpi=100)
ax = f.add_subplot(111)
ax.grid()

canvas = FigureCanvas(f)
canvas.set_size_request(400, 400)
win.add(canvas)

win.show_all()
Gtk.main()

enter image description here

Angularjs $http post file and form data

You can also upload using HTML5. You can use this AJAX uploader.

The JS code is basically:

  $scope.doPhotoUpload = function () {
    // ..
    var myUploader = new uploader(document.getElementById('file_upload_element_id'), options);
    myUploader.send();
    // ..
  }

Which reads from an HTML input element

<input id="file_upload_element_id" type="file" onchange="angular.element(this).scope().doPhotoUpload()">