EzDevInfo.com

init

INIT extends HTML5 Boilerplate, adds more structure for SCSS and JavaScripts files, includes build tasks and a whole lot more. INIT • An initial boilerplate for front-end projects init is an initial boilerplate for front-end projects which adds more complexity to your application.

Help understanding jQuery's jQuery.fn.init Why is init in fn

I was looking over the jQuery to better understand how it works. The constructor basically just calls

new jQuery.fn.init

I was wondering what is the point of having the init inside jQuery's prototype? Wouldn't defining init() as part of the jQuery object itself serve the same purpose?


Basically I would like to know why jQuery's init function is located at jQuery.fn.init() and not jQuery.init()

Are there people doing this:

jQuery('a').eq(0).hide().init('div').slideToggle(); //?

Source: (StackOverflow)

How to set which control has focus on Application start

In C#/Winforms how do I set the default focus when my application starts?


Source: (StackOverflow)

Advertisements

What is the use of the init() usage in JavaScript?

So, I just wanna know if anybody knows the particular meaning and usage of the init() statement in JavaScript, never really knew, kind of a newb.


Source: (StackOverflow)

Convert NSNumber to NSDecimalNumber

I realize that NSDecimalNumber inherits from NSNumber.

However, I am struggling to figure out how I can init an NSDecimalNumber from an NSNumber or how to convert an NSNumber to an NSDecimalNumber.

I have tried

NSDecimalNumber* d = [aNumber copy];

where aNumber is an NSNumber object to no avail.

Am I missing something?

Thanks.


Source: (StackOverflow)

Inheritance and init method in Python

I'm begginer of python. I can't understand inheritance and init().

class Num:
    def __init__(self,num):
        self.n1 = num

class Num2(Num):
    def show(self):
        print self.n1

mynumber = Num2(8)
mynumber.show()

RESULT: 8

This is OK.But I replace Num2 with

class Num2(Num):
    def __init__(self,num):
        self.n2 = num*2
    def show(self):
        print self.n1,self.n2

RESULT: Error. Num2 has no attribute "n1".

In this case, how can Num2 access "n1"?


Source: (StackOverflow)

Objective-C: init vs initialize

In Objective-C, what is the difference between the init method (i.e. the designated initializer for a class) and the initialize method? What initialization code should be put in each?


Source: (StackOverflow)

git add all ignoring files in gitignore

I am adding source control to a project that had none. The problem is that there are a lot of files to initially add to git with a .gitignore file, but I can't figure out how to add all files without including the files matching something in the .gitignore file.

git add *

The above command will not add any files because it detects files which are ignored by the .gitignore.

git add -f *

The above command will add all files including the files I wish to ignore.

So, how do I add all files while still adhering to the .gitignore file?


Source: (StackOverflow)

Passing parameters to a custom class on initialization

I have a class Message with two attributes, name and message, and another class MessageController with two text fields, nameField and messageField. I want to make an instance of Message in MessageController, passing these two attributes as arguments.

Right now, I am doing this:

 Message *messageIns = [[Message alloc] init];
 messageIns.name = nameField;
 messageIns.message = MessageField; 

How can I pass the values at the creation of an instance? I tried to redefine init in Message.m, but I don't know how do that.

-(id)init{
    if((self=[super init])){

    }
    return self;
}

Please help.


Source: (StackOverflow)

__init__() got multiple values for keyword argument

