_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q53300
simple_getter
train
def simple_getter(queryset, object_regex=None, lookup_field=None): ''' Returns simple object_getter function for use with PluggableSite. It takes 'queryset' with QuerySet or Model instance, 'object_regex' with url regex and 'lookup_field' with lookup field. ''' object_regex = object_regex or r'\d+' ...
python
{ "resource": "" }
q53301
PluggableSite.reverse
train
def reverse(self, url, args=None, kwargs=None): ''' Reverse an url taking self.app_name in account ''' return reverse("%s:%s" % (self.instance_name, url,), args=args, kwargs=kwargs, current_app = self.app_name)
python
{ "resource": "" }
q53302
RtsProfile.find_comp_by_target
train
def find_comp_by_target(self, target): '''Finds a component using a TargetComponent or one of its subclasses. @param A @ref TargetComponent object or subclass of @ref TargetComponent. @return A Component object matching the target. @raises MissingComponentError ''' ...
python
{ "resource": "" }
q53303
RtsProfile.optional_data_connections
train
def optional_data_connections(self): '''Finds all data connections in which one or more components are not required. If all the components involved in a connection are required, that connection is also required. If one or more are not required, that connection is optional. ...
python
{ "resource": "" }
q53304
RtsProfile.optional_service_connections
train
def optional_service_connections(self): '''Finds all service connections in which one or more components are not required. If all the components involved in a connection are required, that connection is also required. If one or more are not required, that connection is optional....
python
{ "resource": "" }
q53305
RtsProfile.parse_from_xml
train
def parse_from_xml(self, xml_spec): '''Parse a string or file containing an XML specification. Example: >>> s = RtsProfile() >>> s.parse_from_xml(open('test/rtsystem.xml')) >>> len(s.components) 3 Load of invalid data should throw exception: >>> s.parse_...
python
{ "resource": "" }
q53306
Manhole.help
train
def help(self): '''Prints exposed methods and their docstrings.''' cmds = self.get_exposed_cmds() t = text_helper.Table(fields=['command', 'doc'], lengths=[50, 85]) return t.render((reflect.formatted_function_name(x), x.__doc__, ) for...
python
{ "resource": "" }
q53307
Parser.split
train
def split(self, text): ''' Splits the text with function arguments into the array with first class citizens separated. See the unit tests for clarificatin. ''' # nesting character -> count counters = {"'": False, '(': 0} def reverse(char): def wrappe...
python
{ "resource": "" }
q53308
Parser.get_local
train
def get_local(self, variable_name): ''' Return the value of the local variable. Raises UnknownVariable is the name is not known. ''' if variable_name not in self._locals: raise UnknownVariable('Unknown variable %s' % variable_name) return self._locals[variable...
python
{ "resource": "" }
q53309
join_path
train
def join_path(base, *parts: str): """Creates urls from base path and additional parts.""" _parts = "/".join((_part.strip("/") for _part in parts)) # _parts = '/'.join(parts) if base.endswith("/"): url = base + _parts else: url = base + "/" + _parts return url
python
{ "resource": "" }
q53310
tabs_or_spaces
train
def tabs_or_spaces(physical_line, indent_char): """ Never mix tabs and spaces. The most popular way of indenting Python is with spaces only. The second-most popular way is with tabs only. Code indented with a mixture of tabs and spaces should be converted to using spaces exclusively. When in...
python
{ "resource": "" }
q53311
tabs_obsolete
train
def tabs_obsolete(physical_line): """ For new projects, spaces-only are strongly recommended over tabs. Most editors have features that make this easy to do. """ indent = indent_match(physical_line).group(1) if indent.count('\t'): return indent.index('\t'), "W191 indentation contains ta...
python
{ "resource": "" }
q53312
blank_lines
train
def blank_lines(logical_line, blank_lines, indent_level, line_number, previous_logical): """ Separate top-level function and class definitions with two blank lines. Method definitions inside a class are separated by a single blank line. Extra blank lines may be used (sparingly) to sepa...
python
{ "resource": "" }
q53313
indentation
train
def indentation(logical_line, previous_logical, indent_char, indent_level, previous_indent_level): """ Use 4 spaces per indentation level. For really old code that you don't want to mess up, you can continue to use 8-space tabs. """ if indent_char == ' ' and indent_level % 4: ...
python
{ "resource": "" }
q53314
expand_indent
train
def expand_indent(line): """ Return the amount of indentation. Tabs are expanded to the next multiple of 8. >>> expand_indent(' ') 4 >>> expand_indent('\\t') 8 >>> expand_indent(' \\t') 8 >>> expand_indent(' \\t') 8 >>> expand_indent(' \\t') 16 ...
python
{ "resource": "" }
q53315
find_checks
train
def find_checks(argument_name): """ Find all globally visible functions where the first argument name starts with argument_name. """ checks = [] function_type = type(find_checks) for name, function in globals().iteritems(): if type(function) is function_type: args = inspe...
python
{ "resource": "" }
q53316
input_dir
train
def input_dir(dirname): """ Check all Python source files in this directory and all subdirectories. """ dirname = dirname.rstrip('/') if excluded(dirname): return 0 errors = 0 for root, dirs, files in os.walk(dirname): if options.verbose: message('directory ' + ro...
python
{ "resource": "" }
q53317
excluded
train
def excluded(filename): """ Check if options.exclude contains a pattern that matches filename. """ basename = os.path.basename(filename) for pattern in options.exclude: if fnmatch(basename, pattern): # print basename, 'excluded because it matches', pattern return True
python
{ "resource": "" }
q53318
filename_match
train
def filename_match(filename): """ Check if options.filename contains a pattern that matches filename. If options.filename is unspecified, this always returns True. """ if not options.filename: return True for pattern in options.filename: if fnmatch(filename, pattern): ...
python
{ "resource": "" }
q53319
_download_items
train
def _download_items(db, last_id): """ Download items from the aleph and store them in `db`. Start from `last_id` if specified. Args: db (obj): Dictionary-like object used as DB. last_id (int): Start from this id. """ MAX_RETRY = 20 # how many times to try till decision that thi...
python
{ "resource": "" }
q53320
download_items
train
def download_items(cache_fn, start=None): """ Open the `cache_fn` as database and download all not-yet downloaded items. Args: cache_fn (str): Path to the sqlite database. If not exists, it will be created. start (int, default None): If set, start from this sysno. """ wi...
python
{ "resource": "" }
q53321
_pick_keywords
train
def _pick_keywords(db): """ Go thru downloaded data stored in `db` and filter keywords, which are parsed and then yielded. Shows nice progress bar. Args: db (obj): Opened database connection. Yields: obj: :class:`KeywordInfo` instances for yeach keyword. """ for key, v...
python
{ "resource": "" }
q53322
generate
train
def generate(cache_fn): """ Go thru `cache_fn` and filter keywords. Store them in `keyword_list.json`. Args: cache_fn (str): Path to the file with cache. Returns: list: List of :class:`KeywordInfo` objects. """ if not os.path.exists(cache_fn): print >> sys.stderr, "Can'...
python
{ "resource": "" }
q53323
_add
train
def _add(a, b, relicAdd): """ Adds two elements @a,@b of the same type into @result using @relicAddFunc. """ # Check types, create a result object of the same type, and call the relic # function. assertSameType(a,b) result = type(a)() relicAdd(byref(result), byref(a), byref(b)) retur...
python
{ "resource": "" }
q53324
_scalarMultiply
train
def _scalarMultiply(P, a, n, relicScalarMult): """ Performs scalar multiplication between point P \in G, scalar a \in Z, using the function @relicScalarMult. @n is the order of the group G. """ # Ensure the scalar is a BigInt a = coerceBigInt(a) if not a: return NotImplemented ...
python
{ "resource": "" }
q53325
_hash
train
def _hash(x, elementType, relicHashFunc): """ Hash an array of bytes, @x, using @relicHashFunc and returns the result of @elementType. """ # Combine all inputs into a single bytearray barray = bytearray() map(barray.extend, bytes(x)) # Create an element of the correct type to hold the h...
python
{ "resource": "" }
q53326
serializeG1
train
def serializeG1(x, compress=True): """ Converts G1 element @x into an array of bytes. If @compress is True, the point will be compressed resulting in a much shorter string of bytes. """ assertType(x, G1Element) return _serialize(x, compress, librelic.g1_size_bin_abi, librelic.g1_write_b...
python
{ "resource": "" }
q53327
serializeG2
train
def serializeG2(x, compress=True): """ Converts G2 element @x into an array of bytes. If @compress is True, the point will be compressed resulting in a much shorter string of bytes. """ assertType(x, G2Element) return _serialize(x, compress, librelic.g2_size_bin_abi, librelic.g2_write_b...
python
{ "resource": "" }
q53328
serializeGt
train
def serializeGt(x, compress=True): """ Converts Gt element @x into an array of bytes. If @compress is True, the point will be compressed resulting in a much shorter string of bytes. """ assertType(x, GtElement) return _serialize(x, compress, librelic.gt_size_bin_abi, librelic.gt_write_b...
python
{ "resource": "" }
q53329
G2Element.mul_table
train
def mul_table(self, other): """ Fast multiplication using a the LWNAF precomputation table. """ # Get a BigInt other = coerceBigInt(other) if not other: return NotImplemented other %= orderG2() # Building the precomputation table, if there is ...
python
{ "resource": "" }
q53330
compile_keywords
train
def compile_keywords(keywords): """ Translate `keywords` to full keyword records as they are used in Aleph. Returns tuple with three lists, each of which is later used in different part of the MRC/MARC record. Args: keywords (list): List of keyword strings. Returns: tuple: (md...
python
{ "resource": "" }
q53331
url_to_fn
train
def url_to_fn(url): """ Convert `url` to filename used to download the datasets. ``http://kitakitsune.org/xe`` -> ``kitakitsune.org_xe``. Args: url (str): URL of the resource. Returns: str: Normalized URL. """ url = url.replace("http://", "").replace("https://", "") ur...
python
{ "resource": "" }
q53332
parse_date_range
train
def parse_date_range(date, alt_end_date=None): """ Parse input `date` string in free-text format for four-digit long groups. Args: date (str): Input containing years. Returns: tuple: ``(from, to)`` as four-digit strings. """ NOT_ENDED = "9999" all_years = re.findall(r"\d{4}...
python
{ "resource": "" }
q53333
_to_date_in_588
train
def _to_date_in_588(date_str): """ Convert date in the format ala 03.02.2017 to 3.2.2017. Viz #100 for details. """ try: date_tokens = (int(x) for x in date_str.split(".")) except ValueError: return date_str return ".".join(str(x) for x in date_tokens)
python
{ "resource": "" }
q53334
to_output
train
def to_output(data): """ Convert WA-KAT frontend dataset to three output datasets - `MRC`, `MARC` and `Dublin core`. Conversion is implemented as filling ofthe MRC template, which is then converted to MARC record. Dublin core is converted standalone from the input dataset. """ data = js...
python
{ "resource": "" }
q53335
is_ipv4
train
def is_ipv4(ip: str) -> bool: """ Returns True if the IPv4 address ia valid, otherwise returns False. """ try: socket.inet_aton(ip) except socket.error: return False return True
python
{ "resource": "" }
q53336
main
train
def main(api_key, token): """List out the boards for our client""" trello_client = TrelloClient( api_key=api_key, token=token, ) print('Boards') print('-----') print('Name: Id') for board in trello_client.list_boards(): print('{board.name}: {board.id}'.format(board=bo...
python
{ "resource": "" }
q53337
Cdstar._req
train
def _req(self, path, method='get', json=True, assert_status=200, **kw): """Make a request to the API of an cdstar instance. :param path: HTTP path. :param method: HTTP method. :param json: Flag signalling whether the response should be treated as JSON. :param assert_status: Expe...
python
{ "resource": "" }
q53338
Cdstar.search
train
def search(self, query, limit=15, offset=0, index=None): """ Query the search service. :param query: The query. :param limit: The maximal number of results to return (at most 500). :param offset: Use to page through big search result sets. :param index: Name of the index...
python
{ "resource": "" }
q53339
_copy_update
train
def _copy_update(sourcepath, destname): """Copy source to dest only if source is newer.""" if sys.platform.startswith('linux'): return os.system("/bin/cp -ua '%s' '%s'" % (sourcepath, destname)) else: return os.system("rsync -ua '%s' '%s'" % (sourcepath, destname))
python
{ "resource": "" }
q53340
_move_update
train
def _move_update(sourcepath, destname): """Move source to dest only if source is newer.""" if sys.platform.startswith('linux'): return os.system("/bin/mv -fu '%s' '%s'" % (sourcepath, destname)) else: return os.system("rsync -ua --remove-source-files '%s' '%s'" % (sourcepath, destname))
python
{ "resource": "" }
q53341
DataProduct.remove_file
train
def remove_file(self): """Removes archived file associated with this DP""" if not self.fullpath or not self.archived: raise RuntimeError("""Can't remove a non-archived data product""") try: os.remove(self.fullpath) except: print("Error removing %s: %s"...
python
{ "resource": "" }
q53342
DataProduct.remove_subproducts
train
def remove_subproducts(self): """Removes all archived files subproducts associated with this DP""" if not self.fullpath or not self.archived: raise RuntimeError("""Can't remove a non-archived data product""") for root, dirs, files in os.walk(self.subproduct_dir(), topdown=False): ...
python
{ "resource": "" }
q53343
LogEntry.load
train
def load(self, pathname): """Loads entry from directory.""" match = self._entry_re.match(pathname) if not match: return None self.ignore = (match.group(1) == "ignore") if not os.path.isdir(pathname): raise ValueError("%s: not a directory" % pathname) ...
python
{ "resource": "" }
q53344
LogEntry.generateIndex
train
def generateIndex(self, refresh=0, refresh_index=0): """Writes the index file""" open(self.index_file, "wt").write(self.renderIndex(refresh=refresh, refresh_index=refresh_index))
python
{ "resource": "" }
q53345
juggle_types
train
def juggle_types(data): """Force all digits in a list to become integers.""" # Data is a list of lists (2D) and not a single column table (1D) if isinstance(data[0], list): return [[force_int(col) for col in row] for row in data] # Data is 1D elif isinstance(data, list): return [for...
python
{ "resource": "" }
q53346
resolve_path
train
def resolve_path(file_path, calling_function): """ Conditionally set a path to a CSV file. Option 1 - Join working directory and calling function name (file_name) Option 2 - Join working directory and provided file_path string Option 3 - Return provided file_path :param file_path: None, filena...
python
{ "resource": "" }
q53347
get_calling_file
train
def get_calling_file(file_path=None, result='name'): """ Retrieve file_name or file_path of calling Python script """ # Get full path of calling python script if file_path is None: path = inspect.stack()[1][1] else: path = file_path name = path.split('/')[-1].split('.')[0] ...
python
{ "resource": "" }
q53348
CSV.write
train
def write(self, data, method='w'): """ Export data to CSV file. :param data: Either a list of tuples or a list of lists. :param method: File opening method. """ # Create list of lists from flat list data = data if isinstance(data[0], (list, set, tuple)) else [[d]...
python
{ "resource": "" }
q53349
CSV.append
train
def append(self, data): """Append rows to an existing CSV file.""" # CSV file exists, append rows if os.path.exists(self.file_path): return self.write(data, method='a') # CSV file does NOT exist, create new file and write rows else: return self.write(data,...
python
{ "resource": "" }
q53350
CSV.read
train
def read(self): """Reads CSV file and returns list of contents""" # Validate file path assert os.path.isfile(self.file_path), 'No such file exists: ' + str(self.file_path) # Open CSV file and read contents with open(self.file_path, 'r') as f: reader = csv_builtin.rea...
python
{ "resource": "" }
q53351
topological_sort
train
def topological_sort(dependency_pairs): "Sort values subject to dependency constraints" num_heads = defaultdict(int) # num arrows pointing in tails = defaultdict(list) # list of arrows going out heads = [] # unique list of heads in order first seen for h, t in dependency_pairs: num_heads[...
python
{ "resource": "" }
q53352
dmp_to_mdiff
train
def dmp_to_mdiff(diffs): """Convert from diff_match_patch format to _mdiff format. This is sadly necessary to use the HtmlDiff module. """ def yield_buffer(lineno_left, lineno_right): while left_buffer or right_buffer: if left_buffer: left = lineno_left, '\0-{0}\1'....
python
{ "resource": "" }
q53353
Diff._make_diff
train
def _make_diff(self, correct, given): """Return the intermediate representation of the diff.""" dmp = DMP() dmp.Diff_Timeout = 4 text1, text2, array = dmp.diff_linesToChars(correct, given) diffs = dmp.diff_main(text1, text2) dmp.diff_cleanupSemantic(diffs) dmp.dif...
python
{ "resource": "" }
q53354
next_splitter_or_func
train
def next_splitter_or_func(string, splitters, func, pseudo_type): """ Helper for doing the next splitter check. If the list is not empty, call the next splitter decorator appropriately, otherwise call the decorated function. """ if splitters: return splitters[0](string, splitters[1:]...
python
{ "resource": "" }
q53355
PrintfValidator.precondition
train
def precondition(self): """Check if the number of plurals in the two languages is the same.""" return self.tlang.nplurals == self.slang.nplurals and \ super(PrintfValidator, self).precondition()
python
{ "resource": "" }
q53356
convert_path
train
def convert_path(path): """ Convert path to a normalized format """ if os.path.isabs(path): raise Exception("Cannot include file with absolute path {}. Please use relative path instead".format((path))) path = os.path.normpath(path) return path
python
{ "resource": "" }
q53357
is_job_config
train
def is_job_config(config): """ Check whether given dict of config is job config """ try: # Every job has name if config['config']['job']['name'] is not None: return True except KeyError: return False except TypeError: return False except IndexError...
python
{ "resource": "" }
q53358
sessionize
train
def sessionize(user_events, cutoff=defaults.CUTOFF): """ Clusters user sessions from a sequence of user events. Note that, `event` data will simply be returned in the case of a revert. This function serves as a convenience wrapper around calls to :class:`~mw.lib.sessions.Cache`'s :meth:`~mw.lib.se...
python
{ "resource": "" }
q53359
STIX_Import.reference_handler
train
def reference_handler(self, iobject, fact, attr_info, add_fact_kargs): """ Handler for facts that contain a reference to a fact. As shown below in the handler list, this handler is called when a attribute with key '@idref' on the fact's node is detected -- this attribute signifi...
python
{ "resource": "" }
q53360
STIX_Import.cybox_valueset_fact_handler
train
def cybox_valueset_fact_handler(self, enrichment, fact, attr_info, add_fact_kargs): """ Handler for dealing with 'value_set' values. Unfortunately, CybOX et al. sometimes use comma-separated value lists rather than an XML structure that can contain several values. This ...
python
{ "resource": "" }
q53361
STIX_Import.cybox_csv_handler
train
def cybox_csv_handler(self, enrichment, fact, attr_info, add_fact_kargs): """ Handler for dealing with comma-separated values. Unfortunately, CybOX et al. sometimes use comma-separated value lists. Or rather, since Cybox 2.0.1, '##comma##'-separated lists. At least now we can ...
python
{ "resource": "" }
q53362
STIX_Import.split_qname
train
def split_qname(self, cybox_id): """ Separate the namespace from the identifier in a qualified name and lookup the namespace URI associated with the given namespace. """ if ':' in cybox_id: (namespace, uid) = cybox_id.split(':', 1) else: namespace ...
python
{ "resource": "" }
q53363
STIX_Import.derive_iobject_type
train
def derive_iobject_type(self, embedding_ns, embedded_ns, elt_name): """ Derive type of information object stemming from an embedded element based on namespace information of embedding element, the embedded element itself, and the name of the element. """ # Extract name...
python
{ "resource": "" }
q53364
STIX_Import.iobject_import
train
def iobject_import(self, id_and_rev_info, elt_name, obj_dict, markings=None, cybox_id=None): """ Derives InfoObjectType and import InfoObjectType """ iobject_type_ns = Non...
python
{ "resource": "" }
q53365
parse_radl
train
def parse_radl(data): """ Parse a RADL document. Args: - data(str): filepath to a RADL content or a string with content. Return: RADL object. """ if data is None: return None elif os.path.isfile(data): f = open(data) data = "".join(f.readlines()) f.clos...
python
{ "resource": "" }
q53366
_convert_to_wakat_format
train
def _convert_to_wakat_format(seeder_struct): """ Convert Seeder's structure to the internal structure used at frontend. Args:, seeder_struct (dict): Dictionary with Seeder data. Returns: obj: :class:`Model`. """ def pick_active(seeder_struct, what): """ From the...
python
{ "resource": "" }
q53367
_send_request
train
def _send_request(url_id, data=None, json=None, req_type=None): """ Send request to Seeder's API. Args: url_id (str): ID used as identification in Seeder. data (obj, default None): Optional parameter for data. json (obj, default None): Optional parameter for JSON body. req_t...
python
{ "resource": "" }
q53368
get_remote_info
train
def get_remote_info(url_id): """ Download data and convert them to dict used in frontend. Args: url_id (str): ID used as identification in Seeder. Returns: dict: Dict with data for frontend or None in case of error. """ try: data = _send_request(url_id) except Excep...
python
{ "resource": "" }
q53369
_convert_to_seeder_format
train
def _convert_to_seeder_format(dataset): """ WA KAT dataset has different structure from Seeder. This is convertor which converts WA-KAT -> Seeder data format. Args: dataset (dict): WA-KAT dataset sent from frontend. Returns: dict: Dict with converted data. """ data = {} ...
python
{ "resource": "" }
q53370
send_update
train
def send_update(url_id, dataset): """ Send request to Seeder's API with data changed by user. Args: url_id (str): ID used as identification in Seeder. dataset (dict): WA-KAT dataset sent from frontend. """ data = _convert_to_seeder_format(dataset) if not data: return ...
python
{ "resource": "" }
q53371
RatelimitedIterator._delay
train
def _delay(self): """Delay for between zero and self.interval time units""" if not self.next_scheduled: self.next_scheduled = self.clock_func() + self.interval return while True: current = self.clock_func() if current >= self.next_scheduled: ...
python
{ "resource": "" }
q53372
get_text_length
train
def get_text_length(*args): r"""Measure the size of string rendered with a TTF no-nomospaced fonts. :param \*args: List of strings to be measured. :returns: The length of the strings. """ txt = Image.new('RGBA', (16, 16), (255, 255, 255, 0)) d = ImageDraw.Draw(txt) font = ImageFont.truetype...
python
{ "resource": "" }
q53373
generate_badge_png
train
def generate_badge_png(title, value, color='#007ec6'): """Generate the badge in PNG format.""" badge = generate_badge_svg(title, value, color) return cairosvg.svg2png(badge)
python
{ "resource": "" }
q53374
badges_processor
train
def badges_processor(): """Context processor for badges.""" def badge_svg(title, value, color='#007ec6'): """Context processor function to generate SVG badges.""" return generate_badge_svg(title, value, color) def badge_png(title, value, color='#007ec6'): """Context processor functi...
python
{ "resource": "" }
q53375
change_same_starting_points
train
def change_same_starting_points(flaglist): """Gets points at which changes begin""" change_points = [] same_points = [] in_change = False if flaglist and not flaglist[0]: same_points.append(0) for x, flag in enumerate(flaglist): if flag and not in_change: change_po...
python
{ "resource": "" }
q53376
HTMLDiff.make_table
train
def make_table(self, renderable): """Makes unique anchor prefixes so that multiple tables may exist on the same page without conflict.""" self._make_prefix() diffs = renderable.diff._diff # set up iterator to wrap lines that exceed desired width if self._wrapcolumn: ...
python
{ "resource": "" }
q53377
HTMLDiff._convert_flags
train
def _convert_flags(self, fromlist, tolist, flaglist, context, numlines): """Handles making inline links in the document.""" # all anchor names will be generated using the unique "to" prefix toprefix = self._prefix[1] sameprefix = self._prefix[2] # process change flags, generati...
python
{ "resource": "" }
q53378
Database.save_doc
train
def save_doc(self, doc, doc_id=None, following_attachments=None): '''Imitate sending HTTP request to CouchDB server''' self.log("save_document called for doc: %r", doc) d = defer.Deferred() try: if not isinstance(doc, (str, unicode, )): raise ValueError('Do...
python
{ "resource": "" }
q53379
Database.open_doc
train
def open_doc(self, doc_id): '''Imitated fetching the document from the database. Doesnt implement options from paisley to get the old revision or get the list of revision. ''' d = defer.Deferred() self.increase_stat('open_doc') try: doc = self._get_doc...
python
{ "resource": "" }
q53380
Database.delete_doc
train
def delete_doc(self, doc_id, revision): '''Imitates sending DELETE request to CouchDB server''' d = defer.Deferred() self.increase_stat('delete_doc') try: doc = self._get_doc(doc_id) if doc['_rev'] != revision: raise ConflictError("Document updat...
python
{ "resource": "" }
q53381
Database.load_fixture
train
def load_fixture(self, body, attachment_bodies={}): ''' Loads the document into the database from json string. Fakes the attachments if necessary.''' doc = json.loads(body) self._documents[doc['_id']] = doc self._attachments[doc['_id']] = dict() for name in doc.ge...
python
{ "resource": "" }
q53382
Database._flatten
train
def _flatten(self, iterator, **filter_options): ''' iterator here gives as lists of tuples. Method flattens the structure to a single list of tuples. ''' resp = list() for entry in iterator: for tup in entry: if self._matches_filter(tup, **filt...
python
{ "resource": "" }
q53383
indent_string
train
def indent_string(string, num_spaces=2): '''Add indentation to a string. Replaces all new lines in the string with a new line followed by the specified number of spaces, and adds the specified number of spaces to the start of the string. ''' indent = ' '.ljust(num_spaces) return indent + r...
python
{ "resource": "" }
q53384
validate_attribute
train
def validate_attribute(attr, name, expected_type=None, required=False): '''Validates that an attribute meets expectations. This function will check if the given attribute value matches a necessary type and/or is not None, an empty string, an empty list, etc. It will raise suitable exceptions on validat...
python
{ "resource": "" }
q53385
main
train
def main(): """ Main function of this example. """ parser = argparse.ArgumentParser() parser.add_argument( '--digest', default="md5", help="Digest to use", choices=sorted( getattr(hashlib, 'algorithms', None) or hashlib.algorithms_available)) parser.add_argument( ...
python
{ "resource": "" }
q53386
written_hash_proxy.write
train
def write(self, data): """ Intercepted method for writing data. :param data: Data to write :returns: Whatever the original method returns :raises: Whatever the original method raises This method updates the internal digest object with...
python
{ "resource": "" }
q53387
author_tokenize
train
def author_tokenize(name): """This is how the name should be tokenized for the matcher.""" phrases = scan_author_string_for_phrases(name) res = {'lastnames': [], 'nonlastnames': []} for key, tokens in phrases.items(): lst = res.get(key) if lst is None: continue for to...
python
{ "resource": "" }
q53388
AnalysisSystemInstance.get_scheduled_analyses
train
def get_scheduled_analyses(self): """ Retrieve all scheduled analyses for this instance. :return: A list of :class:`.ScheduledAnalysis` objects. """ url = '{}scheduled_analyses/'.format(self.url) return ScheduledAnalysis._get_list_from_url(url, append_base_url=False)
python
{ "resource": "" }
q53389
main
train
def main(argv): """ This parses a json manifest file containing list of webidl files and generates a file containing javascript arrays of json objects for each webidl file. usage: process_idl.py manifest.json ~/B2G The generated js file can then be included with the test app. """ argp...
python
{ "resource": "" }
q53390
find_template_source
train
def find_template_source(name): """ Load the source code and origin of the first template that matches the given name. """ for loader_path in settings.TEMPLATE_LOADERS: template_loader = loader.find_template_loader(loader_path) try: source, origin = template_loader.load_t...
python
{ "resource": "" }
q53391
find_parents
train
def find_parents(name, parents=None): """ Recursively find all of this template's parents and return them as a list. """ template = loader.get_template(name) source, origin = find_template_source(name) if parents is None: parents = [] else: parents.append({'name': name, 'file...
python
{ "resource": "" }
q53392
pipe
train
def pipe(p1, p2): """Joins two pipes""" if isinstance(p1, Pipeable) or isinstance(p2, Pipeable): return p1 | p2 return Pipe([p1, p2])
python
{ "resource": "" }
q53393
transform_field
train
def transform_field(instance, source_field_name, destination_field_name, transformation): ''' Does an image transformation on a instance. It will get the image from the source field attribute of the instnace, then call the transformation function with that instance, and finally save that transformed...
python
{ "resource": "" }
q53394
read_mutiple_items
train
def read_mutiple_items(f, container_type, item_type, separator=" "): """ Extract an iterable from the current line of a file-like object. Args: f (file): the file-like object to read from container_type (type): type of the iterable that will be returned item_type (type): type of the va...
python
{ "resource": "" }
q53395
install
train
def install(trg_queue, is_down=False, is_triggered=False, user=None, group=None, mode=None, item_user=None, item_group=None, item_mode=None, hosts=None, is_host_triggered=False): '''Atomically install a queue''' mode, user, group, item_user, item_group, item_mode =\ _def_mode(mod...
python
{ "resource": "" }
q53396
uninstall
train
def uninstall(trg_queue, item_user=None, item_group=None, item_mode=None): '''Idempotently uninstall a queue, should you want to subvert FSQ_ROOT settings, merely pass in an abolute path''' # immediately down the queue try: down(trg_queue, user=item_user, group=item_group, mode=(...
python
{ "resource": "" }
q53397
uninstall_host
train
def uninstall_host(trg_queue, *hosts, **kwargs): '''Idempotently uninstall a host queue, should you want to subvert FSQ_ROOT settings, merely pass in an abolute path''' # immediately down the queue item_user = kwargs.pop('item_user', None) item_group = kwargs.pop('item_group', None) item_mode...
python
{ "resource": "" }
q53398
install_host
train
def install_host(trg_queue, *hosts, **kwargs): ''' Atomically install host queues ''' user = kwargs.pop('user', None) group = kwargs.pop('group', None) mode = kwargs.pop('mode', None) item_user = kwargs.pop('item_user', None) item_group = kwargs.pop('item_group', None) item_mode = kwargs.pop...
python
{ "resource": "" }
q53399
to_string
train
def to_string(comp_type): '''Returns the correct string for a given composite type. @raises InvalidCompositeTypeError ''' if comp_type == NONE: return NONE elif comp_type== PERIODIC_EC_SHARED: return PERIODC_EC_SHARED elif comp_type == PERIODIC_STATE_SHARED: return PERI...
python
{ "resource": "" }