code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
def _fundamentalToSqls(self, symbol, keyTimeValueDict): ''' convert fundament dict to sqls ''' sqls=[] for key, timeValues in keyTimeValueDict.iteritems(): for timeStamp, value in timeValues.iteritems(): sqls.append(FmSql(symbol, key, timeStamp, value)) ...
convert fundament dict to sqls
null
null
null
if self._writeable: self._write(('CRVDEL', Integer), self.idx) else: raise RuntimeError('Can not delete read-only curves.')
def delete(self)
Deletes the current curve. :raises RuntimeError: Raises when` when one tries to delete a read-only curve.
23.134775
16.405663
1.41017
# TODO: We should parse the response properly. return self._query(('PGM?', [Integer, Integer], String), self.idx, idx)
def line(self, idx)
Return the i'th program line. :param i: The i'th program line.
56.606659
49.533024
1.142806
# TODO: The user still has to write the raw line, this is error prone. self._write(('PGM', [Integer, String]), self.idx, new_line)
def append_line(self, new_line)
Appends the new_line to the LS340 program.
34.118973
30.142462
1.131924
args = [std, dest, serial, T1, U1, T2, U2] dtype = [Integer(min=1, max=21), Integer(min=21, max=61), String(max=10), Float, Float, Float, Float] if (T3 is not None) and (U3 is not None): args.extend([T3, U3]) dtype.extend([Float, Float]) self._write(('SCA...
def softcal(self, std, dest, serial, T1, U1, T2, U2, T3=None, U3=None)
Generates a softcal curve. :param std: The standard curve index used to calculate the softcal curve. Valid entries are 1-20 :param dest: The user curve index where the softcal curve is stored. Valid entries are 21-60. :param serial: The serial number of the new curve. A ...
3.545319
2.813689
1.260025
if Image is None: # throw the ImportError here import PIL image = Image.open(inputFile) # Resize needed? if thumbnailSize < max(image.size): # Convert bilevel and paletted images to grayscale and RGB respectively; # otherwise PIL silently switches to Image.NEAREST sa...
def makeThumbnail(inputFile, outputFile, thumbnailSize, outputFormat='jpeg')
Make a thumbnail of the image stored at C{inputPath}, preserving its aspect ratio, and write the result to C{outputPath}. @param inputFile: The image file (or path to the file) to thumbnail. @type inputFile: C{file} or C{str} @param outputFile: The file (or path to the file) to write the thumbnail ...
4.717029
5.278319
0.893661
descriptiveIdentifierMethod = getattr( contactType, 'descriptiveIdentifier', None) if descriptiveIdentifierMethod is not None: return descriptiveIdentifierMethod() warn( "IContactType now has the 'descriptiveIdentifier'" " method, %s did not implement it" % (contactType....
def _descriptiveIdentifier(contactType)
Get a descriptive identifier for C{contactType}, taking into account the fact that it might not have implemented the C{descriptiveIdentifier} method. @type contactType: L{IContactType} provider. @rtype: C{unicode}
6.042213
6.072378
0.995032
name = getattr(plugin, 'name', None) if name is not None: return name warn( "IOrganizerPlugin now has the 'name' attribute" " and %s does not define it" % (plugin.__class__,), category=PendingDeprecationWarning) return _objectToName(plugin).decode('ascii')
def _organizerPluginName(plugin)
Get a name for C{plugin}, taking into account the fact that it might not have defined L{IOrganizerPlugin.name}. @type plugin: L{IOrganizerPlugin} provider. @rtype: C{unicode}
6.309315
6.212351
1.015608
return dict((k.encode('ascii'), v) for (k, v) in d.iteritems())
def _stringifyKeys(d)
Return a copy of C{d} with C{str} keys. @type d: C{dict} with C{unicode} keys. @rtype: C{dict} with C{str} keys.
4.892593
6.774535
0.722204
smallerBody = Mugshot.makeThumbnail(old.body.open(), old.person, old.type.split('/')[1], smaller=True) return old.upgradeVersion(Mugshot.typeName, 1, 2, per...
def mugshot1to2(old)
Upgrader for L{Mugshot} from version 1 to version 2, which sets the C{smallerBody} attribute to the path of a smaller mugshot image.
7.700899
6.329175
1.21673
new = old.upgradeVersion(Mugshot.typeName, 2, 3, person=old.person, type=old.type, body=old.body, smallerBody=old.smallerBody) new.smallerBody = new.makeThumbnail( new.body.open(), ne...
def mugshot2to3(old)
Upgrader for L{Mugshot} from version 2 to version 3, which re-thumbnails the mugshot to take into account the new value of L{Mugshot.smallerSize}.
8.246573
6.655858
1.238995
isVIP = False # default if contactItem is not None: isVIP = contactItem.person.vip return [liveform.Parameter( 'vip', liveform.CHECKBOX_INPUT, bool, 'VIP', default=isVIP)]
def getParameters(self, contactItem)
Return a list containing a single parameter suitable for changing the VIP status of a person. @type contactItem: L{_PersonVIPStatus} @rtype: C{list} of L{liveform.Parameter}
9.627099
7.649243
1.258569
if emailAddress is not None: address = emailAddress.address else: address = u'' return [ liveform.Parameter('email', liveform.TEXT_INPUT, _normalizeWhitespace, 'Email Address', default=addr...
def getParameters(self, emailAddress)
Return a C{list} of one L{LiveForm} parameter for editing an L{EmailAddress}. @type emailAddress: L{EmailAddress} or C{NoneType} @param emailAddress: If not C{None}, an existing contact item from which to get the email address default value. @rtype: C{list} @return:...
8.072706
6.304215
1.280525
return self.store.findUnique( EmailAddress, EmailAddress.address == email, default=None)
def _existing(self, email)
Return the existing L{EmailAddress} item with the given address, or C{None} if there isn't one.
6.151285
4.421985
1.391069
if email: address = self._existing(email) if address is not None: raise ValueError('There is already a person with that email ' 'address (%s): ' % (address.person.name,)) return EmailAddress(store=self.store, ...
def createContactItem(self, person, email)
Create a new L{EmailAddress} associated with the given person based on the given email address. @type person: L{Person} @param person: The person with whom to associate the new L{EmailAddress}. @type email: C{unicode} @param email: The value to use for the I{address...
6.827456
7.140127
0.956209
return person.store.query( EmailAddress, EmailAddress.person == person)
def getContactItems(self, person)
Return all L{EmailAddress} instances associated with the given person. @type person: L{Person}
15.655205
14.392946
1.0877
address = self._existing(email) if address is not None and address is not contact: raise ValueError('There is already a person with that email ' 'address (%s): ' % (address.person.name,)) contact.address = email
def editContactItem(self, contact, email)
Change the email address of the given L{EmailAddress} to that specified by C{email}. @type email: C{unicode} @param email: The new value to use for the I{address} attribute of the L{EmailAddress}. @return: C{None}
8.8053
8.766728
1.0044
return self.store.query( EmailAddress, EmailAddress.person == self).getColumn('address')
def getEmailAddresses(self)
Return an iterator of all email addresses associated with this person. @return: an iterator of unicode strings in RFC2822 address format.
11.937886
11.014056
1.083877
mugshot = self.store.findUnique( Mugshot, Mugshot.person == self, default=None) if mugshot is not None: return mugshot return Mugshot.placeholderForPerson(self)
def getMugshot(self)
Return the L{Mugshot} associated with this L{Person}, or an unstored L{Mugshot} pointing at a placeholder mugshot image.
4.036385
2.904801
1.389557
if self.store is None: return None userInfo = self.store.findFirst(signup.UserInfo) name = u'' if userInfo is not None: name = userInfo.realName account = self.store.findUnique(LoginAccount, LoginAccount.ava...
def _makeStoreOwnerPerson(self)
Make a L{Person} representing the owner of the store that this L{Organizer} is installed in. @rtype: L{Person}
6.404643
6.494304
0.986194
for plugin in self.getOrganizerPlugins(): implementation = getattr(plugin, methodName, None) if implementation is not None: yield implementation else: warn( ('IOrganizerPlugin now has the %r method, %s' ...
def _gatherPluginMethods(self, methodName)
Walk through each L{IOrganizerPlugin} powerup, yielding the bound method if the powerup implements C{methodName}. Upon encountering a plugin which fails to implement it, issue a L{PendingDeprecationWarning}. @param methodName: The name of a L{IOrganizerPlugin} method. @type met...
7.273854
5.052623
1.439619
if getattr(contactType, 'getEditFormForPerson', None) is None: warn( "IContactType now has the 'getEditFormForPerson'" " method, but %s did not implement it." % ( contactType.__class__,), category=PendingDeprecationWarning)...
def _checkContactType(self, contactType)
Possibly emit some warnings about C{contactType}'s implementation of L{IContactType}. @type contactType: L{IContactType} provider
4.601099
4.317166
1.065768
yield VIPPersonContactType() yield EmailContactType(self.store) yield PostalContactType() yield PhoneNumberContactType() yield NotesContactType() for getContactTypes in self._gatherPluginMethods('getContactTypes'): for contactType in getContactTypes()...
def getContactTypes(self)
Return an iterator of L{IContactType} providers available to this organizer's store.
7.352242
6.825229
1.077216
yield AllPeopleFilter() yield VIPPeopleFilter() for getPeopleFilters in self._gatherPluginMethods('getPeopleFilters'): for peopleFilter in getPeopleFilters(): yield peopleFilter for tag in sorted(self.getPeopleTags()): yield TaggedPeopleFi...
def getPeopleFilters(self)
Return an iterator of L{IPeopleFilter} providers available to this organizer's store.
7.958839
6.684143
1.190705
query = self.store.query( Tag, Tag.object == Person.storeID) return set(query.getColumn('name').distinct())
def getPeopleTags(self)
Return a sequence of tags which have been applied to L{Person} items. @rtype: C{set}
13.741428
11.875486
1.157126
# this is a slightly awkward, specific API, but at the time of # writing, read-only views are the thing that the only caller cares # about. we need the contact type to get a read-only view for a # contact item. there is no way to get from a contact item to a # contact ...
def groupReadOnlyViews(self, person)
Collect all contact items from the available contact types for the given person, organize them by contact group, and turn them into read-only views. @type person: L{Person} @param person: The person whose contact items we're interested in. @return: A mapping of of L{ContactGrou...
6.384127
5.818735
1.097167
for contactType in self.getContactTypes(): if contactType.allowMultipleContactItems: descriptiveIdentifier = _descriptiveIdentifier(contactType) yield liveform.ListChangeParameter( contactType.uniqueIdentifier(), contac...
def getContactCreationParameters(self)
Yield a L{Parameter} for each L{IContactType} known. Each yielded object can be used with a L{LiveForm} to create a new instance of a particular L{IContactType}.
8.860963
7.301145
1.21364
defaults = {} for p in parameters: if isinstance(p, liveform.ChoiceParameter): selected = [] for choice in p.choices: if choice.selected: selected.append(choice.value) defaults[p.name] = sele...
def _parametersToDefaults(self, parameters)
Extract the defaults from C{parameters}, constructing a dictionary mapping parameter names to default values, suitable for passing to L{ListChangeParameter}. @type parameters: C{list} of L{liveform.Parameter} or L{liveform.ChoiceParameter}. @rtype: C{dict}
2.675072
2.147182
1.245853
contactItems = list(contactType.getContactItems(person)) if contactType.allowMultipleContactItems: defaults = [] modelObjects = [] for contactItem in contactItems: defaultedParameters = contactType.getParameters(contactItem) if...
def toContactEditorialParameter(self, contactType, person)
Convert the given contact type into a L{liveform.LiveForm} parameter. @type contactType: L{IContactType} provider. @type person: L{Person} @rtype: L{liveform.Parameter} or similar.
5.090389
4.743962
1.073025
for contactType in self.getContactTypes(): yield ( contactType, self.toContactEditorialParameter(contactType, person))
def getContactEditorialParameters(self, person)
Yield L{LiveForm} parameters to edit each contact item of each contact type for the given person. @type person: L{Person} @return: An iterable of two-tuples. The first element of each tuple is an L{IContactType} provider. The third element of each tuple is the L{LiveFo...
6.600204
5.308908
1.243232
for person in (self.store.query( Person, attributes.AND( Person.name == nickname, Person.organizer == self))): raise ValueError("Person with name %r exists already." % (nickname,)) person = Person( store=self.store,...
def createPerson(self, nickname, vip=_NO_VIP)
Create a new L{Person} with the given name in this organizer. @type nickname: C{unicode} @param nickname: The value for the new person's C{name} attribute. @type vip: C{bool} @param vip: Value to set the created person's C{vip} attribute to (deprecated). @rtype: L{Pers...
5.033678
4.44654
1.132044
contactItem = contactType.createContactItem( person, **_stringifyKeys(contactInfo)) if contactItem is not None: self._callOnOrganizerPlugins('contactItemCreated', contactItem) return contactItem
def createContactItem(self, contactType, person, contactInfo)
Create a new contact item for the given person with the given contact type. Broadcast a creation to all L{IOrganizerPlugin} powerups. @type contactType: L{IContactType} @param contactType: The contact type which will be used to create the contact item. @type person: L{Pers...
8.813711
7.895627
1.116278
contactType.editContactItem( contactItem, **_stringifyKeys(contactInfo)) self._callOnOrganizerPlugins('contactItemEdited', contactItem)
def editContactItem(self, contactType, contactItem, contactInfo)
Edit the given contact item with the given contact type. Broadcast the edit to all L{IOrganizerPlugin} powerups. @type contactType: L{IContactType} @param contactType: The contact type which will be used to edit the contact item. @param contactItem: The contact item to edi...
18.076565
18.100033
0.998703
for observer in self.getOrganizerPlugins(): method = getattr(observer, methodName, None) if method is not None: method(*args) else: warn( "IOrganizerPlugin now has the %s method, %s " "did not im...
def _callOnOrganizerPlugins(self, methodName, *args)
Call a method on all L{IOrganizerPlugin} powerups on C{self.store}, or emit a deprecation warning for each one which does not implement that method.
5.083322
4.17528
1.21748
for existing in self.store.query(Person, Person.name == nickname): if existing is person: continue raise ValueError( "A person with the name %r exists already." % (nickname,)) oldname = person.name person.name = nickname se...
def editPerson(self, person, nickname, edits)
Change the name and contact information associated with the given L{Person}. @type person: L{Person} @param person: The person which will be modified. @type nickname: C{unicode} @param nickname: The new value for L{Person.name} @type edits: C{list} @param edits...
4.724685
4.905694
0.963102
return self.store.findOrCreate(Person, organizer=self, name=name)
def personByName(self, name)
Retrieve the L{Person} item for the given Q2Q address, creating it first if necessary. @type name: C{unicode}
9.792676
11.469792
0.85378
email = self.store.findUnique(EmailAddress, EmailAddress.address == address, default=None) if email is not None: return email.person
def personByEmailAddress(self, address)
Retrieve the L{Person} item for the given email address (or return None if no such person exists) @type name: C{unicode}
3.758649
4.781286
0.786117
# ideally there would be a more general mechanism for encoding state # like this in a url, rather than ad-hoc query arguments for each # fragment which needs to do it. organizerURL = self._webTranslator.linkTo(self.storeID) return url.URL( netloc='', scheme='...
def urlForViewState(self, person, viewState)
Return a url for L{OrganizerFragment} which will display C{person} in state C{viewState}. @type person: L{Person} @type viewState: L{ORGANIZER_VIEW_STATES} constant. @rtype: L{url.URL}
15.373578
13.94432
1.102498
filter = self.filters[filterName] self.baseConstraint = filter.getPeopleQueryComparison(self.store)
def filterByFilter(self, filterName)
Swap L{baseConstraint} with the result of calling L{IPeopleFilter.getPeopleQueryComparison} on the named filter. @type filterName: C{unicode}
22.885231
7.036499
3.25236
groupPattern = inevow.IQ(tag).patternGenerator('contact-group') groupedViews = self.organizer.groupReadOnlyViews(self.person) for (groupName, views) in sorted(groupedViews.items()): if groupName is None: yield views else: yield gro...
def contactInfo(self, request, tag)
Render the result of calling L{IContactType.getReadOnlyView} on the corresponding L{IContactType} for each piece of contact info associated with L{person}. Arrange the result by group, using C{tag}'s I{contact-group} pattern. Groupless contact items will have their views yielded directl...
8.586321
5.021515
1.709906
iq = inevow.IQ(tag) tabNames = [ _organizerPluginName(p).encode('ascii') # gunk for p in self.plugins] child = tabbedPane.TabbedPaneFragment( zip(tabNames, ([self.getPluginWidget(tabNames[0])] + [iq.onePattern('...
def pluginTabbedPane(self, request, tag)
Render a L{tabbedPane.TabbedPaneFragment} with an entry for each item in L{plugins}.
9.684454
8.266192
1.171574
# this will always pick the first plugin with pluginName if there is # more than one. don't do that. for plugin in self.plugins: if _organizerPluginName(plugin) == pluginName: view = self._toLiveElement( plugin.personalize(self.person)) ...
def getPluginWidget(self, pluginName)
Return the named plugin's view. @type pluginName: C{unicode} @param pluginName: The name of the plugin. @rtype: L{LiveElement}
11.916729
9.863915
1.208113
# see the comment in Organizer.urlForViewState which suggests an # alternate implementation of this kind of functionality. request = inevow.IRequest(ctx) if not set(['initial-person', 'initial-state']).issubset( # <= set(request.args)): return ini...
def beforeRender(self, ctx)
Implement this hook to initialize the L{initialPerson} and L{initialState} slots with information from the request url's query args.
5.068471
4.240045
1.195381
initialArguments = (self.organizer.storeOwnerPerson.name,) if self.initialPerson is not None: initialArguments += (self.initialPerson.name, self.initialState) return initialArguments
def getInitialArguments(self)
Include L{organizer}'s C{storeOwnerPerson}'s name, and the name of L{initialPerson} and the value of L{initialState}, if they are set.
8.756343
2.856404
3.065513
fragment = AddPersonFragment(self.organizer) fragment.setFragmentParent(self) return fragment
def getAddPerson(self)
Return an L{AddPersonFragment} which is a child of this fragment and which will add a person to C{self.organizer}.
11.906979
4.170713
2.854902
fragment = ImportPeopleWidget(self.organizer) fragment.setFragmentParent(self) return fragment
def getImportPeople(self)
Return an L{ImportPeopleWidget} which is a child of this fragment and which will add people to C{self.organizer}.
15.025339
5.734981
2.619946
view = EditPersonView(self.organizer.personByName(name)) view.setFragmentParent(self) return view
def getEditPerson(self, name)
Get an L{EditPersonView} for editing the person named C{name}. @param name: A person name. @type name: C{unicode} @rtype: L{EditPersonView}
9.515328
10.338165
0.920408
self.organizer.deletePerson(self.organizer.personByName(name))
def deletePerson(self, name)
Delete the person named C{name} @param name: A person name. @type name: C{unicode}
7.137017
9.960465
0.716534
f = PersonScrollingFragment( self.organizer, None, Person.name, self.wt) f.setFragmentParent(self) f.docFactory = webtheme.getLoader(f.fragmentName) return f
def peopleTable(self, request, tag)
Return a L{PersonScrollingFragment} which will display the L{Person} items in the wrapped organizer.
17.9291
9.368771
1.913709
filters = iter(self.organizer.getPeopleFilters()) # at some point we might actually want to look at what filter is # yielded first, and filter the person list accordingly. we're just # going to assume it's the "All" filter, and leave the person list # untouched for now....
def peopleFilters(self, request, tag)
Return an instance of C{tag}'s I{filter} pattern for each filter we get from L{Organizer.getPeopleFilters}, filling the I{name} slot with the filter's name. The first filter will be rendered using the I{selected-filter} pattern.
9.728271
6.342625
1.533793
fragment = PersonPluginView( self.organizer.getOrganizerPlugins(), self.organizer.personByName(name)) fragment.setFragmentParent(self) return fragment
def getPersonPluginWidget(self, name)
Return the L{PersonPluginView} for the named person. @type name: C{unicode} @param name: A value which corresponds to the I{name} attribute of an extant L{Person}. @rtype: L{PersonPluginView}
9.724764
9.316044
1.043873
submissions = [] for paramName, submission in edits.iteritems(): contactType = self.contactTypes[paramName] submissions.append((contactType, submission)) self.person.store.transact( self.organizer.editPerson, self.person, nickname, submiss...
def editContactItems(self, nickname, **edits)
Update the information on the contact items associated with the wrapped L{Person}. @type nickname: C{unicode} @param nickname: New value to use for the I{name} attribute of the L{Person}. @param **edits: mapping from contact type identifiers to ListChanges insta...
7.632825
6.7062
1.138174
parameters = [ liveform.Parameter( 'nickname', liveform.TEXT_INPUT, _normalizeWhitespace, 'Name', default=self.person.name)] separateForms = [] for contactType in self.organizer.getContactTypes(): if getattr(contact...
def makeEditorialLiveForms(self)
Make some L{liveform.LiveForm} instances for editing the contact information of the wrapped L{Person}.
5.031714
4.677149
1.075808
defaultNumber = u'' defaultLabel = PhoneNumber.LABELS.HOME if phoneNumber is not None: defaultNumber = phoneNumber.number defaultLabel = phoneNumber.label labelChoiceParameter = liveform.ChoiceParameter( 'label', [liveform.Option(l...
def getParameters(self, phoneNumber)
Return a C{list} of two liveform parameters, one for editing C{phoneNumber}'s I{number} attribute, and one for editing its I{label} attribute. @type phoneNumber: L{PhoneNumber} or C{NoneType} @param phoneNumber: If not C{None}, an existing contact item from which to get the para...
4.653491
4.116058
1.13057
if number: return PhoneNumber( store=person.store, person=person, label=label, number=number)
def createContactItem(self, person, label, number)
Create a L{PhoneNumber} item for C{number}, associated with C{person}. @type person: L{Person} @param label: The value to use for the I{label} attribute of the new L{PhoneNumber} item. @type label: C{unicode} @param number: The value to use for the I{number} attribute of the n...
7.20751
6.633394
1.086549
contact.label = label contact.number = number
def editContactItem(self, contact, label, number)
Change the I{number} attribute of C{contact} to C{number}, and the I{label} attribute to C{label}. @type contact: L{PhoneNumber} @type label: C{unicode} @type number: C{unicode} @return: C{None}
5.760588
16.341625
0.35251
return person.store.query( PhoneNumber, PhoneNumber.person == person)
def getContactItems(self, person)
Return an iterable of L{PhoneNumber} items that are associated with C{person}. @type person: L{Person}
16.827019
13.001949
1.294192
address = u'' if postalAddress is not None: address = postalAddress.address return [ liveform.Parameter('address', liveform.TEXT_INPUT, unicode, 'Postal Address', default=address)]
def getParameters(self, postalAddress)
Return a C{list} of one L{LiveForm} parameter for editing a L{PostalAddress}. @type postalAddress: L{PostalAddress} or C{NoneType} @param postalAddress: If not C{None}, an existing contact item from which to get the postal address default value. @rtype: C{list} @re...
8.130856
6.23365
1.304349
if address: return PostalAddress( store=person.store, person=person, address=address)
def createContactItem(self, person, address)
Create a new L{PostalAddress} associated with the given person based on the given postal address. @type person: L{Person} @param person: The person with whom to associate the new L{EmailAddress}. @type address: C{unicode} @param address: The value to use for the I{a...
10.132584
9.900546
1.023437
return person.store.query(PostalAddress, PostalAddress.person == person)
def getContactItems(self, person)
Return a C{list} of the L{PostalAddress} items associated with the given person. @type person: L{Person}
16.367992
13.953958
1.173
defaultNotes = u'' if notes is not None: defaultNotes = notes.notes return [ liveform.Parameter('notes', liveform.TEXTAREA_INPUT, unicode, 'Notes', default=defaultNotes)]
def getParameters(self, notes)
Return a C{list} of one L{LiveForm} parameter for editing a L{Notes}. @type notes: L{Notes} or C{NoneType} @param notes: If not C{None}, an existing contact item from which to get the parameter's default value. @rtype: C{list}
8.781193
7.928354
1.107568
if notes: return Notes( store=person.store, person=person, notes=notes)
def createContactItem(self, person, notes)
Create a new L{Notes} associated with the given person based on the given string. @type person: L{Person} @param person: The person with whom to associate the new L{Notes}. @type notes: C{unicode} @param notes: The value to use for the I{notes} attribute of the newly cr...
12.069802
13.37658
0.902309
notes = list(person.store.query(Notes, Notes.person == person)) if not notes: return [Notes(store=person.store, person=person, notes=u'')] return notes
def getContactItems(self, person)
Return a C{list} of the L{Notes} items associated with the given person. If none exist, create one, wrap it in a list and return it. @type person: L{Person}
6.582736
5.844937
1.126229
addPersonForm = liveform.LiveForm( self.addPerson, self._baseParameters, description='Add Person') addPersonForm.compact() addPersonForm.jsClass = u'Mantissa.People.AddPersonForm' addPersonForm.setFragmentParent(self) return addPersonForm
def render_addPersonForm(self, ctx, data)
Create and return a L{liveform.LiveForm} for creating a new L{Person}.
6.545722
5.0896
1.286098
try: self.organizer.createPerson(nickname) except ValueError, e: raise liveform.InputError(unicode(e))
def addPerson(self, nickname)
Create a new L{Person} with the given C{nickname}. @type nickname: C{unicode} @param nickname: The value for the I{name} attribute of the created L{Person}. @raise L{liveform.InputError}: When some aspect of person creation raises a L{ValueError}.
9.046642
4.722357
1.915705
def coerce((name, email)): if len(email): if not len(name): name = email.split(u'@', 1)[0] # lame return (name, email) coerced = map(coerce, getaddresses([addresses])) return [r for r in coerced if r is not None]
def _parseAddresses(addresses)
Extract name/address pairs from an RFC 2822 style address list. For addresses without a display name, the name defaults to the local-part for the purpose of importing. @type addresses: unicode @return: a list of C{(name, email)} tuples
6.414659
5.810071
1.104059
form = liveform.LiveForm( self.importAddresses, [liveform.Parameter('addresses', liveform.TEXTAREA_INPUT, self._parseAddresses, 'Email Addresses')], description='Import People') form.jsClass = u'Mantissa.People.ImportPeopleForm...
def importPeopleForm(self, request, tag)
Create and return a L{liveform.LiveForm} for adding new L{Person}s.
9.295885
7.223829
1.286836
results = [] for (name, address) in addresses: def txn(): # Skip names and addresses that already exist. if self.organizer.personByEmailAddress(address) is not None: return # XXX: Needs a better existence check. ...
def importAddresses(self, addresses)
Create new L{Person}s for the given names and email addresses. Names and emails that already exist are ignored. @param addresses: a sequence of C{(name, email)} tuples (as returned from L{_parseAddresses}) @return: the names of people actually imported
6.489138
5.849026
1.109439
req = inevow.IRequest(ctx) if req.method == 'POST': udata = req.fields['uploaddata'] self.cbGotMugshot(udata.type.decode('ascii'), udata.file) return rend.Page.renderHTTP(self, ctx)
def renderHTTP(self, ctx)
Extract the data from the I{uploaddata} field of the request and pass it to our callback.
7.208684
5.925559
1.216541
body = cls.makeThumbnail(inputFile, person, format, smaller=False) inputFile.seek(0) smallerBody = cls.makeThumbnail( inputFile, person, format, smaller=True) ctype = u'image/' + format self = person.store.findUnique( cls, cls.person == person, ...
def fromFile(cls, person, inputFile, format)
Create a L{Mugshot} item for C{person} out of the image data in C{inputFile}, or update C{person}'s existing L{Mugshot} item to reflect the new images. @param inputFile: An image of a person. @type inputFile: C{file} @param person: The person this mugshot is to be associated wi...
3.642355
3.780249
0.963523
dirsegs = ['mugshots', str(person.storeID)] if smaller: dirsegs.insert(1, 'smaller') size = cls.smallerSize else: size = cls.size atomicOutputFile = person.store.newFile(*dirsegs) makeThumbnail(inputFile, atomicOutputFile, size, format...
def makeThumbnail(cls, inputFile, person, format, smaller)
Make a thumbnail of a mugshot image and store it on disk. @param inputFile: The image to thumbnail. @type inputFile: C{file} @param person: The person this mugshot thumbnail is associated with. @type person: L{Person} @param format: The format of the data in C{inputFile}. ...
6.799778
6.188632
1.098753
imageDir = FilePath(__file__).parent().child( 'static').child('images') return cls( type=u'image/png', body=imageDir.child('mugshot-placeholder.png'), smallerBody=imageDir.child( 'mugshot-placeholder-smaller.png'), pers...
def placeholderForPerson(cls, person)
Make an unstored, placeholder L{Mugshot} instance for the given person. @param person: A person without a L{Mugshot}. @type person: L{Person} @rtype: L{Mugshot}
5.235524
5.114897
1.023583
jinja = container.get('ioc.extra.jinja2') for id in container_builder.get_ids_by_tag('jinja2.filter'): definition = container_builder.get(id) for option in definition.get_tag('jinja2.filter'): if 'name' not in option: break ...
def post_build(self, container_builder, container)
Register filter and global in jinja environment instance IoC tags are: - jinja2.filter to register filter, the tag must contain a name and a method options - jinja2.global to add new global, here globals are functions. The tag must contain a name and a method op...
2.763462
2.187619
1.263228
key = "" for arg in args: if callable(arg): key += ":%s" % repr(arg) else: key += ":%s" % str(arg) return key
def cache_key(*args, **kwargs)
Base method for computing the cache key with respect to the given arguments.
3.238345
3.390179
0.955214
filehash = sha1sum(filename) files = {'filedata': open(filename, 'rb')} payload = { 'sha1': filehash, 'filename': os.path.basename(filename), 'token': token, 'nonce': nonce, } return method("%s/sign/%s" % (baseurl, format_), files=files, data=payload, verify=ce...
def uploadfile(baseurl, filename, format_, token, nonce, cert, method=requests.post)
Uploads file (given by `filename`) to server at `baseurl`. `sesson_key` and `nonce` are string values that get passed as POST parameters.
2.828711
3.280854
0.862187
''' Decode base64 encoded responses from Consul storage ''' def inner(*args, **kwargs): ''' decorator ''' data = fct(*args, **kwargs) if 'error' not in data: for result in data: result['Value'] = base64.b64decode(result['Value']) return data return...
def decode_values(fct)
Decode base64 encoded responses from Consul storage
4.565604
3.489172
1.308507
''' Return json messages instead of raising errors ''' def inner(*args, **kwargs): ''' decorator ''' try: _data = fct(*args, **kwargs) except requests.exceptions.ConnectionError as error: return {'error': str(error), 'status': 404} if _data.ok: ...
def safe_request(fct)
Return json messages instead of raising errors
3.004005
2.590699
1.159534
parts = [] parser = _AddressParser() end = parser(parts, address) if end != len(address): raise InvalidTrailingBytes() return parts[0]
def parseAddress(address)
Parse the given RFC 2821 email address into a structured object. @type address: C{str} @param address: The address to parse. @rtype: L{Address} @raise xmantissa.error.ArgumentError: The given string was not a valid RFC 2821 address.
8.960942
13.102809
0.683895
self._initial_setup() self.on_service_start() self.app = self.make_tornado_app() enable_pretty_logging() self.app.listen(self.port, address=self.host) self._start_periodic_tasks() # starts the event handlers self._initialize_event_handlers() ...
def start(self)
The main method that starts the service. This is blocking.
5.731496
5.35704
1.0699
for plugin in self.plugins: if plugin.name == name: return plugin raise PluginDoesNotExistError("Plugin '{}' not found".format(name))
def get_plugin(self, name)
Returns a plugin by name and raises ``gemstone.errors.PluginDoesNotExistError`` error if no plugin with such name exists. :param name: a string specifying a plugin name. :return: the corresponding plugin instance.
3.28787
3.72743
0.882074
if not self.discovery_strategies: raise ServiceConfigurationError("No service registry available") cached = self.remote_service_cache.get_entry(name) if cached: return cached.remote_service for strategy in self.discovery_strategies: endpoint...
def get_service(self, name)
Locates a remote service by name. The name can be a glob-like pattern (``"project.worker.*"``). If multiple services match the given name, a random instance will be chosen. There might be multiple services that match a given name if there are multiple services with the same name running,...
3.874789
3.226734
1.20084
thread_obj = threading.Thread(target=target, args=args, kwargs=kwargs, daemon=True) thread_obj.start()
def start_thread(self, target, args, kwargs)
Shortcut method for starting a thread. :param target: The function to be executed. :param args: A tuple or list representing the positional arguments for the thread. :param kwargs: A dictionary representing the keyword arguments. .. versionadded:: 0.5.0
2.183139
3.26606
0.668432
for transport in self.event_transports: transport.emit_event(event_name, event_body)
def emit_event(self, event_name, event_body)
Publishes an event of type ``event_name`` to all subscribers, having the body ``event_body``. The event is pushed through all available event transports. The event body must be a Python object that can be represented as a JSON. :param event_name: a ``str`` representing the event type :...
3.950164
4.292829
0.920177
handlers = [ (self.endpoint, TornadoJsonRpcHandler, {"microservice": self}) ] self._add_extra_handlers(handlers) self._add_static_handlers(handlers) return Application(handlers, template_path=self.template_dir)
def make_tornado_app(self)
Creates a :py:class`tornado.web.Application` instance that respect the JSON RPC 2.0 specs and exposes the designated methods. Can be used in tests to obtain the Tornado application. :return: a :py:class:`tornado.web.Application` instance
4.91819
6.08934
0.807672
extra_handlers = [(h[0], h[1], {"microservice": self}) for h in self.extra_handlers] handlers.extend(extra_handlers)
def _add_extra_handlers(self, handlers)
Adds the extra handler (defined by the user) :param handlers: a list of :py:class:`tornado.web.RequestHandler` instances. :return:
5.076396
7.502653
0.676613
for url, path in self.static_dirs: handlers.append((url.rstrip("/") + "/(.*)", StaticFileHandler, {"path": path}))
def _add_static_handlers(self, handlers)
Creates and adds the handles needed for serving static files. :param handlers:
4.948598
6.563762
0.753927
self._extract_methods_from_container(self) for module in self.modules: self._extract_methods_from_container(module)
def _gather_exposed_methods(self)
Searches for the exposed methods in the current microservice class. A method is considered exposed if it is decorated with the :py:func:`gemstone.public_method` or :py:func:`gemstone.private_api_method`.
6.027905
6.365685
0.946937
self._extract_event_handlers_from_container(self) for module in self.modules: self._extract_event_handlers_from_container(module)
def _gather_event_handlers(self)
Searches for the event handlers in the current microservice class. :return:
4.5798
6.053452
0.75656
for strategy in self.discovery_strategies: self.default_periodic_tasks.append( (functools.partial(strategy.ping, self.name, self.accessible_at), self.service_registry_ping_interval) ) self.default_periodic_tasks[-1][0]() all_...
def _periodic_task_iter(self)
Iterates through all the periodic tasks: - the service registry pinging - default dummy task if on Windows - user defined periodic tasks :return:
4.451504
4.101958
1.085214
'''Calling this function initializes the printer. Args: None Returns: None Raises: None ''' self.fonttype = self.font_types['bitmap'] self.send(chr(27)+chr(64))
def initialize(self)
Calling this function initializes the printer. Args: None Returns: None Raises: None
10.044047
6.107329
1.644589
'''Select international character set and changes codes in code table accordingly Args: charset: String. The character set we want. Returns: None Raises: RuntimeError: Invalid charset. ''' charsets = {'USA':0, ...
def select_charset(self, charset)
Select international character set and changes codes in code table accordingly Args: charset: String. The character set we want. Returns: None Raises: RuntimeError: Invalid charset.
4.627105
2.832664
1.633482
'''Select character code table, from tree built in ones. Args: table: The desired character code table. Choose from 'standard', 'eastern european', 'western european', and 'spare' Returns: None Raises: RuntimeError: Invalid chartable. ...
def select_char_code_table(self, table)
Select character code table, from tree built in ones. Args: table: The desired character code table. Choose from 'standard', 'eastern european', 'western european', and 'spare' Returns: None Raises: RuntimeError: Invalid chartable.
5.777058
2.008856
2.875795
'''Set cut setting for printer. Args: cut: The type of cut setting we want. Choices are 'full', 'half', 'chain', and 'special'. Returns: None Raises: RuntimeError: Invalid cut type. ''' cut_settings = {'full' : 0b0000...
def cut_setting(self, cut)
Set cut setting for printer. Args: cut: The type of cut setting we want. Choices are 'full', 'half', 'chain', and 'special'. Returns: None Raises: RuntimeError: Invalid cut type.
3.405402
1.910678
1.7823
'''Calling this function applies the desired action to the printing orientation of the printer. Args: action: The desired printing orientation. 'rotate' enables rotated printing. 'normal' disables rotated printing. Returns: None Raises: ...
def rotated_printing(self, action)
Calling this function applies the desired action to the printing orientation of the printer. Args: action: The desired printing orientation. 'rotate' enables rotated printing. 'normal' disables rotated printing. Returns: None Raises: RuntimeEr...
5.986308
2.393291
2.501287
'''Calling this function sets the form feed amount to the specified setting. Args: amount: the form feed setting you desire. Options are '1/8', '1/6', 'x/180', and 'x/60', with x being your own desired amount. X must be a minimum of 24 for 'x/180' and 8 for 'x/60' Re...
def feed_amount(self, amount)
Calling this function sets the form feed amount to the specified setting. Args: amount: the form feed setting you desire. Options are '1/8', '1/6', 'x/180', and 'x/60', with x being your own desired amount. X must be a minimum of 24 for 'x/180' and 8 for 'x/60' Returns: ...
4.036238
1.861118
2.168717
'''Specifies page length. This command is only valid with continuous length labels. Args: length: The length of the page, in dots. Can't exceed 12000. Returns: None Raises: RuntimeError: Length must be less than 12000. ''' mH =...
def page_length(self, length)
Specifies page length. This command is only valid with continuous length labels. Args: length: The length of the page, in dots. Can't exceed 12000. Returns: None Raises: RuntimeError: Length must be less than 12000.
4.992296
2.481225
2.012029
'''Specify settings for top and bottom margins. Physically printable area depends on media. Args: topmargin: the top margin, in dots. The top margin must be less than the bottom margin. bottommargin: the bottom margin, in dots. The bottom margin must be less than the top...
def page_format(self, topmargin, bottommargin)
Specify settings for top and bottom margins. Physically printable area depends on media. Args: topmargin: the top margin, in dots. The top margin must be less than the bottom margin. bottommargin: the bottom margin, in dots. The bottom margin must be less than the top margin. ...
3.759951
2.153738
1.74578
'''Specify the left margin. Args: margin: The left margin, in character width. Must be less than the media's width. Returns: None Raises: RuntimeError: Invalid margin parameter. ''' if margin <= 255 and margin >= 0: ...
def left_margin(self, margin)
Specify the left margin. Args: margin: The left margin, in character width. Must be less than the media's width. Returns: None Raises: RuntimeError: Invalid margin parameter.
6.28678
2.722995
2.308774
'''Specify the right margin. Args: margin: The right margin, in character width, must be less than the media's width. Returns: None Raises: RuntimeError: Invalid margin parameter ''' if margin >=1 and margin <=255: ...
def right_margin(self, margin)
Specify the right margin. Args: margin: The right margin, in character width, must be less than the media's width. Returns: None Raises: RuntimeError: Invalid margin parameter
7.796575
3.410788
2.285857
'''Sets tab positions, up to a maximum of 32 positions. Also can clear tab positions. Args: positions -- Either a list of tab positions (between 1 and 255), or 'clear'. Returns: None Raises: RuntimeError: Invalid position parameter. ...
def vert_tab_pos(self, positions)
Sets tab positions, up to a maximum of 32 positions. Also can clear tab positions. Args: positions -- Either a list of tab positions (between 1 and 255), or 'clear'. Returns: None Raises: RuntimeError: Invalid position parameter. RuntimeEr...
4.675123
2.566674
1.821471