Hello, I`m try to use a modified init form section, but show me this error, how can I fix them? I need to pass UserProfile to my form, to get a "dbname" field, and I found this a solution, but when I try to get withou POSt, show me the correct form, but when I press submit button and send via POSt, show me the error.

TypeError at /comerx/cliente/novo/
__init__() got multiple values for keyword argument 'vUserProfile'

Here is my form code:

class ClienteForm(ModelForm):
class Meta:
    model = Cliente

def __init__(self, vUserProfile, *args, **kwargs):
    super(ClienteForm, self).__init__(*args, **kwargs)
    self.fields["idcidade"].queryset = Cidade.objects.using(vUserProfile.dbname).all()

and my views code:

def editaCliente(request, pessoa_id=None):
if request.user.is_authenticated():
    profile = request.user.get_profile()
    if pessoa_id:
        cliente = Cliente.objects.using(profile.dbname).get(idpessoa=pessoa_id)
    else:
        cliente = None

    if request.method == 'POST':
        formPessoa = ClienteForm(request.POST, instance=cliente, vUserProfile=profile)
        if formPessoa.is_valid():
            cliente = formPessoa.save(commit=False)
            cliente.idrepresentante = profile.id_comerx3c # passando o id do representante
            cliente.internet = 'S'
            cliente = formPessoa.save()

            if cliente:
                return redirect('listaCliente')
    else:
        formPessoa = ClienteForm(instance=cliente, vUserProfile=profile)

return render_to_response(
    'cliente_novo.html',
    locals(),
    context_instance=RequestContext(request),
)

Here is the code error:

Environment:

Django Version: 1.4.3
Python Version: 2.7.2
Installed Applications:
('django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.admin',
 'django_evolution',
 'pagination',
 'bootstrap_toolkit',
 'tastypie',
 'comerx')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'pagination.middleware.PaginationMiddleware')


Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
  111.                         response = callback(request, *callback_args,     **callback_kwargs)
File "C:\point\comerx\views.py" in editaCliente
  62.             formPessoa = ClienteForm(request.POST, instance=cliente, vUserProfile=profile)

Exception Type: TypeError at /comerx/cliente/novo/
Exception Value: __init__() got multiple values for keyword argument 'vUserProfile'

Source: (StackOverflow)

IOS: NSMutableArray initWithCapacity

I have this situation

array = [[NSMutableArray alloc] initWithCapacity:4]; //in viewDidLoad

if (index == 0){
    [array insertObject:object atIndex:0];
}

if (index == 1){
    [array insertObject:object atIndex:1];
}

if (index == 2){
    [array insertObject:object atIndex:2];
}

if (index == 3){
    [array insertObject:object atIndex:3];
}

but if I insert in order the object it's all ok, instead if I fill the array in this order: 0 and after 3, it don't work fine, why???


Source: (StackOverflow)

iOS loadNibNamed confusion, what is best practice?

I'm familiar with most of the process of creating an XIB for my own UIView subclass, but not everything is working properly for me - it's mostly to do with the IBOutlets linking up. I can get them to work in what seems like a roundabout way.

My setup is this:

  • I have MyClass.h and MyClass.m. They have IBOutlets for a UIView (called view) and a UILabel (called myLabel). I added the 'view' property because some examples online seemed to suggest that you need this, and it actually solved an issue where I was getting a crash because it couldn't find the view property, I guess not even in the UIView parent class.
  • I have an XIB file called MyClass.xib, and its File's Owner custom class is MyClass, which prefilled correctly after my .h and .m for that class existed.

My init method is where I'm having issues.

I tried to use the NSBundle mainBundle's 'loadNibNamed' method and set the owner to 'self', hoping that I'd be creating an instance of the view and it'd automatically get its outlets matched to the ones in my class (I know how to do this and I'm careful with it). I then thought I'd want to make 'self' equal to the subview at index 0 in that nib, rather than doing

self = [super init];

or anything like that.

I sense that I'm doing things wrong here, but examples online have had similar things going on in the init method, but they assign that subview 0 to the view property and add it as a child - but is that not then a total of two MyClass instances? One essentially unlinked to IBOutlets, containing the child MyClass instantiated via loadNibNamed? Or at best, is it not a MyClass instance with an extra intermediary UIView containing all the IBOutlets I originally wanted as direct children of MyClass? That poses a slight annoyance when it comes to doing things like instanceOfMyClass.frame.size.width, as it returns 0, when the child UIView that's been introduced returns the real frame size I was looking for.

Is the thing I'm doing wrong that I'm messing with loadNibNamed inside an init method? Should I be doing something more like this?

MyClass *instance = [[MyClass alloc] init];
[[NSBundle mainBundle] loadNibNamed:@"MyClass" owner:instance options:nil];  

Or like this?

MyClass *instance = [[[NSBundle mainBundle] loadNibNamed:@"MyClass" owner:nil options:nil] objectAtIndex:0]; 

Thanks in advance for any assitance.


Source: (StackOverflow)

Why are alloc and init called separately in Objective-C?

Note: I'm relatively new to Objective-C and am coming from Java and PHP.

Could someone explain to me why I always have to first allocate and then initialize an instance?

Couldn't this be done in the init methods like this:

+ (MyClass*)init {
    MyClass *instance = [MyClass alloc];
    [instance setFoo:@"bla"];

    return instance;
}

+ (MyClass*)initWithString:(NSString*)text {
    MyClass *instance = [MyClass init];
    [instance setFoo:text];

    return instance;
}
...

Is this just a relict from the old C days or is there something that I'm not seeing?

I know this isn't a problem as I could as well always call alloc and init, but since it's a bit tedious I'd like to at least know why I'm doing it.

I'm liking the expressiveness of the language so far, but this is something that I want to fully understand in order to think the Objective-C way.

Thank you!


Source: (StackOverflow)

Setting an NSDate to specific date, time and timezone

I need to set a NSDate to a specific date, time and timezone for an iPhone App.

The example code below works fine on iOS 4 as the setTimeZone was introduced with iOS 4. How could I easily set a NSDate to a date, time and timezone without using setTimeZone so it can be used on iOS 3.0 devices?

    NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setYear:2010];
[comps setMonth:8];
[comps setDay:24];
[comps setHour:17];
[comps setMinute:5];
[comps setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"] ];

NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *referenceTime = [cal dateFromComponents:comps];

Guess this should be simple, but somehow NSDate, components and calendars and I are not good friends...


Source: (StackOverflow)

Initialization of members when inheriting from extern C struct

In Mixing C and C++ Code in the Same Program the following example (slightly abbreviated here to the relevant parts) is given. Assume buf.h contains the following:

struct buf {
    char* data;
    unsigned count;
};

// some declarations of existing C functions for handling buf...

It is then recommended to use

extern "C" {
  #include "buf.h"
}

class mybuf : public buf {
public:
    mybuf() : data(0), count(0) { }

    // add new methods here (e.g. wrappers for existing C functions)...
};

in order to use the struct within C++ with added features.

However, this clearly will produce the following error:

error: class `mybuf' does not have any field named `data'
error: class `mybuf' does not have any field named `count'

