Rectangle 27 20

Step #2: Create an instance of Select2

<input name="mySelect2" type="hidden" id="mySelect2">
$("#mySelect2").select2({
      placeholder: "My Select 2",
      multiple: false,
      minimumInputLength: 1,
      ajax: {
          url: "/elements/all",
          dataType: 'json',
          quietMillis: 250,
          data: function(term, page) {
              return {
                  q: term,
              };
          },
          results: function(data, page) {
              return {results: data};
          },
          cache: true
      },
      formatResult: function(element){
          return element.text + ' (' + element.id + ')';
      },
      formatSelection: function(element){
          return element.text + ' (' + element.id + ')';
      },
      escapeMarkup: function(m) {
          return m;
      }
});
$("#mySelect2").select2('data', { id:"elementID", text: "Hello!"});

If you use select2 without AJAX you can do as follow:

<select name="mySelect2" id="mySelect2">
  <option value="0">One</option>
  <option value="1">Two</option>
  <option value="2">Three</option>
</select>
/* //////////// "One" will be the selected option */
$('[name=mySelect2]').val("0");

You can also do so:

$("#mySelect2").select2("val", "0");

For select2 v4 you can append directly an option/s as follow:

<select id="myMultipleSelect2" multiple="" name="myMultipleSelect2[]">
    <option value="TheID" selected="selected">The text</option>                                                                   
</select>

Or with JQuery:

var $newOption = $("<option></option>").val("TheID").text("The text")

$("#myMultipleSelect2").append($newOption).trigger('change');
$("select123455").val(5).trigger('change');

This won't work on Select2 v4 - probably why the downvote. It looks like a bug.

javascript - How to set selected value of jquery select2? - Stack Over...

javascript php jquery ajax jquery-select2
Rectangle 27 30

What is the difference between a source template and an instance templ...

The fact that Angular allows DOM manipulation means that the input markup into the compilation process sometimes differ from the output. Particularly, some input markup may be cloned a few times (like with ng-repeat) before being rendered to the DOM.

Angular terminology is a bit inconsistent, but it still distinguishes between two types of markups:

  • Source template - the markup to be cloned, if needed. If cloned, this markup will not be rendered to the DOM.
  • Instance template - the actual markup to be rendered to the DOM. If cloning is involved, each instance will be a clone.

The following markup demonstrates this:

<div ng-repeat="i in [0,1,2]">
    <my-directive>{{i}}</my-directive>
</div>
<my-directive>{{i}}</my-directive>

which serves as the source template.

But as it is wrapped within an ng-repeat directive, this source template will be cloned (3 times in our case). These clones are instance template, each will appear in the DOM and be bound to the relevant scope.

angularjs - Angular directives - when and how to use compile, controll...

angularjs angularjs-directive
Rectangle 27 29

What is the difference between a source template and an instance templ...

The fact that Angular allows DOM manipulation means that the input markup into the compilation process sometimes differ from the output. Particularly, some input markup may be cloned a few times (like with ng-repeat) before being rendered to the DOM.

Angular terminology is a bit inconsistent, but it still distinguishes between two types of markups:

  • Source template - the markup to be cloned, if needed. If cloned, this markup will not be rendered to the DOM.
  • Instance template - the actual markup to be rendered to the DOM. If cloning is involved, each instance will be a clone.

The following markup demonstrates this:

<div ng-repeat="i in [0,1,2]">
    <my-directive>{{i}}</my-directive>
</div>
<my-directive>{{i}}</my-directive>

which serves as the source template.

But as it is wrapped within an ng-repeat directive, this source template will be cloned (3 times in our case). These clones are instance template, each will appear in the DOM and be bound to the relevant scope.

angularjs - Angular directives - when and how to use compile, controll...

angularjs angularjs-directive
Rectangle 27 29

What is the difference between a source template and an instance templ...

The fact that Angular allows DOM manipulation means that the input markup into the compilation process sometimes differ from the output. Particularly, some input markup may be cloned a few times (like with ng-repeat) before being rendered to the DOM.

Angular terminology is a bit inconsistent, but it still distinguishes between two types of markups:

  • Source template - the markup to be cloned, if needed. If cloned, this markup will not be rendered to the DOM.
  • Instance template - the actual markup to be rendered to the DOM. If cloning is involved, each instance will be a clone.

The following markup demonstrates this:

<div ng-repeat="i in [0,1,2]">
    <my-directive>{{i}}</my-directive>
