_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q53100
Pipe.comment
train
def comment(self, comment, show=False, endline=True, newpar=False): """writes a comment tag to the Purr pipe""" if not endline: comment += "<NOBR>" if newpar: comment += "<BR>" self._write("comment:%d:%s\n" % (int(show), comment)) return self
python
{ "resource": "" }
q53101
Pipe.pounce
train
def pounce(self, file, show=False): """writes a pounce command to the Purr pipe""" file = os.path.abspath(os.path.normpath(os.path.realpath(file))) self._write("pounce:%d:%s\n" % (int(show), file)) return self
python
{ "resource": "" }
q53102
echo_with_markers
train
def echo_with_markers(text, marker='=', marker_color='blue', text_color=None): """Print a text to the screen with markers surrounding it. The output looks like: ======== text ======== with marker='=' right now. In the event that the terminal window is too small, the text is printed without mar...
python
{ "resource": "" }
q53103
echo_heading
train
def echo_heading(text, marker='=', marker_color='blue'): """Print a text formatted to look like a heading. The output looks like: ===> text with marker='=' right now. :param str text: the text to echo :param str marker: the marker to mark the heading :param str marker_color: one of ('black...
python
{ "resource": "" }
q53104
cyclic_deps
train
def cyclic_deps(options, **kwargs): """ Analysis function Check whether there are any cyclic dependencies in a call graph Cyclic dependencies in include graph are prevented at a parsing stage with FileIndex """ call_graph = options['call_graph'] call_result = _CallResult(cyclic_test(call_gr...
python
{ "resource": "" }
q53105
get_staff_updater
train
def get_staff_updater(cls): """ This returns a function for passing to a signal. """ from django.core.exceptions import ImproperlyConfigured if not issubclass(cls, BaseStaffMember): raise ImproperlyConfigured("%s is not a sublass of StaffMember" % cls) def update_staff_member(sender, in...
python
{ "resource": "" }
q53106
StaffMemberManager.active
train
def active(self): """ Return only the current staff members """ qset = super(StaffMemberManager, self).get_queryset() return qset.filter(is_active=True)
python
{ "resource": "" }
q53107
StaffMemberManager.inactive
train
def inactive(self): """ Return inactive staff members """ qset = super(StaffMemberManager, self).get_queryset() return qset.filter(is_active=False)
python
{ "resource": "" }
q53108
BaseStaffMember.save
train
def save(self, force_insert=False, force_update=False, *args, **kwargs): """ Makes sure we are in sync with the User field """ self.first_name = self.user.first_name self.last_name = self.user.last_name self.email = self.user.email full_name = '%s %s' % (self.firs...
python
{ "resource": "" }
q53109
get_report
train
def get_report(report=None): """Returns details of a specific report """ if not report: report = list_reports()[-1:][0] report_path = _get_reports_path(report) report_dict = {"report": report} for filename in os.listdir(report_path): with open(os.path.join(report_path, filename),...
python
{ "resource": "" }
q53110
Channel._cleanup_processing_chain
train
def _cleanup_processing_chain(self): """Called on reconnection. Removes all the entries which are don't have the remember_between_connections flag set""" self.log("Removing stale processing chain entries.") self._processing_chain = [x for x in self._processing_chain ...
python
{ "resource": "" }
q53111
FileIndex.load_files
train
def load_files(self, path): """ Loads files in a given path and all its subdirectories """ if self.verbose == 2: print("Indexing {}".format(path)) for filename in os.listdir(path): file_path = path + "/" + filename if os.path.isdir(file_pat...
python
{ "resource": "" }
q53112
FileIndex.add_file
train
def add_file(self, path, yaml): """ Adds given file to the file index """ if is_job_config(yaml): name = self.get_job_name(yaml) file_data = FileData(path=path, yaml=yaml) self.files[path] = file_data self.jobs[name] = file_data e...
python
{ "resource": "" }
q53113
FileIndex.inject_include_info
train
def inject_include_info(self, path, config, include_type): """ Wrap a dictionary into dict that contains config itself and include info """ if isinstance(config, list): config = config[0] ret = OrderedDict() ret[include_flag] = IncludeInfo(type=inclu...
python
{ "resource": "" }
q53114
FileIndex.include_constructor
train
def include_constructor(self, loader, node): """ Called when PyYaml encounters '!include' """ v = self._unfold_yaml(node.value) return v
python
{ "resource": "" }
q53115
FileIndex.include_raw_constructor
train
def include_raw_constructor(self, loader, node): """ Called when PyYaml encounters '!include-raw' """ path = convert_path(node.value) with open(path, 'r') as f: config = f.read() config = self.inject_include_info(path, config, include_type='include-raw'...
python
{ "resource": "" }
q53116
number
train
def number(digit): """ Gets a spoken-word representation for a number. Arguments: digit (int): An integer to convert into spoken-word. Returns: A spoken-word representation for a digit, including an article ('a' or 'an') and a suffix, e.g. 1 -> 'a 1st', 11 -> "an 11th". Adittionally delimits characters ...
python
{ "resource": "" }
q53117
ImageRenderer.canRender
train
def canRender(filename): """Check extensions.""" name, ext = os.path.splitext(filename) ext = ext.lstrip('.').lower() if ext in ImageRenderer._extensions: return 100 else: return False
python
{ "resource": "" }
q53118
ins2dict
train
def ins2dict(ins, kind=''): """Turn a SQLAlchemy Model instance to dict. :param ins: a SQLAlchemy instance. :param kind: specify which kind of dict tranformer should be called. :return: dict, instance data. If model has defined `to_xxx_dict`, then ins2dict(ins, 'xxx') will call `model.to_xxx_d...
python
{ "resource": "" }
q53119
get_instance
train
def get_instance(model, instance_id): """Get an instance by id. :param model: a string, model name in rio.models :param id: an integer, instance id. :return: None or a SQLAlchemy Model instance. """ try: model = get_model(model) except ImportError: return None return mo...
python
{ "resource": "" }
q53120
get_data_or_404
train
def get_data_or_404(model, instance_id, kind=''): """Wrap `get_data`, when missing data, raise BadRequest. """ data = get_data(model, instance_id, kind) if not data: return abort(404) return data
python
{ "resource": "" }
q53121
get_data
train
def get_data(model, instance_id, kind=''): """Get instance data by id. :param model: a string, model name in rio.models :param id: an integer, instance id. :param kind: a string specified which kind of dict tranformer should be called. :return: data. """ instance = get_instance(model, insta...
python
{ "resource": "" }
q53122
get_instance_by_slug
train
def get_instance_by_slug(model, slug, **kwargs): """Get an instance by slug. :param model: a string, model name in rio.models :param slug: a string used to query by `slug`. This requires there is a slug field in model definition. :return: None or a SQLAlchemy Model instance. """ ...
python
{ "resource": "" }
q53123
get_data_by_slug
train
def get_data_by_slug(model, slug, kind='', **kwargs): """Get instance data by slug and kind. Raise 404 Not Found if there is no data. This function requires model has a `slug` column. :param model: a string, model name in rio.models :param slug: a string used to query by `slug`. This requires there is...
python
{ "resource": "" }
q53124
get_data_by_slug_or_404
train
def get_data_by_slug_or_404(model, slug, kind='', **kwargs): """Wrap get_data_by_slug, abort 404 if missing data.""" data = get_data_by_slug(model, slug, kind, **kwargs) if not data: abort(404) return data
python
{ "resource": "" }
q53125
get_instance_by_bin_uuid
train
def get_instance_by_bin_uuid(model, bin_uuid): """Get an instance by binary uuid. :param model: a string, model name in rio.models. :param bin_uuid: a 16-bytes binary string. :return: None or a SQLAlchemy instance. """ try: model = get_model(model) except ImportError: return...
python
{ "resource": "" }
q53126
get_data_by_hex_uuid_or_404
train
def get_data_by_hex_uuid_or_404(model, hex_uuid, kind=''): """Get instance data by uuid and kind. Raise 404 Not Found if there is no data. This requires model has a `bin_uuid` column. :param model: a string, model name in rio.models :param hex_uuid: a hex uuid string in 24-bytes human-readable represe...
python
{ "resource": "" }
q53127
add_instance
train
def add_instance(model, _commit=True, **kwargs): """Add instance to database. :param model: a string, model name in rio.models :param _commit: control whether commit data to database or not. Default True. :param \*\*kwargs: persisted data. :return: instance id. """ try: model = get_...
python
{ "resource": "" }
q53128
delete_instance
train
def delete_instance(model, instance_id, _commit=True): """Delete instance. :param model: a string, model name in rio.models. :param instance_id: integer, instance id. :param _commit: control whether commit data to database or not. Default True. """ try: model = get_model(model) exce...
python
{ "resource": "" }
q53129
make_schema
train
def make_schema(fields, datefields=()): '''Create a whoosh.fields.Schema object from a list of field names. All fields will be set as TEXT fields. If datefields is supplied, additionally create DATETIME fields with those names ''' text_field = whoosh.fields.TEXT(analyzer=whoosh.analysis.SimpleA...
python
{ "resource": "" }
q53130
MinusPlugin.do_minus
train
def do_minus(self, parser, group): '''This filter sorts nodes in a flat group into "required", "default", and "banned" subgroups based on the presence of plus and minus nodes. ''' grouper = group.__class__() next_not = None for node in group: if isins...
python
{ "resource": "" }
q53131
validate_key
train
def validate_key(request, group=None, perm=None, keytype=None): """ Validate the given key """ def update_last_access(): if KEY_LAST_USED_UPDATE: request.key.save() if request.user.is_authenticated() and is_valid_consumer(request): if not group and not perm and not k...
python
{ "resource": "" }
q53132
HL7Parser.parse
train
def parse(self, msg): """ Parse an HL7 message and return an HL7 dictionary. :param msg: HL7 message to parse :return: An HL7 dictionary """ #init dictValues = HL7Dict(self.tersersep) msg_ = msg.strip('\r\n ') # extracts separator defined in the message ...
python
{ "resource": "" }
q53133
long2str
train
def long2str(l): """Convert an integer to a string.""" if type(l) not in (types.IntType, types.LongType): raise ValueError('the input must be an integer') if l < 0: raise ValueError('the input must be greater than 0') s = '' while l: s = s + chr(l & 255) l >>= 8 ...
python
{ "resource": "" }
q53134
str2long
train
def str2long(s): """Convert a string to a long integer.""" if type(s) not in (types.StringType, types.UnicodeType): raise ValueError('the input must be a string') l = 0 for i in s: l <<= 8 l |= ord(i) return l
python
{ "resource": "" }
q53135
is_android
train
def is_android(filename): """Return the type of the file @param filename : the filename @rtype : "APK", "DEX", None """ if not filename: return None with open(filename, "rb") as fd: f_bytes = fd.read() return is_android_raw(f_bytes) return None
python
{ "resource": "" }
q53136
interpolate_tuple
train
def interpolate_tuple(startcolor, goalcolor, steps): """ Take two RGB color sets and mix them over a specified number of steps. Return the list """ # white R = startcolor[0] G = startcolor[1] B = startcolor[2] targetR = goalcolor[0] targetG = goalcolor[1] targetB = goalcolor[2...
python
{ "resource": "" }
q53137
draw_img_button
train
def draw_img_button(width=200, height=50, text='This is a button', color=rgb(200,100,50)): """ Draws a simple image button. """ surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) ctx = cairo.Context(surface) ctx.rectangle(0, 0, width - 1, height - 1) ctx.set_source_rgb(color.red/...
python
{ "resource": "" }
q53138
draw_css_button
train
def draw_css_button(width=200, height=50, text='This is a button', color=rgb(200,100,50)): """ Draws a simple CSS button. """ # TODO: once we've decided on a scss compiler, import it at the top instead from scss import Scss # TODO: make this customizable css_class = 'button' html = '<a cl...
python
{ "resource": "" }
q53139
Worker.make_project
train
def make_project(self, executable, target): """Build the project and verify the executable exists.""" command = 'make -f ../Makefile -C {0} {1}'.format(SRC_PATH, target) pipe = Popen(command, shell=True, stdout=PIPE, stderr=STDOUT, env=CHILD_ENV) output = pipe.commun...
python
{ "resource": "" }
q53140
VersionFinder._git_repo_path
train
def _git_repo_path(self): """ Attempt to determine whether this package is installed via git or not; if so, return the path to the git repository. :rtype: str :returns: path to git repo, or None """ logger.debug('Checking for git directory in: %s', self._package_...
python
{ "resource": "" }
q53141
VersionFinder._find_pkg_info
train
def _find_pkg_info(self): """ Find information about the installed package from pkg_resources. :returns: information from pkg_resources about ``self.package_name`` :rtype: dict """ dist = pkg_resources.require(self.package_name)[0] self._pkg_resources_locations =...
python
{ "resource": "" }
q53142
VersionFinder._dist_version_url
train
def _dist_version_url(self, dist): """ Get version and homepage for a pkg_resources.Distribution :param dist: the pkg_resources.Distribution to get information for :returns: 2-tuple of (version, homepage URL) :rtype: tuple """ ver = str(dist.version) url ...
python
{ "resource": "" }
q53143
VersionFinder._find_git_info
train
def _find_git_info(self, gitdir): """ Find information about the git repository, if this file is in a clone. :param gitdir: path to the git repo's .git directory :type gitdir: str :returns: information about the git clone :rtype: dict """ res = {'remotes'...
python
{ "resource": "" }
q53144
VersionFinder._package_top_dir
train
def _package_top_dir(self): """ Find one or more directories that we think may be the top-level directory of the package; return a list of their absolute paths. :return: list of possible package top-level directories (absolute paths) :rtype: list """ r = [self.pa...
python
{ "resource": "" }
q53145
get_repo_url
train
def get_repo_url(pypirc, repository): """Fetch the RepositoryURL for a given repository, reading info from pypirc. Will try to find the repository in the .pypirc, including username/password. Args: pypirc (str): path to the .pypirc config file repository (str): URL or alias for the reposit...
python
{ "resource": "" }
q53146
C_snodeBranch.node_branch
train
def node_branch(self, astr_node, abranch): """ Adds a branch to a node, i.e. depth addition. The given node's md_nodes is set to the abranch's mdict_branch. """ self.dict_branch[astr_node].node_dictBranch(abranch.dict_branch)
python
{ "resource": "" }
q53147
C_stree.root
train
def root(self): """ Reset all nodes and branches to 'root'. """ str_treeRoot = '/' self.l_cwd = [str_treeRoot] self.snode_current = self.snode_root self.sbranch_current = self.sbranch_root
python
{ "resource": "" }
q53148
C_stree.cwd
train
def cwd(self): """ Return a UNIX FS type string of the current working 'directory'. """ l_cwd = self.l_cwd[:] str_cwd = '/'.join(l_cwd) if len(str_cwd)>1: str_cwd = str_cwd[1:] return str_cwd
python
{ "resource": "" }
q53149
C_stree.path_has
train
def path_has(self, **kwargs): """ Checks if the current path has a node spec'd by kwargs """ str_node = "/" # This node will always be "False" for key, val in kwargs.items(): if key == 'node': str_node = val if str_node in self...
python
{ "resource": "" }
q53150
C_stree.pwd
train
def pwd(self, **kwargs): """ Returns the cwd Optional kwargs: node = <node> If specified, return only the directory name at depth <node>. """ b_node = False node = 0 for key,val in kwargs.items():...
python
{ "resource": "" }
q53151
C_stree.cat
train
def cat(self, name): """ Returns the contents of the 'name'd element at this level. If file does not exist, returns a False TODO: parse possible path spec in name... """ origDir = self.cwd() # First, parse any path specs... ...
python
{ "resource": "" }
q53152
C_stree.touch
train
def touch(self, name, data): """ Create a 'file' analog called 'name' and put 'data' to the d_data dictionary under key 'name'. The 'name' can contain a path specifier. """ b_OK = True str_here = self.cwd() # prin...
python
{ "resource": "" }
q53153
C_stree.rm
train
def rm(self, name): """ Remove a data analog called 'name'. The 'name' can contain a path specifier. Warning: see http://stackoverflow.com/questions/5844672/delete-an-element-from-a-dictionary deleting from the snode_current changes diction...
python
{ "resource": "" }
q53154
C_stree.append
train
def append(self, name, data): """Append 'data' to the current node d_data This method appends 'data' to the current contents in the key named 'name'. The append assumes that the operation makes sense and that the data types can be appended to each other. ...
python
{ "resource": "" }
q53155
C_stree.b_pathOK
train
def b_pathOK(self, al_path): """ Checks if the absolute path specified in the al_path is valid for current tree """ b_OK = True try: self.l_allPaths.index(al_path) except: b_OK = False return b_OK
python
{ "resource": "" }
q53156
C_stree.cdnode
train
def cdnode(self, astr_path): """Change working node to astr_path. The path is converted to a list, split on '/'. By performing a 'cd' all parent and derived nodes need to be updated relative to new location. Args: astr_path (string): The path...
python
{ "resource": "" }
q53157
C_stree.lsf
train
def lsf(self, astr_path=""): """ List only the "files" in the astr_path. :param astr_path: path to list :return: "files" in astr_path, empty list if no files """ d_files = self.ls(astr_path, nodes=False, data=True) l_files = d_files.ke...
python
{ "resource": "" }
q53158
C_stree.lstr_lsnode
train
def lstr_lsnode(self, astr_path=""): """ Return the string names of the set of nodes branching from current node as list of strings """ self.sCore.reset() str_cwd = self.cwd() if len(astr_path): self.cdnode(astr_path) ...
python
{ "resource": "" }
q53159
C_stree.tree_load
train
def tree_load(**kwargs): """ Load a tree from disk. Essentially, this reads a disk filetree into an snode tree. :param kwargs: :return: """ str_pathDiskRoot = '' b_loadJSON = True b_loadPickle ...
python
{ "resource": "" }
q53160
C_stree.treeExplore
train
def treeExplore(self, **kwargs): """ Recursively walk through a C_stree, applying a passed function at each node. The actual "walk" uses individual nodes' internal child dictionaries. It is assumed that the start origin of exploration can in fact ...
python
{ "resource": "" }
q53161
C_stree.treeWalk
train
def treeWalk(self, **kwargs): """ Recursively walk through a C_stree, applying a passed function at each node. The actual "walk" depends on using the 'cd' function which will only descend into paths that already exist in the internal path database. ...
python
{ "resource": "" }
q53162
C_stree.pathFromHere_explore
train
def pathFromHere_explore(self, astr_startPath = '/'): """ Return a list of paths from "here" in the stree, using the child explore access. :param astr_startPath: path from which to start :return: a list of paths from "here" """ self.l...
python
{ "resource": "" }
q53163
is_py_script
train
def is_py_script(filename): "Returns True if a file is a python executable." if not os.path.exists(filename) and os.path.isfile(filename): return False elif filename.endswith(".py"): return True elif not os.access(filename, os.X_OK): return False else: try: ...
python
{ "resource": "" }
q53164
Resolver.lookupAllRecords
train
def lookupAllRecords(self, name, timeout = None): """ Overwrite this method to use A type query instead of ANY which is done by default by the resolver. """ return self._lookup(name, dns.IN, dns.A, timeout)
python
{ "resource": "" }
q53165
print_markers
train
def print_markers(f): """A decorator that prints the invoked command before and after the command. """ @click.pass_context def new_func(ctx, *args, **kwargs): command = ctx.info_name assert command is not None command_name = ctx.command_path click_extensions.echo_with...
python
{ "resource": "" }
q53166
DepExtractor.get_calls
train
def get_calls(self, job_name): ''' Reads file by given name and returns CallEdge array ''' config = self.file_index.get_by_name(job_name).yaml calls = self.get_calls_from_dict(config, from_name=job_name) return calls
python
{ "resource": "" }
q53167
DepExtractor.get_calls_from_dict
train
def get_calls_from_dict(self, file_dict, from_name, settings={}): ''' Processes unfolded yaml object to CallEdge array settings is a dict of settings for keeping information like in what section we are right now (e.g. builders, publishers) ''' calls = [] call_se...
python
{ "resource": "" }
q53168
DepExtractor.get_includes
train
def get_includes(self, path): """ Get all includes from a config in a given path """ config = self.file_index.unfold_yaml(path) return self.get_includes_from_dict(config, extract=True)
python
{ "resource": "" }
q53169
openfile
train
def openfile(filename, mode="rt", *args, expanduser=False, expandvars=False, makedirs=False, **kwargs): """Open filename and return a corresponding file object.""" if filename in ("-", None): return sys.stdin if "r" in mode else sys.stdout if expanduser: filename = os.path.expan...
python
{ "resource": "" }
q53170
get_or_create_analysis_system_instance
train
def get_or_create_analysis_system_instance(instance_uuid='', identifier='', verbose_name='', tag_filter_exp='', uuid_file='uuid.txt'): """Get or create an analysis system instance for the analysis system with the respective identifier. This is a function for solving a common problem with implementations of MAS...
python
{ "resource": "" }
q53171
process_analyses
train
def process_analyses(analysis_system_instance, analysis_method, sleep_time): """Process all analyses which are scheduled for the analysis system instance. This function does not terminate on its own, give it a SIGINT or Ctrl+C to stop. :param analysis_system_instance: The analysis system instance for whic...
python
{ "resource": "" }
q53172
SeriesWorker.run
train
def run(self): """ Requests, parses series, writes to appropriate CSV """ empty = False while not empty: try: # Grab fields url = self.genre_urls.get() namestamp = "{}.csv".format(str(int(round(time.time() * 1000000)))) # GET request self.logger.info('At...
python
{ "resource": "" }
q53173
blind
train
def blind(m, hashfunc=hashG1): """ Blinds an arbitrary string or byte array @m using an ephemeral key @r that can be used to deblind. Computes: x = H(x)^r @returns (1/r,x) """ # Find r with a suitable inverse in Gt rInv = None while not rInv: r = randomZ() rInv = inverse(...
python
{ "resource": "" }
q53174
_unwrap
train
def _unwrap(x, deserializeFunc, decodeFunc=base64.urlsafe_b64decode, compress=True): """ Unwraps an element @x by decoding and then deserializing """ return deserializeFunc(decodeFunc(x), compress)
python
{ "resource": "" }
q53175
checkpermission.get_permission
train
def get_permission(self, service, func): """ Build permission required to access function "func" """ if self.permission: perm = self.permission elif self.prefix is False: # No permission will be checked perm = False elif self.prefix: ...
python
{ "resource": "" }
q53176
checkpermission.has_perm
train
def has_perm(self, service, perm_name, obj, call_name): """ Raise PermissionDenied if user has no permission in object """ user = service.user if not (perm_name is False): if not user.has_perm(perm_name, obj=obj): LOG_PERM.warn( u'U...
python
{ "resource": "" }
q53177
BaseService.validate
train
def validate(self, obj): """ Raises django.core.exceptions.ValidationError if any validation error exists """ if not isinstance(obj, self.model_class): raise ValidationError('Invalid object(%s) for service %s' % (type(obj), type(self))) LOG.debug(u'Object %s state: %s', self.model_c...
python
{ "resource": "" }
q53178
BaseService.filter_objects
train
def filter_objects(self, objects, perm=None): """ Return only objects with specified permission in objects list. If perm not specified, 'view' perm will be used. """ if perm is None: perm = build_permission_name(self.model_class, 'view') return filter(lambda o: self.user.has_perm(per...
python
{ "resource": "" }
q53179
Broker.disconnect
train
def disconnect(self): ''' This is called as part of the agency shutdown. ''' self.log("Disconnecting broker %r.", self) d = defer.succeed(None) if self.is_master(): if self.listener is not None: d.addCallback(defer.drop_param, self.listener.sto...
python
{ "resource": "" }
q53180
Broker.become_slave
train
def become_slave(self, broker): ''' Run as part of the handshake. @param broker: Remote reference to the broker object ''' self._set_state(BrokerRole.slave) self._master = broker d = defer.succeed(None) if callable(self.on_slave_cb): d.addCallb...
python
{ "resource": "" }
q53181
StandaloneBroker.spawn_missing_master
train
def spawn_missing_master(self): ''' Notifies the standalone slave agency that the master agency is missing ''' d = defer.succeed(None) if callable(self.on_master_missing_cb): d.addCallback(defer.drop_param, self.on_master_missing_cb) return d
python
{ "resource": "" }
q53182
AdminController.make_controller
train
def make_controller(cls, config, session, left_menu_items=None): """New CRUD controllers using the admin configuration can be created using this.""" m = config.model Controller = config.defaultCrudRestController class ModelController(Controller): model = m ...
python
{ "resource": "" }
q53183
FalkonryService.get_datastreams
train
def get_datastreams(self): """ To get list of Datastream """ datastreams = [] response = self.http.get('/Datastream') for datastream in response: datastreams.append(Schemas.Datastream(datastream=datastream)) return datastreams
python
{ "resource": "" }
q53184
FalkonryService.get_datastream
train
def get_datastream(self, datastream): """ To get Datastream by id """ response = self.http.get('/Datastream/' + str(datastream)) datastream = Schemas.Datastream(datastream=response) return datastream
python
{ "resource": "" }
q53185
FalkonryService.get_assessments
train
def get_assessments(self): """ To get list of Assessments """ assessments = [] response = self.http.get('/Assessment') for assessment in response: assessments.append(Schemas.Assessment(assessment=assessment)) return assessments
python
{ "resource": "" }
q53186
FalkonryService.get_assessment
train
def get_assessment(self, assessment): """ To get Assessment by id """ response = self.http.get('/Assessment/' + str(assessment)) assessment = Schemas.Assessment(assessment=response) return assessment
python
{ "resource": "" }
q53187
PDFPluginModel.save
train
def save(self, *args, **kwargs): """Customized to generate an image from the pdf file.""" # open image from pdf img = Image(filename=self.file.path + '[0]') # make new filename filename = os.path.basename(self.file.path).split('.')[:-1] if type(filename) == list: ...
python
{ "resource": "" }
q53188
generate
train
def generate(regex, Ns): "Return the strings matching regex whose length is in Ns." return sorted(regex_parse(regex)[0](Ns), key=lambda s: (len(s), s))
python
{ "resource": "" }
q53189
unused_configs
train
def unused_configs(options, **kwargs): """ Analysis functions Find all configs that are never used and return it as a list Jobs configs are always considered used """ include_graph = options['include_graph'] call_graph = options['call_graph'] used_configs = get_used_configs(include_gra...
python
{ "resource": "" }
q53190
create_badge_blueprint
train
def create_badge_blueprint(allowed_types): """Create the badge blueprint. :param allowed_types: A list of allowed types. :returns: A Flask blueprint. """ from invenio_formatter.context_processors.badges import \ generate_badge_png, generate_badge_svg blueprint = Blueprint( 'inv...
python
{ "resource": "" }
q53191
CallGraph.render_simple_edge
train
def render_simple_edge(self, name, edge, edge_settings, label="call"): """ Render edge without label """ self.gv_graph.edge(self.get_path_from_name(name), self.get_path_from_name(edge.to), label=label, **edge_settings)
python
{ "resource": "" }
q53192
CallGraph.render_edge_with_label
train
def render_edge_with_label(self, name, edge, edge_settings): """ Render edge with label as text """ props_to_display = self.extract_props(edge.settings) label = '<' for prop, value in props_to_display.items(): label += self.get_label(prop, value) ...
python
{ "resource": "" }
q53193
CallGraph.render_edge_with_node_label
train
def render_edge_with_node_label(self, name, edge, edge_settings): """ Render edge with label as separate node """ props_to_display = self.extract_props(edge.settings) label = '<' label += "|".join(self.get_label(prop, value) for prop, value in props_to_display.items()) ...
python
{ "resource": "" }
q53194
CallGraph.get_label
train
def get_label(self, prop, value): """ Format label If value is missing, label will be colored red """ if value is None: return '{}: <FONT color="red">{}</FONT>'.format(prop, "not set") else: return "{}:{}".format(prop, value)
python
{ "resource": "" }
q53195
CallGraph.extract_props
train
def extract_props(self, settings): ''' Extract all valuable properties to be displayed ''' props = {} for param in self.call_parameters: if param in settings: props[param] = settings[param] else: props[param] = None ...
python
{ "resource": "" }
q53196
SteamWebBrowser._get_cookie
train
def _get_cookie(self, name, domain): ''' Return the cookie "name" for "domain" if found If there are mote than one, only the first is returned ''' for c in self.session.cookies: if c.name==name and c.domain==domain: return c return None
python
{ "resource": "" }
q53197
SteamWebBrowser._get_rsa_key
train
def _get_rsa_key(self): ''' get steam RSA key, build and return cipher ''' url = 'https://steamcommunity.com/mobilelogin/getrsakey/' values = { 'username': self._username, 'donotcache' : self._get_donotcachetime(), } req = self.post(url, data=value...
python
{ "resource": "" }
q53198
SteamWebBrowser._handle_captcha
train
def _handle_captcha(captcha_data, message=''): # pylint:disable=unused-argument ''' Called when a captcha must be solved Writes the image to a temporary file and asks the user to enter the code. Args: captcha_data: Bytestring of the PNG captcha image. message: Optional. ...
python
{ "resource": "" }
q53199
SteamWebBrowser._handle_emailauth
train
def _handle_emailauth(maildomain='', message=''): # pylint:disable=unused-argument ''' Called when SteamGuard requires authentication via e-mail. Asks the user to enter the code. Args: maildomain: Optional. The mail domain of the e-mail address the SteamGuard code is...
python
{ "resource": "" }