The reasons for this are explained in How can I initialize base class member variables in derived class constructor?, C++: Initialization of inherited field, and Initialize parent's protected members with initialization list (C++).

Thus, I have the following two questions:

  1. Is the code provided just plainly wrong or am I missing some relevant aspect? (After all, the article seems to stem from a reputable source)
  2. What is the correct way to achieve the desired effect (i.e., turning a C struct into a C++ class and adding some convenience methods like, e.g., a constructor, etc.)?

Update: Using aggregation initialization as suggested, i.e.,

mybuf() : buf{0, 0} {}

works, but requires C++11. I therefore add the following question:

  1. Using C++03, is there a better way to achieve the desired outcome than using the following constructor?

    mybuf() {
      data = 0;
      count = 0;
    }
    

Source: (StackOverflow)

what does object's __init__() do in python? [duplicate]

This question already has an answer here:

I'm reading the code of OpenStack and I encountered this.

A class named 'Service' inherits the base class 'object', and then, in Service's __init__() method, object's __init__ is called. The related code like this:

the class definition:

class Service(object):

and Service's init method definition:

def __init__(self, host, binary, topic, manager, report_interval=None,
             periodic_interval=None, *args, **kwargs):

and a call to super(the 'object' here) in Service's init:

super(Service, self).__init__(*args, **kwargs)

I don't understand what does the last call, object.__init__() actually do. anyone can help?


Source: (StackOverflow)