id_within_dataset
int64
1
55.5k
snippet
stringlengths
19
14.2k
tokens
listlengths
6
1.63k
nl
stringlengths
6
352
split_within_dataset
stringclasses
1 value
is_duplicated
bool
2 classes
13,791
def escape_script(text): return SCRIPT_RE.sub(u'<-\\1/script>', text)
[ "def", "escape_script", "(", "text", ")", ":", "return", "SCRIPT_RE", ".", "sub", "(", "u'<-\\\\1/script>'", ",", "text", ")" ]
escape </script> tags in text so that it can be placed within a <script> block without accidentally closing it .
train
false
13,792
def order_rainbow(s): colors_shuffle = [(globals()[i.encode('utf8')] if (not str(i).isdigit()) else term_color(int(i))) for i in c['CYCLE_COLOR']] colored = [colors_shuffle[(i % 7)](s[i]) for i in xrange(len(s))] return ''.join(colored)
[ "def", "order_rainbow", "(", "s", ")", ":", "colors_shuffle", "=", "[", "(", "globals", "(", ")", "[", "i", ".", "encode", "(", "'utf8'", ")", "]", "if", "(", "not", "str", "(", "i", ")", ".", "isdigit", "(", ")", ")", "else", "term_color", "(", "int", "(", "i", ")", ")", ")", "for", "i", "in", "c", "[", "'CYCLE_COLOR'", "]", "]", "colored", "=", "[", "colors_shuffle", "[", "(", "i", "%", "7", ")", "]", "(", "s", "[", "i", "]", ")", "for", "i", "in", "xrange", "(", "len", "(", "s", ")", ")", "]", "return", "''", ".", "join", "(", "colored", ")" ]
print a string with ordered color with each character .
train
false
13,793
@login_required def account(request): return render(request, 'web/account.html', {'page': 'account'})
[ "@", "login_required", "def", "account", "(", "request", ")", ":", "return", "render", "(", "request", ",", "'web/account.html'", ",", "{", "'page'", ":", "'account'", "}", ")" ]
return the users account web page .
train
false
13,795
def collection_check_options(options): try: _validate_collection_options(options) return True except ValueError: return False
[ "def", "collection_check_options", "(", "options", ")", ":", "try", ":", "_validate_collection_options", "(", "options", ")", "return", "True", "except", "ValueError", ":", "return", "False" ]
check collections options .
train
false
13,796
def subpixel_indices(position, subsampling): fractions = np.modf((np.asanyarray(position) + 0.5))[0] return np.floor((fractions * subsampling))
[ "def", "subpixel_indices", "(", "position", ",", "subsampling", ")", ":", "fractions", "=", "np", ".", "modf", "(", "(", "np", ".", "asanyarray", "(", "position", ")", "+", "0.5", ")", ")", "[", "0", "]", "return", "np", ".", "floor", "(", "(", "fractions", "*", "subsampling", ")", ")" ]
convert decimal points to indices .
train
false
13,797
def qual(clazz): return ((clazz.__module__ + '.') + clazz.__name__)
[ "def", "qual", "(", "clazz", ")", ":", "return", "(", "(", "clazz", ".", "__module__", "+", "'.'", ")", "+", "clazz", ".", "__name__", ")" ]
return full import path of a class .
train
false
13,798
def _prepare_archive_at_path(filename): try: with ZipFile(filename, 'r') as archive: archive.close() except BadZipfile: return None if _is_overwritten(filename): log.debug('ZIP file contains a file with the same name, original is going to be overwrite') new_zip_path = (filename + _random_extension()) move(filename, new_zip_path) filename = new_zip_path return filename
[ "def", "_prepare_archive_at_path", "(", "filename", ")", ":", "try", ":", "with", "ZipFile", "(", "filename", ",", "'r'", ")", "as", "archive", ":", "archive", ".", "close", "(", ")", "except", "BadZipfile", ":", "return", "None", "if", "_is_overwritten", "(", "filename", ")", ":", "log", ".", "debug", "(", "'ZIP file contains a file with the same name, original is going to be overwrite'", ")", "new_zip_path", "=", "(", "filename", "+", "_random_extension", "(", ")", ")", "move", "(", "filename", ",", "new_zip_path", ")", "filename", "=", "new_zip_path", "return", "filename" ]
verifies that theres a readable zip archive at the given path .
train
false
13,799
def get_allowed_params(params, whitelist): allowed_params = {} for (key, get_type) in six.iteritems(whitelist): assert (get_type in PARAM_TYPES) value = None if (get_type == PARAM_TYPE_SINGLE): value = params.get(key) elif (get_type == PARAM_TYPE_MULTI): value = params.getall(key) elif (get_type == PARAM_TYPE_MIXED): value = params.getall(key) if (isinstance(value, list) and (len(value) == 1)): value = value.pop() if value: allowed_params[key] = value return allowed_params
[ "def", "get_allowed_params", "(", "params", ",", "whitelist", ")", ":", "allowed_params", "=", "{", "}", "for", "(", "key", ",", "get_type", ")", "in", "six", ".", "iteritems", "(", "whitelist", ")", ":", "assert", "(", "get_type", "in", "PARAM_TYPES", ")", "value", "=", "None", "if", "(", "get_type", "==", "PARAM_TYPE_SINGLE", ")", ":", "value", "=", "params", ".", "get", "(", "key", ")", "elif", "(", "get_type", "==", "PARAM_TYPE_MULTI", ")", ":", "value", "=", "params", ".", "getall", "(", "key", ")", "elif", "(", "get_type", "==", "PARAM_TYPE_MIXED", ")", ":", "value", "=", "params", ".", "getall", "(", "key", ")", "if", "(", "isinstance", "(", "value", ",", "list", ")", "and", "(", "len", "(", "value", ")", "==", "1", ")", ")", ":", "value", "=", "value", ".", "pop", "(", ")", "if", "value", ":", "allowed_params", "[", "key", "]", "=", "value", "return", "allowed_params" ]
extract from params all entries listed in whitelist .
train
false
13,800
def qsort(lst): if (len(lst) <= 1): return lst (pivot, rest) = (lst[0], lst[1:]) less_than = [] for lt in rest: if (lt < pivot): less_than.append(lt) greater_equal = [] for ge in rest: if (ge >= pivot): greater_equal.append(ge) return ((qsort(less_than) + [pivot]) + qsort(greater_equal))
[ "def", "qsort", "(", "lst", ")", ":", "if", "(", "len", "(", "lst", ")", "<=", "1", ")", ":", "return", "lst", "(", "pivot", ",", "rest", ")", "=", "(", "lst", "[", "0", "]", ",", "lst", "[", "1", ":", "]", ")", "less_than", "=", "[", "]", "for", "lt", "in", "rest", ":", "if", "(", "lt", "<", "pivot", ")", ":", "less_than", ".", "append", "(", "lt", ")", "greater_equal", "=", "[", "]", "for", "ge", "in", "rest", ":", "if", "(", "ge", ">=", "pivot", ")", ":", "greater_equal", ".", "append", "(", "ge", ")", "return", "(", "(", "qsort", "(", "less_than", ")", "+", "[", "pivot", "]", ")", "+", "qsort", "(", "greater_equal", ")", ")" ]
quicksort in o and no extra memory .
train
false
13,801
def deferLater(clock, delay, callable, *args, **kw): def deferLaterCancel(deferred): delayedCall.cancel() d = defer.Deferred(deferLaterCancel) d.addCallback((lambda ignored: callable(*args, **kw))) delayedCall = clock.callLater(delay, d.callback, None) return d
[ "def", "deferLater", "(", "clock", ",", "delay", ",", "callable", ",", "*", "args", ",", "**", "kw", ")", ":", "def", "deferLaterCancel", "(", "deferred", ")", ":", "delayedCall", ".", "cancel", "(", ")", "d", "=", "defer", ".", "Deferred", "(", "deferLaterCancel", ")", "d", ".", "addCallback", "(", "(", "lambda", "ignored", ":", "callable", "(", "*", "args", ",", "**", "kw", ")", ")", ")", "delayedCall", "=", "clock", ".", "callLater", "(", "delay", ",", "d", ".", "callback", ",", "None", ")", "return", "d" ]
call the given function after a certain period of time has passed .
train
false
13,804
def parse_timedelta(text): td_kwargs = {} for match in _PARSE_TD_RE.finditer(text): (value, unit) = (match.group('value'), match.group('unit')) try: unit_key = _PARSE_TD_KW_MAP[unit] except KeyError: raise ValueError(('invalid time unit %r, expected one of %r' % (unit, _PARSE_TD_KW_MAP.keys()))) try: value = float(value) except ValueError: raise ValueError(('invalid time value for unit %r: %r' % (unit, value))) td_kwargs[unit_key] = value return timedelta(**td_kwargs)
[ "def", "parse_timedelta", "(", "text", ")", ":", "td_kwargs", "=", "{", "}", "for", "match", "in", "_PARSE_TD_RE", ".", "finditer", "(", "text", ")", ":", "(", "value", ",", "unit", ")", "=", "(", "match", ".", "group", "(", "'value'", ")", ",", "match", ".", "group", "(", "'unit'", ")", ")", "try", ":", "unit_key", "=", "_PARSE_TD_KW_MAP", "[", "unit", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "(", "'invalid time unit %r, expected one of %r'", "%", "(", "unit", ",", "_PARSE_TD_KW_MAP", ".", "keys", "(", ")", ")", ")", ")", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "(", "'invalid time value for unit %r: %r'", "%", "(", "unit", ",", "value", ")", ")", ")", "td_kwargs", "[", "unit_key", "]", "=", "value", "return", "timedelta", "(", "**", "td_kwargs", ")" ]
parse a string like 5 days into a timedelta object .
train
true
13,805
def json_stream(stream): return split_buffer(stream, json_splitter, json_decoder.decode)
[ "def", "json_stream", "(", "stream", ")", ":", "return", "split_buffer", "(", "stream", ",", "json_splitter", ",", "json_decoder", ".", "decode", ")" ]
given a stream of text .
train
false
13,806
def _fake_is_request_in_microsite(): return True
[ "def", "_fake_is_request_in_microsite", "(", ")", ":", "return", "True" ]
mocked version of microsite helper method to always return true .
train
false
13,810
@core_helper def build_nav(menu_item, title, **kw): return _make_menu_item(menu_item, title, icon=None, **kw)
[ "@", "core_helper", "def", "build_nav", "(", "menu_item", ",", "title", ",", "**", "kw", ")", ":", "return", "_make_menu_item", "(", "menu_item", ",", "title", ",", "icon", "=", "None", ",", "**", "kw", ")" ]
build a navigation item used for example breadcrumbs .
train
false
13,812
def _compile_state(mods=None, saltenv='base'): st_ = HighState(__opts__) (high_data, errors) = st_.render_highstate({saltenv: mods}) (high_data, ext_errors) = st_.state.reconcile_extend(high_data) errors += ext_errors errors += st_.state.verify_high(high_data) if errors: return errors (high_data, req_in_errors) = st_.state.requisite_in(high_data) errors += req_in_errors high_data = st_.state.apply_exclude(high_data) if errors: return errors return st_.state.compile_high_data(high_data)
[ "def", "_compile_state", "(", "mods", "=", "None", ",", "saltenv", "=", "'base'", ")", ":", "st_", "=", "HighState", "(", "__opts__", ")", "(", "high_data", ",", "errors", ")", "=", "st_", ".", "render_highstate", "(", "{", "saltenv", ":", "mods", "}", ")", "(", "high_data", ",", "ext_errors", ")", "=", "st_", ".", "state", ".", "reconcile_extend", "(", "high_data", ")", "errors", "+=", "ext_errors", "errors", "+=", "st_", ".", "state", ".", "verify_high", "(", "high_data", ")", "if", "errors", ":", "return", "errors", "(", "high_data", ",", "req_in_errors", ")", "=", "st_", ".", "state", ".", "requisite_in", "(", "high_data", ")", "errors", "+=", "req_in_errors", "high_data", "=", "st_", ".", "state", ".", "apply_exclude", "(", "high_data", ")", "if", "errors", ":", "return", "errors", "return", "st_", ".", "state", ".", "compile_high_data", "(", "high_data", ")" ]
generates the chunks of lowdata from the list of modules .
train
false
13,813
def radial_gradient(color, color_light=50): if (not isinstance(color_light, QColor)): color_light = saturated(color, color_light) gradient = QRadialGradient(0.5, 0.5, 0.5) gradient.setColorAt(0.0, color_light) gradient.setColorAt(0.5, color_light) gradient.setColorAt(1.0, color) gradient.setCoordinateMode(QRadialGradient.ObjectBoundingMode) return gradient
[ "def", "radial_gradient", "(", "color", ",", "color_light", "=", "50", ")", ":", "if", "(", "not", "isinstance", "(", "color_light", ",", "QColor", ")", ")", ":", "color_light", "=", "saturated", "(", "color", ",", "color_light", ")", "gradient", "=", "QRadialGradient", "(", "0.5", ",", "0.5", ",", "0.5", ")", "gradient", ".", "setColorAt", "(", "0.0", ",", "color_light", ")", "gradient", ".", "setColorAt", "(", "0.5", ",", "color_light", ")", "gradient", ".", "setColorAt", "(", "1.0", ",", "color", ")", "gradient", ".", "setCoordinateMode", "(", "QRadialGradient", ".", "ObjectBoundingMode", ")", "return", "gradient" ]
radial_gradient radial_gradient return a radial gradient .
train
false
13,814
def make_asset_md(amount): all_asset_md = [] for __ in xrange(amount): all_asset_md.append(generate_random_asset_md()) return all_asset_md
[ "def", "make_asset_md", "(", "amount", ")", ":", "all_asset_md", "=", "[", "]", "for", "__", "in", "xrange", "(", "amount", ")", ":", "all_asset_md", ".", "append", "(", "generate_random_asset_md", "(", ")", ")", "return", "all_asset_md" ]
make a number of fake assetmetadata objects .
train
false
13,816
def init_qtapp(): global QApp QApp = QtWidgets.QApplication.instance() if (QApp is None): QApp = QtWidgets.QApplication([]) return QApp
[ "def", "init_qtapp", "(", ")", ":", "global", "QApp", "QApp", "=", "QtWidgets", ".", "QApplication", ".", "instance", "(", ")", "if", "(", "QApp", "is", "None", ")", ":", "QApp", "=", "QtWidgets", ".", "QApplication", "(", "[", "]", ")", "return", "QApp" ]
initialize qappliction .
train
false
13,817
@bdd.then(bdd.parsers.re('(?P<is_regex>regex )?"(?P<pattern>[^"]+)" should be logged')) def should_be_logged(quteproc, httpbin, is_regex, pattern): if is_regex: pattern = re.compile(pattern) else: pattern = pattern.replace('(port)', str(httpbin.port)) line = quteproc.wait_for(message=pattern) line.expected = True
[ "@", "bdd", ".", "then", "(", "bdd", ".", "parsers", ".", "re", "(", "'(?P<is_regex>regex )?\"(?P<pattern>[^\"]+)\" should be logged'", ")", ")", "def", "should_be_logged", "(", "quteproc", ",", "httpbin", ",", "is_regex", ",", "pattern", ")", ":", "if", "is_regex", ":", "pattern", "=", "re", ".", "compile", "(", "pattern", ")", "else", ":", "pattern", "=", "pattern", ".", "replace", "(", "'(port)'", ",", "str", "(", "httpbin", ".", "port", ")", ")", "line", "=", "quteproc", ".", "wait_for", "(", "message", "=", "pattern", ")", "line", ".", "expected", "=", "True" ]
expect the given pattern on regex in the log .
train
false
13,818
def send_zulip(email, api_key, site, stream, subject, content): client = zulip.Client(email=email, api_key=api_key, site=site, client=('ZulipMercurial/' + VERSION)) message_data = {'type': 'stream', 'to': stream, 'subject': subject, 'content': content} client.send_message(message_data)
[ "def", "send_zulip", "(", "email", ",", "api_key", ",", "site", ",", "stream", ",", "subject", ",", "content", ")", ":", "client", "=", "zulip", ".", "Client", "(", "email", "=", "email", ",", "api_key", "=", "api_key", ",", "site", "=", "site", ",", "client", "=", "(", "'ZulipMercurial/'", "+", "VERSION", ")", ")", "message_data", "=", "{", "'type'", ":", "'stream'", ",", "'to'", ":", "stream", ",", "'subject'", ":", "subject", ",", "'content'", ":", "content", "}", "client", ".", "send_message", "(", "message_data", ")" ]
send a message to zulip using the provided credentials .
train
false
13,819
def at_server_cold_stop(): pass
[ "def", "at_server_cold_stop", "(", ")", ":", "pass" ]
this is called only when the server goes down due to a shutdown or reset .
train
false
13,821
def shuffled_hdf5_batch_generator(state_dataset, action_dataset, indices, batch_size, transforms=[]): state_batch_shape = ((batch_size,) + state_dataset.shape[1:]) game_size = state_batch_shape[(-1)] Xbatch = np.zeros(state_batch_shape) Ybatch = np.zeros((batch_size, (game_size * game_size))) batch_idx = 0 while True: for data_idx in indices: transform = np.random.choice(transforms) state = np.array([transform(plane) for plane in state_dataset[data_idx]]) action_xy = tuple(action_dataset[data_idx]) action = transform(one_hot_action(action_xy, game_size)) Xbatch[batch_idx] = state Ybatch[batch_idx] = action.flatten() batch_idx += 1 if (batch_idx == batch_size): batch_idx = 0 (yield (Xbatch, Ybatch))
[ "def", "shuffled_hdf5_batch_generator", "(", "state_dataset", ",", "action_dataset", ",", "indices", ",", "batch_size", ",", "transforms", "=", "[", "]", ")", ":", "state_batch_shape", "=", "(", "(", "batch_size", ",", ")", "+", "state_dataset", ".", "shape", "[", "1", ":", "]", ")", "game_size", "=", "state_batch_shape", "[", "(", "-", "1", ")", "]", "Xbatch", "=", "np", ".", "zeros", "(", "state_batch_shape", ")", "Ybatch", "=", "np", ".", "zeros", "(", "(", "batch_size", ",", "(", "game_size", "*", "game_size", ")", ")", ")", "batch_idx", "=", "0", "while", "True", ":", "for", "data_idx", "in", "indices", ":", "transform", "=", "np", ".", "random", ".", "choice", "(", "transforms", ")", "state", "=", "np", ".", "array", "(", "[", "transform", "(", "plane", ")", "for", "plane", "in", "state_dataset", "[", "data_idx", "]", "]", ")", "action_xy", "=", "tuple", "(", "action_dataset", "[", "data_idx", "]", ")", "action", "=", "transform", "(", "one_hot_action", "(", "action_xy", ",", "game_size", ")", ")", "Xbatch", "[", "batch_idx", "]", "=", "state", "Ybatch", "[", "batch_idx", "]", "=", "action", ".", "flatten", "(", ")", "batch_idx", "+=", "1", "if", "(", "batch_idx", "==", "batch_size", ")", ":", "batch_idx", "=", "0", "(", "yield", "(", "Xbatch", ",", "Ybatch", ")", ")" ]
a generator of batches of training data for use with the fit_generator function of keras .
train
false
13,822
def addMenuEntitiesToMenuFrameable(menu, menuEntities): for menuEntity in menuEntities: menuEntity.addToMenuFrameable(menu)
[ "def", "addMenuEntitiesToMenuFrameable", "(", "menu", ",", "menuEntities", ")", ":", "for", "menuEntity", "in", "menuEntities", ":", "menuEntity", ".", "addToMenuFrameable", "(", "menu", ")" ]
add the menu entities to the menu .
train
false
13,824
def _diff_expand_link(context, expandable, text, tooltip, expand_pos, image_class): return render_to_string(u'diffviewer/expand_link.html', {u'tooltip': tooltip, u'text': text, u'chunk': context[u'chunk'], u'file': context[u'file'], u'expand_pos': expand_pos, u'image_class': image_class, u'expandable': expandable})
[ "def", "_diff_expand_link", "(", "context", ",", "expandable", ",", "text", ",", "tooltip", ",", "expand_pos", ",", "image_class", ")", ":", "return", "render_to_string", "(", "u'diffviewer/expand_link.html'", ",", "{", "u'tooltip'", ":", "tooltip", ",", "u'text'", ":", "text", ",", "u'chunk'", ":", "context", "[", "u'chunk'", "]", ",", "u'file'", ":", "context", "[", "u'file'", "]", ",", "u'expand_pos'", ":", "expand_pos", ",", "u'image_class'", ":", "image_class", ",", "u'expandable'", ":", "expandable", "}", ")" ]
utility function to render a diff expansion link .
train
false
13,825
@pytest.mark.parametrize('template', ['{}', 'attachment; filename="{}"', 'inline; {}', 'attachment; {}="foo"', 'attachment; filename*=iso-8859-1{}', 'attachment; filename*={}']) @hypothesis.given(strategies.text(alphabet=[chr(x) for x in range(255)])) def test_parse_content_disposition(caplog, template, stubs, s): header = template.format(s) reply = stubs.FakeNetworkReply(headers={'Content-Disposition': header}) with caplog.at_level(logging.ERROR, 'rfc6266'): http.parse_content_disposition(reply)
[ "@", "pytest", ".", "mark", ".", "parametrize", "(", "'template'", ",", "[", "'{}'", ",", "'attachment; filename=\"{}\"'", ",", "'inline; {}'", ",", "'attachment; {}=\"foo\"'", ",", "'attachment; filename*=iso-8859-1{}'", ",", "'attachment; filename*={}'", "]", ")", "@", "hypothesis", ".", "given", "(", "strategies", ".", "text", "(", "alphabet", "=", "[", "chr", "(", "x", ")", "for", "x", "in", "range", "(", "255", ")", "]", ")", ")", "def", "test_parse_content_disposition", "(", "caplog", ",", "template", ",", "stubs", ",", "s", ")", ":", "header", "=", "template", ".", "format", "(", "s", ")", "reply", "=", "stubs", ".", "FakeNetworkReply", "(", "headers", "=", "{", "'Content-Disposition'", ":", "header", "}", ")", "with", "caplog", ".", "at_level", "(", "logging", ".", "ERROR", ",", "'rfc6266'", ")", ":", "http", ".", "parse_content_disposition", "(", "reply", ")" ]
test parsing headers based on templates which hypothesis completes .
train
false
13,827
def _diff_file(a, b): diff = _diff(open(a).readlines(), open(b).readlines()) return list(diff)
[ "def", "_diff_file", "(", "a", ",", "b", ")", ":", "diff", "=", "_diff", "(", "open", "(", "a", ")", ".", "readlines", "(", ")", ",", "open", "(", "b", ")", ".", "readlines", "(", ")", ")", "return", "list", "(", "diff", ")" ]
diff of files read as strings .
train
false
13,828
@register.filter('timezone') def do_timezone(value, arg): if (not isinstance(value, datetime)): return '' try: if timezone.is_naive(value): default_timezone = timezone.get_default_timezone() value = timezone.make_aware(value, default_timezone) except Exception: return '' if isinstance(arg, tzinfo): tz = arg elif isinstance(arg, str): try: tz = pytz.timezone(arg) except pytz.UnknownTimeZoneError: return '' else: return '' result = timezone.localtime(value, tz) result = datetimeobject(result.year, result.month, result.day, result.hour, result.minute, result.second, result.microsecond, result.tzinfo) result.convert_to_local_time = False return result
[ "@", "register", ".", "filter", "(", "'timezone'", ")", "def", "do_timezone", "(", "value", ",", "arg", ")", ":", "if", "(", "not", "isinstance", "(", "value", ",", "datetime", ")", ")", ":", "return", "''", "try", ":", "if", "timezone", ".", "is_naive", "(", "value", ")", ":", "default_timezone", "=", "timezone", ".", "get_default_timezone", "(", ")", "value", "=", "timezone", ".", "make_aware", "(", "value", ",", "default_timezone", ")", "except", "Exception", ":", "return", "''", "if", "isinstance", "(", "arg", ",", "tzinfo", ")", ":", "tz", "=", "arg", "elif", "isinstance", "(", "arg", ",", "str", ")", ":", "try", ":", "tz", "=", "pytz", ".", "timezone", "(", "arg", ")", "except", "pytz", ".", "UnknownTimeZoneError", ":", "return", "''", "else", ":", "return", "''", "result", "=", "timezone", ".", "localtime", "(", "value", ",", "tz", ")", "result", "=", "datetimeobject", "(", "result", ".", "year", ",", "result", ".", "month", ",", "result", ".", "day", ",", "result", ".", "hour", ",", "result", ".", "minute", ",", "result", ".", "second", ",", "result", ".", "microsecond", ",", "result", ".", "tzinfo", ")", "result", ".", "convert_to_local_time", "=", "False", "return", "result" ]
converts a datetime to local time in a given time zone .
train
false
13,832
def read_from_smaps(pid, key): smaps = open(('/proc/%s/smaps' % pid)) smaps_info = smaps.read() smaps.close() memory_size = 0 for each_number in re.findall(('%s:\\s+(\\d+)' % key), smaps_info): memory_size += int(each_number) return memory_size
[ "def", "read_from_smaps", "(", "pid", ",", "key", ")", ":", "smaps", "=", "open", "(", "(", "'/proc/%s/smaps'", "%", "pid", ")", ")", "smaps_info", "=", "smaps", ".", "read", "(", ")", "smaps", ".", "close", "(", ")", "memory_size", "=", "0", "for", "each_number", "in", "re", ".", "findall", "(", "(", "'%s:\\\\s+(\\\\d+)'", "%", "key", ")", ",", "smaps_info", ")", ":", "memory_size", "+=", "int", "(", "each_number", ")", "return", "memory_size" ]
get specific item value from the smaps of a process include all sections .
train
false
13,834
def parse_mr_job_stderr(stderr, counters=None): if isinstance(stderr, bytes): stderr = BytesIO(stderr) if (counters is None): counters = {} statuses = [] other = [] for line in stderr: m = _COUNTER_RE.match(line.rstrip('\r\n')) if m: (group, counter, amount_str) = m.groups() group = to_string(group) counter = to_string(counter) counters.setdefault(group, {}) counters[group].setdefault(counter, 0) counters[group][counter] += int(amount_str) continue m = _STATUS_RE.match(line.rstrip('\r\n')) if m: statuses.append(to_string(m.group(1))) continue other.append(to_string(line)) return {'counters': counters, 'statuses': statuses, 'other': other}
[ "def", "parse_mr_job_stderr", "(", "stderr", ",", "counters", "=", "None", ")", ":", "if", "isinstance", "(", "stderr", ",", "bytes", ")", ":", "stderr", "=", "BytesIO", "(", "stderr", ")", "if", "(", "counters", "is", "None", ")", ":", "counters", "=", "{", "}", "statuses", "=", "[", "]", "other", "=", "[", "]", "for", "line", "in", "stderr", ":", "m", "=", "_COUNTER_RE", ".", "match", "(", "line", ".", "rstrip", "(", "'\\r\\n'", ")", ")", "if", "m", ":", "(", "group", ",", "counter", ",", "amount_str", ")", "=", "m", ".", "groups", "(", ")", "group", "=", "to_string", "(", "group", ")", "counter", "=", "to_string", "(", "counter", ")", "counters", ".", "setdefault", "(", "group", ",", "{", "}", ")", "counters", "[", "group", "]", ".", "setdefault", "(", "counter", ",", "0", ")", "counters", "[", "group", "]", "[", "counter", "]", "+=", "int", "(", "amount_str", ")", "continue", "m", "=", "_STATUS_RE", ".", "match", "(", "line", ".", "rstrip", "(", "'\\r\\n'", ")", ")", "if", "m", ":", "statuses", ".", "append", "(", "to_string", "(", "m", ".", "group", "(", "1", ")", ")", ")", "continue", "other", ".", "append", "(", "to_string", "(", "line", ")", ")", "return", "{", "'counters'", ":", "counters", ",", "'statuses'", ":", "statuses", ",", "'other'", ":", "other", "}" ]
parse counters and status messages out of mrjob output .
train
false
13,836
def permutation_helper(random_state, n, shape): assert (n.shape == ()) n = int(n.item()) if (shape is None): shape = () out_shape = list(shape) out_shape.append(n) out = numpy.empty(out_shape, int) for i in numpy.ndindex(*shape): out[i] = random_state.permutation(n) return out
[ "def", "permutation_helper", "(", "random_state", ",", "n", ",", "shape", ")", ":", "assert", "(", "n", ".", "shape", "==", "(", ")", ")", "n", "=", "int", "(", "n", ".", "item", "(", ")", ")", "if", "(", "shape", "is", "None", ")", ":", "shape", "=", "(", ")", "out_shape", "=", "list", "(", "shape", ")", "out_shape", ".", "append", "(", "n", ")", "out", "=", "numpy", ".", "empty", "(", "out_shape", ",", "int", ")", "for", "i", "in", "numpy", ".", "ndindex", "(", "*", "shape", ")", ":", "out", "[", "i", "]", "=", "random_state", ".", "permutation", "(", "n", ")", "return", "out" ]
helper function to generate permutations from integers .
train
false
13,837
def construction_error(tot_items, block_shape, axes, e=None): passed = tuple(map(int, ([tot_items] + list(block_shape)))) implied = tuple(map(int, [len(ax) for ax in axes])) if ((passed == implied) and (e is not None)): raise e if (block_shape[0] == 0): raise ValueError('Empty data passed with indices specified.') raise ValueError('Shape of passed values is {0}, indices imply {1}'.format(passed, implied))
[ "def", "construction_error", "(", "tot_items", ",", "block_shape", ",", "axes", ",", "e", "=", "None", ")", ":", "passed", "=", "tuple", "(", "map", "(", "int", ",", "(", "[", "tot_items", "]", "+", "list", "(", "block_shape", ")", ")", ")", ")", "implied", "=", "tuple", "(", "map", "(", "int", ",", "[", "len", "(", "ax", ")", "for", "ax", "in", "axes", "]", ")", ")", "if", "(", "(", "passed", "==", "implied", ")", "and", "(", "e", "is", "not", "None", ")", ")", ":", "raise", "e", "if", "(", "block_shape", "[", "0", "]", "==", "0", ")", ":", "raise", "ValueError", "(", "'Empty data passed with indices specified.'", ")", "raise", "ValueError", "(", "'Shape of passed values is {0}, indices imply {1}'", ".", "format", "(", "passed", ",", "implied", ")", ")" ]
raise a helpful message about our construction .
train
true
13,838
def linear_eq_to_matrix(equations, *symbols): if (not symbols): raise ValueError('Symbols must be given, for which coefficients are to be found.') if hasattr(symbols[0], '__iter__'): symbols = symbols[0] M = Matrix([symbols]) M = M.col_insert(len(symbols), Matrix([1])) row_no = 1 for equation in equations: f = sympify(equation) if isinstance(f, Equality): f = (f.lhs - f.rhs) coeff_list = [] for symbol in symbols: coeff_list.append(f.coeff(symbol)) coeff_list.append((- f.as_coeff_add(*symbols)[0])) M = M.row_insert(row_no, Matrix([coeff_list])) row_no += 1 M.row_del(0) (A, b) = (M[:, :(-1)], M[:, (-1):]) return (A, b)
[ "def", "linear_eq_to_matrix", "(", "equations", ",", "*", "symbols", ")", ":", "if", "(", "not", "symbols", ")", ":", "raise", "ValueError", "(", "'Symbols must be given, for which coefficients are to be found.'", ")", "if", "hasattr", "(", "symbols", "[", "0", "]", ",", "'__iter__'", ")", ":", "symbols", "=", "symbols", "[", "0", "]", "M", "=", "Matrix", "(", "[", "symbols", "]", ")", "M", "=", "M", ".", "col_insert", "(", "len", "(", "symbols", ")", ",", "Matrix", "(", "[", "1", "]", ")", ")", "row_no", "=", "1", "for", "equation", "in", "equations", ":", "f", "=", "sympify", "(", "equation", ")", "if", "isinstance", "(", "f", ",", "Equality", ")", ":", "f", "=", "(", "f", ".", "lhs", "-", "f", ".", "rhs", ")", "coeff_list", "=", "[", "]", "for", "symbol", "in", "symbols", ":", "coeff_list", ".", "append", "(", "f", ".", "coeff", "(", "symbol", ")", ")", "coeff_list", ".", "append", "(", "(", "-", "f", ".", "as_coeff_add", "(", "*", "symbols", ")", "[", "0", "]", ")", ")", "M", "=", "M", ".", "row_insert", "(", "row_no", ",", "Matrix", "(", "[", "coeff_list", "]", ")", ")", "row_no", "+=", "1", "M", ".", "row_del", "(", "0", ")", "(", "A", ",", "b", ")", "=", "(", "M", "[", ":", ",", ":", "(", "-", "1", ")", "]", ",", "M", "[", ":", ",", "(", "-", "1", ")", ":", "]", ")", "return", "(", "A", ",", "b", ")" ]
converts a given system of equations into matrix form .
train
false
13,839
def gpu_reconstruct_graph(inputs, outputs, tag=None): if (tag is None): tag = '' nw_inputs = [gpu_safe_new(x, tag) for x in inputs] givens = {} for (nw_x, x) in zip(nw_inputs, inputs): givens[x] = nw_x nw_outputs = scan_utils.clone(outputs, replace=givens) return (nw_inputs, nw_outputs)
[ "def", "gpu_reconstruct_graph", "(", "inputs", ",", "outputs", ",", "tag", "=", "None", ")", ":", "if", "(", "tag", "is", "None", ")", ":", "tag", "=", "''", "nw_inputs", "=", "[", "gpu_safe_new", "(", "x", ",", "tag", ")", "for", "x", "in", "inputs", "]", "givens", "=", "{", "}", "for", "(", "nw_x", ",", "x", ")", "in", "zip", "(", "nw_inputs", ",", "inputs", ")", ":", "givens", "[", "x", "]", "=", "nw_x", "nw_outputs", "=", "scan_utils", ".", "clone", "(", "outputs", ",", "replace", "=", "givens", ")", "return", "(", "nw_inputs", ",", "nw_outputs", ")" ]
different interface to clone .
train
false
13,841
def format_prefix(listname='', keyword=''): formattedPrefix = c['PREFIX'] owner = ('@' + c['original_name']) place = '' if keyword: formattedPrefix = ''.join(formattedPrefix.split('#owner')) formattedPrefix = ''.join(formattedPrefix.split('#place')) formattedPrefix = ''.join(formattedPrefix.split('#me')) elif listname: formattedPrefix = ''.join(formattedPrefix.split('#keyword')) formattedPrefix = ''.join(formattedPrefix.split('#me')) (owner, place) = listname.split('/') place = ('/' + place) else: formattedPrefix = ''.join(formattedPrefix.split('#keyword')) formattedPrefix = ''.join(formattedPrefix.split('#owner')) formattedPrefix = ''.join(formattedPrefix.split('#place')) formattedPrefix = formattedPrefix.replace('#owner', owner) formattedPrefix = formattedPrefix.replace('#place', place) formattedPrefix = formattedPrefix.replace('#keyword', keyword) formattedPrefix = formattedPrefix.replace('#me', ('@' + c['original_name'])) return formattedPrefix
[ "def", "format_prefix", "(", "listname", "=", "''", ",", "keyword", "=", "''", ")", ":", "formattedPrefix", "=", "c", "[", "'PREFIX'", "]", "owner", "=", "(", "'@'", "+", "c", "[", "'original_name'", "]", ")", "place", "=", "''", "if", "keyword", ":", "formattedPrefix", "=", "''", ".", "join", "(", "formattedPrefix", ".", "split", "(", "'#owner'", ")", ")", "formattedPrefix", "=", "''", ".", "join", "(", "formattedPrefix", ".", "split", "(", "'#place'", ")", ")", "formattedPrefix", "=", "''", ".", "join", "(", "formattedPrefix", ".", "split", "(", "'#me'", ")", ")", "elif", "listname", ":", "formattedPrefix", "=", "''", ".", "join", "(", "formattedPrefix", ".", "split", "(", "'#keyword'", ")", ")", "formattedPrefix", "=", "''", ".", "join", "(", "formattedPrefix", ".", "split", "(", "'#me'", ")", ")", "(", "owner", ",", "place", ")", "=", "listname", ".", "split", "(", "'/'", ")", "place", "=", "(", "'/'", "+", "place", ")", "else", ":", "formattedPrefix", "=", "''", ".", "join", "(", "formattedPrefix", ".", "split", "(", "'#keyword'", ")", ")", "formattedPrefix", "=", "''", ".", "join", "(", "formattedPrefix", ".", "split", "(", "'#owner'", ")", ")", "formattedPrefix", "=", "''", ".", "join", "(", "formattedPrefix", ".", "split", "(", "'#place'", ")", ")", "formattedPrefix", "=", "formattedPrefix", ".", "replace", "(", "'#owner'", ",", "owner", ")", "formattedPrefix", "=", "formattedPrefix", ".", "replace", "(", "'#place'", ",", "place", ")", "formattedPrefix", "=", "formattedPrefix", ".", "replace", "(", "'#keyword'", ",", "keyword", ")", "formattedPrefix", "=", "formattedPrefix", ".", "replace", "(", "'#me'", ",", "(", "'@'", "+", "c", "[", "'original_name'", "]", ")", ")", "return", "formattedPrefix" ]
format the custom prefix .
train
false
13,844
def test_log_partition_function(): sigma = 2.3 model = DiagonalMND(nvis=1, init_beta=(1 / np.square(sigma)), min_beta=1e-06, max_beta=1000000.0, init_mu=17.0) log_Z = model.log_partition_function() log_Z = function([], log_Z)() ground = np.log((sigma * np.sqrt((2.0 * np.pi)))) print(ground) print(log_Z) assert np.allclose(ground, log_Z)
[ "def", "test_log_partition_function", "(", ")", ":", "sigma", "=", "2.3", "model", "=", "DiagonalMND", "(", "nvis", "=", "1", ",", "init_beta", "=", "(", "1", "/", "np", ".", "square", "(", "sigma", ")", ")", ",", "min_beta", "=", "1e-06", ",", "max_beta", "=", "1000000.0", ",", "init_mu", "=", "17.0", ")", "log_Z", "=", "model", ".", "log_partition_function", "(", ")", "log_Z", "=", "function", "(", "[", "]", ",", "log_Z", ")", "(", ")", "ground", "=", "np", ".", "log", "(", "(", "sigma", "*", "np", ".", "sqrt", "(", "(", "2.0", "*", "np", ".", "pi", ")", ")", ")", ")", "print", "(", "ground", ")", "print", "(", "log_Z", ")", "assert", "np", ".", "allclose", "(", "ground", ",", "log_Z", ")" ]
tests that the log partition function is right in the simple 1d case .
train
false
13,845
def get_backup_size(service): backup_files = get_snapshot_paths(service) total_size = sum((getsize(file) for file in backup_files)) return total_size
[ "def", "get_backup_size", "(", "service", ")", ":", "backup_files", "=", "get_snapshot_paths", "(", "service", ")", "total_size", "=", "sum", "(", "(", "getsize", "(", "file", ")", "for", "file", "in", "backup_files", ")", ")", "return", "total_size" ]
sums up the size of the snapshot files that consist the backup for the given service .
train
false
13,846
def accumulateClassDict(classObj, attr, adict, baseClass=None): for base in classObj.__bases__: accumulateClassDict(base, attr, adict) if ((baseClass is None) or (baseClass in classObj.__bases__)): adict.update(classObj.__dict__.get(attr, {}))
[ "def", "accumulateClassDict", "(", "classObj", ",", "attr", ",", "adict", ",", "baseClass", "=", "None", ")", ":", "for", "base", "in", "classObj", ".", "__bases__", ":", "accumulateClassDict", "(", "base", ",", "attr", ",", "adict", ")", "if", "(", "(", "baseClass", "is", "None", ")", "or", "(", "baseClass", "in", "classObj", ".", "__bases__", ")", ")", ":", "adict", ".", "update", "(", "classObj", ".", "__dict__", ".", "get", "(", "attr", ",", "{", "}", ")", ")" ]
accumulate all attributes of a given name in a class heirarchy into a single dictionary .
train
false
13,847
def teardown_test(): warnings.simplefilter('default')
[ "def", "teardown_test", "(", ")", ":", "warnings", ".", "simplefilter", "(", "'default'", ")" ]
default package level teardown routine for skimage tests .
train
false
13,848
def view_tree_set(v, treeset): treeset.add(v) for (cl, v_input_pos_to_cl) in v.clients: if (cl == 'output'): continue vmap = getattr(cl.op, 'view_map', {}) dmap = getattr(cl.op, 'destroy_map', {}) for (opos, iposlist) in chain(iteritems(vmap), iteritems(dmap)): if (v_input_pos_to_cl in iposlist): if (cl.outputs[opos] not in treeset): view_tree_set(cl.outputs[opos], treeset)
[ "def", "view_tree_set", "(", "v", ",", "treeset", ")", ":", "treeset", ".", "add", "(", "v", ")", "for", "(", "cl", ",", "v_input_pos_to_cl", ")", "in", "v", ".", "clients", ":", "if", "(", "cl", "==", "'output'", ")", ":", "continue", "vmap", "=", "getattr", "(", "cl", ".", "op", ",", "'view_map'", ",", "{", "}", ")", "dmap", "=", "getattr", "(", "cl", ".", "op", ",", "'destroy_map'", ",", "{", "}", ")", "for", "(", "opos", ",", "iposlist", ")", "in", "chain", "(", "iteritems", "(", "vmap", ")", ",", "iteritems", "(", "dmap", ")", ")", ":", "if", "(", "v_input_pos_to_cl", "in", "iposlist", ")", ":", "if", "(", "cl", ".", "outputs", "[", "opos", "]", "not", "in", "treeset", ")", ":", "view_tree_set", "(", "cl", ".", "outputs", "[", "opos", "]", ",", "treeset", ")" ]
add to treeset all variables that are views of v .
train
false
13,850
@require_context def volume_attachment_get_all_by_instance_uuid(context, instance_uuid): session = get_session() with session.begin(): result = model_query(context, models.VolumeAttachment, session=session).filter_by(instance_uuid=instance_uuid).filter((models.VolumeAttachment.attach_status != fields.VolumeAttachStatus.DETACHED)).options(joinedload('volume')).all() return result
[ "@", "require_context", "def", "volume_attachment_get_all_by_instance_uuid", "(", "context", ",", "instance_uuid", ")", ":", "session", "=", "get_session", "(", ")", "with", "session", ".", "begin", "(", ")", ":", "result", "=", "model_query", "(", "context", ",", "models", ".", "VolumeAttachment", ",", "session", "=", "session", ")", ".", "filter_by", "(", "instance_uuid", "=", "instance_uuid", ")", ".", "filter", "(", "(", "models", ".", "VolumeAttachment", ".", "attach_status", "!=", "fields", ".", "VolumeAttachStatus", ".", "DETACHED", ")", ")", ".", "options", "(", "joinedload", "(", "'volume'", ")", ")", ".", "all", "(", ")", "return", "result" ]
fetch all attachment records associated with the specified instance .
train
false
13,852
@scopes.add_arg_scope def variable(name, shape=None, dtype=tf.float32, initializer=None, regularizer=None, trainable=True, collections=None, device='', restore=True): collections = list((collections or [])) collections += [tf.GraphKeys.GLOBAL_VARIABLES, MODEL_VARIABLES] if restore: collections.append(VARIABLES_TO_RESTORE) collections = set(collections) with tf.device(variable_device(device, name)): return tf.get_variable(name, shape=shape, dtype=dtype, initializer=initializer, regularizer=regularizer, trainable=trainable, collections=collections)
[ "@", "scopes", ".", "add_arg_scope", "def", "variable", "(", "name", ",", "shape", "=", "None", ",", "dtype", "=", "tf", ".", "float32", ",", "initializer", "=", "None", ",", "regularizer", "=", "None", ",", "trainable", "=", "True", ",", "collections", "=", "None", ",", "device", "=", "''", ",", "restore", "=", "True", ")", ":", "collections", "=", "list", "(", "(", "collections", "or", "[", "]", ")", ")", "collections", "+=", "[", "tf", ".", "GraphKeys", ".", "GLOBAL_VARIABLES", ",", "MODEL_VARIABLES", "]", "if", "restore", ":", "collections", ".", "append", "(", "VARIABLES_TO_RESTORE", ")", "collections", "=", "set", "(", "collections", ")", "with", "tf", ".", "device", "(", "variable_device", "(", "device", ",", "name", ")", ")", ":", "return", "tf", ".", "get_variable", "(", "name", ",", "shape", "=", "shape", ",", "dtype", "=", "dtype", ",", "initializer", "=", "initializer", ",", "regularizer", "=", "regularizer", ",", "trainable", "=", "trainable", ",", "collections", "=", "collections", ")" ]
gets an existing variable with these parameters or creates a new one .
train
true
13,856
def config_course_cohorts(course, is_cohorted, auto_cohorts=[], manual_cohorts=[], discussion_topics=[], cohorted_discussions=[], always_cohort_inline_discussions=True): def to_id(name): 'Convert name to id.' return topic_name_to_id(course, name) set_course_cohort_settings(course.id, is_cohorted=is_cohorted, cohorted_discussions=[to_id(name) for name in cohorted_discussions], always_cohort_inline_discussions=always_cohort_inline_discussions) for cohort_name in auto_cohorts: cohort = CohortFactory(course_id=course.id, name=cohort_name) CourseCohortFactory(course_user_group=cohort, assignment_type=CourseCohort.RANDOM) for cohort_name in manual_cohorts: cohort = CohortFactory(course_id=course.id, name=cohort_name) CourseCohortFactory(course_user_group=cohort, assignment_type=CourseCohort.MANUAL) course.discussion_topics = dict(((name, {'sort_key': 'A', 'id': to_id(name)}) for name in discussion_topics)) try: modulestore().update_item(course, ModuleStoreEnum.UserID.test) except NotImplementedError: pass
[ "def", "config_course_cohorts", "(", "course", ",", "is_cohorted", ",", "auto_cohorts", "=", "[", "]", ",", "manual_cohorts", "=", "[", "]", ",", "discussion_topics", "=", "[", "]", ",", "cohorted_discussions", "=", "[", "]", ",", "always_cohort_inline_discussions", "=", "True", ")", ":", "def", "to_id", "(", "name", ")", ":", "return", "topic_name_to_id", "(", "course", ",", "name", ")", "set_course_cohort_settings", "(", "course", ".", "id", ",", "is_cohorted", "=", "is_cohorted", ",", "cohorted_discussions", "=", "[", "to_id", "(", "name", ")", "for", "name", "in", "cohorted_discussions", "]", ",", "always_cohort_inline_discussions", "=", "always_cohort_inline_discussions", ")", "for", "cohort_name", "in", "auto_cohorts", ":", "cohort", "=", "CohortFactory", "(", "course_id", "=", "course", ".", "id", ",", "name", "=", "cohort_name", ")", "CourseCohortFactory", "(", "course_user_group", "=", "cohort", ",", "assignment_type", "=", "CourseCohort", ".", "RANDOM", ")", "for", "cohort_name", "in", "manual_cohorts", ":", "cohort", "=", "CohortFactory", "(", "course_id", "=", "course", ".", "id", ",", "name", "=", "cohort_name", ")", "CourseCohortFactory", "(", "course_user_group", "=", "cohort", ",", "assignment_type", "=", "CourseCohort", ".", "MANUAL", ")", "course", ".", "discussion_topics", "=", "dict", "(", "(", "(", "name", ",", "{", "'sort_key'", ":", "'A'", ",", "'id'", ":", "to_id", "(", "name", ")", "}", ")", "for", "name", "in", "discussion_topics", ")", ")", "try", ":", "modulestore", "(", ")", ".", "update_item", "(", "course", ",", "ModuleStoreEnum", ".", "UserID", ".", "test", ")", "except", "NotImplementedError", ":", "pass" ]
set discussions and configure cohorts for a course .
train
false
13,857
def campfire(registry, xml_parent, data): root = XML.SubElement(xml_parent, 'hudson.plugins.campfire.CampfireNotifier') campfire = XML.SubElement(root, 'campfire') if (('subdomain' in data) and data['subdomain']): subdomain = XML.SubElement(campfire, 'subdomain') subdomain.text = data['subdomain'] if (('token' in data) and data['token']): token = XML.SubElement(campfire, 'token') token.text = data['token'] if ('ssl' in data): ssl = XML.SubElement(campfire, 'ssl') ssl.text = str(data['ssl']).lower() if (('room' in data) and data['room']): room = XML.SubElement(root, 'room') name = XML.SubElement(room, 'name') name.text = data['room'] XML.SubElement(room, 'campfire reference="../../campfire"')
[ "def", "campfire", "(", "registry", ",", "xml_parent", ",", "data", ")", ":", "root", "=", "XML", ".", "SubElement", "(", "xml_parent", ",", "'hudson.plugins.campfire.CampfireNotifier'", ")", "campfire", "=", "XML", ".", "SubElement", "(", "root", ",", "'campfire'", ")", "if", "(", "(", "'subdomain'", "in", "data", ")", "and", "data", "[", "'subdomain'", "]", ")", ":", "subdomain", "=", "XML", ".", "SubElement", "(", "campfire", ",", "'subdomain'", ")", "subdomain", ".", "text", "=", "data", "[", "'subdomain'", "]", "if", "(", "(", "'token'", "in", "data", ")", "and", "data", "[", "'token'", "]", ")", ":", "token", "=", "XML", ".", "SubElement", "(", "campfire", ",", "'token'", ")", "token", ".", "text", "=", "data", "[", "'token'", "]", "if", "(", "'ssl'", "in", "data", ")", ":", "ssl", "=", "XML", ".", "SubElement", "(", "campfire", ",", "'ssl'", ")", "ssl", ".", "text", "=", "str", "(", "data", "[", "'ssl'", "]", ")", ".", "lower", "(", ")", "if", "(", "(", "'room'", "in", "data", ")", "and", "data", "[", "'room'", "]", ")", ":", "room", "=", "XML", ".", "SubElement", "(", "root", ",", "'room'", ")", "name", "=", "XML", ".", "SubElement", "(", "room", ",", "'name'", ")", "name", ".", "text", "=", "data", "[", "'room'", "]", "XML", ".", "SubElement", "(", "room", ",", "'campfire reference=\"../../campfire\"'", ")" ]
yaml: campfire send build notifications to campfire rooms .
train
false
13,858
def GetStatus(plist): try: return plist['RunAtLoad'] except KeyError: return 'False'
[ "def", "GetStatus", "(", "plist", ")", ":", "try", ":", "return", "plist", "[", "'RunAtLoad'", "]", "except", "KeyError", ":", "return", "'False'" ]
plists may have a runatload key .
train
false
13,859
def set_lights_temp(hass, lights, mired, brightness): for light in lights: if is_on(hass, light): turn_on(hass, light, color_temp=int(mired), brightness=brightness, transition=30)
[ "def", "set_lights_temp", "(", "hass", ",", "lights", ",", "mired", ",", "brightness", ")", ":", "for", "light", "in", "lights", ":", "if", "is_on", "(", "hass", ",", "light", ")", ":", "turn_on", "(", "hass", ",", "light", ",", "color_temp", "=", "int", "(", "mired", ")", ",", "brightness", "=", "brightness", ",", "transition", "=", "30", ")" ]
set color of array of lights .
train
false
13,860
def is_commerce_service_configured(): ecommerce_api_url = configuration_helpers.get_value('ECOMMERCE_API_URL', settings.ECOMMERCE_API_URL) ecommerce_api_signing_key = configuration_helpers.get_value('ECOMMERCE_API_SIGNING_KEY', settings.ECOMMERCE_API_SIGNING_KEY) return bool((ecommerce_api_url and ecommerce_api_signing_key))
[ "def", "is_commerce_service_configured", "(", ")", ":", "ecommerce_api_url", "=", "configuration_helpers", ".", "get_value", "(", "'ECOMMERCE_API_URL'", ",", "settings", ".", "ECOMMERCE_API_URL", ")", "ecommerce_api_signing_key", "=", "configuration_helpers", ".", "get_value", "(", "'ECOMMERCE_API_SIGNING_KEY'", ",", "settings", ".", "ECOMMERCE_API_SIGNING_KEY", ")", "return", "bool", "(", "(", "ecommerce_api_url", "and", "ecommerce_api_signing_key", ")", ")" ]
return a boolean indicating whether or not configuration is present to use the external commerce service .
train
false
13,865
@frappe.whitelist() def get_companies(): return [d.name for d in frappe.get_list(u'Company', fields=[u'name'], order_by=u'name')]
[ "@", "frappe", ".", "whitelist", "(", ")", "def", "get_companies", "(", ")", ":", "return", "[", "d", ".", "name", "for", "d", "in", "frappe", ".", "get_list", "(", "u'Company'", ",", "fields", "=", "[", "u'name'", "]", ",", "order_by", "=", "u'name'", ")", "]" ]
get a list of companies based on permission .
train
false
13,866
def clear_all_messages(): BackendMessage.objects.filter(name=BACKEND_NAME).delete()
[ "def", "clear_all_messages", "(", ")", ":", "BackendMessage", ".", "objects", ".", "filter", "(", "name", "=", "BACKEND_NAME", ")", ".", "delete", "(", ")" ]
forget all messages .
train
false
13,867
def parse_name(source, allow_numeric=False, allow_group_0=False): name = source.get_while(set(')>'), include=False) if (not name): raise error('missing group name', source.string, source.pos) if name.isdigit(): min_group = (0 if allow_group_0 else 1) if ((not allow_numeric) or (int(name) < min_group)): raise error('bad character in group name', source.string, source.pos) elif (not is_identifier(name)): raise error('bad character in group name', source.string, source.pos) return name
[ "def", "parse_name", "(", "source", ",", "allow_numeric", "=", "False", ",", "allow_group_0", "=", "False", ")", ":", "name", "=", "source", ".", "get_while", "(", "set", "(", "')>'", ")", ",", "include", "=", "False", ")", "if", "(", "not", "name", ")", ":", "raise", "error", "(", "'missing group name'", ",", "source", ".", "string", ",", "source", ".", "pos", ")", "if", "name", ".", "isdigit", "(", ")", ":", "min_group", "=", "(", "0", "if", "allow_group_0", "else", "1", ")", "if", "(", "(", "not", "allow_numeric", ")", "or", "(", "int", "(", "name", ")", "<", "min_group", ")", ")", ":", "raise", "error", "(", "'bad character in group name'", ",", "source", ".", "string", ",", "source", ".", "pos", ")", "elif", "(", "not", "is_identifier", "(", "name", ")", ")", ":", "raise", "error", "(", "'bad character in group name'", ",", "source", ".", "string", ",", "source", ".", "pos", ")", "return", "name" ]
parses a name .
train
false
13,868
def dup_add(f, g, K): if (not f): return g if (not g): return f df = dup_degree(f) dg = dup_degree(g) if (df == dg): return dup_strip([(a + b) for (a, b) in zip(f, g)]) else: k = abs((df - dg)) if (df > dg): (h, f) = (f[:k], f[k:]) else: (h, g) = (g[:k], g[k:]) return (h + [(a + b) for (a, b) in zip(f, g)])
[ "def", "dup_add", "(", "f", ",", "g", ",", "K", ")", ":", "if", "(", "not", "f", ")", ":", "return", "g", "if", "(", "not", "g", ")", ":", "return", "f", "df", "=", "dup_degree", "(", "f", ")", "dg", "=", "dup_degree", "(", "g", ")", "if", "(", "df", "==", "dg", ")", ":", "return", "dup_strip", "(", "[", "(", "a", "+", "b", ")", "for", "(", "a", ",", "b", ")", "in", "zip", "(", "f", ",", "g", ")", "]", ")", "else", ":", "k", "=", "abs", "(", "(", "df", "-", "dg", ")", ")", "if", "(", "df", ">", "dg", ")", ":", "(", "h", ",", "f", ")", "=", "(", "f", "[", ":", "k", "]", ",", "f", "[", "k", ":", "]", ")", "else", ":", "(", "h", ",", "g", ")", "=", "(", "g", "[", ":", "k", "]", ",", "g", "[", "k", ":", "]", ")", "return", "(", "h", "+", "[", "(", "a", "+", "b", ")", "for", "(", "a", ",", "b", ")", "in", "zip", "(", "f", ",", "g", ")", "]", ")" ]
add dense polynomials in k[x] .
train
false
13,869
def identify_object(inp): if hasattr(inp, '__dbclass__'): clsname = inp.__dbclass__.__name__ if (clsname == 'PlayerDB'): return (inp, 'player') elif (clsname == 'ObjectDB'): return (inp, 'object') elif (clsname == 'ChannelDB'): return (inp, 'channel') if isinstance(inp, basestring): return (inp, 'string') elif dbref(inp): return (dbref(inp), 'dbref') else: return (inp, None)
[ "def", "identify_object", "(", "inp", ")", ":", "if", "hasattr", "(", "inp", ",", "'__dbclass__'", ")", ":", "clsname", "=", "inp", ".", "__dbclass__", ".", "__name__", "if", "(", "clsname", "==", "'PlayerDB'", ")", ":", "return", "(", "inp", ",", "'player'", ")", "elif", "(", "clsname", "==", "'ObjectDB'", ")", ":", "return", "(", "inp", ",", "'object'", ")", "elif", "(", "clsname", "==", "'ChannelDB'", ")", ":", "return", "(", "inp", ",", "'channel'", ")", "if", "isinstance", "(", "inp", ",", "basestring", ")", ":", "return", "(", "inp", ",", "'string'", ")", "elif", "dbref", "(", "inp", ")", ":", "return", "(", "dbref", "(", "inp", ")", ",", "'dbref'", ")", "else", ":", "return", "(", "inp", ",", "None", ")" ]
helper function .
train
false
13,874
def nextCategory(string): if string.startswith(u'('): return matchBrackets(string) return NEXTPRIM_RE.match(string).groups()
[ "def", "nextCategory", "(", "string", ")", ":", "if", "string", ".", "startswith", "(", "u'('", ")", ":", "return", "matchBrackets", "(", "string", ")", "return", "NEXTPRIM_RE", ".", "match", "(", "string", ")", ".", "groups", "(", ")" ]
separate the string for the next portion of the category from the rest of the string .
train
false
13,876
def __write_docker_compose(path, docker_compose): if (os.path.isdir(path) is False): os.mkdir(path) f = salt.utils.fopen(os.path.join(path, dc_filename), 'w') if f: f.write(docker_compose) f.close() else: return __standardize_result(False, 'Could not write docker-compose file in {0}'.format(path), None, None) project = __load_project(path) if isinstance(project, dict): os.remove(os.path.join(path, dc_filename)) return project return path
[ "def", "__write_docker_compose", "(", "path", ",", "docker_compose", ")", ":", "if", "(", "os", ".", "path", ".", "isdir", "(", "path", ")", "is", "False", ")", ":", "os", ".", "mkdir", "(", "path", ")", "f", "=", "salt", ".", "utils", ".", "fopen", "(", "os", ".", "path", ".", "join", "(", "path", ",", "dc_filename", ")", ",", "'w'", ")", "if", "f", ":", "f", ".", "write", "(", "docker_compose", ")", "f", ".", "close", "(", ")", "else", ":", "return", "__standardize_result", "(", "False", ",", "'Could not write docker-compose file in {0}'", ".", "format", "(", "path", ")", ",", "None", ",", "None", ")", "project", "=", "__load_project", "(", "path", ")", "if", "isinstance", "(", "project", ",", "dict", ")", ":", "os", ".", "remove", "(", "os", ".", "path", ".", "join", "(", "path", ",", "dc_filename", ")", ")", "return", "project", "return", "path" ]
write docker-compose to a temp directory in order to use it with docker-compose .
train
false
13,877
def register_treebuilders_from(module): this_module = sys.modules['bs4.builder'] for name in module.__all__: obj = getattr(module, name) if issubclass(obj, TreeBuilder): setattr(this_module, name, obj) this_module.__all__.append(name) this_module.builder_registry.register(obj)
[ "def", "register_treebuilders_from", "(", "module", ")", ":", "this_module", "=", "sys", ".", "modules", "[", "'bs4.builder'", "]", "for", "name", "in", "module", ".", "__all__", ":", "obj", "=", "getattr", "(", "module", ",", "name", ")", "if", "issubclass", "(", "obj", ",", "TreeBuilder", ")", ":", "setattr", "(", "this_module", ",", "name", ",", "obj", ")", "this_module", ".", "__all__", ".", "append", "(", "name", ")", "this_module", ".", "builder_registry", ".", "register", "(", "obj", ")" ]
copy treebuilders from the given module into this module .
train
false
13,878
def get_root_modules(paths): modules = [] spy_modules = [] for path in paths: spy_modules += module_list(path) spy_modules = set(spy_modules) if ('__init__' in spy_modules): spy_modules.remove('__init__') spy_modules = list(spy_modules) if ('rootmodules' in modules_db): return (spy_modules + modules_db['rootmodules']) t = time() modules = list(sys.builtin_module_names) for path in sys.path: modules += module_list(path) if ((time() - t) > TIMEOUT_GIVEUP): print 'Module list generation is taking too long, we give up.\n' modules_db['rootmodules'] = [] return [] modules = set(modules) excluded_modules = (['__init__'] + spy_modules) for mod in excluded_modules: if (mod in modules): modules.remove(mod) modules = list(modules) modules_db['rootmodules'] = modules return (spy_modules + modules)
[ "def", "get_root_modules", "(", "paths", ")", ":", "modules", "=", "[", "]", "spy_modules", "=", "[", "]", "for", "path", "in", "paths", ":", "spy_modules", "+=", "module_list", "(", "path", ")", "spy_modules", "=", "set", "(", "spy_modules", ")", "if", "(", "'__init__'", "in", "spy_modules", ")", ":", "spy_modules", ".", "remove", "(", "'__init__'", ")", "spy_modules", "=", "list", "(", "spy_modules", ")", "if", "(", "'rootmodules'", "in", "modules_db", ")", ":", "return", "(", "spy_modules", "+", "modules_db", "[", "'rootmodules'", "]", ")", "t", "=", "time", "(", ")", "modules", "=", "list", "(", "sys", ".", "builtin_module_names", ")", "for", "path", "in", "sys", ".", "path", ":", "modules", "+=", "module_list", "(", "path", ")", "if", "(", "(", "time", "(", ")", "-", "t", ")", ">", "TIMEOUT_GIVEUP", ")", ":", "print", "'Module list generation is taking too long, we give up.\\n'", "modules_db", "[", "'rootmodules'", "]", "=", "[", "]", "return", "[", "]", "modules", "=", "set", "(", "modules", ")", "excluded_modules", "=", "(", "[", "'__init__'", "]", "+", "spy_modules", ")", "for", "mod", "in", "excluded_modules", ":", "if", "(", "mod", "in", "modules", ")", ":", "modules", ".", "remove", "(", "mod", ")", "modules", "=", "list", "(", "modules", ")", "modules_db", "[", "'rootmodules'", "]", "=", "modules", "return", "(", "spy_modules", "+", "modules", ")" ]
returns list of names of all modules from pythonpath folders .
train
false
13,879
def buildTransform(inputProfile, outputProfile, inMode, outMode, renderingIntent=INTENT_PERCEPTUAL, flags=0): if ((not isinstance(renderingIntent, int)) or (not (0 <= renderingIntent <= 3))): raise PyCMSError('renderingIntent must be an integer between 0 and 3') if ((not isinstance(flags, int)) or (not (0 <= flags <= _MAX_FLAG))): raise PyCMSError(('flags must be an integer between 0 and %s' + _MAX_FLAG)) try: if (not isinstance(inputProfile, ImageCmsProfile)): inputProfile = ImageCmsProfile(inputProfile) if (not isinstance(outputProfile, ImageCmsProfile)): outputProfile = ImageCmsProfile(outputProfile) return ImageCmsTransform(inputProfile, outputProfile, inMode, outMode, renderingIntent, flags=flags) except (IOError, TypeError, ValueError) as v: raise PyCMSError(v)
[ "def", "buildTransform", "(", "inputProfile", ",", "outputProfile", ",", "inMode", ",", "outMode", ",", "renderingIntent", "=", "INTENT_PERCEPTUAL", ",", "flags", "=", "0", ")", ":", "if", "(", "(", "not", "isinstance", "(", "renderingIntent", ",", "int", ")", ")", "or", "(", "not", "(", "0", "<=", "renderingIntent", "<=", "3", ")", ")", ")", ":", "raise", "PyCMSError", "(", "'renderingIntent must be an integer between 0 and 3'", ")", "if", "(", "(", "not", "isinstance", "(", "flags", ",", "int", ")", ")", "or", "(", "not", "(", "0", "<=", "flags", "<=", "_MAX_FLAG", ")", ")", ")", ":", "raise", "PyCMSError", "(", "(", "'flags must be an integer between 0 and %s'", "+", "_MAX_FLAG", ")", ")", "try", ":", "if", "(", "not", "isinstance", "(", "inputProfile", ",", "ImageCmsProfile", ")", ")", ":", "inputProfile", "=", "ImageCmsProfile", "(", "inputProfile", ")", "if", "(", "not", "isinstance", "(", "outputProfile", ",", "ImageCmsProfile", ")", ")", ":", "outputProfile", "=", "ImageCmsProfile", "(", "outputProfile", ")", "return", "ImageCmsTransform", "(", "inputProfile", ",", "outputProfile", ",", "inMode", ",", "outMode", ",", "renderingIntent", ",", "flags", "=", "flags", ")", "except", "(", "IOError", ",", "TypeError", ",", "ValueError", ")", "as", "v", ":", "raise", "PyCMSError", "(", "v", ")" ]
builds an icc transform mapping from the inputprofile to the outputprofile .
train
false
13,880
@pytest.mark.django_db def test_valid_permissions_for_all_modules(): for module in get_modules(): url_permissions = set(get_permissions_from_urls(module.get_urls())) module_permissions = set(module.get_required_permissions()) for permission in (url_permissions | module_permissions): if (module.__class__ in migrated_permissions): assert (permission in migrated_permissions[module.__class__]) else: assert get_permission_object_from_string(permission)
[ "@", "pytest", ".", "mark", ".", "django_db", "def", "test_valid_permissions_for_all_modules", "(", ")", ":", "for", "module", "in", "get_modules", "(", ")", ":", "url_permissions", "=", "set", "(", "get_permissions_from_urls", "(", "module", ".", "get_urls", "(", ")", ")", ")", "module_permissions", "=", "set", "(", "module", ".", "get_required_permissions", "(", ")", ")", "for", "permission", "in", "(", "url_permissions", "|", "module_permissions", ")", ":", "if", "(", "module", ".", "__class__", "in", "migrated_permissions", ")", ":", "assert", "(", "permission", "in", "migrated_permissions", "[", "module", ".", "__class__", "]", ")", "else", ":", "assert", "get_permission_object_from_string", "(", "permission", ")" ]
if a module requires permissions .
train
false
13,881
def make_lag_names(names, lag_order, trendorder=1): lag_names = [] if isinstance(names, string_types): names = [names] for i in range(1, (lag_order + 1)): for name in names: if (not isinstance(name, string_types)): name = str(name) lag_names.append(((('L' + str(i)) + '.') + name)) if (trendorder != 0): lag_names.insert(0, 'const') if (trendorder > 1): lag_names.insert(0, 'trend') if (trendorder > 2): lag_names.insert(0, 'trend**2') return lag_names
[ "def", "make_lag_names", "(", "names", ",", "lag_order", ",", "trendorder", "=", "1", ")", ":", "lag_names", "=", "[", "]", "if", "isinstance", "(", "names", ",", "string_types", ")", ":", "names", "=", "[", "names", "]", "for", "i", "in", "range", "(", "1", ",", "(", "lag_order", "+", "1", ")", ")", ":", "for", "name", "in", "names", ":", "if", "(", "not", "isinstance", "(", "name", ",", "string_types", ")", ")", ":", "name", "=", "str", "(", "name", ")", "lag_names", ".", "append", "(", "(", "(", "(", "'L'", "+", "str", "(", "i", ")", ")", "+", "'.'", ")", "+", "name", ")", ")", "if", "(", "trendorder", "!=", "0", ")", ":", "lag_names", ".", "insert", "(", "0", ",", "'const'", ")", "if", "(", "trendorder", ">", "1", ")", ":", "lag_names", ".", "insert", "(", "0", ",", "'trend'", ")", "if", "(", "trendorder", ">", "2", ")", ":", "lag_names", ".", "insert", "(", "0", ",", "'trend**2'", ")", "return", "lag_names" ]
produce list of lag-variable names .
train
false
13,882
def fixxpath(root, xpath): (namespace, root_tag) = root.tag[1:].split('}', 1) fixed_xpath = '/'.join([('{%s}%s' % (namespace, e)) for e in xpath.split('/')]) return fixed_xpath
[ "def", "fixxpath", "(", "root", ",", "xpath", ")", ":", "(", "namespace", ",", "root_tag", ")", "=", "root", ".", "tag", "[", "1", ":", "]", ".", "split", "(", "'}'", ",", "1", ")", "fixed_xpath", "=", "'/'", ".", "join", "(", "[", "(", "'{%s}%s'", "%", "(", "namespace", ",", "e", ")", ")", "for", "e", "in", "xpath", ".", "split", "(", "'/'", ")", "]", ")", "return", "fixed_xpath" ]
elementtree wants namespaces in its xpaths .
train
false
13,883
def exec2(ctid_or_name, command): return run_as_root(("vzctl exec2 %s '%s'" % (ctid_or_name, command)))
[ "def", "exec2", "(", "ctid_or_name", ",", "command", ")", ":", "return", "run_as_root", "(", "(", "\"vzctl exec2 %s '%s'\"", "%", "(", "ctid_or_name", ",", "command", ")", ")", ")" ]
run a command inside the container .
train
false
13,884
def initialize(cli): cli.register('building-command-table.main', change_name) cli.register('building-command-table.deploy', inject_commands) cli.register('building-argument-table.deploy.get-application-revision', modify_revision_arguments) cli.register('building-argument-table.deploy.register-application-revision', modify_revision_arguments) cli.register('building-argument-table.deploy.create-deployment', modify_revision_arguments)
[ "def", "initialize", "(", "cli", ")", ":", "cli", ".", "register", "(", "'building-command-table.main'", ",", "change_name", ")", "cli", ".", "register", "(", "'building-command-table.deploy'", ",", "inject_commands", ")", "cli", ".", "register", "(", "'building-argument-table.deploy.get-application-revision'", ",", "modify_revision_arguments", ")", "cli", ".", "register", "(", "'building-argument-table.deploy.register-application-revision'", ",", "modify_revision_arguments", ")", "cli", ".", "register", "(", "'building-argument-table.deploy.create-deployment'", ",", "modify_revision_arguments", ")" ]
initialize linter with checkers in this package .
train
false
13,886
def list_storage_services(conn=None, call=None): if (call != 'function'): raise SaltCloudSystemExit('The list_storage_services function must be called with -f or --function.') if (not conn): conn = get_conn() ret = {} accounts = conn.list_storage_accounts() for service in accounts.storage_services: ret[service.service_name] = {'capabilities': service.capabilities, 'service_name': service.service_name, 'storage_service_properties': service.storage_service_properties, 'extended_properties': service.extended_properties, 'storage_service_keys': service.storage_service_keys, 'url': service.url} return ret
[ "def", "list_storage_services", "(", "conn", "=", "None", ",", "call", "=", "None", ")", ":", "if", "(", "call", "!=", "'function'", ")", ":", "raise", "SaltCloudSystemExit", "(", "'The list_storage_services function must be called with -f or --function.'", ")", "if", "(", "not", "conn", ")", ":", "conn", "=", "get_conn", "(", ")", "ret", "=", "{", "}", "accounts", "=", "conn", ".", "list_storage_accounts", "(", ")", "for", "service", "in", "accounts", ".", "storage_services", ":", "ret", "[", "service", ".", "service_name", "]", "=", "{", "'capabilities'", ":", "service", ".", "capabilities", ",", "'service_name'", ":", "service", ".", "service_name", ",", "'storage_service_properties'", ":", "service", ".", "storage_service_properties", ",", "'extended_properties'", ":", "service", ".", "extended_properties", ",", "'storage_service_keys'", ":", "service", ".", "storage_service_keys", ",", "'url'", ":", "service", ".", "url", "}", "return", "ret" ]
list vms on this azure account .
train
true
13,887
def build_name(registry, xml_parent, data): bsetter = XML.SubElement(xml_parent, 'org.jenkinsci.plugins.buildnamesetter.BuildNameSetter') XML.SubElement(bsetter, 'template').text = data['name']
[ "def", "build_name", "(", "registry", ",", "xml_parent", ",", "data", ")", ":", "bsetter", "=", "XML", ".", "SubElement", "(", "xml_parent", ",", "'org.jenkinsci.plugins.buildnamesetter.BuildNameSetter'", ")", "XML", ".", "SubElement", "(", "bsetter", ",", "'template'", ")", ".", "text", "=", "data", "[", "'name'", "]" ]
given a dictionary that represents a "long" imdb name .
train
false
13,888
def update_site_forward(apps, schema_editor): Site = apps.get_model(u'sites', u'Site') Site.objects.update_or_create(id=settings.SITE_ID, defaults={u'domain': u'{{cookiecutter.domain_name}}', u'name': u'{{cookiecutter.project_name}}'})
[ "def", "update_site_forward", "(", "apps", ",", "schema_editor", ")", ":", "Site", "=", "apps", ".", "get_model", "(", "u'sites'", ",", "u'Site'", ")", "Site", ".", "objects", ".", "update_or_create", "(", "id", "=", "settings", ".", "SITE_ID", ",", "defaults", "=", "{", "u'domain'", ":", "u'{{cookiecutter.domain_name}}'", ",", "u'name'", ":", "u'{{cookiecutter.project_name}}'", "}", ")" ]
set site domain and name .
train
false
13,890
def dup_discriminant(f, K): d = dup_degree(f) if (d <= 0): return K.zero else: s = ((-1) ** ((d * (d - 1)) // 2)) c = dup_LC(f, K) r = dup_resultant(f, dup_diff(f, 1, K), K) return K.quo(r, (c * K(s)))
[ "def", "dup_discriminant", "(", "f", ",", "K", ")", ":", "d", "=", "dup_degree", "(", "f", ")", "if", "(", "d", "<=", "0", ")", ":", "return", "K", ".", "zero", "else", ":", "s", "=", "(", "(", "-", "1", ")", "**", "(", "(", "d", "*", "(", "d", "-", "1", ")", ")", "//", "2", ")", ")", "c", "=", "dup_LC", "(", "f", ",", "K", ")", "r", "=", "dup_resultant", "(", "f", ",", "dup_diff", "(", "f", ",", "1", ",", "K", ")", ",", "K", ")", "return", "K", ".", "quo", "(", "r", ",", "(", "c", "*", "K", "(", "s", ")", ")", ")" ]
computes discriminant of a polynomial in k[x] .
train
false
13,891
def path_surgery(cmd): dirs = ('/usr/sbin', '/usr/local/bin', '/usr/local/sbin') path = os.environ['PATH'] added = [] for d in dirs: if (d not in path): path += (os.pathsep + d) added.append(d) if any(added): logger.debug("Can't find %s, attempting PATH mitigation by adding %s", cmd, os.pathsep.join(added)) os.environ['PATH'] = path if util.exe_exists(cmd): return True else: expanded = (' expanded' if any(added) else '') logger.warning('Failed to find %s in%s PATH: %s', cmd, expanded, path) return False
[ "def", "path_surgery", "(", "cmd", ")", ":", "dirs", "=", "(", "'/usr/sbin'", ",", "'/usr/local/bin'", ",", "'/usr/local/sbin'", ")", "path", "=", "os", ".", "environ", "[", "'PATH'", "]", "added", "=", "[", "]", "for", "d", "in", "dirs", ":", "if", "(", "d", "not", "in", "path", ")", ":", "path", "+=", "(", "os", ".", "pathsep", "+", "d", ")", "added", ".", "append", "(", "d", ")", "if", "any", "(", "added", ")", ":", "logger", ".", "debug", "(", "\"Can't find %s, attempting PATH mitigation by adding %s\"", ",", "cmd", ",", "os", ".", "pathsep", ".", "join", "(", "added", ")", ")", "os", ".", "environ", "[", "'PATH'", "]", "=", "path", "if", "util", ".", "exe_exists", "(", "cmd", ")", ":", "return", "True", "else", ":", "expanded", "=", "(", "' expanded'", "if", "any", "(", "added", ")", "else", "''", ")", "logger", ".", "warning", "(", "'Failed to find %s in%s PATH: %s'", ",", "cmd", ",", "expanded", ",", "path", ")", "return", "False" ]
attempt to perform path surgery to find cmd mitigates URL .
train
false
13,892
def get_retcode(ret): retcode = 0 if (isinstance(ret, dict) and (ret.get('retcode', 0) != 0)): return ret['retcode'] elif (isinstance(ret, bool) and (not ret)): return 1 return retcode
[ "def", "get_retcode", "(", "ret", ")", ":", "retcode", "=", "0", "if", "(", "isinstance", "(", "ret", ",", "dict", ")", "and", "(", "ret", ".", "get", "(", "'retcode'", ",", "0", ")", "!=", "0", ")", ")", ":", "return", "ret", "[", "'retcode'", "]", "elif", "(", "isinstance", "(", "ret", ",", "bool", ")", "and", "(", "not", "ret", ")", ")", ":", "return", "1", "return", "retcode" ]
determine a retcode for a given return .
train
true
13,893
def _get_powercfg_minute_values(scheme, guid, subguid, safe_name): if (scheme is None): scheme = _get_current_scheme() if (__grains__['osrelease'] == '7'): cmd = 'powercfg /q {0} {1}'.format(scheme, guid) else: cmd = 'powercfg /q {0} {1} {2}'.format(scheme, guid, subguid) out = __salt__['cmd.run'](cmd, python_shell=False) split = out.split('\r\n\r\n') if (len(split) > 1): for s in split: if ((safe_name in s) or (subguid in s)): out = s break else: out = split[0] raw_settings = re.findall('Power Setting Index: ([0-9a-fx]+)', out) return {'ac': (int(raw_settings[0], 0) / 60), 'dc': (int(raw_settings[1], 0) / 60)}
[ "def", "_get_powercfg_minute_values", "(", "scheme", ",", "guid", ",", "subguid", ",", "safe_name", ")", ":", "if", "(", "scheme", "is", "None", ")", ":", "scheme", "=", "_get_current_scheme", "(", ")", "if", "(", "__grains__", "[", "'osrelease'", "]", "==", "'7'", ")", ":", "cmd", "=", "'powercfg /q {0} {1}'", ".", "format", "(", "scheme", ",", "guid", ")", "else", ":", "cmd", "=", "'powercfg /q {0} {1} {2}'", ".", "format", "(", "scheme", ",", "guid", ",", "subguid", ")", "out", "=", "__salt__", "[", "'cmd.run'", "]", "(", "cmd", ",", "python_shell", "=", "False", ")", "split", "=", "out", ".", "split", "(", "'\\r\\n\\r\\n'", ")", "if", "(", "len", "(", "split", ")", ">", "1", ")", ":", "for", "s", "in", "split", ":", "if", "(", "(", "safe_name", "in", "s", ")", "or", "(", "subguid", "in", "s", ")", ")", ":", "out", "=", "s", "break", "else", ":", "out", "=", "split", "[", "0", "]", "raw_settings", "=", "re", ".", "findall", "(", "'Power Setting Index: ([0-9a-fx]+)'", ",", "out", ")", "return", "{", "'ac'", ":", "(", "int", "(", "raw_settings", "[", "0", "]", ",", "0", ")", "/", "60", ")", ",", "'dc'", ":", "(", "int", "(", "raw_settings", "[", "1", "]", ",", "0", ")", "/", "60", ")", "}" ]
returns the ac/dc values in an array for a guid and subguid for a the given scheme .
train
true
13,894
def libvlc_audio_equalizer_get_preset_name(u_index): f = (_Cfunctions.get('libvlc_audio_equalizer_get_preset_name', None) or _Cfunction('libvlc_audio_equalizer_get_preset_name', ((1,),), None, ctypes.c_char_p, ctypes.c_uint)) return f(u_index)
[ "def", "libvlc_audio_equalizer_get_preset_name", "(", "u_index", ")", ":", "f", "=", "(", "_Cfunctions", ".", "get", "(", "'libvlc_audio_equalizer_get_preset_name'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_audio_equalizer_get_preset_name'", ",", "(", "(", "1", ",", ")", ",", ")", ",", "None", ",", "ctypes", ".", "c_char_p", ",", "ctypes", ".", "c_uint", ")", ")", "return", "f", "(", "u_index", ")" ]
get the name of a particular equalizer preset .
train
true
13,896
def get_composite_indexes_rows(entities, composite_indexes): if (len(entities) == 0): return [] row_keys = [] for ent in entities: for index_def in composite_indexes: kind = get_entity_kind(ent.key()) if (index_def.definition().entity_type() != kind): continue prop_name_def_list = [index_prop.name() for index_prop in index_def.definition().property_list()] all_prop_names_in_ent = [prop.name() for prop in ent.property_list()] has_values = True for index_prop_name in prop_name_def_list: if (index_prop_name not in all_prop_names_in_ent): has_values = False if (index_prop_name == '__key__'): has_values = True if (not has_values): continue composite_index_keys = get_composite_index_keys(index_def, ent) row_keys.extend(composite_index_keys) return row_keys
[ "def", "get_composite_indexes_rows", "(", "entities", ",", "composite_indexes", ")", ":", "if", "(", "len", "(", "entities", ")", "==", "0", ")", ":", "return", "[", "]", "row_keys", "=", "[", "]", "for", "ent", "in", "entities", ":", "for", "index_def", "in", "composite_indexes", ":", "kind", "=", "get_entity_kind", "(", "ent", ".", "key", "(", ")", ")", "if", "(", "index_def", ".", "definition", "(", ")", ".", "entity_type", "(", ")", "!=", "kind", ")", ":", "continue", "prop_name_def_list", "=", "[", "index_prop", ".", "name", "(", ")", "for", "index_prop", "in", "index_def", ".", "definition", "(", ")", ".", "property_list", "(", ")", "]", "all_prop_names_in_ent", "=", "[", "prop", ".", "name", "(", ")", "for", "prop", "in", "ent", ".", "property_list", "(", ")", "]", "has_values", "=", "True", "for", "index_prop_name", "in", "prop_name_def_list", ":", "if", "(", "index_prop_name", "not", "in", "all_prop_names_in_ent", ")", ":", "has_values", "=", "False", "if", "(", "index_prop_name", "==", "'__key__'", ")", ":", "has_values", "=", "True", "if", "(", "not", "has_values", ")", ":", "continue", "composite_index_keys", "=", "get_composite_index_keys", "(", "index_def", ",", "ent", ")", "row_keys", ".", "extend", "(", "composite_index_keys", ")", "return", "row_keys" ]
get the composite indexes keys in the db for the given entities .
train
false
13,898
def _json_team_stats(data): return TeamStats(first_downs=int(data['totfd']), total_yds=int(data['totyds']), passing_yds=int(data['pyds']), rushing_yds=int(data['ryds']), penalty_cnt=int(data['pen']), penalty_yds=int(data['penyds']), turnovers=int(data['trnovr']), punt_cnt=int(data['pt']), punt_yds=int(data['ptyds']), punt_avg=int(data['ptavg']), pos_time=PossessionTime(data['top']))
[ "def", "_json_team_stats", "(", "data", ")", ":", "return", "TeamStats", "(", "first_downs", "=", "int", "(", "data", "[", "'totfd'", "]", ")", ",", "total_yds", "=", "int", "(", "data", "[", "'totyds'", "]", ")", ",", "passing_yds", "=", "int", "(", "data", "[", "'pyds'", "]", ")", ",", "rushing_yds", "=", "int", "(", "data", "[", "'ryds'", "]", ")", ",", "penalty_cnt", "=", "int", "(", "data", "[", "'pen'", "]", ")", ",", "penalty_yds", "=", "int", "(", "data", "[", "'penyds'", "]", ")", ",", "turnovers", "=", "int", "(", "data", "[", "'trnovr'", "]", ")", ",", "punt_cnt", "=", "int", "(", "data", "[", "'pt'", "]", ")", ",", "punt_yds", "=", "int", "(", "data", "[", "'ptyds'", "]", ")", ",", "punt_avg", "=", "int", "(", "data", "[", "'ptavg'", "]", ")", ",", "pos_time", "=", "PossessionTime", "(", "data", "[", "'top'", "]", ")", ")" ]
takes a team stats json entry and converts it to a teamstats namedtuple .
train
false
13,899
def host_is_trusted(hostname, trusted_list): if (not hostname): return False if isinstance(trusted_list, string_types): trusted_list = [trusted_list] def _normalize(hostname): if (':' in hostname): hostname = hostname.rsplit(':', 1)[0] return _encode_idna(hostname) try: hostname = _normalize(hostname) except UnicodeError: return False for ref in trusted_list: if ref.startswith('.'): ref = ref[1:] suffix_match = True else: suffix_match = False try: ref = _normalize(ref) except UnicodeError: return False if (ref == hostname): return True if (suffix_match and hostname.endswith(('.' + ref))): return True return False
[ "def", "host_is_trusted", "(", "hostname", ",", "trusted_list", ")", ":", "if", "(", "not", "hostname", ")", ":", "return", "False", "if", "isinstance", "(", "trusted_list", ",", "string_types", ")", ":", "trusted_list", "=", "[", "trusted_list", "]", "def", "_normalize", "(", "hostname", ")", ":", "if", "(", "':'", "in", "hostname", ")", ":", "hostname", "=", "hostname", ".", "rsplit", "(", "':'", ",", "1", ")", "[", "0", "]", "return", "_encode_idna", "(", "hostname", ")", "try", ":", "hostname", "=", "_normalize", "(", "hostname", ")", "except", "UnicodeError", ":", "return", "False", "for", "ref", "in", "trusted_list", ":", "if", "ref", ".", "startswith", "(", "'.'", ")", ":", "ref", "=", "ref", "[", "1", ":", "]", "suffix_match", "=", "True", "else", ":", "suffix_match", "=", "False", "try", ":", "ref", "=", "_normalize", "(", "ref", ")", "except", "UnicodeError", ":", "return", "False", "if", "(", "ref", "==", "hostname", ")", ":", "return", "True", "if", "(", "suffix_match", "and", "hostname", ".", "endswith", "(", "(", "'.'", "+", "ref", ")", ")", ")", ":", "return", "True", "return", "False" ]
checks if a host is trusted against a list .
train
true
13,902
def _get_salt_params(): all_stats = __salt__['status.all_status']() all_grains = __salt__['grains.items']() params = {} try: params['name'] = all_grains['id'] params['hostname'] = all_grains['host'] if (all_grains['kernel'] == 'Darwin'): sd_os = {'code': 'mac', 'name': 'Mac'} else: sd_os = {'code': all_grains['kernel'].lower(), 'name': all_grains['kernel']} params['os'] = json.dumps(sd_os) params['cpuCores'] = all_stats['cpuinfo']['cpu cores'] params['installedRAM'] = str((int(all_stats['meminfo']['MemTotal']['value']) / 1024)) params['swapSpace'] = str((int(all_stats['meminfo']['SwapTotal']['value']) / 1024)) params['privateIPs'] = json.dumps(all_grains['fqdn_ip4']) params['privateDNS'] = json.dumps(all_grains['fqdn']) except KeyError: pass return params
[ "def", "_get_salt_params", "(", ")", ":", "all_stats", "=", "__salt__", "[", "'status.all_status'", "]", "(", ")", "all_grains", "=", "__salt__", "[", "'grains.items'", "]", "(", ")", "params", "=", "{", "}", "try", ":", "params", "[", "'name'", "]", "=", "all_grains", "[", "'id'", "]", "params", "[", "'hostname'", "]", "=", "all_grains", "[", "'host'", "]", "if", "(", "all_grains", "[", "'kernel'", "]", "==", "'Darwin'", ")", ":", "sd_os", "=", "{", "'code'", ":", "'mac'", ",", "'name'", ":", "'Mac'", "}", "else", ":", "sd_os", "=", "{", "'code'", ":", "all_grains", "[", "'kernel'", "]", ".", "lower", "(", ")", ",", "'name'", ":", "all_grains", "[", "'kernel'", "]", "}", "params", "[", "'os'", "]", "=", "json", ".", "dumps", "(", "sd_os", ")", "params", "[", "'cpuCores'", "]", "=", "all_stats", "[", "'cpuinfo'", "]", "[", "'cpu cores'", "]", "params", "[", "'installedRAM'", "]", "=", "str", "(", "(", "int", "(", "all_stats", "[", "'meminfo'", "]", "[", "'MemTotal'", "]", "[", "'value'", "]", ")", "/", "1024", ")", ")", "params", "[", "'swapSpace'", "]", "=", "str", "(", "(", "int", "(", "all_stats", "[", "'meminfo'", "]", "[", "'SwapTotal'", "]", "[", "'value'", "]", ")", "/", "1024", ")", ")", "params", "[", "'privateIPs'", "]", "=", "json", ".", "dumps", "(", "all_grains", "[", "'fqdn_ip4'", "]", ")", "params", "[", "'privateDNS'", "]", "=", "json", ".", "dumps", "(", "all_grains", "[", "'fqdn'", "]", ")", "except", "KeyError", ":", "pass", "return", "params" ]
try to get all sort of parameters for server density server info .
train
false
13,905
def str_split(arr, pat=None, n=None): if (pat is None): if ((n is None) or (n == 0)): n = (-1) f = (lambda x: x.split(pat, n)) elif (len(pat) == 1): if ((n is None) or (n == 0)): n = (-1) f = (lambda x: x.split(pat, n)) else: if ((n is None) or (n == (-1))): n = 0 regex = re.compile(pat) f = (lambda x: regex.split(x, maxsplit=n)) res = _na_map(f, arr) return res
[ "def", "str_split", "(", "arr", ",", "pat", "=", "None", ",", "n", "=", "None", ")", ":", "if", "(", "pat", "is", "None", ")", ":", "if", "(", "(", "n", "is", "None", ")", "or", "(", "n", "==", "0", ")", ")", ":", "n", "=", "(", "-", "1", ")", "f", "=", "(", "lambda", "x", ":", "x", ".", "split", "(", "pat", ",", "n", ")", ")", "elif", "(", "len", "(", "pat", ")", "==", "1", ")", ":", "if", "(", "(", "n", "is", "None", ")", "or", "(", "n", "==", "0", ")", ")", ":", "n", "=", "(", "-", "1", ")", "f", "=", "(", "lambda", "x", ":", "x", ".", "split", "(", "pat", ",", "n", ")", ")", "else", ":", "if", "(", "(", "n", "is", "None", ")", "or", "(", "n", "==", "(", "-", "1", ")", ")", ")", ":", "n", "=", "0", "regex", "=", "re", ".", "compile", "(", "pat", ")", "f", "=", "(", "lambda", "x", ":", "regex", ".", "split", "(", "x", ",", "maxsplit", "=", "n", ")", ")", "res", "=", "_na_map", "(", "f", ",", "arr", ")", "return", "res" ]
split each string in the series/index by given pattern .
train
true
13,908
def heappushpop(heap, item): if (heap and (heap[0] < item)): (item, heap[0]) = (heap[0], item) _siftup(heap, 0) return item
[ "def", "heappushpop", "(", "heap", ",", "item", ")", ":", "if", "(", "heap", "and", "(", "heap", "[", "0", "]", "<", "item", ")", ")", ":", "(", "item", ",", "heap", "[", "0", "]", ")", "=", "(", "heap", "[", "0", "]", ",", "item", ")", "_siftup", "(", "heap", ",", "0", ")", "return", "item" ]
fast version of a heappush followed by a heappop .
train
true
13,909
def mkdir_with_parents(dir_name): pathmembers = dir_name.split(os.sep) tmp_stack = [] while (pathmembers and (not os.path.isdir(deunicodise(os.sep.join(pathmembers))))): tmp_stack.append(pathmembers.pop()) while tmp_stack: pathmembers.append(tmp_stack.pop()) cur_dir = os.sep.join(pathmembers) try: debug(('mkdir(%s)' % cur_dir)) os.mkdir(deunicodise(cur_dir)) except (OSError, IOError) as e: debug(("Can not make directory '%s' (Reason: %s)" % (cur_dir, e.strerror))) return False except Exception as e: debug(("Can not make directory '%s' (Reason: %s)" % (cur_dir, e))) return False return True
[ "def", "mkdir_with_parents", "(", "dir_name", ")", ":", "pathmembers", "=", "dir_name", ".", "split", "(", "os", ".", "sep", ")", "tmp_stack", "=", "[", "]", "while", "(", "pathmembers", "and", "(", "not", "os", ".", "path", ".", "isdir", "(", "deunicodise", "(", "os", ".", "sep", ".", "join", "(", "pathmembers", ")", ")", ")", ")", ")", ":", "tmp_stack", ".", "append", "(", "pathmembers", ".", "pop", "(", ")", ")", "while", "tmp_stack", ":", "pathmembers", ".", "append", "(", "tmp_stack", ".", "pop", "(", ")", ")", "cur_dir", "=", "os", ".", "sep", ".", "join", "(", "pathmembers", ")", "try", ":", "debug", "(", "(", "'mkdir(%s)'", "%", "cur_dir", ")", ")", "os", ".", "mkdir", "(", "deunicodise", "(", "cur_dir", ")", ")", "except", "(", "OSError", ",", "IOError", ")", "as", "e", ":", "debug", "(", "(", "\"Can not make directory '%s' (Reason: %s)\"", "%", "(", "cur_dir", ",", "e", ".", "strerror", ")", ")", ")", "return", "False", "except", "Exception", "as", "e", ":", "debug", "(", "(", "\"Can not make directory '%s' (Reason: %s)\"", "%", "(", "cur_dir", ",", "e", ")", ")", ")", "return", "False", "return", "True" ]
mkdir_with_parents create directory dir_name with all parent directories returns true on success .
train
false
13,910
def create_fake_resource_path(request, resource, child_keys, include_child): if (resource._parent_resource and (resource._parent_resource.name != 'root')): path = create_fake_resource_path(request, resource._parent_resource, child_keys, True) else: path = '/api/' if (resource.name != 'root'): path += ('%s/' % resource.uri_name) if ((not resource.singleton) and include_child and resource.model and resource.uri_object_key): q = resource.get_queryset(request, **child_keys) if (q.count() == 0): logging.critical('Resource "%s" requires objects in the database', resource.__class__) assert (q.count() > 0) obj = q[0] value = getattr(obj, resource.model_object_key) child_keys[resource.uri_object_key] = value path += ('%s/' % value) return path
[ "def", "create_fake_resource_path", "(", "request", ",", "resource", ",", "child_keys", ",", "include_child", ")", ":", "if", "(", "resource", ".", "_parent_resource", "and", "(", "resource", ".", "_parent_resource", ".", "name", "!=", "'root'", ")", ")", ":", "path", "=", "create_fake_resource_path", "(", "request", ",", "resource", ".", "_parent_resource", ",", "child_keys", ",", "True", ")", "else", ":", "path", "=", "'/api/'", "if", "(", "resource", ".", "name", "!=", "'root'", ")", ":", "path", "+=", "(", "'%s/'", "%", "resource", ".", "uri_name", ")", "if", "(", "(", "not", "resource", ".", "singleton", ")", "and", "include_child", "and", "resource", ".", "model", "and", "resource", ".", "uri_object_key", ")", ":", "q", "=", "resource", ".", "get_queryset", "(", "request", ",", "**", "child_keys", ")", "if", "(", "q", ".", "count", "(", ")", "==", "0", ")", ":", "logging", ".", "critical", "(", "'Resource \"%s\" requires objects in the database'", ",", "resource", ".", "__class__", ")", "assert", "(", "q", ".", "count", "(", ")", ">", "0", ")", "obj", "=", "q", "[", "0", "]", "value", "=", "getattr", "(", "obj", ",", "resource", ".", "model_object_key", ")", "child_keys", "[", "resource", ".", "uri_object_key", "]", "=", "value", "path", "+=", "(", "'%s/'", "%", "value", ")", "return", "path" ]
creates a fake path to a resource .
train
false
13,911
def vn_delete(call=None, kwargs=None): if (call != 'function'): raise SaltCloudSystemExit('The vn_delete function must be called with -f or --function.') if (kwargs is None): kwargs = {} name = kwargs.get('name', None) vn_id = kwargs.get('vn_id', None) if vn_id: if name: log.warning("Both the 'vn_id' and 'name' arguments were provided. 'vn_id' will take precedence.") elif name: vn_id = get_vn_id(kwargs={'name': name}) else: raise SaltCloudSystemExit("The vn_delete function requires a 'name' or a 'vn_id' to be provided.") (server, user, password) = _get_xml_rpc() auth = ':'.join([user, password]) response = server.one.vn.delete(auth, int(vn_id)) data = {'action': 'vn.delete', 'deleted': response[0], 'vn_id': response[1], 'error_code': response[2]} return data
[ "def", "vn_delete", "(", "call", "=", "None", ",", "kwargs", "=", "None", ")", ":", "if", "(", "call", "!=", "'function'", ")", ":", "raise", "SaltCloudSystemExit", "(", "'The vn_delete function must be called with -f or --function.'", ")", "if", "(", "kwargs", "is", "None", ")", ":", "kwargs", "=", "{", "}", "name", "=", "kwargs", ".", "get", "(", "'name'", ",", "None", ")", "vn_id", "=", "kwargs", ".", "get", "(", "'vn_id'", ",", "None", ")", "if", "vn_id", ":", "if", "name", ":", "log", ".", "warning", "(", "\"Both the 'vn_id' and 'name' arguments were provided. 'vn_id' will take precedence.\"", ")", "elif", "name", ":", "vn_id", "=", "get_vn_id", "(", "kwargs", "=", "{", "'name'", ":", "name", "}", ")", "else", ":", "raise", "SaltCloudSystemExit", "(", "\"The vn_delete function requires a 'name' or a 'vn_id' to be provided.\"", ")", "(", "server", ",", "user", ",", "password", ")", "=", "_get_xml_rpc", "(", ")", "auth", "=", "':'", ".", "join", "(", "[", "user", ",", "password", "]", ")", "response", "=", "server", ".", "one", ".", "vn", ".", "delete", "(", "auth", ",", "int", "(", "vn_id", ")", ")", "data", "=", "{", "'action'", ":", "'vn.delete'", ",", "'deleted'", ":", "response", "[", "0", "]", ",", "'vn_id'", ":", "response", "[", "1", "]", ",", "'error_code'", ":", "response", "[", "2", "]", "}", "return", "data" ]
deletes the given virtual network from opennebula .
train
true
13,912
def getregentry(): return codecs.CodecInfo(name='hexlify', encode=hex_encode, decode=hex_decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamwriter=StreamWriter, streamreader=StreamReader)
[ "def", "getregentry", "(", ")", ":", "return", "codecs", ".", "CodecInfo", "(", "name", "=", "'hexlify'", ",", "encode", "=", "hex_encode", ",", "decode", "=", "hex_decode", ",", "incrementalencoder", "=", "IncrementalEncoder", ",", "incrementaldecoder", "=", "IncrementalDecoder", ",", "streamwriter", "=", "StreamWriter", ",", "streamreader", "=", "StreamReader", ")" ]
encodings module api .
train
true
13,915
def OSXFindProxies(): sc = objc.SystemConfiguration() settings = sc.dll.SCDynamicStoreCopyProxies(None) if (not settings): return [] try: cf_http_enabled = sc.CFDictRetrieve(settings, 'kSCPropNetProxiesHTTPEnable') if (cf_http_enabled and bool(sc.CFNumToInt32(cf_http_enabled))): cfproxy = sc.CFDictRetrieve(settings, 'kSCPropNetProxiesHTTPProxy') cfport = sc.CFDictRetrieve(settings, 'kSCPropNetProxiesHTTPPort') if (cfproxy and cfport): proxy = sc.CFStringToPystring(cfproxy) port = sc.CFNumToInt32(cfport) return [('http://%s:%d/' % (proxy, port))] cf_auto_enabled = sc.CFDictRetrieve(settings, 'kSCPropNetProxiesProxyAutoConfigEnable') if (cf_auto_enabled and bool(sc.CFNumToInt32(cf_auto_enabled))): cfurl = sc.CFDictRetrieve(settings, 'kSCPropNetProxiesProxyAutoConfigURLString') if cfurl: unused_url = sc.CFStringToPystring(cfurl) return [] finally: sc.dll.CFRelease(settings) return []
[ "def", "OSXFindProxies", "(", ")", ":", "sc", "=", "objc", ".", "SystemConfiguration", "(", ")", "settings", "=", "sc", ".", "dll", ".", "SCDynamicStoreCopyProxies", "(", "None", ")", "if", "(", "not", "settings", ")", ":", "return", "[", "]", "try", ":", "cf_http_enabled", "=", "sc", ".", "CFDictRetrieve", "(", "settings", ",", "'kSCPropNetProxiesHTTPEnable'", ")", "if", "(", "cf_http_enabled", "and", "bool", "(", "sc", ".", "CFNumToInt32", "(", "cf_http_enabled", ")", ")", ")", ":", "cfproxy", "=", "sc", ".", "CFDictRetrieve", "(", "settings", ",", "'kSCPropNetProxiesHTTPProxy'", ")", "cfport", "=", "sc", ".", "CFDictRetrieve", "(", "settings", ",", "'kSCPropNetProxiesHTTPPort'", ")", "if", "(", "cfproxy", "and", "cfport", ")", ":", "proxy", "=", "sc", ".", "CFStringToPystring", "(", "cfproxy", ")", "port", "=", "sc", ".", "CFNumToInt32", "(", "cfport", ")", "return", "[", "(", "'http://%s:%d/'", "%", "(", "proxy", ",", "port", ")", ")", "]", "cf_auto_enabled", "=", "sc", ".", "CFDictRetrieve", "(", "settings", ",", "'kSCPropNetProxiesProxyAutoConfigEnable'", ")", "if", "(", "cf_auto_enabled", "and", "bool", "(", "sc", ".", "CFNumToInt32", "(", "cf_auto_enabled", ")", ")", ")", ":", "cfurl", "=", "sc", ".", "CFDictRetrieve", "(", "settings", ",", "'kSCPropNetProxiesProxyAutoConfigURLString'", ")", "if", "cfurl", ":", "unused_url", "=", "sc", ".", "CFStringToPystring", "(", "cfurl", ")", "return", "[", "]", "finally", ":", "sc", ".", "dll", ".", "CFRelease", "(", "settings", ")", "return", "[", "]" ]
this reads the osx system configuration and gets the proxies .
train
true
13,916
def Md5ForFile(f): md5 = hashlib.md5() if os.path.isfile(f): with open(f, 'rb') as f: for chunk in iter((lambda : f.read((128 * md5.block_size))), ''): md5.update(chunk) else: return '0' return md5.digest()
[ "def", "Md5ForFile", "(", "f", ")", ":", "md5", "=", "hashlib", ".", "md5", "(", ")", "if", "os", ".", "path", ".", "isfile", "(", "f", ")", ":", "with", "open", "(", "f", ",", "'rb'", ")", "as", "f", ":", "for", "chunk", "in", "iter", "(", "(", "lambda", ":", "f", ".", "read", "(", "(", "128", "*", "md5", ".", "block_size", ")", ")", ")", ",", "''", ")", ":", "md5", ".", "update", "(", "chunk", ")", "else", ":", "return", "'0'", "return", "md5", ".", "digest", "(", ")" ]
return an md5 hash of the specified file .
train
false
13,918
def generate_mac_address(): mac = [250, 22, 62, random.randint(0, 127), random.randint(0, 255), random.randint(0, 255)] return ':'.join(map((lambda x: ('%02x' % x)), mac))
[ "def", "generate_mac_address", "(", ")", ":", "mac", "=", "[", "250", ",", "22", ",", "62", ",", "random", ".", "randint", "(", "0", ",", "127", ")", ",", "random", ".", "randint", "(", "0", ",", "255", ")", ",", "random", ".", "randint", "(", "0", ",", "255", ")", "]", "return", "':'", ".", "join", "(", "map", "(", "(", "lambda", "x", ":", "(", "'%02x'", "%", "x", ")", ")", ",", "mac", ")", ")" ]
generate an ethernet mac address .
train
false
13,919
def symptom_password_regular_expression_description_not_set(): return (CONF.security_compliance.password_regex and (not CONF.security_compliance.password_regex_description))
[ "def", "symptom_password_regular_expression_description_not_set", "(", ")", ":", "return", "(", "CONF", ".", "security_compliance", ".", "password_regex", "and", "(", "not", "CONF", ".", "security_compliance", ".", "password_regex_description", ")", ")" ]
password regular expression description is not set .
train
false
13,920
def percentOutputsStableOverNTimeSteps(vectors, numSamples=None): totalSamples = len(vectors) windowSize = numSamples numWindows = 0 pctStable = 0 for wStart in range(0, ((totalSamples - windowSize) + 1)): data = vectors[wStart:(wStart + windowSize)] outputSums = data.sum(axis=0) stableOutputs = (outputSums == windowSize).sum() samplePctStable = (float(stableOutputs) / data[0].sum()) print samplePctStable pctStable += samplePctStable numWindows += 1 return (float(pctStable) / numWindows)
[ "def", "percentOutputsStableOverNTimeSteps", "(", "vectors", ",", "numSamples", "=", "None", ")", ":", "totalSamples", "=", "len", "(", "vectors", ")", "windowSize", "=", "numSamples", "numWindows", "=", "0", "pctStable", "=", "0", "for", "wStart", "in", "range", "(", "0", ",", "(", "(", "totalSamples", "-", "windowSize", ")", "+", "1", ")", ")", ":", "data", "=", "vectors", "[", "wStart", ":", "(", "wStart", "+", "windowSize", ")", "]", "outputSums", "=", "data", ".", "sum", "(", "axis", "=", "0", ")", "stableOutputs", "=", "(", "outputSums", "==", "windowSize", ")", ".", "sum", "(", ")", "samplePctStable", "=", "(", "float", "(", "stableOutputs", ")", "/", "data", "[", "0", "]", ".", "sum", "(", ")", ")", "print", "samplePctStable", "pctStable", "+=", "samplePctStable", "numWindows", "+=", "1", "return", "(", "float", "(", "pctStable", ")", "/", "numWindows", ")" ]
returns the percent of the outputs that remain completely stable over n time steps .
train
true
13,922
def unique_boxes(boxes, scale=1.0): v = np.array([1, 1000.0, 1000000.0, 1000000000.0]) hashes = np.round((boxes * scale)).dot(v) (_, index) = np.unique(hashes, return_index=True) return np.sort(index)
[ "def", "unique_boxes", "(", "boxes", ",", "scale", "=", "1.0", ")", ":", "v", "=", "np", ".", "array", "(", "[", "1", ",", "1000.0", ",", "1000000.0", ",", "1000000000.0", "]", ")", "hashes", "=", "np", ".", "round", "(", "(", "boxes", "*", "scale", ")", ")", ".", "dot", "(", "v", ")", "(", "_", ",", "index", ")", "=", "np", ".", "unique", "(", "hashes", ",", "return_index", "=", "True", ")", "return", "np", ".", "sort", "(", "index", ")" ]
return indices of unique boxes .
train
false
13,923
def keyring_save(**kwargs): return ceph_cfg.keyring_save(**kwargs)
[ "def", "keyring_save", "(", "**", "kwargs", ")", ":", "return", "ceph_cfg", ".", "keyring_save", "(", "**", "kwargs", ")" ]
create save keyring locally cli example: .
train
false
13,925
def minimum(image, selem, out=None, mask=None, shift_x=False, shift_y=False): return _apply_scalar_per_pixel(generic_cy._minimum, image, selem, out=out, mask=mask, shift_x=shift_x, shift_y=shift_y)
[ "def", "minimum", "(", "image", ",", "selem", ",", "out", "=", "None", ",", "mask", "=", "None", ",", "shift_x", "=", "False", ",", "shift_y", "=", "False", ")", ":", "return", "_apply_scalar_per_pixel", "(", "generic_cy", ".", "_minimum", ",", "image", ",", "selem", ",", "out", "=", "out", ",", "mask", "=", "mask", ",", "shift_x", "=", "shift_x", ",", "shift_y", "=", "shift_y", ")" ]
element-wise minimum of two tensors .
train
false
13,926
def AddFileToFileStore(pathspec=None, client_id=None, token=None): if (pathspec is None): raise ValueError("pathspec can't be None") if (client_id is None): raise ValueError("client_id can't be None") urn = aff4_grr.VFSGRRClient.PathspecToURN(pathspec, client_id) client_mock = action_mocks.GetFileClientMock() for _ in test_lib.TestFlowHelper(transfer.GetFile.__name__, client_mock, token=token, client_id=client_id, pathspec=pathspec): pass auth_state = rdf_flows.GrrMessage.AuthorizationState.AUTHENTICATED events.Events.PublishEvent('FileStore.AddFileToStore', rdf_flows.GrrMessage(payload=urn, auth_state=auth_state), token=token) worker = test_lib.MockWorker(token=token) worker.Simulate() return urn
[ "def", "AddFileToFileStore", "(", "pathspec", "=", "None", ",", "client_id", "=", "None", ",", "token", "=", "None", ")", ":", "if", "(", "pathspec", "is", "None", ")", ":", "raise", "ValueError", "(", "\"pathspec can't be None\"", ")", "if", "(", "client_id", "is", "None", ")", ":", "raise", "ValueError", "(", "\"client_id can't be None\"", ")", "urn", "=", "aff4_grr", ".", "VFSGRRClient", ".", "PathspecToURN", "(", "pathspec", ",", "client_id", ")", "client_mock", "=", "action_mocks", ".", "GetFileClientMock", "(", ")", "for", "_", "in", "test_lib", ".", "TestFlowHelper", "(", "transfer", ".", "GetFile", ".", "__name__", ",", "client_mock", ",", "token", "=", "token", ",", "client_id", "=", "client_id", ",", "pathspec", "=", "pathspec", ")", ":", "pass", "auth_state", "=", "rdf_flows", ".", "GrrMessage", ".", "AuthorizationState", ".", "AUTHENTICATED", "events", ".", "Events", ".", "PublishEvent", "(", "'FileStore.AddFileToStore'", ",", "rdf_flows", ".", "GrrMessage", "(", "payload", "=", "urn", ",", "auth_state", "=", "auth_state", ")", ",", "token", "=", "token", ")", "worker", "=", "test_lib", ".", "MockWorker", "(", "token", "=", "token", ")", "worker", ".", "Simulate", "(", ")", "return", "urn" ]
adds file with given pathspec to the hash file store .
train
false
13,927
def hashDBRetrieve(key, unserialize=False, checkConf=False): _ = ('%s%s%s' % ((conf.url or ('%s%s' % (conf.hostname, conf.port))), key, HASHDB_MILESTONE_VALUE)) retVal = (conf.hashDB.retrieve(_, unserialize) if (kb.resumeValues and (not (checkConf and any((conf.flushSession, conf.freshQueries))))) else None) if ((not kb.inferenceMode) and (not kb.fileReadMode) and any(((_ in (retVal or '')) for _ in (PARTIAL_VALUE_MARKER, PARTIAL_HEX_VALUE_MARKER)))): retVal = None return retVal
[ "def", "hashDBRetrieve", "(", "key", ",", "unserialize", "=", "False", ",", "checkConf", "=", "False", ")", ":", "_", "=", "(", "'%s%s%s'", "%", "(", "(", "conf", ".", "url", "or", "(", "'%s%s'", "%", "(", "conf", ".", "hostname", ",", "conf", ".", "port", ")", ")", ")", ",", "key", ",", "HASHDB_MILESTONE_VALUE", ")", ")", "retVal", "=", "(", "conf", ".", "hashDB", ".", "retrieve", "(", "_", ",", "unserialize", ")", "if", "(", "kb", ".", "resumeValues", "and", "(", "not", "(", "checkConf", "and", "any", "(", "(", "conf", ".", "flushSession", ",", "conf", ".", "freshQueries", ")", ")", ")", ")", ")", "else", "None", ")", "if", "(", "(", "not", "kb", ".", "inferenceMode", ")", "and", "(", "not", "kb", ".", "fileReadMode", ")", "and", "any", "(", "(", "(", "_", "in", "(", "retVal", "or", "''", ")", ")", "for", "_", "in", "(", "PARTIAL_VALUE_MARKER", ",", "PARTIAL_HEX_VALUE_MARKER", ")", ")", ")", ")", ":", "retVal", "=", "None", "return", "retVal" ]
helper function for restoring session data from hashdb .
train
false
13,929
def h5_cost_data(filename, epoch_axis=True): ret = list() with h5py.File(filename, 'r') as f: (config, cost, time_markers) = [f[x] for x in ['config', 'cost', 'time_markers']] total_epochs = config.attrs['total_epochs'] total_minibatches = config.attrs['total_minibatches'] minibatch_markers = time_markers['minibatch'] for (name, ydata) in cost.items(): y = ydata[...] if (ydata.attrs['time_markers'] == 'epoch_freq'): y_epoch_freq = ydata.attrs['epoch_freq'] assert (len(y) == (total_epochs // y_epoch_freq)) x = create_epoch_x(len(y), y_epoch_freq, minibatch_markers, epoch_axis) elif (ydata.attrs['time_markers'] == 'minibatch'): assert (len(y) == total_minibatches) x = create_minibatch_x(total_minibatches, minibatch_markers, epoch_axis) else: raise TypeError('Unsupported data format for h5_cost_data') ret.append((name, x, y)) return ret
[ "def", "h5_cost_data", "(", "filename", ",", "epoch_axis", "=", "True", ")", ":", "ret", "=", "list", "(", ")", "with", "h5py", ".", "File", "(", "filename", ",", "'r'", ")", "as", "f", ":", "(", "config", ",", "cost", ",", "time_markers", ")", "=", "[", "f", "[", "x", "]", "for", "x", "in", "[", "'config'", ",", "'cost'", ",", "'time_markers'", "]", "]", "total_epochs", "=", "config", ".", "attrs", "[", "'total_epochs'", "]", "total_minibatches", "=", "config", ".", "attrs", "[", "'total_minibatches'", "]", "minibatch_markers", "=", "time_markers", "[", "'minibatch'", "]", "for", "(", "name", ",", "ydata", ")", "in", "cost", ".", "items", "(", ")", ":", "y", "=", "ydata", "[", "...", "]", "if", "(", "ydata", ".", "attrs", "[", "'time_markers'", "]", "==", "'epoch_freq'", ")", ":", "y_epoch_freq", "=", "ydata", ".", "attrs", "[", "'epoch_freq'", "]", "assert", "(", "len", "(", "y", ")", "==", "(", "total_epochs", "//", "y_epoch_freq", ")", ")", "x", "=", "create_epoch_x", "(", "len", "(", "y", ")", ",", "y_epoch_freq", ",", "minibatch_markers", ",", "epoch_axis", ")", "elif", "(", "ydata", ".", "attrs", "[", "'time_markers'", "]", "==", "'minibatch'", ")", ":", "assert", "(", "len", "(", "y", ")", "==", "total_minibatches", ")", "x", "=", "create_minibatch_x", "(", "total_minibatches", ",", "minibatch_markers", ",", "epoch_axis", ")", "else", ":", "raise", "TypeError", "(", "'Unsupported data format for h5_cost_data'", ")", "ret", ".", "append", "(", "(", "name", ",", "x", ",", "y", ")", ")", "return", "ret" ]
read cost data from hdf5 file .
train
false
13,930
def attachRequest(PTmsiSignature_presence=0, GprsTimer_presence=0, TmsiStatus_presence=0): a = TpPd(pd=3) b = MessageType(mesType=1) c = MsNetworkCapability() d = AttachTypeAndCiphKeySeqNr() f = DrxParameter() g = MobileId() h = RoutingAreaIdentification() i = MsRadioAccessCapability() packet = (((((((a / b) / c) / d) / f) / g) / h) / i) if (PTmsiSignature_presence is 1): j = PTmsiSignature(ieiPTS=25) packet = (packet / j) if (GprsTimer_presence is 1): k = GprsTimer(ieiGT=23) packet = (packet / k) if (TmsiStatus_presence is 1): l = TmsiStatus(ieiTS=9) packet = (packet / l) return packet
[ "def", "attachRequest", "(", "PTmsiSignature_presence", "=", "0", ",", "GprsTimer_presence", "=", "0", ",", "TmsiStatus_presence", "=", "0", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "3", ")", "b", "=", "MessageType", "(", "mesType", "=", "1", ")", "c", "=", "MsNetworkCapability", "(", ")", "d", "=", "AttachTypeAndCiphKeySeqNr", "(", ")", "f", "=", "DrxParameter", "(", ")", "g", "=", "MobileId", "(", ")", "h", "=", "RoutingAreaIdentification", "(", ")", "i", "=", "MsRadioAccessCapability", "(", ")", "packet", "=", "(", "(", "(", "(", "(", "(", "(", "a", "/", "b", ")", "/", "c", ")", "/", "d", ")", "/", "f", ")", "/", "g", ")", "/", "h", ")", "/", "i", ")", "if", "(", "PTmsiSignature_presence", "is", "1", ")", ":", "j", "=", "PTmsiSignature", "(", "ieiPTS", "=", "25", ")", "packet", "=", "(", "packet", "/", "j", ")", "if", "(", "GprsTimer_presence", "is", "1", ")", ":", "k", "=", "GprsTimer", "(", "ieiGT", "=", "23", ")", "packet", "=", "(", "packet", "/", "k", ")", "if", "(", "TmsiStatus_presence", "is", "1", ")", ":", "l", "=", "TmsiStatus", "(", "ieiTS", "=", "9", ")", "packet", "=", "(", "packet", "/", "l", ")", "return", "packet" ]
attach request section 9 .
train
true
13,931
def _get_offset(cmd): dict_offset = cmd.dictionary_page_offset data_offset = cmd.data_page_offset if ((dict_offset is None) or (data_offset < dict_offset)): return data_offset return dict_offset
[ "def", "_get_offset", "(", "cmd", ")", ":", "dict_offset", "=", "cmd", ".", "dictionary_page_offset", "data_offset", "=", "cmd", ".", "data_page_offset", "if", "(", "(", "dict_offset", "is", "None", ")", "or", "(", "data_offset", "<", "dict_offset", ")", ")", ":", "return", "data_offset", "return", "dict_offset" ]
return the offset into the cmd based upon if its a dictionary page or a data page .
train
true
13,932
def check_run_and_monitor(command, echo=True, input=None): result = run_and_monitor(command, echo=echo, input=input) if (result.returncode != 0): error = 'FAILED {command} with exit code {code}\n{err}'.format(command=command, code=result.returncode, err=result.stderr.strip()) sys.stderr.write((error + '\n')) raise RuntimeError(error) return result
[ "def", "check_run_and_monitor", "(", "command", ",", "echo", "=", "True", ",", "input", "=", "None", ")", ":", "result", "=", "run_and_monitor", "(", "command", ",", "echo", "=", "echo", ",", "input", "=", "input", ")", "if", "(", "result", ".", "returncode", "!=", "0", ")", ":", "error", "=", "'FAILED {command} with exit code {code}\\n{err}'", ".", "format", "(", "command", "=", "command", ",", "code", "=", "result", ".", "returncode", ",", "err", "=", "result", ".", "stderr", ".", "strip", "(", ")", ")", "sys", ".", "stderr", ".", "write", "(", "(", "error", "+", "'\\n'", ")", ")", "raise", "RuntimeError", "(", "error", ")", "return", "result" ]
runs the command in a subshell and throws an exception if it fails .
train
false
13,933
def create_service_check(check_name, status, tags=None, timestamp=None, hostname=None, check_run_id=None, message=None): if (check_run_id is None): check_run_id = get_next_id('service_check') return {'id': check_run_id, 'check': check_name, 'status': status, 'host_name': hostname, 'tags': tags, 'timestamp': float((timestamp or time.time())), 'message': message}
[ "def", "create_service_check", "(", "check_name", ",", "status", ",", "tags", "=", "None", ",", "timestamp", "=", "None", ",", "hostname", "=", "None", ",", "check_run_id", "=", "None", ",", "message", "=", "None", ")", ":", "if", "(", "check_run_id", "is", "None", ")", ":", "check_run_id", "=", "get_next_id", "(", "'service_check'", ")", "return", "{", "'id'", ":", "check_run_id", ",", "'check'", ":", "check_name", ",", "'status'", ":", "status", ",", "'host_name'", ":", "hostname", ",", "'tags'", ":", "tags", ",", "'timestamp'", ":", "float", "(", "(", "timestamp", "or", "time", ".", "time", "(", ")", ")", ")", ",", "'message'", ":", "message", "}" ]
create a service_check dict .
train
false
13,934
def widont_html(value): def replace(matchobj): return (u'%s&nbsp;%s%s' % matchobj.groups()) return re_widont_html.sub(replace, force_unicode(value))
[ "def", "widont_html", "(", "value", ")", ":", "def", "replace", "(", "matchobj", ")", ":", "return", "(", "u'%s&nbsp;%s%s'", "%", "matchobj", ".", "groups", "(", ")", ")", "return", "re_widont_html", ".", "sub", "(", "replace", ",", "force_unicode", "(", "value", ")", ")" ]
adds an html non-breaking space between the final two words at the end of block level tags to avoid "widowed" words .
train
false
13,936
def apply_gmail_label_rules(db_session, message, added_categories, removed_categories): add = {} discard = {} categories = {c.name: c for c in message.categories if c.name} for cat in added_categories: if (cat.name == 'all'): discard = {'trash', 'spam'} elif (cat.name == 'trash'): discard = {'all', 'spam', 'inbox'} elif (cat.name == 'spam'): discard = {'all', 'trash', 'inbox'} elif (cat.name == 'inbox'): add = {'all'} discard = {'trash', 'spam'} for name in add: if (name not in categories): category = db_session.query(Category).filter((Category.namespace_id == message.namespace_id), (Category.name == name)).one() message.categories.add(category) for name in discard: if (name in categories): message.categories.discard(categories[name])
[ "def", "apply_gmail_label_rules", "(", "db_session", ",", "message", ",", "added_categories", ",", "removed_categories", ")", ":", "add", "=", "{", "}", "discard", "=", "{", "}", "categories", "=", "{", "c", ".", "name", ":", "c", "for", "c", "in", "message", ".", "categories", "if", "c", ".", "name", "}", "for", "cat", "in", "added_categories", ":", "if", "(", "cat", ".", "name", "==", "'all'", ")", ":", "discard", "=", "{", "'trash'", ",", "'spam'", "}", "elif", "(", "cat", ".", "name", "==", "'trash'", ")", ":", "discard", "=", "{", "'all'", ",", "'spam'", ",", "'inbox'", "}", "elif", "(", "cat", ".", "name", "==", "'spam'", ")", ":", "discard", "=", "{", "'all'", ",", "'trash'", ",", "'inbox'", "}", "elif", "(", "cat", ".", "name", "==", "'inbox'", ")", ":", "add", "=", "{", "'all'", "}", "discard", "=", "{", "'trash'", ",", "'spam'", "}", "for", "name", "in", "add", ":", "if", "(", "name", "not", "in", "categories", ")", ":", "category", "=", "db_session", ".", "query", "(", "Category", ")", ".", "filter", "(", "(", "Category", ".", "namespace_id", "==", "message", ".", "namespace_id", ")", ",", "(", "Category", ".", "name", "==", "name", ")", ")", ".", "one", "(", ")", "message", ".", "categories", ".", "add", "(", "category", ")", "for", "name", "in", "discard", ":", "if", "(", "name", "in", "categories", ")", ":", "message", ".", "categories", ".", "discard", "(", "categories", "[", "name", "]", ")" ]
the api optimistically updates message .
train
false
13,937
def aggregate_file_tree_metadata(addon_short_name, fileobj_metadata, user): disk_usage = fileobj_metadata.get('size') if (fileobj_metadata['kind'] == 'file'): result = StatResult(target_name=fileobj_metadata['name'], target_id=fileobj_metadata['path'].lstrip('/'), disk_usage=(disk_usage or 0)) return result else: return AggregateStatResult(target_id=fileobj_metadata['path'].lstrip('/'), target_name=fileobj_metadata['name'], targets=[aggregate_file_tree_metadata(addon_short_name, child, user) for child in fileobj_metadata.get('children', [])])
[ "def", "aggregate_file_tree_metadata", "(", "addon_short_name", ",", "fileobj_metadata", ",", "user", ")", ":", "disk_usage", "=", "fileobj_metadata", ".", "get", "(", "'size'", ")", "if", "(", "fileobj_metadata", "[", "'kind'", "]", "==", "'file'", ")", ":", "result", "=", "StatResult", "(", "target_name", "=", "fileobj_metadata", "[", "'name'", "]", ",", "target_id", "=", "fileobj_metadata", "[", "'path'", "]", ".", "lstrip", "(", "'/'", ")", ",", "disk_usage", "=", "(", "disk_usage", "or", "0", ")", ")", "return", "result", "else", ":", "return", "AggregateStatResult", "(", "target_id", "=", "fileobj_metadata", "[", "'path'", "]", ".", "lstrip", "(", "'/'", ")", ",", "target_name", "=", "fileobj_metadata", "[", "'name'", "]", ",", "targets", "=", "[", "aggregate_file_tree_metadata", "(", "addon_short_name", ",", "child", ",", "user", ")", "for", "child", "in", "fileobj_metadata", ".", "get", "(", "'children'", ",", "[", "]", ")", "]", ")" ]
recursively traverse the addons file tree and collect metadata in aggregatestatresult .
train
false
13,938
def add_extra_model_fields(sender, **kwargs): model_key = (sender._meta.app_label, sender._meta.model_name) for (field_name, field) in fields.get(model_key, {}): field.contribute_to_class(sender, field_name)
[ "def", "add_extra_model_fields", "(", "sender", ",", "**", "kwargs", ")", ":", "model_key", "=", "(", "sender", ".", "_meta", ".", "app_label", ",", "sender", ".", "_meta", ".", "model_name", ")", "for", "(", "field_name", ",", "field", ")", "in", "fields", ".", "get", "(", "model_key", ",", "{", "}", ")", ":", "field", ".", "contribute_to_class", "(", "sender", ",", "field_name", ")" ]
injects custom fields onto the given sender model as defined by the extra_model_fields setting .
train
true
13,939
def gtkformat_factory(format, colnum): if (format is None): return None format = copy.copy(format) format.xalign = 0.0 format.cell = None def negative_red_cell(column, cell, model, thisiter): val = model.get_value(thisiter, colnum) try: val = float(val) except: cell.set_property(u'foreground', u'black') else: if (val < 0): cell.set_property(u'foreground', u'red') else: cell.set_property(u'foreground', u'black') if (isinstance(format, mlab.FormatFloat) or isinstance(format, mlab.FormatInt)): format.cell = negative_red_cell format.xalign = 1.0 elif isinstance(format, mlab.FormatDate): format.xalign = 1.0 return format
[ "def", "gtkformat_factory", "(", "format", ",", "colnum", ")", ":", "if", "(", "format", "is", "None", ")", ":", "return", "None", "format", "=", "copy", ".", "copy", "(", "format", ")", "format", ".", "xalign", "=", "0.0", "format", ".", "cell", "=", "None", "def", "negative_red_cell", "(", "column", ",", "cell", ",", "model", ",", "thisiter", ")", ":", "val", "=", "model", ".", "get_value", "(", "thisiter", ",", "colnum", ")", "try", ":", "val", "=", "float", "(", "val", ")", "except", ":", "cell", ".", "set_property", "(", "u'foreground'", ",", "u'black'", ")", "else", ":", "if", "(", "val", "<", "0", ")", ":", "cell", ".", "set_property", "(", "u'foreground'", ",", "u'red'", ")", "else", ":", "cell", ".", "set_property", "(", "u'foreground'", ",", "u'black'", ")", "if", "(", "isinstance", "(", "format", ",", "mlab", ".", "FormatFloat", ")", "or", "isinstance", "(", "format", ",", "mlab", ".", "FormatInt", ")", ")", ":", "format", ".", "cell", "=", "negative_red_cell", "format", ".", "xalign", "=", "1.0", "elif", "isinstance", "(", "format", ",", "mlab", ".", "FormatDate", ")", ":", "format", ".", "xalign", "=", "1.0", "return", "format" ]
copy the format .
train
false
13,940
def vm_virt_type(domain): ret = __salt__['vmadm.lookup'](search='uuid={uuid}'.format(uuid=domain), order='type') if (len(ret) < 1): raise CommandExecutionError("We can't determine the type of this VM") return ret[0]['type']
[ "def", "vm_virt_type", "(", "domain", ")", ":", "ret", "=", "__salt__", "[", "'vmadm.lookup'", "]", "(", "search", "=", "'uuid={uuid}'", ".", "format", "(", "uuid", "=", "domain", ")", ",", "order", "=", "'type'", ")", "if", "(", "len", "(", "ret", ")", "<", "1", ")", ":", "raise", "CommandExecutionError", "(", "\"We can't determine the type of this VM\"", ")", "return", "ret", "[", "0", "]", "[", "'type'", "]" ]
return vm virtualization type : os or kvm cli example: .
train
true