_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q39900
Ec2Inventory.do_api_calls_update_cache
train
def do_api_calls_update_cache(self): ''' Do API calls to each region, and save data in cache files ''' if self.route53_enabled: self.get_route53_records() for region in self.regions: self.get_instances_by_region(region) if self.rds_enabled: s...
python
{ "resource": "" }
q39901
Ec2Inventory.connect
train
def connect(self, region): ''' create connection to api server''' if self.eucalyptus: conn = boto.connect_euca(host=self.eucalyptus_host) conn.APIVersion = '2010-08-31' else: conn = self.connect_to_aws(ec2, region) return conn
python
{ "resource": "" }
q39902
Ec2Inventory.get_instances_by_region
train
def get_instances_by_region(self, region): ''' Makes an AWS EC2 API call to the list of instances in a particular region ''' try: conn = self.connect(region) reservations = [] if self.ec2_instance_filters: for filter_key, filter_values in self...
python
{ "resource": "" }
q39903
Ec2Inventory.get_rds_instances_by_region
train
def get_rds_instances_by_region(self, region): ''' Makes an AWS API call to the list of RDS instances in a particular region ''' try: conn = self.connect_to_aws(rds, region) if conn: instances = conn.get_all_dbinstances() for instance in i...
python
{ "resource": "" }
q39904
Ec2Inventory.get_elasticache_replication_groups_by_region
train
def get_elasticache_replication_groups_by_region(self, region): ''' Makes an AWS API call to the list of ElastiCache replication groups in a particular region.''' # ElastiCache boto module doesn't provide a get_all_intances method, # that's why we need to call describe directly (it woul...
python
{ "resource": "" }
q39905
Ec2Inventory.get_auth_error_message
train
def get_auth_error_message(self): ''' create an informative error message if there is an issue authenticating''' errors = ["Authentication error retrieving ec2 inventory."] if None in [os.environ.get('AWS_ACCESS_KEY_ID'), os.environ.get('AWS_SECRET_ACCESS_KEY')]: errors.append(' - No...
python
{ "resource": "" }
q39906
Ec2Inventory.fail_with_error
train
def fail_with_error(self, err_msg, err_operation=None): '''log an error to std err for ansible-playbook to consume and exit''' if err_operation: err_msg = 'ERROR: "{err_msg}", while: {err_operation}'.format( err_msg=err_msg, err_operation=err_operation) sys.stderr.wri...
python
{ "resource": "" }
q39907
Ec2Inventory.add_rds_instance
train
def add_rds_instance(self, instance, region): ''' Adds an RDS instance to the inventory and index, as long as it is addressable ''' # Only want available instances unless all_rds_instances is True if not self.all_rds_instances and instance.status != 'available': return ...
python
{ "resource": "" }
q39908
Ec2Inventory.add_elasticache_node
train
def add_elasticache_node(self, node, cluster, region): ''' Adds an ElastiCache node to the inventory and index, as long as it is addressable ''' # Only want available nodes unless all_elasticache_nodes is True if not self.all_elasticache_nodes and node['CacheNodeStatus'] != 'available':...
python
{ "resource": "" }
q39909
Ec2Inventory.add_elasticache_replication_group
train
def add_elasticache_replication_group(self, replication_group, region): ''' Adds an ElastiCache replication group to the inventory and index ''' # Only want available clusters unless all_elasticache_replication_groups is True if not self.all_elasticache_replication_groups and replication_group[...
python
{ "resource": "" }
q39910
Ec2Inventory.get_route53_records
train
def get_route53_records(self): ''' Get and store the map of resource records to domain names that point to them. ''' r53_conn = route53.Route53Connection() all_zones = r53_conn.get_zones() route53_zones = [ zone for zone in all_zones if zone.name[:-1] ...
python
{ "resource": "" }
q39911
Ec2Inventory.get_instance_route53_names
train
def get_instance_route53_names(self, instance): ''' Check if an instance is referenced in the records we have from Route53. If it is, return the list of domain names pointing to said instance. If nothing points to it, return an empty list. ''' instance_attributes = [ 'public_dns_name', ...
python
{ "resource": "" }
q39912
Ec2Inventory.get_host_info_dict_from_describe_dict
train
def get_host_info_dict_from_describe_dict(self, describe_dict): ''' Parses the dictionary returned by the API call into a flat list of parameters. This method should be used only when 'describe' is used directly because Boto doesn't provide specific classes. ''' # I really don't...
python
{ "resource": "" }
q39913
Ec2Inventory.get_host
train
def get_host(self, host): ''' Get variables about a specific host ''' if len(self.index) == 0: # Need to load index from cache self.load_index_from_cache() if not host in self.index: # try updating the cache self.do_api_calls_update_cache() ...
python
{ "resource": "" }
q39914
Ec2Inventory.push
train
def push(self, my_dict, key, element): ''' Push an element onto an array that may not have been defined in the dict ''' group_info = my_dict.setdefault(key, []) if isinstance(group_info, dict): host_list = group_info.setdefault('hosts', []) host_list.append(elemen...
python
{ "resource": "" }
q39915
Ec2Inventory.push_group
train
def push_group(self, my_dict, key, element): ''' Push a group as a child of another group. ''' parent_group = my_dict.setdefault(key, {}) if not isinstance(parent_group, dict): parent_group = my_dict[key] = {'hosts': parent_group} child_groups = parent_group.setdefault('child...
python
{ "resource": "" }
q39916
Ec2Inventory.load_inventory_from_cache
train
def load_inventory_from_cache(self): ''' Reads the inventory from the cache file and returns it as a JSON object ''' cache = open(self.cache_path_cache, 'r') json_inventory = cache.read() self.inventory = json.loads(json_inventory)
python
{ "resource": "" }
q39917
Ec2Inventory.load_index_from_cache
train
def load_index_from_cache(self): ''' Reads the index from the cache file sets self.index ''' cache = open(self.cache_path_index, 'r') json_index = cache.read() self.index = json.loads(json_index)
python
{ "resource": "" }
q39918
Ec2Inventory.write_to_cache
train
def write_to_cache(self, data, filename): ''' Writes data in JSON format to a file ''' json_data = json.dumps(data, sort_keys=True, indent=2) cache = open(filename, 'w') cache.write(json_data) cache.close()
python
{ "resource": "" }
q39919
Ec2Inventory.to_safe
train
def to_safe(self, word): ''' Converts 'bad' characters in a string to underscores so they can be used as Ansible groups ''' regex = "[^A-Za-z0-9\_" if not self.replace_dash_in_groups: regex += "\-" return re.sub(regex + "]", "_", word)
python
{ "resource": "" }
q39920
SentenceMaker.from_keyword_list
train
def from_keyword_list(self, keyword_list, strictness=2, timeout=3): """ Convert a list of keywords to sentence. The result is sometimes None :param list keyword_list: a list of string :param int | None strictness: None for highest strictness. 2 or 1 for a less strict POS matching ...
python
{ "resource": "" }
q39921
VideoDownloader.render_path
train
def render_path(self) -> str: """Render path by filling the path template with video information.""" # TODO: Fix defaults when date is not found (empty string or None) # https://stackoverflow.com/questions/23407295/default-kwarg-values-for-pythons-str-format-method from string import Fo...
python
{ "resource": "" }
q39922
PasswordAuthentication._expand_des_key
train
def _expand_des_key(key): """ Expand the key from a 7-byte password key into a 8-byte DES key """ key = key[:7] + b'\0' * (7 - len(key)) byte = struct.unpack_from('BBBBBBB', key) s = struct.pack('B', ((byte[0] >> 1) & 0x7f) << 1) s += struct.pack("B", ((byte[0] &...
python
{ "resource": "" }
q39923
PasswordAuthentication.get_lmv2_response
train
def get_lmv2_response(domain, username, password, server_challenge, client_challenge): """ Computes an appropriate LMv2 response based on the supplied arguments The algorithm is based on jCIFS. The response is 24 bytes, with the 16 bytes of hash concatenated with the 8 byte client client...
python
{ "resource": "" }
q39924
BaseEngine.xml
train
def xml(self, value): """Set new XML string""" self._xml = value self._root = s2t(value)
python
{ "resource": "" }
q39925
BaseEngine.root
train
def root(self, value): """Set new XML tree""" self._xml = t2s(value) self._root = value
python
{ "resource": "" }
q39926
XslEngine.xsl_elements
train
def xsl_elements(self): """Find all "XSL" styled runs, normalize related paragraph and returns list of XslElements""" def append_xsl_elements(xsl_elements, r, xsl): if r is not None: r.xpath('.//w:t', namespaces=self.namespaces)[0].text = xsl xe = XslElement...
python
{ "resource": "" }
q39927
XslEngine.render_xsl
train
def render_xsl(self, node, context): """Render all XSL elements""" for e in self.xsl_elements: e.render(e.run)
python
{ "resource": "" }
q39928
XslEngine.remove_style
train
def remove_style(self): """Remove all XSL run rStyle elements""" for n in self.root.xpath('.//w:rStyle[@w:val="%s"]' % self.style, namespaces=self.namespaces): n.getparent().remove(n)
python
{ "resource": "" }
q39929
XslEngine.render
train
def render(self, xml, context, raise_on_errors=True): """Render xml string and apply XSLT transfomation with context""" if xml: self.xml = xml # render XSL self.render_xsl(self.root, context) # create root XSL sheet xsl_ns = self.namespaces[...
python
{ "resource": "" }
q39930
handle_image_posts
train
def handle_image_posts(function=None): """ Decorator for views that handles ajax image posts in base64 encoding, saving the image and returning the url """ @wraps(function, assigned=available_attrs(function)) def _wrapped_view(request, *args, **kwargs): if 'image' in request.META['CONTEN...
python
{ "resource": "" }
q39931
verboselogs_class_transform
train
def verboselogs_class_transform(cls): """Make Pylint aware of our custom logger methods.""" if cls.name == 'RootLogger': for meth in ['notice', 'spam', 'success', 'verbose']: cls.locals[meth] = [scoped_nodes.Function(meth, None)]
python
{ "resource": "" }
q39932
verboselogs_module_transform
train
def verboselogs_module_transform(mod): """Make Pylint aware of our custom log levels.""" if mod.name == 'logging': for const in ['NOTICE', 'SPAM', 'SUCCESS', 'VERBOSE']: mod.locals[const] = [nodes.Const(const)]
python
{ "resource": "" }
q39933
cache_etag
train
def cache_etag(request, *argz, **kwz): '''Produce etag value for a cached page. Intended for usage in conditional views (@condition decorator).''' response, site, cachekey = kwz.get('_view_data') or initview(request) if not response: return None return fjcache.str2md5( '{0}--{1}--{2}'.format( site.id if site el...
python
{ "resource": "" }
q39934
cache_last_modified
train
def cache_last_modified(request, *argz, **kwz): '''Last modification date for a cached page. Intended for usage in conditional views (@condition decorator).''' response, site, cachekey = kwz.get('_view_data') or initview(request) if not response: return None return response[1]
python
{ "resource": "" }
q39935
blogroll
train
def blogroll(request, btype): 'View that handles the generation of blogrolls.' response, site, cachekey = initview(request) if response: return response[0] template = loader.get_template('feedjack/{0}.xml'.format(btype)) ctx = dict() fjlib.get_extra_context(site, ctx) ctx = Context(ctx) response = HttpResponse...
python
{ "resource": "" }
q39936
buildfeed
train
def buildfeed(request, feedclass, **criterias): 'View that handles the feeds.' view_data = initview(request) wrap = lambda func: ft.partial(func, _view_data=view_data, **criterias) return condition( etag_func=wrap(cache_etag), last_modified_func=wrap(cache_last_modified) )\ (_buildfeed)(request, feedclass, ...
python
{ "resource": "" }
q39937
mainview
train
def mainview(request, **criterias): 'View that handles all page requests.' view_data = initview(request) wrap = lambda func: ft.partial(func, _view_data=view_data, **criterias) return condition( etag_func=wrap(cache_etag), last_modified_func=wrap(cache_last_modified) )\ (_mainview)(request, view_data, **cri...
python
{ "resource": "" }
q39938
post
train
def post(request): """ Create a Gallery """ defaultname = 'New Gallery %i' % Gallery.objects.all().count() data = request.POST or json.loads(request.body)['body'] title = data.get('title', defaultname) description = data.get('description', '') security = int(data.get('security', Gallery.PUBLIC))...
python
{ "resource": "" }
q39939
put
train
def put(request, obj_id=None): """ Adds Image and Video objects to Gallery based on GUIDs """ data = request.PUT or json.loads(request.body)['body'] guids = data.get('guids', '').split(',') move = data.get('from') security = request.PUT.get('security') gallery = Gallery.objects.get(pk=obj_id) ...
python
{ "resource": "" }
q39940
delete
train
def delete(request, obj_id=None): """ Removes ImageVideo objects from Gallery """ data = request.DELETE or json.loads(request.body) guids = data.get('guids').split(',') objects = getObjectsFromGuids(guids) gallery = Gallery.objects.get(pk=obj_id) LOGGER.info('{} removed {} from {}'.format(reque...
python
{ "resource": "" }
q39941
filterObjects
train
def filterObjects(request, obj_id): """ Filters Gallery for the requested ImageVideo objects. Returns a Result object with serialized objects """ if int(obj_id) == 0: obj = None else: obj = Gallery.objects.get(pk=obj_id) isanonymous = request.user.is_anonymous() if isa...
python
{ "resource": "" }
q39942
_sortObjects
train
def _sortObjects(orderby='created', **kwargs): """Sorts lists of objects and combines them into a single list""" o = [] for m in kwargs.values(): for l in iter(m): o.append(l) o = list(set(o)) sortfunc = _sortByCreated if orderby == 'created' else _sortByModified if six....
python
{ "resource": "" }
q39943
_sortByCreated
train
def _sortByCreated(a, b): """Sort function for object by created date""" if a.created < b.created: return 1 elif a.created > b.created: return -1 else: return 0
python
{ "resource": "" }
q39944
_sortByModified
train
def _sortByModified(a, b): """Sort function for object by modified date""" if a.modified < b.modified: return 1 elif a.modified > b.modified: return -1 else: return 0
python
{ "resource": "" }
q39945
search
train
def search(query, model): """ Performs a search query and returns the object ids """ query = query.strip() LOGGER.debug(query) sqs = SearchQuerySet() results = sqs.raw_search('{}*'.format(query)).models(model) if not results: results = sqs.raw_search('*{}'.format(query)).models(model) ...
python
{ "resource": "" }
q39946
find
train
def find(whatever=None, language=None, iso639_1=None, iso639_2=None, native=None): """Find data row with the language. :param whatever: key to search in any of the following fields :param language: key to search in English language name :param iso639_1: key to search in ISO 639-1 code (2 digit...
python
{ "resource": "" }
q39947
to_iso639_1
train
def to_iso639_1(key): """Find ISO 639-1 code for language specified by key. >>> to_iso639_1("swe") u'sv' >>> to_iso639_1("English") u'en' """ item = find(whatever=key) if not item: raise NonExistentLanguageError('Language does not exist.') return item[u'iso639_1']
python
{ "resource": "" }
q39948
to_iso639_2
train
def to_iso639_2(key, type='B'): """Find ISO 639-2 code for language specified by key. :param type: "B" - bibliographical (default), "T" - terminological >>> to_iso639_2("German") u'ger' >>> to_iso639_2("German", "T") u'deu' """ if type not in ('B', 'T'): raise ValueError('Type ...
python
{ "resource": "" }
q39949
to_name
train
def to_name(key): """Find the English name for the language specified by key. >>> to_name('br') u'Breton' >>> to_name('sw') u'Swahili' """ item = find(whatever=key) if not item: raise NonExistentLanguageError('Language does not exist.') return item[u'name']
python
{ "resource": "" }
q39950
to_native
train
def to_native(key): """Find the native name for the language specified by key. >>> to_native('br') u'brezhoneg' >>> to_native('sw') u'Kiswahili' """ item = find(whatever=key) if not item: raise NonExistentLanguageError('Language does not exist.') return item[u'native']
python
{ "resource": "" }
q39951
address_inline
train
def address_inline(request, prefix="", country_code=None, template_name="postal/form.html"): """ Displays postal address with localized fields """ country_prefix = "country" prefix = request.POST.get('prefix', prefix) if prefix: country_prefix = prefix + '-country' country_cod...
python
{ "resource": "" }
q39952
Benchmark.run_timeit
train
def run_timeit(self, stmt, setup): """ Create the function call statement as a string used for timeit. """ _timer = timeit.Timer(stmt=stmt, setup=setup) trials = _timer.repeat(self.timeit_repeat, self.timeit_number) self.time_average_seconds = sum(trials) / len(trials) / self.timeit_numb...
python
{ "resource": "" }
q39953
_get_mx_exchanges
train
def _get_mx_exchanges(domain): """Fetch the MX records for the specified domain :param str domain: The domain to get the MX records for :rtype: list """ try: answer = resolver.query(domain, 'MX') return [str(record.exchange).lower()[:-1] for record in answer] except (resolver.N...
python
{ "resource": "" }
q39954
_domain_check
train
def _domain_check(domain, domain_list, resolve): """Returns ``True`` if the ``domain`` is serviced by the ``domain_list``. :param str domain: The domain to check :param list domain_list: The domains to check for :param bool resolve: Resolve the domain :rtype: bool """ if domain in domain_l...
python
{ "resource": "" }
q39955
normalize
train
def normalize(email_address, resolve=True): """Return the normalized email address, removing :param str email_address: The normalized email address :param bool resolve: Resolve the domain :rtype: str """ address = utils.parseaddr(email_address) local_part, domain_part = address[1].lower()....
python
{ "resource": "" }
q39956
validate
train
def validate(filename, verbose=False): """ Validate file and return JSON result as dictionary. "filename" can be a file name or an HTTP URL. Return "" if the validator does not return valid JSON. Raise OSError if curl command returns an error status. """ # is_css = filename.endswith(".css")...
python
{ "resource": "" }
q39957
main
train
def main(): """Parser the command line and run the validator.""" parser = argparse.ArgumentParser( description="[v" + __version__ + "] " + __doc__, prog="w3c_validator", ) parser.add_argument( "--log", default="INFO", help=("log level: DEBUG, INFO or INFO " ...
python
{ "resource": "" }
q39958
format_info_response
train
def format_info_response(value): """Format the response from redis :param str value: The return response from redis :rtype: dict """ info = {} for line in value.decode('utf-8').splitlines(): if not line or line[0] == '#': continue if ':' in line: key, va...
python
{ "resource": "" }
q39959
Multicolor.intersect
train
def intersect(self, other): """ Computes the multiset intersection, between the current Multicolor and the supplied Multicolor :param other: another Multicolor object to compute a multiset intersection with :return: :raise TypeError: an intersection can be computed only between two Mult...
python
{ "resource": "" }
q39960
text2wngram
train
def text2wngram(text, output_file, n=3, chars=63636363, words=9090909, compress=False, verbosity=2): """ List of every word n-gram which occurred in the text, along with its number of occurrences. The maximum numbers of charactors and words that can be stored in the buffer are given by the chars and...
python
{ "resource": "" }
q39961
ngram2mgram
train
def ngram2mgram(input_file, output_file, n, m, words=False, ascii_idngram=False): """ Takes either a word n-gram file, or an id n-gram file and outputs a file of the same type where m < n. """ cmd = ['ngram2mgram', '-n', n, '-m', m] if words and ascii_idngram: ...
python
{ "resource": "" }
q39962
wngram2idngram
train
def wngram2idngram(input_file, vocab_file, output_file, buffersize=100, hashtablesize=2000000, files=20, compress=False, verbosity=2, n=3, write_ascii=False, fof_size=10): """ Takes a word N-gram file and a vocabulary file and lists every id n-gram which occurred in the text, along with its number of occurr...
python
{ "resource": "" }
q39963
idngram2stats
train
def idngram2stats(input_file, output_file, n=3, fof_size=50, verbosity=2, ascii_input=False): """ Lists the frequency-of-frequencies for each of the 2-grams, ... , n-grams, which can enable the user to choose appropriate cut-offs, and to specify appropriate memory requirements with the spec_num parameter in...
python
{ "resource": "" }
q39964
binlm2arpa
train
def binlm2arpa(input_file, output_file, verbosity=2): """ Converts a binary format language model, as generated by idngram2lm, into an an ARPA format language model. """ cmd = ['binlm2arpa', '-binary', input_file, '-arpa'. output_file] if verbosity: cmd.exte...
python
{ "resource": "" }
q39965
text2vocab
train
def text2vocab(text, output_file, text2wfreq_kwargs={}, wfreq2vocab_kwargs={}): """ Convienience function that uses text2wfreq and wfreq2vocab to create a vocabulary file from text. """ with tempfile.NamedTemporaryFile(suffix='.wfreq', delete=False) as f: wfreq_file = f.name try: ...
python
{ "resource": "" }
q39966
HyperLogLogMixin.pfadd
train
def pfadd(self, key, *elements): """Adds all the element arguments to the HyperLogLog data structure stored at the variable name specified as first argument. As a side effect of this command the HyperLogLog internals may be updated to reflect a different estimation of the number of uniq...
python
{ "resource": "" }
q39967
HyperLogLogMixin.pfmerge
train
def pfmerge(self, dest_key, *keys): """Merge multiple HyperLogLog values into an unique value that will approximate the cardinality of the union of the observed Sets of the source HyperLogLog structures. The computed merged HyperLogLog is set to the destination variable, which i...
python
{ "resource": "" }
q39968
Emitter.get
train
def get(cls, format): """ Gets an emitter, returns the class and a content-type. """ if cls.EMITTERS.has_key(format): return cls.EMITTERS.get(format) raise ValueError("No emitters found for type %s" % format)
python
{ "resource": "" }
q39969
Emitter.register
train
def register(cls, name, klass, content_type='text/plain'): """ Register an emitter. Parameters:: - `name`: The name of the emitter ('json', 'xml', 'yaml', ...) - `klass`: The emitter class. - `content_type`: The content type to serve response as. """ c...
python
{ "resource": "" }
q39970
Resource.determine_emitter
train
def determine_emitter(self, request, *args, **kwargs): """ Function for determening which emitter to use for output. It lives here so you can easily subclass `Resource` in order to change how emission is detected. You could also check for the `Accept` HTTP header here, s...
python
{ "resource": "" }
q39971
Resource.form_validation_response
train
def form_validation_response(self, e): """ Method to return form validation error information. You will probably want to override this in your own `Resource` subclass. """ resp = rc.BAD_REQUEST resp.write(' '+str(e.form.errors)) return resp
python
{ "resource": "" }
q39972
Resource.cleanup_request
train
def cleanup_request(request): """ Removes `oauth_` keys from various dicts on the request object, and returns the sanitized version. """ for method_type in ('GET', 'PUT', 'POST', 'DELETE'): block = getattr(request, method_type, { }) if True in [ k.startsw...
python
{ "resource": "" }
q39973
Resource.error_handler
train
def error_handler(self, e, request, meth, em_format): """ Override this method to add handling of errors customized for your needs """ if isinstance(e, FormValidationError): return self.form_validation_response(e) elif isinstance(e, TypeError): r...
python
{ "resource": "" }
q39974
parse
train
def parse(path): """ Parses xml and returns a formatted dict. Example: wpparser.parse("./blog.wordpress.2014-09-26.xml") Will return: { "blog": { "tagline": "Tagline", "site_url": "http://marteinn.se/blog", "blog_url": "http://marteinn.se/b...
python
{ "resource": "" }
q39975
_parse_authors
train
def _parse_authors(element): """ Returns a well formatted list of users that can be matched against posts. """ authors = [] items = element.findall("./{%s}author" % WP_NAMESPACE) for item in items: login = item.find("./{%s}author_login" % WP_NAMESPACE).text email = item.find("....
python
{ "resource": "" }
q39976
_parse_categories
train
def _parse_categories(element): """ Returns a list with categories with relations. """ reference = {} items = element.findall("./{%s}category" % WP_NAMESPACE) for item in items: term_id = item.find("./{%s}term_id" % WP_NAMESPACE).text nicename = item.find("./{%s}category_nicenam...
python
{ "resource": "" }
q39977
_build_category_tree
train
def _build_category_tree(slug, reference=None, items=None): """ Builds a recursive tree with category relations as children. """ if items is None: items = [] for key in reference: category = reference[key] if category["parent"] == slug: children = _build_catego...
python
{ "resource": "" }
q39978
_parse_posts
train
def _parse_posts(element): """ Returns a list with posts. """ posts = [] items = element.findall("item") for item in items: title = item.find("./title").text link = item.find("./link").text pub_date = item.find("./pubDate").text creator = item.find("./{%s}creato...
python
{ "resource": "" }
q39979
_parse_postmeta
train
def _parse_postmeta(element): import phpserialize """ Retrive post metadata as a dictionary """ metadata = {} fields = element.findall("./{%s}postmeta" % WP_NAMESPACE) for field in fields: key = field.find("./{%s}meta_key" % WP_NAMESPACE).text value = field.find("./{%s}met...
python
{ "resource": "" }
q39980
_parse_comments
train
def _parse_comments(element): """ Returns a list with comments. """ comments = [] items = element.findall("./{%s}comment" % WP_NAMESPACE) for item in items: comment_id = item.find("./{%s}comment_id" % WP_NAMESPACE).text author = item.find("./{%s}comment_author" % WP_NAMESPACE)....
python
{ "resource": "" }
q39981
Connection.open_umanager
train
def open_umanager(self): """Used to open an uManager session. """ if self.umanager_opened: return self.ser.write(self.cmd_umanager_invocation) # optimistic approach first: assume umanager is not invoked if self.read_loop(lambda x: x.endswith(self.uma...
python
{ "resource": "" }
q39982
Connection.list_current_filter_set
train
def list_current_filter_set(self,raw=False): """User to list a currently selected filter set""" buf = [] self.open_umanager() self.ser.write(''.join((self.cmd_current_filter_list,self.cr))) if self.read_loop(lambda x: x.endswith(self.umanager_prompt),self.timeout,lambda...
python
{ "resource": "" }
q39983
ListsMixin.ltrim
train
def ltrim(self, key, start, stop): """ Crop a list to the specified range. :param key: The list's key :type key: :class:`str`, :class:`bytes` :param int start: zero-based index to first element to retain :param int stop: zero-based index of the last element to retain ...
python
{ "resource": "" }
q39984
ListsMixin.lpushx
train
def lpushx(self, key, *values): """ Insert values at the head of an existing list. :param key: The list's key :type key: :class:`str`, :class:`bytes` :param values: One or more positional arguments to insert at the beginning of the list. Each value is inserted at th...
python
{ "resource": "" }
q39985
ListsMixin.rpushx
train
def rpushx(self, key, *values): """ Insert values at the tail of an existing list. :param key: The list's key :type key: :class:`str`, :class:`bytes` :param values: One or more positional arguments to insert at the tail of the list. :returns: the length of th...
python
{ "resource": "" }
q39986
encode_date_optional_time
train
def encode_date_optional_time(obj): """ ISO encode timezone-aware datetimes """ if isinstance(obj, datetime.datetime): return timezone("UTC").normalize(obj.astimezone(timezone("UTC"))).strftime('%Y-%m-%dT%H:%M:%SZ') raise TypeError("{0} is not JSON serializable".format(repr(obj)))
python
{ "resource": "" }
q39987
Command.file_handler
train
def file_handler(self, handler_type, path, prefixed_path, source_storage): """ Create a dict with all kwargs of the `copy_file` or `link_file` method of the super class and add it to the queue for later processing. """ if self.faster: if prefixed_path not in self.foun...
python
{ "resource": "" }
q39988
Command.delete_file
train
def delete_file(self, path, prefixed_path, source_storage): """ We don't need all the file_exists stuff because we have to override all files anyways. """ if self.faster: return True else: return super(Command, self).delete_file(path, prefixed_path, source...
python
{ "resource": "" }
q39989
Command.collect
train
def collect(self): """ Create some concurrent workers that process the tasks simultaneously. """ collected = super(Command, self).collect() if self.faster: self.worker_spawn_method() self.post_processor() return collected
python
{ "resource": "" }
q39990
_load_github_hooks
train
def _load_github_hooks(github_url='https://api.github.com'): """Request GitHub's IP block from their API. Return the IP network. If we detect a rate-limit error, raise an error message stating when the rate limit will reset. If something else goes wrong, raise a generic 503. """ try: ...
python
{ "resource": "" }
q39991
is_github_ip
train
def is_github_ip(ip_str): """Verify that an IP address is owned by GitHub.""" if isinstance(ip_str, bytes): ip_str = ip_str.decode() ip = ipaddress.ip_address(ip_str) if ip.version == 6 and ip.ipv4_mapped: ip = ip.ipv4_mapped for block in load_github_hooks(): if ip in ipadd...
python
{ "resource": "" }
q39992
check_signature
train
def check_signature(signature, key, data): """Compute the HMAC signature and test against a given hash.""" if isinstance(key, type(u'')): key = key.encode() digest = 'sha1=' + hmac.new(key, data, hashlib.sha1).hexdigest() # Covert everything to byte sequences if isinstance(digest, type(u''...
python
{ "resource": "" }
q39993
Hooks.init_app
train
def init_app(self, app, url='/hooks'): """Register the URL route to the application. :param app: the optional :class:`~flask.Flask` instance to register the extension :param url: the url that events will be posted to """ app.config.setdefault('VALIDATE_IP', True)...
python
{ "resource": "" }
q39994
Hooks.register_hook
train
def register_hook(self, hook_name, fn): """Register a function to be called on a GitHub event.""" if hook_name not in self._hooks: self._hooks[hook_name] = fn else: raise Exception('%s hook already registered' % hook_name)
python
{ "resource": "" }
q39995
Hooks.hook
train
def hook(self, hook_name): """A decorator that's used to register a new hook handler. :param hook_name: the event to handle """ def wrapper(fn): self.register_hook(hook_name, fn) return fn return wrapper
python
{ "resource": "" }
q39996
websocket.send
train
def send(self, *args): """ Send a number of frames. """ for frame in args: self.sock.sendall(self.apply_send_hooks(frame, False).pack())
python
{ "resource": "" }
q39997
websocket.queue_send
train
def queue_send(self, frame, callback=None, recv_callback=None): """ Enqueue `frame` to the send buffer so that it is send on the next `do_async_send`. `callback` is an optional callable to call when the frame has been fully written. `recv_callback` is an optional callable to quic...
python
{ "resource": "" }
q39998
websocket.do_async_send
train
def do_async_send(self): """ Send any queued data. This function should only be called after a write event on a file descriptor. """ assert len(self.sendbuf) nwritten = self.sock.send(self.sendbuf) nframes = 0 for entry in self.sendbuf_frames: ...
python
{ "resource": "" }
q39999
websocket.do_async_recv
train
def do_async_recv(self, bufsize): """ Receive any completed frames from the socket. This function should only be called after a read event on a file descriptor. """ data = self.sock.recv(bufsize) if len(data) == 0: raise socket.error('no data to receive') ...
python
{ "resource": "" }