</div>
<my-directive>{{i}}</my-directive>

which serves as the source template.

But as it is wrapped within an ng-repeat directive, this source template will be cloned (3 times in our case). These clones are instance template, each will appear in the DOM and be bound to the relevant scope.

angularjs - Angular directives - when and how to use compile, controll...

angularjs angularjs-directive
Rectangle 27 18

Instances don't have names. By the time the global name ThisObject gets bound to the instance created by evaluating the SomeObject constructor, the constructor has finished running.

If you want an object to have a name, just pass the name along in the constructor.

def __init__(self, name):
    self.name = name

Liked this answer best, since I'm already aware that there aren't true variables in Python(there really should still be a way to grab the name bound to an instance, but that's another argument for another day I guess). It's logical that it wouldn't have the name bound to the instance, so I guess for the time being I'll just require 'def_name' instead of 'def_name=None'

There is no such thing as a "variable" by your definition. In what language can some object be bound to only one name?

@JonathanFeinberg My hunch is OP is a Matlab native. This kind of thing is really easy in Matlab...it is awful on (computer) memory, easy on programmer.

python - Getting an instance name inside class __init__() - Stack Over...

python class variables object instance
Rectangle 27 18

Instances don't have names. By the time the global name ThisObject gets bound to the instance created by evaluating the SomeObject constructor, the constructor has finished running.

If you want an object to have a name, just pass the name along in the constructor.

def __init__(self, name):
    self.name = name

Liked this answer best, since I'm already aware that there aren't true variables in Python(there really should still be a way to grab the name bound to an instance, but that's another argument for another day I guess). It's logical that it wouldn't have the name bound to the instance, so I guess for the time being I'll just require 'def_name' instead of 'def_name=None'

There is no such thing as a "variable" by your definition. In what language can some object be bound to only one name?

@JonathanFeinberg My hunch is OP is a Matlab native. This kind of thing is really easy in Matlab...it is awful on (computer) memory, easy on programmer.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

python - Getting an instance name inside class __init__() - Stack Over...

python class variables object instance
Rectangle 27 81

Instance initializers are a useful alternative to instance variable initializers whenever:

But in a class that had multiple constructors, you would have to repeat the code in each constructor. With an instance initializer, you can just write the code once, and it will be executed no matter what constructor is used to create the object. Instance initializers are also useful in anonymous inner classes, which can't declare any constructors at all.

On the other hand you can write code once in one constructor and just call it from all other constructors. But anonymous inner classes make a good point.

You can call it from other constructors - but then you are again repeating the call. If you add a new constructor, you have to remember to add the call to it. Not so with an instance initializer.

@talonx, I do agree with your argument about forgetting, but utilizing default behavior is equally dangerous. When a supporter is reading through a constructor in legacy code, one wouldn't always remember to check for possible instance initializers. Whereas an explicitly used init() will stand out.

@javamonkey79: Are you saying that if I pick constructor over instance initializer for my class, the only place where instance initializer is useful is when working with anonymous classes?

@Assambar You cannot assign final fields in your init() method, but you can in an initializer block.

java - How is an instance initializer different from a constructor? - ...

java instantiation
Rectangle 27 401

A fix for this problem is to add swap or paging space to the instance.

Paging works by creating an area on your hard drive and using it for extra memory, this memory is much slower than normal memory however much more of it is available.

sudo /bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
sudo /sbin/mkswap /var/swap.1
sudo chmod 600 /var/swap.1
sudo /sbin/swapon /var/swap.1
/var/swap.1   swap    swap    defaults        0   0

Thanks! Really simple and great to know.

if means 'input file', of means 'output file', bs means 'block size' and count is the number of blocks you want to allocate you can read the man page of the command for more info: linux.die.net/man/1/dd

That dd command line means "copy from /dev/zero to /var/swap.1. Do that by reading 1024 blocks of size 1 megabyte". It's a quick way to create a 1GB file full of zeroes.

@ajtrichards original fstab line /var/swap.1 swap swap defaults 0 0, not the new one in the edited answer, was correct for me.

amazon web services - How do you add swap to an EC2 instance? - Stack ...

amazon-web-services amazon-ec2 out-of-memory
Rectangle 27 396

A fix for this problem is to add swap or paging space to the instance.

Paging works by creating an area on your hard drive and using it for extra memory, this memory is much slower than normal memory however much more of it is available.

sudo /bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
sudo /sbin/mkswap /var/swap.1
sudo chmod 600 /var/swap.1
sudo /sbin/swapon /var/swap.1
/var/swap.1   swap    swap    defaults        0   0

Thanks! Really simple and great to know.

if means 'input file', of means 'output file', bs means 'block size' and count is the number of blocks you want to allocate you can read the man page of the command for more info: linux.die.net/man/1/dd

That dd command line means "copy from /dev/zero to /var/swap.1. Do that by reading 1024 blocks of size 1 megabyte". It's a quick way to create a 1GB file full of zeroes.

@ajtrichards original fstab line /var/swap.1 swap swap defaults 0 0, not the new one in the edited answer, was correct for me.

amazon web services - How do you add swap to an EC2 instance? - Stack ...

amazon-web-services amazon-ec2 out-of-memory
Rectangle 27 22

Think about what aux is. What object will respond to aux? It's an instance method, which means that instances of classes that include ModName will respond to it. The ModName module itself is not an instance of such a class. This would also not work if you had defined ModName as a class you can't call an instance method without an instance.

Modules are very much like classes that can be mixed into other classes to add behavior. When a class mixes in a module, all of the module's instance methods become instance methods of the class. It's a way of implementing multiple inheritance.

They also serve as substitutes for namespaces, since each module defines a namespace. But that's somewhat unrelated. (Incidentally, classes also have their own namespaces, but making it a class implies that you'll create instances of it, so they're conceptually wrong for that purpose.)

One real-world use case for this is with Sinatra's helper method that takes a module and mixes it into requests. If your module methods do not rely on state (e.g. a function that formats a string passed into it) they may also be appropriate called externally as MyHelperModule.foo(bar). Using module_function (per the answer by @JPabloFernndez below) allows a single module 'instance' method to be accessed as the OP requests.

ruby - Instance methods in modules - Stack Overflow

ruby module instance
Rectangle 27 36

Its pretty simple. Assume that your classname is Car and the namespace is Vehicles, then pass the parameter as Vehicles.Car which returns object of type Car. Like this you can create any instance of any class dynamically.

If your Fully Qualified Name(ie, Vehicles.Car in this case) is in another assembly, the Type.GetType will be null. In such cases, you have loop through all assemblies and find the Type. For that you can use the below code

public object GetInstance(string strFullyQualifiedName)
{
     Type type = Type.GetType(strFullyQualifiedName);
     if (type != null)
         return Activator.CreateInstance(type);
     foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
     {
         type = asm.GetType(strFullyQualifiedName);
         if (type != null)
             return Activator.CreateInstance(type);
     }
     return null;
 }

Now if you want to call a parameterized constructor do the following

Activator.CreateInstance(t,17); // Incase you are calling a constructor of int type

instead of

Activator.CreateInstance(t);

How to use it without casting and how to do the cast from the given string??

@TaW - in order to use a class instance you will need to have some knowledge of what it is going to do - otherwise you won't be able to use it. The most common use case for this would be casting to some interface which give you a predefined contract. (This holds unless you're using dynamic code - see stackoverflow.com/a/2690661/904521)

c# - Create an instance of a class from a string - Stack Overflow

c# .net instantiation system.type
Rectangle 27 13

You can't create an instance of an interface

Correct. You create an instance of an object implementing an interface:

IAuditable myUser = new User();

No where in the code does it define which IAudit applies to which IAuditable

You can't do this directly with just one interface. You will need to rethink your design.

You can use a open generic type in the interface and implement it with closed types:

public interface IAudit<T> {
    DateTime DateCreated { get; set; }
}

public class UserAudit : IAudit<User> {
    public string UserName { get; set; }
    public DateTime DateCreated { get; set; }

    public UserAdit(User user) {
        UserName = user.UserName;
    }
}

I can't specify that the IAudit interface must have a constructor which takes an IAuditable

Correct, you can't. See here. You need to create such a constructor on the implementers.

Useful answer, useful info for OP, but still focuses too much on the c#/.net specifics to get an upvote from me ... for now. Tridus' addresses the real issue IMO. Still, useful info for OP.

c# - Creating an Instance of an Interface - Stack Overflow

c# interface
Rectangle 27 180

Swap should take place on the Instance Storage (ephemeral) disk and not an EBS device. Swapping will cause a lot of IO and will increase cost on EBS. EBS is also slower than the Instance Store and the Instance Store comes free with certain types of EC2 Instances.

It will usually be mounted to /mnt but if not run

sudo mount /dev/xvda2 /mnt

To then create a swap file on this device do the following for a 4GB swapfile

sudo dd if=/dev/zero of=/mnt/swapfile bs=1M count=4096

Make sure no other user can view the swap file

sudo chown root:root /mnt/swapfile
sudo chmod 600 /mnt/swapfile

Make and Flag as swap

sudo mkswap /mnt/swapfile
sudo swapon /mnt/swapfile

Add/Make sure the following are in your /etc/fstab

/dev/xvda2      /mnt    auto    defaults,nobootwait,comment=cloudconfig 0   2
/mnt/swapfile swap swap defaults 0 0
sudo swapon -a

To mount a file system one must specify the file system type. To find the file system the command is: $df -T This will show you the devices and their file systems. Mostly ext4. For me it was /dev/xvda1, not 2.

According to docs.aws.amazon.com/AWSEC2/latest/UserGuide/ it is not longer possible to add Instance stores to t1/t2 instances. After trying regardless, it would seem to be correct.

@alfetopito You can probably create a literal swapfile on an existing partition instead of adding another partition as swap. A nice guide for Centos 6 - digitalocean.com/community/tutorials/

amazon web services - How do you add swap to an EC2 instance? - Stack ...

amazon-web-services amazon-ec2 out-of-memory
Rectangle 27 178

Swap should take place on the Instance Storage (ephemeral) disk and not an EBS device. Swapping will cause a lot of IO and will increase cost on EBS. EBS is also slower than the Instance Store and the Instance Store comes free with certain types of EC2 Instances.

It will usually be mounted to /mnt but if not run

sudo mount /dev/xvda2 /mnt

To then create a swap file on this device do the following for a 4GB swapfile

sudo dd if=/dev/zero of=/mnt/swapfile bs=1M count=4096

Make sure no other user can view the swap file

sudo chown root:root /mnt/swapfile
sudo chmod 600 /mnt/swapfile

Make and Flag as swap

sudo mkswap /mnt/swapfile
sudo swapon /mnt/swapfile

Add/Make sure the following are in your /etc/fstab

/dev/xvda2      /mnt    auto    defaults,nobootwait,comment=cloudconfig 0   2
/mnt/swapfile swap swap defaults 0 0
sudo swapon -a

To mount a file system one must specify the file system type. To find the file system the command is: $df -T This will show you the devices and their file systems. Mostly ext4. For me it was /dev/xvda1, not 2.

According to docs.aws.amazon.com/AWSEC2/latest/UserGuide/ it is not longer possible to add Instance stores to t1/t2 instances. After trying regardless, it would seem to be correct.

@alfetopito You can probably create a literal swapfile on an existing partition instead of adding another partition as swap. A nice guide for Centos 6 - digitalocean.com/community/tutorials/

amazon web services - How do you add swap to an EC2 instance? - Stack ...

amazon-web-services amazon-ec2 out-of-memory
Rectangle 27 15

Python doesn't call the special methods, those with name surrounded by __ on the instance, but only on the class, apparently to improve performance. So there's no way to override __repr__() directly on an instance and make it work. Instead, you need to do something like so:

class A(object):
    def __repr__(self):
        return self._repr()
    def _repr(self):
        return object.__repr__(self)

Now you can override __repr__() on an instance by substituting _repr().

"Python doesn't call the special methods, those with name surrounded by __ on the instance, but only on the class, apparently to improve performance" <-- Do you have a reference to this?

See this. The rules are slightly relaxed on old-style classes, but you should use new-style classes, and in Python 3 they are the only kind anyway.

It's not primarily to improve performance. As the docs say, "The rationale behind this behaviour lies with a number of special methods such as __hash__() and __repr__() that are implemented by all objects, including type objects. If the implicit lookup of these methods used the conventional lookup process, they would fail when invoked on the type object itself" (However, the rationale for __getattribute__ also being skippable is performance.)

Also, "Python doesn't call the special methods" isn't true. Python doesn't guarantee to call them. CPython has a specific list of cases where it skips normal lookup, but that list is implementation-specific, and not documented, so you shouldn't rely on it. Special methods may or may not be looked up on the instance, so make sure your code works either way.

This is not about performance. Special methods are looked up on the type to make sure that both an instance and the type can support the special operation. For example, class objects are hashable. They have a __hash__ method. If the class implements a __hash__ method to make instances hashable, then that method would clash if hash(ClassObject) would look up the method directly on the class (which is itself an instance of a metatype).

python - Overriding special methods on an instance - Stack Overflow

python metaprogramming
Rectangle 27 28

What you're seeing is the use of underlines to distinguish between instance variables and properties. So a class declaration might be:

@interface Foo {
  NSString* _label;
  ....
}

@property (nonatomic, retain) NSString* label; // notice: no underline

Then in the implementation file you would have:

@synthesize label=_label; // the property is matched with the ivar

Now when inside the implementation, if you want to access the instance variable directly you could just use _label but to go through the property accessor methods (which take care of retain/releases and a bunch of other book-keeping tasks) you would use self.label. From the outside, you would always want to go through the {object}.label property.

The other way is to do without the underline and just use:

NSString* label;
@property (nonatomic, retain) NSString* label;
...
@synthesize label;

It works the same but then it might confuse someone reading the code and trying to keep track of label vs self.label. I personally find the Apple convention (with underlines) a bit easier to read but it's a matter of preference.

I just spent ages tracking down a memory management issue due to a variable not being retained since I was using timer instead of self.timer. After this experience, I strongly recommend the use of an _ in front of all private variables

Thanks for this explanation, I was baffled myself. All clear now.

iphone - When do you make an underscore in front of an instance variab...

iphone objective-c cocoa cocoa-touch
Rectangle 27 28

What you're seeing is the use of underlines to distinguish between instance variables and properties. So a class declaration might be:

@interface Foo {
  NSString* _label;
  ....
}

@property (nonatomic, retain) NSString* label; // notice: no underline

Then in the implementation file you would have:

@synthesize label=_label; // the property is matched with the ivar

Now when inside the implementation, if you want to access the instance variable directly you could just use _label but to go through the property accessor methods (which take care of retain/releases and a bunch of other book-keeping tasks) you would use self.label. From the outside, you would always want to go through the {object}.label property.

The other way is to do without the underline and just use:

NSString* label;
@property (nonatomic, retain) NSString* label;
...
@synthesize label;

It works the same but then it might confuse someone reading the code and trying to keep track of label vs self.label. I personally find the Apple convention (with underlines) a bit easier to read but it's a matter of preference.

I just spent ages tracking down a memory management issue due to a variable not being retained since I was using timer instead of self.timer. After this experience, I strongly recommend the use of an _ in front of all private variables

Thanks for this explanation, I was baffled myself. All clear now.

iphone - When do you make an underscore in front of an instance variab...

iphone objective-c cocoa cocoa-touch
Rectangle 27 289

Basically, you check if an object is an instance of a specific class. You normally use it, when you have a reference or parameter to an object that is of a super class or interface type and need to know whether the actual object has some other type (normally more concrete).

public void doSomething(Number param) {
  if( param instanceof Double) {
    System.out.println("param is a Double");
  }
  else if( param instanceof Integer) {
    System.out.println("param is an Integer");
  }

  if( param instanceof Comparable) {
    //subclasses of Number like Double etc. implement Comparable
    //other subclasses might not -> you could pass Number instances that don't implement that interface
    System.out.println("param is comparable"); 
  }
}

Note that if you have to use that operator very often it is generally a hint that your design has some flaws. So in a well designed application you should have to use that operator as little as possible (of course there are exceptions to that general rule).

Is the Integer.class format actually legal? When I attempt to use it in your example, in Eclipse, I get Syntax error on token "class", Identifier expected. However, switching it to simply Integer works fine.

A common place to find this method is in .equals() methods. it's common for intelliJ to generate equals methods that use instanceof

use of "Instance of" in java - Stack Overflow

java
Rectangle 27 52

You need to implement hashCode and equals on Key. The default implementation of these methods simply checks for instance equality (in other words, two Objects will only be equal if they are in fact the same object).

java - Using an instance of an object as a key in hashmap, and then ac...

java hashmap
Rectangle 27 1163

Have you tried the __name__ attribute of the class? ie type(x).__name__ will give you the name of the class, which I think is what you want.

>>> import itertools
>>> x = itertools.count(0)
>>> type(x).__name__
'count'

This method works with new-style classes only. Your code might use some old-style classes. The following works for both:

x.__class__.__name__

Amazingly simple. Wonder why dir(x.__class__) does not list it?

Why use __class__ over the type method? Like so: type(x).__name__. Isn't calling double underscore members directly discouraged? I can't see a way around using __name__, though.

You have to use __class__ directly to be compatible with old-style classes, since their type is just instance.

introspection - Getting the class name of an instance in Python - Stac...

python introspection instanceof python-datamodel