_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q43000 | pipupdate | train | def pipupdate():
"""
Update all currently installed pip packages
"""
packages = [d for d in pkg_resources.working_set]
subprocess.call('pip install --upgrade ' + ' '.join(packages)) | python | {
"resource": ""
} |
q43001 | loglevel | train | def loglevel(leveltype=None, isequal=False):
"""
Set or get the logging level of Quilt
:type leveltype: string or integer
:param leveltype: Choose the logging level. Possible choices are none (0), debug (10), info (20), warning (30), error (40) and critical (50).
:type isequal: boolean
:param ... | python | {
"resource": ""
} |
q43002 | text | train | def text(path, operation, content):
"""
Perform changes on text files
:type path: string
:param path: The path to perform the action on
:type operation: string
:param operation: The operation to use on the file
:type content: string
:param content: The content to use with the operatio... | python | {
"resource": ""
} |
q43003 | mailto | train | def mailto(to, cc=None, bcc=None, subject=None, body=None):
"""
Generate and run mailto.
:type to: string
:param to: The recipient email address.
:type cc: string
:param cc: The recipient to copy to.
:type bcc: string
:param bcc: The recipient to blind copy to.
:type subject: str... | python | {
"resource": ""
} |
q43004 | Virsh.execute_virsh_command | train | def execute_virsh_command(self,
**kwargs):
'''
common virsh execution function
'''
host_list = kwargs.get('host_list', None)
remote_user = kwargs.get('remote_user', None)
remote_pass = kwargs.get('remote_pass', None)
sudo = kwargs.get... | python | {
"resource": ""
} |
q43005 | Virsh.virsh_version | train | def virsh_version(self,
host_list=None,
remote_user=None,
remote_pass=None,
sudo=False,
sudo_user=None,
sudo_pass=None):
'''
Get the virsh version
'''
host_... | python | {
"resource": ""
} |
q43006 | Virsh.virsh_per_domain_info | train | def virsh_per_domain_info(self,
**kwargs):
'''
Get per domain stats from each hosts passed as hostlist.
'''
host_list = kwargs.get('host_list', self.host_list)
remote_user = kwargs.get('remote_user', self.remote_user)
remote_pass = kwargs.get... | python | {
"resource": ""
} |
q43007 | getUserAgent | train | def getUserAgent():
'''
Generate a randomized user agent by permuting a large set of possible values.
The returned user agent should look like a valid, in-use brower, with a specified preferred language of english.
Return value is a list of tuples, where each tuple is one of the user-agent headers.
Currently can... | python | {
"resource": ""
} |
q43008 | CatTransformer.get_generator | train | def get_generator(self):
"""Return the generator object to anonymize data."""
faker = Faker()
try:
return getattr(faker, self.category)
except AttributeError:
raise ValueError('Category {} couldn\'t be found on faker') | python | {
"resource": ""
} |
q43009 | CatTransformer.anonymize_column | train | def anonymize_column(self, col):
"""Map the values of column to new ones of the same type.
It replaces the values from others generated using `faker`. It will however,
keep the original distribution. That mean that the generated `probability_map` for both
will have the same values, but ... | python | {
"resource": ""
} |
q43010 | CatTransformer._fit | train | def _fit(self, col):
"""Create a map of the empirical probability for each category.
Args:
col(pandas.DataFrame): Data to transform.
"""
column = col[self.col_name].replace({np.nan: np.inf})
frequencies = column.groupby(column).count().rename({np.inf: None}).to_dict... | python | {
"resource": ""
} |
q43011 | CatTransformer.fit_transform | train | def fit_transform(self, col):
"""Prepare the transformer and return processed data.
Args:
col(pandas.DataFrame): Data to transform.
Returns:
pandas.DataFrame
"""
if self.anonymize:
col = self.anonymize_column(col)
self._fit(col)
... | python | {
"resource": ""
} |
q43012 | CatTransformer.get_val | train | def get_val(self, x):
"""Convert cat value into num between 0 and 1."""
interval, mean, std = self.probability_map[x]
new_val = norm.rvs(mean, std)
return new_val | python | {
"resource": ""
} |
q43013 | CatTransformer.get_category | train | def get_category(self, column):
"""Returns categories for the specified numeric values
Args:
column(pandas.Series): Values to transform into categories
Returns:
pandas.Series
"""
result = pd.Series(index=column.index)
for category, stats in self... | python | {
"resource": ""
} |
q43014 | PositiveNumberTransformer.transform | train | def transform(self, column):
"""Applies an exponential to values to turn them positive numbers.
Args:
column (pandas.DataFrame): Data to transform.
Returns:
pd.DataFrame
"""
self.check_data_type()
return pd.DataFrame({self.col_name: np.exp(colum... | python | {
"resource": ""
} |
q43015 | PositiveNumberTransformer.reverse_transform | train | def reverse_transform(self, column):
"""Applies the natural logarithm function to turn positive values into real ranged values.
Args:
column (pandas.DataFrame): Data to transform.
Returns:
pd.DataFrame
"""
self.check_data_type()
return pd.DataFr... | python | {
"resource": ""
} |
q43016 | YQL._payload_builder | train | def _payload_builder(self, query, format=None):
'''Build the payload'''
if self.community :
query = self.COMMUNITY_DATA + query # access to community data tables
if vars(self).get('yql_table_url') : # Attribute only defined when MYQL.use has been called before
query = "u... | python | {
"resource": ""
} |
q43017 | YQL.execute_query | train | def execute_query(self, payload):
'''Execute the query and returns and response'''
if vars(self).get('oauth'):
if not self.oauth.token_is_valid(): # Refresh token if token has expired
self.oauth.refresh_token()
response = self.oauth.session.get(self.PRIVATE_URL, p... | python | {
"resource": ""
} |
q43018 | YQL.response_builder | train | def response_builder(self, response):
'''Try to return a pretty formatted response object
'''
try:
r = response.json()
result = r['query']['results']
response = {
'num_result': r['query']['count'] ,
'result': result
... | python | {
"resource": ""
} |
q43019 | YQL._func_filters | train | def _func_filters(self, filters):
'''Build post query filters
'''
if not isinstance(filters, (list,tuple)):
raise TypeError('func_filters must be a <type list> or <type tuple>')
for i, func in enumerate(filters) :
if isinstance(func, str) and func == 'reverse':
... | python | {
"resource": ""
} |
q43020 | MYQL.show_tables | train | def show_tables(self, format='json'):
'''Return list of all available tables'''
query = 'SHOW TABLES'
payload = self._payload_builder(query, format)
response = self.execute_query(payload)
return response | python | {
"resource": ""
} |
q43021 | event | train | def event(from_states=None, to_state=None):
""" a decorator for transitioning from certain states to a target state. must be used on bound methods of a class
instance, only. """
from_states_tuple = (from_states, ) if isinstance(from_states, State) else tuple(from_states or [])
if not len(from_states_tup... | python | {
"resource": ""
} |
q43022 | Weather.get_weather_in | train | def get_weather_in(self, place, unit=None, items=None):
"""Return weather info according to place
"""
unit = unit if unit else self.unit
response = self.select('weather.forecast', items=items).where(['woeid','IN',('SELECT woeid FROM geo.places WHERE text="{0}"'.format(place),)], ['u','='... | python | {
"resource": ""
} |
q43023 | Weather.get_weather_forecast | train | def get_weather_forecast(self, place, unit=None):
"""Return weather forecast accoriding to place
"""
unit = unit if unit else self.unit
response = self.get_weather_in(place, items=['item.forecast'], unit=unit)
return response | python | {
"resource": ""
} |
q43024 | WebGetCrMixin.stepThroughJsWaf_bare_chromium | train | def stepThroughJsWaf_bare_chromium(self, url, titleContains='', titleNotContains='', extra_tid=None):
'''
Use Chromium to access a resource behind WAF protection.
Params:
``url`` - The URL to access that is protected by WAF
``titleContains`` - A string that is in the title of the protected page, and NOT th... | python | {
"resource": ""
} |
q43025 | WebGetCrMixin.chromiumContext | train | def chromiumContext(self, url, extra_tid=None):
'''
Return a active chromium context, useable for manual operations directly against
chromium.
The WebRequest user agent and other context is synchronized into the chromium
instance at startup, and changes are flushed back to the webrequest instance
from chro... | python | {
"resource": ""
} |
q43026 | load_data_table | train | def load_data_table(table_name, meta_file, meta):
"""Return the contents and metadata of a given table.
Args:
table_name(str): Name of the table.
meta_file(str): Path to the meta.json file.
meta(dict): Contents of meta.json.
Returns:
tuple(pandas.DataFrame, dict)
"""
... | python | {
"resource": ""
} |
q43027 | get_col_info | train | def get_col_info(table_name, col_name, meta_file):
"""Return the content and metadata of a fiven column.
Args:
table_name(str): Name of the table.
col_name(str): Name of the column.
meta_file(str): Path to the meta.json file.
Returns:
tuple(pandas.Series, dict)
"""
... | python | {
"resource": ""
} |
q43028 | task_coverage | train | def task_coverage():
"""show coverage for all modules including tests"""
cov = Coverage(
[PythonPackage('import_deps', 'tests')],
config={'branch':True,},
)
yield cov.all() # create task `coverage`
yield cov.src() | python | {
"resource": ""
} |
q43029 | register_workflow | train | def register_workflow(connection, domain, workflow):
"""Register a workflow type.
Return False if this workflow already registered (and True otherwise).
"""
args = get_workflow_registration_parameter(workflow)
try:
connection.register_workflow_type(domain=domain, **args)
except ClientE... | python | {
"resource": ""
} |
q43030 | pretty_json | train | def pretty_json(data):
"""Return a pretty formatted json
"""
data = json.loads(data.decode('utf-8'))
return json.dumps(data, indent=4, sort_keys=True) | python | {
"resource": ""
} |
q43031 | pretty_xml | train | def pretty_xml(data):
"""Return a pretty formated xml
"""
parsed_string = minidom.parseString(data.decode('utf-8'))
return parsed_string.toprettyxml(indent='\t', encoding='utf-8') | python | {
"resource": ""
} |
q43032 | prettyfy | train | def prettyfy(response, format='json'):
"""A wrapper for pretty_json and pretty_xml
"""
if format == 'json':
return pretty_json(response.content)
else:
return pretty_xml(response.content) | python | {
"resource": ""
} |
q43033 | parse_journal | train | def parse_journal(journal):
"""Parses the USN Journal content removing duplicates
and corrupted records.
"""
events = [e for e in journal if not isinstance(e, CorruptedUsnRecord)]
keyfunc = lambda e: str(e.file_reference_number) + e.file_name + e.timestamp
event_groups = (tuple(g) for k, g in g... | python | {
"resource": ""
} |
q43034 | journal_event | train | def journal_event(events):
"""Group multiple events into a single one."""
reasons = set(chain.from_iterable(e.reasons for e in events))
attributes = set(chain.from_iterable(e.file_attributes for e in events))
return JrnlEvent(events[0].file_reference_number,
events[0].parent_file_r... | python | {
"resource": ""
} |
q43035 | generate_timeline | train | def generate_timeline(usnjrnl, filesystem_content):
"""Aggregates the data collected from the USN journal
and the filesystem content.
"""
journal_content = defaultdict(list)
for event in usnjrnl:
journal_content[event.inode].append(event)
for event in usnjrnl:
try:
... | python | {
"resource": ""
} |
q43036 | lookup_dirent | train | def lookup_dirent(event, filesystem_content, journal_content):
"""Lookup the dirent given a journal event."""
for dirent in filesystem_content[event.inode]:
if dirent.path.endswith(event.name):
return dirent
path = lookup_folder(event, filesystem_content)
if path is not None:
... | python | {
"resource": ""
} |
q43037 | lookup_folder | train | def lookup_folder(event, filesystem):
"""Lookup the parent folder in the filesystem content."""
for dirent in filesystem[event.parent_inode]:
if dirent.type == 'd' and dirent.allocated:
return ntpath.join(dirent.path, event.name) | python | {
"resource": ""
} |
q43038 | lookup_deleted_folder | train | def lookup_deleted_folder(event, filesystem, journal):
"""Lookup the parent folder in the journal content."""
folder_events = (e for e in journal[event.parent_inode]
if 'DIRECTORY' in e.attributes
and 'FILE_DELETE' in e.changes)
for folder_event in folder_events:
... | python | {
"resource": ""
} |
q43039 | FSTimeline._visit_filesystem | train | def _visit_filesystem(self):
"""Walks through the filesystem content."""
self.logger.debug("Parsing File System content.")
root_partition = self._filesystem.inspect_get_roots()[0]
yield from self._root_dirent()
for entry in self._filesystem.filesystem_walk(root_partition):
... | python | {
"resource": ""
} |
q43040 | FSTimeline._root_dirent | train | def _root_dirent(self):
"""Returns the root folder dirent as filesystem_walk API doesn't."""
fstat = self._filesystem.stat('/')
yield Dirent(fstat['ino'], self._filesystem.path('/'),
fstat['size'], 'd', True,
timestamp(fstat['atime'], 0),
... | python | {
"resource": ""
} |
q43041 | NTFSTimeline.usnjrnl_timeline | train | def usnjrnl_timeline(self):
"""Iterates over the changes occurred within the filesystem.
Yields UsnJrnlEvent namedtuples containing:
file_reference_number: known in Unix FS as inode.
path: full path of the file.
size: size of the file in bytes if recoverable.
... | python | {
"resource": ""
} |
q43042 | NTFSTimeline._read_journal | train | def _read_journal(self):
"""Extracts the USN journal from the disk and parses its content."""
root = self._filesystem.inspect_get_roots()[0]
inode = self._filesystem.stat('C:\\$Extend\\$UsnJrnl')['ino']
with NamedTemporaryFile(buffering=0) as tempfile:
self._filesystem.downl... | python | {
"resource": ""
} |
q43043 | ProcessList.put | train | def put(self, stream, cmd):
""" Spawn a new background process """
if len(self.q) < self.max_size:
if stream['id'] in self.q:
raise QueueDuplicate
p = self.call(stream, cmd)
self.q[stream['id']] = p
else:
raise QueueFull | python | {
"resource": ""
} |
q43044 | ProcessList.get_finished | train | def get_finished(self):
""" Clean up terminated processes and returns the list of their ids """
indices = []
for idf, v in self.q.items():
if v.poll() != None:
indices.append(idf)
for i in indices:
self.q.pop(i)
return indices | python | {
"resource": ""
} |
q43045 | ProcessList.get_stdouts | train | def get_stdouts(self):
""" Get the list of stdout of each process """
souts = []
for v in self.q.values():
souts.append(v.stdout)
return souts | python | {
"resource": ""
} |
q43046 | ProcessList.terminate_process | train | def terminate_process(self, idf):
""" Terminate a process by id """
try:
p = self.q.pop(idf)
p.terminate()
return p
except:
return None | python | {
"resource": ""
} |
q43047 | ProcessList.terminate | train | def terminate(self):
""" Terminate all processes """
for w in self.q.values():
try:
w.terminate()
except:
pass
self.q = {} | python | {
"resource": ""
} |
q43048 | StreamList.init | train | def init(self, s):
""" Initialize the text interface """
# Hide cursor
curses.curs_set(0)
self.s = s
self.s.keypad(1)
self.set_screen_size()
self.pads = {}
self.offsets = {}
self.init_help()
self.init_streams_pad()
self.current... | python | {
"resource": ""
} |
q43049 | StreamList.resize | train | def resize(self, signum, obj):
""" handler for SIGWINCH """
self.s.clear()
stream_cursor = self.pads['streams'].getyx()[0]
for pad in self.pads.values():
pad.clear()
self.s.refresh()
self.set_screen_size()
self.set_title(TITLE_STRING)
self.init... | python | {
"resource": ""
} |
q43050 | StreamList.set_screen_size | train | def set_screen_size(self):
""" Setup screen size and padding
We have need 2 free lines at the top and 2 free lines at the bottom
"""
height, width = self.getheightwidth()
curses.resizeterm(height, width)
self.pad_x = 0
self.max_y, self.max_x = (height-1, width-1... | python | {
"resource": ""
} |
q43051 | StreamList.set_title | train | def set_title(self, msg):
""" Set first header line text """
self.s.move(0, 0)
self.overwrite_line(msg, curses.A_REVERSE) | python | {
"resource": ""
} |
q43052 | StreamList.set_header | train | def set_header(self, msg):
""" Set second head line text """
self.s.move(1, 0)
self.overwrite_line(msg, attr=curses.A_NORMAL) | python | {
"resource": ""
} |
q43053 | StreamList.set_footer | train | def set_footer(self, msg, reverse=True):
""" Set first footer line text """
self.s.move(self.max_y-1, 0)
if reverse:
self.overwrite_line(msg, attr=curses.A_REVERSE)
else:
self.overwrite_line(msg, attr=curses.A_NORMAL) | python | {
"resource": ""
} |
q43054 | StreamList.show_help | train | def show_help(self):
""" Redraw Help screen and wait for any input to leave """
self.s.move(1,0)
self.s.clrtobot()
self.set_header('Help'.center(self.pad_w))
self.set_footer(' ESC or \'q\' to return to main menu')
self.s.refresh()
self.current_pad = 'help'
... | python | {
"resource": ""
} |
q43055 | StreamList.init_streams_pad | train | def init_streams_pad(self, start_row=0):
""" Create a curses pad and populate it with a line by stream """
y = 0
pad = curses.newpad(max(1,len(self.filtered_streams)), self.pad_w)
pad.keypad(1)
for s in self.filtered_streams:
pad.addstr(y, 0, self.format_stream_line(s... | python | {
"resource": ""
} |
q43056 | StreamList.move | train | def move(self, direction, absolute=False, pad_name=None, refresh=True):
""" Scroll the current pad
direction : (int) move by one in the given direction
-1 is up, 1 is down. If absolute is True,
go to position direction.
B... | python | {
"resource": ""
} |
q43057 | StreamList.redraw_current_line | train | def redraw_current_line(self):
""" Redraw the highlighted line """
if self.no_streams:
return
row = self.pads[self.current_pad].getyx()[0]
s = self.filtered_streams[row]
pad = self.pads['streams']
pad.move(row, 0)
pad.clrtoeol()
pad.addstr(row,... | python | {
"resource": ""
} |
q43058 | WebGetSeleniumChromiumMixin.stepThroughJsWaf_selenium_chromium | train | def stepThroughJsWaf_selenium_chromium(self, url, titleContains='', titleNotContains=''):
'''
Use Selenium+SeleniumChromium to access a resource behind cloudflare protection.
Params:
``url`` - The URL to access that is protected by cloudflare
``titleContains`` - A string that is in the title of the protect... | python | {
"resource": ""
} |
q43059 | Loader.scope | train | def scope(self, key, *tags, default=None):
"""Only apply tags and default for top-level key, effectively scoping the tags."""
scope = self._scopes[key]
tags = self._ensure_exclamation(tags)
default = default if not default or default.startswith("!") else "!" + default
if scope:
... | python | {
"resource": ""
} |
q43060 | Loader.load | train | def load(self, content):
"""Parse yaml content."""
# Try parsing the YAML with global tags
try:
config = yaml.load(content, Loader=self._loader(self._global_tags))
except yaml.YAMLError:
raise InvalidConfigError(_("Config is not valid yaml."))
# Try extra... | python | {
"resource": ""
} |
q43061 | Loader._loader | train | def _loader(self, tags):
"""Create a yaml Loader."""
class ConfigLoader(SafeLoader):
pass
ConfigLoader.add_multi_constructor("", lambda loader, prefix, node: TaggedValue(node.value, node.tag, *tags))
return ConfigLoader | python | {
"resource": ""
} |
q43062 | Loader._validate | train | def _validate(self, config):
"""Check whether every TaggedValue has a valid tag, otherwise raise InvalidConfigError"""
if isinstance(config, dict):
# Recursively validate each item in the config
for val in config.values():
self._validate(val)
elif isinsta... | python | {
"resource": ""
} |
q43063 | Loader._apply_default | train | def _apply_default(self, config, default):
"""
Apply default value to every str in config.
Also ensure every TaggedValue has default in .tags
"""
# No default, nothing to be done here
if not default:
return config
# If the entire config is just a stri... | python | {
"resource": ""
} |
q43064 | Loader._apply_scope | train | def _apply_scope(self, config, tags):
"""Add locally scoped tags to config"""
if isinstance(config, dict):
# Recursively _apply_scope for each item in the config
for val in config.values():
self._apply_scope(val, tags)
elif isinstance(config, list):
... | python | {
"resource": ""
} |
q43065 | Overload.has_args | train | def has_args():
''' returns true if the decorator invocation
had arguments passed to it before being
sent a function to decorate '''
no_args_syntax = '@overload'
args_syntax = no_args_syntax + '('
args, no_args = [(-1,-1)], [(-1,-1)]
for i, line in enumera... | python | {
"resource": ""
} |
q43066 | Overload.identify | train | def identify(fn):
''' returns a tuple that is used to match
functions to their neighbors in their
resident namespaces '''
return (
fn.__globals__['__name__'], # module namespace
getattr(fn, '__qualname__', getattr(fn, '__name__', '')) # class and function ... | python | {
"resource": ""
} |
q43067 | Overload.overload | train | def overload(fn, function_to_overload=None):
'''
This function decorator allows you to overload already defined functions. The
execution of overloaded functions is done by trying the original version first
and if it fails, the variables are handed off to the overloading function.
While this does seem like a sl... | python | {
"resource": ""
} |
q43068 | package_to_requirement | train | def package_to_requirement(package_name):
"""Translate a name like Foo-1.2 to Foo==1.3"""
match = re.search(r'^(.*?)-(dev|\d.*)', package_name)
if match:
name = match.group(1)
version = match.group(2)
else:
name = package_name
version = ''
if version:
return '... | python | {
"resource": ""
} |
q43069 | string_range | train | def string_range(last):
"""Compute the range of string between "a" and last.
This works for simple "a to z" lists, but also for "a to zz" lists.
"""
for k in range(len(last)):
for x in product(string.ascii_lowercase, repeat=k+1):
result = ''.join(x)
yield result
... | python | {
"resource": ""
} |
q43070 | PackageFinder._get_mirror_urls | train | def _get_mirror_urls(self, mirrors=None, main_mirror_url=None):
"""Retrieves a list of URLs from the main mirror DNS entry
unless a list of mirror URLs are passed.
"""
if not mirrors:
mirrors = get_mirrors(main_mirror_url)
# Should this be made "less random"? E.g.... | python | {
"resource": ""
} |
q43071 | HTMLPage._get_content_type | train | def _get_content_type(url):
"""Get the Content-Type of the given url, using a HEAD request"""
scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
if not scheme in ('http', 'https', 'ftp', 'ftps'):
## FIXME: some warning or something?
## assertion error?
... | python | {
"resource": ""
} |
q43072 | HTMLPage.explicit_rel_links | train | def explicit_rel_links(self, rels=('homepage', 'download')):
"""Yields all links with the given relations"""
for match in self._rel_re.finditer(self.content):
found_rels = match.group(1).lower().split()
for rel in rels:
if rel in found_rels:
br... | python | {
"resource": ""
} |
q43073 | BaseBuilder._metahash | train | def _metahash(self):
"""Checksum hash of all the inputs to this rule.
Output is invalid until collect_srcs and collect_deps have been run.
In theory, if this hash doesn't change, the outputs won't change
either, which makes it useful for caching.
"""
# BE CAREFUL when ... | python | {
"resource": ""
} |
q43074 | BaseBuilder.collect_outs | train | def collect_outs(self):
"""Collect and store the outputs from this rule."""
# TODO: this should probably live in CacheManager.
for outfile in self.rule.output_files or []:
outfile_built = os.path.join(self.buildroot, outfile)
if not os.path.exists(outfile_built):
... | python | {
"resource": ""
} |
q43075 | BaseBuilder.is_cached | train | def is_cached(self):
"""Returns true if this rule is already cached."""
# TODO: cache by target+hash, not per file.
try:
for item in self.rule.output_files:
log.info(item)
self.cachemgr.in_cache(item, self._metahash())
except cache.CacheMiss:
... | python | {
"resource": ""
} |
q43076 | BaseBuilder.get_from_cache | train | def get_from_cache(self):
"""See if this rule has already been built and cached."""
for item in self.rule.output_files:
dstpath = os.path.join(self.buildroot, item)
self.linkorcopy(
self.cachemgr.path_in_cache(item, self._metahash()),
dstpath) | python | {
"resource": ""
} |
q43077 | BaseBuilder.linkorcopy | train | def linkorcopy(self, src, dst):
"""hardlink src file to dst if possible, otherwise copy."""
if os.path.isdir(dst):
log.warn('linkorcopy given a directory as destination. '
'Use caution.')
log.debug('src: %s dst: %s', src, dst)
elif os.path.exists(dst... | python | {
"resource": ""
} |
q43078 | BaseBuilder.rulefor | train | def rulefor(self, addr):
"""Return the rule object for an address from our deps graph."""
return self.rule.subgraph.node[self.rule.makeaddress(addr)][
'target_obj'] | python | {
"resource": ""
} |
q43079 | BaseTarget.composed_deps | train | def composed_deps(self):
"""Dependencies of this build target."""
if 'deps' in self.params:
param_deps = self.params['deps'] or []
deps = [self.makeaddress(dep) for dep in param_deps]
return deps
else:
return None | python | {
"resource": ""
} |
q43080 | BaseTarget.source_files | train | def source_files(self):
"""This rule's source files."""
if 'srcs' in self.params and self.params['srcs'] is not None:
return util.flatten(self.params['srcs']) | python | {
"resource": ""
} |
q43081 | BaseTarget.makeaddress | train | def makeaddress(self, label):
"""Turn a label into an Address with current context.
Adds repo and path if given a label that only has a :target part.
"""
addr = address.new(label)
if not addr.repo:
addr.repo = self.address.repo
if not addr.path:
... | python | {
"resource": ""
} |
q43082 | SignedViewSetMixin.get_queryset | train | def get_queryset(self):
"""Return the allowed queryset for this sign or the default one."""
if 'sign' in self.request.query_params:
try:
filter_and_actions = unsign_filters_and_actions(
self.request.query_params['sign'],
'{}.{}'.format(... | python | {
"resource": ""
} |
q43083 | slugify | train | def slugify(value, allow_unicode=False):
"""
Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens.
Remove characters that aren't alphanumerics, underscores, or hyphens.
Convert to lowercase. Also strip leading and trailing whitespace.
"""
value
if allow_unicode:
va... | python | {
"resource": ""
} |
q43084 | Configuration.items | train | def items(self):
"""Settings as key-value pair.
"""
return [(section, dict(self.conf.items(section, raw=True))) for \
section in [section for section in self.conf.sections()]] | python | {
"resource": ""
} |
q43085 | jarsign | train | def jarsign(storepass, keypass, keystore, source, alias, path=None):
"""
Uses Jarsign to sign an apk target file using the provided keystore information.
:param storepass(str) - keystore storepass
:param keypass(str) - keystore keypass
:param keystore(str) - keystore file path
:param source(str) - apk path... | python | {
"resource": ""
} |
q43086 | get_default_keystore | train | def get_default_keystore(prefix='AG_'):
"""
Gets the default keystore information based on environment variables and a prefix.
$PREFIX_KEYSTORE_PATH - keystore file path, default is opt/digger/debug.keystore
$PREFIX_KEYSTORE_STOREPASS - keystore storepass, default is android
$PREFIX_KEYSTORE_KEYPASS - keysto... | python | {
"resource": ""
} |
q43087 | get_highest_build_tool | train | def get_highest_build_tool(sdk_version=None):
"""
Gets the highest build tool version based on major version sdk version.
:param sdk_version(int) - sdk version to be used as the marjor build tool version context.
Returns:
A string containg the build tool version (default is 23.0.2 if none is found)
"""
... | python | {
"resource": ""
} |
q43088 | Command.rename_file | train | def rename_file(self, instance, field_name):
"""
Renames a file and updates the model field to point to the new file.
Returns True if a change has been made; otherwise False
"""
file = getattr(instance, field_name)
if file:
new_name = get_hashed_filename(fil... | python | {
"resource": ""
} |
q43089 | PeekPlatformServerHttpHookABC.addServerResource | train | def addServerResource(self, pluginSubPath: bytes, resource: BasicResource) -> None:
""" Add Server Resource
Add a cusotom implementation of a served http resource.
:param pluginSubPath: The resource path where you want to serve this resource.
:param resource: The resource to serve.
... | python | {
"resource": ""
} |
q43090 | BaseHttpStreamWriter.write | train | def write(self, data: bytes) -> None:
"""
Write the data.
"""
if self.finished():
if self._exc:
raise self._exc
raise WriteAfterFinishedError
if not data:
return
try:
self._delegate.write_data(data, finish... | python | {
"resource": ""
} |
q43091 | BaseHttpStreamWriter.flush | train | async def flush(self) -> None:
"""
Give the writer a chance to flush the pending data
out of the internal buffer.
"""
async with self._flush_lock:
if self.finished():
if self._exc:
raise self._exc
return
... | python | {
"resource": ""
} |
q43092 | BaseHttpStreamWriter.finish | train | def finish(self, data: bytes=b"") -> None:
"""
Finish the stream.
"""
if self.finished():
if self._exc:
raise self._exc
if data:
raise WriteAfterFinishedError
return
try:
self._delegate.write_data(... | python | {
"resource": ""
} |
q43093 | register | train | def register(**kwargs):
"""Registers a notification_cls.
"""
def _wrapper(notification_cls):
if not issubclass(notification_cls, (Notification,)):
raise RegisterNotificationError(
f"Wrapped class must be a 'Notification' class. "
f"Got '{notification_cls... | python | {
"resource": ""
} |
q43094 | Address.__parse_target | train | def __parse_target(targetstr, current_repo=None):
"""Parse a build target string.
General form: //repo[gitref]/dir/path:target.
These are all valid:
//repo
//repo[a038fi31d9e8bc11582ef1b1b1982d8fc]
//repo[a039aa30853298]:foo
//repo/dir
//repo[a... | python | {
"resource": ""
} |
q43095 | authenticated_session | train | def authenticated_session(username, password):
"""
Given username and password, return an authenticated Yahoo `requests`
session that can be used for further scraping requests.
Throw an AuthencationError if authentication fails.
"""
session = requests.Session()
session.headers.update(header... | python | {
"resource": ""
} |
q43096 | post_data | train | def post_data(page, username, password):
"""
Given username and password, return the post data necessary for login
"""
soup = BeautifulSoup(page)
try:
inputs = soup.find(id='hiddens').findAll('input')
post_data = {input['name']: input['value'] for input in inputs}
post_data['... | python | {
"resource": ""
} |
q43097 | Certification.from_signed_raw | train | def from_signed_raw(cls: Type[CertificationType], signed_raw: str) -> CertificationType:
"""
Return Certification instance from signed raw document
:param signed_raw: Signed raw document
:return:
"""
n = 0
lines = signed_raw.splitlines(True)
version = in... | python | {
"resource": ""
} |
q43098 | Certification.from_inline | train | def from_inline(cls: Type[CertificationType], version: int, currency: str, blockhash: Optional[str],
inline: str) -> CertificationType:
"""
Return Certification instance from inline document
Only self.pubkey_to is populated.
You must populate self.identity with an Id... | python | {
"resource": ""
} |
q43099 | Certification.inline | train | def inline(self) -> str:
"""
Return inline document string
:return:
"""
return "{0}:{1}:{2}:{3}".format(self.pubkey_from, self.pubkey_to,
self.timestamp.number, self.signatures[0]) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.