code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def parse_keqv_list(l):
parsed = {}
for elt in l:
k, v = elt.split('=', 1)
if v[0] == '"' and v[-1] == '"':
v = v[1:-1]
parsed[k] = v
return parsed | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary for_statement identifier identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end integer if_statement boolean_operator comparison_operator subscript identifier integer string string_start string_content string_end comparison_operator subscript identifier unary_operator integer string string_start string_content string_end block expression_statement assignment identifier subscript identifier slice integer unary_operator integer expression_statement assignment subscript identifier identifier identifier return_statement identifier | Parse list of key=value strings where keys are not duplicated. |
async def unixlisten(path, onlink):
info = {'path': path, 'unix': True}
async def onconn(reader, writer):
link = await Link.anit(reader, writer, info=info)
link.schedCoro(onlink(link))
return await asyncio.start_unix_server(onconn, path=path) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end true function_definition identifier parameters identifier identifier block expression_statement assignment identifier await call attribute identifier identifier argument_list identifier identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier return_statement await call attribute identifier identifier argument_list identifier keyword_argument identifier identifier | Start an PF_UNIX server listening on the given path. |
def number_of_statements(self, n):
stmt_type = n.type
if stmt_type == syms.compound_stmt:
return 1
elif stmt_type == syms.stmt:
return self.number_of_statements(n.children[0])
elif stmt_type == syms.simple_stmt:
return len(n.children) // 2
else:
raise AssertionError("non-statement node") | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier attribute identifier identifier block return_statement integer elif_clause comparison_operator identifier attribute identifier identifier block return_statement call attribute identifier identifier argument_list subscript attribute identifier identifier integer elif_clause comparison_operator identifier attribute identifier identifier block return_statement binary_operator call identifier argument_list attribute identifier identifier integer else_clause block raise_statement call identifier argument_list string string_start string_content string_end | Compute the number of AST statements contained in a node. |
def single_discriminator(x, filters=128, kernel_size=8,
strides=4, pure_mean=False):
with tf.variable_scope("discriminator"):
net = layers().Conv2D(
filters, kernel_size, strides=strides, padding="SAME", name="conv1")(x)
if pure_mean:
net = tf.reduce_mean(net, [1, 2])
else:
net = mean_with_attention(net, "mean_with_attention")
return net | module function_definition identifier parameters identifier default_parameter identifier integer default_parameter identifier integer default_parameter identifier integer default_parameter identifier false block with_statement with_clause with_item call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier call call attribute call identifier argument_list identifier argument_list identifier identifier keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end argument_list identifier if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier list integer integer else_clause block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end return_statement identifier | A simple single-layer convolutional discriminator. |
def load(cls,filename):
filename = cls.correct_file_extension(filename)
with open(filename,'rb') as f:
return pickle.load(f) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block return_statement call attribute identifier identifier argument_list identifier | Load from stored files |
async def uv_protection_window(
self, low: float = 3.5, high: float = 3.5) -> dict:
return await self.request(
'get', 'protection', params={
'from': str(low),
'to': str(high)
}) | module function_definition identifier parameters identifier typed_default_parameter identifier type identifier float typed_default_parameter identifier type identifier float type identifier block return_statement await call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier dictionary pair string string_start string_content string_end call identifier argument_list identifier pair string string_start string_content string_end call identifier argument_list identifier | Get data on when a UV protection window is. |
def _extract_lower_bound(self, name: str, expr: Expression) -> Optional[Expression]:
etype = expr.etype
args = expr.args
if etype[1] in ['<=', '<']:
if args[1].is_pvariable_expression() and args[1].name == name:
return args[0]
elif etype[1] in ['>=', '>']:
if args[0].is_pvariable_expression() and args[0].name == name:
return args[1]
return None | module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type identifier type generic_type identifier type_parameter type identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator subscript identifier integer list string string_start string_content string_end string string_start string_content string_end block if_statement boolean_operator call attribute subscript identifier integer identifier argument_list comparison_operator attribute subscript identifier integer identifier identifier block return_statement subscript identifier integer elif_clause comparison_operator subscript identifier integer list string string_start string_content string_end string string_start string_content string_end block if_statement boolean_operator call attribute subscript identifier integer identifier argument_list comparison_operator attribute subscript identifier integer identifier identifier block return_statement subscript identifier integer return_statement none | Returns the lower bound expression of the action with given `name`. |
def render_field_description(field):
if hasattr(field, 'description') and field.description != '':
html =
html = html.format(
field=field
)
return HTMLString(html)
return '' | module function_definition identifier parameters identifier block if_statement boolean_operator call identifier argument_list identifier string string_start string_content string_end comparison_operator attribute identifier identifier string string_start string_end block expression_statement assignment identifier assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier return_statement call identifier argument_list identifier return_statement string string_start string_end | Render a field description as HTML. |
def stop(self):
for tile in self._tiles.values():
tile.signal_stop()
for tile in self._tiles.values():
tile.wait_stopped()
super(TileBasedVirtualDevice, self).stop() | module function_definition identifier parameters identifier block for_statement identifier call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list for_statement identifier call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list | Stop running this virtual device including any worker threads. |
def CreateGaugeMetadata(metric_name,
value_type,
fields=None,
docstring=None,
units=None):
return rdf_stats.MetricMetadata(
varname=metric_name,
metric_type=rdf_stats.MetricMetadata.MetricType.GAUGE,
value_type=MetricValueTypeFromPythonType(value_type),
fields_defs=FieldDefinitionProtosFromTuples(fields or []),
docstring=docstring,
units=units) | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none block return_statement call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier attribute attribute attribute identifier identifier identifier identifier keyword_argument identifier call identifier argument_list identifier keyword_argument identifier call identifier argument_list boolean_operator identifier list keyword_argument identifier identifier keyword_argument identifier identifier | Helper function for creating MetricMetadata for gauge metrics. |
def dump_rexobj_results(rexobj, options=None):
print("-" * 60)
print("Match count: ", rexobj.res_count)
matches = rexobj.matches
for match in matches:
print("Loc:", match.loc, ":: ")
for key in match.named_groups.keys():
print("%s: %s" %
(key, match.named_groups[key]))
print("") | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement call identifier argument_list binary_operator string string_start string_content string_end integer expression_statement call identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier attribute identifier identifier for_statement identifier identifier block expression_statement call identifier argument_list string string_start string_content string_end attribute identifier identifier string string_start string_content string_end for_statement identifier call attribute attribute identifier identifier identifier argument_list block expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier subscript attribute identifier identifier identifier expression_statement call identifier argument_list string string_start string_end | print all the results. |
def generate(env):
add_all_to_env(env)
add_f77_to_env(env)
fcomp = env.Detect(compilers) or 'g77'
if env['PLATFORM'] in ['cygwin', 'win32']:
env['SHFORTRANFLAGS'] = SCons.Util.CLVar('$FORTRANFLAGS')
env['SHF77FLAGS'] = SCons.Util.CLVar('$F77FLAGS')
else:
env['SHFORTRANFLAGS'] = SCons.Util.CLVar('$FORTRANFLAGS -fPIC')
env['SHF77FLAGS'] = SCons.Util.CLVar('$F77FLAGS -fPIC')
env['FORTRAN'] = fcomp
env['SHFORTRAN'] = '$FORTRAN'
env['F77'] = fcomp
env['SHF77'] = '$F77'
env['INCFORTRANPREFIX'] = "-I"
env['INCFORTRANSUFFIX'] = ""
env['INCF77PREFIX'] = "-I"
env['INCF77SUFFIX'] = "" | module function_definition identifier parameters identifier block expression_statement call identifier argument_list identifier expression_statement call identifier argument_list identifier expression_statement assignment identifier boolean_operator call attribute identifier identifier argument_list identifier string string_start string_content string_end if_statement comparison_operator subscript identifier string string_start string_content string_end list string string_start string_content string_end string string_start string_content string_end block expression_statement assignment subscript identifier string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end else_clause block expression_statement assignment subscript identifier string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_end expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_end | Add Builders and construction variables for g77 to an Environment. |
def node_labels(self):
assert list(self.node_indices)[0] == 0
labels = list("m{}".format(i) for i in self.node_indices)
return NodeLabels(labels, self.node_indices) | module function_definition identifier parameters identifier block assert_statement comparison_operator subscript call identifier argument_list attribute identifier identifier integer integer expression_statement assignment identifier call identifier generator_expression call attribute string string_start string_content string_end identifier argument_list identifier for_in_clause identifier attribute identifier identifier return_statement call identifier argument_list identifier attribute identifier identifier | Return the labels for macro nodes. |
def list_availability_zones(self, retrieve_all=True, **_params):
return self.list('availability_zones', self.availability_zones_path,
retrieve_all, **_params) | module function_definition identifier parameters identifier default_parameter identifier true dictionary_splat_pattern identifier block return_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier identifier dictionary_splat identifier | Fetches a list of all availability zones. |
def load_stanzas(stanzas_file):
f = stanzas_file.readlines()
stanzas = []
for i, line in enumerate(f):
if i % 4 == 0:
stanza_words = line.strip().split()[1:]
stanzas.append(Stanza(stanza_words))
return stanzas | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier list for_statement pattern_list identifier identifier call identifier argument_list identifier block if_statement comparison_operator binary_operator identifier integer integer block expression_statement assignment identifier subscript call attribute call attribute identifier identifier argument_list identifier argument_list slice integer expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier return_statement identifier | Load stanzas from gold standard file |
def to_pascal_case(s):
return re.sub(r'(?!^)_([a-zA-Z])', lambda m: m.group(1).upper(), s.capitalize()) | module function_definition identifier parameters identifier block return_statement call attribute identifier identifier argument_list string string_start string_content string_end lambda lambda_parameters identifier call attribute call attribute identifier identifier argument_list integer identifier argument_list call attribute identifier identifier argument_list | Transform underscore separated string to pascal case |
def _TTA(learn:Learner, beta:float=0.4, scale:float=1.35, ds_type:DatasetType=DatasetType.Valid, with_loss:bool=False) -> Tensors:
"Applies TTA to predict on `ds_type` dataset."
preds,y = learn.get_preds(ds_type)
all_preds = list(learn.tta_only(scale=scale, ds_type=ds_type))
avg_preds = torch.stack(all_preds).mean(0)
if beta is None: return preds,avg_preds,y
else:
final_preds = preds*beta + avg_preds*(1-beta)
if with_loss:
with NoneReduceOnCPU(learn.loss_func) as lf: loss = lf(final_preds, y)
return final_preds, y, loss
return final_preds, y | module function_definition identifier parameters typed_parameter identifier type identifier typed_default_parameter identifier type identifier float typed_default_parameter identifier type identifier float typed_default_parameter identifier type identifier attribute identifier identifier typed_default_parameter identifier type identifier false type identifier block expression_statement string string_start string_content string_end expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier identifier argument_list integer if_statement comparison_operator identifier none block return_statement expression_list identifier identifier identifier else_clause block expression_statement assignment identifier binary_operator binary_operator identifier identifier binary_operator identifier parenthesized_expression binary_operator integer identifier if_statement identifier block with_statement with_clause with_item as_pattern call identifier argument_list attribute identifier identifier as_pattern_target identifier block expression_statement assignment identifier call identifier argument_list identifier identifier return_statement expression_list identifier identifier identifier return_statement expression_list identifier identifier | Applies TTA to predict on `ds_type` dataset. |
def send_complete(self):
self.active = True
if self.should_finish():
self._detach()
if not self._finished:
self.safe_finish()
else:
if self.session:
self.session.flush() | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier true if_statement call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list if_statement not_operator attribute identifier identifier block expression_statement call attribute identifier identifier argument_list else_clause block if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list | Verify if connection should be closed based on amount of data that was sent. |
def float_format(self, value):
if isinstance(value, str):
'{0:{1}}'.format(1.23, value)
self._float_format = value
else:
raise TypeError('Floating point format code must be a string.') | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement call attribute string string_start string_content string_end identifier argument_list float identifier expression_statement assignment attribute identifier identifier identifier else_clause block raise_statement call identifier argument_list string string_start string_content string_end | Validate and set the upper case flag. |
def Start(self):
with data_store.DB.GetMutationPool() as mutation_pool:
self.CreateCollections(mutation_pool)
if not self.runner_args.description:
self.SetDescription() | module function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call attribute attribute identifier identifier identifier argument_list as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier if_statement not_operator attribute attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list | Initializes this hunt from arguments. |
def lazy_result(f):
@wraps(f)
def decorated(ctx, param, value):
return LocalProxy(lambda: f(ctx, param, value))
return decorated | module function_definition identifier parameters identifier block decorated_definition decorator call identifier argument_list identifier function_definition identifier parameters identifier identifier identifier block return_statement call identifier argument_list lambda call identifier argument_list identifier identifier identifier return_statement identifier | Decorate function to return LazyProxy. |
def read_tcp_size(conn, size):
chunks = []
bytes_read = 0
while bytes_read < size:
chunk = conn.recv(size - bytes_read)
if not chunk:
if bytes_read > 0:
logging.warning("Incomplete read: %s of %s.", bytes_read, size)
return
chunks.append(chunk)
bytes_read += len(chunk)
return b"".join(chunks) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list expression_statement assignment identifier integer while_statement comparison_operator identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator identifier identifier if_statement not_operator identifier block if_statement comparison_operator identifier integer block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier return_statement expression_statement call attribute identifier identifier argument_list identifier expression_statement augmented_assignment identifier call identifier argument_list identifier return_statement call attribute string string_start string_end identifier argument_list identifier | Read `size` number of bytes from `conn`, retrying as needed. |
def _reindex_axes(self, axes, level, limit, tolerance, method, fill_value,
copy):
obj = self
for a in self._AXIS_ORDERS:
labels = axes[a]
if labels is None:
continue
ax = self._get_axis(a)
new_index, indexer = ax.reindex(labels, level=level, limit=limit,
tolerance=tolerance, method=method)
axis = self._get_axis_number(a)
obj = obj._reindex_with_indexers({axis: [new_index, indexer]},
fill_value=fill_value,
copy=copy, allow_dups=False)
return obj | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier identifier for_statement identifier attribute identifier identifier block expression_statement assignment identifier subscript identifier identifier if_statement comparison_operator identifier none block continue_statement expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list dictionary pair identifier list identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier false return_statement identifier | Perform the reindex for all the axes. |
def from_iso(cls, iso):
result = cls.list({'sort_by': 'id ASC'})
dc_isos = {}
for dc in result:
if dc['iso'] not in dc_isos:
dc_isos[dc['iso']] = dc['id']
return dc_isos.get(iso) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier dictionary for_statement identifier identifier block if_statement comparison_operator subscript identifier string string_start string_content string_end identifier block expression_statement assignment subscript identifier subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end return_statement call attribute identifier identifier argument_list identifier | Retrieve the first datacenter id associated to an ISO. |
def getAnalysisServicesVocabulary(self):
bsc = getToolByName(self, 'bika_setup_catalog')
brains = bsc(portal_type='AnalysisService',
is_active=True)
items = [(b.UID, b.Title) for b in brains]
items.insert(0, ("", ""))
items.sort(lambda x, y: cmp(x[1], y[1]))
return DisplayList(list(items)) | module function_definition identifier parameters identifier 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 keyword_argument identifier string string_start string_content string_end keyword_argument identifier true expression_statement assignment identifier list_comprehension tuple attribute identifier identifier attribute identifier identifier for_in_clause identifier identifier expression_statement call attribute identifier identifier argument_list integer tuple string string_start string_end string string_start string_end expression_statement call attribute identifier identifier argument_list lambda lambda_parameters identifier identifier call identifier argument_list subscript identifier integer subscript identifier integer return_statement call identifier argument_list call identifier argument_list identifier | Get all active Analysis Services from Bika Setup and return them as Display List. |
def add_access_element_info(self, access_element):
service_name = access_element.attrib['serviceName']
url_path = access_element.attrib['urlPath']
self.access_element_info[service_name] = url_path | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment subscript attribute identifier identifier identifier identifier | Create an access method from a catalog element. |
def _request(self, data):
return requests.post(self.endpoint, data=data.encode("ascii")).content | module function_definition identifier parameters identifier identifier block return_statement attribute call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier | Moved out to make testing easier. |
def main(argv):
del argv
flags.mark_flag_as_required('load_file')
run_game(
load_file=FLAGS.load_file,
selfplay_dir=FLAGS.selfplay_dir,
holdout_dir=FLAGS.holdout_dir,
holdout_pct=FLAGS.holdout_pct,
sgf_dir=FLAGS.sgf_dir) | module function_definition identifier parameters identifier block delete_statement identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call 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 | Entry point for running one selfplay game. |
def removeCurrentItem(self):
logger.debug("removeCurrentFile")
currentIndex = self.getRowCurrentIndex()
if not currentIndex.isValid():
return
self.model().deleteItemAtIndex(currentIndex) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list if_statement not_operator call attribute identifier identifier argument_list block return_statement expression_statement call attribute call attribute identifier identifier argument_list identifier argument_list identifier | Removes the current item from the repository tree. |
def y0(x, context=None):
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_y0,
(BigFloat._implicit_convert(x),),
context,
) | module function_definition identifier parameters identifier default_parameter identifier none block return_statement call identifier argument_list identifier attribute identifier identifier tuple call attribute identifier identifier argument_list identifier identifier | Return the value of the second kind Bessel function of order 0 at x. |
def grant_authority(self, column=None, value=None, **kwargs):
return self._resolve_call('GIC_GRANT_AUTH', column, value, **kwargs) | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none dictionary_splat_pattern identifier block return_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier dictionary_splat identifier | Many-to-many table connecting grants and authority. |
def add_function(self, function):
if not len(self.settings.FUNCTION_MANAGERS):
raise ConfigurationError(
'Where have the default function manager gone?!')
self.settings.FUNCTION_MANAGERS[0].add_function(function) | module function_definition identifier parameters identifier identifier block if_statement not_operator call identifier argument_list attribute attribute identifier identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement call attribute subscript attribute attribute identifier identifier identifier integer identifier argument_list identifier | Registers the function to the server's default fixed function manager. |
def encode(self, obj):
s = super(CustomEncoder, self).encode(obj)
if len(s.splitlines()) > 1:
s = self.postprocess(s)
return s | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier identifier argument_list identifier if_statement comparison_operator call identifier argument_list call attribute identifier identifier argument_list integer block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement identifier | Fired for every object. |
def bnode_id(self):
if self.subject.type != 'bnode':
return self.subject
rtn_list = []
for prop in sorted(self):
for value in sorted(self[prop]):
rtn_list.append("%s%s" % (prop, value))
return sha1("".join(rtn_list).encode()).hexdigest() | module function_definition identifier parameters identifier block if_statement comparison_operator attribute attribute identifier identifier identifier string string_start string_content string_end block return_statement attribute identifier identifier expression_statement assignment identifier list for_statement identifier call identifier argument_list identifier block for_statement identifier call identifier argument_list subscript identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier return_statement call attribute call identifier argument_list call attribute call attribute string string_start string_end identifier argument_list identifier identifier argument_list identifier argument_list | calculates the bnode id for the class |
def _plot(self):
for serie in self.series[::-1 if self.stack_from_top else 1]:
self.bar(serie)
for serie in self.secondary_series[::-1 if self.stack_from_top else 1]:
self.bar(serie, True) | module function_definition identifier parameters identifier block for_statement identifier subscript attribute identifier identifier slice conditional_expression unary_operator integer attribute identifier identifier integer block expression_statement call attribute identifier identifier argument_list identifier for_statement identifier subscript attribute identifier identifier slice conditional_expression unary_operator integer attribute identifier identifier integer block expression_statement call attribute identifier identifier argument_list identifier true | Draw bars for series and secondary series |
def min_cost(self):
if self._min_cost:
return self._min_cost
self._min_cost = np.sum(self.c[np.arange(self.nx), self.solution])
return self._min_cost | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block return_statement attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list subscript attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier return_statement attribute identifier identifier | Returns the cost of the best assignment |
def python_like_exts():
exts = []
for lang in languages.PYTHON_LIKE_LANGUAGES:
exts.extend(list(languages.ALL_LANGUAGES[lang]))
return ['.' + ext for ext in exts] | module function_definition identifier parameters block expression_statement assignment identifier list for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list subscript attribute identifier identifier identifier return_statement list_comprehension binary_operator string string_start string_content string_end identifier for_in_clause identifier identifier | Return a list of all python-like extensions |
def parse(string):
"return a BaseX tree for the string"
print string
if string.strip().lower().startswith('create index'): return IndexX(string)
return YACC.parse(string, lexer=LEXER.clone()) | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end print_statement identifier if_statement call attribute call attribute call attribute identifier identifier argument_list identifier argument_list identifier argument_list string string_start string_content string_end block return_statement call identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier keyword_argument identifier call attribute identifier identifier argument_list | return a BaseX tree for the string |
def _restore_constructor(self, cls):
cls.__init__ = self._observers[cls].init
del self._observers[cls] | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier attribute subscript attribute identifier identifier identifier identifier delete_statement subscript attribute identifier identifier identifier | Restore the original constructor, lose track of class. |
def _remove_summary(self):
if self.size > 0:
print("\nRemoved summary")
print("=" * 79)
print("{0}Size of removed packages {1} {2}.{3}".format(
self.meta.color["GREY"], round(self.size, 2), self.unit,
self.meta.color["ENDC"])) | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier integer block expression_statement call identifier argument_list string string_start string_content escape_sequence string_end expression_statement call identifier argument_list binary_operator string string_start string_content string_end integer expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list subscript attribute attribute identifier identifier identifier string string_start string_content string_end call identifier argument_list attribute identifier identifier integer attribute identifier identifier subscript attribute attribute identifier identifier identifier string string_start string_content string_end | Removed packge size summary |
def check_recaptcha(view_func):
@wraps(view_func)
def _wrapped_view(request, *args, **kwargs):
request.recaptcha_is_valid = None
if request.method == 'POST':
recaptcha_response = request.POST.get('g-recaptcha-response')
data = {
'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
'response': recaptcha_response
}
r = requests.post(
'https://www.google.com/recaptcha/api/siteverify',
data=data
)
result = r.json()
if result['success']:
request.recaptcha_is_valid = True
else:
request.recaptcha_is_valid = False
error_message = 'Invalid reCAPTCHA. Please try again. '
error_message += str(result['error-codes'])
print(error_message)
return view_func(request, *args, **kwargs)
return _wrapped_view | module function_definition identifier parameters identifier block decorated_definition decorator call identifier argument_list identifier function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment attribute identifier identifier none if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list 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 identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list if_statement subscript identifier string string_start string_content string_end block expression_statement assignment attribute identifier identifier true else_clause block expression_statement assignment attribute identifier identifier false expression_statement assignment identifier string string_start string_content string_end expression_statement augmented_assignment identifier call identifier argument_list subscript identifier string string_start string_content string_end expression_statement call identifier argument_list identifier return_statement call identifier argument_list identifier list_splat identifier dictionary_splat identifier return_statement identifier | Chech that the entered recaptcha data is correct |
def post(self):
self.reqparse.add_argument('templateName', type=str, required=True)
self.reqparse.add_argument('template', type=str, required=True)
args = self.reqparse.parse_args()
template = db.Template.find_one(template_name=args['templateName'])
if template:
return self.make_response('Template already exists, update the existing template instead', HTTP.CONFLICT)
template = Template()
template.template_name = args['templateName']
template.template = args['template']
db.session.add(template)
db.session.commit()
auditlog(event='template.create', actor=session['user'].username, data=args)
return self.make_response('Template {} has been created'.format(template.template_name), HTTP.CREATED) | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier true expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier true expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier subscript identifier string string_start string_content string_end if_statement identifier block return_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier call identifier argument_list expression_statement assignment attribute identifier identifier subscript identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier subscript identifier string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier attribute subscript identifier string string_start string_content string_end identifier keyword_argument identifier identifier return_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier attribute identifier identifier | Create a new template |
def to_edit(self, postid):
if self.userinfo.role[0] > '0':
pass
else:
return False
kwd = {}
self.render('man_info/wiki_man_edit.html',
userinfo=self.userinfo,
postinfo=MWiki.get_by_uid(postid),
kwd=kwd) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator subscript attribute attribute identifier identifier identifier integer string string_start string_content string_end block pass_statement else_clause block return_statement false expression_statement assignment identifier dictionary expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier attribute identifier identifier keyword_argument identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier | Try to edit the Post. |
def parse_args( self, args = None, values = None ):
q = multiproc.Queue()
p = multiproc.Process(target=self._parse_args, args=(q, args, values))
p.start()
ret = q.get()
p.join()
return ret | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier tuple identifier identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list return_statement identifier | multiprocessing wrapper around _parse_args |
def yaw_pitch(self):
if not self:
return YawPitch(0, 0)
ground_distance = math.sqrt(self.x ** 2 + self.z ** 2)
if ground_distance:
alpha1 = -math.asin(self.x / ground_distance) / math.pi * 180
alpha2 = math.acos(self.z / ground_distance) / math.pi * 180
if alpha2 > 90:
yaw = 180 - alpha1
else:
yaw = alpha1
pitch = math.atan2(-self.y, ground_distance) / math.pi * 180
else:
yaw = 0
y = round(self.y)
if y > 0:
pitch = -90
elif y < 0:
pitch = 90
else:
pitch = 0
return YawPitch(yaw, pitch) | module function_definition identifier parameters identifier block if_statement not_operator identifier block return_statement call identifier argument_list integer integer expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator binary_operator attribute identifier identifier integer binary_operator attribute identifier identifier integer if_statement identifier block expression_statement assignment identifier binary_operator binary_operator unary_operator call attribute identifier identifier argument_list binary_operator attribute identifier identifier identifier attribute identifier identifier integer expression_statement assignment identifier binary_operator binary_operator call attribute identifier identifier argument_list binary_operator attribute identifier identifier identifier attribute identifier identifier integer if_statement comparison_operator identifier integer block expression_statement assignment identifier binary_operator integer identifier else_clause block expression_statement assignment identifier identifier expression_statement assignment identifier binary_operator binary_operator call attribute identifier identifier argument_list unary_operator attribute identifier identifier identifier attribute identifier identifier integer else_clause block expression_statement assignment identifier integer expression_statement assignment identifier call identifier argument_list attribute identifier identifier if_statement comparison_operator identifier integer block expression_statement assignment identifier unary_operator integer elif_clause comparison_operator identifier integer block expression_statement assignment identifier integer else_clause block expression_statement assignment identifier integer return_statement call identifier argument_list identifier identifier | Calculate the yaw and pitch of this vector |
def end_headers(self):
if self.request_version != 'HTTP/0.9':
self._headers_buffer.append(b"\r\n")
self.flush_headers() | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content escape_sequence escape_sequence string_end expression_statement call attribute identifier identifier argument_list | Send the blank line ending the MIME headers. |
def update(site=False, organizations=False, users=False, datasets=False,
reuses=False):
do_all = not any((site, organizations, users, datasets, reuses))
if do_all or site:
log.info('Update site metrics')
update_site_metrics()
if do_all or datasets:
log.info('Update datasets metrics')
for dataset in Dataset.objects.timeout(False):
update_metrics_for(dataset)
if do_all or reuses:
log.info('Update reuses metrics')
for reuse in Reuse.objects.timeout(False):
update_metrics_for(reuse)
if do_all or organizations:
log.info('Update organizations metrics')
for organization in Organization.objects.timeout(False):
update_metrics_for(organization)
if do_all or users:
log.info('Update user metrics')
for user in User.objects.timeout(False):
update_metrics_for(user)
success('All metrics have been updated') | module function_definition identifier parameters default_parameter identifier false default_parameter identifier false default_parameter identifier false default_parameter identifier false default_parameter identifier false block expression_statement assignment identifier not_operator call identifier argument_list tuple identifier identifier identifier identifier identifier if_statement boolean_operator identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list if_statement boolean_operator identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end for_statement identifier call attribute attribute identifier identifier identifier argument_list false block expression_statement call identifier argument_list identifier if_statement boolean_operator identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end for_statement identifier call attribute attribute identifier identifier identifier argument_list false block expression_statement call identifier argument_list identifier if_statement boolean_operator identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end for_statement identifier call attribute attribute identifier identifier identifier argument_list false block expression_statement call identifier argument_list identifier if_statement boolean_operator identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end for_statement identifier call attribute attribute identifier identifier identifier argument_list false block expression_statement call identifier argument_list identifier expression_statement call identifier argument_list string string_start string_content string_end | Update all metrics for the current date |
def build_from_issue_comment(gh_token, body):
if body["action"] in ["created", "edited"]:
github_con = Github(gh_token)
repo = github_con.get_repo(body['repository']['full_name'])
issue = repo.get_issue(body['issue']['number'])
text = body['comment']['body']
try:
comment = issue.get_comment(body['comment']['id'])
except UnknownObjectException:
return None
return WebhookMetadata(repo, issue, text, comment)
return None | module function_definition identifier parameters identifier identifier block if_statement comparison_operator subscript identifier string string_start string_content string_end list string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list subscript subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list subscript subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier subscript subscript identifier string string_start string_content string_end string string_start string_content string_end try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list subscript subscript identifier string string_start string_content string_end string string_start string_content string_end except_clause identifier block return_statement none return_statement call identifier argument_list identifier identifier identifier identifier return_statement none | Create a WebhookMetadata from a comment added to an issue. |
def update(self, old, new):
i = self.rank[old]
del self.rank[old]
self.heap[i] = new
self.rank[new] = i
if old < new:
self.down(i)
else:
self.up(i) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier identifier delete_statement subscript attribute identifier identifier identifier expression_statement assignment subscript attribute identifier identifier identifier identifier expression_statement assignment subscript attribute identifier identifier identifier identifier if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier | Replace an element in the heap |
def _logs_options(p):
_default_options(p, blacklist=['cache', 'quiet'])
p.add_argument(
'--start',
default='the beginning',
help='Start date and/or time',
)
p.add_argument(
'--end',
default=datetime.now().strftime('%c'),
help='End date and/or time',
) | module function_definition identifier parameters identifier block expression_statement call identifier argument_list identifier keyword_argument identifier list 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 keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier call attribute call attribute identifier identifier argument_list identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end | Add options specific to logs subcommand. |
def available_backups(self):
if not hasattr(self, '_avail_backups'):
result = self._client.get("{}/backups".format(Instance.api_endpoint), model=self)
if not 'automatic' in result:
raise UnexpectedResponseError('Unexpected response loading available backups!', json=result)
automatic = []
for a in result['automatic']:
cur = Backup(self._client, a['id'], self.id, a)
automatic.append(cur)
snap = None
if result['snapshot']['current']:
snap = Backup(self._client, result['snapshot']['current']['id'], self.id,
result['snapshot']['current'])
psnap = None
if result['snapshot']['in_progress']:
psnap = Backup(self._client, result['snapshot']['in_progress']['id'], self.id,
result['snapshot']['in_progress'])
self._set('_avail_backups', MappedObject(**{
"automatic": automatic,
"snapshot": {
"current": snap,
"in_progress": psnap,
}
}))
return self._avail_backups | module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier keyword_argument identifier identifier if_statement not_operator comparison_operator string string_start string_content string_end identifier block raise_statement call identifier argument_list string string_start string_content string_end keyword_argument identifier identifier expression_statement assignment identifier list for_statement identifier subscript identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list attribute identifier identifier subscript identifier string string_start string_content string_end attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier none if_statement subscript subscript identifier string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list attribute identifier identifier subscript subscript subscript identifier string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end attribute identifier identifier subscript subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier none if_statement subscript subscript identifier string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list attribute identifier identifier subscript subscript subscript identifier string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end attribute identifier 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 call identifier argument_list dictionary_splat dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier return_statement attribute identifier identifier | The backups response contains what backups are available to be restored. |
def _get_node(self):
data = self.meta.read(self.node_size)
return PFSNode(data, self.endianness) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier return_statement call identifier argument_list identifier attribute identifier identifier | Reads a chunk of meta data from file and returns a PFSNode. |
def _id_or_key(list_item):
if isinstance(list_item, dict):
if 'id' in list_item:
return list_item['id']
if 'key' in list_item:
return list_item['key']
return list_item | module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier identifier block if_statement comparison_operator string string_start string_content string_end identifier block return_statement subscript identifier string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block return_statement subscript identifier string string_start string_content string_end return_statement identifier | Return the value at key 'id' or 'key'. |
def check_cpu_interval(self, cpu_process):
try:
if not cpu_process.is_alive():
log.critical("raise SystemExit, because CPU is not alive.")
_thread.interrupt_main()
raise SystemExit("Kill pager.getch()")
except KeyboardInterrupt:
_thread.interrupt_main()
else:
t = threading.Timer(1.0, self.check_cpu_interval, args=[cpu_process])
t.start() | module function_definition identifier parameters identifier identifier block try_statement block if_statement not_operator call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list raise_statement call identifier argument_list string string_start string_content string_end except_clause identifier block expression_statement call attribute identifier identifier argument_list else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list float attribute identifier identifier keyword_argument identifier list identifier expression_statement call attribute identifier identifier argument_list | work-a-round for blocking input |
def index(elem):
parent = elem.getparent()
for x in range(0, len(parent.getchildren())):
if parent.getchildren()[x] == elem:
return x
return -1 | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list for_statement identifier call identifier argument_list integer call identifier argument_list call attribute identifier identifier argument_list block if_statement comparison_operator subscript call attribute identifier identifier argument_list identifier identifier block return_statement identifier return_statement unary_operator integer | Return the index position of an element in the children of a parent. |
def overflow(self):
indices = self.hist.xyz(self.idx)
for i in range(self.hist.GetDimension()):
if indices[i] == 0 or indices[i] == self.hist.nbins(i) + 1:
return True
return False | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier for_statement identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list block if_statement boolean_operator comparison_operator subscript identifier identifier integer comparison_operator subscript identifier identifier binary_operator call attribute attribute identifier identifier identifier argument_list identifier integer block return_statement true return_statement false | Returns true if this BinProxy is for an overflow bin |
def eval_function(value):
name, args = value[0], value[1:]
if name == "NOW":
return datetime.utcnow().replace(tzinfo=tzutc())
elif name in ["TIMESTAMP", "TS"]:
return parse(unwrap(args[0])).replace(tzinfo=tzlocal())
elif name in ["UTCTIMESTAMP", "UTCTS"]:
return parse(unwrap(args[0])).replace(tzinfo=tzutc())
elif name == "MS":
return 1000 * resolve(args[0])
else:
raise SyntaxError("Unrecognized function %r" % name) | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier expression_list subscript identifier integer subscript identifier slice integer if_statement comparison_operator identifier string string_start string_content string_end block return_statement call attribute call attribute identifier identifier argument_list identifier argument_list keyword_argument identifier call identifier argument_list elif_clause comparison_operator identifier list string string_start string_content string_end string string_start string_content string_end block return_statement call attribute call identifier argument_list call identifier argument_list subscript identifier integer identifier argument_list keyword_argument identifier call identifier argument_list elif_clause comparison_operator identifier list string string_start string_content string_end string string_start string_content string_end block return_statement call attribute call identifier argument_list call identifier argument_list subscript identifier integer identifier argument_list keyword_argument identifier call identifier argument_list elif_clause comparison_operator identifier string string_start string_content string_end block return_statement binary_operator integer call identifier argument_list subscript identifier integer else_clause block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier | Evaluate a timestamp function |
def keystroke_model():
model = Pohmm(n_hidden_states=2,
init_spread=2,
emissions=['lognormal', 'lognormal'],
smoothing='freq',
init_method='obs',
thresh=1)
return model | module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list keyword_argument identifier integer keyword_argument identifier integer keyword_argument identifier list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier integer return_statement identifier | Generates a 2-state model with lognormal emissions and frequency smoothing |
def query_by_post(postid):
return TabReply.select().where(
TabReply.post_id == postid
).order_by(TabReply.timestamp.desc()) | module function_definition identifier parameters identifier block return_statement call attribute call attribute call attribute identifier identifier argument_list identifier argument_list comparison_operator attribute identifier identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list | Get reply list of certain post. |
def _convert_to_indexer(self, obj, axis=None, is_setter=False):
if axis is None:
axis = self.axis or 0
if isinstance(obj, slice):
return self._convert_slice_indexer(obj, axis)
elif is_float(obj):
return self._convert_scalar_indexer(obj, axis)
try:
self._validate_key(obj, axis)
return obj
except ValueError:
raise ValueError("Can only index by location with "
"a [{types}]".format(types=self._valid_types)) | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier false block if_statement comparison_operator identifier none block expression_statement assignment identifier boolean_operator attribute identifier identifier integer if_statement call identifier argument_list identifier identifier block return_statement call attribute identifier identifier argument_list identifier identifier elif_clause call identifier argument_list identifier block return_statement call attribute identifier identifier argument_list identifier identifier try_statement block expression_statement call attribute identifier identifier argument_list identifier identifier return_statement identifier except_clause identifier block raise_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 attribute identifier identifier | much simpler as we only have to deal with our valid types |
def do_preprocess(defn):
from pycparser.ply import lex, cpp
lexer = lex.lex(cpp)
p = cpp.Preprocessor(lexer)
p.parse(defn)
return ''.join(tok.value for tok in p.parser if tok.type not in p.ignore) | module function_definition identifier parameters identifier block import_from_statement dotted_name identifier identifier dotted_name identifier dotted_name identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier return_statement call attribute string string_start string_end identifier generator_expression attribute identifier identifier for_in_clause identifier attribute identifier identifier if_clause comparison_operator attribute identifier identifier attribute identifier identifier | Run a string through the C preprocessor that ships with pycparser but is weirdly inaccessible? |
def expected_signature(self):
k_secret = b"AWS4" + self.key_mapping[self.access_key].encode("utf-8")
k_date = hmac.new(k_secret, self.request_date.encode("utf-8"),
sha256).digest()
k_region = hmac.new(k_date, self.region.encode("utf-8"),
sha256).digest()
k_service = hmac.new(k_region, self.service.encode("utf-8"),
sha256).digest()
k_signing = hmac.new(k_service, _aws4_request_bytes, sha256).digest()
return hmac.new(k_signing, self.string_to_sign.encode("utf-8"),
sha256).hexdigest() | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end call attribute subscript attribute identifier identifier attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier identifier argument_list expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier identifier argument_list expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier identifier argument_list expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier identifier identifier identifier argument_list return_statement call attribute call attribute identifier identifier argument_list identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier identifier argument_list | The AWS SigV4 signature expected from the request. |
def compute_coordinates(self):
self._x, self._y = self.board.index_to_coordinates(self.index) | module function_definition identifier parameters identifier block expression_statement assignment pattern_list attribute identifier identifier attribute identifier identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier | Compute 2D coordinates of the piece. |
def flowtable(self):
ftable = dict()
for table in self.flow_table:
for k, v in table.items():
if k not in ftable:
ftable[k] = set(v)
else:
[ftable[k].add(i) for i in v]
for k in ftable:
ftable[k] = list(ftable[k])
return ftable | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list for_statement identifier attribute identifier identifier block 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 call identifier argument_list identifier else_clause block expression_statement list_comprehension call attribute subscript identifier identifier identifier argument_list identifier for_in_clause identifier identifier for_statement identifier identifier block expression_statement assignment subscript identifier identifier call identifier argument_list subscript identifier identifier return_statement identifier | get a flat flow table globally |
def resolve_sorting(self, query):
sorting = {}
sort_on = query.get("sidx", None)
sort_on = sort_on or query.get("sort_on", None)
sort_on = sort_on == "Title" and "sortable_title" or sort_on
if sort_on:
sorting["sort_on"] = sort_on
sort_order = query.get("sord", None)
sort_order = sort_order or query.get("sort_order", None)
if sort_order in ["desc", "reverse", "rev", "descending"]:
sorting["sort_order"] = "descending"
else:
sorting["sort_order"] = "ascending"
sort_limit = api.to_int(query.get("limit", 30), default=30)
if sort_limit:
sorting["sort_limit"] = sort_limit
return sorting | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end none expression_statement assignment identifier boolean_operator identifier call attribute identifier identifier argument_list string string_start string_content string_end none expression_statement assignment identifier boolean_operator boolean_operator comparison_operator identifier string string_start string_content string_end string string_start string_content string_end identifier if_statement identifier block expression_statement assignment subscript identifier 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 none expression_statement assignment identifier boolean_operator identifier call attribute identifier identifier argument_list string string_start string_content string_end none if_statement comparison_operator 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 block expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_content string_end else_clause block expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end integer keyword_argument identifier integer if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier return_statement identifier | Resolves the sorting criteria for the given query |
def _call(self, method, *args, **kwargs):
assert self.session
if not kwargs.get('verify'):
kwargs['verify'] = self.SSL_VERIFY
response = self.session.request(method, *args, **kwargs)
response_json = response.text and response.json() or {}
if response.status_code < 200 or response.status_code >= 300:
message = response_json.get('error', response_json.get('message'))
raise HelpScoutRemoteException(response.status_code, message)
self.page_current = response_json.get(self.PAGE_CURRENT, 1)
self.page_total = response_json.get(self.PAGE_TOTAL, 1)
try:
return response_json[self.PAGE_DATA_MULTI]
except KeyError:
pass
try:
return [response_json[self.PAGE_DATA_SINGLE]]
except KeyError:
pass
return None | module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block assert_statement attribute identifier identifier if_statement not_operator call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier list_splat identifier dictionary_splat identifier expression_statement assignment identifier boolean_operator boolean_operator attribute identifier identifier call attribute identifier identifier argument_list dictionary if_statement boolean_operator comparison_operator attribute identifier identifier integer comparison_operator attribute identifier identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end raise_statement call identifier argument_list attribute identifier identifier identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier integer expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier integer try_statement block return_statement subscript identifier attribute identifier identifier except_clause identifier block pass_statement try_statement block return_statement list subscript identifier attribute identifier identifier except_clause identifier block pass_statement return_statement none | Call the remote service and return the response data. |
def _save_lang(self):
for combobox, (option, _default) in list(self.comboboxes.items()):
if option == 'interface_language':
data = combobox.itemData(combobox.currentIndex())
value = from_qvariant(data, to_text_string)
break
try:
save_lang_conf(value)
self.set_option('interface_language', value)
except Exception:
QMessageBox.critical(
self, _("Error"),
_("We're sorry but the following error occurred while trying "
"to set your selected language:<br><br>"
"<tt>{}</tt>").format(traceback.format_exc()),
QMessageBox.Ok)
return | module function_definition identifier parameters identifier block for_statement pattern_list identifier tuple_pattern identifier identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list block if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list identifier identifier break_statement try_statement block expression_statement call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier except_clause identifier block expression_statement call attribute identifier identifier argument_list identifier call identifier argument_list string string_start string_content string_end call attribute call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier return_statement | Get selected language setting and save to language configuration file. |
def add_column(self, table, name='ID', data_type='int(11)', after_col=None, null=False, primary_key=False):
location = 'AFTER {0}'.format(after_col) if after_col else 'FIRST'
null_ = 'NULL' if null else 'NOT NULL'
comment = "COMMENT 'Column auto created by mysql-toolkit'"
pk = 'AUTO_INCREMENT PRIMARY KEY {0}'.format(comment) if primary_key else ''
query = 'ALTER TABLE {0} ADD COLUMN {1} {2} {3} {4} {5}'.format(wrap(table), name, data_type, null_, pk,
location)
self.execute(query)
self._printer("\tAdded column '{0}' to '{1}' {2}".format(name, table, '(Primary Key)' if primary_key else ''))
return name | module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end default_parameter identifier string string_start string_content string_end default_parameter identifier none default_parameter identifier false default_parameter identifier false block expression_statement assignment identifier conditional_expression call attribute string string_start string_content string_end identifier argument_list identifier identifier string string_start string_content string_end expression_statement assignment identifier conditional_expression string string_start string_content string_end identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier conditional_expression call attribute string string_start string_content string_end identifier argument_list identifier identifier string string_start string_end expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier identifier identifier identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier identifier conditional_expression string string_start string_content string_end identifier string string_start string_end return_statement identifier | Add a column to an existing table. |
def visit_pass(self, node, parent):
return nodes.Pass(node.lineno, node.col_offset, parent) | module function_definition identifier parameters identifier identifier identifier block return_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier identifier | visit a Pass node by returning a fresh instance of it |
def strategyLastK(kls, n, k=10):
return set(map(str, filter(lambda x:x>=0, range(n, n-k, -1)))) | module function_definition identifier parameters identifier identifier default_parameter identifier integer block return_statement call identifier argument_list call identifier argument_list identifier call identifier argument_list lambda lambda_parameters identifier comparison_operator identifier integer call identifier argument_list identifier binary_operator identifier identifier unary_operator integer | Return the directory names to preserve under the LastK purge strategy. |
def isNumber(self, value):
try:
str(value)
float(value)
return True
except ValueError:
return False | module function_definition identifier parameters identifier identifier block try_statement block expression_statement call identifier argument_list identifier expression_statement call identifier argument_list identifier return_statement true except_clause identifier block return_statement false | Validate whether a value is a number or not |
def pdf(alphas):
alphap = alphas - 1
c = np.exp(gammaln(alphas.sum()) - gammaln(alphas).sum())
def dirichlet(xs):
return c * (xs**alphap).prod(axis=1)
return dirichlet | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator call identifier argument_list call attribute identifier identifier argument_list call attribute call identifier argument_list identifier identifier argument_list function_definition identifier parameters identifier block return_statement binary_operator identifier call attribute parenthesized_expression binary_operator identifier identifier identifier argument_list keyword_argument identifier integer return_statement identifier | Returns a Dirichlet PDF function |
def host2id(self, hostname):
for key, value in self.server_map.items():
if value == hostname:
return key | module function_definition identifier parameters 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 identifier | return member id by hostname |
def ListHuntApprovals(context=None):
items = context.SendIteratorRequest("ListHuntApprovals",
hunt_pb2.ApiListHuntApprovalsArgs())
def MapHuntApproval(data):
return HuntApproval(data=data, username=context.username, context=context)
return utils.MapItemsIterator(MapHuntApproval, items) | module function_definition identifier parameters default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list function_definition identifier parameters identifier block return_statement call identifier argument_list keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier return_statement call attribute identifier identifier argument_list identifier identifier | List all hunt approvals belonging to requesting user. |
def ResolveCronJobFlowURN(self, cron_job_id):
if not self._value:
raise ValueError("Can't call ResolveCronJobFlowURN on an empty "
"client id.")
return cron_job_id.ToURN().Add(self._value) | module function_definition identifier parameters identifier identifier block if_statement not_operator attribute identifier identifier block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end return_statement call attribute call attribute identifier identifier argument_list identifier argument_list attribute identifier identifier | Resolve a URN of a flow with this id belonging to a given cron job. |
def _detect(self):
theip = None
try:
if self.opts_family == AF_INET6:
addrlist = netifaces.ifaddresses(self.opts_iface)[netifaces.AF_INET6]
else:
addrlist = netifaces.ifaddresses(self.opts_iface)[netifaces.AF_INET]
except ValueError as exc:
LOG.error("netifaces choked while trying to get network interface"
" information for interface '%s'", self.opts_iface,
exc_info=exc)
else:
for pair in addrlist:
try:
detip = ipaddress(pair["addr"])
except (TypeError, ValueError) as exc:
LOG.debug("Found invalid IP '%s' on interface '%s'!?",
pair["addr"], self.opts_iface, exc_info=exc)
continue
if self.netmask is not None:
if detip in self.netmask:
theip = pair["addr"]
else:
continue
else:
theip = pair["addr"]
break
self.set_current_value(theip)
return theip | module function_definition identifier parameters identifier block expression_statement assignment identifier none try_statement block if_statement comparison_operator attribute identifier identifier identifier block expression_statement assignment identifier subscript call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier else_clause block expression_statement assignment identifier subscript call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end attribute identifier identifier keyword_argument identifier identifier else_clause block for_statement identifier identifier block try_statement block expression_statement assignment identifier call identifier argument_list subscript identifier string string_start string_content string_end except_clause as_pattern tuple identifier identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end subscript identifier string string_start string_content string_end attribute identifier identifier keyword_argument identifier identifier continue_statement if_statement comparison_operator attribute identifier identifier none block if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end else_clause block continue_statement else_clause block expression_statement assignment identifier subscript identifier string string_start string_content string_end break_statement expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Use the netifaces module to detect ifconfig information. |
def main(argv=None):
parser = argparse.ArgumentParser(
description='Commands as arguments'
)
command_help = 'optional command to run, if no command given, enter an interactive shell'
parser.add_argument('command', nargs='?',
help=command_help)
arg_help = 'optional arguments for command'
parser.add_argument('command_args', nargs=argparse.REMAINDER,
help=arg_help)
args = parser.parse_args(argv)
c = CmdLineApp()
if args.command:
c.onecmd_plus_hooks('{} {}'.format(args.command, ' '.join(args.command_args)))
else:
c.cmdloop() | module function_definition identifier parameters default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier expression_statement assignment identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list | Run when invoked from the operating system shell |
def insert(self, value):
if not self.payload or value == self.payload:
self.payload = value
else:
if value <= self.payload:
if self.left:
self.left.insert(value)
else:
self.left = BinaryTreeNode(value)
else:
if self.right:
self.right.insert(value)
else:
self.right = BinaryTreeNode(value) | module function_definition identifier parameters identifier identifier block if_statement boolean_operator not_operator attribute identifier identifier comparison_operator identifier attribute identifier identifier block expression_statement assignment attribute identifier identifier identifier else_clause block if_statement comparison_operator identifier attribute identifier identifier block if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier else_clause block expression_statement assignment attribute identifier identifier call identifier argument_list identifier else_clause block if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier else_clause block expression_statement assignment attribute identifier identifier call identifier argument_list identifier | Insert a value in the tree |
def make_estimator_input_fn(self,
mode,
hparams,
data_dir=None,
force_repeat=False,
prevent_repeat=False,
dataset_kwargs=None):
def estimator_input_fn(params, config):
return self.input_fn(
mode,
hparams,
data_dir=data_dir,
params=params,
config=config,
force_repeat=force_repeat,
prevent_repeat=prevent_repeat,
dataset_kwargs=dataset_kwargs)
return estimator_input_fn | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none default_parameter identifier false default_parameter identifier false default_parameter identifier none block function_definition identifier parameters identifier identifier block return_statement call attribute identifier identifier argument_list identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier return_statement identifier | Return input_fn wrapped for Estimator. |
def metarate(self, func, name='values'):
setattr(func, name, self.values)
return func | module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end block expression_statement call identifier argument_list identifier identifier attribute identifier identifier return_statement identifier | Set the values object to the function object's namespace |
def _pfp__handle_implicit_array(self, name, child):
existing_child = self._pfp__children_map[name]
if isinstance(existing_child, Array):
existing_child.append(child)
return existing_child
else:
cls = child._pfp__class if hasattr(child, "_pfp__class") else child.__class__
ary = Array(0, cls)
ary._pfp__offset = existing_child._pfp__offset
ary._pfp__parent = self
ary._pfp__name = name
ary.implicit = True
ary.append(existing_child)
ary.append(child)
exist_idx = -1
for idx,child in enumerate(self._pfp__children):
if child is existing_child:
exist_idx = idx
break
self._pfp__children[exist_idx] = ary
self._pfp__children_map[name] = ary
return ary | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier identifier if_statement call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier else_clause block expression_statement assignment identifier conditional_expression attribute identifier identifier call identifier argument_list identifier string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier call identifier argument_list integer identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier true expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier unary_operator integer for_statement pattern_list identifier identifier call identifier argument_list attribute identifier identifier block if_statement comparison_operator identifier identifier block expression_statement assignment identifier identifier break_statement expression_statement assignment subscript attribute identifier identifier identifier identifier expression_statement assignment subscript attribute identifier identifier identifier identifier return_statement identifier | Handle inserting implicit array elements |
def _grid_in_property(field_name, docstring, read_only=False,
closed_only=False):
def getter(self):
if closed_only and not self._closed:
raise AttributeError("can only get %r on a closed file" %
field_name)
if field_name == 'length':
return self._file.get(field_name, 0)
return self._file.get(field_name, None)
def setter(self, value):
if self._closed:
self._coll.files.update_one({"_id": self._file["_id"]},
{"$set": {field_name: value}})
self._file[field_name] = value
if read_only:
docstring += "\n\nThis attribute is read-only."
elif closed_only:
docstring = "%s\n\n%s" % (docstring, "This attribute is read-only and "
"can only be read after :meth:`close` "
"has been called.")
if not read_only and not closed_only:
return property(getter, setter, doc=docstring)
return property(getter, doc=docstring) | module function_definition identifier parameters identifier identifier default_parameter identifier false default_parameter identifier false block function_definition identifier parameters identifier block if_statement boolean_operator identifier not_operator attribute identifier identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier if_statement comparison_operator identifier string string_start string_content string_end block return_statement call attribute attribute identifier identifier identifier argument_list identifier integer return_statement call attribute attribute identifier identifier identifier argument_list identifier none function_definition identifier parameters identifier identifier block if_statement attribute identifier identifier block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list dictionary pair string string_start string_content string_end subscript attribute identifier identifier string string_start string_content string_end dictionary pair string string_start string_content string_end dictionary pair identifier identifier expression_statement assignment subscript attribute identifier identifier identifier identifier if_statement identifier block expression_statement augmented_assignment identifier string string_start string_content escape_sequence escape_sequence string_end elif_clause identifier block expression_statement assignment identifier binary_operator string string_start string_content escape_sequence escape_sequence string_end tuple identifier concatenated_string string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end if_statement boolean_operator not_operator identifier not_operator identifier block return_statement call identifier argument_list identifier identifier keyword_argument identifier identifier return_statement call identifier argument_list identifier keyword_argument identifier identifier | Create a GridIn property. |
def directory_complete(self, text, line, begidx, endidx):
return [filename for filename in self.filename_complete(text, line, begidx, endidx) if filename[-1] == '/'] | module function_definition identifier parameters identifier identifier identifier identifier identifier block return_statement list_comprehension identifier for_in_clause identifier call attribute identifier identifier argument_list identifier identifier identifier identifier if_clause comparison_operator subscript identifier unary_operator integer string string_start string_content string_end | Figure out what directories match the completion. |
def iter_data(self):
for (k, v) in self.proxy.items():
if (
not (isinstance(k, str) and k[0] == '_') and
k not in (
'character',
'name',
'location'
)
):
yield k, v | module function_definition identifier parameters identifier block for_statement tuple_pattern identifier identifier call attribute attribute identifier identifier identifier argument_list block if_statement parenthesized_expression boolean_operator not_operator parenthesized_expression boolean_operator call identifier argument_list identifier identifier comparison_operator subscript identifier integer string string_start string_content string_end 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 block expression_statement yield expression_list identifier identifier | Iterate over key-value pairs that are really meant to be displayed |
def clone(client):
kwargs = client.redis.connection_pool.connection_kwargs
kwargs['parser_class'] = redis.connection.PythonParser
pool = redis.connection.ConnectionPool(**kwargs)
return redis.Redis(connection_pool=pool) | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute attribute attribute identifier identifier identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end attribute attribute identifier identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list dictionary_splat identifier return_statement call attribute identifier identifier argument_list keyword_argument identifier identifier | Clone the redis client to be slowlog-compatible |
def _walk(recursion):
try:
from scandir import walk as walk_function
except ImportError:
from os import walk as walk_function
if recursion:
walk = partial(walk_function)
else:
def walk(path):
try:
yield next(walk_function(path))
except NameError:
yield walk_function(path)
return walk | module function_definition identifier parameters identifier block try_statement block import_from_statement dotted_name identifier aliased_import dotted_name identifier identifier except_clause identifier block import_from_statement dotted_name identifier aliased_import dotted_name identifier identifier if_statement identifier block expression_statement assignment identifier call identifier argument_list identifier else_clause block function_definition identifier parameters identifier block try_statement block expression_statement yield call identifier argument_list call identifier argument_list identifier except_clause identifier block expression_statement yield call identifier argument_list identifier return_statement identifier | Returns a recursive or non-recursive directory walker |
def _store_inserted_ids(self, mapping, job_id, local_ids_for_batch):
id_table_name = self._reset_id_table(mapping)
conn = self.session.connection()
for batch_id, local_ids in local_ids_for_batch.items():
try:
results_url = "{}/job/{}/batch/{}/result".format(
self.bulk.endpoint, job_id, batch_id
)
with _download_file(results_url, self.bulk) as f:
self.logger.info(
" Downloaded results for batch {}".format(batch_id)
)
self._store_inserted_ids_for_batch(
f, local_ids, id_table_name, conn
)
self.logger.info(
" Updated {} for batch {}".format(id_table_name, batch_id)
)
except Exception:
self.logger.error(
"Could not download batch results: {}".format(batch_id)
)
continue
self.session.commit() | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block try_statement block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list attribute attribute identifier identifier identifier identifier identifier with_statement with_clause with_item as_pattern call identifier argument_list identifier attribute identifier identifier as_pattern_target identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier except_clause identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier continue_statement expression_statement call attribute attribute identifier identifier identifier argument_list | Get the job results and store inserted SF Ids in a new table |
def _validate_outgroup(self, outgroup):
if outgroup:
outgroup = outgroup.replace("-", "_")
good_outgroup = False
for seq_record in self.seq_records:
if seq_record.voucher_code == outgroup:
good_outgroup = True
break
if good_outgroup:
self.outgroup = outgroup
else:
raise ValueError("The given outgroup {0!r} cannot be found in the "
"input sequence records.".format(outgroup))
else:
self.outgroup = None | module function_definition identifier parameters identifier identifier block if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier false for_statement identifier attribute identifier identifier block if_statement comparison_operator attribute identifier identifier identifier block expression_statement assignment identifier true break_statement if_statement identifier block expression_statement assignment attribute identifier identifier identifier else_clause block raise_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 identifier else_clause block expression_statement assignment attribute identifier identifier none | All voucher codes in our datasets have dashes converted to underscores. |
def fix_e701(self, result):
line_index = result['line'] - 1
target = self.source[line_index]
c = result['column']
fixed_source = (target[:c] + '\n' +
_get_indentation(target) + self.indent_word +
target[c:].lstrip('\n\r \t\\'))
self.source[result['line'] - 1] = fixed_source
return [result['line'], result['line'] + 1] | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator subscript identifier string string_start string_content string_end integer expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier parenthesized_expression binary_operator binary_operator binary_operator binary_operator subscript identifier slice identifier string string_start string_content escape_sequence string_end call identifier argument_list identifier attribute identifier identifier call attribute subscript identifier slice identifier identifier argument_list string string_start string_content escape_sequence escape_sequence escape_sequence escape_sequence string_end expression_statement assignment subscript attribute identifier identifier binary_operator subscript identifier string string_start string_content string_end integer identifier return_statement list subscript identifier string string_start string_content string_end binary_operator subscript identifier string string_start string_content string_end integer | Put colon-separated compound statement on separate lines. |
def today(self, chamber):
"Return today's votes in a given chamber"
now = datetime.date.today()
return self.by_range(chamber, now, now) | module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list return_statement call attribute identifier identifier argument_list identifier identifier identifier | Return today's votes in a given chamber |
def wrap_sync(func):
@functools.wraps(func)
def wrapped(*args, **kwargs):
fut = asyncio.Future()
def green():
try:
fut.set_result(func(*args, **kwargs))
except BaseException as e:
fut.set_exception(e)
greenlet.greenlet(green).switch()
return fut
return wrapped | module function_definition identifier parameters identifier block decorated_definition decorator call attribute identifier identifier argument_list identifier function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list function_definition identifier parameters block try_statement block expression_statement call attribute identifier identifier argument_list call identifier argument_list list_splat identifier dictionary_splat identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute call attribute identifier identifier argument_list identifier identifier argument_list return_statement identifier return_statement identifier | Wraps a synchronous function into an asynchronous function. |
def _cl_gof3r(file_info, region):
command = ["gof3r", "get", "--no-md5",
"-k", file_info.key,
"-b", file_info.bucket]
if region != "us-east-1":
command += ["--endpoint=s3-%s.amazonaws.com" % region]
return (command, "gof3r") | module function_definition identifier parameters identifier 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 attribute identifier identifier string string_start string_content string_end attribute identifier identifier if_statement comparison_operator identifier string string_start string_content string_end block expression_statement augmented_assignment identifier list binary_operator string string_start string_content string_end identifier return_statement tuple identifier string string_start string_content string_end | Command line required for download using gof3r. |
def _process_include_fields(self, include_fields, exclude_fields,
extra_fields):
def _convert_fields(_in):
if not _in:
return _in
for newname, oldname in self._get_api_aliases():
if oldname in _in:
_in.remove(oldname)
if newname not in _in:
_in.append(newname)
return _in
ret = {}
if self._check_version(4, 0):
if include_fields:
include_fields = _convert_fields(include_fields)
if "id" not in include_fields:
include_fields.append("id")
ret["include_fields"] = include_fields
if exclude_fields:
exclude_fields = _convert_fields(exclude_fields)
ret["exclude_fields"] = exclude_fields
if self._supports_getbug_extra_fields:
if extra_fields:
ret["extra_fields"] = _convert_fields(extra_fields)
return ret | module function_definition identifier parameters identifier identifier identifier identifier block function_definition identifier parameters identifier block if_statement not_operator identifier block return_statement identifier for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier expression_statement assignment identifier dictionary if_statement call attribute identifier identifier argument_list integer integer block if_statement identifier block expression_statement assignment identifier call identifier argument_list identifier 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 expression_statement assignment subscript identifier string string_start string_content string_end identifier if_statement identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier if_statement attribute identifier identifier block if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list identifier return_statement identifier | Internal helper to process include_fields lists |
def do_genesis_block_audit(genesis_block_path=None, key_id=None):
signing_keys = GENESIS_BLOCK_SIGNING_KEYS
if genesis_block_path is not None:
genesis_block_load(genesis_block_path)
if key_id is not None:
gpg2_path = find_gpg2()
assert gpg2_path, 'You need to install gpg2'
p = subprocess.Popen([gpg2_path, '-a', '--export', key_id], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
if p.returncode != 0:
log.error('Failed to load key {}\n{}'.format(key_id, err))
return False
signing_keys = { key_id: out.strip() }
res = genesis_block_audit(get_genesis_block_stages(), key_bundle=signing_keys)
if not res:
log.error('Genesis block is NOT signed by {}'.format(', '.join(signing_keys.keys())))
return False
return True | module function_definition identifier parameters default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier identifier if_statement comparison_operator identifier none block expression_statement call identifier argument_list identifier if_statement comparison_operator identifier none block expression_statement assignment identifier call identifier argument_list assert_statement identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list list identifier string string_start string_content string_end string string_start string_content string_end identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list if_statement comparison_operator attribute identifier identifier integer block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier identifier return_statement false expression_statement assignment identifier dictionary pair identifier call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list call identifier argument_list keyword_argument identifier 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 call attribute string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list return_statement false return_statement true | Loads and audits the genesis block, optionally using an alternative key |
def _find_known(row):
out = []
clinvar_no = set(["unknown", "untested", "non-pathogenic", "probable-non-pathogenic",
"uncertain_significance", "uncertain_significance", "not_provided",
"benign", "likely_benign"])
if row["cosmic_ids"] or row["cosmic_id"]:
out.append("cosmic")
if row["clinvar_sig"] and not row["clinvar_sig"].lower() in clinvar_no:
out.append("clinvar")
return out | module function_definition identifier parameters identifier block expression_statement assignment identifier list expression_statement assignment identifier call identifier argument_list 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 string_end string string_start string_content string_end if_statement boolean_operator subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end if_statement boolean_operator subscript identifier string string_start string_content string_end not_operator comparison_operator call attribute subscript identifier string string_start string_content string_end identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement identifier | Find variant present in known pathogenic databases. |
def register(self, key, dbtype):
if not issubclass(dbtype, (BaseField, EmbeddedDocument)):
msg = 'ExtrasField can only register MongoEngine fields'
raise TypeError(msg)
self.registered[key] = dbtype | module function_definition identifier parameters identifier identifier identifier block if_statement not_operator call identifier argument_list identifier tuple identifier identifier block expression_statement assignment identifier string string_start string_content string_end raise_statement call identifier argument_list identifier expression_statement assignment subscript attribute identifier identifier identifier identifier | Register a DB type to add constraint on a given extra key |
def _basename(fname):
if not isinstance(fname, Path):
fname = Path(fname)
path, name, ext = fname.parent, fname.stem, fname.suffix
return path, name, ext | module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment pattern_list identifier identifier identifier expression_list attribute identifier identifier attribute identifier identifier attribute identifier identifier return_statement expression_list identifier identifier identifier | Return file name without path. |
def cli():
parser = argparse.ArgumentParser(prog="sphinx-serve",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
conflict_handler="resolve",
description=__doc__
)
parser.add_argument("-v", "--version", action="version",
version="%(prog)s {0}".format(__version__)
)
parser.add_argument("-h", "--host", action="store",
default="0.0.0.0",
help="Listen to the given hostname"
)
parser.add_argument("-p", "--port", action="store",
type=int, default=8081,
help="Listen to given port"
)
parser.add_argument("-b", "--build", action="store",
default="_build",
help="Build folder name"
)
parser.add_argument("-s", "--single", action="store_true",
help="Serve the single-html documentation version"
)
return parser.parse_args() | module function_definition identifier parameters block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier attribute identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier integer keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end return_statement call attribute identifier identifier argument_list | Parse options from the command line |
def sha1_hmac(secret, document):
signature = hmac.new(secret, document, hashlib.sha1).digest().encode("base64")[:-1]
return signature | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript call attribute call attribute call attribute identifier identifier argument_list identifier identifier attribute identifier identifier identifier argument_list identifier argument_list string string_start string_content string_end slice unary_operator integer return_statement identifier | Calculate the Base 64 encoding of the HMAC for the given document. |
def on_gtk_prefer_dark_theme_toggled(self, chk):
self.settings.general.set_boolean('gtk-prefer-dark-theme', chk.get_active())
select_gtk_theme(self.settings) | module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list expression_statement call identifier argument_list attribute identifier identifier | Set the `gtk_prefer_dark_theme' property in dconf |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.