code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def make_table_map(table, headers):
header_parts = {}
for i, h in enumerate(headers):
header_parts[h] = 'row[{}]'.format(i)
body_code = 'lambda row: [{}]'.format(','.join(header_parts.get(c.name, 'None') for c in table.columns))
header_code = 'lambda row: [{}]'.format(
','.join(header_parts.get(c.name, "'{}'".format(c.name)) for c in table.columns))
return eval(header_code), eval(body_code) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier call identifier argument_list identifier block expression_statement assignment subscript identifier identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list call attribute string string_start string_content string_end identifier generator_expression call attribute identifier identifier argument_list attribute identifier identifier string string_start string_content string_end for_in_clause identifier attribute identifier identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list call attribute string string_start string_content string_end identifier generator_expression call attribute identifier identifier argument_list attribute identifier identifier call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier for_in_clause identifier attribute identifier identifier return_statement expression_list call identifier argument_list identifier call identifier argument_list identifier | Create a function to map from rows with the structure of the headers to the structure of the table. |
def reset(self):
self.terms = OrderedDict()
self.y = None
self.backend = None
self.added_terms = []
self._added_priors = {}
self.completes = []
self.clean_data = None | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call identifier argument_list expression_statement assignment attribute identifier identifier none expression_statement assignment attribute identifier identifier none expression_statement assignment attribute identifier identifier list expression_statement assignment attribute identifier identifier dictionary expression_statement assignment attribute identifier identifier list expression_statement assignment attribute identifier identifier none | Reset list of terms and y-variable. |
def remove_bad(string):
remove = [':', ',', '(', ')', ' ', '|', ';', '\'']
for c in remove:
string = string.replace(c, '_')
return string | module function_definition identifier parameters identifier block expression_statement assignment identifier list 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_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content escape_sequence string_end for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end return_statement identifier | remove problem characters from string |
def archs(self, _args):
print('{Style.BRIGHT}Available target architectures are:'
'{Style.RESET_ALL}'.format(Style=Out_Style))
for arch in self.ctx.archs:
print(' {}'.format(arch.arch)) | module function_definition identifier parameters identifier identifier block expression_statement call identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list keyword_argument identifier identifier for_statement identifier attribute attribute identifier identifier identifier block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier | List the target architectures available to be built for. |
def dict_to_pendulum(d: Dict[str, Any],
pendulum_class: ClassType) -> DateTime:
return pendulum.parse(d['iso']) | module function_definition identifier parameters typed_parameter identifier type generic_type identifier type_parameter type identifier type identifier typed_parameter identifier type identifier type identifier block return_statement call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end | Converts a ``dict`` object back to a ``Pendulum``. |
def __display_stats(self):
self.display('unify.tmpl', processed=self.total,
matched=self.matched,
unified=self.total - self.matched) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier binary_operator attribute identifier identifier attribute identifier identifier | Display some stats regarding unify process |
def main():
logging.basicConfig(format=LOGGING_FORMAT)
parser = argparse.ArgumentParser(description=main.__doc__)
add_debug(parser)
add_app(parser)
add_env(parser)
add_region(parser)
args = parser.parse_args()
logging.getLogger(__package__.split('.')[0]).setLevel(args.debug)
assert destroy_elb(**vars(args)) | module function_definition identifier parameters block expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier expression_statement call identifier argument_list identifier expression_statement call identifier argument_list identifier expression_statement call identifier argument_list identifier expression_statement call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute call attribute identifier identifier argument_list subscript call attribute identifier identifier argument_list string string_start string_content string_end integer identifier argument_list attribute identifier identifier assert_statement call identifier argument_list dictionary_splat call identifier argument_list identifier | Destroy any ELB related Resources. |
def eval_fieldnames(string_, varname="fieldnames"):
ff = eval(string_)
if not isinstance(ff, list):
raise RuntimeError("{0!s} must be a list".format(varname))
if not all([isinstance(x, str) for x in ff]):
raise RuntimeError("{0!s} must be a list of strings".format(varname))
ff = [x.upper() for x in ff]
return ff | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list identifier if_statement not_operator call identifier argument_list identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier if_statement not_operator call identifier argument_list list_comprehension call identifier argument_list identifier identifier for_in_clause identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list for_in_clause identifier identifier return_statement identifier | Evaluates string_, must evaluate to list of strings. Also converts field names to uppercase |
def parse_file(src):
if config.dest_dir == None:
dest = src.dir
else:
dest = config.dest_dir
output = get_output(src)
output_file = dest + '/' + src.basename + '.min.js'
f = open(output_file,'w')
f.write(jsmin.jsmin(output))
f.close()
print "Wrote combined and minified file to: %s" % (output_file) | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier attribute identifier identifier else_clause block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier binary_operator binary_operator binary_operator identifier string string_start string_content string_end attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list print_statement binary_operator string string_start string_content string_end parenthesized_expression identifier | find file in config and output to dest dir |
def fromfile(cls, f):
filter = cls()
filter._setup(*unpack(cls.FILE_FMT, f.read(calcsize(cls.FILE_FMT))))
nfilters, = unpack(b'<l', f.read(calcsize(b'<l')))
if nfilters > 0:
header_fmt = b'<' + b'Q'*nfilters
bytes = f.read(calcsize(header_fmt))
filter_lengths = unpack(header_fmt, bytes)
for fl in filter_lengths:
filter.filters.append(BloomFilter.fromfile(f, fl))
else:
filter.filters = []
return filter | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list list_splat call identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list call identifier argument_list attribute identifier identifier expression_statement assignment pattern_list identifier call identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list call identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier integer block expression_statement assignment identifier binary_operator string string_start string_content string_end binary_operator string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier identifier for_statement identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list identifier identifier else_clause block expression_statement assignment attribute identifier identifier list return_statement identifier | Deserialize the ScalableBloomFilter in file object `f'. |
def read_plain_int32(file_obj, count):
length = 4 * count
data = file_obj.read(length)
if len(data) != length:
raise EOFError("Expected {} bytes but got {} bytes".format(length, len(data)))
res = struct.unpack("<{}i".format(count).encode("utf-8"), data)
return res | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator integer identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator call identifier argument_list identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list call attribute call attribute string string_start string_content string_end identifier argument_list identifier identifier argument_list string string_start string_content string_end identifier return_statement identifier | Read `count` 32-bit ints using the plain encoding. |
def setup_logger(log_file, level=logging.DEBUG):
cfg = AppBuilder.get_pcfg()
logger = cfg['log_module']
assert logger in ("logging", "logbook", "structlog"), 'bad logger specified'
exec("import {0};logging = {0}".format(logger))
AppBuilder.logger = logging
logging.basicConfig(
filename=log_file,
filemode='w',
level=level,
format='%(asctime)s:%(levelname)s: %(message)s')
logging.debug('System is: %s' % platform.platform())
logging.debug('Python archetecture is: %s' % platform.architecture()[0])
logging.debug('Machine archetecture is: %s' % platform.machine())
set_windows_permissions(log_file) | module function_definition identifier parameters identifier default_parameter identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier subscript identifier string string_start string_content string_end assert_statement comparison_operator identifier tuple 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 expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end subscript call attribute identifier identifier argument_list integer expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end call attribute identifier identifier argument_list expression_statement call identifier argument_list identifier | One function call to set up logging with some nice logs about the machine |
def lorem(anon, obj, field, val):
return ' '.join(anon.faker.sentences(field=field)) | module function_definition identifier parameters identifier identifier identifier identifier block return_statement call attribute string string_start string_content string_end identifier argument_list call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier | Generates a paragraph of lorem ipsum text |
def _add_definition(self):
header_part, rId = self._document_part.add_header_part()
self._sectPr.add_headerReference(self._hdrftr_index, rId)
return header_part | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier return_statement identifier | Return newly-added header part. |
def parse_timemap_from_blocks(profile_block_list):
prefix_list = []
timemap = ut.ddict(list)
for ix in range(len(profile_block_list)):
block = profile_block_list[ix]
total_time = get_block_totaltime(block)
if total_time is None:
prefix_list.append(block)
elif total_time != 0:
timemap[total_time].append(block)
return prefix_list, timemap | module function_definition identifier parameters identifier block expression_statement assignment identifier list expression_statement assignment identifier call attribute identifier identifier argument_list identifier for_statement identifier call identifier argument_list call identifier argument_list identifier block expression_statement assignment identifier subscript identifier identifier expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list identifier elif_clause comparison_operator identifier integer block expression_statement call attribute subscript identifier identifier identifier argument_list identifier return_statement expression_list identifier identifier | Build a map from times to line_profile blocks |
def render(file):
fp = file.open()
content = fp.read()
fp.close()
notebook = nbformat.reads(content.decode('utf-8'), as_version=4)
html_exporter = HTMLExporter()
html_exporter.template_file = 'basic'
(body, resources) = html_exporter.from_notebook_node(notebook)
return body, resources | 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 expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier integer expression_statement assignment identifier call identifier argument_list expression_statement assignment attribute identifier identifier string string_start string_content string_end expression_statement assignment tuple_pattern identifier identifier call attribute identifier identifier argument_list identifier return_statement expression_list identifier identifier | Generate the result HTML. |
def flipped(self):
forward, reverse = self.value
return self.__class__((reverse, forward)) | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier attribute identifier identifier return_statement call attribute identifier identifier argument_list tuple identifier identifier | Return the flipped version of this direction. |
def add_metadata_defaults(md):
defaults = {"batch": None,
"phenotype": ""}
for k, v in defaults.items():
if k not in md:
md[k] = v
return md | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end none pair string string_start string_content string_end string string_start string_end for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement comparison_operator identifier identifier block expression_statement assignment subscript identifier identifier identifier return_statement identifier | Central location for defaults for algorithm inputs. |
def workspaces_provider(context):
catalog = api.portal.get_tool(name="portal_catalog")
workspaces = catalog(portal_type="ploneintranet.workspace.workspacefolder")
current = api.content.get_uuid(context)
terms = []
for ws in workspaces:
if current != ws["UID"]:
terms.append(SimpleVocabulary.createTerm(
ws["UID"], ws["UID"], ws["Title"]))
return SimpleVocabulary(terms) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier list for_statement identifier identifier block if_statement comparison_operator identifier subscript identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end return_statement call identifier argument_list identifier | create a vocab of all workspaces in this site |
def _update(self):
aps = []
for k, v in self.records.items():
recall, prec = self._recall_prec(v, self.counts[k])
ap = self._average_precision(recall, prec)
aps.append(ap)
if self.num is not None and k < (self.num - 1):
self.sum_metric[k] = ap
self.num_inst[k] = 1
if self.num is None:
self.num_inst = 1
self.sum_metric = np.mean(aps)
else:
self.num_inst[-1] = 1
self.sum_metric[-1] = np.mean(aps) | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier subscript attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier if_statement boolean_operator comparison_operator attribute identifier identifier none comparison_operator identifier parenthesized_expression binary_operator attribute identifier identifier integer block expression_statement assignment subscript attribute identifier identifier identifier identifier expression_statement assignment subscript attribute identifier identifier identifier integer if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier else_clause block expression_statement assignment subscript attribute identifier identifier unary_operator integer integer expression_statement assignment subscript attribute identifier identifier unary_operator integer call attribute identifier identifier argument_list identifier | update num_inst and sum_metric |
def delete_session(self, ticket):
assert isinstance(self.session_storage_adapter, CASSessionAdapter)
logging.debug('[CAS] Deleting session for ticket {}'.format(ticket))
self.session_storage_adapter.delete(ticket) | module function_definition identifier parameters identifier identifier block assert_statement call identifier argument_list attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Delete a session record associated with a service ticket. |
def generate_bbox(self, collision_function=None, tag=""):
boundingBox = AABoundingBox(None, collision_function, tag)
CollisionManager.add_object(boundingBox) | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier string string_start string_end block expression_statement assignment identifier call identifier argument_list none identifier identifier expression_statement call attribute identifier identifier argument_list identifier | Create a bounding box around this tile so that it can collide with objects not included in the TileManager |
def read_until_yieldable(self):
while not self.yieldable():
read_content, read_position = _get_next_chunk(self.fp, self.read_position, self.chunk_size)
self.add_to_buffer(read_content, read_position) | module function_definition identifier parameters identifier block while_statement not_operator call attribute identifier identifier argument_list block expression_statement assignment pattern_list identifier identifier call identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier | Read in additional chunks until it is yieldable. |
def years_match(data, years):
years = [years] if isinstance(years, int) else years
dt = datetime.datetime
if isinstance(years, dt) or isinstance(years[0], dt):
error_msg = "`year` can only be filtered with ints or lists of ints"
raise TypeError(error_msg)
return data.isin(years) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier conditional_expression list identifier call identifier argument_list identifier identifier identifier expression_statement assignment identifier attribute identifier identifier if_statement boolean_operator call identifier argument_list identifier identifier call identifier argument_list subscript identifier integer identifier block expression_statement assignment identifier string string_start string_content string_end raise_statement call identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier | matching of year columns for data filtering |
def walker(top, names):
global packages, extensions
if any(exc in top for exc in excludes):
return
package = top[top.rfind('holoviews'):].replace(os.path.sep, '.')
packages.append(package)
for name in names:
ext = '.'.join(name.split('.')[1:])
ext_str = '*.%s' % ext
if ext and ext not in excludes and ext_str not in extensions[package]:
extensions[package].append(ext_str) | module function_definition identifier parameters identifier identifier block global_statement identifier identifier if_statement call identifier generator_expression comparison_operator identifier identifier for_in_clause identifier identifier block return_statement expression_statement assignment identifier call attribute subscript identifier slice call attribute identifier identifier argument_list string string_start string_content string_end identifier argument_list attribute attribute identifier identifier identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier for_statement identifier identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list subscript call attribute identifier identifier argument_list string string_start string_content string_end slice integer expression_statement assignment identifier binary_operator string string_start string_content string_end identifier if_statement boolean_operator boolean_operator identifier comparison_operator identifier identifier comparison_operator identifier subscript identifier identifier block expression_statement call attribute subscript identifier identifier identifier argument_list identifier | Walks a directory and records all packages and file extensions. |
def connectShell(connection, protocol):
deferred = connectSession(connection, protocol)
@deferred.addCallback
def requestSubsystem(session):
return session.requestShell()
return deferred | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier decorated_definition decorator attribute identifier identifier function_definition identifier parameters identifier block return_statement call attribute identifier identifier argument_list return_statement identifier | Connect a Protocol to a ssh shell session |
def MLP(num_hidden_layers=2,
hidden_size=512,
activation_fn=layers.Relu,
num_output_classes=10,
mode="train"):
del mode
cur_layers = [layers.Flatten()]
for _ in range(num_hidden_layers):
cur_layers += [layers.Dense(hidden_size), activation_fn()]
cur_layers += [layers.Dense(num_output_classes), layers.LogSoftmax()]
return layers.Serial(*cur_layers) | module function_definition identifier parameters default_parameter identifier integer default_parameter identifier integer default_parameter identifier attribute identifier identifier default_parameter identifier integer default_parameter identifier string string_start string_content string_end block delete_statement identifier expression_statement assignment identifier list call attribute identifier identifier argument_list for_statement identifier call identifier argument_list identifier block expression_statement augmented_assignment identifier list call attribute identifier identifier argument_list identifier call identifier argument_list expression_statement augmented_assignment identifier list call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list return_statement call attribute identifier identifier argument_list list_splat identifier | Multi-layer feed-forward neural network with non-linear activations. |
def format_arg(arg):
s = str(arg)
dot = s.rfind('.')
if dot >= 0:
s = s[dot + 1:]
s = s.replace(';', '')
s = s.replace('[]', 'Array')
if len(s) > 0:
c = s[0].lower()
s = c + s[1:]
return s | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier integer block expression_statement assignment identifier subscript identifier slice binary_operator identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment identifier call attribute subscript identifier integer identifier argument_list expression_statement assignment identifier binary_operator identifier subscript identifier slice integer return_statement identifier | formats an argument to be shown |
def setKey(self, key):
key = self._guardAgainstUnicode(key)
self.__key = key | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier | Will set the crypting key for this object. |
def _get_image_size(self, image_path):
command = 'du -b %s' % image_path
(rc, output) = zvmutils.execute(command)
if rc:
msg = ("Error happened when executing command du -b with"
"reason: %s" % output)
LOG.error(msg)
raise exception.SDKImageOperationError(rs=8)
size = output.split()[0]
return size | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end identifier expression_statement assignment tuple_pattern identifier identifier call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement assignment identifier parenthesized_expression binary_operator concatenated_string string string_start string_content string_end string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier raise_statement call attribute identifier identifier argument_list keyword_argument identifier integer expression_statement assignment identifier subscript call attribute identifier identifier argument_list integer return_statement identifier | Return disk size in bytes |
def save(self, *args, **kwargs):
now = datetime.utcnow().replace(tzinfo=pytz.UTC)
if not self.pk:
self.created = now
self.modified = now
return super(Configuration, self).save(*args, **kwargs) | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list keyword_argument identifier attribute identifier identifier if_statement not_operator attribute identifier identifier block expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier return_statement call attribute call identifier argument_list identifier identifier identifier argument_list list_splat identifier dictionary_splat identifier | On save, update timestamps |
def records(self):
return ModelList(*[r for sent in self.sentences for r in sent.records]) | module function_definition identifier parameters identifier block return_statement call identifier argument_list list_splat list_comprehension identifier for_in_clause identifier attribute identifier identifier for_in_clause identifier attribute identifier identifier | Return a list of records for this text passage. |
def document_is_multiline_python(document):
def ends_in_multiline_string():
delims = _multiline_string_delims.findall(document.text)
opening = None
for delim in delims:
if opening is None:
opening = delim
elif delim == opening:
opening = None
return bool(opening)
if '\n' in document.text or ends_in_multiline_string():
return True
def line_ends_with_colon():
return document.current_line.rstrip()[-1:] == ':'
if line_ends_with_colon() or \
(document.is_cursor_at_the_end and
has_unclosed_brackets(document.text_before_cursor)) or \
document.text.startswith('@'):
return True
elif document.text_before_cursor[-1:] == '\\':
return True
return False | module function_definition identifier parameters identifier block function_definition identifier parameters block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier none for_statement identifier identifier block if_statement comparison_operator identifier none block expression_statement assignment identifier identifier elif_clause comparison_operator identifier identifier block expression_statement assignment identifier none return_statement call identifier argument_list identifier if_statement boolean_operator comparison_operator string string_start string_content escape_sequence string_end attribute identifier identifier call identifier argument_list block return_statement true function_definition identifier parameters block return_statement comparison_operator subscript call attribute attribute identifier identifier identifier argument_list slice unary_operator integer string string_start string_content string_end if_statement boolean_operator boolean_operator call identifier argument_list line_continuation parenthesized_expression boolean_operator attribute identifier identifier call identifier argument_list attribute identifier identifier line_continuation call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block return_statement true elif_clause comparison_operator subscript attribute identifier identifier slice unary_operator integer string string_start string_content escape_sequence string_end block return_statement true return_statement false | Determine whether this is a multiline Python document. |
def load_functionalChannels(self, groups: Iterable[Group]):
self.functionalChannels = []
for channel in self._rawJSONData["functionalChannels"].values():
fc = self._parse_functionalChannel(channel, groups)
self.functionalChannels.append(fc)
self.functionalChannelCount = Counter(
x.functionalChannelType for x in self.functionalChannels
) | module function_definition identifier parameters identifier typed_parameter identifier type generic_type identifier type_parameter type identifier block expression_statement assignment attribute identifier identifier list for_statement identifier call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier call identifier generator_expression attribute identifier identifier for_in_clause identifier attribute identifier identifier | this function will load the functionalChannels into the device |
def examples(path='holoviews-examples', verbose=False, force=False, root=__file__):
filepath = os.path.abspath(os.path.dirname(root))
example_dir = os.path.join(filepath, './examples')
if not os.path.exists(example_dir):
example_dir = os.path.join(filepath, '../examples')
if os.path.exists(path):
if not force:
print('%s directory already exists, either delete it or set the force flag' % path)
return
shutil.rmtree(path)
ignore = shutil.ignore_patterns('.ipynb_checkpoints', '*.pyc', '*~')
tree_root = os.path.abspath(example_dir)
if os.path.isdir(tree_root):
shutil.copytree(tree_root, path, ignore=ignore, symlinks=True)
else:
print('Cannot find %s' % tree_root) | module function_definition identifier parameters default_parameter identifier string string_start string_content string_end default_parameter identifier false default_parameter identifier false default_parameter identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end if_statement call attribute attribute identifier identifier identifier argument_list identifier block if_statement not_operator identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier return_statement expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier identifier keyword_argument identifier identifier keyword_argument identifier true else_clause block expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier | Copies the notebooks to the supplied path. |
def AltTab(self, n=1, delay=0):
self._delay(delay)
self.add(Command("KeyDown", 'KeyDown "%s", %s' % (BoardKey.Alt, 1)))
for i in range(n):
self.add(Command("KeyPress", 'KeyPress "%s", %s' % (BoardKey.Tab, 1)))
self.add(Command("KeyUp", 'KeyUp "%s", %s' % (BoardKey.Alt, 1))) | module function_definition identifier parameters identifier default_parameter identifier integer default_parameter identifier integer block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call identifier argument_list string string_start string_content string_end binary_operator string string_start string_content string_end tuple attribute identifier identifier integer for_statement identifier call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list string string_start string_content string_end binary_operator string string_start string_content string_end tuple attribute identifier identifier integer expression_statement call attribute identifier identifier argument_list call identifier argument_list string string_start string_content string_end binary_operator string string_start string_content string_end tuple attribute identifier identifier integer | Press down Alt, then press n times Tab, then release Alt. |
def ip_address_list(ips):
try:
return ip_address(ips)
except ValueError:
pass
return list(ipaddress.ip_network(u(ips)).hosts()) | module function_definition identifier parameters identifier block try_statement block return_statement call identifier argument_list identifier except_clause identifier block pass_statement return_statement call identifier argument_list call attribute call attribute identifier identifier argument_list call identifier argument_list identifier identifier argument_list | IP address range validation and expansion. |
def HMAC(self, message, use_sha256=False):
h = self._NewHMAC(use_sha256=use_sha256)
h.update(message)
return h.finalize() | module function_definition identifier parameters identifier identifier default_parameter identifier false block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list | Calculates the HMAC for a given message. |
def _cycle_proceedings(self):
next_approvals = self._get_next_approvals().exclude(
status=PENDING).exclude(cloned=True)
for ta in next_approvals:
clone_transition_approval, c = TransitionApproval.objects.get_or_create(
source_state=ta.source_state,
destination_state=ta.destination_state,
content_type=ta.content_type,
object_id=ta.object_id,
field_name=ta.field_name,
skip=ta.skip,
priority=ta.priority,
enabled=ta.enabled,
status=PENDING,
meta=ta.meta
)
if c:
clone_transition_approval.permissions.add(*ta.permissions.all())
clone_transition_approval.groups.add(*ta.groups.all())
next_approvals.update(cloned=True)
return True if next_approvals.count() else False | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call attribute call attribute identifier identifier argument_list identifier argument_list keyword_argument identifier identifier identifier argument_list keyword_argument identifier true for_statement identifier identifier block expression_statement assignment pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier if_statement identifier block expression_statement call attribute attribute identifier identifier identifier argument_list list_splat call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list list_splat call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list keyword_argument identifier true return_statement conditional_expression true call attribute identifier identifier argument_list false | Finds next proceedings and clone them for cycling if it exists. |
def py_log_level(self, default='none'):
level = self._get_str("PY_LOG_LEVEL", default, "debug")
LEVELS = {'trace': logging.TRACE,
'debug': logging.DEBUG,
'info' : logging.INFO,
'warn' : logging.WARNING,
'error': logging.ERROR,
'fatal': logging.CRITICAL,
'none' : None}
return LEVELS[level] | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier string string_start string_content string_end expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end none return_statement subscript identifier identifier | Set the log level for python Bokeh code. |
def publish_event_from_dict(self, event_type, data):
for key, value in self.additional_publish_event_data.items():
if key in data:
return {'result': 'error', 'message': 'Key should not be in publish_event data: {}'.format(key)}
data[key] = value
self.runtime.publish(self, event_type, data)
return {'result': 'success'} | module function_definition identifier parameters identifier identifier identifier block for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block if_statement comparison_operator identifier identifier block return_statement dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment subscript identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier identifier return_statement dictionary pair string string_start string_content string_end string string_start string_content string_end | Combine 'data' with self.additional_publish_event_data and publish an event |
def post_save(sender, instance, created, **kwargs):
model_label = '.'.join([sender._meta.app_label, sender._meta.object_name])
labels = resolve_labels(model_label)
order_field_names = is_orderable(model_label)
if order_field_names:
orderitem_set = getattr(
instance,
resolve_order_item_related_set_name(labels)
)
if not orderitem_set.all():
fields = {}
for order_field_name in order_field_names:
fields[order_field_name] = 1
orderitem_set.model.objects.create(item=instance, **fields)
sanitize_order(orderitem_set.model) | module function_definition identifier parameters identifier identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list list attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier if_statement identifier block expression_statement assignment identifier call identifier argument_list identifier call identifier argument_list identifier if_statement not_operator call attribute identifier identifier argument_list block expression_statement assignment identifier dictionary for_statement identifier identifier block expression_statement assignment subscript identifier identifier integer expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list keyword_argument identifier identifier dictionary_splat identifier expression_statement call identifier argument_list attribute identifier identifier | After save create order instance for sending instance for orderable models. |
def __convert_env(env, encoding):
d = dict(os.environ, **(oget(env, {})))
if not SHOULD_NOT_ENCODE_ARGS:
return dict((k.encode(encoding), v.encode(encoding)) for k, v in d.items())
else:
return d | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier dictionary_splat parenthesized_expression call identifier argument_list identifier dictionary if_statement not_operator identifier block return_statement call identifier generator_expression tuple call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list else_clause block return_statement identifier | Environment variables should be bytes not unicode on Windows. |
def bam_to_fastq_pair(in_file, target_region, pair):
space, start, end = target_region
bam_file = pysam.Samfile(in_file, "rb")
for read in bam_file:
if (not read.is_unmapped and not read.mate_is_unmapped
and bam_file.getrname(read.tid) == space
and bam_file.getrname(read.mrnm) == space
and read.pos >= start and read.pos <= end
and read.mpos >= start and read.mpos <= end
and not read.is_secondary
and read.is_paired and getattr(read, "is_read%s" % pair)):
seq = Seq.Seq(read.seq)
qual = list(read.qual)
if read.is_reverse:
seq = seq.reverse_complement()
qual.reverse()
yield read.qname, str(seq), "".join(qual) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment pattern_list identifier identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end for_statement identifier identifier block if_statement parenthesized_expression boolean_operator boolean_operator boolean_operator boolean_operator boolean_operator boolean_operator boolean_operator boolean_operator boolean_operator boolean_operator not_operator attribute identifier identifier not_operator attribute identifier identifier comparison_operator call attribute identifier identifier argument_list attribute identifier identifier identifier comparison_operator call attribute identifier identifier argument_list attribute identifier identifier identifier comparison_operator attribute identifier identifier identifier comparison_operator attribute identifier identifier identifier comparison_operator attribute identifier identifier identifier comparison_operator attribute identifier identifier identifier not_operator attribute identifier identifier attribute identifier identifier call identifier argument_list identifier binary_operator string string_start string_content string_end identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier if_statement attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement yield expression_list attribute identifier identifier call identifier argument_list identifier call attribute string string_start string_end identifier argument_list identifier | Generator to convert BAM files into name, seq, qual in a region. |
def yesterday(self) -> datetime:
self.value = datetime.today() - timedelta(days=1)
return self.value | module function_definition identifier parameters identifier type identifier block expression_statement assignment attribute identifier identifier binary_operator call attribute identifier identifier argument_list call identifier argument_list keyword_argument identifier integer return_statement attribute identifier identifier | Set the value to yesterday |
def GetTotalValue(self):
value = ""
if hasattr(self, "meter"):
top_value = self.meter.beats
bottom = self.meter.type
fraction = top_value / bottom
if fraction == 1:
value = "1"
else:
if fraction > 1:
value = "1."
if fraction < 1:
if fraction >= 0.5:
fraction -= 0.5
value = "2"
if fraction == 0.25:
value += "."
return value | module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_end if_statement call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier binary_operator identifier identifier if_statement comparison_operator identifier integer block expression_statement assignment identifier string string_start string_content string_end else_clause block if_statement comparison_operator identifier integer block expression_statement assignment identifier string string_start string_content string_end if_statement comparison_operator identifier integer block if_statement comparison_operator identifier float block expression_statement augmented_assignment identifier float expression_statement assignment identifier string string_start string_content string_end if_statement comparison_operator identifier float block expression_statement augmented_assignment identifier string string_start string_content string_end return_statement identifier | Gets the total value of the bar according to it's time signature |
def save_config(self, cmd="write mem", confirm=False, confirm_response=""):
return super(CiscoIosBase, self).save_config(
cmd=cmd, confirm=confirm, confirm_response=confirm_response
) | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier false default_parameter identifier string string_start string_end block return_statement call attribute call identifier argument_list identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | Saves Config Using Copy Run Start |
def setnode(delta, graph, node, exists):
delta.setdefault(graph, {}).setdefault('nodes', {})[node] = bool(exists) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment subscript call attribute call attribute identifier identifier argument_list identifier dictionary identifier argument_list string string_start string_content string_end dictionary identifier call identifier argument_list identifier | Change a delta to say that a node was created or deleted |
def MethodName(self, name, separator='_'):
if name is None:
return None
name = Names.__ToCamel(name, separator=separator)
return Names.CleanName(name) | module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end block if_statement comparison_operator identifier none block return_statement none expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier return_statement call attribute identifier identifier argument_list identifier | Generate a valid method name from name. |
def _variable(lexer):
names = _names(lexer)
tok = next(lexer)
if isinstance(tok, LBRACK):
indices = _indices(lexer)
_expect_token(lexer, {RBRACK})
else:
lexer.unpop_token(tok)
indices = tuple()
return ('var', names, indices) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement call identifier argument_list identifier set identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list return_statement tuple string string_start string_content string_end identifier identifier | Return a variable expression. |
def _combine_core_aux_specs(self):
all_specs = []
for core_dict in self._permute_core_specs():
for aux_dict in self._permute_aux_specs():
all_specs.append(_merge_dicts(core_dict, aux_dict))
return all_specs | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier call attribute identifier identifier argument_list block for_statement identifier call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier identifier return_statement identifier | Combine permutations over core and auxilliary Calc specs. |
def resolve_file(fname, paths):
fpath = path.abspath(fname)
for p in paths:
spath = path.abspath(p)
if fpath.startswith(spath):
return fpath[len(spath) + 1:]
return fname | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement call attribute identifier identifier argument_list identifier block return_statement subscript identifier slice binary_operator call identifier argument_list identifier integer return_statement identifier | Resolve filename relatively against one of the given paths, if possible. |
def ethernet_interfaces(self):
return ethernet_interface.EthernetInterfaceCollection(
self._conn,
self._get_hpe_sub_resource_collection_path('EthernetInterfaces'),
redfish_version=self.redfish_version) | module function_definition identifier parameters identifier block return_statement call attribute identifier identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier attribute identifier identifier | Provide reference to EthernetInterfacesCollection instance |
def match_data(self, tokens, item):
if len(tokens) == 2:
data_type, matches = tokens
star_match = None
elif len(tokens) == 3:
data_type, matches, star_match = tokens
else:
raise CoconutInternalException("invalid data match tokens", tokens)
self.add_check("_coconut.isinstance(" + item + ", " + data_type + ")")
if star_match is None:
self.add_check("_coconut.len(" + item + ") == " + str(len(matches)))
elif len(matches):
self.add_check("_coconut.len(" + item + ") >= " + str(len(matches)))
self.match_all_in(matches, item)
if star_match is not None:
self.match(star_match, item + "[" + str(len(matches)) + ":]") | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment pattern_list identifier identifier identifier expression_statement assignment identifier none elif_clause comparison_operator call identifier argument_list identifier integer block expression_statement assignment pattern_list identifier identifier identifier identifier else_clause block raise_statement call identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list binary_operator binary_operator binary_operator binary_operator string string_start string_content string_end identifier string string_start string_content string_end identifier string string_start string_content string_end if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list binary_operator binary_operator binary_operator string string_start string_content string_end identifier string string_start string_content string_end call identifier argument_list call identifier argument_list identifier elif_clause call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list binary_operator binary_operator binary_operator string string_start string_content string_end identifier string string_start string_content string_end call identifier argument_list call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier identifier if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list identifier binary_operator binary_operator binary_operator identifier string string_start string_content string_end call identifier argument_list call identifier argument_list identifier string string_start string_content string_end | Matches a data type. |
def write(self, fptr):
read_buffer = ET.tostring(self.xml.getroot(), encoding='utf-8')
fptr.write(struct.pack('>I4s', len(read_buffer) + 8, b'xml '))
fptr.write(read_buffer) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end binary_operator call identifier argument_list identifier integer string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier | Write an XML box to file. |
def _slice_value(index, context=None):
if isinstance(index, Const):
if isinstance(index.value, (int, type(None))):
return index.value
elif index is None:
return None
else:
try:
inferred = next(index.infer(context=context))
except exceptions.InferenceError:
pass
else:
if isinstance(inferred, Const):
if isinstance(inferred.value, (int, type(None))):
return inferred.value
return _SLICE_SENTINEL | module function_definition identifier parameters identifier default_parameter identifier none block if_statement call identifier argument_list identifier identifier block if_statement call identifier argument_list attribute identifier identifier tuple identifier call identifier argument_list none block return_statement attribute identifier identifier elif_clause comparison_operator identifier none block return_statement none else_clause block try_statement block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier identifier except_clause attribute identifier identifier block pass_statement else_clause block if_statement call identifier argument_list identifier identifier block if_statement call identifier argument_list attribute identifier identifier tuple identifier call identifier argument_list none block return_statement attribute identifier identifier return_statement identifier | Get the value of the given slice index. |
def need_finalize(cls, resource):
vm_id = cls.usable_id(resource)
params = {'type': 'hosting_migration_vm',
'step': 'RUN',
'vm_id': vm_id}
result = cls.call('operation.list', params)
if not result or len(result) > 1:
raise MigrationNotFinalized('Cannot find VM %s '
'migration operation.' % resource)
need_finalize = result[0]['params']['inner_step'] == 'wait_finalize'
if not need_finalize:
raise MigrationNotFinalized('VM %s migration does not need '
'finalization.' % resource) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier if_statement boolean_operator not_operator identifier comparison_operator call identifier argument_list identifier integer block raise_statement call identifier argument_list binary_operator concatenated_string string string_start string_content string_end string string_start string_content string_end identifier expression_statement assignment identifier comparison_operator subscript subscript subscript identifier integer string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end if_statement not_operator identifier block raise_statement call identifier argument_list binary_operator concatenated_string string string_start string_content string_end string string_start string_content string_end identifier | Check if vm migration need to be finalized. |
def triple_reference_of(label: ShExJ.tripleExprLabel, cntxt: Context) -> Optional[ShExJ.tripleExpr]:
te: Optional[ShExJ.tripleExpr] = None
if cntxt.schema.start is not None:
te = triple_in_shape(cntxt.schema.start, label, cntxt)
if te is None:
for shapeExpr in cntxt.schema.shapes:
te = triple_in_shape(shapeExpr, label, cntxt)
if te:
break
return te | module function_definition identifier parameters typed_parameter identifier type attribute identifier identifier typed_parameter identifier type identifier type generic_type identifier type_parameter type attribute identifier identifier block expression_statement assignment identifier type generic_type identifier type_parameter type attribute identifier identifier none if_statement comparison_operator attribute attribute identifier identifier identifier none block expression_statement assignment identifier call identifier argument_list attribute attribute identifier identifier identifier identifier identifier if_statement comparison_operator identifier none block for_statement identifier attribute attribute identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier identifier if_statement identifier block break_statement return_statement identifier | Search for the label in a Schema |
def expose_init(self, *args):
gldrawable = self.get_gl_drawable()
glcontext = self.get_gl_context()
if not gldrawable or not gldrawable.gl_begin(glcontext):
return False
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glInitNames()
glPushName(0)
self.name_counter = 1
return False | module function_definition identifier parameters identifier list_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list if_statement boolean_operator not_operator identifier not_operator call attribute identifier identifier argument_list identifier block return_statement false expression_statement call identifier argument_list binary_operator identifier identifier expression_statement call identifier argument_list expression_statement call identifier argument_list integer expression_statement assignment attribute identifier identifier integer return_statement false | Process the drawing routine |
def to_label(var_instance):
assert isinstance(var_instance, SymbolVAR)
from symbols import LABEL
var_instance.__class__ = LABEL
var_instance.class_ = CLASS.label
var_instance._scope_owner = []
return var_instance | module function_definition identifier parameters identifier block assert_statement call identifier argument_list identifier identifier import_from_statement dotted_name identifier dotted_name identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier list return_statement identifier | Converts a var_instance to a label one |
def write(self, session, directory, name, replaceParamFile=None, **kwargs):
if self.raster is not None or self.rasterText is not None:
super(RasterMapFile, self).write(session, directory, name, replaceParamFile, **kwargs) | module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier none dictionary_splat_pattern identifier block if_statement boolean_operator comparison_operator attribute identifier identifier none comparison_operator attribute identifier identifier none block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier identifier identifier identifier dictionary_splat identifier | Wrapper for GsshaPyFileObjectBase write method |
def bb_get_instr_max_width(basic_block):
asm_mnemonic_max_width = 0
for instr in basic_block:
if len(instr.mnemonic) > asm_mnemonic_max_width:
asm_mnemonic_max_width = len(instr.mnemonic)
return asm_mnemonic_max_width | module function_definition identifier parameters identifier block expression_statement assignment identifier integer for_statement identifier identifier block if_statement comparison_operator call identifier argument_list attribute identifier identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier return_statement identifier | Get maximum instruction mnemonic width |
def search_channels(self, **kwargs):
params = [(key, kwargs[key]) for key in sorted(kwargs.keys())]
url = "/notification/v1/channel?{}".format(
urlencode(params, doseq=True))
response = NWS_DAO().getURL(url, self._read_headers)
if response.status != 200:
raise DataFailureException(url, response.status, response.data)
data = json.loads(response.data)
channels = []
for datum in data.get("Channels", []):
channels.append(self._channel_from_json(datum))
return channels | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier list_comprehension tuple identifier subscript identifier identifier for_in_clause identifier call identifier argument_list call attribute identifier identifier argument_list expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier keyword_argument identifier true expression_statement assignment identifier call attribute call identifier argument_list identifier argument_list identifier attribute identifier identifier if_statement comparison_operator attribute identifier identifier integer block raise_statement call identifier argument_list identifier attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier list for_statement identifier call attribute identifier identifier argument_list string string_start string_content string_end list block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier return_statement identifier | Search for all channels by parameters |
def log(self, *args):
print("%s %s" % (str(self).ljust(8), " ".join([str(x) for x in args]))) | module function_definition identifier parameters identifier list_splat_pattern identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple call attribute call identifier argument_list identifier identifier argument_list integer call attribute string string_start string_content string_end identifier argument_list list_comprehension call identifier argument_list identifier for_in_clause identifier identifier | stdout and stderr for the link |
def delete_global_cache(appname='default'):
shelf_fpath = get_global_shelf_fpath(appname)
util_path.remove_file(shelf_fpath, verbose=True, dryrun=False) | module function_definition identifier parameters default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier true keyword_argument identifier false | Reads cache files to a safe place in each operating system |
def collect_frames_for_random_starts(
storage_env, stacked_env, agent, frame_stack_size, random_starts_step_limit,
log_every_steps=None
):
del frame_stack_size
storage_env.start_new_epoch(0)
tf.logging.info(
"Collecting %d frames for random starts.", random_starts_step_limit
)
rl_utils.run_rollouts(
stacked_env, agent, stacked_env.reset(),
step_limit=random_starts_step_limit,
many_rollouts_from_each_env=True,
log_every_steps=log_every_steps,
)
stacked_env.reset() | module function_definition identifier parameters identifier identifier identifier identifier identifier default_parameter identifier none block delete_statement identifier expression_statement call attribute identifier identifier argument_list integer expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier true keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list | Collects frames from real env for random starts of simulated env. |
def _ensure_like_indices(time, panels):
n_time = len(time)
n_panel = len(panels)
u_panels = np.unique(panels)
u_time = np.unique(time)
if len(u_time) == n_time:
time = np.tile(u_time, len(u_panels))
if len(u_panels) == n_panel:
panels = np.repeat(u_panels, len(u_time))
return time, panels | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier call identifier argument_list identifier if_statement comparison_operator call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier call identifier argument_list identifier return_statement expression_list identifier identifier | Makes sure that time and panels are conformable. |
def stop(self):
self._server.shutdown()
self._server.server_close()
self._thread.join()
self.running = False | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier false | Shuts the server down and waits for server thread to join |
def does_fragment_condition_match(
self,
fragment: Union[FragmentDefinitionNode, InlineFragmentNode],
type_: GraphQLObjectType,
) -> bool:
type_condition_node = fragment.type_condition
if not type_condition_node:
return True
conditional_type = type_from_ast(self.schema, type_condition_node)
if conditional_type is type_:
return True
if is_abstract_type(conditional_type):
return self.schema.is_possible_type(
cast(GraphQLAbstractType, conditional_type), type_
)
return False | module function_definition identifier parameters identifier typed_parameter identifier type generic_type identifier type_parameter type identifier type identifier typed_parameter identifier type identifier type identifier block expression_statement assignment identifier attribute identifier identifier if_statement not_operator identifier block return_statement true expression_statement assignment identifier call identifier argument_list attribute identifier identifier identifier if_statement comparison_operator identifier identifier block return_statement true if_statement call identifier argument_list identifier block return_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list identifier identifier identifier return_statement false | Determine if a fragment is applicable to the given type. |
def commitWorkingCopy(self, configFile):
fn = self.function_table.commitWorkingCopy
result = fn(configFile)
return result | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list identifier return_statement identifier | Saves the current working copy to disk |
def _get_element(name, element_type, server=None, with_properties=True):
element = {}
name = quote(name, safe='')
data = _api_get('{0}/{1}'.format(element_type, name), server)
if any(data['extraProperties']['entity']):
for key, value in data['extraProperties']['entity'].items():
element[key] = value
if with_properties:
element['properties'] = _get_element_properties(name, element_type)
return element
return None | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier true block expression_statement assignment identifier dictionary expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier string string_start string_end expression_statement assignment identifier call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier identifier if_statement call identifier argument_list subscript subscript identifier string string_start string_content string_end string string_start string_content string_end block for_statement pattern_list identifier identifier call attribute subscript subscript identifier string string_start string_content string_end string string_start string_content string_end identifier argument_list block expression_statement assignment subscript identifier identifier identifier if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list identifier identifier return_statement identifier return_statement none | Get an element with or without properties |
def program_files(self, executable):
if self._get_version() == 6:
paths = self.REQUIRED_PATHS_6
elif self._get_version() > 6:
paths = self.REQUIRED_PATHS_7_1
return paths | module function_definition identifier parameters identifier identifier block if_statement comparison_operator call attribute identifier identifier argument_list integer block expression_statement assignment identifier attribute identifier identifier elif_clause comparison_operator call attribute identifier identifier argument_list integer block expression_statement assignment identifier attribute identifier identifier return_statement identifier | Determine the file paths to be adopted |
def _deprecation_warning(cls):
if issubclass(cls, Location):
warnings.warn(
"Location is deprecated! Please use locator.BlockUsageLocator",
DeprecationWarning,
stacklevel=3
)
elif issubclass(cls, AssetLocation):
warnings.warn(
"AssetLocation is deprecated! Please use locator.AssetLocator",
DeprecationWarning,
stacklevel=3
)
else:
warnings.warn(
"{} is deprecated!".format(cls),
DeprecationWarning,
stacklevel=3
) | module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier keyword_argument identifier integer elif_clause call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier keyword_argument identifier integer else_clause block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier keyword_argument identifier integer | Display a deprecation warning for the given cls |
def barracks_in_middle(self) -> Point2:
if len(self.upper2_for_ramp_wall) == 2:
points = self.upper2_for_ramp_wall
p1 = points.pop().offset((self.x_offset, self.y_offset))
p2 = points.pop().offset((self.x_offset, self.y_offset))
intersects = p1.circle_intersection(p2, 5 ** 0.5)
anyLowerPoint = next(iter(self.lower))
return max(intersects, key=lambda p: p.distance_to(anyLowerPoint))
raise Exception("Not implemented. Trying to access a ramp that has a wrong amount of upper points.") | module function_definition identifier parameters identifier type identifier block if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list tuple attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list tuple attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier binary_operator integer float expression_statement assignment identifier call identifier argument_list call identifier argument_list attribute identifier identifier return_statement call identifier argument_list identifier keyword_argument identifier lambda lambda_parameters identifier call attribute identifier identifier argument_list identifier raise_statement call identifier argument_list string string_start string_content string_end | Barracks position in the middle of the 2 depots |
def _execute(self, handler, *args, **kwargs):
result = None
exc_info = None
try:
result = handler(*args, **kwargs)
except Exception:
exc_info = sys.exc_info()
if exc_info:
return exc_info
return result | module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier none expression_statement assignment identifier none try_statement block expression_statement assignment identifier call identifier argument_list list_splat identifier dictionary_splat identifier except_clause identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement identifier block return_statement identifier return_statement identifier | executes one callback function |
def _key_tab(self):
if self.is_cursor_on_last_line():
empty_line = not self.get_current_line_to_cursor().strip()
if empty_line:
self.stdkey_tab()
else:
self.show_code_completion() | module function_definition identifier parameters identifier block if_statement call attribute identifier identifier argument_list block expression_statement assignment identifier not_operator call attribute call attribute identifier identifier argument_list identifier argument_list if_statement identifier block expression_statement call attribute identifier identifier argument_list else_clause block expression_statement call attribute identifier identifier argument_list | Action for TAB key |
def updated(self, user):
for who, what, old, new in self.history(user):
if (what == "comment" or what == "description") and new != "":
return True
return False | module function_definition identifier parameters identifier identifier block for_statement pattern_list identifier identifier identifier identifier call attribute identifier identifier argument_list identifier block if_statement boolean_operator parenthesized_expression boolean_operator comparison_operator identifier string string_start string_content string_end comparison_operator identifier string string_start string_content string_end comparison_operator identifier string string_start string_end block return_statement true return_statement false | True if the user commented the ticket in given time frame |
def simplify_polynomial(polynomial, monomial_substitutions):
if isinstance(polynomial, (int, float, complex)):
return polynomial
polynomial = (1.0 * polynomial).expand(mul=True,
multinomial=True)
if is_number_type(polynomial):
return polynomial
if polynomial.is_Mul:
elements = [polynomial]
else:
elements = polynomial.as_coeff_mul()[1][0].as_coeff_add()[1]
new_polynomial = 0
for element in elements:
monomial, coeff = separate_scalar_factor(element)
monomial = apply_substitutions(monomial, monomial_substitutions)
new_polynomial += coeff * monomial
return new_polynomial | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier tuple identifier identifier identifier block return_statement identifier expression_statement assignment identifier call attribute parenthesized_expression binary_operator float identifier identifier argument_list keyword_argument identifier true keyword_argument identifier true if_statement call identifier argument_list identifier block return_statement identifier if_statement attribute identifier identifier block expression_statement assignment identifier list identifier else_clause block expression_statement assignment identifier subscript call attribute subscript subscript call attribute identifier identifier argument_list integer integer identifier argument_list integer expression_statement assignment identifier integer for_statement identifier identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement augmented_assignment identifier binary_operator identifier identifier return_statement identifier | Simplify a polynomial for uniform handling later. |
def generate(env):
env.AppendUnique(LATEXSUFFIXES=SCons.Tool.LaTeXSuffixes)
from . import dvi
dvi.generate(env)
from . import pdf
pdf.generate(env)
bld = env['BUILDERS']['DVI']
bld.add_action('.ltx', LaTeXAuxAction)
bld.add_action('.latex', LaTeXAuxAction)
bld.add_emitter('.ltx', SCons.Tool.tex.tex_eps_emitter)
bld.add_emitter('.latex', SCons.Tool.tex.tex_eps_emitter)
SCons.Tool.tex.generate_common(env) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list keyword_argument identifier attribute attribute identifier identifier identifier import_from_statement relative_import import_prefix dotted_name identifier expression_statement call attribute identifier identifier argument_list identifier import_from_statement relative_import import_prefix dotted_name identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier subscript subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute attribute attribute identifier identifier identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute attribute attribute identifier identifier identifier identifier expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list identifier | Add Builders and construction variables for LaTeX to an Environment. |
def _generate_prime(bits, rng):
"primtive attempt at prime generation"
hbyte_mask = pow(2, bits % 8) - 1
while True:
x = rng.read((bits+7) // 8)
if hbyte_mask > 0:
x = chr(ord(x[0]) & hbyte_mask) + x[1:]
n = util.inflate_long(x, 1)
n |= 1
n |= (1 << (bits - 1))
while not number.isPrime(n):
n += 2
if util.bit_length(n) == bits:
break
return n | module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier binary_operator call identifier argument_list integer binary_operator identifier integer integer while_statement true block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator parenthesized_expression binary_operator identifier integer integer if_statement comparison_operator identifier integer block expression_statement assignment identifier binary_operator call identifier argument_list binary_operator call identifier argument_list subscript identifier integer identifier subscript identifier slice integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier integer expression_statement augmented_assignment identifier integer expression_statement augmented_assignment identifier parenthesized_expression binary_operator integer parenthesized_expression binary_operator identifier integer while_statement not_operator call attribute identifier identifier argument_list identifier block expression_statement augmented_assignment identifier integer if_statement comparison_operator call attribute identifier identifier argument_list identifier identifier block break_statement return_statement identifier | primtive attempt at prime generation |
def createZMQSocket(self, sock_type):
sock = self.ZMQcontext.socket(sock_type)
sock.setsockopt(zmq.LINGER, LINGER_TIME)
sock.setsockopt(zmq.IPV4ONLY, 0)
sock.setsockopt(zmq.SNDHWM, 0)
sock.setsockopt(zmq.RCVHWM, 0)
try:
sock.setsockopt(zmq.IMMEDIATE, 1)
except:
pass
if sock_type == zmq.ROUTER:
sock.setsockopt(zmq.ROUTER_MANDATORY, 1)
return sock | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier integer expression_statement call attribute identifier identifier argument_list attribute identifier identifier integer expression_statement call attribute identifier identifier argument_list attribute identifier identifier integer try_statement block expression_statement call attribute identifier identifier argument_list attribute identifier identifier integer except_clause block pass_statement if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier integer return_statement identifier | Create a socket of the given sock_type and deactivate message dropping |
def sync_in(self, force=False):
self.log('---- Sync In ----')
self.dstate = self.STATES.BUILDING
for path_name in self.source_fs.listdir():
f = self.build_source_files.instance_from_name(path_name)
if not f:
self.warn('Ignoring unknown file: {}'.format(path_name))
continue
if f and f.exists and (f.fs_is_newer or force):
self.log('Sync: {}'.format(f.record.path))
f.fs_to_record()
f.record_to_objects()
self.commit()
self.library.search.index_bundle(self, force=True) | module function_definition identifier parameters identifier default_parameter identifier false block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier attribute attribute identifier identifier identifier for_statement identifier call attribute attribute identifier identifier identifier argument_list block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier continue_statement if_statement boolean_operator boolean_operator identifier attribute identifier identifier parenthesized_expression boolean_operator attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list identifier keyword_argument identifier true | Synchronize from files to records, and records to objects |
def removeTarget(self, iid):
sql = 'delete from {} where _id=?'.format(self.TABLE_ITEMS)
cursor = self.db.execute(sql, (iid,))
if cursor.rowcount > 0:
self.db.commit()
return True
return False | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier tuple identifier if_statement comparison_operator attribute identifier identifier integer block expression_statement call attribute attribute identifier identifier identifier argument_list return_statement true return_statement false | Removes target information from vault database |
def close(self):
self.flush()
if self._recordio_writer is not None:
self._recordio_writer.close()
self._recordio_writer = None | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier none | Flushes the pending events and closes the writer after it is done. |
def skip(self, length):
if length >= self.__size:
skip_amount = self.__size
rem = length - skip_amount
self.__segments.clear()
self.__offset = 0
self.__size = 0
self.position += skip_amount
else:
rem = 0
self.read(length, skip=True)
return rem | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier binary_operator identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier integer expression_statement augmented_assignment attribute identifier identifier identifier else_clause block expression_statement assignment identifier integer expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier true return_statement identifier | Removes ``length`` bytes and returns the number length still required to skip |
def _discover(**kwargs):
query = station_server.MULTICAST_QUERY
for host, response in multicast.send(query, **kwargs):
try:
result = json.loads(response)
except ValueError:
_LOG.warn('Received bad JSON over multicast from %s: %s', host, response)
try:
yield StationInfo(result['cell'], host, result['port'],
result['station_id'], 'ONLINE',
result.get('test_description'),
result['test_name'])
except KeyError:
if 'last_activity_time_millis' in result:
_LOG.debug('Received old station API response on multicast. Ignoring.')
else:
_LOG.warn('Received bad multicast response from %s: %s', host, response) | module function_definition identifier parameters dictionary_splat_pattern identifier block expression_statement assignment identifier attribute identifier identifier for_statement pattern_list identifier identifier call attribute identifier identifier argument_list identifier dictionary_splat identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier except_clause identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier try_statement block expression_statement yield call identifier argument_list subscript identifier string string_start string_content string_end identifier subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end subscript identifier string string_start string_content string_end except_clause identifier block if_statement comparison_operator string string_start string_content string_end identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier | Yields info about station servers announcing themselves via multicast. |
def add_cache(self, namespace, key, query_hash, length, cache):
start = 0
bulk_insert = self.bulk_insert
cache_len = len(cache)
row = '(%s,%s,%s,%s,%s,%s)'
query = 'INSERT INTO gauged_cache ' \
'(namespace, key, "hash", length, start, value) VALUES '
execute = self.cursor.execute
query_hash = self.psycopg2.Binary(query_hash)
while start < cache_len:
rows = cache[start:start+bulk_insert]
params = []
for timestamp, value in rows:
params.extend((namespace, key, query_hash, length,
timestamp, value))
insert = (row + ',') * (len(rows) - 1) + row
execute(query + insert, params)
start += bulk_insert
self.db.commit() | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier integer expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier concatenated_string string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier while_statement comparison_operator identifier identifier block expression_statement assignment identifier subscript identifier slice identifier binary_operator identifier identifier expression_statement assignment identifier list for_statement pattern_list identifier identifier identifier block expression_statement call attribute identifier identifier argument_list tuple identifier identifier identifier identifier identifier identifier expression_statement assignment identifier binary_operator binary_operator parenthesized_expression binary_operator identifier string string_start string_content string_end parenthesized_expression binary_operator call identifier argument_list identifier integer identifier expression_statement call identifier argument_list binary_operator identifier identifier identifier expression_statement augmented_assignment identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list | Add cached values for the specified date range and query |
def build_xlsx_response(wb, title="report"):
title = generate_filename(title, '.xlsx')
myfile = BytesIO()
myfile.write(save_virtual_workbook(wb))
response = HttpResponse(
myfile.getvalue(),
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=%s' % title
response['Content-Length'] = myfile.tell()
return response | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end binary_operator string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list return_statement identifier | Take a workbook and return a xlsx file response |
def sync_one(self, aws_syncr, amazon, key):
key_info = amazon.kms.key_info(key.name, key.location)
if not key_info:
amazon.kms.create_key(key.name, key.description, key.location, key.grant, key.policy.document)
else:
amazon.kms.modify_key(key_info, key.name, key.description, key.location, key.grant, key.policy.document) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier if_statement not_operator identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute attribute identifier identifier identifier else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute attribute identifier identifier identifier | Make sure this key is as defined |
def pdfFromPOST(self):
html = self.request.form.get('html')
style = self.request.form.get('style')
reporthtml = "<html><head>%s</head><body><div id='report'>%s</body></html>" % (style, html)
return self.printFromHTML(safe_unicode(reporthtml).encode('utf-8')) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier binary_operator string string_start string_content string_end tuple identifier identifier return_statement call attribute identifier identifier argument_list call attribute call identifier argument_list identifier identifier argument_list string string_start string_content string_end | It returns the pdf for the sampling rounds printed |
def translate_kwargs(self, **kwargs):
local_kwargs = self.kwargs.copy()
local_kwargs.update(kwargs)
if "data" in local_kwargs and "json" in local_kwargs:
raise ValueError("Cannot use data and json together")
if "data" in local_kwargs and isinstance(local_kwargs["data"], dict):
local_kwargs.update({"json": local_kwargs["data"]})
del local_kwargs["data"]
headers = DEFAULT_HEADERS.copy()
if "headers" in kwargs:
headers.update(kwargs["headers"])
if "json" in local_kwargs:
headers.update({"Content-Type": "application/json;charset=UTF-8"})
local_kwargs.update({"headers": headers})
return local_kwargs | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier if_statement boolean_operator comparison_operator string string_start string_content string_end identifier comparison_operator string string_start string_content string_end identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement boolean_operator comparison_operator string string_start string_content string_end identifier call identifier argument_list subscript identifier string string_start string_content string_end identifier block expression_statement call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end subscript identifier string string_start string_content string_end delete_statement subscript identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator string string_start string_content string_end identifier block expression_statement call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end identifier return_statement identifier | Translate kwargs replacing `data` with `json` if necessary. |
def match_sound_mode(self, sound_mode_raw):
try:
sound_mode = self._sm_match_dict[sound_mode_raw.upper()]
return sound_mode
except KeyError:
smr_up = sound_mode_raw.upper()
self._sound_mode_dict[smr_up] = [smr_up]
self._sm_match_dict = self.construct_sm_match_dict()
_LOGGER.warning("Not able to match sound mode: '%s', "
"returning raw sound mode.", sound_mode_raw)
return sound_mode_raw | module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment identifier subscript attribute identifier identifier call attribute identifier identifier argument_list return_statement identifier except_clause identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment subscript attribute identifier identifier identifier list identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end identifier return_statement identifier | Match the raw_sound_mode to its corresponding sound_mode. |
def find(self, txt):
result = []
for d in self.data:
if txt in d:
result.append(d)
return result | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list for_statement identifier attribute identifier identifier block if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | returns a list of records containing text |
def _Resample(self, stats, target_size):
t_first = stats[0][0]
t_last = stats[-1][0]
interval = (t_last - t_first) / target_size
result = []
current_t = t_first
current_v = 0
i = 0
while i < len(stats):
stat_t = stats[i][0]
stat_v = stats[i][1]
if stat_t <= (current_t + interval):
current_v = stat_v
i += 1
else:
result.append([current_t + interval, current_v])
current_t += interval
result.append([current_t + interval, current_v])
return result | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier subscript subscript identifier integer integer expression_statement assignment identifier subscript subscript identifier unary_operator integer integer expression_statement assignment identifier binary_operator parenthesized_expression binary_operator identifier identifier identifier expression_statement assignment identifier list expression_statement assignment identifier identifier expression_statement assignment identifier integer expression_statement assignment identifier integer while_statement comparison_operator identifier call identifier argument_list identifier block expression_statement assignment identifier subscript subscript identifier identifier integer expression_statement assignment identifier subscript subscript identifier identifier integer if_statement comparison_operator identifier parenthesized_expression binary_operator identifier identifier block expression_statement assignment identifier identifier expression_statement augmented_assignment identifier integer else_clause block expression_statement call attribute identifier identifier argument_list list binary_operator identifier identifier identifier expression_statement augmented_assignment identifier identifier expression_statement call attribute identifier identifier argument_list list binary_operator identifier identifier identifier return_statement identifier | Resamples the stats to have a specific number of data points. |
def text2html_table(items):
"Put the texts in `items` in an HTML table."
html_code = f
html_code += f
for i in items[0]: html_code += f" <th>{i}</th>\n"
html_code += f" </tr>\n </thead>\n <tbody>\n"
for line in items[1:]:
html_code += " <tr>\n"
for i in line: html_code += f" <td>{i}</td>\n"
html_code += " </tr>\n"
html_code += " </tbody>\n</table><p>"
return html_code | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier identifier expression_statement augmented_assignment identifier identifier for_statement identifier subscript identifier integer block expression_statement augmented_assignment identifier string string_start string_content interpolation identifier string_content escape_sequence string_end expression_statement augmented_assignment identifier string string_start string_content escape_sequence escape_sequence escape_sequence string_end for_statement identifier subscript identifier slice integer block expression_statement augmented_assignment identifier string string_start string_content escape_sequence string_end for_statement identifier identifier block expression_statement augmented_assignment identifier string string_start string_content interpolation identifier string_content escape_sequence string_end expression_statement augmented_assignment identifier string string_start string_content escape_sequence string_end expression_statement augmented_assignment identifier string string_start string_content escape_sequence string_end return_statement identifier | Put the texts in `items` in an HTML table. |
def stop_cmd(self, name, force):
check_permissions()
if name:
echo("Would stop container {0}".format(name))
else:
echo("Would stop all containers")
echo("For now use 'docker stop' to stop the containers") | module function_definition identifier parameters identifier identifier identifier block expression_statement call identifier argument_list if_statement identifier block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier else_clause block expression_statement call identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list string string_start string_content string_end | Stop the specified or all docker containers launched by us |
def wp_slope(self):
last_w = None
for i in range(1, self.wploader.count()):
w = self.wploader.wp(i)
if w.command not in [mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, mavutil.mavlink.MAV_CMD_NAV_LAND]:
continue
if last_w is not None:
if last_w.frame != w.frame:
print("WARNING: frame change %u -> %u at %u" % (last_w.frame, w.frame, i))
delta_alt = last_w.z - w.z
if delta_alt == 0:
slope = "Level"
else:
delta_xy = mp_util.gps_distance(w.x, w.y, last_w.x, last_w.y)
slope = "%.1f" % (delta_xy / delta_alt)
print("WP%u: slope %s" % (i, slope))
last_w = w | module function_definition identifier parameters identifier block expression_statement assignment identifier none for_statement identifier call identifier argument_list integer call attribute attribute identifier identifier identifier argument_list block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement comparison_operator attribute identifier identifier list attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier block continue_statement if_statement comparison_operator identifier none block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple attribute identifier identifier attribute identifier identifier identifier expression_statement assignment identifier binary_operator attribute identifier identifier attribute identifier identifier if_statement comparison_operator identifier integer block expression_statement assignment identifier string string_start string_content string_end else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier expression_statement assignment identifier binary_operator string string_start string_content string_end parenthesized_expression binary_operator identifier identifier expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier expression_statement assignment identifier identifier | show slope of waypoints |
def limitsChanged(self, param, limits):
ParameterItem.limitsChanged(self, param, limits)
t = self.param.opts['type']
if t == 'int' or t == 'float':
self.widget.setOpts(bounds=limits)
else:
return | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier identifier identifier expression_statement assignment identifier subscript attribute attribute identifier identifier identifier string string_start string_content string_end if_statement boolean_operator comparison_operator identifier string string_start string_content string_end comparison_operator identifier string string_start string_content string_end block expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier else_clause block return_statement | Called when the parameter's limits have changed |
def update_task(deadline, label, task_id):
client = get_client()
task_doc = assemble_generic_doc("task", label=label, deadline=deadline)
res = client.update_task(task_id, task_doc)
formatted_print(res, simple_text="Success") | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement call identifier argument_list identifier keyword_argument identifier string string_start string_content string_end | Executor for `globus task update` |
def object(self, *args, **kwargs):
kwargs['api'] = self.api
return Object(*args, **kwargs) | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier return_statement call identifier argument_list list_splat identifier dictionary_splat identifier | Registers a class based router to this API |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.