code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
data = {'TableName' : table_name, 'Key' : key, 'AttributeUpdates': attribute_updates} if expected: data['Expected'] = expected if return_values: data['ReturnValues'] = return_values json_input = json.dumps(data) ret...
def update_item(self, table_name, key, attribute_updates, expected=None, return_values=None, object_hook=None)
Edits an existing item's attributes. You can perform a conditional update (insert a new attribute name-value pair if it doesn't exist, or replace an existing name-value pair if it has certain expected attribute values). :type table_name: str :param table_name: The name of the ta...
1.974822
2.775993
0.711393
data = {'TableName' : table_name, 'Key' : key} if expected: data['Expected'] = expected if return_values: data['ReturnValues'] = return_values json_input = json.dumps(data) return self.make_request('DeleteItem', json_input, ...
def delete_item(self, table_name, key, expected=None, return_values=None, object_hook=None)
Delete an item and all of it's attributes by primary key. You can perform a conditional delete by specifying an expected rule. :type table_name: str :param table_name: The name of the table containing the item. :type key: dict :param key: A Python version of the Key dat...
2.05641
2.972217
0.691878
data = {'TableName': table_name, 'HashKeyValue': hash_key_value} if range_key_conditions: data['RangeKeyCondition'] = range_key_conditions if attributes_to_get: data['AttributesToGet'] = attributes_to_get if limit: data['Limit'...
def query(self, table_name, hash_key_value, range_key_conditions=None, attributes_to_get=None, limit=None, consistent_read=False, scan_index_forward=True, exclusive_start_key=None, object_hook=None)
Perform a query of DynamoDB. This version is currently punting and expecting you to provide a full and correct JSON body which is passed as is to DynamoDB. :type table_name: str :param table_name: The name of the table to query. :type hash_key_value: dict :param key: A...
1.515415
1.661205
0.912239
data = {'TableName': table_name} if scan_filter: data['ScanFilter'] = scan_filter if attributes_to_get: data['AttributesToGet'] = attributes_to_get if limit: data['Limit'] = limit if count: data['Count'] = True if e...
def scan(self, table_name, scan_filter=None, attributes_to_get=None, limit=None, count=False, exclusive_start_key=None, object_hook=None)
Perform a scan of DynamoDB. This version is currently punting and expecting you to provide a full and correct JSON body which is passed as is to DynamoDB. :type table_name: str :param table_name: The name of the table to scan. :type scan_filter: dict :param scan_filter...
1.553039
1.912617
0.811997
if img.size == 0: return img img = gray3(img) # delete rows with complete background color h, w = img.shape[:2] i = 0 while i < h: mask = np.logical_or(img[i, :, :] < th[0], img[i, :, :] > th[1]) if not mask.any(): img = np.delete(img, i, axis=0) ...
def remove_bg(img, th=(240, 255))
Removes similar colored background in the given image. :param img: Input image :param th: Tuple(2) Background color threshold (lower-limit, upper-limit) :return: Background removed image as result
2.014896
2.041472
0.986982
img = gray3(img) h, w, d = img.shape new_img = np.ones((h + 2*padding, w + 2*padding, d)) * color[:d] new_img = new_img.astype(np.uint8) set_img_box(new_img, (padding, padding, w, h), img) return new_img
def add_bg(img, padding, color=COL_WHITE)
Adds a padding to the given image as background of specified color :param img: Input image. :param padding: constant padding around the image. :param color: background color that needs to filled for the newly padded region. :return: New image with background.
3.212152
3.564814
0.901071
if isinstance(box, tuple): box = Box.from_tup(box) if len(img.shape) == 3: return img[box.y:box.y + box.height, box.x:box.x + box.width, :] else: return img[box.y:box.y + box.height, box.x:box.x + box.width]
def img_box(img, box)
Selects the sub-image inside the given box :param img: Image to crop from :param box: Box to crop from. Box can be either Box object or array of [x, y, width, height] :return: Cropped sub-image from the main image
1.969961
1.979443
0.99521
if color is None: color = COL_WHITE text = str(text) top_left = pos if box is not None: top_left = box.move(pos).to_int().top_left() if top_left[0] > img.shape[1]: return if vertical: if box is not None: h, w, d = box.height, box.width, ...
def add_text_img(img, text, pos, box=None, color=None, thickness=1, scale=1, vertical=False)
Adds the given text in the image. :param img: Input image :param text: String text :param pos: (x, y) in the image or relative to the given Box object :param box: Box object. If not None, the text is placed inside the box. :param color: Color of the text. :param thickness: Thickness of the font...
2.545732
2.589964
0.982922
if color is None: color = COL_GRAY box = box.to_int() cv.rectangle(img, box.top_left(), box.bottom_right(), color, thickness)
def add_rect(img, box, color=None, thickness=1)
Draws a bounding box inside the image. :param img: Input image :param box: Box object that defines the bounding box. :param color: Color of the box :param thickness: Thickness of line :return: Rectangle added image
3.91781
5.126783
0.764185
n = len(imgs) nrows = int(math.ceil(math.sqrt(n))) ncols = int(math.ceil(n / nrows)) for row in range(nrows): for col in range(ncols): i = row * ncols + col if i >= n: break plt.subplot(nrows, ncols, i+1) show_img(imgs[i], opti...
def imshow(*imgs, **options)
Plots multiple images using matplotlib by dynamically finding the required number of rows and cols. :param imgs: Images as any number of arguments :param options: Dict of options - cmap: Color map for gray scale images - vmin: Minimum value to be used in color map - vmax: Maximum...
1.874376
2.068921
0.905968
# make 2d array if not isinstance(imgs[0], list): imgs = [imgs] h, w = imgs[0][0].shape[:2] nrows, ncols = size nr, nc = nrows * h + (nrows-1) * padding, ncols * w + (ncols-1) * padding res = np.ones((nr, nc, 3), dtype=np.uint8) * np.array(bg, dtype=np.uint8) for r in range(n...
def collage(imgs, size, padding=10, bg=COL_BLACK)
Constructs a collage of same-sized images with specified padding. :param imgs: Array of images. Either 1d-array or 2d-array. :param size: (no. of rows, no. of cols) :param padding: Padding space between each image :param bg: Background color for the collage. Default: Black :return: New collage
2.065024
2.120554
0.973813
for fname in utils.each_img(img_dir): fname = os.path.join(img_dir, fname) yield cv.imread(fname), fname
def each_img(img_dir)
Reads and iterates through each image file in the given directory
4.293357
4.386208
0.978831
h, w = img.shape[:2] if h > w: nh = max_side nw = w * (nh / h) else: nw = max_side nh = h * (nw / w) return cv.resize(img, (nw, nh))
def resize_max(img, max_side)
Resize the image to threshold the maximum dimension within max_side :param img: :param max_side: Length of the maximum height or width :return:
2.347759
2.539924
0.924342
return self.connection.set_alarm_state(self.name, reason, value, data)
def set_state(self, value, reason, data=None)
Temporarily sets the state of an alarm. :type value: str :param value: OK | ALARM | INSUFFICIENT_DATA :type reason: str :param reason: Reason alarm set (human readable). :type data: str :param data: Reason data (will be jsonified).
6.992627
8.093505
0.86398
if not action_arn: return # Raise exception instead? self.actions_enabled = 'true' self.alarm_actions.append(action_arn)
def add_alarm_action(self, action_arn=None)
Adds an alarm action, represented as an SNS topic, to this alarm. What do do when alarm is triggered. :type action_arn: str :param action_arn: SNS topics to which notification should be sent if the alarm goes to state ALARM.
5.757834
8.800213
0.654283
if not action_arn: return self.actions_enabled = 'true' self.insufficient_data_actions.append(action_arn)
def add_insufficient_data_action(self, action_arn=None)
Adds an insufficient_data action, represented as an SNS topic, to this alarm. What to do when the insufficient_data state is reached. :type action_arn: str :param action_arn: SNS topics to which notification should be sent if the alarm goes to state INSUFFICIENT_DATA...
4.428144
5.756044
0.769303
if not action_arn: return self.actions_enabled = 'true' self.ok_actions.append(action_arn)
def add_ok_action(self, action_arn=None)
Adds an ok action, represented as an SNS topic, to this alarm. What to do when the ok state is reached. :type action_arn: str :param action_arn: SNS topics to which notification should be sent if the alarm goes to state INSUFFICIENT_DATA.
4.550819
6.108346
0.745017
token_key = '%s:%s' % (self.region.name, self.provider.access_key) token = self._check_token_cache(token_key, duration) if force_new or not token: boto.log.debug('fetching a new token for %s' % token_key) self._mutex.acquire() token = self._get_sessio...
def get_session_token(self, duration=None, force_new=False)
Return a valid session token. Because retrieving new tokens from the Secure Token Service is a fairly heavyweight operation this module caches previously retrieved tokens and returns them when appropriate. Each token is cached with a key consisting of the region name of the STS endpoin...
3.168119
3.425099
0.924971
params = {'Name' : name} if duration: params['DurationSeconds'] = duration if policy: params['Policy'] = policy return self.get_object('GetFederationToken', params, FederationToken, verb='POST')
def get_federation_token(self, name, duration=None, policy=None)
:type name: str :param name: The name of the Federated user associated with the credentials. :type duration: int :param duration: The number of seconds the credentials should remain valid. :type policy: str :par...
2.834368
3.807758
0.744367
params = {'ContentType' : 'JSON', 'TopicArn' : topic, 'AttributeName' : attr_name, 'AttributeValue' : attr_value} response = self.make_request('SetTopicAttributes', params, '/', 'GET') body = response.read() if response.statu...
def set_topic_attributes(self, topic, attr_name, attr_value)
Get attributes of a Topic :type topic: string :param topic: The ARN of the topic. :type attr_name: string :param attr_name: The name of the attribute you want to set. Only a subset of the topic's attributes are mutable. Valid values: ...
2.205242
2.228065
0.989757
params = {'ContentType' : 'JSON', 'TopicArn' : topic, 'Label' : label} self.build_list_params(params, account_ids, 'AWSAccountId') self.build_list_params(params, actions, 'ActionName') response = self.make_request('AddPermission', params, '/',...
def add_permission(self, topic, label, account_ids, actions)
Adds a statement to a topic's access control policy, granting access for the specified AWS accounts to the specified actions. :type topic: string :param topic: The ARN of the topic. :type label: string :param label: A unique identifier for the new policy statement. :ty...
2.402804
2.467205
0.973897
params = {'ContentType' : 'JSON', 'TopicArn' : topic, 'Message' : message} if subject: params['Subject'] = subject response = self.make_request('Publish', params, '/', 'GET') body = response.read() if response.status == 200...
def publish(self, topic, message, subject=None)
Get properties of a Topic :type topic: string :param topic: The ARN of the new topic. :type message: string :param message: The message you want to send to the topic. Messages must be UTF-8 encoded strings and be at most 4KB in size. ...
2.388115
2.429936
0.982789
params = {'ContentType' : 'JSON', 'TopicArn' : topic, 'Protocol' : protocol, 'Endpoint' : endpoint} response = self.make_request('Subscribe', params, '/', 'GET') body = response.read() if response.status == 200: r...
def subscribe(self, topic, protocol, endpoint)
Subscribe to a Topic. :type topic: string :param topic: The name of the new topic. :type protocol: string :param protocol: The protocol used to communicate with the subscriber. Current choices are: email|email-json|http|https|sqs ...
2.331532
2.4079
0.968285
t = queue.id.split('/') q_arn = 'arn:aws:sqs:%s:%s:%s' % (queue.connection.region.name, t[1], t[2]) resp = self.subscribe(topic, 'sqs', q_arn) policy = queue.get_attributes('Policy') if 'Version' not in policy: policy...
def subscribe_sqs_queue(self, topic, queue)
Subscribe an SQS queue to a topic. This is convenience method that handles most of the complexity involved in using ans SQS queue as an endpoint for an SNS topic. To achieve this the following operations are performed: * The correct ARN is constructed for the SQS queue and tha...
2.313589
2.289576
1.010488
params = {'ContentType' : 'JSON', 'TopicArn' : topic, 'Token' : token} if authenticate_on_unsubscribe: params['AuthenticateOnUnsubscribe'] = 'true' response = self.make_request('ConfirmSubscription', params, '/', 'GET') body = resp...
def confirm_subscription(self, topic, token, authenticate_on_unsubscribe=False)
Get properties of a Topic :type topic: string :param topic: The ARN of the new topic. :type token: string :param token: Short-lived token sent to and endpoint during the Subscribe operation. :type authenticate_on_unsubscribe: bool :param authentic...
2.178558
2.253502
0.966743
params = {'ContentType' : 'JSON', 'SubscriptionArn' : subscription} response = self.make_request('Unsubscribe', params, '/', 'GET') body = response.read() if response.status == 200: return json.loads(body) else: boto.log.error('%...
def unsubscribe(self, subscription)
Allows endpoint owner to delete subscription. Confirmation message will be delivered. :type subscription: string :param subscription: The ARN of the subscription to be deleted.
2.609771
2.498605
1.044491
params = {'ContentType' : 'JSON'} if next_token: params['NextToken'] = next_token response = self.make_request('ListSubscriptions', params, '/', 'GET') body = response.read() if response.status == 200: return json.loads(body) else: ...
def get_all_subscriptions(self, next_token=None)
Get list of all subscriptions. :type next_token: string :param next_token: Token returned by the previous call to this method.
2.302511
2.47285
0.931117
# We allow you to pass in either an array or # an InvalidationBatch object if not isinstance(paths, InvalidationBatch): paths = InvalidationBatch(paths) paths.connection = self uri = '/%s/distribution/%s/invalidation' % (self.Version, ...
def create_invalidation_request(self, distribution_id, paths, caller_reference=None)
Creates a new invalidation request :see: http://goo.gl/8vECq
3.098387
3.337542
0.928344
if(transaction_id == None): transaction_id = uuid.uuid4() params = {} params['PaymentInstruction'] = instruction params['TokenType'] = token_type params['CallerReference'] = transaction_id response = self.make_request("InstallPaymentInstruction", par...
def install_payment_instruction(self, instruction, token_type="Unrestricted", transaction_id=None)
InstallPaymentInstruction instruction: The PaymentInstruction to send, for example: MyRole=='Caller' orSay 'Roles do not match'; token_type: Defaults to "Unrestricted" transaction_id: Defaults to a new ID
2.965682
2.944806
1.007089
response = self.install_payment_instruction("MyRole=='Caller';", token_type=token_type, transaction_id=transaction_id) body = response.read() if(response.status == 200): r...
def install_caller_instruction(self, token_type="Unrestricted", transaction_id=None)
Set us up as a caller This will install a new caller_token into the FPS section. This should really only be called to regenerate the caller token.
4.65147
4.096488
1.135477
endpoint_host = 'authorize.payments-sandbox.amazon.com' base = "/cobranded-ui/actions/start" params['callerKey'] = str(self.aws_access_key_id) params['returnURL'] = str(returnURL) params['pipelineName'] = str(pipelineName) params['maxFixedFee'] = str(maxFixedFee) ...
def make_marketplace_registration_url(self, returnURL, pipelineName, maxFixedFee=0.0, maxVariableFee=0.0, recipientPaysFee=True, **params): # use the sandbox authorization endpoint if we're using the # sandbo...
Generate the URL with the signature required for signing up a recipient
2.769219
2.723075
1.016946
# use the sandbox authorization endpoint if we're using the # sandbox for API calls. endpoint_host = 'authorize.payments.amazon.com' if 'sandbox' in self.host: endpoint_host = 'authorize.payments-sandbox.amazon.com' base = "/cobranded-ui/actions/start" ...
def make_url(self, returnURL, paymentReason, pipelineName, transactionAmount, **params)
Generate the URL with the signature required for a transaction
3.483099
3.521598
0.989068
params = {} params['SenderTokenId'] = senderTokenId # this is for 2008-09-17 specification params['TransactionAmount.Amount'] = str(transactionAmount) params['TransactionAmount.CurrencyCode'] = "USD" #params['TransactionAmount'] = str(transactionAmount) p...
def pay(self, transactionAmount, senderTokenId, recipientTokenId=None, callerTokenId=None, chargeFeeTo="Recipient", callerReference=None, senderReference=None, recipientReference=None, senderDescription=None, recipientDescription=None, callerDescription=None, ...
Make a payment transaction. You must specify the amount. This can also perform a Reserve request if 'reserve' is set to True.
2.10326
2.083462
1.009502
params = {} params['TransactionId'] = transactionId response = self.make_request("GetTransactionStatus", params) body = response.read() if(response.status == 200): rs = ResultSet() h = handler.XmlHandler(rs, self) xml.sax.parseStr...
def get_transaction_status(self, transactionId)
Returns the status of a given transaction.
2.994445
2.924139
1.024043
params = {} params['ReserveTransactionId'] = reserveTransactionId if(transactionAmount != None): params['TransactionAmount'] = transactionAmount response = self.make_request("Settle", params) body = response.read() if(response.status == 200):...
def settle(self, reserveTransactionId, transactionAmount=None)
Charges for a reserved payment.
2.59199
2.496429
1.038279
params = {} params['CallerReference'] = callerReference params['TransactionId'] = transactionId if(refundAmount != None): params['RefundAmount'] = refundAmount if(callerDescription != None): params['CallerDescription'] = callerDescription ...
def refund(self, callerReference, transactionId, refundAmount=None, callerDescription=None)
Refund a transaction. This refunds the full amount by default unless 'refundAmount' is specified.
2.261304
2.192857
1.031214
uri = resource.uri if (uri in self and not replace): raise ResourceSetDupeError( "Attempt to add resource already in this set") self[uri] = resource
def add(self, resource, replace=False)
Add just a single resource.
7.926484
6.96254
1.138447
'''Helper function for building a pdf from a latex jinja2 template :param path_jinja2: the root directory for latex jinja2 templates :param template_name: the relative path, to path_jinja2, to the desired jinja2 Latex template :param path_outfile: the full path to the desired final output file ...
def build_pdf(path_jinja2, template_name, path_outfile, template_kwargs=None)
Helper function for building a pdf from a latex jinja2 template :param path_jinja2: the root directory for latex jinja2 templates :param template_name: the relative path, to path_jinja2, to the desired jinja2 Latex template :param path_outfile: the full path to the desired final output file ...
5.706632
1.660453
3.436791
'''Helper function for building an html from a latex jinja2 template :param path_jinja2: the root directory for latex jinja2 templates :param template_name: the relative path, to path_jinja2, to the desired jinja2 Latex template :param path_outfile: the full path to the desired final output fil...
def build_html(path_jinja2, template_name, path_outfile, template_kwargs=None)
Helper function for building an html from a latex jinja2 template :param path_jinja2: the root directory for latex jinja2 templates :param template_name: the relative path, to path_jinja2, to the desired jinja2 Latex template :param path_outfile: the full path to the desired final output file ...
5.928751
1.669337
3.551561
'''Helper function for building a docx file from a latex jinja2 template :param path_jinja2: the root directory for latex jinja2 templates :param template_name: the relative path, to path_jinja2, to the desired jinja2 Latex template :param path_outfile: the full path to the desired final output...
def build_docx(path_jinja2, template_name, path_outfile, template_kwargs=None)
Helper function for building a docx file from a latex jinja2 template :param path_jinja2: the root directory for latex jinja2 templates :param template_name: the relative path, to path_jinja2, to the desired jinja2 Latex template :param path_outfile: the full path to the desired final output file ...
5.610061
1.651527
3.396893
try: fh = URLopener().open(uri) self.num_files += 1 except IOError as e: raise IOError( "Failed to load sitemap/sitemapindex from %s (%s)" % (uri, str(e))) # Get the Content-Length if we can (works fine for local files)...
def read(self, uri=None, resources=None, index_only=False)
Read sitemap from a URI including handling sitemapindexes. If index_only is True then individual sitemaps references in a sitemapindex will not be read. This will result in no resources being returned and is useful only to read the metadata and links listed in the sitemapindex. Include...
4.057591
3.963661
1.023698
if (sitemapindex_is_file): if (not self.is_file_uri(sitemap_uri)): # Attempt to map URI to local file remote_uri = sitemap_uri sitemap_uri = self.mapper.src_to_dst(remote_uri) self.logger.info( "Mapped %s to...
def read_component_sitemap( self, sitemapindex_uri, sitemap_uri, sitemap, sitemapindex_is_file)
Read a component sitemap of a Resource List with index. Each component must be a sitemap with the
4.531712
4.613887
0.98219
if (self.max_sitemap_entries is None or len(self) <= self.max_sitemap_entries): return(False) return(int(math.ceil(len(self) / float(self.max_sitemap_entries))))
def requires_multifile(self)
Return False or the number of component sitemaps required. In the case that no len() is available for self.resources then then self.count must be set beforehand to avoid an exception.
4.654573
3.303257
1.409086
if (not self.requires_multifile()): return super(ListBaseWithIndex, self).as_xml() elif (allow_multifile): return self.as_xml_index(basename) else: raise ListBaseIndexError( "Attempt to write single XML string for list with %d entries ...
def as_xml(self, allow_multifile=False, basename="/tmp/sitemap.xml")
Return XML serialization of this list. If this list can be serialized as a single sitemap then the superclass method is used. If there is no single XML serialization (in the case that the number of list resources is more than is allowed in a single sitemap) then raise an except...
5.67912
4.743116
1.19734
num_parts = self.requires_multifile() if (not num_parts): raise ListBaseIndexError( "Request for sitemapindex for list with only %d entries when max_sitemap_entries is set to %s" % (len(self), str( self.max_sitemap_entries))) ...
def as_xml_index(self, basename="/tmp/sitemap.xml")
Return a string of the index for a large list that is split. All we need to do is determine the number of component sitemaps will be is and generate their URIs based on a pattern. Q - should there be a flag to select generation of each component sitemap in order to calculate the md5sum...
7.920191
7.74612
1.022472
if (not self.requires_multifile()): raise ListBaseIndexError( "Request for component sitemap for list with only %d entries when max_sitemap_entries is set to %s" % (len(self), str( self.max_sitemap_entries))) start = part_number * ...
def as_xml_part(self, basename="/tmp/sitemap.xml", part_number=0)
Return a string of component sitemap number part_number. Used in the case of a large list that is split into component sitemaps. basename is used to create "index" links to the sitemapindex Q - what timestamp should be used?
5.134803
4.966502
1.033887
# Access resources through iterator only resources_iter = iter(self.resources) (chunk, nxt) = self.get_resources_chunk(resources_iter) s = self.new_sitemap() if (nxt is not None): # Have more than self.max_sitemap_entries => sitemapindex if (not s...
def write(self, basename='/tmp/sitemap.xml')
Write one or a set of sitemap files to disk. resources is a ResourceContainer that may be an ResourceList or a ChangeList. This may be a generator so data is read as needed and length is determined at the end. basename is used as the name of the single sitemap file or the sitem...
3.722542
3.486889
1.067582
self.default_capability() s = self.new_sitemap() return s.resources_as_xml(self, sitemapindex=True)
def index_as_xml(self)
XML serialization of this list taken to be sitemapindex entries.
19.610165
12.600722
1.556273
chunk = ListBase(md=self.md.copy(), ln=list(self.ln)) chunk.capability_name = self.capability_name chunk.default_capability() if (first is not None): chunk.add(first) for r in resource_iter: chunk.add(r) if (len(chunk) >= self.max_site...
def get_resources_chunk(self, resource_iter, first=None)
Return next chunk of resources from resource_iter, and next item. If first parameter is specified then this will be prepended to the list. The chunk will contain self.max_sitemap_entries if the iterator returns that many. next will have the value of the next value from the iter...
5.199298
4.416452
1.177257
# Work out how to name the sitemaps, attempt to add %05d before # ".xml$", else append sitemap_prefix = basename sitemap_suffix = '.xml' if (basename[-4:] == '.xml'): sitemap_prefix = basename[:-4] return(sitemap_prefix + ("%05d" % (part_number)) + si...
def part_name(self, basename='/tmp/sitemap.xml', part_number=0)
Name (file or URI) for one component sitemap. Works for both filenames and URIs because manipulates only the end of the string. Abstracting this into a function that starts from the basename to get prefix and suffix each time seems a bit wasteful but perhaps not worth worrying ...
5.941257
5.971138
0.994996
return functools.partial(interpolate.splev, tck=(knots, coef, degree), der=der, ext=ext)
def _basis_spline_factory(coef, degree, knots, der, ext)
Return a B-Spline given some coefficients.
5.149505
4.765667
1.080542
return cls._basis_spline_factory(coef, degree, knots, 1, ext)
def derivatives_factory(cls, coef, degree, knots, ext, **kwargs)
Given some coefficients, return a the derivative of a B-spline.
7.476704
6.535321
1.144045
return cls._basis_spline_factory(coef, degree, knots, 0, ext)
def functions_factory(cls, coef, degree, knots, ext, **kwargs)
Given some coefficients, return a B-spline.
7.829213
6.394503
1.224366
m = urlparse(url) self.master_scheme = m.scheme self.master_netloc = m.netloc self.master_path = os.path.dirname(m.path)
def set_master(self, url)
Set the master url that this object works with.
2.499608
2.351194
1.063123
s = urlparse(url) if (s.scheme != self.master_scheme): return(False) if (s.netloc != self.master_netloc): if (not s.netloc.endswith('.' + self.master_netloc)): return(False) # Maybe should allow parallel for 3+ components, eg. a.exampl...
def has_authority_over(self, url)
Return True of the current master has authority over url. In strict mode checks scheme, server and path. Otherwise checks just that the server names match or the query url is a sub-domain of the master.
3.93439
3.511891
1.120305
try: pkg_resources.get_distribution('invenio-access') from invenio_access import Permission except pkg_resources.DistributionNotFound: from flask_principal import Permission return Permission(action_admin_access)
def admin_permission_factory(admin_view)
Default factory for creating a permission for an admin. It tries to load a :class:`invenio_access.permissions.Permission` instance if `invenio_access` is installed. Otherwise, it loads a :class:`flask_principal.Permission` instance. :param admin_view: Instance of administration view which is currently...
5.420246
4.547712
1.191862
cld_svc_map = {"aws": conn_aws, "azure": conn_az, "gcp": conn_gcp, "alicloud": conn_ali} sys.stdout.write("\rEstablishing Connections: ") sys.stdout.flush() busy_obj = busy_disp_on() conn_fn = [[cld_svc_map[x.rstrip('1234567890')], cred[...
def get_conns(cred, providers)
Collect node data asynchronously using gevent lib.
4.728814
4.560904
1.036815
cld_svc_map = {"aws": nodes_aws, "azure": nodes_az, "gcp": nodes_gcp, "alicloud": nodes_ali} sys.stdout.write("\rCollecting Info: ") sys.stdout.flush() busy_obj = busy_disp_on() collec_fn = [[cld_svc_map[x.rstrip('1234567890')], conn_obj...
def get_data(conn_objs, providers)
Refresh node data using existing connection-objects.
5.60202
5.4505
1.027799
dobj.kill(block=False) sys.stdout.write("\033[D \033[D") sys.stdout.flush()
def busy_disp_off(dobj)
Turn OFF busy_display to indicate completion.
5.041676
5.461497
0.923131
sys.stdout.write("\033[?25l") # cursor off sys.stdout.flush() for x in range(1800): symb = ['\\', '|', '/', '-'] sys.stdout.write("\033[D{}".format(symb[x % 4])) sys.stdout.flush() gevent.sleep(0.1)
def busy_display()
Display animation to show activity.
3.120735
3.20521
0.973644
driver = get_driver(Provider.EC2) try: aws_obj = driver(cred['aws_access_key_id'], cred['aws_secret_access_key'], region=cred['aws_default_region']) except SSLError as e: abort_err("\r SSL Error with AWS: {}".format(e)) except Invali...
def conn_aws(cred, crid)
Establish connection to AWS service.
3.906576
3.705094
1.05438
aws_nodes = [] try: aws_nodes = c_obj.list_nodes() except BaseHTTPError as e: abort_err("\r HTTP Error with AWS: {}".format(e)) aws_nodes = adj_nodes_aws(aws_nodes) return aws_nodes
def nodes_aws(c_obj)
Get node objects from AWS.
6.166636
5.955318
1.035484
for node in aws_nodes: node.cloud = "aws" node.cloud_disp = "AWS" node.private_ips = ip_to_str(node.private_ips) node.public_ips = ip_to_str(node.public_ips) node.zone = node.extra['availability'] node.size = node.extra['instance_type'] node.type = node.e...
def adj_nodes_aws(aws_nodes)
Adjust details specific to AWS.
2.983727
2.875102
1.037781
driver = get_driver(Provider.AZURE_ARM) try: az_obj = driver(tenant_id=cred['az_tenant_id'], subscription_id=cred['az_sub_id'], key=cred['az_app_id'], secret=cred['az_app_sec']) except SSLError as e: abort_err("\r S...
def conn_az(cred, crid)
Establish connection to Azure service.
3.926002
3.774145
1.040236
az_nodes = [] try: az_nodes = c_obj.list_nodes() except BaseHTTPError as e: abort_err("\r HTTP Error with Azure: {}".format(e)) az_nodes = adj_nodes_az(az_nodes) return az_nodes
def nodes_az(c_obj)
Get node objects from Azure.
6.69769
6.262772
1.069445
for node in az_nodes: node.cloud = "azure" node.cloud_disp = "Azure" node.private_ips = ip_to_str(node.private_ips) node.public_ips = ip_to_str(node.public_ips) node.zone = node.extra['location'] node.size = node.extra['properties']['hardwareProfile']['vmSize'] ...
def adj_nodes_az(az_nodes)
Adjust details specific to Azure.
3.887786
3.650359
1.065042
gcp_auth_type = cred.get('gcp_auth_type', "S") if gcp_auth_type == "A": # Application Auth gcp_crd_ia = CONFIG_DIR + ".gcp_libcloud_a_auth." + cred['gcp_proj_id'] gcp_crd = {'user_id': cred['gcp_client_id'], 'key': cred['gcp_client_sec'], 'project': cr...
def conn_gcp(cred, crid)
Establish connection to GCP.
3.185519
3.123295
1.019922
gcp_nodes = [] try: gcp_nodes = c_obj.list_nodes(ex_use_disk_cache=True) except BaseHTTPError as e: abort_err("\r HTTP Error with GCP: {}".format(e)) gcp_nodes = adj_nodes_gcp(gcp_nodes) return gcp_nodes
def nodes_gcp(c_obj)
Get node objects from GCP.
6.147339
5.968107
1.030032
for node in gcp_nodes: node.cloud = "gcp" node.cloud_disp = "GCP" node.private_ips = ip_to_str(node.private_ips) node.public_ips = ip_to_str(node.public_ips) node.zone = node.extra['zone'].name return gcp_nodes
def adj_nodes_gcp(gcp_nodes)
Adjust details specific to GCP.
3.057082
2.823085
1.082887
driver = get_driver(Provider.ALIYUN_ECS) try: ali_obj = driver(cred['ali_access_key_id'], cred['ali_access_key_secret'], region=cred['ali_region']) except SSLError as e: abort_err("\r SSL Error with AliCloud: {}".format(e)) except In...
def conn_ali(cred, crid)
Establish connection to AliCloud service.
4.366018
3.89767
1.120161
ali_nodes = [] try: ali_nodes = c_obj.list_nodes() except BaseHTTPError as e: abort_err("\r HTTP Error with AliCloud: {}".format(e)) ali_nodes = adj_nodes_ali(ali_nodes) return ali_nodes
def nodes_ali(c_obj)
Get node objects from AliCloud.
7.798341
6.669724
1.169215
for node in ali_nodes: node.cloud = "alicloud" node.cloud_disp = "AliCloud" node.private_ips = ip_to_str(node.extra['vpc_attributes']['private_ip_address']) node.public_ips = ip_to_str(node.public_ips) node.zone = node.extra['zone_id'] node.size = node.extra['ins...
def adj_nodes_ali(ali_nodes)
Adjust details specific to AliCloud.
3.323456
2.937387
1.131433
# def_list = 'def_list' in md.registeredExtensions md.parser.blockprocessors.add( 'figcaption', FigcaptionProcessor(md.parser), '<ulist')
def extendMarkdown(self, md, md_globals)
Add an instance of FigcaptionProcessor to BlockParser.
10.976338
7.367909
1.489749
if (uri is not None): try: fh = URLopener().open(uri) except IOError as e: raise Exception( "Failed to load sitemap/sitemapindex from %s (%s)" % (uri, str(e))) elif (str_data is not None): ...
def parse(self, uri=None, fh=None, str_data=None, **kwargs)
Parse a single XML document for this list. Accepts either a uri (uri or default if parameter not specified), or a filehandle (fh) or a string (str_data). Note that this method does not handle the case of a sitemapindex+sitemaps. LEGACY SUPPORT - the parameter str may be used in place o...
4.271606
4.070448
1.049419
self.default_capability() s = self.new_sitemap() return s.resources_as_xml(self, sitemapindex=self.sitemapindex)
def as_xml(self)
Return XML serialization of this list. This code does not support the case where the list is too big for a single XML document.
18.773695
16.918163
1.109677
self.default_capability() fh = open(basename, 'w') s = self.new_sitemap() s.resources_as_xml(self, fh=fh, sitemapindex=self.sitemapindex) fh.close()
def write(self, basename="/tmp/resynclist.xml")
Write a single sitemap or sitemapindex XML document. Must be overridden to support multi-file lists.
8.828909
6.85733
1.287514
if (resource.change is not None): self.resources.append(resource) else: raise ChangeTypeError(resource.change)
def add_if_changed(self, resource)
Add resource if change is not None else ChangeTypeError.
7.704659
3.806486
2.024087
if isinstance(resource, collections.Iterable): for r in resource: self.add_if_changed(r) else: self.add_if_changed(resource)
def add(self, resource)
Add a resource change or an iterable collection of them. Allows multiple resource_change objects for the same resource (ie. URI) and preserves the order of addition.
3.027997
2.830961
1.0696
for resource in resources: rc = Resource(resource=resource, change=change) self.add(rc)
def add_changed_resources(self, resources, change=None)
Add items from a ResourceContainer resources. If change is specified then the attribute is set in the Resource objects created.
5.438204
4.872755
1.116043
'''retrieve_config High-level api: Retrive config from rpc-reply. Parameters ---------- element : `Element` A rpc-reply or content of Config instance. Returns ------- Element A new element which represents config data. ...
def retrieve_config(element)
retrieve_config High-level api: Retrive config from rpc-reply. Parameters ---------- element : `Element` A rpc-reply or content of Config instance. Returns ------- Element A new element which represents config data.
3.265814
2.091748
1.561285
'''node_add High-level api: Combine two configs or apply an instance of ConfigDelta to a config. This method is recursive. node_sum will be modified during the process, and it becomes the result at the end. Parameters ---------- node_sum : `Element` ...
def node_add(self, node_sum, node_other)
node_add High-level api: Combine two configs or apply an instance of ConfigDelta to a config. This method is recursive. node_sum will be modified during the process, and it becomes the result at the end. Parameters ---------- node_sum : `Element` A config n...
3.697181
2.528086
1.462443
'''_node_add_without_peer_leaf Low-level api: Apply delta child_other to node_sum when there is no peer of child_other can be found under node_sum. child_other is a leaf node. Element node_sum will be modified during the process. Parameters ---------- node_sum ...
def _node_add_without_peer_leaf(self, node_sum, child_other)
_node_add_without_peer_leaf Low-level api: Apply delta child_other to node_sum when there is no peer of child_other can be found under node_sum. child_other is a leaf node. Element node_sum will be modified during the process. Parameters ---------- node_sum : `Element`...
6.291899
1.659429
3.791604
'''_node_add_without_peer_leaflist Low-level api: Apply delta child_other to node_sum when there is no peer of child_other can be found under node_sum. child_other is a leaf-list node. Element node_sum will be modified during the process. Parameters ---------- ...
def _node_add_without_peer_leaflist(self, node_sum, child_other)
_node_add_without_peer_leaflist Low-level api: Apply delta child_other to node_sum when there is no peer of child_other can be found under node_sum. child_other is a leaf-list node. Element node_sum will be modified during the process. Parameters ---------- node_sum : ...
2.386988
1.751882
1.362528
'''_node_add_without_peer_container Low-level api: Apply delta child_other to node_sum when there is no peer of child_other can be found under node_sum. child_other is a container node. Element node_sum will be modified during the process. Parameters ---------- ...
def _node_add_without_peer_container(self, node_sum, child_other)
_node_add_without_peer_container Low-level api: Apply delta child_other to node_sum when there is no peer of child_other can be found under node_sum. child_other is a container node. Element node_sum will be modified during the process. Parameters ---------- node_sum :...
6.38486
1.645987
3.879046
'''_node_add_without_peer_list Low-level api: Apply delta child_other to node_sum when there is no peer of child_other can be found under node_sum. child_other is a list node. Element node_sum will be modified during the process. Parameters ---------- node_sum ...
def _node_add_without_peer_list(self, node_sum, child_other)
_node_add_without_peer_list Low-level api: Apply delta child_other to node_sum when there is no peer of child_other can be found under node_sum. child_other is a list node. Element node_sum will be modified during the process. Parameters ---------- node_sum : `Element`...
2.468236
1.794129
1.375729
'''_node_add_with_peer_leaf Low-level api: Apply delta child_other to child_self when child_self is the peer of child_other. Element child_self and child_other are leaf nodes. Element child_self will be modified during the process. RFC6020 section 7.6.7 is a reference of this me...
def _node_add_with_peer_leaf(self, child_self, child_other)
_node_add_with_peer_leaf Low-level api: Apply delta child_other to child_self when child_self is the peer of child_other. Element child_self and child_other are leaf nodes. Element child_self will be modified during the process. RFC6020 section 7.6.7 is a reference of this method. ...
3.307129
1.845217
1.79227
'''_node_add_with_peer_container Low-level api: Apply delta child_other to child_self when child_self is the peer of child_other. Element child_self and child_other are container nodes. Element child_self will be modified during the process. RFC6020 section 7.5.8 is a reference ...
def _node_add_with_peer_container(self, child_self, child_other)
_node_add_with_peer_container Low-level api: Apply delta child_other to child_self when child_self is the peer of child_other. Element child_self and child_other are container nodes. Element child_self will be modified during the process. RFC6020 section 7.5.8 is a reference of this met...
3.603191
2.023021
1.781094
'''_url_to_prefix Low-level api: Convert an identifier from `{namespace}tagname` notation to `prefix:tagname` notation by looking at nsmap of the node. If the identifier does not have a namespace, the identifier is simply returned without modification. Parameters ...
def _url_to_prefix(node, id)
_url_to_prefix Low-level api: Convert an identifier from `{namespace}tagname` notation to `prefix:tagname` notation by looking at nsmap of the node. If the identifier does not have a namespace, the identifier is simply returned without modification. Parameters ---------...
4.073621
1.691348
2.408505
src = src.strip('\n') if not lang: lexer = TextLexer() else: try: lexer = get_lexer_by_name(lang, stripall=True) except ValueError: lexer = TextLexer() formatter = HtmlFormatter(linenos=linenums, tab_length=TAB_LENGTH) html = highlight(src, lexer,...
def highlight_syntax(src, lang, linenums=False)
Pass code to the [Pygments](http://pygments.pocoo.org/) highliter with optional line numbers. The output should then be styled with CSS to your liking. No styles are applied by default - only styling hooks (i.e.: <span class="k">).
2.898926
3.006198
0.964316
text = "\n".join(lines) while 1: m = FENCED_BLOCK_RE.search(text) if not m: break lang = m.group('lang') linenums = bool(m.group('linenums')) html = highlight_syntax(m.group('code'), lang, linenums=linenums) ...
def run(self, lines)
Match and store Fenced Code Blocks in the HtmlStash.
3.238187
2.720545
1.190271
if ('md5' in self.hashes): self.md5_calc = hashlib.md5() if ('sha-1' in self.hashes): self.sha1_calc = hashlib.sha1() if ('sha-256' in self.hashes): self.sha256_calc = hashlib.sha256()
def initialize_hashes(self)
Create new hashlib objects for each hash we are going to calculate.
1.866723
1.621255
1.151406
self.initialize_hashes() f = open(file, 'rb') while True: data = f.read(block_size) if not data: break if (self.md5_calc is not None): self.md5_calc.update(data) if (self.sha1_calc is not None): ...
def compute_for_file(self, file, block_size=2**14)
Compute hash digests for a file. Calculate the hashes based on one read through the file. Optional block_size parameter controls memory used to do calculations. This should be a multiple of 128 bytes.
1.78938
1.748724
1.023249
value = getattr(model_instance, self.attname) if self.clean_isbn and value not in EMPTY_VALUES: cleaned_isbn = value.replace(' ', '').replace('-', '').upper() setattr(model_instance, self.attname, cleaned_isbn) return super(ISBNField, self).pre_save(model_instanc...
def pre_save(self, model_instance, add)
Remove dashes, spaces, and convert isbn to uppercase before saving when clean_isbn is enabled
2.9966
2.041397
1.467916
# build ! width = self.width height = self.height tiles_w = self.tiles_w tiles_h = self.tiles_h self.z = 0 # add walls #self.map_layer = ti.load(os.path.join(script_dir, 'test.tmx'))['map0'] self.map_layer = self.generator.map(tiles_w, t...
def generate_random_level(self)
Configure and add cocos layers
2.907162
2.856014
1.017909
# if not playing dont update model if self.win_status != 'undecided': return # Step known time for agents if self.force_fps > 0: dt = 1 / self.force_fps # update target self.player.update_rotation(dt, self.buttons) # Get planned...
def update(self, dt)
Updates game engine each tick
4.197189
4.184633
1.003001
assert isinstance(self.player.cshape.center, eu.Vector2) pos = self.player.cshape.center # Helper function def set_visited(layer, cell): if cell and not cell.properties.get('visited') and cell.tile and cell.tile.id > 0: cell.properties['visited'] = T...
def update_visited(self)
Updates exploration map visited status
4.822218
4.852651
0.993729
assert isinstance(self.player.cshape.center, eu.Vector2) pos = self.player.cshape.center a = math.radians(self.player.rotation) for sensor in self.player.sensors: sensor.sensed_type = 'wall' rad = a + sensor.angle dis = min(self.distance_to_t...
def update_sensors(self)
Check path for each sensor and record wall proximity
5.841986
5.69014
1.026686
# Include battery level in state battery = self.player.stats['battery']/100 # Create observation from sensor proximities # TODO: Have state persist, then update columns by `sensed_type` # Multi-channel; detecting `items` if len(self.mode['items']) > 0: ...
def get_state(self)
Create state from sensors and battery
6.173845
5.828823
1.059192
assert isinstance(buttons, dict) ma = buttons['right'] - buttons['left'] if ma != 0: self.stats['battery'] -= self.battery_use['angular'] self.rotation += ma * dt * self.angular_velocity # Redirect velocity in new direction a = math.radians(self...
def update_rotation(self, dt, buttons)
Updates rotation and impulse direction
8.276958
7.327964
1.129503
assert isinstance(dt, int) or isinstance(dt, float) assert isinstance(buttons, dict) newVel = self.velocity # Redirect existing vel to new direction. nv = newVel.magnitude() newVel = nv * self.impulse_dir mv = buttons['up'] if mv != 0: ...
def do_move(self, dt, buttons)
Updates velocity and returns Rects for start/finish positions
5.864287
5.646287
1.038609