code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
params = { 'LoadBalancerName' : lb_name, 'LoadBalancerPort' : lb_port, } self.build_list_params(params, policies, 'PolicyNames.member.%d') return self.get_status('SetLoadBalancerPoliciesOfListener', params)
def set_lb_policies_of_listener(self, lb_name, lb_port, policies)
Associates, updates, or disables a policy with a listener on the load balancer. Currently only zero (0) or one (1) policy can be associated with a listener.
3.197691
3.060353
1.044876
params = {'LoadBalancerName' : name} self.build_list_params(params, security_groups, 'SecurityGroups.member.%d') return self.get_list('ApplySecurityGroupsToLoadBalancer', params, None)
def apply_security_groups_to_lb(self, name, security_groups)
Applies security groups to the load balancer. Applying security groups that are already registered with the Load Balancer has no effect. :type name: string :param name: The name of the Load Balancer :type security_groups: List of strings :param security_groups: The nam...
3.704824
4.425158
0.837219
params = {'LoadBalancerName' : name} self.build_list_params(params, subnets, 'Subnets.member.%d') return self.get_list('AttachLoadBalancerToSubnets', params, None)
def attach_lb_to_subnets(self, name, subnets)
Attaches load balancer to one or more subnets. Attaching subnets that are already registered with the Load Balancer has no effect. :type name: string :param name: The name of the Load Balancer :type subnets: List of strings :param subnets: The name of the subnet(s) to ...
3.807318
4.467241
0.852275
params = {'LoadBalancerName' : name} self.build_list_params(params, subnets, 'Subnets.member.%d') return self.get_list('DettachLoadBalancerFromSubnets', params, None)
def detach_lb_from_subnets(self, name, subnets)
Detaches load balancer from one or more subnets. :type name: string :param name: The name of the Load Balancer :type subnets: List of strings :param subnets: The name of the subnet(s) to detach. :rtype: List of strings :return: An updated list of subnets for this Load ...
3.9117
5.608756
0.697427
for key in list(target_dict.keys()): if key not in src_dict: target_dict.pop(key)
def remove_missing_keys(src_dict, target_dict)
Remove keys from target_dict that are not available in src_dict :param src_dict: source dictionary to search for :param target_dict: target dictionary where keys should be removed
2.006583
2.884989
0.695525
fname = os.path.basename(path) # if file name exists in path, skip the filename if fname.__contains__('.'): path = os.path.dirname(path) if not os.path.exists(path): os.makedirs(path)
def create_dirs(path)
Creates all directories mentioned in the given path. Useful to write a new file with the specified path. It carefully skips the file-name in the given path. :param path: Path of a file or directory
4.138374
4.580444
0.903488
for fname in os.listdir(dir_path): if fname.endswith('.jpg') or fname.endswith('.png') or fname.endswith('.bmp'): yield fname
def each_img(dir_path)
Iterates through each image in the given directory. (not recursive) :param dir_path: Directory path where images files are present :return: Iterator to iterate through image files
2.329012
2.898012
0.803658
instance = cls(symbol, start_date, end_date) return instance.data
def select(cls, symbol, start_date, end_date)
Method returns stock prices for current: ticker/symbol, start date, end date.
4.80666
4.466132
1.076247
if relativedelta(self.end_date, self.start_date).years <= const.ONE_YEAR: data = self.request.send(self.symbol, self.start_date, self.end_date) else: data = self.fetch_chunk_data() return self.clean(data)
def fetch_data(self)
Method returns results from response of Yahoo YQL API. It should returns always python list.
5.092793
4.761889
1.06949
data = [] counter = (relativedelta(self.end_date, self.start_date).months / 6) + 1 months = 0 for month in range(counter): chunk_start_date = self.start_date + relativedelta(months=months) chunk_end_date = self.start_date + relativedelta(months=months ...
def fetch_chunk_data(self)
If period of time between start end end is bigger then one year We have to create and fetch chunks dates (6 months chunks).
2.809484
2.394141
1.173483
cleaned_data = list() if not isinstance(data, list): data = [data] for item in data: date = datetime.datetime.strptime(item['Date'], '%Y-%m-%d').date() cleaned_data.append(dict(price=item['Adj_Close'], date=date)) return cleaned_data
def clean(self, data)
Method returns cleaned list of stock closing prices (i.e. dict(date=datetime.date(2015, 1, 2), price='23.21')).
2.837403
2.384516
1.189929
if self.connection_cls: return self.connection_cls(region=self, **kw_params)
def connect(self, **kw_params)
Connect to this Region's endpoint. Returns an connection object pointing to the endpoint associated with this region. You may pass any of the arguments accepted by the connection class's constructor as keyword arguments and they will be passed along to the connection object. ...
6.244895
5.696658
1.096238
params = dict( Title=title, Description=description, AssignmentDurationInSeconds= self.duration_as_seconds(duration), ) params.update(MTurkConnection.get_price_as_price(reward).get_as_params('Reward')) if keywords: ...
def register_hit_type(self, title, description, reward, duration, keywords=None, approval_delay=None, qual_req=None)
Register a new HIT Type title, description are strings reward is a Price object duration can be a timedelta, or an object castable to an int
3.620801
3.41525
1.060186
return self._set_notification(hit_type, 'Email', email, event_types)
def set_email_notification(self, hit_type, email, event_types=None)
Performs a SetHITTypeNotification operation to set email notification for a specified HIT type
4.183973
4.845958
0.863394
return self._set_notification(hit_type, 'REST', url, event_types)
def set_rest_notification(self, hit_type, url, event_types=None)
Performs a SetHITTypeNotification operation to set REST notification for a specified HIT type
3.895768
5.016868
0.776534
assert type(hit_type) is str, "hit_type argument should be a string." params = {'HITTypeId': hit_type} # from the Developer Guide: # The 'Active' parameter is optional. If omitted, the active status of # the HIT type's notification specification is unch...
def _set_notification(self, hit_type, transport, destination, event_types=None)
Common SetHITTypeNotification operation to set notification for a specified HIT type
5.630886
5.378899
1.046847
# handle single or multiple questions neither = question is None and questions is None both = question is not None and questions is not None if neither or both: raise ValueError("Must specify either question (single Question instance) or questions (list or Q...
def create_hit(self, hit_type=None, question=None, lifetime=datetime.timedelta(days=7), max_assignments=1, title=None, description=None, keywords=None, reward=None, duration=datetime.timedelta(days=7), approval_delay=None, a...
Creates a new HIT. Returns a ResultSet See: http://docs.amazonwebservices.com/AWSMechanicalTurkRequester/2006-10-31/ApiReference_CreateHITOperation.html
3.900872
3.6785
1.060452
params = {'HITId' : hit_id, 'HITTypeId': hit_type} return self._process_request('ChangeHITTypeOfHIT', params)
def change_hit_type_of_hit(self, hit_id, hit_type)
Change the HIT type of an existing HIT. Note that the reward associated with the new HIT type must match the reward of the current HIT type in order for the operation to be valid. :type hit_id: str :type hit_type: str
4.872483
6.6894
0.728389
params = {'Status' : status, 'SortProperty' : sort_by, 'SortDirection' : sort_direction, 'PageSize' : page_size, 'PageNumber' : page_number} # Handle optional hit_type argument if hit_type is not None: ...
def get_reviewable_hits(self, hit_type=None, status='Reviewable', sort_by='Expiration', sort_direction='Ascending', page_size=10, page_number=1)
Retrieve the HITs that have a status of Reviewable, or HITs that have a status of Reviewing, and that belong to the Requester calling the operation.
2.656346
2.814669
0.943751
pages = total_records/page_size+bool(total_records%page_size) return range(1, pages+1)
def _get_pages(page_size, total_records)
Given a page size (records per page) and a total number of records, return the page numbers to be retrieved.
4.15076
3.883117
1.068925
page_size = 100 search_rs = self.search_hits(page_size=page_size) total_records = int(search_rs.TotalNumResults) get_page_hits = lambda(page): self.search_hits(page_size=page_size, page_number=page) page_nums = self._get_pages(page_size, total_records) hit_sets =...
def get_all_hits(self)
Return all of a Requester's HITs Despite what search_hits says, it does not return all hits, but instead returns a page of hits. This method will pull the hits from the server 100 at a time, but will yield the results iteratively, so subsequent requests are made on demand.
3.548838
3.098563
1.145317
params = {'SortProperty' : sort_by, 'SortDirection' : sort_direction, 'PageSize' : page_size, 'PageNumber' : page_number} # Handle optional response groups argument if response_groups: self.build_list_params(params, respo...
def search_hits(self, sort_by='CreationTime', sort_direction='Ascending', page_size=10, page_number=1, response_groups=None)
Return a page of a Requester's HITs, on behalf of the Requester. The operation returns HITs of any status, except for HITs that have been disposed with the DisposeHIT operation. Note: The SearchHITs operation does not accept any search parameters that filter the results.
3.404628
3.69637
0.921073
params = {'HITId' : hit_id, 'SortProperty' : sort_by, 'SortDirection' : sort_direction, 'PageSize' : page_size, 'PageNumber' : page_number} if status is not None: params['AssignmentStatus'] = status # ...
def get_assignments(self, hit_id, status=None, sort_by='SubmitTime', sort_direction='Ascending', page_size=10, page_number=1, response_groups=None)
Retrieves completed assignments for a HIT. Use this operation to retrieve the results for a HIT. The returned ResultSet will have the following attributes: NumResults The number of assignments on the page in the filtered results list, equivalent to the number o...
2.867538
3.33479
0.859885
params = {'HITId' : hit_id,} if revert: params['Revert'] = revert return self._process_request('SetHITAsReviewing', params)
def set_reviewing(self, hit_id, revert=None)
Update a HIT with a status of Reviewable to have a status of Reviewing, or reverts a Reviewing HIT back to the Reviewable status. Only HITs with a status of Reviewable can be updated with a status of Reviewing. Similarly, only Reviewing HITs can be reverted back to a status of Reviewa...
4.049597
4.987097
0.812015
params = {'HITId' : hit_id,} # Handle optional response groups argument if response_groups: self.build_list_params(params, response_groups, 'ResponseGroup') return self._process_request('DisableHIT', params)
def disable_hit(self, hit_id, response_groups=None)
Remove a HIT from the Mechanical Turk marketplace, approves all submitted assignments that have not already been approved or rejected, and disposes of the HIT and all assignment data. Assignments for the HIT that have already been submitted, but not yet approved or rejected, will be aut...
4.638159
5.292061
0.876437
# must provide assignment *or* expiration increment if (assignments_increment is None and expiration_increment is None) or \ (assignments_increment is not None and expiration_increment is not None): raise ValueError("Must specify either assignments_increment or expiration...
def extend_hit(self, hit_id, assignments_increment=None, expiration_increment=None)
Increase the maximum number of assignments, or extend the expiration date, of an existing HIT. NOTE: If a HIT has a status of Reviewable and the HIT is extended to make it Available, the HIT will not be returned by GetReviewableHITs, and its submitted assignments will not be ...
2.539975
2.611997
0.972426
params = {'About': about, 'HelpType': help_type,} return self._process_request('Help', params)
def get_help(self, about, help_type='Operation')
Return information about the Mechanical Turk Service operations and response group NOTE - this is basically useless as it just returns the URL of the documentation help_type: either 'Operation' or 'ResponseGroup'
5.413188
5.672242
0.954329
params = bonus_price.get_as_params('BonusAmount', 1) params['WorkerId'] = worker_id params['AssignmentId'] = assignment_id params['Reason'] = reason return self._process_request('GrantBonus', params)
def grant_bonus(self, worker_id, assignment_id, bonus_price, reason)
Issues a payment of money from your account to a Worker. To be eligible for a bonus, the Worker must have submitted results for one of your HITs, and have had those results approved or rejected. This payment happens separately from the reward you pay to the Worker when you approve the W...
4.190137
4.080256
1.02693
params = {'WorkerId': worker_id, 'Reason': reason} return self._process_request('BlockWorker', params)
def block_worker(self, worker_id, reason)
Block a worker from working on my tasks.
4.914162
3.846308
1.277631
params = {'WorkerId': worker_id, 'Reason': reason} return self._process_request('UnblockWorker', params)
def unblock_worker(self, worker_id, reason)
Unblock a worker from working on my tasks.
4.488671
3.742586
1.19935
params = {'Subject' : subject, 'MessageText': message_text} self.build_list_params(params, worker_ids, 'WorkerId') return self._process_request('NotifyWorkers', params)
def notify_workers(self, worker_ids, subject, message_text)
Send a text message to workers.
5.144926
4.415916
1.165087
params = {'Name' : name, 'Description' : description, 'QualificationTypeStatus' : status, } if retry_delay is not None: params['RetryDelayInSeconds'] = retry_delay if test is not None: assert(isinstance(test...
def create_qualification_type(self, name, description, status, keywords=None, retry_delay=None, test=None, ...
Create a new Qualification Type. name: This will be visible to workers and must be unique for a given requester. description: description shown to workers. Max 2000 characters. status: 'Active' or 'Inactive' keywords: list of keyword strings or comma separated string. ...
2.677016
2.529625
1.058266
params = {'Query' : query, 'SortProperty' : sort_by, 'SortDirection' : sort_direction, 'PageSize' : page_size, 'PageNumber' : page_number, 'MustBeRequestable' : must_be_requestable, 'MustBeOwnedB...
def search_qualification_types(self, query=None, sort_by='Name', sort_direction='Ascending', page_size=10, page_number=1, must_be_requestable=True, must_be_owned_by_caller=True)
TODO: Document.
1.917997
1.887681
1.01606
params = {'QualificationTypeId' : qualification_type_id, 'SortProperty' : sort_by, 'SortDirection' : sort_direction, 'PageSize' : page_size, 'PageNumber' : page_number} return self._process_request('GetQualificationRequests...
def get_qualification_requests(self, qualification_type_id, sort_by='Expiration', sort_direction='Ascending', page_size=10, page_number=1)
TODO: Document.
2.690073
2.643374
1.017666
params = {'QualificationRequestId' : qualification_request_id, 'IntegerValue' : integer_value} return self._process_request('GrantQualification', params)
def grant_qualification(self, qualification_request_id, integer_value=1)
TODO: Document.
3.148539
2.645976
1.189935
params = {'SubjectId' : subject_id, 'QualificationTypeId' : qualification_type_id, 'Reason' : reason} return self._process_request('RevokeQualification', params)
def revoke_qualification(self, subject_id, qualification_type_id, reason=None)
TODO: Document.
2.371491
2.273412
1.043142
params = {'QualificationTypeId' : qualification_type_id, 'SubjectId' : worker_id} return self._process_request('GetQualificationScore', params, [('Qualification', Qualification),])
def get_qualification_score(self, qualification_type_id, worker_id)
TODO: Document.
5.317852
4.681252
1.135989
params = {'QualificationTypeId' : qualification_type_id, 'SubjectId' : worker_id, 'IntegerValue' : value} return self._process_request('UpdateQualificationScore', params)
def update_qualification_score(self, qualification_type_id, worker_id, value)
TODO: Document.
3.556378
3.295484
1.079167
response = self.make_request(request_type, params, verb='POST') return self._process_response(response, marker_elems)
def _process_request(self, request_type, params, marker_elems=None)
Helper to process the xml response from AWS
3.689968
3.308416
1.115328
body = response.read() #print body if '<Errors>' not in body: rs = ResultSet(marker_elems) h = handler.XmlHandler(rs, self) xml.sax.parseString(body, h) return rs else: raise MTurkRequestError(response.status, response....
def _process_response(self, response, marker_elems=None)
Helper to process the xml response from AWS
4.470784
4.142326
1.079293
if type(keywords) is list: keywords = ', '.join(keywords) if type(keywords) is str: final_keywords = keywords elif type(keywords) is unicode: final_keywords = keywords.encode('utf-8') elif keywords is None: final_keywords = "" ...
def get_keywords_as_string(keywords)
Returns a comma+space-separated string of keywords from either a list or a string
2.347338
2.325062
1.009581
if isinstance(reward, Price): final_price = reward else: final_price = Price(reward) return final_price
def get_price_as_price(reward)
Returns a Price data structure from either a float or a Price
3.719923
2.813864
1.321998
expired = False if hasattr(self, 'Expiration'): now = datetime.datetime.utcnow() expiration = datetime.datetime.strptime(self.Expiration, '%Y-%m-%dT%H:%M:%SZ') expired = (now >= expiration) else: raise ValueError("ERROR: Request for expire...
def _has_expired(self)
Has this HIT expired yet?
4.22154
3.412634
1.237033
more_results = True k = None while more_results: rs = bucket.get_all_keys(prefix=prefix, marker=marker, delimiter=delimiter, headers=headers) for k in rs: yield k if k: marker = rs.next_marker or k.name more_result...
def bucket_lister(bucket, prefix='', delimiter='', marker='', headers=None)
A generator function for listing keys in a bucket.
3.311977
3.29574
1.004927
more_results = True k = None while more_results: rs = bucket.get_all_versions(prefix=prefix, key_marker=key_marker, version_id_marker=version_id_marker, delimiter=delimiter, headers=headers, ...
def versioned_bucket_lister(bucket, prefix='', delimiter='', key_marker='', version_id_marker='', headers=None)
A generator function for listing versions in a bucket.
2.150892
2.181333
0.986045
more_results = True k = None while more_results: rs = bucket.get_all_multipart_uploads(key_marker=key_marker, upload_id_marker=upload_id_marker, headers=headers) for k in rs: yield k ...
def multipart_upload_lister(bucket, key_marker='', upload_id_marker='', headers=None)
A generator function for listing multipart uploads in a bucket.
2.106317
2.095516
1.005154
return self.connection.put_attributes(self, item_name, attributes, replace, expected_value)
def put_attributes(self, item_name, attributes, replace=True, expected_value=None)
Store attributes for a given item. :type item_name: string :param item_name: The name of the item whose attributes are being stored. :type attribute_names: dict or dict-like object :param attribute_names: The name/value pairs to store as attributes :type expected_value: list ...
3.495153
4.972055
0.70296
return self.connection.batch_put_attributes(self, items, replace)
def batch_put_attributes(self, items, replace=True)
Store attributes for multiple items. :type items: dict or dict-like object :param items: A dictionary-like object. The keys of the dictionary are the item names and the values are themselves dictionaries of attribute names/values, exactly the same as the ...
3.955326
8.815349
0.448686
return self.connection.get_attributes(self, item_name, attribute_name, consistent_read, item)
def get_attributes(self, item_name, attribute_name=None, consistent_read=False, item=None)
Retrieve attributes for a given item. :type item_name: string :param item_name: The name of the item whose attributes are being retrieved. :type attribute_names: string or list of strings :param attribute_names: An attribute name or list of attribute names. This ...
2.961683
4.879327
0.606986
return self.connection.delete_attributes(self, item_name, attributes, expected_values)
def delete_attributes(self, item_name, attributes=None, expected_values=None)
Delete attributes from a given item. :type item_name: string :param item_name: The name of the item whose attributes are being deleted. :type attributes: dict, list or :class:`boto.sdb.item.Item` :param attributes: Either a list containing attribute names which will cause ...
3.763693
5.914599
0.636339
return SelectResultSet(self, query, max_items=max_items, next_token=next_token, consistent_read=consistent_read)
def select(self, query='', next_token=None, consistent_read=False, max_items=None)
Returns a set of Attributes for item names within domain_name that match the query. The query must be expressed in using the SELECT style syntax rather than the original SimpleDB query language. :type query: string :param query: The SimpleDB query to be performed. :rtype: iter ...
3.165588
4.33262
0.730641
item = self.get_attributes(item_name, consistent_read=consistent_read) if item: item.domain = self return item else: return None
def get_item(self, item_name, consistent_read=False)
Retrieves an item from the domain, along with all of its attributes. :param string item_name: The name of the item to retrieve. :rtype: :class:`boto.sdb.item.Item` or ``None`` :keyword bool consistent_read: When set to true, ensures that the most ...
3.456697
4.441301
0.778307
if not f: from tempfile import TemporaryFile f = TemporaryFile() print >> f, '<?xml version="1.0" encoding="UTF-8"?>' print >> f, '<Domain id="%s">' % self.name for item in self: print >> f, '\t<Item id="%s">' % item.name for k in ...
def to_xml(self, f=None)
Get this domain as an XML DOM Document :param f: Optional File to dump directly to :type f: File or Stream :return: File object where the XML has been dumped to :rtype: file
1.922888
1.935864
0.993297
import xml.sax handler = DomainDumpParser(self) xml.sax.parse(doc, handler) return handler
def from_xml(self, doc)
Load this domain based on an XML document
7.47212
6.427514
1.162521
# NOTE: only check content digest if locally cached content is set # (content already pulled or new content set); otherwise this # results in pulling content down to checksum it ! return self.info_modified or \ self._content and self._content_digest() != self.digest
def isModified(self)
Check if either the datastream content or profile fields have changed and should be saved to Fedora. :rtype: boolean
34.121681
33.03775
1.032809
'''Get history/version information for this datastream and return as an instance of :class:`~eulfedora.xml.DatastreamHistory`.''' r = self.obj.api.getDatastreamHistory(self.obj.pid, self.id, format='xml') return parse_xml_object(DatastreamHistory, r.content, r.url)
def history(self)
Get history/version information for this datastream and return as an instance of :class:`~eulfedora.xml.DatastreamHistory`.
7.740679
3.305776
2.341562
if self.as_of_date is not None: raise RuntimeError('Saving is not implemented for datastream versions') save_opts = {} if self.info_modified: if self.label: save_opts['dsLabel'] = self.label if self.mimetype: save_opts...
def save(self, logmessage=None)
Save datastream content and any changed datastream profile information to Fedora. :rtype: boolean for success
4.085366
3.860344
1.058291
# NOTE: currently not clearing any of the object caches and backups # of fedora content and datastream info, as it is unclear what (if anything) # should be cleared if self.versionable: # if this is a versioned datastream, get datastream history # and pu...
def undo_last_save(self, logMessage=None)
Undo the last change made to the datastream content and profile, effectively reverting to the object state in Fedora as of the specified timestamp. For a versioned datastream, this will purge the most recent datastream. For an unversioned datastream, this will overwrite the last changes with ...
5.996204
4.660965
1.286473
'''Generator that returns the datastream content in chunks, so larger datastreams can be used without reading the entire contents into memory.''' # get the datastream dissemination, but return the actual http response r = self.obj.api.getDatastreamDissemination(self.obj.pid, sel...
def get_chunked_content(self, chunksize=4096)
Generator that returns the datastream content in chunks, so larger datastreams can be used without reading the entire contents into memory.
9.482681
5.19
1.827106
'''Check if this datastream has a valid checksum in Fedora, by running the :meth:`REST_API.compareDatastreamChecksum` API call. Returns a boolean based on the checksum valid response from Fedora. :param date: (optional) check the datastream validity at a particular ...
def validate_checksum(self, date=None)
Check if this datastream has a valid checksum in Fedora, by running the :meth:`REST_API.compareDatastreamChecksum` API call. Returns a boolean based on the checksum valid response from Fedora. :param date: (optional) check the datastream validity at a particular date/time (...
9.342092
2.712039
3.444674
# NB: The hypothetical statement <src> <src> <src> will be removed # and re-added several times. The subject block will remove it and # add <dest> <src> <src>. The predicate block will remove that and # add <dest> <dest> <src>. The object block will then remove that # a...
def replace_uri(self, src, dest)
Replace a uri reference everywhere it appears in the graph with another one. It could appear as the subject, predicate, or object of a statement, so for each position loop through each statement that uses the reference in that position, remove the old statement, and add the replacement.
4.272299
3.958334
1.079318
# see also commentary on DigitalObject.DUMMY_URIREF self.replace_uri(self.obj.DUMMY_URIREF, self.obj.uriref)
def _prepare_ingest(self)
If the RDF datastream refers to the object by the default dummy uriref then we need to replace that dummy reference with a real one before we ingest the object.
24.176289
11.51096
2.100284
"Instance of :class:`eulfedora.api.ResourceIndex`, with the same root url and credentials" if self._risearch is None: self._risearch = ResourceIndex(self.api.base_url, self.api.username, self.api.password) return self._risearch
def risearch(self)
Instance of :class:`eulfedora.api.ResourceIndex`, with the same root url and credentials
5.281918
2.432387
2.171496
'''Initialize and return a new :class:`~eulfedora.models.DigitalObject` instance from the same repository, passing along the connection credentials in use by the current object. If type is not specified, the current DigitalObject class will be used. :param pid: pid of t...
def get_object(self, pid, type=None)
Initialize and return a new :class:`~eulfedora.models.DigitalObject` instance from the same repository, passing along the connection credentials in use by the current object. If type is not specified, the current DigitalObject class will be used. :param pid: pid of the object t...
5.169238
1.664042
3.106434
'''Get the next default pid when creating and ingesting a new DigitalObject instance without specifying a pid. By default, calls :meth:`ApiFacade.getNextPID` with the configured class default_pidspace (if specified) as the pid namespace. If your project requires custom pid logi...
def get_default_pid(self)
Get the next default pid when creating and ingesting a new DigitalObject instance without specifying a pid. By default, calls :meth:`ApiFacade.getNextPID` with the configured class default_pidspace (if specified) as the pid namespace. If your project requires custom pid logic (e.g., ob...
10.400002
2.994976
3.472483
"Fedora URI for this object (``info:fedora/foo:###`` form of object pid) " use_pid = self.pid if callable(use_pid): use_pid = self.DUMMY_PID return 'info:fedora/' + use_pid
def uri(self)
Fedora URI for this object (``info:fedora/foo:###`` form of object pid)
15.283216
4.666218
3.275289
'''Read-only list of object owners, separated by the configured :attr:`OWNER_ID_SEPARATOR`, with whitespace stripped.''' return [o.strip() for o in self.owner.split(self.OWNER_ID_SEPARATOR)]
def owners(self)
Read-only list of object owners, separated by the configured :attr:`OWNER_ID_SEPARATOR`, with whitespace stripped.
8.785028
2.698989
3.254933
# If we made the object under the pretext that it doesn't exist in # fedora yet, then assume it doesn't exist in fedora yet. if self._create: return False # If we can get a valid object profile, regardless of its contents, # then this object exists. If not,...
def exists(self)
:type: bool True when the object actually exists (and can be accessed by the current user) in Fedora
10.599269
9.13454
1.160351
''':type: bool True when the current object has the expected content models for whatever subclass of :class:`DigitalObject` it was initialized as.''' for cmodel in getattr(self, 'CONTENT_MODELS', ()): if not self.has_model(cmodel): return False ...
def has_requisite_content_models(self)
:type: bool True when the current object has the expected content models for whatever subclass of :class:`DigitalObject` it was initialized as.
10.470071
3.104121
3.372958
# NOTE: used by DatastreamObject if self._create: return None r = self.api.getDatastream(self.pid, dsid, asOfDateTime=date) return parse_xml_object(DatastreamProfile, r.content, r.url)
def getDatastreamProfile(self, dsid, date=None)
Get information about a particular datastream belonging to this object. :param dsid: datastream id :rtype: :class:`DatastreamProfile`
8.170053
8.390071
0.973776
'''Username responsible for ingesting this object into the repository, as recorded in the :attr:`audit_trail`, if available.''' # if there is an audit trail and it has records and the first # action is ingest, return the user if self.audit_trail and self.audit_trail.records \ ...
def ingest_user(self)
Username responsible for ingesting this object into the repository, as recorded in the :attr:`audit_trail`, if available.
6.426452
3.02576
2.123914
'''A set of all usernames recorded in the :attr:`audit_trail`, if available.''' if self.audit_trail: return set([r.user for r in self.audit_trail.records]) return set()
def audit_trail_users(self)
A set of all usernames recorded in the :attr:`audit_trail`, if available.
6.738454
2.803249
2.403801
if self._create: return ObjectProfile() else: if self._profile is None: r = self.api.getObjectProfile(self.pid) self._profile = parse_xml_object(ObjectProfile, r.content, r.url) return self._profile
def getProfile(self)
Get information about this object (label, owner, date created, etc.). :rtype: :class:`ObjectProfile`
5.114288
4.527524
1.129599
if self._create: self._prepare_ingest() self._ingest(logMessage) else: self._save_existing(logMessage) #No errors, then return true return True
def save(self, logMessage=None)
Save to Fedora any parts of this object that have been modified (including object profile attributes such as :attr:`label`, :attr:`owner`, or :attr:`state`, and any changes to datastream content or datastream properties). If a failure occurs at any point on saving any of the parts of th...
9.240949
9.152925
1.009617
return [ds for ds in datastreams if self.dscache[ds].undo_last_save(logMessage)]
def _undo_save(self, datastreams, logMessage=None)
Takes a list of datastreams and a datetime, run undo save on all of them, and returns a list of the datastreams where the undo succeeded. :param datastreams: list of datastream ids (should be in self.dscache) :param logMessage: optional log message
11.170782
5.829953
1.916102
if self._create: # FIXME: should we default to the datastreams defined in code? return {} else: # NOTE: can be accessed as a cached class property via ds_list r = self.api.listDatastreams(self.pid) dsobj = parse_xml_object(ObjectDatast...
def _get_datastreams(self)
Get all datastreams that belong to this object. Returns a dictionary; key is datastream id, value is an :class:`ObjectDatastream` for that datastream. :rtype: dictionary
8.913447
8.728981
1.021133
self._ds_list = self._get_datastreams() return self._ds_list
def ds_list(self): # NOTE: how to name to distinguish from locally configured datastream objects? # FIXME: how to make access to a versioned ds_list ? if self._ds_list is None
Dictionary of all datastreams that belong to this object in Fedora. Key is datastream id, value is an :class:`ObjectDatastream` for that datastream. Only retrieved when requested; cached after first retrieval.
6.006132
5.846579
1.02729
'''Get any datastream on this object as a :class:`DatastreamObject` **or** add a new datastream. If the datastream id corresponds to a predefined datastream, the configured object will be returned and the datastream object will be returned. If type is not specified for an exist...
def getDatastreamObject(self, dsid, dsobj_type=None, as_of_date=None)
Get any datastream on this object as a :class:`DatastreamObject` **or** add a new datastream. If the datastream id corresponds to a predefined datastream, the configured object will be returned and the datastream object will be returned. If type is not specified for an existing datastr...
4.465206
2.833958
1.575608
if isinstance(rel_uri, URIRef): rel_uri = force_text(rel_uri) obj_is_literal = True if isinstance(obj, DigitalObject): obj = obj.uri obj_is_literal = False elif (isinstance(obj, str) or isinstance(obj, six.string_types)) \ and obj.s...
def add_relationship(self, rel_uri, obj)
Add a new relationship to the RELS-EXT for this object. Calls :meth:`API_M.addRelationship`. Example usage:: isMemberOfCollection = 'info:fedora/fedora-system:def/relations-external#isMemberOfCollection' collection_uri = 'info:fedora/foo:456' object.add_relationship...
4.748819
4.136791
1.147948
if isinstance(rel_uri, URIRef): rel_uri = force_text(rel_uri) # old_object obj_old_is_literal = True if isinstance(old_object, DigitalObject): old_object = old_object.uri obj_old_is_literal = False elif (isinstance(old_object, str) o...
def modify_relationship(self, rel_uri, old_object, new_object)
Modify a relationship from RELS-EXT for this object. As the Fedora API-M does not contain a native "modifyRelationship", this method purges an existing one, then adds a new one, pivoting on the predicate. Calls :meth:`API_M.purgeRelationship`, :meth:`API_M.addRelationship` Example usag...
2.733699
2.474587
1.104709
# TODO: # - accept DigitalObject for model? # - convert model pid to info:fedora/ form if not passed in that way? try: rels = self.rels_ext.content except RequestFailed: # if rels-ext can't be retrieved, confirm this object does not have a RELS-EX...
def has_model(self, model)
Check if this object subscribes to the specified content model. :param model: URI for the content model, as a string (currently only accepted in ``info:fedora/foo:###`` format) :rtype: boolean
13.427849
10.274031
1.30697
try: rels = self.rels_ext.content except RequestFailed: # if rels-ext can't be retrieved, confirm this object does not have a RELS-EXT # (in which case, it does not have any content models) if "RELS-EXT" not in self.ds_list.keys(): ...
def get_models(self)
Get a list of content models the object subscribes to.
8.817721
7.926325
1.11246
'''Generate and return a dictionary of default fields to be indexed for searching (e.g., in Solr). Includes top-level object properties, Content Model URIs, and Dublin Core fields. This method is intended to be customized and extended in order to easily modify the field...
def index_data(self)
Generate and return a dictionary of default fields to be indexed for searching (e.g., in Solr). Includes top-level object properties, Content Model URIs, and Dublin Core fields. This method is intended to be customized and extended in order to easily modify the fields that shou...
7.232269
3.282777
2.203095
'''Descriptive data to be included in :meth:`index_data` output. This implementation includes all Dublin Core fields, but should be extended or overridden as appropriate for custom :class:`~eulfedora.models.DigitalObject` classes.''' dc_fields = ['title', 'contributor', 'covera...
def index_data_descriptive(self)
Descriptive data to be included in :meth:`index_data` output. This implementation includes all Dublin Core fields, but should be extended or overridden as appropriate for custom :class:`~eulfedora.models.DigitalObject` classes.
4.819695
2.620993
1.838881
'''Standard Fedora relations to be included in :meth:`index_data` output. This implementation includes all standard relations included in the Fedora relations namespace, but should be extended or overridden as appropriate for custom :class:`~eulfedora.models.DigitalObject` class...
def index_data_relations(self)
Standard Fedora relations to be included in :meth:`index_data` output. This implementation includes all standard relations included in the Fedora relations namespace, but should be extended or overridden as appropriate for custom :class:`~eulfedora.models.DigitalObject` classes.
12.407919
5.470742
2.26805
'''Generate a ContentModel object for the specified :class:`DigitalObject` class. Content model object is saved in the specified repository if it doesn't already exist.''' full_name = '%s.%s' % (digobj.__module__, digobj.__name__) cmodels = getattr(digobj, 'CONTENT_MODELS', None...
def for_class(digobj, repo)
Generate a ContentModel object for the specified :class:`DigitalObject` class. Content model object is saved in the specified repository if it doesn't already exist.
3.096442
2.657691
1.165087
# different from EC2 list params for i in xrange(1, len(items)+1): if isinstance(items[i-1], dict): for k, v in items[i-1].iteritems(): if isinstance(v, dict): for kk, vv in v.iteritems(): params...
def build_list_params(self, params, items, label)
Items is a list of dictionaries or strings:: [ { 'Protocol' : 'HTTP', 'LoadBalancerPort' : '80', 'InstancePort' : '80' }, .. ] etc. or:: ['us-east-1b',...]
1.984744
2.134279
0.929936
if(force_delete): params = {'AutoScalingGroupName': name, 'ForceDelete': 'true'} else: params = {'AutoScalingGroupName': name} return self.get_object('DeleteAutoScalingGroup', params, Request)
def delete_auto_scaling_group(self, name, force_delete=False)
Deletes the specified auto scaling group if the group has no instances and no scaling activities in progress.
2.860658
2.979075
0.96025
params = {'ImageId': launch_config.image_id, 'LaunchConfigurationName': launch_config.name, 'InstanceType': launch_config.instance_type} if launch_config.key_name: params['KeyName'] = launch_config.key_name if launch_config.user_data: ...
def create_launch_configuration(self, launch_config)
Creates a new Launch Configuration. :type launch_config: :class:`boto.ec2.autoscale.launchconfig.LaunchConfiguration` :param launch_config: LaunchConfiguration object.
1.607664
1.63362
0.984111
params = {'AdjustmentType': scaling_policy.adjustment_type, 'AutoScalingGroupName': scaling_policy.as_name, 'PolicyName': scaling_policy.name, 'ScalingAdjustment': scaling_policy.scaling_adjustment} if scaling_policy.cooldown is not None: ...
def create_scaling_policy(self, scaling_policy)
Creates a new Scaling Policy. :type scaling_policy: :class:`boto.ec2.autoscale.policy.ScalingPolicy` :param scaling_policy: ScalingPolicy object.
2.171649
2.266576
0.958119
params = {} if max_records: params['MaxRecords'] = max_records if next_token: params['NextToken'] = next_token if names: self.build_list_params(params, names, 'AutoScalingGroupNames') return self.get_list('DescribeAutoScalingGroups', p...
def get_all_groups(self, names=None, max_records=None, next_token=None)
Returns a full description of each Auto Scaling group in the given list. This includes all Amazon EC2 instances that are members of the group. If a list of names is not provided, the service returns the full details of all Auto Scaling groups. This action supports pagination by returnin...
2.157919
2.274623
0.948693
params = {} max_records = kwargs.get('max_records', None) names = kwargs.get('names', None) if max_records is not None: params['MaxRecords'] = max_records if names: self.build_list_params(params, names, 'LaunchConfigurationNames') next_tok...
def get_all_launch_configurations(self, **kwargs)
Returns a full description of the launch configurations given the specified names. If no names are specified, then the full details of all launch configurations are returned. :type names: list :param names: List of configuration names which should be searched for. :typ...
2.422662
2.086245
1.161255
name = autoscale_group if isinstance(autoscale_group, AutoScalingGroup): name = autoscale_group.name params = {'AutoScalingGroupName' : name} if max_records: params['MaxRecords'] = max_records if next_token: params['NextToken'] = next_...
def get_all_activities(self, autoscale_group, activity_ids=None, max_records=None, next_token=None)
Get all activities for the given autoscaling group. This action supports pagination by returning a token if there are more pages to retrieve. To get the next page, call this action again with the returned token as the NextToken parameter :type autoscale_group: str or :class...
2.175889
2.397617
0.907522
params = {'ScheduledActionName': scheduled_action_name} if autoscale_group: params['AutoScalingGroupName'] = autoscale_group return self.get_status('DeleteScheduledAction', params)
def delete_scheduled_action(self, scheduled_action_name, autoscale_group=None)
Deletes a previously scheduled action. :type scheduled_action_name: str :param scheduled_action_name: The name of the action you want to delete. :type autoscale_group: str :param autoscale_group: The name of the autoscale group.
1.970964
2.700399
0.729879
params = {'InstanceId': instance_id} if decrement_capacity: params['ShouldDecrementDesiredCapacity'] = 'true' else: params['ShouldDecrementDesiredCapacity'] = 'false' return self.get_object('TerminateInstanceInAutoScalingGroup', params, ...
def terminate_instance(self, instance_id, decrement_capacity=True)
Terminates the specified instance. The desired group size can also be adjusted, if desired. :type instance_id: str :param instance_id: The ID of the instance to be terminated. :type decrement_capability: bool :param decrement_capacity: Whether to decrement the size of the ...
2.641
3.250028
0.812608
params = {'PolicyName': policy_name} if autoscale_group: params['AutoScalingGroupName'] = autoscale_group return self.get_status('DeletePolicy', params)
def delete_policy(self, policy_name, autoscale_group=None)
Delete a policy. :type policy_name: str :param policy_name: The name or ARN of the policy to delete. :type autoscale_group: str :param autoscale_group: The name of the autoscale group.
2.057884
2.969224
0.693071
params = {} if instance_ids: self.build_list_params(params, instance_ids, 'InstanceIds') if max_records: params['MaxRecords'] = max_records if next_token: params['NextToken'] = next_token return self.get_list('DescribeAutoScalingInstan...
def get_all_autoscaling_instances(self, instance_ids=None, max_records=None, next_token=None)
Returns a description of each Auto Scaling instance in the instance_ids list. If a list is not provided, the service returns the full details of all instances up to a maximum of fifty. This action supports pagination by returning a token if there are more pages to retrieve. To get the n...
1.83628
2.345281
0.782968
params = {} if as_group: params['AutoScalingGroupName'] = as_group if policy_names: self.build_list_params(params, policy_names, 'PolicyNames') if max_records: params['MaxRecords'] = max_records if next_token: params['NextT...
def get_all_policies(self, as_group=None, policy_names=None, max_records=None, next_token=None)
Returns descriptions of what each policy does. This action supports pagination. If the response includes a token, there are more records available. To get the additional records, repeat the request with the response token as the NextToken parameter. If no group name or list of policy na...
1.741313
2.102684
0.828138
params = {'AutoScalingGroupName': as_group} if scaling_processes: self.build_list_params(params, scaling_processes, 'ScalingProcesses') return self.get_status('SuspendProcesses', params)
def suspend_processes(self, as_group, scaling_processes=None)
Suspends Auto Scaling processes for an Auto Scaling group. :type as_group: string :param as_group: The auto scaling group to suspend processes on. :type scaling_processes: list :param scaling_processes: Processes you want to suspend. If omitted, all processes will be suspen...
2.913344
3.740562
0.778852
params = {'AutoScalingGroupName': as_group} if scaling_processes: self.build_list_params(params, scaling_processes, 'ScalingProcesses') return self.get_status('ResumeProcesses', params)
def resume_processes(self, as_group, scaling_processes=None)
Resumes Auto Scaling processes for an Auto Scaling group. :type as_group: string :param as_group: The auto scaling group to resume processes on. :type scaling_processes: list :param scaling_processes: Processes you want to resume. If omitted, all processes will be resumed.
3.702969
4.430961
0.835703