_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q42600 | parse_log | train | def parse_log(file_path):
"""
Parse a CISM output log and extract some information.
Args:
file_path: absolute path to the log file
Return:
A dictionary created by the elements object corresponding to
the results of the bit for bit testing
"""
if not os.path.isfile(file_... | python | {
"resource": ""
} |
q42601 | parse_config | train | def parse_config(file_path):
"""
Convert the CISM configuration file to a python dictionary
Args:
file_path: absolute path to the configuration file
Returns:
A dictionary representation of the given file
"""
if not os.path.isfile(file_path):
return {}
parser = Confi... | python | {
"resource": ""
} |
q42602 | MainWidget._selectedRepoRow | train | def _selectedRepoRow(self):
""" Return the currently select repo """
# TODO - figure out what happens if no repo is selected
selectedModelIndexes = \
self.reposTableWidget.selectionModel().selectedRows()
for index in selectedModelIndexes:
return index.row() | python | {
"resource": ""
} |
q42603 | MetaboliticsAnalysis.set_objective | train | def set_objective(self, measured_metabolites):
'''
Updates objective function for given measured metabolites.
:param dict measured_metabolites: dict in which keys are metabolite names
and values are float numbers represent fold changes in metabolites.
'''
self.clea... | python | {
"resource": ""
} |
q42604 | Routers | train | def Routers(typ, share, handler=RoutersHandler):
"""
Pass the result of this function to the handler argument
in your attribute declaration
"""
_sharing_id, _mode = tuple(share.split(":"))
_router_cls = ROUTERS.get(typ)
class _Handler(handler):
mode=_mode
sharing_id=_sharing_... | python | {
"resource": ""
} |
q42605 | Segment.stringize | train | def stringize(
self,
rnf_profile,
):
"""Create RNF representation of this segment.
Args:
rnf_profile (rnftools.rnfformat.RnfProfile): RNF profile (with widths).
"""
coor_width = max(rnf_profile.coor_width, len(str(self.left)), len(str(self.right)))
return "({},{},{},... | python | {
"resource": ""
} |
q42606 | Segment.destringize | train | def destringize(self, string):
"""Get RNF values for this segment from its textual representation and
save them into this object.
Args:
string (str): Textual representation of a segment.
"""
m = segment_destr_pattern.match(string)
self.genome_id = int(m.group(1))
self.chr_id =... | python | {
"resource": ""
} |
q42607 | AssignmentsAPI.list_assignments | train | def list_assignments(self, course_id, assignment_ids=None, bucket=None, include=None, needs_grading_count_by_section=None, override_assignment_dates=None, search_term=None):
"""
List assignments.
Returns the list of assignments for the current context.
"""
path = {}
... | python | {
"resource": ""
} |
q42608 | AssignmentsAPI.get_single_assignment | train | def get_single_assignment(self, id, course_id, all_dates=None, include=None, needs_grading_count_by_section=None, override_assignment_dates=None):
"""
Get a single assignment.
Returns the assignment with the given id.
"observed_users" is passed, submissions for observed users will... | python | {
"resource": ""
} |
q42609 | randomize_es | train | def randomize_es(es_queryset):
"""Randomize an elasticsearch queryset."""
return es_queryset.query(
query.FunctionScore(
functions=[function.RandomScore()]
)
).sort("-_score") | python | {
"resource": ""
} |
q42610 | Configurator.configure | train | def configure(self, cfg, handler, path=""):
"""
Start configuration process for the provided handler
Args:
cfg (dict): config container
handler (config.Handler class): config handler to use
path (str): current path in the configuration progress
"""
... | python | {
"resource": ""
} |
q42611 | Configurator.set | train | def set(self, handler, attr, name, path, cfg):
"""
Obtain value for config variable, by prompting the user
for input and substituting a default value if needed.
Also does validation on user input
"""
full_name = ("%s.%s" % (path, name)).strip(".")
# obtain def... | python | {
"resource": ""
} |
q42612 | _from_keras_log_format | train | def _from_keras_log_format(data, **kwargs):
"""Plot accuracy and loss from a panda's dataframe.
Args:
data: Panda dataframe in the format of the Keras CSV log.
output_dir_path: The path to the directory where the resultings plots
should end up.
"""
data_val = pd.DataFrame(da... | python | {
"resource": ""
} |
q42613 | from_keras_log | train | def from_keras_log(csv_path, output_dir_path, **kwargs):
"""Plot accuracy and loss from a Keras CSV log.
Args:
csv_path: The path to the CSV log with the actual data.
output_dir_path: The path to the directory where the resultings plots
should end up.
"""
# automatically get... | python | {
"resource": ""
} |
q42614 | Component.get_config | train | def get_config(self, key_name):
"""
Return configuration value
Args:
key_name (str): configuration key
Returns:
The value for the specified configuration key, or if not found
in the config the default value specified in the Configuration Handler
... | python | {
"resource": ""
} |
q42615 | make_pagination_headers | train | def make_pagination_headers(request, limit, curpage, total, links=False):
"""Return Link Hypermedia Header."""
lastpage = math.ceil(total / limit) - 1
headers = {'X-Total-Count': str(total), 'X-Limit': str(limit),
'X-Page-Last': str(lastpage), 'X-Page': str(curpage)}
if links:
bas... | python | {
"resource": ""
} |
q42616 | RESTHandler.bind | train | def bind(cls, app, *paths, methods=None, name=None, **kwargs):
"""Bind to the application.
Generate URL, name if it's not provided.
"""
paths = paths or ['/%s(/{%s})?/?' % (cls.name, cls.name)]
name = name or "api.%s" % cls.name
return super(RESTHandler, cls).bind(app, *... | python | {
"resource": ""
} |
q42617 | RESTHandler.dispatch | train | async def dispatch(self, request, view=None, **kwargs):
"""Process request."""
# Authorization endpoint
self.auth = await self.authorize(request, **kwargs) # noqa
# Load collection
self.collection = await self.get_many(request, **kwargs)
if request.method == 'POST' and... | python | {
"resource": ""
} |
q42618 | RESTHandler.get | train | async def get(self, request, resource=None, **kwargs):
"""Get resource or collection of resources.
---
parameters:
- name: resource
in: path
type: string
"""
if resource is not None and resource != '':
return self.to_simple(re... | python | {
"resource": ""
} |
q42619 | RESTHandler.load | train | async def load(self, request, resource=None, **kwargs):
"""Load resource from given data."""
schema = self.get_schema(request, resource=resource, **kwargs)
data = await self.parse(request)
resource, errors = schema.load(
data, partial=resource is not None, many=isinstance(dat... | python | {
"resource": ""
} |
q42620 | MergedPollDataView.render_to_response | train | def render_to_response(self, context, **response_kwargs):
"""
This endpoint sets very permiscuous CORS headers.
Access-Control-Allow-Origin is set to the request Origin. This allows
a page from ANY domain to make a request to this endpoint.
Access-Control-Allow-Credentials is... | python | {
"resource": ""
} |
q42621 | resize | train | def resize(widthWindow, heightWindow):
"""Setup 3D projection for window"""
glViewport(0, 0, widthWindow, heightWindow)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(70, 1.0*widthWindow/heightWindow, 0.001, 10000.0)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity() | python | {
"resource": ""
} |
q42622 | to_d | train | def to_d(l):
"""
Converts list of dicts to dict.
"""
_d = {}
for x in l:
for k, v in x.items():
_d[k] = v
return _d | python | {
"resource": ""
} |
q42623 | tailor | train | def tailor(pattern_or_root, dimensions=None, distributed_dim='time',
read_only=False):
"""
Return a TileManager to wrap the root descriptor and tailor all the
dimensions to a specified window.
Keyword arguments:
root -- a NCObject descriptor.
pattern -- a filename string to open a NC... | python | {
"resource": ""
} |
q42624 | get_dependants | train | def get_dependants(project_name):
"""Yield dependants of `project_name`."""
for package in get_installed_distributions(user_only=ENABLE_USER_SITE):
if is_dependant(package, project_name):
yield package.project_name | python | {
"resource": ""
} |
q42625 | is_dependant | train | def is_dependant(package, project_name):
"""Determine whether `package` is a dependant of `project_name`."""
for requirement in package.requires():
# perform case-insensitive matching
if requirement.project_name.lower() == project_name.lower():
return True
return False | python | {
"resource": ""
} |
q42626 | Miner.get_global_rate_limit | train | def get_global_rate_limit(self):
"""Get the global rate limit per client.
:rtype: int
:returns: The global rate limit for each client.
"""
r = urllib.request.urlopen('https://archive.org/metadata/iamine-rate-limiter')
j = json.loads(r.read().decode('utf-8'))
retu... | python | {
"resource": ""
} |
q42627 | ItemMiner.mine_items | train | def mine_items(self, identifiers, params=None, callback=None):
"""Mine metadata from Archive.org items.
:param identifiers: Archive.org identifiers to be mined.
:type identifiers: iterable
:param params: URL parameters to send with each metadata
request.
... | python | {
"resource": ""
} |
q42628 | Luis.analyze | train | def analyze(self, text):
"""Sends text to LUIS for analysis.
Returns a LuisResult.
"""
logger.debug('Sending %r to LUIS app %s', text, self._url)
r = requests.get(self._url, {'q': text})
logger.debug('Request sent to LUIS URL: %s', r.url)
logger.debug(
... | python | {
"resource": ""
} |
q42629 | enum | train | def enum(**enums):
"""
A basic enum implementation.
Usage:
>>> MY_ENUM = enum(FOO=1, BAR=2)
>>> MY_ENUM.FOO
1
>>> MY_ENUM.BAR
2
"""
# Enum values must be hashable to support reverse lookup.
if not all(isinstance(val, collections.Hashable) for val in _valu... | python | {
"resource": ""
} |
q42630 | Manager.create_translation_tasks | train | def create_translation_tasks(self, instance):
"""
Creates the translations tasks from the instance and its translatable children
:param instance:
:return:
"""
langs = self.get_languages()
result = []
# get the previous and actual values
# in cas... | python | {
"resource": ""
} |
q42631 | Manager.update_task | train | def update_task(self, differences):
"""
Updates a task as done if we have a new value for this alternative language
:param differences:
:return:
"""
self.log('differences UPDATING: {}'.format(differences))
object_name = '{} - {}'.format(self.app_label, self.ins... | python | {
"resource": ""
} |
q42632 | Manager.get_previous_and_current_values | train | def get_previous_and_current_values(self, instance):
"""
Obtain the previous and actual values and compares them
in order to detect which fields has changed
:param instance:
:param translation:
:return:
"""
translated_field_names = self._get_translated_fi... | python | {
"resource": ""
} |
q42633 | Manager.get_obj_values | train | def get_obj_values(obj, translated_field_names):
"""
get the translated field values from translatable fields of an object
:param obj:
:param translated_field_names:
:return:
"""
# set of translated fields to list
fields = list(translated_field_names)
... | python | {
"resource": ""
} |
q42634 | Manager._get_translated_field_names | train | def _get_translated_field_names(model_instance):
"""
Get the instance translatable fields
:return:
"""
hvad_internal_fields = ['id', 'language_code', 'master', 'master_id', 'master_id']
translated_field_names = set(model_instance._translated_field_names) - set(hvad_inter... | python | {
"resource": ""
} |
q42635 | Manager.get_languages | train | def get_languages(self, include_main=False):
"""
Get all the languages except the main.
Try to get in order:
1.- item languages
2.- model languages
3.- application model languages
# 4.- default languages
:param master:
:param incl... | python | {
"resource": ""
} |
q42636 | Manager.get_languages_from_model | train | def get_languages_from_model(app_label, model_label):
"""
Get the languages configured for the current model
:param model_label:
:param app_label:
:return:
"""
try:
mod_lan = TransModelLanguage.objects.filter(model='{} - {}'.format(app_label, model_la... | python | {
"resource": ""
} |
q42637 | Manager.get_languages_from_application | train | def get_languages_from_application(app_label):
"""
Get the languages configured for the current application
:param app_label:
:return:
"""
try:
mod_lan = TransApplicationLanguage.objects.filter(application=app_label).get()
languages = [lang.code f... | python | {
"resource": ""
} |
q42638 | Manager.log | train | def log(self, msg):
"""
Log a message information adding the master_class and instance_class if available
:param msg:
:return:
"""
if self.master_class and self.instance_class:
logger.info('{0} - {1} - {2} - {3} - lang: {4} msg: {5}'.format(
s... | python | {
"resource": ""
} |
q42639 | Manager.get_field_label | train | def get_field_label(self, trans, field):
"""
Get the field label from the _meta api of the model
:param trans:
:param field:
:return:
"""
try:
# get from the instance
object_field_label = trans._meta.get_field_by_name(field)[0].verbose_nam... | python | {
"resource": ""
} |
q42640 | Manager.get_translatable_children | train | def get_translatable_children(self, obj):
"""
Obtain all the translatable children from "obj"
:param obj:
:return:
"""
collector = NestedObjects(using='default')
collector.collect([obj])
object_list = collector.nested()
items = self.get_elements(o... | python | {
"resource": ""
} |
q42641 | Manager.get_elements | train | def get_elements(self, object_list):
"""
Recursive method to iterate the tree of children in order to flatten it
:param object_list:
:return:
"""
result = []
for item in object_list:
if isinstance(item, list):
result += self.get_elemen... | python | {
"resource": ""
} |
q42642 | Manager.update_model_languages | train | def update_model_languages(self, model_class, languages):
"""
Update the TransModelLanguages model with the selected languages
:param model_class:
:param languages:
:return:
"""
# get the langs we have to add to the TransModelLanguage
qs = TransLanguage.o... | python | {
"resource": ""
} |
q42643 | Manager.add_item_languages | train | def add_item_languages(self, item, languages):
"""
Update the TransItemLanguage model with the selected languages
:param item:
:param languages:
:return:
"""
# get the langs we have to add to the TransModelLanguage
qs = TransLanguage.objects.filter(code__... | python | {
"resource": ""
} |
q42644 | Manager.remove_item_languages | train | def remove_item_languages(self, item, languages):
"""
delete the selected languages from the TransItemLanguage model
:param item:
:param languages:
:return:
"""
# get the langs we have to add to the TransModelLanguage
qs = TransLanguage.objects.filter(cod... | python | {
"resource": ""
} |
q42645 | Manager.get_translation_from_instance | train | def get_translation_from_instance(instance, lang):
"""
Get the translation from the instance in a specific language, hits the db
:param instance:
:param lang:
:return:
"""
try:
translation = get_translation(instance, lang)
except (AttributeErr... | python | {
"resource": ""
} |
q42646 | Manager.create_translations_for_item_and_its_children | train | def create_translations_for_item_and_its_children(self, item, languages=None):
"""
Creates the translations from an item and defined languages and return the id's of the created tasks
:param item: (master)
:param languages:
:return:
"""
if not self.master:
... | python | {
"resource": ""
} |
q42647 | RegistryHive.keys | train | def keys(self):
"""Iterates over the hive's keys.
Yields WinRegKey namedtuples containing:
path: path of the key "RootKey\\Key\\..."
timestamp: date and time of last modification
values: list of values (("ValueKey", "ValueType", ValueValue), ... )
"""
... | python | {
"resource": ""
} |
q42648 | RegistryHive._value_data | train | def _value_data(self, value):
"""Parses binary and unidentified values."""
return codecs.decode(
codecs.encode(self.value_value(value)[1], 'base64'), 'utf8') | python | {
"resource": ""
} |
q42649 | intersection | train | def intersection(*args):
"""
Return the intersection of lists, using the first list to determine item order
"""
if not args:
return []
# remove duplicates from first list whilst preserving order
base = list(OrderedDict.fromkeys(args[0]))
if len(args) == 1:
return base
e... | python | {
"resource": ""
} |
q42650 | union | train | def union(*args):
"""
Return the union of lists, ordering by first seen in any list
"""
if not args:
return []
base = args[0]
for other in args[1:]:
base.extend(other)
return list(OrderedDict.fromkeys(base)) | python | {
"resource": ""
} |
q42651 | random_string | train | def random_string(length):
"""
Generates a random alphanumeric string
"""
# avoid things that could be mistaken ex: 'I' and '1'
letters = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"
return "".join([random.choice(letters) for _ in range(length)]) | python | {
"resource": ""
} |
q42652 | filter_dict | train | def filter_dict(d, keys):
"""
Creates a new dict from an existing dict that only has the given keys
"""
return {k: v for k, v in d.items() if k in keys} | python | {
"resource": ""
} |
q42653 | get_cacheable | train | def get_cacheable(cache_key, cache_ttl, calculate, recalculate=False):
"""
Gets the result of a method call, using the given key and TTL as a cache
"""
if not recalculate:
cached = cache.get(cache_key)
if cached is not None:
return json.loads(cached)
calculated = calcula... | python | {
"resource": ""
} |
q42654 | get_obj_cacheable | train | def get_obj_cacheable(obj, attr_name, calculate, recalculate=False):
"""
Gets the result of a method call, using the given object and attribute name
as a cache
"""
if not recalculate and hasattr(obj, attr_name):
return getattr(obj, attr_name)
calculated = calculate()
setattr(obj, at... | python | {
"resource": ""
} |
q42655 | datetime_to_ms | train | def datetime_to_ms(dt):
"""
Converts a datetime to a millisecond accuracy timestamp
"""
seconds = calendar.timegm(dt.utctimetuple())
return seconds * 1000 + int(dt.microsecond / 1000) | python | {
"resource": ""
} |
q42656 | ms_to_datetime | train | def ms_to_datetime(ms):
"""
Converts a millisecond accuracy timestamp to a datetime
"""
dt = datetime.datetime.utcfromtimestamp(ms / 1000)
return dt.replace(microsecond=(ms % 1000) * 1000).replace(tzinfo=pytz.utc) | python | {
"resource": ""
} |
q42657 | chunks | train | def chunks(iterable, size):
"""
Splits a very large list into evenly sized chunks.
Returns an iterator of lists that are no more than the size passed in.
"""
it = iter(iterable)
item = list(islice(it, size))
while item:
yield item
item = list(islice(it, size)) | python | {
"resource": ""
} |
q42658 | is_owner | train | def is_owner(package, abspath):
"""Determine whether `abspath` belongs to `package`."""
try:
files = package['files']
location = package['location']
except KeyError:
return False
paths = (os.path.abspath(os.path.join(location, f))
for f in files)
return abspath... | python | {
"resource": ""
} |
q42659 | RestURL._get_subfolder | train | def _get_subfolder(self, foldername, returntype,
params=None, file_data=None):
"""Return an object of the requested type with the path relative
to the current object's URL. Optionally, query parameters
may be set."""
newurl = compat.urljoin(self.url, compat.q... | python | {
"resource": ""
} |
q42660 | RestURL._contents | train | def _contents(self):
"""The raw contents of the URL as fetched, this is done lazily.
For non-lazy fetching this is accessed in the object constructor."""
if self.__urldata__ is Ellipsis or self.__cache_request__ is False:
if self._file_data:
# Special-case: do a mu... | python | {
"resource": ""
} |
q42661 | RestURL._json_struct | train | def _json_struct(self):
"""The json data structure in the URL contents, it will cache this
if it makes sense so it doesn't parse over and over."""
if self.__has_json__:
if self.__cache_request__:
if self.__json_struct__ is Ellipsis:
if self._con... | python | {
"resource": ""
} |
q42662 | RestURL.parent | train | def parent(self):
"Get this object's parent"
if self._parent:
return self._parent
# auto-compute parent if needed
elif getattr(self, '__parent_type__', None):
return self._get_subfolder('..' if self._url[2].endswith('/')
... | python | {
"resource": ""
} |
q42663 | Folder._register_service_type | train | def _register_service_type(cls, subclass):
"""Registers subclass handlers of various service-type-specific service
implementations. Look for classes decorated with
@Folder._register_service_type for hints on how this works."""
if hasattr(subclass, '__service_type__'):
c... | python | {
"resource": ""
} |
q42664 | Folder.servicenames | train | def servicenames(self):
"Give the list of services available in this folder."
return set([service['name'].rstrip('/').split('/')[-1]
for service in self._json_struct.get('services', [])]) | python | {
"resource": ""
} |
q42665 | Folder.services | train | def services(self):
"Returns a list of Service objects available in this folder"
return [self._get_subfolder("%s/%s/" %
(s['name'].rstrip('/').split('/')[-1], s['type']),
self._service_type_mapping.get(s['type'], Service)) for s
in self._json_struct.get(... | python | {
"resource": ""
} |
q42666 | MapLayer.QueryLayer | train | def QueryLayer(self, text=None, Geometry=None, inSR=None,
spatialRel='esriSpatialRelIntersects', where=None,
outFields=None, returnGeometry=None, outSR=None,
objectIds=None, time=None, maxAllowableOffset=None,
returnIdsOnly=None):
"""T... | python | {
"resource": ""
} |
q42667 | MapLayer.timeInfo | train | def timeInfo(self):
"""Return the time info for this Map Service"""
time_info = self._json_struct.get('timeInfo', {})
if not time_info:
return None
time_info = time_info.copy()
if 'timeExtent' in time_info:
time_info['timeExtent'] = utils.timetopythonvalue... | python | {
"resource": ""
} |
q42668 | GPExecutionResult.results | train | def results(self):
"Returns a dict of outputs from the GPTask execution."
if self._results is None:
results = self._json_struct['results']
def result_iterator():
for result in results:
datatype = None
conversion = None
... | python | {
"resource": ""
} |
q42669 | GPTask.Execute | train | def Execute(self, *params, **kw):
"""Synchronously execute the specified GP task. Parameters are passed
in either in order or as keywords."""
fp = self.__expandparamstodict(params, kw)
return self._get_subfolder('execute/', GPExecutionResult, fp) | python | {
"resource": ""
} |
q42670 | GPTask.SubmitJob | train | def SubmitJob(self, *params, **kw):
"""Asynchronously execute the specified GP task. This will return a
Geoprocessing Job object. Parameters are passed in either in order
or as keywords."""
fp = self.__expandparamstodict(params, kw)
return self._get_subfolder('submitJob/',... | python | {
"resource": ""
} |
q42671 | NetworkLayer.SolveClosestFacility | train | def SolveClosestFacility(self, facilities=None,
incidents=None,
barriers=None,
polylineBarriers=None,
polygonBarriers=None,
attributeParameterValues=None,
... | python | {
"resource": ""
} |
q42672 | RouteNetworkLayer.Solve | train | def Solve(self, stops=None, barriers=None, returnDirections=None,
returnRoutes=None, returnStops=None, returnBarriers=None,
outSR=None, ignoreInvalidLocations=None, outputLines=None,
findBestSequence=None, preserveFirstStop=None,
preserveLastStop=None, useTimeWind... | python | {
"resource": ""
} |
q42673 | TaskBulksSerializer.save | train | def save(self, **kwargs):
"""
Method that creates the translations tasks for every selected instance
:param kwargs:
:return:
"""
try:
# result_ids = []
manager = Manager()
for item in self.model_class.objects.language(manager.get_main_... | python | {
"resource": ""
} |
q42674 | get_version | train | def get_version():
""" Gets the current version of the package.
"""
version_py = os.path.join(os.path.dirname(__file__), 'deepgram', 'version.py')
with open(version_py, 'r') as fh:
for line in fh:
if line.startswith('__version__'):
return line.split('=')[-1].strip().replace('"', '')
raise ValueError('Fail... | python | {
"resource": ""
} |
q42675 | config | train | def config(env=DEFAULT_ENV, default=None, **overrides):
"""Returns configured REDIS dictionary from REDIS_URL."""
config = {}
s = os.environ.get(env, default)
if s:
config = parse(s)
overrides = dict([(k.upper(), v) for k, v in overrides.items()])
config.update(overrides)
retur... | python | {
"resource": ""
} |
q42676 | hash_filesystem | train | def hash_filesystem(filesystem, hashtype='sha1'):
"""Utility function for running the files iterator at once.
Returns a dictionary.
{'/path/on/filesystem': 'file_hash'}
"""
try:
return dict(filesystem.checksums('/'))
except RuntimeError:
results = {}
logging.warni... | python | {
"resource": ""
} |
q42677 | FileSystem.fsroot | train | def fsroot(self):
"""Returns the file system root."""
if self.osname == 'windows':
return '{}:\\'.format(
self._handler.inspect_get_drive_mappings(self._root)[0][0])
else:
return self._handler.inspect_get_mountpoints(self._root)[0][0] | python | {
"resource": ""
} |
q42678 | FileSystem.mount | train | def mount(self, readonly=True):
"""Mounts the given disk.
It must be called before any other method.
"""
self._handler.add_drive_opts(self.disk_path, readonly=True)
self._handler.launch()
for mountpoint, device in self._inspect_disk():
if readonly:
... | python | {
"resource": ""
} |
q42679 | FileSystem._inspect_disk | train | def _inspect_disk(self):
"""Inspects the disk and returns the mountpoints mapping
as a list which order is the supposed one for correct mounting.
"""
roots = self._handler.inspect_os()
if roots:
self._root = roots[0]
return sorted(self._handler.inspect_g... | python | {
"resource": ""
} |
q42680 | FileSystem.download | train | def download(self, source, destination):
"""Downloads the file on the disk at source into destination."""
self._handler.download(posix_path(source), destination) | python | {
"resource": ""
} |
q42681 | FileSystem.nodes | train | def nodes(self, path):
"""Iterates over the files and directories contained within the disk
starting from the given path.
Yields the path of the nodes.
"""
path = posix_path(path)
yield from (self.path(path, e) for e in self._handler.find(path)) | python | {
"resource": ""
} |
q42682 | FileSystem.checksum | train | def checksum(self, path, hashtype='sha1'):
"""Returns the checksum of the given path."""
return self._handler.checksum(hashtype, posix_path(path)) | python | {
"resource": ""
} |
q42683 | FileSystem.checksums | train | def checksums(self, path, hashtype='sha1'):
"""Iterates over the files hashes contained within the disk
starting from the given path.
The hashtype keyword allows to choose the file hashing algorithm.
Yields the following values:
"C:\\Windows\\System32\\NTUSER.DAT", "hash" ... | python | {
"resource": ""
} |
q42684 | ListenCloselyApp.attend_pendings | train | def attend_pendings(self):
"""
Check all chats created with no agent assigned yet.
Schedule a timer timeout to call it.
"""
chats_attended = []
pending_chats = Chat.pending.all()
for pending_chat in pending_chats:
free_agent = self.strategy.free_agent(... | python | {
"resource": ""
} |
q42685 | ListenCloselyApp.terminate_obsolete | train | def terminate_obsolete(self):
"""
Check chats can be considered as obsolete to terminate them
"""
chats_terminated = []
live_chats = Chat.live.all()
for live_chat in live_chats:
if live_chat.is_obsolete(self.time_obsolete_offset):
live_chat.ter... | python | {
"resource": ""
} |
q42686 | ListenCloselyApp.on_message | train | def on_message(self, message_id_service, contact_id_service, content):
"""
To use as callback in message service backend
"""
try:
live_chat = Chat.live.get(
Q(agent__id_service=contact_id_service) | Q(asker__id_service=contact_id_service))
... | python | {
"resource": ""
} |
q42687 | decode_path | train | def decode_path(file_path):
"""Turn a path name into unicode."""
if file_path is None:
return
if isinstance(file_path, six.binary_type):
file_path = file_path.decode(sys.getfilesystemencoding())
return file_path | python | {
"resource": ""
} |
q42688 | SocketConnector.handle_set_key | train | def handle_set_key(self):
"""Read incoming key from server"""
track_id = self.reader.int()
row = self.reader.int()
value = self.reader.float()
kind = self.reader.byte()
logger.info(" -> track=%s, row=%s, value=%s, type=%s", track_id, row, value, kind)
# Add or up... | python | {
"resource": ""
} |
q42689 | SocketConnector.handle_delete_key | train | def handle_delete_key(self):
"""Read incoming delete key event from server"""
track_id = self.reader.int()
row = self.reader.int()
logger.info(" -> track=%s, row=%s", track_id, row)
# Delete the actual track value
track = self.tracks.get_by_id(track_id)
track.del... | python | {
"resource": ""
} |
q42690 | SocketConnector.handle_set_row | train | def handle_set_row(self):
"""Read incoming row change from server"""
row = self.reader.int()
logger.info(" -> row: %s", row)
self.controller.row = row | python | {
"resource": ""
} |
q42691 | SocketConnector.handle_pause | train | def handle_pause(self):
"""Read pause signal from server"""
flag = self.reader.byte()
if flag > 0:
logger.info(" -> pause: on")
self.controller.playing = False
else:
logger.info(" -> pause: off")
self.controller.playing = True | python | {
"resource": ""
} |
q42692 | TransLanguage.save | train | def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
"""
Overwrite of the save method in order that when setting the language
as main we deactivate any other model selected as main before
:param force_insert:
:param force_update:
:param... | python | {
"resource": ""
} |
q42693 | BaseTransformer.check_data_type | train | def check_data_type(self):
"""Check the type of the transformer and column match.
Args:
column_metadata(dict): Metadata of the column.
Raises a ValueError if the types don't match
"""
metadata_type = self.column_metadata.get('type')
if self.type != metadata_... | python | {
"resource": ""
} |
q42694 | DTTransformer.fit | train | def fit(self, col):
"""Prepare the transformer to convert data.
Args:
col(pandas.DataFrame): Data to transform.
Returns:
None
"""
dates = self.safe_datetime_cast(col)
self.default_val = dates.groupby(dates).count().index[0].timestamp() * 1e9 | python | {
"resource": ""
} |
q42695 | DTTransformer.safe_datetime_cast | train | def safe_datetime_cast(self, col):
"""Parses string values into datetime.
Args:
col(pandas.DataFrame): Data to transform.
Returns:
pandas.Series
"""
casted_dates = pd.to_datetime(col[self.col_name], format=self.date_format, errors='coerce')
if l... | python | {
"resource": ""
} |
q42696 | DTTransformer.to_timestamp | train | def to_timestamp(self, data):
"""Transform a datetime series into linux epoch.
Args:
data(pandas.DataFrame): DataFrame containins a column named as `self.col_name`.
Returns:
pandas.Series
"""
result = pd.Series(index=data.index)
_slice = ~data[se... | python | {
"resource": ""
} |
q42697 | Hsp.chop_sequence | train | def chop_sequence(sequence, limit_length):
"""Input sequence is divided on smaller non-overlapping sequences with set length. """
return [sequence[i:i + limit_length] for i in range(0, len(sequence), limit_length)] | python | {
"resource": ""
} |
q42698 | Hsp.get_tabular_str | train | def get_tabular_str(self):
"""Creates table-like string from fields. """
hsp_string = ""
try:
hsp_list = [
{"length": self.align_length},
{"e-value": self.expect},
{"score": self.score},
{"identities": self.identities},... | python | {
"resource": ""
} |
q42699 | Alignment.best_identities | train | def best_identities(self):
"""Returns identities of the best HSP in alignment. """
if len(self.hsp_list) > 0:
return round(float(self.hsp_list[0].identities) / float(self.hsp_list[0].align_length) * 100, 1) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.