code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def call(self, methodname, *args, **kwargs):
for plugin in self._plugins:
method = getattr(plugin, methodname, None)
if method is None:
continue
yield method(*args, **kwargs) | module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block for_statement identifier attribute identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier none if_statement c... | Call a common method on all the plugins, if it exists. |
def frame_apply(obj, func, axis=0, broadcast=None,
raw=False, reduce=None, result_type=None,
ignore_failures=False,
args=None, kwds=None):
axis = obj._get_axis_number(axis)
if axis == 0:
klass = FrameRowApply
elif axis == 1:
klass = FrameColumn... | module function_definition identifier parameters identifier identifier default_parameter identifier integer default_parameter identifier none default_parameter identifier false default_parameter identifier none default_parameter identifier none default_parameter identifier false default_parameter identifier none defaul... | construct and return a row or column based frame apply object |
def cli(yamlfile, format, output, collections):
print(ShExGenerator(yamlfile, format).serialize(output=output, collections=collections)) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call identifier argument_list call attribute call identifier argument_list identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier | Generate a ShEx Schema for a biolink model |
def fatal(*tokens: Token, **kwargs: Any) -> None:
error(*tokens, **kwargs)
sys.exit(1) | module function_definition identifier parameters typed_parameter list_splat_pattern identifier type identifier typed_parameter dictionary_splat_pattern identifier type identifier type none block expression_statement call identifier argument_list list_splat identifier dictionary_splat identifier expression_statement cal... | Print an error message and call ``sys.exit`` |
def _set_axis(self, param, unit):
axisValues = []
for astroObject in self.objectList:
try:
value = eval('astroObject.{0}'.format(param))
except ac.HierarchyError:
value = np.nan
if unit is None:
axisValues.append(value)
... | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier list for_statement identifier attribute identifier identifier block try_statement block expression_statement assignment identifier call identifier argument_list call attribute string string... | this should take a variable or a function and turn it into a list by evaluating on each planet |
async def save(self):
old_tags = list(self._orig_data['tags'])
new_tags = list(self.tags)
self._changed_data.pop('tags', None)
await super(BlockDevice, self).save()
for tag_name in new_tags:
if tag_name not in old_tags:
await self._handler.add_tag(
... | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list attribute identifier... | Save this block device. |
def VCRuntimeRedist(self):
arch_subdir = self.pi.target_dir(x64=True)
if self.vc_ver < 15:
redist_path = self.si.VCInstallDir
vcruntime = 'redist%s\\Microsoft.VC%d0.CRT\\vcruntime%d0.dll'
else:
redist_path = self.si.VCInstallDir.replace('\\Tools', '\\Redist')
... | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier true if_statement comparison_operator attribute identifier identifier integer block expression_statement assign... | Microsoft Visual C++ runtime redistribuable dll |
def check_for_bypass_url(raw_creds, nova_args):
if 'BYPASS_URL' in raw_creds.keys():
bypass_args = ['--bypass-url', raw_creds['BYPASS_URL']]
nova_args = bypass_args + nova_args
return nova_args | module function_definition identifier parameters identifier identifier block if_statement comparison_operator string string_start string_content string_end call attribute identifier identifier argument_list block expression_statement assignment identifier list string string_start string_content string_end subscript ide... | Return a list of extra args that need to be passed on cmdline to nova. |
def header(self):
if self._block_header is None:
self._block_header = BlockHeader()
self._block_header.ParseFromString(self.block.header)
return self._block_header | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier call identifier argument_list expression_statement call attribute attribute identifier identifier identifier argum... | Returns the header of the block |
def _read_color_and_depth_image(self):
frames = self._pipe.wait_for_frames()
if self._depth_align:
frames = self._align.process(frames)
depth_frame = frames.get_depth_frame()
color_frame = frames.get_color_frame()
if not depth_frame or not color_frame:
log... | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement attribute identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifie... | Read a color and depth image from the device. |
def NetFxSDKLibraries(self):
if self.vc_ver < 14.0 or not self.si.NetFxSdkDir:
return []
arch_subdir = self.pi.target_dir(x64=True)
return [os.path.join(self.si.NetFxSdkDir, r'lib\um%s' % arch_subdir)] | module function_definition identifier parameters identifier block if_statement boolean_operator comparison_operator attribute identifier identifier float not_operator attribute attribute identifier identifier identifier block return_statement list expression_statement assignment identifier call attribute attribute iden... | Microsoft .Net Framework SDK Libraries |
def load_inventory_from_cache(self):
try:
self.inventory = self.cache.get_all_data_from_cache()
hosts = self.inventory['_meta']['hostvars']
except Exception as e:
print(
"Invalid inventory file %s. Please rebuild with -refresh-cache option."
... | module function_definition identifier parameters identifier block try_statement block expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier subscript subscript attribute identifier identifier str... | Loads inventory from JSON on disk. |
def translate_detector(self, vector):
vector = np.array(vector, dtype=float)
self.pmts.pos_x += vector[0]
self.pmts.pos_y += vector[1]
self.pmts.pos_z += vector[2]
self.reset_caches() | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier expression_statement augmented_assignment attribute attribute identifier identifier identifier subs... | Translate the detector by a given vector |
def _replace_scalar(self, scalar):
if not is_arg_scalar(scalar):
return scalar
name = scalar[1:]
return self.get_scalar_value(name) | module function_definition identifier parameters identifier identifier block if_statement not_operator call identifier argument_list identifier block return_statement identifier expression_statement assignment identifier subscript identifier slice integer return_statement call attribute identifier identifier argument_l... | Replace scalar name with scalar value |
def from_int(cls, retries, redirect=True, default=None):
if retries is None:
retries = default if default is not None else cls.DEFAULT
if isinstance(retries, Retry):
return retries
redirect = bool(redirect) and None
new_retries = cls(retries, redirect=redirect)
... | module function_definition identifier parameters identifier identifier default_parameter identifier true default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier conditional_expression identifier comparison_operator identifier none attribu... | Backwards-compatibility for the old retries format. |
def print_fatal_results(results, level=0):
print_level(logger.critical, _RED + "[X] Fatal Error: %s", level, results.error) | module function_definition identifier parameters identifier default_parameter identifier integer block expression_statement call identifier argument_list attribute identifier identifier binary_operator identifier string string_start string_content string_end identifier attribute identifier identifier | Print fatal errors that occurred during validation runs. |
def run(
self,
cluster_config,
rg_parser,
partition_measurer,
cluster_balancer,
args,
):
self.cluster_config = cluster_config
self.args = args
with ZK(self.cluster_config) as self.zk:
self.log.debug(
... | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier with_statement with_clause with_item as_pattern c... | Initialize cluster_config, args, and zk then call run_command. |
def log_middleware(store):
def wrapper(next_):
def log_dispatch(action):
print('Dispatch Action:', action)
return next_(action)
return log_dispatch
return wrapper | module function_definition identifier parameters identifier block function_definition identifier parameters identifier block function_definition identifier parameters identifier block expression_statement call identifier argument_list string string_start string_content string_end identifier return_statement call identi... | log all actions to console as they are dispatched |
def merge_chromosome_dfs(df_tuple):
plus_df, minus_df = df_tuple
index_cols = "Chromosome Bin".split()
count_column = plus_df.columns[0]
if plus_df.empty:
return return_other(minus_df, count_column, index_cols)
if minus_df.empty:
return return_other(plus_df, count_column, index_cols)... | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list expression_statement assignment identifier subs... | Merges data from the two strands into strand-agnostic counts. |
def _get_field(xdmf_file, data_item):
shp = _get_dim(data_item)
h5file, group = data_item.text.strip().split(':/', 1)
icore = int(group.split('_')[-2]) - 1
fld = _read_group_h5(xdmf_file.parent / h5file, group).reshape(shp)
return icore, fld | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment pattern_list identifier identifier call attribute call attribute attribute identifier identifier identifier argument_list ident... | Extract field from data item. |
def _compile_pattern(self, rule):
out = ''
for i, part in enumerate(self.syntax.split(rule)):
if i%3 == 0: out += re.escape(part.replace('\\:',':'))
elif i%3 == 1: out += '(?P<%s>' % part if part else '(?:'
else: out += '%s)' % (part or '[^/]+')
ret... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier string string_start string_end for_statement pattern_list identifier identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier block i... | Return a regular expression with named groups for each wildcard. |
def update_password(self, user, password, skip_validation=False):
pwcol = self.options["password_column"]
pwhash = self.bcrypt.generate_password_hash(password)
if not skip_validation:
self.validate_password(user, password, pwhash)
if self.options['prevent_password_reuse']:
... | module function_definition identifier parameters identifier identifier identifier default_parameter identifier false block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier call attribute attribut... | Updates the password of a user |
def delete_blob(call=None, kwargs=None):
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit(
'A container must be specified'
)
if 'blob' not in kwargs:
raise SaltCloudSystemExit(
'A blob must be specified'
)
... | module function_definition identifier parameters default_parameter identifier none default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier dictionary if_statement comparison_operator string string_start string_content string_end identifie... | Delete a blob from a container. |
def parse_unit(prop, dictionary, dt=None):
try:
dt = timezone.parse_datetime(dictionary.get('date_time'))
except TypeError:
dt = None
matches = [k for k in dictionary.keys() if prop in k]
try:
value = dictionary[matches[0]]
unit = re.search(r' \(([^)]+)\)', matches[0])
... | module function_definition identifier parameters identifier identifier default_parameter identifier none block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_en... | Do a fuzzy match for `prop` in the dictionary, taking into account unit suffix. |
def packageOf(self, dotted_name, packagelevel=None):
if '.' not in dotted_name:
return dotted_name
if not self.isPackage(dotted_name):
dotted_name = '.'.join(dotted_name.split('.')[:-1])
if packagelevel:
dotted_name = '.'.join(dotted_name.split('.')[:packagele... | module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement comparison_operator string string_start string_content string_end identifier block return_statement identifier if_statement not_operator call attribute identifier identifier argument_list identifi... | Determine the package that contains ``dotted_name``. |
def transformer_base_vq_ada_32ex_packed():
hparams = transformer_base_v2()
expert_utils.update_hparams_for_vq_gating(hparams)
hparams.moe_num_experts = 32
hparams.gating_type = "vq"
hparams.batch_size = 5072
hparams.ffn_layer = "local_moe"
hparams.shared_embedding_and_softmax_weights = False
hparams.lea... | module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier integer expression_statement assignment attri... | Set of hyperparameters for lm1b packed following tpu params. |
def smsc(self, smscNumber):
if smscNumber != self._smscNumber:
if self.alive:
self.write('AT+CSCA="{0}"'.format(smscNumber))
self._smscNumber = smscNumber | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start str... | Set the default SMSC number to use when sending SMS messages |
def read_plain_boolean(file_obj, count):
return read_bitpacked(file_obj, count << 1, 1, logger.isEnabledFor(logging.DEBUG)) | module function_definition identifier parameters identifier identifier block return_statement call identifier argument_list identifier binary_operator identifier integer integer call attribute identifier identifier argument_list attribute identifier identifier | Read `count` booleans using the plain encoding. |
def build(pattern=None, path='.'):
path = abspath(path)
c = Clay(path)
c.build(pattern) | module function_definition identifier parameters default_parameter identifier none default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list... | Generates a static copy of the sources |
def __find_smallest(self):
minval = sys.maxsize
for i in range(self.n):
for j in range(self.n):
if (not self.row_covered[i]) and (not self.col_covered[j]):
if minval > self.C[i][j]:
minval = self.C[i][j]
return minval | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier for_statement identifier call identifier argument_list attribute identifier identifier block for_statement identifier call identifier argument_list attribute identifier identifier... | Find the smallest uncovered value in the matrix. |
def size_to_content(self):
new_sizing = self.copy_sizing()
new_sizing.minimum_width = 0
new_sizing.maximum_width = 0
axes = self.__axes
if axes and axes.is_valid:
if axes.y_calibration and axes.y_calibration.units:
new_sizing.minimum_width = self.font_... | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier integer expression_state... | Size the canvas item to the proper width. |
def render(self):
tpl = '<xml>\n{data}\n</xml>'
nodes = []
msg_type = '<MsgType><![CDATA[{msg_type}]]></MsgType>'.format(
msg_type=self.type
)
nodes.append(msg_type)
for name, field in self._fields.items():
value = getattr(self, name, field.default... | module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_content escape_sequence escape_sequence string_end expression_statement assignment identifier list expression_statement assignment identifier call attribute string string_start string_... | Render reply from Python object to XML string |
def fig_height(self):
return (
4
+ len(self.data) * len(self.var_names)
- 1
+ 0.1 * sum(1 for j in self.plotters.values() for _ in j.iterator())
) | module function_definition identifier parameters identifier block return_statement parenthesized_expression binary_operator binary_operator binary_operator integer binary_operator call identifier argument_list attribute identifier identifier call identifier argument_list attribute identifier identifier integer binary_o... | Figure out the height of this plot. |
def resolve(self, uri=None, **parts):
if uri:
result = self.__class__(urljoin(str(self), str(uri)))
else:
result = self.__class__(self)
for part, value in parts.items():
if part not in self.__all_parts__:
raise TypeError("Unknown URI component: " + part)
setattr(result, part, value)
return resul... | module function_definition identifier parameters identifier default_parameter identifier none dictionary_splat_pattern identifier block if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list call identifier argument_list ... | Attempt to resolve a new URI given an updated URI, partial or complete. |
async def _reset_vector(self):
self._logger.debug("sensor_graph subsystem task starting")
self.initialized.set()
while True:
stream, reading = await self._inputs.get()
try:
await process_graph_input(self.graph, stream, reading, self._executor)
... | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list while_statement true b... | Background task to initialize this system in the event loop. |
def _parse_check(self, rule):
for check_cls in (checks.FalseCheck, checks.TrueCheck):
check = check_cls()
if rule == str(check):
return check
try:
kind, match = rule.split(':', 1)
except Exception:
if self.raise_error:
... | module function_definition identifier parameters identifier identifier block for_statement identifier tuple attribute identifier identifier attribute identifier identifier block expression_statement assignment identifier call identifier argument_list if_statement comparison_operator identifier call identifier argument_... | Parse a single base check rule into an appropriate Check object. |
def sense_dep(self, target):
self.chipset.rf_configuration(0x02, b"\x0B\x0B\x0A")
return super(Device, self).sense_dep(target) | module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list integer string string_start string_content escape_sequence escape_sequence escape_sequence string_end return_statement call attribute call identifier ... | Search for a DEP Target in active or passive communication mode. |
def close(self):
self._closed = True
if self.receive_task:
self.receive_task.cancel()
if self.connection:
self.connection.close() | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier true if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list if_statement attribute identifier identif... | Close the underlying connection. |
def update_radii(self, radii):
self.radii = np.array(radii, dtype='float32')
prim_radii = self._gen_radii(self.radii)
self._radii_vbo.set_data(prim_radii)
self.widget.update() | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier ... | Update the radii inplace |
def write_file(path, contents):
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w") as file:
file.write(contents) | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier true with_statement with_clause with_item as_pattern call id... | Write contents to a local file. |
def do_down(self, arg):
print "running down migration"
self.manager.run_one(arg, Direction.DOWN) | module function_definition identifier parameters identifier identifier block print_statement string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list identifier attribute identifier identifier | Run down migration with name or numeric id matching arg |
def kwargs_helper(kwargs):
args = []
for param, value in kwargs.items():
param = kw_subst.get(param, param)
args.append((param, value))
return args | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list identi... | This function preprocesses the kwargs dictionary to sanitize it. |
def job_started(self, job, queue):
job.hmset(start=str(datetime.utcnow()), status=STATUSES.RUNNING)
job.tries.hincrby(1)
self.log(self.job_started_message(job, queue))
if hasattr(job, 'on_started'):
job.on_started(queue) | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list keyword_argument identifier call identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier attribute identifier id... | Called just before the execution of the job |
def all(A, ax=None):
if isinstance(A, Poly):
out = numpy.zeros(A.shape, dtype=bool)
B = A.A
for key in A.keys:
out += all(B[key], ax)
return out
return numpy.all(A, ax) | module function_definition identifier parameters identifier default_parameter identifier none block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identi... | Test if all values in A evaluate to True |
def constants(self):
constants = [ ]
for k in self.__slots__:
v = getattr(self, k)
if isinstance(v, IRExpr):
constants.extend(v.constants)
elif isinstance(v, IRConst):
constants.append(v)
return constants | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier attribute identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier if_statement call identifier argument_list ident... | A list of all of the constants that this expression ends up using. |
def _windows_wwns():
ps_cmd = r'Get-WmiObject -ErrorAction Stop ' \
r'-class MSFC_FibrePortHBAAttributes ' \
r'-namespace "root\WMI" | ' \
r'Select -Expandproperty Attributes | ' \
r'%{($_.PortWWN | % {"{0:x2}" -f $_}) -join ""}'
ret = []
cmd_ret = salt.mo... | module function_definition identifier parameters block expression_statement assignment identifier concatenated_string string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_star... | Return Fibre Channel port WWNs from a Windows host. |
def char_pad_trunc(data, maxlen):
new_dataset = []
for sample in data:
if len(sample) > maxlen:
new_data = sample[:maxlen]
elif len(sample) < maxlen:
pads = maxlen - len(sample)
new_data = sample + ['PAD'] * pads
else:
new_data = sample
... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list for_statement identifier identifier block if_statement comparison_operator call identifier argument_list identifier identifier block expression_statement assignment identifier subscript identifie... | We truncate to maxlen or add in PAD tokens |
def map_permissions_check(view_func):
@wraps(view_func)
def wrapper(request, *args, **kwargs):
map_inst = get_object_or_404(Map, pk=kwargs['map_id'])
user = request.user
kwargs['map_inst'] = map_inst
if map_inst.edit_status >= map_inst.EDITORS:
can_edit = map_inst.can... | module function_definition identifier parameters identifier block decorated_definition decorator call identifier argument_list identifier function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifie... | Used for URLs dealing with the map. |
def globals(self):
try:
return vars(__import__(self.module, fromlist=self.module.split('.')))
except ImportError:
if self.warn_import:
warnings.warn(ImportWarning(
'Cannot import module {} for SerializableFunction. Restricting to builtins.'.for... | module function_definition identifier parameters identifier block try_statement block return_statement call identifier argument_list call identifier argument_list attribute identifier identifier keyword_argument identifier call attribute attribute identifier identifier identifier argument_list string string_start strin... | Find the globals of `self` by importing `self.module` |
def cleanup():
for sck in list(Wdb._sockets):
try:
sck.close()
except Exception:
log.warn('Error in cleanup', exc_info=True) | module function_definition identifier parameters block for_statement identifier call identifier argument_list attribute identifier identifier block try_statement block expression_statement call attribute identifier identifier argument_list except_clause identifier block expression_statement call attribute identifier id... | Close all sockets at exit |
def resolve_node_modules(self):
'import the modules specified in init'
if not self.resolved_node_modules:
try:
self.resolved_node_modules = [
importlib.import_module(mod, self.node_package)
for mod in self.node_modules
]... | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end if_statement not_operator attribute identifier identifier block try_statement block expression_statement assignment attribute identifier identifier list_comprehension call attribute ident... | import the modules specified in init |
def retrieve_customer(self, handle, with_additional_data=False):
response = self.request(E.retrieveCustomerRequest(
E.handle(handle),
E.withAdditionalData(int(with_additional_data)),
))
return response.as_model(Customer) | module function_definition identifier parameters identifier identifier default_parameter identifier false block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier c... | Retrieve information of an existing customer. |
def enableGroup(self):
radioButtonListInGroup = PygWidgetsRadioButton.__PygWidgets__Radio__Buttons__Groups__Dicts__[self.group]
for radioButton in radioButtonListInGroup:
radioButton.enable() | module function_definition identifier parameters identifier block expression_statement assignment identifier subscript attribute identifier identifier attribute identifier identifier for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list | Enables all radio buttons in the group. |
def build_source_files(self):
from .files import BuildSourceFileAccessor
return BuildSourceFileAccessor(self, self.dataset, self.source_fs) | module function_definition identifier parameters identifier block import_from_statement relative_import import_prefix dotted_name identifier dotted_name identifier return_statement call identifier argument_list identifier attribute identifier identifier attribute identifier identifier | Return acessors to the build files |
def _get_snapshot(name, suffix, array):
snapshot = name + '.' + suffix
try:
for snap in array.get_volume(name, snap=True):
if snap['name'] == snapshot:
return snapshot
except purestorage.PureError:
return None | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier binary_operator binary_operator identifier string string_start string_content string_end identifier try_statement block for_statement identifier call attribute identifier identifier argumen... | Private function to check snapshot |
def getParameterByType(self, type):
result = None
for parameter in self.getParameters():
typeParam = parameter.getType()
if typeParam == type:
result = parameter
break
return result | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier none for_statement identifier call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement compar... | Searchs a parameter by type and returns it. |
def read_blob(arg):
result = None
if arg == '@-':
result = sys.stdin.read()
elif any(arg.startswith('@{}://'.format(x)) for x in {'http', 'https', 'ftp', 'file'}):
if not requests:
raise error.UserError("You must 'pip install requests' to support @URL arguments.")
try:
... | module function_definition identifier parameters identifier block expression_statement assignment identifier none if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_... | Read a BLOB from given ``@arg``. |
def add_node(self, node):
num_agents = len(self.nodes(type=Agent))
curr_generation = int((num_agents - 1) / float(self.generation_size))
node.generation = curr_generation
if curr_generation == 0 and self.initial_source:
parent = self._select_oldest_source()
else:
... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement assignment identifier call identifier argument_list binary_... | Link to the agent from a parent based on the parent's fitness |
def create(self, model_obj):
model_obj = self._set_auto_fields(model_obj)
identifier = model_obj[self.entity_cls.meta_.id_field.field_name]
with self.conn['lock']:
self.conn['data'][self.schema_name][identifier] = model_obj
return model_obj | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier subscript identifier attribute attribute attribute attribute identifier identifier identifier i... | Write a record to the dict repository |
def _unpack_int_base128(varint, offset):
res = ord(varint[offset])
if ord(varint[offset]) >= 0x80:
offset += 1
res = ((res - 0x80) << 7) + ord(varint[offset])
if ord(varint[offset]) >= 0x80:
offset += 1
res = ((res - 0x80) << 7) + ord(v... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list subscript identifier identifier if_statement comparison_operator call identifier argument_list subscript identifier identifier integer block expression_statement augmente... | Implement Perl unpack's 'w' option, aka base 128 decoding. |
def explained_variance(pred:Tensor, targ:Tensor)->Rank0Tensor:
"Explained variance between `pred` and `targ`."
pred,targ = flatten_check(pred,targ)
var_pct = torch.var(targ - pred) / torch.var(targ)
return 1 - var_pct | module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier type identifier block expression_statement string string_start string_content string_end expression_statement assignment pattern_list identifier identifier call identifier argument_list... | Explained variance between `pred` and `targ`. |
def _bits_to_float(bits, lower=-90.0, middle=0.0, upper=90.0):
for i in bits:
if i:
lower = middle
else:
upper = middle
middle = (upper + lower) / 2
return middle | module function_definition identifier parameters identifier default_parameter identifier unary_operator float default_parameter identifier float default_parameter identifier float block for_statement identifier identifier block if_statement identifier block expression_statement assignment identifier identifier else_cla... | Convert GeoHash bits to a float. |
def _get_interpretation_description_and_output_type(interpretation, dtype):
type_string = dtype.__name__
name = "%s__%s" % (interpretation, type_string)
if not hasattr(_interpretations_class, name):
raise ValueError("No transform available for type '%s' with interpretation '%s'."
... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier binary_operator string string_start string_content string_end tuple identifier identifier if_statement not_operator call iden... | Returns the description and output type for a given interpretation. |
def closeEvent(self, event):
self.visibilityChanged.emit(0)
model = self.paramList.model()
model.hintRequested.disconnect()
model.rowsInserted.disconnect()
model.rowsRemoved.disconnect() | module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list integer expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call a... | Emits a signal to update start values on components |
def close(self):
self.cancel()
self.logger.debug("Closing AMQP connection")
try:
self.connection.close()
except Exception, eee:
self.logger.warning("Received an error while trying to close AMQP connection: " + str(eee)) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end try_statement block expression_statement ca... | Closes the internal connection. |
def polyline(document, coords):
"polyline with more then 2 vertices"
points = []
for i in range(0, len(coords), 2):
points.append("%s,%s" % (coords[i], coords[i+1]))
return setattribs(
document.createElement('polyline'),
points = ' '.join(points),
) | module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier list for_statement identifier call identifier argument_list integer call identifier argument_list identifier integer block expression... | polyline with more then 2 vertices |
async def rename(self, name):
set_node_name = SetNodeName(pyvlx=self.pyvlx, node_id=self.node_id, name=name)
await set_node_name.do_api_call()
if not set_node_name.success:
raise PyVLXException("Unable to rename node")
self.name = name | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier expression_... | Change name of node. |
def popen(command, tempFile):
fileHandle = open(tempFile, 'w')
logger.debug("Running the command: %s" % command)
sts = subprocess.call(command, shell=True, stdout=fileHandle, bufsize=-1)
fileHandle.close()
if sts != 0:
raise RuntimeError("Command: %s exited with non-zero status %i" % (comman... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list binary_operator string string_start strin... | Runs a command and captures standard out in the given temp file. |
def bug_suggestions(self, request, project, pk=None):
try:
job = Job.objects.get(repository__name=project, id=pk)
except ObjectDoesNotExist:
return Response("No job with id: {0}".format(pk), status=HTTP_404_NOT_FOUND)
return Response(get_error_summary(job)) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identif... | Gets a set of bug suggestions for this job |
def add(self, doc):
array = doc.to_array(self.attrs)
if len(array.shape) == 1:
array = array.reshape((array.shape[0], 1))
self.tokens.append(array)
spaces = doc.to_array(SPACY)
assert array.shape[0] == spaces.shape[0]
spaces = spaces.reshape((spaces.shape[0], ... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block expressi... | Add a doc's annotations to the binder for serialization. |
def _get_base_dataframe(df):
if isinstance(df, GroupedDataFrame):
base_df = GroupedDataFrame(
df.loc[:, df.plydata_groups], df.plydata_groups,
copy=True)
else:
base_df = pd.DataFrame(index=df.index)
return base_df | module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list subscript attribute identifier identifier slice attribute identifier identifier attribute identifier identifie... | Remove all columns other than those grouped on |
def observer_update(self, message):
for action in ('added', 'changed', 'removed'):
for item in message[action]:
self.send_json(
{
'msg': action,
'observer': message['observer'],
'primary_key':... | module function_definition identifier parameters identifier identifier block for_statement identifier tuple string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end block for_statement identifier subscript identifier identifier block expre... | Called when update from observer is received. |
def handle_parse_result(self, ctx, opts, args):
if 'sclize' in opts and not SclConvertor:
raise click.UsageError("Please install spec2scl package to "
"perform SCL-style conversion")
if self.name in opts and 'sclize' not in opts:
raise click.Usa... | module function_definition identifier parameters identifier identifier identifier identifier block if_statement boolean_operator comparison_operator string string_start string_content string_end identifier not_operator identifier block raise_statement call attribute identifier identifier argument_list concatenated_stri... | Validate SCL related options before parsing. |
def create_instance(self, nova, image_name, instance_name, flavor):
self.log.debug('Creating instance '
'({}|{}|{})'.format(instance_name, image_name, flavor))
image = nova.glance.find_image(image_name)
flavor = nova.flavors.find(name=flavor)
instance = nova.server... | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content s... | Create the specified instance. |
def setDefaultColorRamp(self, colorRampEnum=ColorRampEnum.COLOR_RAMP_HUE):
self._colorRamp = ColorRampGenerator.generateDefaultColorRamp(colorRampEnum) | module function_definition identifier parameters identifier default_parameter identifier attribute identifier identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier | Returns the color ramp as a list of RGB tuples |
def terminate(self):
for t in self._threads:
t.quit()
self._thread = []
self._workers = [] | module function_definition identifier parameters identifier block for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier list expression_statement assignment attribute identifi... | Terminate all workers and threads. |
def newDocProp(self, name, value):
ret = libxml2mod.xmlNewDocProp(self._o, name, value)
if ret is None:raise treeError('xmlNewDocProp() failed')
__tmp = xmlAttr(_obj=ret)
return __tmp | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier identifier identifier if_statement comparison_operator identifier none block raise_statement call identifi... | Create a new property carried by a document. |
def extract_translations(self, string):
trans = []
for t in Lexer(string.decode("utf-8"), None).tokenize():
if t.token_type == TOKEN_BLOCK:
if not t.contents.startswith(
(self.tranz_tag, self.tranzchoice_tag)):
continue
... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list for_statement identifier call attribute call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end none identifier argument_lis... | Extract messages from Django template string. |
def render_binary(self, context, result):
context.response.app_iter = iter((result, ))
return True | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment attribute attribute identifier identifier identifier call identifier argument_list tuple identifier return_statement true | Return binary responses unmodified. |
def url_dirname(url):
p = six.moves.urllib.parse.urlparse(url)
for e in [private.FILE_EXT_JSON, private.FILE_EXT_YAML]:
if p.path.endswith(e):
return six.moves.urllib.parse.urlunparse(
p[:2]+
(os.path.dirname(p.path),)+
p[3:]
)
... | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute attribute attribute identifier identifier identifier identifier identifier argument_list identifier for_statement identifier list attribute identifier identifier attribute identifier ide... | Return the folder containing the '.json' file |
def _validate(self, writing=False):
if self.brand not in ['jp2 ', 'jpx ']:
msg = ("The file type brand was '{brand}'. "
"It should be either 'jp2 ' or 'jpx '.")
msg = msg.format(brand=self.brand)
if writing:
raise IOError(msg)
e... | module function_definition identifier parameters identifier default_parameter identifier false block if_statement comparison_operator attribute identifier identifier list string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier parenthe... | Validate the box before writing to file. |
def _combined_services(cls):
combined = {}
for parent in reversed(cls.mro()):
combined.update(getattr(parent, "_services_requested", {}))
return combined | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary for_statement identifier call identifier argument_list call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list call identifier ... | A dictionary that collects all _services_requested by all ancestors of this XBlock class. |
def fetchcolumnar(self):
self._wait_to_finish()
if not self._last_operation.is_columnar:
raise NotSupportedError("Server does not support columnar "
"fetching")
batches = []
while True:
batch = (self._last_operation.fetch(
... | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list if_statement not_operator attribute attribute identifier identifier identifier block raise_statement call identifier argument_list concatenated_string string string_start string_cont... | Executes a fetchall operation returning a list of CBatches |
def remove_all_locks(self):
locks = list(self._locks.items())
locks.sort(key=lambda l: l[1].get_last_access())
for l in locks:
self._remove_lock(l[0]) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list keyword_argument identifier lambda la... | Removes all locks and ensures their content is written to disk. |
def collect_modules(self):
try:
res = {}
m = sys.modules
for k in m:
if ('.' in k) or k[0] == '_':
continue
if m[k]:
try:
d = m[k].__dict__
if "version" in ... | module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier dictionary expression_statement assignment identifier attribute identifier identifier for_statement identifier identifier block if_statement boolean_operator parenthesized_expression comparis... | Collect up the list of modules in use |
def OnSafeModeExit(self, event):
self.main_window.main_menu.enable_file_approve(False)
self.main_window.grid.Refresh()
event.Skip() | module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list false expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list expressio... | Safe mode exit event handler |
def profile_rule(self, rule):
rule_str = self.reduce_string(rule)
if rule_str not in self.profile_info:
self.profile_info[rule_str] = 1
else:
self.profile_info[rule_str] += 1 | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment subscript attribute iden... | Bump count of the number of times _rule_ was used |
def search_overlap(self, point_list):
result = set()
for j in point_list:
self.search_point(j, result)
return result | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier identifier return_statement identifier | Returns all intervals that overlap the point_list. |
def _get_exclusive_error_codes(cls, options):
codes = set(ErrorRegistry.get_error_codes())
checked_codes = None
if options.ignore is not None:
ignored = cls._expand_error_codes(options.ignore)
checked_codes = codes - ignored
elif options.select is not None:
... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list expression_statement assignment identifier none if_statement comparison_operator attribute identifier identifier none b... | Extract the error codes from the selected exclusive option. |
def contextMenuEvent(self, event):
menu = QtWidgets.QMenu(self)
for action in self.actions():
menu.addAction(action)
openAsMenu = self.createOpenAsMenu(parent=menu)
menu.insertMenu(self.closeItemAction, openAsMenu)
menu.exec_(event.globalPos()) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier for_statement identifier call attribute identifier identifier argument_list block expression_statement call attribute identifier identifie... | Creates and executes the context menu for the tree view |
def forward(self, method, type, path, data=None):
try:
action = "/{}/{}".format(type, path)
res = yield from self.http_query(method, action, data=data, timeout=None)
except aiohttp.ServerDisconnectedError:
log.error("Connection lost to %s during %s %s", self._id, meth... | module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier none block try_statement block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier identifier expression_state... | Forward a call to the emulator on compute |
def unpack(destdir):
if not nav:
sys.exit(1)
ecode = 0
try:
anchore_print("Unpacking images: " + ' '.join(nav.get_images()))
result = nav.unpack(destdir=destdir)
if not result:
anchore_print_err("no images unpacked")
ecode = 1
else:
... | module function_definition identifier parameters identifier block if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list integer expression_statement assignment identifier integer try_statement block expression_statement call identifier argument_list binary_op... | Unpack and Squash image to local filesystem |
def supported_operations(self):
return tuple(op for op in backend.FILE_OPS if self._operations & op) | module function_definition identifier parameters identifier block return_statement call identifier generator_expression identifier for_in_clause identifier attribute identifier identifier if_clause binary_operator attribute identifier identifier identifier | All file operations supported by the camera. |
def _get_run_by_other_worker(worker):
task_sets = _get_external_workers(worker).values()
return functools.reduce(lambda a, b: a | b, task_sets, set()) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier argument_list return_statement call attribute identifier identifier argument_list lambda lambda_parameters identifier identifier binary_operator... | This returns a set of the tasks that are being run by other worker |
def create_page_from_template(template_file, output_path):
mkdir_p(os.path.dirname(output_path))
shutil.copy(os.path.join(livvkit.resource_dir, template_file), output_path) | module function_definition identifier parameters identifier identifier block expression_statement call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call attribute attribute identifier i... | Copy the correct html template file to the output directory |
def getElementById(id: str) -> Optional[Node]:
elm = Element._elements_with_id.get(id)
return elm | module function_definition identifier parameters typed_parameter identifier type identifier type generic_type identifier type_parameter type identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier return_statement identifier | Get element with ``id``. |
def pk_names(cls):
if cls._cache_pk_names is None:
cls._cache_pk_names = cls._get_primary_key_names()
return cls._cache_pk_names | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list return_statement attribute identifier identifier | Primary key column name list. |
def insertReferenceSet(self, referenceSet):
try:
models.Referenceset.create(
id=referenceSet.getId(),
name=referenceSet.getLocalId(),
description=referenceSet.getDescription(),
assemblyid=referenceSet.getAssemblyId(),
is... | module function_definition identifier parameters identifier identifier block try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list keyword_argument identifier call attribute identifi... | Inserts the specified referenceSet into this repository. |
def WriteBlobs(self, blob_id_data_map):
urns = {self._BlobUrn(blob_id): blob_id for blob_id in blob_id_data_map}
mutation_pool = data_store.DB.GetMutationPool()
existing = aff4.FACTORY.MultiOpen(
urns, aff4_type=aff4.AFF4MemoryStreamBase, mode="r")
for blob_urn, blob_id in iteritems(urns):
... | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary_comprehension pair call attribute identifier identifier argument_list identifier identifier for_in_clause identifier identifier expression_statement assignment identifier call attribute att... | Creates or overwrites blobs. |
def __convert_node(node, default_value='', default_flags=vsflags()):
name = __get_attribute(node, 'Name')
logging.debug('Found %s named %s', node.tagName, name)
converted = {}
converted['name'] = name
converted['switch'] = __get_attribute(node, 'Switch')
converted['comment'] = __get_attribute(no... | module function_definition identifier parameters identifier default_parameter identifier string string_start string_end default_parameter identifier call identifier argument_list block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end expre... | Converts a XML node to a JSON equivalent. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.