code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
self.run("useradd -m %s" % user) usr = getpwnam(user) return usr
def create_user(self, user)
Create a user on the local system
9.769242
7.481833
1.305728
'''Split a chunk of data into sections by start and end binary content tags.''' # using string split because it is significantly faster than regex. # use common text of start and end tags to split the text # (i.e. without < or </ tag beginning) binary_content_tag = BINARY_CONTENT_START[1:] ...
def binarycontent_sections(chunk)
Split a chunk of data into sections by start and end binary content tags.
6.908667
6.172051
1.119347
'''Calculate a rough estimate of object size, based on the sizes of all versions of all datastreams. If archive is true, adjusts the size estimate of managed datastreams for base64 encoded data. ''' size_estimate = 250000 # initial rough estimate for foxml size for ds in obj.ds_list: ...
def estimate_object_size(obj, archive=True)
Calculate a rough estimate of object size, based on the sizes of all versions of all datastreams. If archive is true, adjusts the size estimate of managed datastreams for base64 encoded data.
6.825797
3.32314
2.05402
'''Check if the text ends with any partial version of the specified string.''' # at the end of the content # we don't care about complete overlap, so start checking # for matches without the last character test_str = partial_str[:-1] # look for progressively smaller segments while test_s...
def endswith_partial(text, partial_str)
Check if the text ends with any partial version of the specified string.
7.402945
6.010906
1.231585
'''Use regular expressions to pull datastream [version] details (id, mimetype, size, and checksum) for binary content, in order to sanity check the decoded data. :param dsinfo: text content just before a binaryContent tag :returns: dict with keys for id, mimetype, size, type and...
def get_datastream_info(self, dsinfo)
Use regular expressions to pull datastream [version] details (id, mimetype, size, and checksum) for binary content, in order to sanity check the decoded data. :param dsinfo: text content just before a binaryContent tag :returns: dict with keys for id, mimetype, size, type and digest, ...
7.679899
4.541998
1.690864
'''Process the archival export and return a buffer with foxml content for ingest into the destination repository. :returns: :class:`io.BytesIO` for ingest, with references to uploaded datastream content or content location urls ''' self.foxml_buffer = io.BytesIO() ...
def object_data(self)
Process the archival export and return a buffer with foxml content for ingest into the destination repository. :returns: :class:`io.BytesIO` for ingest, with references to uploaded datastream content or content location urls
5.463394
4.42443
1.234824
'''Generator for datastream content. Takes a list of sections of data within the current chunk (split on binaryContent start and end tags), runs a base64 decode, and yields the data. Computes datastream size and MD5 as data is decoded for sanity-checking purposes. If binary con...
def encoded_datastream(self)
Generator for datastream content. Takes a list of sections of data within the current chunk (split on binaryContent start and end tags), runs a base64 decode, and yields the data. Computes datastream size and MD5 as data is decoded for sanity-checking purposes. If binary content is not...
6.032688
2.71552
2.221559
dme_url = 'https://www.dnsmadeeasy.com/servlet/updateip' dme_url += '?username=%s&password=%s&id=%s&ip=%s' s = urllib2.urlopen(dme_url % (username, password, dme_id, ip_address)) return s.read()
def update_dme(username, password, dme_id, ip_address)
Update your Dynamic DNS record with DNSMadeEasy.com
3.001827
2.582937
1.162176
boto.log.info('Fetching %s' % uri) if file == None: file = tempfile.NamedTemporaryFile() try: if uri.startswith('s3://'): bucket_name, key_name = uri[len('s3://'):].split('/', 1) c = boto.connect_s3(aws_access_key_id=username, aws_secret_access_key=password) ...
def fetch_file(uri, file=None, username=None, password=None)
Fetch a file based on the URI provided. If you do not pass in a file pointer a tempfile.NamedTemporaryFile, or None if the file could not be retrieved is returned. The URI can be either an HTTP url, or "s3://bucket_name/key_name"
1.735452
1.69584
1.023358
wrapper = MIMEMultipart() for name,con in content: definite_type = guess_mime_type(con, deftype) maintype, subtype = definite_type.split('/', 1) if maintype == 'text': mime_con = MIMEText(con, _subtype=subtype) else: mime_con = MIMEBase(maintype, subt...
def write_mime_multipart(content, compress=False, deftype='text/plain', delimiter=':')
Description: :param content: A list of tuples of name-content pairs. This is used instead of a dict to ensure that scripts run in order :type list of tuples: :param compress: Use gzip to compress the scripts, defaults to no compression :type bool: :param deftype: The type that should be assume...
2.004578
2.050775
0.977474
#Mappings recognized by cloudinit starts_with_mappings={ '#include' : 'text/x-include-url', '#!' : 'text/x-shellscript', '#cloud-config' : 'text/cloud-config', '#upstart-job' : 'text/upstart-job', '#part-handler' : 'text/part-handler', '#cloud-boothook' : 't...
def guess_mime_type(content, deftype)
Description: Guess the mime type of a block of text :param content: content we're finding the type of :type str: :param deftype: Default mime type :type str: :rtype: <type>: :return: <description>
4.116645
4.382039
0.939436
m = md5() spos = fp.tell() if size and size < buf_size: s = fp.read(size) else: s = fp.read(buf_size) while s: m.update(s) if size: size -= len(s) if size <= 0: break if size and size < buf_size: s = fp....
def compute_md5(fp, buf_size=8192, size=None)
Compute MD5 hash on passed file and return results in a tuple of values. :type fp: file :param fp: File pointer to the file to MD5 hash. The file pointer will be reset to its current location before the method returns. :type buf_size: integer :param buf_size: Number of b...
2.101109
2.06137
1.019278
regions = [] for region_name in RegionData: region = RegionInfo(name=region_name, endpoint=RegionData[region_name], connection_cls=CloudWatchConnection) regions.append(region) return regions
def regions()
Get all available regions for the CloudWatch service. :rtype: list :return: A list of :class:`boto.RegionInfo` instances
5.180288
3.775749
1.37199
params = {'Period' : period, 'MetricName' : metric_name, 'Namespace' : namespace, 'StartTime' : start_time.isoformat(), 'EndTime' : end_time.isoformat()} self.build_list_params(params, statistics, 'Statistics.member.%d') ...
def get_metric_statistics(self, period, start_time, end_time, metric_name, namespace, statistics, dimensions=None, unit=None)
Get time-series data for one or more statistics of a given metric. :type period: integer :param period: The granularity, in seconds, of the returned datapoints. Period must be at least 60 seconds and must be a multiple of 60. The default value is 60. ...
2.667638
3.146873
0.847711
params = {} if next_token: params['NextToken'] = next_token if dimensions: self.build_dimension_param(dimensions, params) if metric_name: params['MetricName'] = metric_name if namespace: params['Namespace'] = namespace ...
def list_metrics(self, next_token=None, dimensions=None, metric_name=None, namespace=None)
Returns a list of the valid metrics for which there is recorded data available. :type next_token: str :param next_token: A maximum of 500 metrics will be returned at one time. If more results are available, the ResultSet returned will conta...
2.194039
2.51349
0.872905
params = {'Namespace': namespace} self.build_put_params(params, name, value=value, timestamp=timestamp, unit=unit, dimensions=dimensions, statistics=statistics) return self.get_status('PutMetricData', params)
def put_metric_data(self, namespace, name, value=None, timestamp=None, unit=None, dimensions=None, statistics=None)
Publishes metric data points to Amazon CloudWatch. Amazon Cloudwatch associates the data points with the specified metric. If the specified metric does not exist, Amazon CloudWatch creates the metric. If a list is specified for some, but not all, of the arguments, the remaining argum...
3.02595
4.608276
0.656634
params = {} if action_prefix: params['ActionPrefix'] = action_prefix if alarm_name_prefix: params['AlarmNamePrefix'] = alarm_name_prefix elif alarm_names: self.build_list_params(params, alarm_names, 'AlarmNames.member.%s') if max_recor...
def describe_alarms(self, action_prefix=None, alarm_name_prefix=None, alarm_names=None, max_records=None, state_value=None, next_token=None)
Retrieves alarms with the specified names. If no name is specified, all alarms for the user are returned. Alarms can be retrieved by using only a prefix for the alarm name, the alarm state, or a prefix for any action. :type action_prefix: string :param action_name: The action na...
1.791903
2.052197
0.873163
params = {} if alarm_name: params['AlarmName'] = alarm_name if start_date: params['StartDate'] = start_date.isoformat() if end_date: params['EndDate'] = end_date.isoformat() if history_item_type: params['HistoryItemType'] =...
def describe_alarm_history(self, alarm_name=None, start_date=None, end_date=None, max_records=None, history_item_type=None, next_token=None)
Retrieves history for the specified alarm. Filter alarms by date range or item type. If an alarm name is not specified, Amazon CloudWatch returns histories for all of the owner's alarms. Amazon CloudWatch retains the history of deleted alarms for a period of six weeks. If an alarm has b...
1.474428
1.572282
0.937763
params = {'MetricName' : metric_name, 'Namespace' : namespace} if period: params['Period'] = period if statistic: params['Statistic'] = statistic if dimensions: self.build_dimension_param(dimensions, params) if unit: ...
def describe_alarms_for_metric(self, metric_name, namespace, period=None, statistic=None, dimensions=None, unit=None)
Retrieves all alarms for a single metric. Specify a statistic, period, or unit to filter the set of alarms further. :type metric_name: string :param metric_name: The name of the metric :type namespace: string :param namespace: The namespace of the metric. :type period:...
2.090951
2.499226
0.836639
params = { 'AlarmName' : alarm.name, 'MetricName' : alarm.metric, 'Namespace' : alarm.namespace, 'Statistic' : alarm.statistic, 'Com...
def put_metric_alarm(self, alarm)
Creates or updates an alarm and associates it with the specified Amazon CloudWatch metric. Optionally, this operation can associate one or more Amazon Simple Notification Service resources with the alarm. When this operation creates an alarm, the alarm state is immediately set to INSUFF...
1.762465
1.745792
1.00955
params = {} self.build_list_params(params, alarms, 'AlarmNames.member.%s') return self.get_status('DeleteAlarms', params)
def delete_alarms(self, alarms)
Deletes all specified alarms. In the event of an error, no alarms are deleted. :type alarms: list :param alarms: List of alarm names.
3.603601
5.236909
0.688116
params = {'AlarmName' : alarm_name, 'StateReason' : state_reason, 'StateValue' : state_value} if state_reason_data: params['StateReasonData'] = json.dumps(state_reason_data) return self.get_status('SetAlarmState', params)
def set_alarm_state(self, alarm_name, state_reason, state_value, state_reason_data=None)
Temporarily sets the state of an alarm. When the updated StateValue differs from the previous value, the action configured for the appropriate state is invoked. This is not a permanent change. The next periodic alarm check (in about a minute) will set the alarm to its actual state. ...
1.975506
2.307085
0.856278
params = {} self.build_list_params(params, alarm_names, 'AlarmNames.member.%s') return self.get_status('EnableAlarmActions', params)
def enable_alarm_actions(self, alarm_names)
Enables actions for the specified alarms. :type alarms: list :param alarms: List of alarm names.
3.346461
4.966255
0.67384
params = {} self.build_list_params(params, alarm_names, 'AlarmNames.member.%s') return self.get_status('DisableAlarmActions', params)
def disable_alarm_actions(self, alarm_names)
Disables actions for the specified alarms. :type alarms: list :param alarms: List of alarm names.
3.371509
4.929792
0.683905
boto.log.info('checking Task[%s]-now=%s, last=%s' % (self.name, self.now, self.last_executed)) if self.hourly and not self.last_executed: return 0 if self.daily and not self.last_executed: if int(self.hour) == self.now.hour: return 0...
def check(self)
Determine how long until the next scheduled time for a Task. Returns the number of seconds until the next scheduled time or zero if the task needs to be run immediately. If it's an hourly task and it's never been run, run it now. If it's a daily task and it's never been run and the hour ...
2.802963
2.411443
1.162359
''' set securities ''' for security in self.securities: self.__trakers[security]=OneTraker(security, self, self.buying_ratio)
def __setUpTrakers(self)
set securities
12.347834
8.448139
1.461604
''' call back for executed order ''' for orderId, order in orderDict.items(): if order.security in self.__trakers.keys(): self.__trakers[order.security].orderExecuted(orderId)
def order_executed(self, orderDict)
call back for executed order
6.192358
6.296789
0.983415
''' consume ticks ''' if not self.__trakers: self.__setUpTrakers() for security, tick in tickDict.items(): if security in self.__trakers: self.__trakers[security].tickUpdate(tick)
def update(self, tickDict)
consume ticks
6.209474
5.992845
1.036148
''' place buy order if conditions meet ''' # place short sell order ''' if (self.__smaShort.getLastValue() < self.__smaLong.getLastValue() or self.__smaMid.getLastValue() < self.__smaLong.getLastValue()): if tick.close/self.__previousMovingLowWeek < 0.95: retu...
def __buyIfMeet(self, tick)
place buy order if conditions meet
2.141825
2.103652
1.018146
''' place short sell order''' share=math.floor(self.__strategy.getAccountCopy().getCash() / float(tick.close)) sellShortOrder=Order(accountId=self.__strategy.accountId, action=Action.SELL_SHORT, is_market=True, ...
def __placeSellShortOrder(self, tick)
place short sell order
4.188649
4.185804
1.00068
''' calculate the amount of money to buy stock ''' account=self.__strategy.getAccountCopy() if (account.getCash() >= account.getTotalValue() / self.buying_ratio): return account.getTotalValue() / self.buying_ratio else: return 0
def __getCashToBuyStock(self)
calculate the amount of money to buy stock
6.023599
5.656416
1.064914
''' place buy order''' cash=self.__getCashToBuyStock() if cash == 0: return share=math.floor(cash / float(tick.close)) buyOrder=Order(accountId=self.__strategy.accountId, action=Action.BUY, is_market...
def __placeBuyOrder(self, tick)
place buy order
3.824608
3.937758
0.971265
''' place stop order ''' orderId=self.__strategy.placeOrder(order) if orderId: self.__stopOrderId=orderId self.__stopOrder=order else: LOG.error("Can't place stop order %s" % order)
def __placeStopOrder(self, order)
place stop order
4.57868
5.038218
0.90879
''' call back for executed order ''' if orderId == self.__stopOrderId: LOG.debug("smaStrategy stop order canceled %s" % orderId) # stop order executed self.__clearStopOrder()
def orderExecuted(self, orderId)
call back for executed order
12.397135
12.733128
0.973613
''' update stop order if needed ''' if not self.__stopOrderId: return if self.__stopOrder.action == Action.SELL: orgStopPrice=self.__buyOrder.price * 0.95 newStopPrice=max(((tick.close + orgStopPrice) / 2), tick.close * 0.85) newStopPrice=min(newS...
def __adjustStopOrder(self, tick)
update stop order if needed
2.253685
2.248461
1.002323
''' update previous state ''' self.__previousTick=tick self.__previousSmaShort=self.__smaShort.getLastValue() self.__previousSmaMid=self.__smaMid.getLastValue() self.__previousSmaLong=self.__smaLong.getLastValue() self.__previousSmaVolumeShort=self.__smaVolumeShort.getLas...
def __updatePreviousState(self, tick)
update previous state
2.456006
2.457348
0.999454
''' consume ticks ''' LOG.debug("tickUpdate %s with tick %s, price %s" % (self.__security, tick.time, tick.close)) # update sma self.__smaShort(tick.close) self.__smaMid(tick.close) self.__smaLong(tick.close) self.__smaVolumeShort(tick.volume) self.__smaVo...
def tickUpdate(self, tick)
consume ticks
5.66768
5.559869
1.019391
assert(len(val) == self.sequence_length) return self.sequence_string[(self.sequence_string.index(val)+1) % len(self.sequence_string)]
def _inc(self, val)
Increment a single value
5.132548
5.357141
0.958076
import time now = time.time() expected_value = [] new_val = {} new_val['timestamp'] = now if self._value != None: new_val['last_value'] = self._value expected_value = ['current_value', str(self._value)] new_val['current_value'] = v...
def set(self, val)
Set the value
4.004193
4.052872
0.987989
val = self.db.get_attributes(self.id, consistent_read=True) if val: if val.has_key('timestamp'): self.timestamp = val['timestamp'] if val.has_key('current_value'): self._value = self.item_type(val['current_value']) if val.has_k...
def get(self)
Get the value
3.246988
3.207256
1.012388
if not self._db: import boto sdb = boto.connect_sdb() if not self.domain_name: self.domain_name = boto.config.get("DB", "sequence_db", boto.config.get("DB", "db_name", "default")) try: self._db = sdb.get_domain(self.domain_...
def _connect(self)
Connect to our domain
2.815802
2.741956
1.026932
c_data = StringIO.StringIO() c_data.write("[Credentials]\n") for line in open(path, "r").readlines(): c_data.write(line.replace("AWSAccessKeyId", "aws_access_key_id").replace("AWSSecretKey", "aws_secret_access_key")) c_data.seek(0) self.readfp(c_data)
def load_credential_file(self, path)
Load a credential file as is setup like the Java utilities
2.645862
2.592618
1.020537
config = ConfigParser.SafeConfigParser() config.read(path) if not config.has_section(section): config.add_section(section) config.set(section, option, value) fp = open(path, 'w') config.write(fp) fp.close() if not self.has_section(sect...
def save_option(self, path, section, option, value)
Write the specified Section.Option to the config file specified by path. Replace any previous value. If the path doesn't exist, create it. Also add the option the the in-memory config.
1.647457
1.523443
1.081404
self.append(Batch(table, keys, attributes_to_get))
def add_batch(self, table, keys, attributes_to_get=None)
Add a Batch to this BatchList. :type table: :class:`boto.dynamodb.table.Table` :param table: The Table object in which the items are contained. :type keys: list :param keys: A list of scalar or tuple values. Each element in the list represents one Item to retrieve....
6.010784
5.357072
1.122028
connection_args = dict(self.connection_args or ()) # Use OrdinaryCallingFormat instead of boto-default # SubdomainCallingFormat because the latter changes the hostname # that's checked during cert validation for HTTPS connections, # which will fail cert validation (when ...
def connect(self, access_key_id=None, secret_access_key=None, **kwargs)
Opens a connection to appropriate provider, depending on provider portion of URI. Requires Credentials defined in boto config file (see boto/pyami/config.py). @type storage_uri: StorageUri @param storage_uri: StorageUri specifying a bucket or a bucket+object @rtype: L{AWSAuthConn...
3.096102
3.04147
1.017962
if not self.bucket_name: raise InvalidUriError('clone_replace_name() on bucket-less URI %s' % self.uri) return BucketStorageUri( self.scheme, self.bucket_name, new_name, self.debug, suppress_consec_slashes=self.suppress_conse...
def clone_replace_name(self, new_name)
Instantiate a BucketStorageUri from the current BucketStorageUri, but replacing the object_name. @type new_name: string @param new_name: new object name
4.860339
4.308343
1.128122
if not self.bucket_name: raise InvalidUriError('get_acl on bucket-less URI (%s)' % self.uri) bucket = self.get_bucket(validate, headers) # This works for both bucket- and object- level ACLs (former passes # key_name=None): acl = bucket.get_acl(self.object_nam...
def get_acl(self, validate=True, headers=None, version_id=None)
returns a bucket's acl
5.552091
5.364586
1.034952
if not self.bucket_name: raise InvalidUriError('set_acl on bucket-less URI (%s)' % self.uri) self.get_bucket(validate, headers).set_acl(acl_or_str, key_name, headers, version_id)
def set_acl(self, acl_or_str, key_name='', validate=True, headers=None, version_id=None)
sets or updates a bucket's acl
4.518722
4.572507
0.988237
if not self.object_name: raise InvalidUriError('set_canned_acl on object-less URI (%s)' % self.uri) key = self.get_key(validate, headers) self.check_response(key, 'key', self.uri) key.set_canned_acl(acl_str, headers, version_id)
def set_canned_acl(self, acl_str, validate=True, headers=None, version_id=None)
sets or updates a bucket's acl to a predefined (canned) value
4.825472
4.745934
1.016759
if not self.stream: return os.path.isdir(self.object_name) else: return False
def names_container(self)
Returns True if this URI is not representing input/output stream and names a directory.
9.99356
4.556651
2.193181
if self.stream: return True else: return os.path.isfile(self.object_name)
def names_singleton(self)
Returns True if this URI names a file or if URI represents input/output stream.
9.408756
5.768175
1.63115
yql = YQL('AAPL', '2014-01-01', '2014-01-10') for item in yql: print item.get('date'), item.get('price') yql.select('AAPL', '2014-01-01', '2014-01-10') for item in yql: print item.get('date'), item.get('price')
def fetch_appl()
Returns stock prices for Apple company.
2.294447
2.175051
1.054894
yql = YQL('GOOGL', '2014-01-01', '2014-01-10') for item in yql: print item.get('date'), item.get('price') yql.select('GOOGL', '2014-01-01', '2014-01-10') for item in yql: print item.get('date'), item.get('price')
def fetch_googl()
Returns stock prices for Google company.
2.351321
2.312616
1.016737
# Check the resultset since Eucalyptus ignores the volumeId param unfiltered_rs = self.connection.get_all_volumes([self.id]) rs = [ x for x in unfiltered_rs if x.id == self.id ] if len(rs) > 0: self._update(rs[0]) elif validate: raise ValueError('...
def update(self, validate=False)
Update the data associated with this volume by querying EC2. :type validate: bool :param validate: By default, if EC2 returns no data about the volume the update method returns quietly. If the validate param is True, however, it will ...
5.238061
4.179274
1.253343
return self.connection.attach_volume(self.id, instance_id, device)
def attach(self, instance_id, device)
Attach this EBS volume to an EC2 instance. :type instance_id: str :param instance_id: The ID of the EC2 instance to which it will be attached. :type device: str :param device: The device on the instance through which the volume will be...
4.384971
6.416234
0.683418
instance_id = None if self.attach_data: instance_id = self.attach_data.instance_id device = None if self.attach_data: device = self.attach_data.device return self.connection.detach_volume(self.id, instance_id, device, force)
def detach(self, force=False)
Detach this EBS volume from an EC2 instance. :type force: bool :param force: Forces detachment if the previous detachment attempt did not occur cleanly. This option can lead to data loss or a corrupted file system. Use this option only as a last ...
2.760711
2.811334
0.981993
state = None if self.attach_data: state = self.attach_data.status return state
def attachment_state(self)
Get the attachment state.
6.185697
5.121276
1.207843
rs = self.connection.get_all_snapshots(owner=owner, restorable_by=restorable_by) mine = [] for snap in rs: if snap.volume_id == self.id: mine.append(snap) return mine
def snapshots(self, owner=None, restorable_by=None)
Get all snapshots related to this volume. Note that this requires that all available snapshots for the account be retrieved from EC2 first and then the list is filtered client-side to contain only those for this volume. :type owner: str :param owner: If present, only the snapsh...
2.998977
2.983623
1.005146
'''Method for accessing an encryption key based on the SECRET_KEY defined in django settings.''' # initialize ENCRYPTION_KEY the first time it is needed, so that # applications that use eulcore without using this specific # functionality do not get bogus warnings about SECRET_KEY size. global EN...
def _get_encryption_key()
Method for accessing an encryption key based on the SECRET_KEY defined in django settings.
5.898824
5.034969
1.171571
'Encrypt a string using an encryption key based on the django SECRET_KEY' crypt = EncryptionAlgorithm.new(_get_encryption_key()) return crypt.encrypt(to_blocksize(text))
def encrypt(text)
Encrypt a string using an encryption key based on the django SECRET_KEY
14.509142
6.914476
2.098372
'Decrypt a string using an encryption key based on the django SECRET_KEY' crypt = EncryptionAlgorithm.new(_get_encryption_key()) return crypt.decrypt(text).rstrip(ENCRYPT_PAD_CHARACTER)
def decrypt(text)
Decrypt a string using an encryption key based on the django SECRET_KEY
14.536345
7.472447
1.945326
self.args.update(args) self.connection_args = copy.copy(self.args) if 'debug' in self.args and self.args['debug'] >= 2: boto.set_stream_logger(self.name()) required = [p.name for p in self.Params+self.Args if not p.optional] for param in self.Params+self.Args...
def process_args(self, **args)
Responsible for walking through Params defined for the request and: * Matching them with keyword parameters passed to the request constructor or via the command line. * Checking to see if all required parameters have been specified and raising an exception, if not. * Encodin...
2.740411
2.636615
1.039367
if len(dct.keys()) > 1: return dct if 'S' in dct: return dct['S'] if 'N' in dct: return convert_num(dct['N']) if 'SS' in dct: return set(dct['SS']) if 'NS' in dct: return set(map(convert_num, dct['NS'])) return dct
def item_object_hook(dct)
A custom object hook for use when decoding JSON item bodys. This hook will transform Amazon DynamoDB JSON responses to something that maps directly to native Python types.
2.131371
2.141355
0.995338
d = {} for attr_name in pending_updates: action, value = pending_updates[attr_name] if value is None: # DELETE without an attribute value d[attr_name] = {"Action": action} else: d[attr_name] = {"Action": action,...
def dynamize_attribute_updates(self, pending_updates)
Convert a set of pending item updates into the structure required by Layer1.
3.068713
2.973116
1.032154
d = None if range_key_condition: d = {} for range_value in range_key_condition: range_condition = range_key_condition[range_value] if range_condition == 'BETWEEN': if isinstance(range_value, tuple): ...
def dynamize_range_key_condition(self, range_key_condition)
Convert a layer2 range_key_condition parameter into the structure required by Layer1.
2.905926
2.907783
0.999362
d = None if scan_filter: d = {} for attr_name, op, value in scan_filter: if op == 'BETWEEN': if isinstance(value, tuple): avl = [self.dynamize_value(v) for v in value] else: ...
def dynamize_scan_filter(self, scan_filter)
Convert a layer2 scan_filter parameter into the structure required by Layer1.
3.119137
3.255127
0.958223
d = None if expected_value: d = {} for attr_name in expected_value: attr_value = expected_value[attr_name] if attr_value is True: attr_value = {'Exists': True} elif attr_value is False: ...
def dynamize_expected_value(self, expected_value)
Convert an expected_value parameter into the data structure required for Layer1.
2.365527
2.31372
1.022391
d = None if last_evaluated_key: hash_key = last_evaluated_key['HashKeyElement'] d = {'HashKeyElement': self.dynamize_value(hash_key)} if 'RangeKeyElement' in last_evaluated_key: range_key = last_evaluated_key['RangeKeyElement'] ...
def dynamize_last_evaluated_key(self, last_evaluated_key)
Convert a last_evaluated_key parameter into the data structure required for Layer1.
2.012406
2.003167
1.004613
d = None if batch_list: d = {} for batch in batch_list: batch_dict = {} key_list = [] for key in batch.keys: if isinstance(key, tuple): hash_key, range_key = key ...
def dynamize_request_items(self, batch_list)
Convert a request_items parameter into the data structure required for Layer1.
2.465507
2.481884
0.993401
dynamodb_type = None if is_num(val): dynamodb_type = 'N' elif is_str(val): dynamodb_type = 'S' elif isinstance(val, (set, frozenset)): if False not in map(is_num, val): dynamodb_type = 'NS' elif False not in map(is_...
def get_dynamodb_type(self, val)
Take a scalar Python value and return a string representing the corresponding Amazon DynamoDB type. If the value passed in is not a supported type, raise a TypeError.
2.015793
1.904828
1.058255
def _str(val): if isinstance(val, bool): return str(int(val)) return str(val) dynamodb_type = self.get_dynamodb_type(val) if dynamodb_type == 'N': val = {dynamodb_type : _str(val)} elif dynamodb_type == 'S': ...
def dynamize_value(self, val)
Take a scalar Python value and return a dict consisting of the Amazon DynamoDB type specification and the value that needs to be sent to Amazon DynamoDB. If the type of the value is not supported, raise a TypeError
2.493048
2.391057
1.042655
dynamodb_key = {} dynamodb_value = self.dynamize_value(hash_key) if dynamodb_value.keys()[0] != schema.hash_key_type: msg = 'Hashkey must be of type: %s' % schema.hash_key_type raise TypeError(msg) dynamodb_key['HashKeyElement'] = dynamodb_value i...
def build_key_from_values(self, schema, hash_key, range_key=None)
Build a Key structure to be used for accessing items in Amazon DynamoDB. This method takes the supplied hash_key and optional range_key and validates them against the schema. If there is a mismatch, a TypeError is raised. Otherwise, a Python dict version of a Amazon DynamoDB Key ...
1.965858
2.016555
0.974859
result = self.layer1.list_tables(limit, start_table) return result['TableNames']
def list_tables(self, limit=None, start_table=None)
Return a list of the names of all Tables associated with the current account and region. TODO - Layer2 should probably automatically handle pagination. :type limit: int :param limit: The maximum number of tables to return. :type start_table: str :param limit: The name o...
6.412919
5.948118
1.078143
response = self.layer1.describe_table(name) return Table(self, response)
def get_table(self, name)
Retrieve the Table object for an existing table. :type name: str :param name: The name of the desired table. :rtype: :class:`boto.dynamodb.table.Table` :return: A Table object representing the table.
11.874788
10.788379
1.100702
response = self.layer1.create_table(name, schema.dict, {'ReadCapacityUnits': read_units, 'WriteCapacityUnits': write_units}) return Table(self, response)
def create_table(self, name, schema, read_units, write_units)
Create a new Amazon DynamoDB table. :type name: str :param name: The name of the desired table. :type schema: :class:`boto.dynamodb.schema.Schema` :param schema: The Schema object that defines the schema used by this table. :type read_units: int...
5.293357
5.033225
1.051683
response = self.layer1.update_table(table.name, {'ReadCapacityUnits': read_units, 'WriteCapacityUnits': write_units}) table.update_from_response(response['TableDescription'])
def update_throughput(self, table, read_units, write_units)
Update the ProvisionedThroughput for the Amazon DynamoDB Table. :type table: :class:`boto.dynamodb.table.Table` :param table: The Table object whose throughput is being updated. :type read_units: int :param read_units: The new value for ReadCapacityUnits. :type...
4.027525
4.113988
0.978983
response = self.layer1.delete_table(table.name) table.update_from_response(response)
def delete_table(self, table)
Delete this table and all items in it. After calling this the Table objects status attribute will be set to 'DELETING'. :type table: :class:`boto.dynamodb.table.Table` :param table: The Table object that is being deleted.
6.908766
6.358958
1.086462
schema = {} hash_key = {} hash_key['AttributeName'] = hash_key_name hash_key_type = self.get_dynamodb_type(hash_key_proto_value) hash_key['AttributeType'] = hash_key_type schema['HashKeyElement'] = hash_key if range_key_name and range_key_proto_value is n...
def create_schema(self, hash_key_name, hash_key_proto_value, range_key_name=None, range_key_proto_value=None)
Create a Schema object used when creating a Table. :type hash_key_name: str :param hash_key_name: The name of the HashKey for the schema. :type hash_key_proto_value: int|long|float|str|unicode :param hash_key_proto_value: A sample or prototype of the type of value you want ...
1.539346
1.61852
0.951082
key = self.build_key_from_values(table.schema, hash_key, range_key) response = self.layer1.get_item(table.name, key, attributes_to_get, consistent_read, object_hook=item_object_hook) item = item_class(table,...
def get_item(self, table, hash_key, range_key=None, attributes_to_get=None, consistent_read=False, item_class=Item)
Retrieve an existing item from the table. :type table: :class:`boto.dynamodb.table.Table` :param table: The Table object from which the item is retrieved. :type hash_key: int|long|float|str|unicode :param hash_key: The HashKey of the requested item. The type of the...
2.794868
3.103925
0.90043
request_items = self.dynamize_request_items(batch_list) return self.layer1.batch_get_item(request_items, object_hook=item_object_hook)
def batch_get_item(self, batch_list)
Return a set of attributes for a multiple items in multiple tables using their primary keys. :type batch_list: :class:`boto.dynamodb.batch.BatchList` :param batch_list: A BatchList object which consists of a list of :class:`boto.dynamoddb.batch.Batch` objects. Each Batch...
6.447032
7.818668
0.824569
expected_value = self.dynamize_expected_value(expected_value) response = self.layer1.put_item(item.table.name, self.dynamize_item(item), expected_value, return_values, object_...
def put_item(self, item, expected_value=None, return_values=None)
Store a new item or completely replace an existing item in Amazon DynamoDB. :type item: :class:`boto.dynamodb.item.Item` :param item: The Item to write to Amazon DynamoDB. :type expected_value: dict :param expected_value: A dictionary of name/value pairs that you expect...
4.195086
4.219461
0.994223
expected_value = self.dynamize_expected_value(expected_value) key = self.build_key_from_values(item.table.schema, item.hash_key, item.range_key) attr_updates = self.dynamize_attribute_updates(item._updates) response = self.layer1.update_...
def update_item(self, item, expected_value=None, return_values=None)
Commit pending item updates to Amazon DynamoDB. :type item: :class:`boto.dynamodb.item.Item` :param item: The Item to update in Amazon DynamoDB. It is expected that you would have called the add_attribute, put_attribute and/or delete_attribute methods on this Item prior to call...
4.091397
3.711258
1.102429
expected_value = self.dynamize_expected_value(expected_value) key = self.build_key_from_values(item.table.schema, item.hash_key, item.range_key) return self.layer1.delete_item(item.table.name, key, expected=...
def delete_item(self, item, expected_value=None, return_values=None)
Delete the item from Amazon DynamoDB. :type item: :class:`boto.dynamodb.item.Item` :param item: The Item to delete from Amazon DynamoDB. :type expected_value: dict :param expected_value: A dictionary of name/value pairs that you expect. This dictionary should have n...
4.431647
4.178835
1.060498
rkc = self.dynamize_range_key_condition(range_key_condition) response = True n = 0 while response: if response is True: pass elif response.has_key("LastEvaluatedKey"): lek = response['LastEvaluatedKey'] excl...
def query(self, table, hash_key, range_key_condition=None, attributes_to_get=None, request_limit=None, max_results=None, consistent_read=False, scan_index_forward=True, exclusive_start_key=None, item_class=Item)
Perform a query on the table. :type table: :class:`boto.dynamodb.table.Table` :param table: The Table object that is being queried. :type hash_key: int|long|float|str|unicode :param hash_key: The HashKey of the requested item. The type of the value must mat...
3.402776
3.598555
0.945595
sf = self.dynamize_scan_filter(scan_filter) response = True n = 0 while response: if response is True: pass elif response.has_key("LastEvaluatedKey"): exclusive_start_key = response['LastEvaluatedKey'] else: ...
def scan(self, table, scan_filter=None, attributes_to_get=None, request_limit=None, max_results=None, count=False, exclusive_start_key=None, item_class=Item)
Perform a scan of DynamoDB. :type table: :class:`boto.dynamodb.table.Table` :param table: The Table object that is being scanned. :type scan_filter: A list of tuples :param scan_filter: A list of tuples where each tuple consists of an attribute name, a comparison operator, ...
3.504417
3.839752
0.912667
method = 'flickr.photos.search' data = _doget(method, auth=auth, user_id=user_id, tags=tags, text=text,\ min_upload_date=min_upload_date,\ max_upload_date=max_upload_date, \ min_taken_date=min_taken_date, \ max_taken_date=max_taken_da...
def photos_search(user_id='', auth=False, tags='', tag_mode='', text='',\ min_upload_date='', max_upload_date='',\ min_taken_date='', max_taken_date='', \ license='', per_page='', page='', sort='')
Returns a list of Photo objects. If auth=True then will auth the user. Can see private etc
1.806122
1.930741
0.935455
method = 'flickr.people.findByEmail' data = _doget(method, find_email=email) user = User(data.rsp.user.id, username=data.rsp.user.username.text) return user
def people_findByEmail(email)
Returns User object.
7.665192
6.795332
1.128008
method = 'flickr.people.findByUsername' data = _doget(method, username=username) user = User(data.rsp.user.id, username=data.rsp.user.username.text) return user
def people_findByUsername(username)
Returns User object.
6.194022
5.623944
1.101366
method = 'flickr.people.getPublicPhotos' data = _doget(method, user_id=user_id, per_page=per_page, page=page) photos = [] if hasattr(data.rsp.photos, "photo"): # Check if there are photos at all (may be been paging too far). if isinstance(data.rsp.photos.photo, list): for photo ...
def people_getPublicPhotos(user_id, per_page='', page='')
Returns list of Photo objects.
3.163963
3.219759
0.982671
method = 'flickr.favorites.getList' data = _doget(method, auth=True, user_id=user_id, per_page=per_page,\ page=page) photos = [] if isinstance(data.rsp.photos.photo, list): for photo in data.rsp.photos.photo: photos.append(_parse_photo(photo)) else: ...
def favorites_getList(user_id='', per_page='', page='')
Returns list of Photo objects.
2.730155
2.661506
1.025793
method = 'flickr.favorites.getPublicList' data = _doget(method, auth=False, user_id=user_id, per_page=per_page,\ page=page) photos = [] if isinstance(data.rsp.photos.photo, list): for photo in data.rsp.photos.photo: photos.append(_parse_photo(photo)) else: ...
def favorites_getPublicList(user_id, per_page='', page='')
Returns list of Photo objects.
2.713057
2.706517
1.002417
method = 'flickr.favorites.add' _dopost(method, auth=True, photo_id=photo_id) return True
def favorites_add(photo_id)
Add a photo to the user's favorites.
5.841249
5.684882
1.027506
method = 'flickr.favorites.remove' _dopost(method, auth=True, photo_id=photo_id) return True
def favorites_remove(photo_id)
Remove a photo from the user's favorites.
5.743144
5.543185
1.036073
method = 'flickr.groups.pools.getGroups' data = _doget(method, auth=True) groups = [] if isinstance(data.rsp.groups.group, list): for group in data.rsp.groups.group: groups.append(Group(group.id, name=group.name, \ privacy=group.privacy)) else...
def groups_pools_getGroups()
Get a list of groups the auth'd user can post photos to.
2.859102
2.773504
1.030863
method = 'flickr.tags.getListUser' auth = user_id == '' data = _doget(method, auth=auth, user_id=user_id) if isinstance(data.rsp.tags.tag, list): return [tag.text for tag in data.rsp.tags.tag] else: return [data.rsp.tags.tag.text]
def tags_getListUser(user_id='')
Returns a list of tags for the given user (in string format)
3.32046
3.282787
1.011476
method = 'flickr.tags.getListUserPopular' auth = user_id == '' data = _doget(method, auth=auth, user_id=user_id) result = {} if isinstance(data.rsp.tags.tag, list): for tag in data.rsp.tags.tag: result[tag.text] = tag.count else: result[data.rsp.tags.tag.text] = ...
def tags_getListUserPopular(user_id='', count='')
Gets the popular tags for a user in dictionary form tag=>count
2.809734
2.759977
1.018028
method = 'flickr.tags.getRelated' data = _doget(method, auth=False, tag=tag) if isinstance(data.rsp.tags.tag, list): return [tag.text for tag in data.rsp.tags.tag] else: return [data.rsp.tags.tag.text]
def tags_getrelated(tag)
Gets the related tags for given tag.
3.448409
3.506276
0.983496
method = 'flickr.contacts.getPublicList' data = _doget(method, auth=False, user_id=user_id) if isinstance(data.rsp.contacts.contact, list): return [User(user.nsid, username=user.username) \ for user in data.rsp.contacts.contact] else: user = data.rsp.contacts.contact...
def contacts_getPublicList(user_id)
Gets the contacts (Users) for the user_id
3.430723
3.477112
0.986659
owner = User(photo.owner) title = photo.title ispublic = photo.ispublic isfriend = photo.isfriend isfamily = photo.isfamily secret = photo.secret server = photo.server p = Photo(photo.id, owner=owner, title=title, ispublic=ispublic,\ isfriend=isfriend, isfamily=isfamil...
def _parse_photo(photo)
Create a Photo object from photo data.
2.919888
2.71555
1.075247
self.__loaded = True method = 'flickr.photos.getInfo' data = _doget(method, photo_id=self.id) photo = data.rsp.photo self.__secret = photo.secret self.__server = photo.server self.__isfavorite = photo.isfavorite self.__license =...
def _load_properties(self)
Loads the properties from Flickr.
2.871576
2.738867
1.048454