code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def add_file(self, path, yaml):
if is_job_config(yaml):
name = self.get_job_name(yaml)
file_data = FileData(path=path, yaml=yaml)
self.files[path] = file_data
self.jobs[name] = file_data
else:
self.files[path] = FileData(path=path, yaml=yaml) | module function_definition identifier parameters identifier identifier identifier block if_statement call identifier argument_list identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument... | Adds given file to the file index |
def reset_sequence(model):
sql = connection.ops.sequence_reset_sql(no_style(), [model])
for cmd in sql:
connection.cursor().execute(cmd) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call identifier argument_list list identifier for_statement identifier identifier block expression_statement call attribute call attribute ... | Reset the ID sequence for a model. |
def _rapply(d, func, *args, **kwargs):
if isinstance(d, (tuple, list)):
return [_rapply(each, func, *args, **kwargs) for each in d]
if isinstance(d, dict):
return {
key: _rapply(value, func, *args, **kwargs) for key, value in iteritems(d)
}
else:
return func(d, *a... | module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement call identifier argument_list identifier tuple identifier identifier block return_statement list_comprehension call identifier argument_list identifier identifier l... | Apply a function to all values in a dictionary or list of dictionaries, recursively. |
def resolveEPICS(self):
kw_name_list = []
kw_ctrlconf_list = []
for line in self.file_lines:
if line.startswith('!!epics'):
el = line.replace('!!epics', '').replace(':', ';;', 1).split(';;')
kw_name_list.append(el[0].strip())
kw_ctrlcon... | module function_definition identifier parameters identifier block expression_statement assignment identifier list expression_statement assignment identifier list for_statement identifier attribute identifier identifier block if_statement call attribute identifier identifier argument_list string string_start string_cont... | extract epics control configs into |
def to_cpu(b:ItemsList):
"Recursively map lists of tensors in `b ` to the cpu."
if is_listy(b): return [to_cpu(o) for o in b]
return b.cpu() if isinstance(b,Tensor) else b | module function_definition identifier parameters typed_parameter identifier type identifier block expression_statement string string_start string_content string_end if_statement call identifier argument_list identifier block return_statement list_comprehension call identifier argument_list identifier for_in_clause iden... | Recursively map lists of tensors in `b ` to the cpu. |
def main():
tar_file = TMPDIR + '/' + BINARY_URL.split('/')[-1]
chksum = TMPDIR + '/' + MD5_URL.split('/')[-1]
if precheck() and os_packages(distro.linux_distribution()):
stdout_message('begin download')
download()
stdout_message('begin valid_checksum')
valid_checksum(tar_fil... | module function_definition identifier parameters block expression_statement assignment identifier binary_operator binary_operator identifier string string_start string_content string_end subscript call attribute identifier identifier argument_list string string_start string_content string_end unary_operator integer exp... | Check Dependencies, download files, integrity check |
def bands(self):
bands = []
for c in self.stars.columns:
if re.search('_mag',c):
bands.append(c)
return bands | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier attribute attribute identifier identifier identifier block if_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier b... | Bandpasses for which StarPopulation has magnitude data |
def refresh_hrefs(self, request):
for item in treenav.MenuItem.objects.all():
item.save()
self.message_user(request, _('Menu item HREFs refreshed successfully.'))
info = self.model._meta.app_label, self.model._meta.model_name
changelist_url = reverse('admin:%s_%s_changelist' ... | module function_definition identifier parameters identifier identifier block for_statement identifier call attribute attribute attribute identifier identifier identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier ... | Refresh all the cached menu item HREFs in the database. |
def query_by_post(postid):
return TabPost2Tag.select().where(
TabPost2Tag.post_id == postid
).order_by(TabPost2Tag.order) | module function_definition identifier parameters identifier block return_statement call attribute call attribute call attribute identifier identifier argument_list identifier argument_list comparison_operator attribute identifier identifier identifier identifier argument_list attribute identifier identifier | Query records by post. |
def make_bundle(bundle, fixed_version=None):
tmp_output_file_name = '%s.%s.%s' % (os.path.join(bundle.bundle_file_root, bundle.bundle_filename), 'temp', bundle.bundle_type)
iter_input = iter_bundle_files(bundle)
output_pipeline = processor_pipeline(bundle.processors, iter_input)
m = md5()
with open(... | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier binary_operator string string_start string_content string_end tuple call attribute attribute identifier identifier identifier argument_list attribute identifier identifier attri... | Does all of the processing required to create a bundle and write it to disk, returning its hash version |
def AreHostsReachable(hostnames, ssh_key):
for hostname in hostnames:
assert(len(hostname))
ssh_ok = [exit_code == 0 for (exit_code, _) in
RunCommandOnHosts('echo test > /dev/null', hostnames, ssh_key)]
return ssh_ok | module function_definition identifier parameters identifier identifier block for_statement identifier identifier block assert_statement parenthesized_expression call identifier argument_list identifier expression_statement assignment identifier list_comprehension comparison_operator identifier integer for_in_clause tup... | Returns list of bools indicating if host reachable via ssh. |
def organisation_logo_path(feature, parent):
_ = feature, parent
organisation_logo_file = setting(
inasafe_organisation_logo_path['setting_key'])
if os.path.exists(organisation_logo_file):
return organisation_logo_file
else:
LOGGER.info(
'The custom organisation logo ... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier expression_list identifier identifier expression_statement assignment identifier call identifier argument_list subscript identifier string string_start string_content string_end if_statement call attr... | Retrieve the full path of used specified organisation logo. |
def compute(self,
text,
lang = "eng"):
params = { "lang": lang, "text": text, "topClustersCount": self._nrOfEventsToReturn }
res = self._er.jsonRequest("/json/getEventForText/enqueueRequest", params)
requestId = res["requestId"]
for i in range(10):
... | module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end i... | compute the list of most similar events for the given text |
def close(self):
if callable(getattr(self._file, 'close', None)):
self._iterator.close()
self._iterator = None
self._unconsumed = None
self.closed = True | module function_definition identifier parameters identifier block if_statement call identifier argument_list call identifier argument_list attribute identifier identifier string string_start string_content string_end none block expression_statement call attribute attribute identifier identifier identifier argument_list... | Disable al operations and close the underlying file-like object, if any |
def keys(self):
keys = self._keys
if keys is None:
keys = tuple(self[i].name for i in self.key_indices)
return keys | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier call identifier generator_expression attribute subscript identifier identifier id... | Return the tuple of field names of key fields. |
def _complete_execution(self, g):
assert g.ready()
self.greenlets.remove(g)
placed = UserCritical(msg='placeholder bogus exception',
hint='report a bug')
if g.successful():
try:
segment = g.get()
if not segment.exp... | module function_definition identifier parameters identifier identifier block assert_statement call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_lis... | Forward any raised exceptions across a channel. |
def skip():
if not settings.platformCompatible():
return False
(output, error) = subprocess.Popen(["osascript", "-e", SKIP], stdout=subprocess.PIPE).communicate() | module function_definition identifier parameters block if_statement not_operator call attribute identifier identifier argument_list block return_statement false expression_statement assignment tuple_pattern identifier identifier call attribute call attribute identifier identifier argument_list list string string_start ... | Tell iTunes to skip a song |
def _is_bright(rgb):
r, g, b = rgb
gray = 0.299 * r + 0.587 * g + 0.114 * b
return gray >= .5 | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier identifier identifier expression_statement assignment identifier binary_operator binary_operator binary_operator float identifier binary_operator float identifier binary_operator float id... | Return whether a RGB color is bright or not. |
def apply_customizations(cls, spec, options):
for key in sorted(spec.keys()):
if isinstance(spec[key], (list, tuple)):
customization = {v.key:v for v in spec[key]}
else:
customization = {k:(Options(**v) if isinstance(v, dict) else v)
... | module function_definition identifier parameters identifier identifier identifier block for_statement identifier call identifier argument_list call attribute identifier identifier argument_list block if_statement call identifier argument_list subscript identifier identifier tuple identifier identifier block expression_... | Apply the given option specs to the supplied options tree. |
def _remove_wrappers(self):
ansible_mitogen.loaders.action_loader.get = action_loader__get
ansible_mitogen.loaders.connection_loader.get = connection_loader__get
ansible.executor.process.worker.WorkerProcess.run = worker__run | module function_definition identifier parameters identifier block expression_statement assignment attribute attribute attribute identifier identifier identifier identifier identifier expression_statement assignment attribute attribute attribute identifier identifier identifier identifier identifier expression_statement... | Uninstall the PluginLoader monkey patches. |
def view(self, request, group, **kwargs):
if request.method == 'POST':
message = request.POST.get('message')
if message is not None and message.strip():
comment = GroupComments(group=group, author=request.user,
message=message.strip... | module function_definition identifier parameters identifier identifier identifier dictionary_splat_pattern identifier block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier call attribute attribute identifier ... | Display and store comments. |
def unit(self):
return Vector(
(self.x / self.magnitude()),
(self.y / self.magnitude()),
(self.z / self.magnitude())
) | module function_definition identifier parameters identifier block return_statement call identifier argument_list parenthesized_expression binary_operator attribute identifier identifier call attribute identifier identifier argument_list parenthesized_expression binary_operator attribute identifier identifier call attri... | Return a Vector instance of the unit vector |
def anyword_substring_search(target_words, query_words):
matches_required = len(query_words)
matches_found = 0
for query_word in query_words:
reply = anyword_substring_search_inner(query_word, target_words)
if reply is not False:
matches_found += 1
else:
retur... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier integer for_statement identifier identifier block expression_statement assignment identifier call identifier argumen... | return True if all query_words match |
def start(self, *args, **kwargs):
self._stop = False
super(Plant, self).start(*args, **kwargs) | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment attribute identifier identifier false expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list list_... | start the instrument thread |
def populate_source(cls, source):
if "name" not in source:
source["name"] = get_url_name(source["url"])
if "verify_ssl" not in source:
source["verify_ssl"] = "https://" in source["url"]
if not isinstance(source["verify_ssl"], bool):
source["verify_ssl"] = sour... | module function_definition identifier parameters identifier identifier block if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list subscript identifi... | Derive missing values of source from the existing fields. |
def download_url(url, filename, headers):
ensure_dirs(filename)
response = requests.get(url, headers=headers, stream=True)
if response.status_code == 200:
with open(filename, 'wb') as f:
for chunk in response.iter_content(16 * 1024):
f.write(chunk) | module function_definition identifier parameters identifier identifier identifier block expression_statement call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifie... | Download a file from `url` to `filename`. |
def project_path(*names):
return os.path.join(os.path.dirname(__file__), *names) | module function_definition identifier parameters list_splat_pattern identifier block return_statement call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier list_splat identifier | Path to a file in the project. |
def unregister(self, recipe):
recipe = self.get_recipe_instance_from_class(recipe)
if recipe.slug in self._registry:
del self._registry[recipe.slug] | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator attribute identifier identifier attribute identifier identifier block delete_statement subscript attribut... | Unregisters a given recipe class. |
def _get_candidates(self, v):
candidates = []
for lshash in self.lshashes:
for bucket_key in lshash.hash_vector(v, querying=True):
bucket_content = self.storage.get_bucket(
lshash.hash_name,
bucket_key,
)
... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list for_statement identifier attribute identifier identifier block for_statement identifier call attribute identifier identifier argument_list identifier keyword_argument identifier true block expres... | Collect candidates from all buckets from all hashes |
def reset(cls):
cls._codecs = {}
c = cls._codec
for (name, encode, decode) in cls._common_codec_data:
cls._codecs[name] = c(encode, decode) | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier dictionary expression_statement assignment identifier attribute identifier identifier for_statement tuple_pattern identifier identifier identifier attribute identifier identifier block expre... | Reset the registry to the standard codecs. |
def el_is_empty(el):
if len(el) == 1 and not isinstance(el[0], (list, tuple)):
return True
subels_are_empty = []
for subel in el:
if isinstance(subel, (list, tuple)):
subels_are_empty.append(el_is_empty(subel))
else:
subels_are_empty.append(not bool(subel))
... | module function_definition identifier parameters identifier block if_statement boolean_operator comparison_operator call identifier argument_list identifier integer not_operator call identifier argument_list subscript identifier integer tuple identifier identifier block return_statement true expression_statement assign... | Return ``True`` if tuple ``el`` represents an empty XML element. |
def reference_year(self, index):
ref_date = self.reference_date(index)
try:
return parse(ref_date).year
except ValueError:
matched = re.search(r"\d{4}", ref_date)
if matched:
return int(matched.group())
else:
return ... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier try_statement block return_statement attribute call identifier argument_list identifier identifier except_clause identifier block expressi... | Return the reference publication year. |
def update_positions(self, positions):
sphs_verts = self.sphs_verts_radii.copy()
sphs_verts += positions.reshape(self.n_spheres, 1, 3)
self.tr.update_vertices(sphs_verts)
self.poslist = positions | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement augmented_assignment identifier call attribute identifier identifier argument_list attribute identifier ide... | Update the sphere positions. |
def common_package_action_options(f):
@click.option(
"-s",
"--skip-errors",
default=False,
is_flag=True,
help="Skip/ignore errors when copying packages.",
)
@click.option(
"-W",
"--no-wait-for-sync",
default=False,
is_flag=True,
... | module function_definition identifier parameters identifier block decorated_definition decorator call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier false keyword_argument identifier true keyword_argum... | Add common options for package actions. |
def _translate_str(self, oprnd1, oprnd2, oprnd3):
assert oprnd1.size and oprnd3.size
op1_var = self._translate_src_oprnd(oprnd1)
op3_var, op3_var_constrs = self._translate_dst_oprnd(oprnd3)
if oprnd3.size > oprnd1.size:
result = smtfunction.zero_extend(op1_var, op3_var.size)
... | module function_definition identifier parameters identifier identifier identifier identifier block assert_statement boolean_operator attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_stateme... | Return a formula representation of a STR instruction. |
def serving_from_csv_input(train_config, args, keep_target):
examples = tf.placeholder(
dtype=tf.string,
shape=(None,),
name='csv_input_string')
features = parse_example_tensor(examples=examples,
train_config=train_config,
keep_ta... | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier tuple none keyword_argument identifier string stri... | Read the input features from a placeholder csv string tensor. |
def _find_usage_network_interfaces(self):
enis = paginate_dict(
self.conn.describe_network_interfaces,
alc_marker_path=['NextToken'],
alc_data_path=['NetworkInterfaces'],
alc_marker_param='NextToken'
)
self.limits['Network interfaces per Region']._... | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute attribute identifier identifier identifier keyword_argument identifier list string string_start string_content string_end keyword_argument identifier list string string_st... | find usage of network interfaces |
def authenticate_credentials(self, userid, password):
credentials = {
get_user_model().USERNAME_FIELD: userid,
'password': password
}
user = authenticate(**credentials)
if user is None:
raise exceptions.AuthenticationFailed(_('Invalid username/password... | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier dictionary pair attribute call identifier argument_list identifier identifier pair string string_start string_content string_end identifier expression_statement assignment identifier call i... | Authenticate the userid and password against username and password. |
def _smooth_hpx_map(hpx_map, sigma):
if hpx_map.hpx.ordering == "NESTED":
ring_map = hpx_map.swap_scheme()
else:
ring_map = hpx_map
ring_data = ring_map.data.copy()
nebins = len(hpx_map.data)
smoothed_data = np.zeros((hpx_map.data.shape))
for i in ... | module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute attribute identifier identifier identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list else_clause... | Smooth a healpix map using a Gaussian |
def quote_code(self, key):
code = self.grid.code_array(key)
quoted_code = quote(code)
if quoted_code is not None:
self.set_code(key, quoted_code) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator ... | Returns string quoted code |
def authenticate_admin(self, transport, account_name, password):
Authenticator.authenticate_admin(self, transport, account_name, password)
auth_token = AuthToken()
auth_token.account_name = account_name
params = {sconstant.E_NAME: account_name,
sconstant.E_PASSWORD: pas... | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier identifier identifier identifier expression_statement assignment identifier call identifier argument_list expression_statement assignment ... | Authenticates administrator using username and password. |
def _blackbox_partial_noise(blackbox, system):
node_tpms = []
for node in system.nodes:
node_tpm = node.tpm_on
for input_node in node.inputs:
if blackbox.hidden_from(input_node, node.index):
node_tpm = marginalize_out([input_node], node_tpm)
... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list for_statement identifier attribute identifier identifier block expression_statement assignment identifier attribute identifier identifier for_statement identifier attribute identifier identifier ... | Noise connections from hidden elements to other boxes. |
def local(reload, port):
import logging
from bottle import run
from app import controller, app
from c7n.resources import load_resources
load_resources()
print("Loaded resources definitions")
logging.basicConfig(level=logging.DEBUG)
logging.getLogger('botocore').setLevel(logging.WARNING)
... | module function_definition identifier parameters identifier identifier block import_statement dotted_name identifier import_from_statement dotted_name identifier dotted_name identifier import_from_statement dotted_name identifier dotted_name identifier dotted_name identifier import_from_statement dotted_name identifier... | run local app server, assumes into the account |
def find(path, saltenv='base'):
ret = []
if saltenv not in __opts__['pillar_roots']:
return ret
for root in __opts__['pillar_roots'][saltenv]:
full = os.path.join(root, path)
if os.path.isfile(full):
with salt.utils.files.fopen(full, 'rb') as fp_:
if salt.... | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier list if_statement comparison_operator identifier subscript identifier string string_start string_content string_end block return_stateme... | Return a dict of the files located with the given path and environment |
def notify(self, data):
LOG.debug('notify received: %s', data)
self._notify_count += 1
if self._cancelled:
LOG.debug('notify skipping due to `cancelled`')
return self
if self._once_done and self._once:
LOG.debug('notify skipping due to `once`')
... | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement augmented_assignment attribute identifier identifier integer if_statement attribute identifie... | Notify this observer that data has arrived |
def _load_weird_container(container_name):
old_container_loading.load_all_containers_from_disk()
container = old_container_loading.get_persisted_container(
container_name)
rotated_container = database_migration.rotate_container_for_alpha(
container)
database.save_new_container(rotated_co... | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifi... | Load a container from persisted containers, whatever that is |
def do_add_signature(input_file, output_file, signature_file):
signature = open(signature_file, 'rb').read()
if len(signature) == 256:
hash_algo = 'sha1'
elif len(signature) == 512:
hash_algo = 'sha384'
else:
raise ValueError()
with open(output_file, 'w+b') as dst:
wi... | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier string string_start string_content string_end identifier argument_list if_statement comparison_operator call identifier argument_list... | Add a signature to the MAR file. |
def readCommaList(fileList):
names=fileList.split(',')
fileList=[]
for item in names:
fileList.append(item)
return fileList | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier list for_statement identifier identifier block expression_statement cal... | Return a list of the files with the commas removed. |
def make(self, url, browsers=None, destination=None, timeout=DEFAULT_TIMEOUT, retries=DEFAULT_RETRIES, **kwargs):
response = self.generate(url, browsers, **kwargs)
return self.download(response['job_id'], destination, timeout, retries) | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none default_parameter identifier identifier default_parameter identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute i... | Generates screenshots for given settings and saves it to specified destination. |
def membuf_tempfile(memfile):
memfile.seek(0, 0)
tmpfd, tmpname = mkstemp(suffix='.rar')
tmpf = os.fdopen(tmpfd, "wb")
try:
while True:
buf = memfile.read(BSIZE)
if not buf:
break
tmpf.write(buf)
tmpf.close()
except:
tmpf.cl... | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list integer integer expression_statement assignment pattern_list identifier identifier call identifier argument_list keyword_argument identifier string string_start string_content string... | Write in-memory file object to real file. |
def _ProcessImage(self, tag, wall_time, step, image):
event = ImageEvent(wall_time=wall_time,
step=step,
encoded_image_string=image.encoded_image_string,
width=image.width,
height=image.height)
self.images.AddItem(tag, e... | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier... | Processes an image by adding it to accumulated state. |
def toggle_sensor(request, sensorname):
if service.read_only:
service.logger.warning("Could not perform operation: read only mode enabled")
raise Http404
source = request.GET.get('source', 'main')
sensor = service.system.namespace[sensorname]
sensor.status = not sensor.status
service... | module function_definition identifier parameters identifier identifier block if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end raise_statement identifier expression_statement assig... | This is used only if websocket fails |
def doc(elt):
"Show `show_doc` info in preview window along with link to full docs."
global use_relative_links
use_relative_links = False
elt = getattr(elt, '__func__', elt)
md = show_doc(elt, markdown=False)
if is_fastai_class(elt):
md += f'\n\n<a href="{get_fn_link(elt)}" target="_blan... | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end global_statement identifier expression_statement assignment identifier false expression_statement assignment identifier call identifier argument_list identifier string string_start string... | Show `show_doc` info in preview window along with link to full docs. |
def parse_macro_params(token):
try:
bits = token.split_contents()
tag_name, macro_name, values = bits[0], bits[1], bits[2:]
except IndexError:
raise template.TemplateSyntaxError(
"{0} tag requires at least one argument (macro name)".format(
token.contents.spli... | module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment pattern_list identifier identifier identifier expression_list subscript identifier integer subscript identif... | Common parsing logic for both use_macro and macro_block |
def fitness(self, width, height):
assert(width > 0 and height >0)
if width > max(self.width, self.height) or\
height > max(self.height, self.width):
return None
if self._waste_management:
if self._waste.fitness(width, height) is not None:
retur... | module function_definition identifier parameters identifier identifier identifier block assert_statement parenthesized_expression boolean_operator comparison_operator identifier integer comparison_operator identifier integer if_statement boolean_operator comparison_operator identifier call identifier argument_list attr... | Search for the best fitness |
def _scrub_generated_timestamps(self, target_workdir):
for root, _, filenames in safe_walk(target_workdir):
for filename in filenames:
source = os.path.join(root, filename)
with open(source, 'r') as f:
lines = f.readlines()
if len(lines) < 1:
return
with ope... | module function_definition identifier parameters identifier identifier block for_statement pattern_list identifier identifier identifier call identifier argument_list identifier block for_statement identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier iden... | Remove the first line of comment from each file if it contains a timestamp. |
def _str(value, depth):
output = []
if depth >0 and _get(value, CLASS) in data_types:
for k, v in value.items():
output.append(str(k) + "=" + _str(v, depth - 1))
return "{" + ",\n".join(output) + "}"
elif depth >0 and is_list(value):
for v in value:
output.app... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list if_statement boolean_operator comparison_operator identifier integer comparison_operator call identifier argument_list identifier identifier identifier block for_statement pattern_list identifier... | FOR DEBUGGING POSSIBLY RECURSIVE STRUCTURES |
def __set_transaction_detail(self, *args, **kwargs):
customer_transaction_id = kwargs.get('customer_transaction_id', None)
if customer_transaction_id:
transaction_detail = self.client.factory.create('TransactionDetail')
transaction_detail.CustomerTransactionId = customer_transact... | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end none if_statement identifier block expression_st... | Checks kwargs for 'customer_transaction_id' and sets it if present. |
def list_build_set_records(id=None, name=None, page_size=200, page_index=0, sort="", q=""):
content = list_build_set_records_raw(id, name, page_size, page_index, sort, q)
if content:
return utils.format_json_list(content) | module function_definition identifier parameters default_parameter identifier none default_parameter identifier none default_parameter identifier integer default_parameter identifier integer default_parameter identifier string string_start string_end default_parameter identifier string string_start string_end block exp... | List all build set records for a BuildConfigurationSet |
def _compute_error(self):
self._err = np.sum(np.multiply(self._R_k, self._C_k.T), axis=0) - self._d | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier binary_operator call attribute identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier attribute attribute identifier identifie... | Evaluate the absolute error of the Nystroem approximation for each column |
def st_atime(self):
atime = self._st_atime_ns / 1e9
return atime if self.use_float else int(atime) | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator attribute identifier identifier float return_statement conditional_expression identifier attribute identifier identifier call identifier argument_list identifier | Return the access time in seconds. |
def arm(self, value):
if value:
return api.request_system_arm(self.blink, self.network_id)
return api.request_system_disarm(self.blink, self.network_id) | module function_definition identifier parameters identifier identifier block if_statement identifier block return_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier return_statement call attribute identifier identifier argument_list attribute ide... | Arm or disarm system. |
def teecsv(table, source=None, encoding=None, errors='strict', write_header=True,
**csvargs):
source = write_source_from_arg(source)
csvargs.setdefault('dialect', 'excel')
return teecsv_impl(table, source=source, encoding=encoding,
errors=errors, write_header=write_header,
... | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier string string_start string_content string_end default_parameter identifier true dictionary_splat_pattern identifier block expression_statement assignment identifie... | Returns a table that writes rows to a CSV file as they are iterated over. |
def cygpath(filename):
if sys.platform == 'cygwin':
proc = Popen(['cygpath', '-am', filename], stdout=PIPE)
return proc.communicate()[0].strip()
else:
return filename | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list list string string_start string_content string_end string string... | Convert a cygwin path into a windows style path |
def load_or_create_config(self, filename, config=None):
os.makedirs(os.path.dirname(os.path.expanduser(filename)), exist_ok=True)
if os.path.exists(filename):
return self.load(filename)
if(config == None):
config = self.random_config()
self.save(filename, config)
... | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argumen... | Loads a config from disk. Defaults to a random config if none is specified |
def limit(self, limit):
query = self._copy()
query._limit = limit
return query | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier identifier return_statement identifier | Apply a LIMIT to the query and return the newly resulting Query. |
def geometric_mean(data):
if not data:
raise StatisticsError('geometric_mean requires at least one data point')
data = [x if x > 0 else math.e if x == 0 else 1.0 for x in data]
return math.pow(math.fabs(functools.reduce(operator.mul, data)), 1.0 / len(data)) | module function_definition identifier parameters identifier block if_statement not_operator identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier list_comprehension conditional_expression identifier comparison_operator ide... | Return the geometric mean of data |
def networks(self, role="all", full="all"):
if full not in ["all", True, False]:
raise ValueError(
"full must be boolean or all, it cannot be {}".format(full)
)
if full == "all":
if role == "all":
return Network.query.all()
... | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier string string_start string_content string_end block if_statement comparison_operator identifier list string string_start string_content string_end true fals... | All the networks in the experiment. |
def list_datasources(self, source_id):
target_url = self.client.get_url('DATASOURCE', 'GET', 'multi', {'source_id': source_id})
return base.Query(self.client.get_manager(Datasource), target_url) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end string string_start string_content s... | Filterable list of Datasources for a Source. |
def debugger():
sdb = _current[0]
if sdb is None or not sdb.active:
sdb = _current[0] = Sdb()
return sdb | module function_definition identifier parameters block expression_statement assignment identifier subscript identifier integer if_statement boolean_operator comparison_operator identifier none not_operator attribute identifier identifier block expression_statement assignment identifier assignment subscript identifier i... | Return the current debugger instance, or create if none. |
def cublasSsymm(handle, side, uplo, m, n, alpha, A, lda, B, ldb, beta, C, ldc):
status = _libcublas.cublasSsymm_v2(handle,
_CUBLAS_SIDE_MODE[side],
_CUBLAS_FILL_MODE[uplo],
m, n, ctypes.byref(ctype... | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier subscript identif... | Matrix-matrix product for symmetric matrix. |
def create_bzip2 (archive, compression, cmd, verbosity, interactive, filenames):
if len(filenames) > 1:
raise util.PatoolError('multi-file compression not supported in Python bz2')
try:
with bz2.BZ2File(archive, 'wb') as bz2file:
filename = filenames[0]
with open(filename... | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block if_statement comparison_operator call identifier argument_list identifier integer block raise_statement call attribute identifier identifier argument_list string string_start string_content string_en... | Create a BZIP2 archive with the bz2 Python module. |
def indent(text: str, num: int = 2) -> str:
lines = text.splitlines()
return "\n".join(indent_iterable(lines, num=num)) | module function_definition identifier parameters typed_parameter identifier type identifier typed_default_parameter identifier type identifier integer type identifier block expression_statement assignment identifier call attribute identifier identifier argument_list return_statement call attribute string string_start s... | Indent a piece of text. |
def _get_drive_api(credentials):
http = httplib2.Http()
http = credentials.authorize(http)
service = discovery.build('drive', 'v2', http=http)
service.credentials = credentials
return service | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribu... | For a given set of credentials, return a drive API object. |
def makeUnicodeToGlyphNameMapping(self):
compiler = self.context.compiler
cmap = None
if compiler is not None:
table = compiler.ttFont.get("cmap")
if table is not None:
cmap = table.getBestCmap()
if cmap is None:
from ufo2ft.util import... | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier none if_statement comparison_operator identifier none block expression_statement assignment identifier call attribu... | Return the Unicode to glyph name mapping for the current font. |
def re_general(Vel, Area, PerimWetted, Nu):
ut.check_range([Vel, ">=0", "Velocity"], [Nu, ">0", "Nu"])
return 4 * radius_hydraulic_general(Area, PerimWetted).magnitude * Vel / Nu | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call attribute identifier identifier argument_list list identifier string string_start string_content string_end string string_start string_content string_end list identifier string string_start strin... | Return the Reynolds Number for a general cross section. |
def _load(self, dataset_spec):
for idx, ds in enumerate(dataset_spec):
self.append(ds, idx) | module function_definition identifier parameters identifier identifier block for_statement pattern_list identifier identifier call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier identifier | Actual loading of datasets |
def getWaitingFeedbacks(self):
feedbacks = []
offset = 0
amount = self.__ask__('doGetWaitingFeedbacksCount')
while amount > 0:
rc = self.__ask__('doGetWaitingFeedbacks',
offset=offset, packageSize=200)
feedbacks.extend(rc['feWaitList'... | module function_definition identifier parameters identifier block expression_statement assignment identifier list expression_statement assignment identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end while_statement... | Return all waiting feedbacks from buyers. |
def add_timeframed_query_manager(sender, **kwargs):
if not issubclass(sender, TimeFramedModel):
return
if _field_exists(sender, 'timeframed'):
raise ImproperlyConfigured(
"Model '%s' has a field named 'timeframed' "
"which conflicts with the TimeFramedModel manager."
... | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block if_statement not_operator call identifier argument_list identifier identifier block return_statement if_statement call identifier argument_list identifier string string_start string_content string_end block raise_state... | Add a QueryManager for a specific timeframe. |
def len(self):
def stream_len(stream):
cur = stream.tell()
try:
stream.seek(0, 2)
return stream.tell() - cur
finally:
stream.seek(cur)
return sum(stream_len(s) for s in self.streams) | module function_definition identifier parameters identifier block function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list try_statement block expression_statement call attribute identifier identifier argument_list integer i... | Length of the data stream |
def create_bokeh_server(io_loop, files, argvs, host, port):
from bokeh.server.server import Server
from bokeh.command.util import build_single_handler_applications
apps = build_single_handler_applications(files, argvs)
kwargs = {
'io_loop':io_loop,
'generate_session_ids':True,
'r... | module function_definition identifier parameters identifier identifier identifier identifier identifier block import_from_statement dotted_name identifier identifier identifier dotted_name identifier import_from_statement dotted_name identifier identifier identifier dotted_name identifier expression_statement assignmen... | Start bokeh server with applications paths |
def master_call(self, **kwargs):
load = kwargs
load['cmd'] = self.client
channel = salt.transport.client.ReqChannel.factory(self.opts,
crypt='clear',
usage='master_call')
... | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier expression_statement assignment i... | Execute a function through the master network interface. |
def set(self, key, value):
task = Task.current_task()
try:
context = task._context
except AttributeError:
task._context = context = {}
context[key] = value | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list try_statement block expression_statement assignment identifier attribute identifier identifier except_clause identifier block expression_s... | Set a value in the task context |
def show_data_file(fname):
txt = '<H2>' + fname + '</H2>'
print (fname)
txt += web.read_csv_to_html_table(fname, 'Y')
txt += '</div>\n'
return txt | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator binary_operator string string_start string_content string_end identifier string string_start string_content string_end expression_statement call identifier argument_list identifier expression_sta... | shows a data file in CSV format - all files live in CORE folder |
def beginning_of_line(event):
" Move to the start of the current line. "
buff = event.current_buffer
buff.cursor_position += buff.document.get_start_of_line_position(after_whitespace=False) | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier attribute identifier identifier expression_statement augmented_assignment attribute identifier identifier call attribute attribute identifier id... | Move to the start of the current line. |
def on_close(self):
log.info('WebSocket connection closed: code=%s, reason=%r', self.close_code, self.close_reason)
if self.connection is not None:
self.application.client_lost(self.connection) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier attribute identifier identifier if_statement comparison_operator attribute identifier identifier none bl... | Clean up when the connection is closed. |
def list_files(dirname, extension=None):
f = []
for (dirpath, dirnames, filenames) in os.walk(dirname):
f.extend(filenames)
break
if extension is not None:
filtered = []
for filename in f:
fn, ext = os.path.splitext(filename)
if ext.lower() == '.' + ex... | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier list for_statement tuple_pattern identifier identifier identifier call attribute identifier identifier argument_list identifier block expression_statement call attribute identif... | List all files in directory `dirname`, option to filter on file extension |
def _write_incron_lines(user, lines):
if user == 'system':
ret = {}
ret['retcode'] = _write_file(_INCRON_SYSTEM_TAB, 'salt', ''.join(lines))
return ret
else:
path = salt.utils.files.mkstemp()
with salt.utils.files.fopen(path, 'wb') as fp_:
fp_.writelines(salt.... | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier dictionary expression_statement assignment subscript identifier string string_start string_content strin... | Takes a list of lines to be committed to a user's incrontab and writes it |
def load( self, stats ):
rows = self.rows
for func, raw in stats.iteritems():
try:
rows[func] = row = PStatRow( func,raw )
except ValueError, err:
log.info( 'Null row: %s', func )
for row in rows.itervalues():
row.weave( rows )
... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block try_statement block expression_statement assignment subscript ... | Build a squaremap-compatible model from a pstats class |
def _FieldSkipper():
WIRETYPE_TO_SKIPPER = [
_SkipVarint,
_SkipFixed64,
_SkipLengthDelimited,
_SkipGroup,
_EndGroup,
_SkipFixed32,
_RaiseInvalidWireType,
_RaiseInvalidWireType,
]
wiretype_mask = wire_format.TAG_TYPE_MASK
def SkipField(buffer, pos, end, tag_byt... | module function_definition identifier parameters block expression_statement assignment identifier list identifier identifier identifier identifier identifier identifier identifier identifier expression_statement assignment identifier attribute identifier identifier function_definition identifier parameters identifier i... | Constructs the SkipField function. |
def filter_archives(ctx, prefix, pattern, engine):
_generate_api(ctx)
for i, match in enumerate(ctx.obj.api.filter(
pattern, engine, prefix=prefix)):
click.echo(match, nl=False)
print('') | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call identifier argument_list identifier for_statement pattern_list identifier identifier call identifier argument_list call attribute attribute attribute identifier identifier identifier identifier a... | List all archives matching filter criteria |
def extract_smiles(s):
smiles = []
for t in s.split():
if len(t) > 2 and SMILES_RE.match(t) and not t.endswith('.') and bracket_level(t) == 0:
smiles.append(t)
return smiles | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier call attribute identifier identifier argument_list block if_statement boolean_operator boolean_operator boolean_operator comparison_operator call identifier argument_list identifier... | Return a list of SMILES identifiers extracted from the string. |
def _check_pid(self, allow_reset=False):
if not self.pid == current_process().pid:
if allow_reset:
self.reset()
else:
raise RuntimeError("Forbidden operation in multiple processes") | module function_definition identifier parameters identifier default_parameter identifier false block if_statement not_operator comparison_operator attribute identifier identifier attribute call identifier argument_list identifier block if_statement identifier block expression_statement call attribute identifier identif... | Check process id to ensure integrity, reset if in new process. |
def deleteSelected(self):
'Delete all selected rows.'
ndeleted = self.deleteBy(self.isSelected)
nselected = len(self._selectedRows)
self._selectedRows.clear()
if ndeleted != nselected:
error('expected %s' % nselected) | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier ar... | Delete all selected rows. |
def _get_top_file_envs():
try:
return __context__['saltutil._top_file_envs']
except KeyError:
try:
st_ = salt.state.HighState(__opts__,
initial_pillar=__pillar__)
top = st_.get_top()
if top:
envs = list(st... | module function_definition identifier parameters block try_statement block return_statement subscript identifier string string_start string_content string_end except_clause identifier block try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_... | Get all environments from the top file |
def _access_rule(method,
ip=None,
port=None,
proto='tcp',
direction='in',
port_origin='d',
ip_origin='d',
comment=''):
if _status_csf():
if ip is None:
return {'error': 'You must suppl... | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier string string_start string_content string_end default_parameter identifier string string_start string_content string_end default_parameter identifier string string... | Handles the cmd execution for allow and deny commands. |
def scan():
cflib.crtp.init_drivers(enable_debug_driver=False)
print('Scanning interfaces for Crazyflies...')
available = cflib.crtp.scan_interfaces()
interfaces = [uri for uri, _ in available]
if not interfaces:
return None
return choose(interfaces, 'Crazyflies found:', 'Select interfac... | module function_definition identifier parameters block expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier false expression_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifie... | Scan for Crazyflie and return its URI. |
async def status(cls):
rqst = Request(cls.session, 'GET', '/manager/status')
rqst.set_json({
'status': 'running',
})
async with rqst.fetch() as resp:
return await resp.json() | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier... | Returns the current status of the configured API server. |
def cleanup(self):
for item in self.server_map:
self.member_del(item, reconfig=False)
self.server_map.clear() | module function_definition identifier parameters identifier block for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier false expression_statement call attribute attribute identifier identifier identi... | remove all members without reconfig |
def shaped_metadata(self):
if not self.is_shaped:
return None
return tuple(json_description_metadata(s.pages[0].is_shaped)
for s in self.series if s.kind.lower() == 'shaped') | module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block return_statement none return_statement call identifier generator_expression call identifier argument_list attribute subscript attribute identifier identifier integer identifier for_in_clause... | Return tifffile metadata from JSON descriptions as dicts. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.