_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q45600 | Russound.close | train | def close(self):
"""
Disconnect from the controller.
"""
logger.info("Closing connection to %s:%s", self._host, self._port)
self._ioloop_future.cancel()
try:
yield from self._ioloop_future
except asyncio.CancelledError:
pass | python | {
"resource": ""
} |
q45601 | Russound.set_zone_variable | train | def set_zone_variable(self, zone_id, variable, value):
"""
Set a zone variable to a new value.
"""
return self._send_cmd("SET %s.%s=\"%s\"" % (
zone_id.device_str(), variable, value)) | python | {
"resource": ""
} |
q45602 | Russound.get_zone_variable | train | def get_zone_variable(self, zone_id, variable):
""" Retrieve the current value of a zone variable. If the variable is
not found in the local cache then the value is requested from the
controller. """
try:
return self._retrieve_cached_zone_variable(zone_id, variable)
... | python | {
"resource": ""
} |
q45603 | Russound.get_cached_zone_variable | train | def get_cached_zone_variable(self, zone_id, variable, default=None):
""" Retrieve the current value of a zone variable from the cache or
return the default value if the variable is not present. """
try:
return self._retrieve_cached_zone_variable(zone_id, variable)
except Unc... | python | {
"resource": ""
} |
q45604 | Russound.unwatch_zone | train | def unwatch_zone(self, zone_id):
""" Remove a zone from the watchlist. """
self._watched_zones.remove(zone_id)
return (yield from
self._send_cmd("WATCH %s OFF" % (zone_id.device_str(), ))) | python | {
"resource": ""
} |
q45605 | Russound.send_zone_event | train | def send_zone_event(self, zone_id, event_name, *args):
""" Send an event to a zone. """
cmd = "EVENT %s!%s %s" % (
zone_id.device_str(), event_name,
" ".join(str(x) for x in args))
return (yield from self._send_cmd(cmd)) | python | {
"resource": ""
} |
q45606 | Russound.set_source_variable | train | def set_source_variable(self, source_id, variable, value):
""" Change the value of a source variable. """
source_id = int(source_id)
return self._send_cmd("SET S[%d].%s=\"%s\"" % (
source_id, variable, value)) | python | {
"resource": ""
} |
q45607 | Russound.get_source_variable | train | def get_source_variable(self, source_id, variable):
""" Get the current value of a source variable. If the variable is not
in the cache it will be retrieved from the controller. """
source_id = int(source_id)
try:
return self._retrieve_cached_source_variable(
... | python | {
"resource": ""
} |
q45608 | Russound.get_cached_source_variable | train | def get_cached_source_variable(self, source_id, variable, default=None):
""" Get the cached value of a source variable. If the variable is not
cached return the default value. """
source_id = int(source_id)
try:
return self._retrieve_cached_source_variable(
... | python | {
"resource": ""
} |
q45609 | Russound.watch_source | train | def watch_source(self, source_id):
""" Add a souce to the watchlist. """
source_id = int(source_id)
r = yield from self._send_cmd(
"WATCH S[%d] ON" % (source_id, ))
self._watched_source.add(source_id)
return r | python | {
"resource": ""
} |
q45610 | Russound.unwatch_source | train | def unwatch_source(self, source_id):
""" Remove a souce from the watchlist. """
source_id = int(source_id)
self._watched_sources.remove(source_id)
return (yield from
self._send_cmd("WATCH S[%d] OFF" % (
source_id, ))) | python | {
"resource": ""
} |
q45611 | BaseContentNegotiatedView.set_renderers | train | def set_renderers(self, request=None, context=None, template_name=None, early=False):
"""
Makes sure that the renderers attribute on the request is up
to date. renderers_for_view keeps track of the view that
is attempting to render the request, so that if the request
has been del... | python | {
"resource": ""
} |
q45612 | BaseContentNegotiatedView.join_template_name | train | def join_template_name(self, template_name, extension):
"""
Appends an extension to a template_name or list of template_names.
"""
if template_name is None:
return None
if isinstance(template_name, (list, tuple)):
return tuple('.'.join([n, extension]) for ... | python | {
"resource": ""
} |
q45613 | AzureProvider.submit | train | def submit(self, command='sleep 1', blocksize=1, job_name="parsl.auto"):
"""Submit command to an Azure instance.
Submit returns an ID that corresponds to the task that was just submitted.
Parameters
----------
command : str
Command to be invoked on the remote side.
... | python | {
"resource": ""
} |
q45614 | AzureProvider.cancel | train | def cancel(self, job_ids):
"""Cancel jobs specified by a list of job ids.
Parameters
----------
list of str
List of identifiers of jobs which should be canceled.
Returns
-------
list of bool
For each entry, True if the cancel operation is... | python | {
"resource": ""
} |
q45615 | save_positions | train | def save_positions(post_data, queryset=None):
"""
Function to update a queryset of position objects with a post data dict.
:post_data: Typical post data dictionary like ``request.POST``, which
contains the keys of the position inputs.
:queryset: Queryset of the model ``ObjectPosition``.
"""
... | python | {
"resource": ""
} |
q45616 | order_by_position | train | def order_by_position(qs, reverse=False):
"""Template filter to return a position-ordered queryset."""
if qs:
# ATTENTION: Django creates an invalid sql statement if two related
# models have both generic positions, so we cannot use
# qs.oder_by('generic_position__position')
posi... | python | {
"resource": ""
} |
q45617 | position_input | train | def position_input(obj, visible=False):
"""Template tag to return an input field for the position of the object."""
if not obj.generic_position.all():
ObjectPosition.objects.create(content_object=obj)
return {'obj': obj, 'visible': visible,
'object_position': obj.generic_position.all()[0... | python | {
"resource": ""
} |
q45618 | position_result_list | train | def position_result_list(change_list):
"""
Returns a template which iters through the models and appends a new
position column.
"""
result = result_list(change_list)
# Remove sortable attributes
for x in range(0, len(result['result_headers'])):
result['result_headers'][x]['sorted'] ... | python | {
"resource": ""
} |
q45619 | register_model_converter | train | def register_model_converter(model, name=None, field='pk', base=IntConverter, queryset=None):
"""
Registers a custom path converter for a model.
:param model: a Django model
:param str name: name to register the converter as
:param str field: name of the lookup field
:param base: base path conv... | python | {
"resource": ""
} |
q45620 | login | train | def login():
" View function which handles an authentication request. "
form = LoginForm(request.form)
# make sure data are valid, but doesn't validate password is right
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
# we use werzeug to validate ... | python | {
"resource": ""
} |
q45621 | logout | train | def logout():
" View function which handles a logout request. "
users.logout()
return redirect(request.referrer or url_for(users._login_manager.login_view)) | python | {
"resource": ""
} |
q45622 | register | train | def register():
" Registration Form. "
form = RegisterForm(request.form)
if form.validate_on_submit():
# create an user instance not yet stored in the database
user = User(
username=form.username.data,
email=form.email.data,
pw_hash=form.password.data)
... | python | {
"resource": ""
} |
q45623 | Project.settings_dir | train | def settings_dir(self):
"""
Directory that contains the the settings for the project
"""
path = os.path.join(self.dir, '.dsb')
utils.create_dir(path)
return os.path.realpath(path) | python | {
"resource": ""
} |
q45624 | Project.read_settings | train | def read_settings(self):
"""
Read the "dsbfile" file
Populates `self.settings`
"""
logger.debug('Reading settings from: %s', self.settings_path)
self.settings = Settings.from_dsbfile(self.settings_path) | python | {
"resource": ""
} |
q45625 | Project.setup_salt_ssh | train | def setup_salt_ssh(self):
"""
Setup `salt-ssh`
"""
self.copy_salt_and_pillar()
self.create_roster_file()
self.salt_ssh_create_dirs()
self.salt_ssh_create_master_file() | python | {
"resource": ""
} |
q45626 | Project.salt_ssh_create_dirs | train | def salt_ssh_create_dirs(self):
"""
Creates the `salt-ssh` required directory structure
"""
logger.debug('Creating salt-ssh dirs into: %s', self.settings_dir)
utils.create_dir(os.path.join(self.settings_dir, 'salt'))
utils.create_dir(os.path.join(self.settings_dir, 'pilla... | python | {
"resource": ""
} |
q45627 | create | train | def create(*units):
"""create this unit within the game as specified"""
ret = []
for unit in units: # implemented using sc2simulator.ScenarioUnit
x, y = unit.position[:2]
pt = Point2D(x=x, y=y)
unit.tag = 0 # forget any tag because a new unit will be created
new = DebugComman... | python | {
"resource": ""
} |
q45628 | Markdown.rewrite_links | train | def rewrite_links(self, func):
"""
Add a callback for rewriting links.
The callback should take a single argument, the url, and
should return a replacement url. The callback function is
called everytime a ``[]()`` or ``<link>`` is processed.
You can use this method as ... | python | {
"resource": ""
} |
q45629 | Markdown.link_attrs | train | def link_attrs(self, func):
"""
Add a callback for adding attributes to links.
The callback should take a single argument, the url, and
should return additional text to be inserted in the link tag,
i.e. ``"target="_blank"``.
You can use this method as a decorator on the... | python | {
"resource": ""
} |
q45630 | xform | train | def xform(value, xformer):
'''
Recursively transforms `value` by calling `xformer` on all
keys & values in dictionaries and all values in sequences. Note
that `xformer` will be passed each value to transform as the
first parameter and other keyword parameters based on type. All
transformers MUST support arb... | python | {
"resource": ""
} |
q45631 | jsonModel._validate_list | train | def _validate_list(self, input_list, schema_list, path_to_root, object_title=''):
'''
a helper method for recursively validating items in a list
:return: input_list
'''
# construct rules for list and items
rules_path_to_root = re.sub('\[\d+\]', '[0]', path_to_root)
... | python | {
"resource": ""
} |
q45632 | jsonModel._validate_number | train | def _validate_number(self, input_number, path_to_root, object_title=''):
'''
a helper method for validating properties of a number
:return: input_number
'''
rules_path_to_root = re.sub('\[\d+\]', '[0]', path_to_root)
input_criteria = self.keyMap[rules_path_to_root]... | python | {
"resource": ""
} |
q45633 | jsonModel._validate_boolean | train | def _validate_boolean(self, input_boolean, path_to_root, object_title=''):
'''
a helper method for validating properties of a boolean
:return: input_boolean
'''
rules_path_to_root = re.sub('\[\d+\]', '[0]', path_to_root)
input_criteria = self.keyMap[rules_path_to_r... | python | {
"resource": ""
} |
q45634 | jsonModel._ingest_dict | train | def _ingest_dict(self, input_dict, schema_dict, path_to_root):
'''
a helper method for ingesting keys, value pairs in a dictionary
:return: valid_dict
'''
valid_dict = {}
# construct path to root for rules
rules_path_to_root = re.sub('\[\d+\]', '[0]', path_to_... | python | {
"resource": ""
} |
q45635 | jsonModel._ingest_list | train | def _ingest_list(self, input_list, schema_list, path_to_root):
'''
a helper method for ingesting items in a list
:return: valid_list
'''
valid_list = []
# construct max list size
max_size = None
rules_path_to_root = re.sub('\[\d+\]', '[0]', path_to_roo... | python | {
"resource": ""
} |
q45636 | jsonModel._ingest_number | train | def _ingest_number(self, input_number, path_to_root):
'''
a helper method for ingesting a number
:return: valid_number
'''
valid_number = 0.0
try:
valid_number = self._validate_number(input_number, path_to_root)
except:
rules_path_t... | python | {
"resource": ""
} |
q45637 | jsonModel._ingest_string | train | def _ingest_string(self, input_string, path_to_root):
'''
a helper method for ingesting a string
:return: valid_string
'''
valid_string = ''
try:
valid_string = self._validate_string(input_string, path_to_root)
except:
rules_path_to... | python | {
"resource": ""
} |
q45638 | jsonModel._ingest_boolean | train | def _ingest_boolean(self, input_boolean, path_to_root):
'''
a helper method for ingesting a boolean
:return: valid_boolean
'''
valid_boolean = False
try:
valid_boolean = self._validate_boolean(input_boolean, path_to_root)
except:
ru... | python | {
"resource": ""
} |
q45639 | jsonModel._reconstruct | train | def _reconstruct(self, path_to_root):
'''
a helper method for finding the schema endpoint from a path to root
:param path_to_root: string with dot path to root from
:return: list, dict, string, number, or boolean at path to root
'''
# split path to root into segments
... | python | {
"resource": ""
} |
q45640 | jsonModel._walk | train | def _walk(self, path_to_root, record_dict):
'''
a helper method for finding the record endpoint from a path to root
:param path_to_root: string with dot path to root from
:param record_dict:
:return: list, dict, string, number, or boolean at path to root
'''
# ... | python | {
"resource": ""
} |
q45641 | jsonModel.validate | train | def validate(self, input_data, path_to_root='', object_title=''):
'''
a core method for validating input against the model
input_data is only returned if all data is valid
:param input_data: list, dict, string, number, or boolean to validate
:param path_to_root: [optio... | python | {
"resource": ""
} |
q45642 | jsonModel.ingest | train | def ingest(self, **kwargs):
'''
a core method to ingest and validate arbitrary keyword data
**NOTE: data is always returned with this method**
for each key in the model, a value is returned according
to the following priority:
1. value in kwar... | python | {
"resource": ""
} |
q45643 | jsonModel.query | train | def query(self, query_criteria, valid_record=None):
'''
a core method for querying model valid data with criteria
**NOTE: input is only returned if all fields & qualifiers are valid for model
:param query_criteria: dictionary with model field names and query qualifiers
... | python | {
"resource": ""
} |
q45644 | url_view | train | def url_view(url_pattern, name=None, priority=None):
"""
Decorator for registering functional views.
Meta decorator syntax has to be used in order to accept arguments.
This decorator does not really do anything that magical:
This:
>>> from urljects import U, url_view
>>> @url_view(U / 'my_... | python | {
"resource": ""
} |
q45645 | url | train | def url(url_pattern, view, kwargs=None, name=None):
"""
This is replacement for ``django.conf.urls.url`` function.
This url auto calls ``as_view`` method for Class based views and resolves
URLPattern objects.
If ``name`` is not specified it will try to guess it.
:param url_pattern: string with... | python | {
"resource": ""
} |
q45646 | view_include | train | def view_include(view_module, namespace=None, app_name=None):
"""
Includes view in the url, works similar to django include function.
Auto imports all class based views that are subclass of ``URLView`` and
all functional views that have been decorated with ``url_view``.
:param view_module: object o... | python | {
"resource": ""
} |
q45647 | copy_file | train | def copy_file(file_name):
"""
Copy a given file from the cache storage
"""
remote_file_path = join(join(expanduser('~'), OCTOGRID_DIRECTORY), file_name)
current_path = join(getcwd(), file_name)
try:
copyfile(remote_file_path, current_path)
except Exception, e:
raise e | python | {
"resource": ""
} |
q45648 | is_cached | train | def is_cached(file_name):
"""
Check if a given file is available in the cache or not
"""
gml_file_path = join(join(expanduser('~'), OCTOGRID_DIRECTORY), file_name)
return isfile(gml_file_path) | python | {
"resource": ""
} |
q45649 | UserManager.register | train | def register(self, app, *args, **kwargs):
" Activate loginmanager and principal. "
if not self._login_manager or self.app != app:
self._login_manager = LoginManager()
self._login_manager.user_callback = self.user_loader
self._login_manager.setup_app(app)
... | python | {
"resource": ""
} |
q45650 | process_star | train | def process_star(filename, output, *, extension, star_name, period, shift,
parameters, period_label, shift_label, **kwargs):
"""Processes a star's lightcurve, prints its coefficients, and saves
its plotted lightcurve to a file. Returns the result of get_lightcurve.
"""
if star_name is N... | python | {
"resource": ""
} |
q45651 | Base.check | train | def check(self, check_url=None):
"""
Checks whether a server is running.
:param str check_url:
URL where to check whether the server is running.
Default is ``"http://{self.host}:{self.port}"``.
"""
if check_url is not None:
self.check_url = s... | python | {
"resource": ""
} |
q45652 | Base.live | train | def live(self, kill_port=False, check_url=None):
"""
Starts a live server in a separate process
and checks whether it is running.
:param bool kill_port:
If ``True``, processes running on the same port as ``self.port``
will be killed.
:param str check_url... | python | {
"resource": ""
} |
q45653 | Base.die | train | def die(self):
"""Stops the server if it is running."""
if self.process:
_log(self.logging,
'Stopping {0} server with PID: {1} running at {2}.'
.format(self.__class__.__name__, self.process.pid,
self.check_url))
... | python | {
"resource": ""
} |
q45654 | url | train | def url(route, resource_id=None, pagination=None, **parameters):
"""
Generates an absolute URL to an API resource.
:param route: One of the routes available (see the header of this file)
:type route: string
:param resource_id: The resource ID you want. If None, it will point to the endpoint.
:t... | python | {
"resource": ""
} |
q45655 | is_nested | train | def is_nested(values):
'''Check if values is composed only by iterable elements.'''
return (all(isinstance(item, Iterable) for item in values)
if isinstance(values, Iterable) else False) | python | {
"resource": ""
} |
q45656 | HTMLElement.get_html_content | train | def get_html_content(self):
"""
Parses the element and subelements and parses any HTML enabled text to
its original HTML form for rendering.
:returns: Parsed HTML enabled text content.
:rtype: str
"""
# Extract full element node content (including subelements)
... | python | {
"resource": ""
} |
q45657 | HTMLElement.convert_html_to_xml | train | def convert_html_to_xml(self):
"""
Parses the HTML parsed texts and converts its tags to XML valid tags.
:returns: HTML enabled text in a XML valid format.
:rtype: str
"""
if hasattr(self, 'content') and self.content != '':
regex = r'<(?!/)(?!!)'
... | python | {
"resource": ""
} |
q45658 | KubernetesProvider._create_deployment_object | train | def _create_deployment_object(self, job_name, job_image,
deployment_name, port=80,
replicas=1,
cmd_string=None,
engine_json_file='~/.ipython/profile_default/security/ipcontroller-engin... | python | {
"resource": ""
} |
q45659 | gen_sites | train | def gen_sites(path):
" Seek sites by path. "
for root, _, _ in walklevel(path, 2):
try:
yield Site(root)
except AssertionError:
continue | python | {
"resource": ""
} |
q45660 | Site.get_info | train | def get_info(self, full=False):
" Return printable information about current site. "
if full:
context = self.as_dict()
return "".join("{0:<25} = {1}\n".format(
key, context[key]) for key in sorted(context.iterkeys()))
return "%s [%s]" % (self.g... | python | {
"resource": ""
} |
q45661 | Site.run_check | train | def run_check(self, template_name=None, service_dir=None):
" Run checking scripts. "
print_header('Check requirements', sep='-')
map(lambda cmd: call("bash %s" % cmd), self._gen_scripts(
'check', template_name=template_name, service_dir=service_dir))
return True | python | {
"resource": ""
} |
q45662 | Site.run_update | train | def run_update(self, template_name=None, service_dir=None):
" Run update scripts. "
LOGGER.info('Site Update start.')
print_header('Update %s' % self.get_name())
map(call, self._gen_scripts(
'update', template_name=template_name, service_dir=service_dir))
LOGGER.info... | python | {
"resource": ""
} |
q45663 | Site.paste_template | train | def paste_template(self, template_name, template=None, deploy_dir=None):
" Paste template. "
LOGGER.debug("Paste template: %s" % template_name)
deploy_dir = deploy_dir or self.deploy_dir
template = template or self._get_template_path(template_name)
self.read([op.join(template, s... | python | {
"resource": ""
} |
q45664 | Config.allLobbySlots | train | def allLobbySlots(self):
"""the current configuration of the lobby's players, defined before the match starts"""
if self.debug:
p = ["Lobby Configuration detail:"] + \
[" %s:%s%s"%(p, " "*(12-len(p.type)), p.name)]
#[" agent: %s"%p for... | python | {
"resource": ""
} |
q45665 | Config.connection | train | def connection(self):
"""identify the remote connection parameters"""
self.getPorts() # acquire if necessary
self.getIPaddresses() # acquire if necessary
return (self.ipAddress, self.ports) | python | {
"resource": ""
} |
q45666 | Config.execPath | train | def execPath(self):
"""the executable application's path"""
vers = self.version.label if self.version else None # executables in Versions folder are stored by baseVersion (modified by game data patches)
return self.installedApp.exec_path(vers) | python | {
"resource": ""
} |
q45667 | Config.installedApp | train | def installedApp(self):
"""identify the propery application to launch, given the configuration"""
try: return self._installedApp
except: # raises if not yet defined
self._installedApp = runConfigs.get() # application/install/platform management
return self._installedAp... | python | {
"resource": ""
} |
q45668 | Config.observers | train | def observers(self):
"""the players who are actually observers"""
ret = []
for player in self.players:
try:
if player.observer: ret.append(player)
except: pass # ignore PlayerRecords which don't have an observer attribute
return ret | python | {
"resource": ""
} |
q45669 | Config.inflate | train | def inflate(self, newData={}):
"""ensure all object attribute values are objects"""
from sc2maptool.functions import selectMap
from sc2maptool.mapRecord import MapRecord
self.__dict__.update(newData)
#if not isinstance(self.state, types.GameStates): self.state = types.Ga... | python | {
"resource": ""
} |
q45670 | Config.load | train | def load(self, cfgFile=None, timeout=None):
"""expect that the data file has already been established"""
#if cfgFile != None: self.cfgFile = cfgFile # if it's specified, use it
if not cfgFile:
cfgs = activeConfigs()
if len(cfgs) > 1: raise Exception("found too many conf... | python | {
"resource": ""
} |
q45671 | Config.loadJson | train | def loadJson(self, data):
"""convert the json data into updating this obj's attrs"""
if not isinstance(data, dict):
data = json.loads(data)
self.__dict__.update(data)
self.inflate() # restore objects from str values
#if self.ports: self._gotPorts = True
retur... | python | {
"resource": ""
} |
q45672 | Config.toJson | train | def toJson(self, data=None, pretty=False):
"""convert the flattened dictionary into json"""
if data==None: data = self.attrs
data = self.flatten(data) # don't send objects as str in json
#if pretty:
ret = json.dumps(data, indent=4, sort_keys=True)
#self.inflate() # restor... | python | {
"resource": ""
} |
q45673 | Config.getVersion | train | def getVersion(self):
"""the executable application's version"""
if isinstance(self.version, versions.Version): return self.version
if self.version: # verify specified version exists
version = versions.Version(self.version) # create this object to allow self._version_ to be specifie... | python | {
"resource": ""
} |
q45674 | Config.getIPaddresses | train | def getIPaddresses(self):
"""identify the IP addresses where this process client will launch the SC2 client"""
if not self.ipAddress:
self.ipAddress = ipAddresses.getAll() # update with IP address
return self.ipAddress | python | {
"resource": ""
} |
q45675 | Config.getPorts | train | def getPorts(self):
"""acquire ports to be used by the SC2 client launched by this process"""
if self.ports: # no need to get ports if ports are al
return self.ports
if not self._gotPorts:
self.ports = [
portpicker.pick_unused_port(), # game_port
... | python | {
"resource": ""
} |
q45676 | Config.requestCreateDetails | train | def requestCreateDetails(self):
"""add configuration to the SC2 protocol create request"""
createReq = sc_pb.RequestCreateGame( # used to advance to Status.initGame state, when hosting
realtime = self.realtime,
disable_fog = self.fogDisabled,
random_seed = int(time... | python | {
"resource": ""
} |
q45677 | Config.returnPorts | train | def returnPorts(self):
"""deallocate specific ports on the current machine"""
if self._gotPorts:
#print("deleting ports >%s<"%(self.ports))
map(portpicker.return_port, self.ports)
self._gotPorts = False
self.ports = [] | python | {
"resource": ""
} |
q45678 | Config.save | train | def save(self, filename=None, debug=False):
"""save a data file such that all processes know the game that is running"""
if not filename: filename = self.name
with open(filename, "w") as f: # save config data file
f.write(self.toJson(self.attrs))
if self.debug or debug:
... | python | {
"resource": ""
} |
q45679 | Config.updateIDs | train | def updateIDs(self, ginfo, tag=None, debug=False):
"""ensure all player's playerIDs are correct given game's info"""
# SC2APIProtocol.ResponseGameInfo attributes:
# map_name
# mod_names
# local_map_path
# player_info
# s... | python | {
"resource": ""
} |
q45680 | Config.whoAmI | train | def whoAmI(self):
"""return the player object that owns this configuration"""
self.inflate() # ensure self.players contains player objects
if self.thePlayer:
for p in self.players:
if p.name != self.thePlayer: continue
return p
elif len(self.pl... | python | {
"resource": ""
} |
q45681 | Session.get_urls | train | def get_urls(self, order="total_clicks desc", offset=None, count=None):
"""Returns a list of URLs you've included in messages.
List is sorted by ``total_clicks``, starting at an optional integer ``offset``, and optionally limited to the first ``count`` items.
"""
req_data = [ None, orde... | python | {
"resource": ""
} |
q45682 | Session.get_message_urls | train | def get_message_urls(self, message_id, order="total_clicks desc"):
"""Returns a list of URLs you've included in a specific message.
List is sorted by ``total_clicks``, starting at an optional integer ``offset``, and optionally limited to the first ``count`` items.
"""
req_data = [ { "me... | python | {
"resource": ""
} |
q45683 | LocalProvider._write_submit_script | train | def _write_submit_script(self, script_string, script_filename):
'''
Load the template string with config values and write the generated submit script to
a submit script file.
Args:
- template_string (string) : The template string to be used for the writing submit script
... | python | {
"resource": ""
} |
q45684 | HgRepo.find_branches | train | def find_branches(self):
"""
Find the branches in the Mercurial repository.
:returns: A generator of :class:`.Revision` objects.
.. note:: Closed branches are not included.
"""
listing = self.context.capture('hg', 'branches')
for line in listing.splitlines():
... | python | {
"resource": ""
} |
q45685 | HgRepo.get_checkout_command | train | def get_checkout_command(self, revision, clean=False):
"""Get the command to update the working tree of the local repository."""
command = ['hg', 'update']
if clean:
command.append('--clean')
command.append('--rev=%s' % revision)
return command | python | {
"resource": ""
} |
q45686 | HgRepo.get_delete_branch_command | train | def get_delete_branch_command(self, branch_name, message, author):
"""Get the command to delete or close a branch in the local repository."""
tokens = ['hg update --rev=%s && hg commit' % quote(branch_name)]
if author:
tokens.append('--user=%s' % quote(author.combined))
token... | python | {
"resource": ""
} |
q45687 | Russound.set_source | train | def set_source(self, controller, zone, source):
""" Set source for a zone - 0 based value for source """
_LOGGER.info("Begin - controller= %s, zone= %s change source to %s.", controller, zone, source)
send_msg = self.create_send_message("F0 @cc 00 7F 00 @zz @kk 05 02 00 00 00 F1 3E 00 00 00 @pr... | python | {
"resource": ""
} |
q45688 | Russound.get_volume | train | def get_volume(self, controller, zone):
""" Gets the volume level which needs to be doubled to get it to the range of 0..100 -
it is located on a 2 byte offset """
volume_level = self.get_zone_info(controller, zone, 2)
if volume_level is not None:
volume_level *= 2
re... | python | {
"resource": ""
} |
q45689 | Russound.create_send_message | train | def create_send_message(self, string_message, controller, zone=None, parameter=None):
""" Creates a message from a string, substituting the necessary parameters,
that is ready to send to the socket """
cc = hex(int(controller) - 1).replace('0x', '') # RNET requires controller value to be zero ... | python | {
"resource": ""
} |
q45690 | Russound.create_response_signature | train | def create_response_signature(self, string_message, zone):
""" Basic helper function to keep code clean for defining a response message signature """
zz = ''
if zone is not None:
zz = hex(int(zone)-1).replace('0x', '') # RNET requires zone value to be zero based
string_mess... | python | {
"resource": ""
} |
q45691 | Russound.send_data | train | def send_data(self, data, delay=COMMAND_DELAY):
""" Send data to connected gateway """
time_since_last_send = time.time() - self._last_send
delay = max(0, delay - time_since_last_send)
time.sleep(delay) # Ensure minim recommended delay since last send
for item in data:
... | python | {
"resource": ""
} |
q45692 | Russound.find_signature | train | def find_signature(self, data_stream, msg_signature):
""" Takes the stream of bytes received and looks for a message that matches the signature
of the expected response """
signature_match_index = None # The message that will be returned if it matches the signature
msg_signature = msg_... | python | {
"resource": ""
} |
q45693 | Russound.calc_checksum | train | def calc_checksum(self, data):
""" Calculate the checksum we need """
output = 0
length = len(data)
for value in data:
output += int(value, 16)
output += length
checksum = hex(output & int('0x007F', 16)).lstrip("0x")
data.append(checksum)
dat... | python | {
"resource": ""
} |
q45694 | crab_factory | train | def crab_factory(**kwargs):
'''
Factory that generates a CRAB client.
A few parameters will be handled by the factory, other parameters will
be passed on to the client.
:param wsdl: `Optional.` Allows overriding the default CRAB wsdl url.
:param proxy: `Optional.` A dictionary of proxy informa... | python | {
"resource": ""
} |
q45695 | BzrRepo.update_context | train | def update_context(self):
"""
Make sure Bazaar respects the configured author.
This method first calls :func:`.Repository.update_context()` and then
it sets the ``$BZR_EMAIL`` environment variable based on the value of
:attr:`~Repository.author` (but only if :attr:`~Repository.a... | python | {
"resource": ""
} |
q45696 | LocalBase.exec_path | train | def exec_path(self, baseVersion=None):
"""Get the exec_path for this platform. Possibly find the latest build."""
if not os.path.isdir(self.data_dir):
raise sc_process.SC2LaunchError("Install Starcraft II at %s or set the SC2PATH environment variable"%(self.data_dir))
if baseVersion==None: # then se... | python | {
"resource": ""
} |
q45697 | LocalBase.start | train | def start(self, version=None, **kwargs):#game_version=None, data_version=None, **kwargs):
"""Launch the game process."""
if not version:
version = self.mostRecentVersion
pysc2Version = lib.Version( # convert to pysc2 Version
version.version,
version.baseVersion,
version.dataH... | python | {
"resource": ""
} |
q45698 | generate_request_access_signature | train | def generate_request_access_signature(parameters, secret_key):
"""
Generate the parameter signature used during third party access requests
"""
# pull out the parameter keys
keys = parameters.keys()
# alphanumerically sort the keys in place
keys.sort()
# create an array of url encoded ... | python | {
"resource": ""
} |
q45699 | has_credentials_stored | train | def has_credentials_stored():
"""
Return 'auth token' string, if the user credentials are already stored
"""
try:
with open(credentials_file, 'r') as f:
token = f.readline().strip()
id = f.readline().strip()
return token
except Exception, e:
retu... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.