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
14,628
def connection_teardown_request(error=None): try: CLIENT_POOL.release() except ClientPool.ExtraneousReleaseError: if (not settings.DEBUG_MODE): raise
[ "def", "connection_teardown_request", "(", "error", "=", "None", ")", ":", "try", ":", "CLIENT_POOL", ".", "release", "(", ")", "except", "ClientPool", ".", "ExtraneousReleaseError", ":", "if", "(", "not", "settings", ".", "DEBUG_MODE", ")", ":", "raise" ]
release the mongodb client back into the pool .
train
false
14,629
def curve3_bezier(p1, p2, p3): (x1, y1) = p1 (x2, y2) = p2 (x3, y3) = p3 points = [] _curve3_recursive_bezier(points, x1, y1, x2, y2, x3, y3) (dx, dy) = ((points[0][0] - x1), (points[0][1] - y1)) if (((dx * dx) + (dy * dy)) > 1e-10): points.insert(0, (x1, y1)) (dx, dy) = ((points[(-1)][0] - x3), (points[(-1)][1] - y3)) if (((dx * dx) + (dy * dy)) > 1e-10): points.append((x3, y3)) return np.array(points).reshape(len(points), 2)
[ "def", "curve3_bezier", "(", "p1", ",", "p2", ",", "p3", ")", ":", "(", "x1", ",", "y1", ")", "=", "p1", "(", "x2", ",", "y2", ")", "=", "p2", "(", "x3", ",", "y3", ")", "=", "p3", "points", "=", "[", "]", "_curve3_recursive_bezier", "(", "points", ",", "x1", ",", "y1", ",", "x2", ",", "y2", ",", "x3", ",", "y3", ")", "(", "dx", ",", "dy", ")", "=", "(", "(", "points", "[", "0", "]", "[", "0", "]", "-", "x1", ")", ",", "(", "points", "[", "0", "]", "[", "1", "]", "-", "y1", ")", ")", "if", "(", "(", "(", "dx", "*", "dx", ")", "+", "(", "dy", "*", "dy", ")", ")", ">", "1e-10", ")", ":", "points", ".", "insert", "(", "0", ",", "(", "x1", ",", "y1", ")", ")", "(", "dx", ",", "dy", ")", "=", "(", "(", "points", "[", "(", "-", "1", ")", "]", "[", "0", "]", "-", "x3", ")", ",", "(", "points", "[", "(", "-", "1", ")", "]", "[", "1", "]", "-", "y3", ")", ")", "if", "(", "(", "(", "dx", "*", "dx", ")", "+", "(", "dy", "*", "dy", ")", ")", ">", "1e-10", ")", ":", "points", ".", "append", "(", "(", "x3", ",", "y3", ")", ")", "return", "np", ".", "array", "(", "points", ")", ".", "reshape", "(", "len", "(", "points", ")", ",", "2", ")" ]
generate the vertices for a quadratic bezier curve .
train
true
14,630
def _extract_translatable_qweb_terms(element, callback): for el in element: if isinstance(el, SKIPPED_ELEMENT_TYPES): continue if ((el.tag.lower() not in SKIPPED_ELEMENTS) and ('t-js' not in el.attrib) and (not (('t-jquery' in el.attrib) and ('t-operation' not in el.attrib))) and (el.get('t-translation', '').strip() != 'off')): _push(callback, el.text, el.sourceline) for att in ('title', 'alt', 'label', 'placeholder'): if (att in el.attrib): _push(callback, el.attrib[att], el.sourceline) _extract_translatable_qweb_terms(el, callback) _push(callback, el.tail, el.sourceline)
[ "def", "_extract_translatable_qweb_terms", "(", "element", ",", "callback", ")", ":", "for", "el", "in", "element", ":", "if", "isinstance", "(", "el", ",", "SKIPPED_ELEMENT_TYPES", ")", ":", "continue", "if", "(", "(", "el", ".", "tag", ".", "lower", "(", ")", "not", "in", "SKIPPED_ELEMENTS", ")", "and", "(", "'t-js'", "not", "in", "el", ".", "attrib", ")", "and", "(", "not", "(", "(", "'t-jquery'", "in", "el", ".", "attrib", ")", "and", "(", "'t-operation'", "not", "in", "el", ".", "attrib", ")", ")", ")", "and", "(", "el", ".", "get", "(", "'t-translation'", ",", "''", ")", ".", "strip", "(", ")", "!=", "'off'", ")", ")", ":", "_push", "(", "callback", ",", "el", ".", "text", ",", "el", ".", "sourceline", ")", "for", "att", "in", "(", "'title'", ",", "'alt'", ",", "'label'", ",", "'placeholder'", ")", ":", "if", "(", "att", "in", "el", ".", "attrib", ")", ":", "_push", "(", "callback", ",", "el", ".", "attrib", "[", "att", "]", ",", "el", ".", "sourceline", ")", "_extract_translatable_qweb_terms", "(", "el", ",", "callback", ")", "_push", "(", "callback", ",", "el", ".", "tail", ",", "el", ".", "sourceline", ")" ]
helper method to walk an etree document representing a qweb template .
train
false
14,633
def moveAndSymlinkFile(srcFile, destFile): try: moveFile(srcFile, destFile) symlink(destFile, srcFile) except Exception as error: logger.log(u'Failed to create symlink of {0} at {1}. Error: {2}. Copying instead'.format(srcFile, destFile, error), logger.WARNING) copyFile(srcFile, destFile)
[ "def", "moveAndSymlinkFile", "(", "srcFile", ",", "destFile", ")", ":", "try", ":", "moveFile", "(", "srcFile", ",", "destFile", ")", "symlink", "(", "destFile", ",", "srcFile", ")", "except", "Exception", "as", "error", ":", "logger", ".", "log", "(", "u'Failed to create symlink of {0} at {1}. Error: {2}. Copying instead'", ".", "format", "(", "srcFile", ",", "destFile", ",", "error", ")", ",", "logger", ".", "WARNING", ")", "copyFile", "(", "srcFile", ",", "destFile", ")" ]
move a file from source to destination .
train
false
14,636
def find_closing_tag(tag, max_tags=sys.maxint): if tag.self_closing: return None stack = [] (block, offset) = (tag.end_block, tag.end_offset) while (block.isValid() and (max_tags > 0)): (block, tag_start) = next_tag_boundary(block, offset) if ((block is None) or (not tag_start.is_start)): break (endblock, tag_end) = next_tag_boundary(block, tag_start.offset) if ((endblock is None) or tag_end.is_start): break if tag_start.closing: try: (prefix, name) = stack.pop() except IndexError: prefix = name = None if ((prefix, name) != (tag_start.prefix, tag_start.name)): return Tag(block, tag_start, endblock, tag_end) elif tag_end.self_closing: pass else: stack.append((tag_start.prefix, tag_start.name)) (block, offset) = (endblock, tag_end.offset) max_tags -= 1 return None
[ "def", "find_closing_tag", "(", "tag", ",", "max_tags", "=", "sys", ".", "maxint", ")", ":", "if", "tag", ".", "self_closing", ":", "return", "None", "stack", "=", "[", "]", "(", "block", ",", "offset", ")", "=", "(", "tag", ".", "end_block", ",", "tag", ".", "end_offset", ")", "while", "(", "block", ".", "isValid", "(", ")", "and", "(", "max_tags", ">", "0", ")", ")", ":", "(", "block", ",", "tag_start", ")", "=", "next_tag_boundary", "(", "block", ",", "offset", ")", "if", "(", "(", "block", "is", "None", ")", "or", "(", "not", "tag_start", ".", "is_start", ")", ")", ":", "break", "(", "endblock", ",", "tag_end", ")", "=", "next_tag_boundary", "(", "block", ",", "tag_start", ".", "offset", ")", "if", "(", "(", "endblock", "is", "None", ")", "or", "tag_end", ".", "is_start", ")", ":", "break", "if", "tag_start", ".", "closing", ":", "try", ":", "(", "prefix", ",", "name", ")", "=", "stack", ".", "pop", "(", ")", "except", "IndexError", ":", "prefix", "=", "name", "=", "None", "if", "(", "(", "prefix", ",", "name", ")", "!=", "(", "tag_start", ".", "prefix", ",", "tag_start", ".", "name", ")", ")", ":", "return", "Tag", "(", "block", ",", "tag_start", ",", "endblock", ",", "tag_end", ")", "elif", "tag_end", ".", "self_closing", ":", "pass", "else", ":", "stack", ".", "append", "(", "(", "tag_start", ".", "prefix", ",", "tag_start", ".", "name", ")", ")", "(", "block", ",", "offset", ")", "=", "(", "endblock", ",", "tag_end", ".", "offset", ")", "max_tags", "-=", "1", "return", "None" ]
find the closing tag corresponding to the specified tag .
train
false
14,639
def default_expire_time(): expire_delta = datetime.timedelta(seconds=CONF.token.expiration) return (timeutils.utcnow() + expire_delta)
[ "def", "default_expire_time", "(", ")", ":", "expire_delta", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "CONF", ".", "token", ".", "expiration", ")", "return", "(", "timeutils", ".", "utcnow", "(", ")", "+", "expire_delta", ")" ]
determine when a fresh token should expire .
train
false
14,640
@pytest.fixture def tp0(language0, project0): from pootle_translationproject.models import TranslationProject return TranslationProject.objects.get(language=language0, project=project0)
[ "@", "pytest", ".", "fixture", "def", "tp0", "(", "language0", ",", "project0", ")", ":", "from", "pootle_translationproject", ".", "models", "import", "TranslationProject", "return", "TranslationProject", ".", "objects", ".", "get", "(", "language", "=", "language0", ",", "project", "=", "project0", ")" ]
require english project0 .
train
false
14,641
@public def sqf_list(f, *gens, **args): return _generic_factor_list(f, gens, args, method='sqf')
[ "@", "public", "def", "sqf_list", "(", "f", ",", "*", "gens", ",", "**", "args", ")", ":", "return", "_generic_factor_list", "(", "f", ",", "gens", ",", "args", ",", "method", "=", "'sqf'", ")" ]
compute a list of square-free factors of f .
train
false
14,642
def re_encrypt(ciphertext_blob, destination_key_id, source_encryption_context=None, destination_encryption_context=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: ciphertext = conn.re_encrypt(ciphertext_blob, destination_key_id, source_encryption_context, destination_encryption_context, grant_tokens) r['ciphertext'] = ciphertext except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r
[ "def", "re_encrypt", "(", "ciphertext_blob", ",", "destination_key_id", ",", "source_encryption_context", "=", "None", ",", "destination_encryption_context", "=", "None", ",", "grant_tokens", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "=", "keyid", ",", "profile", "=", "profile", ")", "r", "=", "{", "}", "try", ":", "ciphertext", "=", "conn", ".", "re_encrypt", "(", "ciphertext_blob", ",", "destination_key_id", ",", "source_encryption_context", ",", "destination_encryption_context", ",", "grant_tokens", ")", "r", "[", "'ciphertext'", "]", "=", "ciphertext", "except", "boto", ".", "exception", ".", "BotoServerError", "as", "e", ":", "r", "[", "'error'", "]", "=", "__utils__", "[", "'boto.get_error'", "]", "(", "e", ")", "return", "r" ]
reencrypt encrypted data with a new master key .
train
true
14,643
def get_alarms(deployment_id, profile='telemetry'): auth = _auth(profile=profile) try: response = requests.get((_get_telemetry_base(profile) + '/alerts?deployment={0}'.format(deployment_id)), headers=auth) except requests.exceptions.RequestException as e: log.error(str(e)) return False if (response.status_code == 200): alarms = response.json() if (len(alarms) > 0): return alarms return 'No alarms defined for deployment: {0}'.format(deployment_id) else: return {'err_code': response.status_code, 'err_msg': json.loads(response.text).get('err', '')}
[ "def", "get_alarms", "(", "deployment_id", ",", "profile", "=", "'telemetry'", ")", ":", "auth", "=", "_auth", "(", "profile", "=", "profile", ")", "try", ":", "response", "=", "requests", ".", "get", "(", "(", "_get_telemetry_base", "(", "profile", ")", "+", "'/alerts?deployment={0}'", ".", "format", "(", "deployment_id", ")", ")", ",", "headers", "=", "auth", ")", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "e", ":", "log", ".", "error", "(", "str", "(", "e", ")", ")", "return", "False", "if", "(", "response", ".", "status_code", "==", "200", ")", ":", "alarms", "=", "response", ".", "json", "(", ")", "if", "(", "len", "(", "alarms", ")", ">", "0", ")", ":", "return", "alarms", "return", "'No alarms defined for deployment: {0}'", ".", "format", "(", "deployment_id", ")", "else", ":", "return", "{", "'err_code'", ":", "response", ".", "status_code", ",", "'err_msg'", ":", "json", ".", "loads", "(", "response", ".", "text", ")", ".", "get", "(", "'err'", ",", "''", ")", "}" ]
get all the alarms set up against the current deployment returns dictionary of alarm information cli example: salt myminion telemetry .
train
false
14,644
def _clear_host_from_gpu(inputs): clean_inputs = [] for inp in inputs: if _owner_isinstance(inp, HostFromGpu): clean_inputs.append(inp.owner.inputs[0]) else: clean_inputs.append(inp) return clean_inputs
[ "def", "_clear_host_from_gpu", "(", "inputs", ")", ":", "clean_inputs", "=", "[", "]", "for", "inp", "in", "inputs", ":", "if", "_owner_isinstance", "(", "inp", ",", "HostFromGpu", ")", ":", "clean_inputs", ".", "append", "(", "inp", ".", "owner", ".", "inputs", "[", "0", "]", ")", "else", ":", "clean_inputs", ".", "append", "(", "inp", ")", "return", "clean_inputs" ]
replace any hostfromgpu by its input .
train
false
14,645
def list_users(profile=None, api_key=None): return salt.utils.pagerduty.list_items('users', 'id', __salt__['config.option'](profile), api_key, opts=__opts__)
[ "def", "list_users", "(", "profile", "=", "None", ",", "api_key", "=", "None", ")", ":", "return", "salt", ".", "utils", ".", "pagerduty", ".", "list_items", "(", "'users'", ",", "'id'", ",", "__salt__", "[", "'config.option'", "]", "(", "profile", ")", ",", "api_key", ",", "opts", "=", "__opts__", ")" ]
list all users within the organization .
train
true
14,646
def test_no_truncate_crval_try2(): w = wcs.WCS(naxis=3) w.wcs.crval = [50, 50, 212345678000.0] w.wcs.cdelt = [1e-05, 1e-05, 100000.0] w.wcs.ctype = [u'RA---SIN', u'DEC--SIN', u'FREQ'] w.wcs.cunit = [u'deg', u'deg', u'Hz'] w.wcs.crpix = [1, 1, 1] w.wcs.restfrq = 234000000000.0 w.wcs.set() header = w.to_header() for ii in range(3): assert (header[u'CRVAL{0}'.format((ii + 1))] == w.wcs.crval[ii]) assert (header[u'CDELT{0}'.format((ii + 1))] == w.wcs.cdelt[ii])
[ "def", "test_no_truncate_crval_try2", "(", ")", ":", "w", "=", "wcs", ".", "WCS", "(", "naxis", "=", "3", ")", "w", ".", "wcs", ".", "crval", "=", "[", "50", ",", "50", ",", "212345678000.0", "]", "w", ".", "wcs", ".", "cdelt", "=", "[", "1e-05", ",", "1e-05", ",", "100000.0", "]", "w", ".", "wcs", ".", "ctype", "=", "[", "u'RA---SIN'", ",", "u'DEC--SIN'", ",", "u'FREQ'", "]", "w", ".", "wcs", ".", "cunit", "=", "[", "u'deg'", ",", "u'deg'", ",", "u'Hz'", "]", "w", ".", "wcs", ".", "crpix", "=", "[", "1", ",", "1", ",", "1", "]", "w", ".", "wcs", ".", "restfrq", "=", "234000000000.0", "w", ".", "wcs", ".", "set", "(", ")", "header", "=", "w", ".", "to_header", "(", ")", "for", "ii", "in", "range", "(", "3", ")", ":", "assert", "(", "header", "[", "u'CRVAL{0}'", ".", "format", "(", "(", "ii", "+", "1", ")", ")", "]", "==", "w", ".", "wcs", ".", "crval", "[", "ii", "]", ")", "assert", "(", "header", "[", "u'CDELT{0}'", ".", "format", "(", "(", "ii", "+", "1", ")", ")", "]", "==", "w", ".", "wcs", ".", "cdelt", "[", "ii", "]", ")" ]
regression test for URL .
train
false
14,647
def test_training_a_model(): dim = 3 m = 10 rng = np.random.RandomState([22, 4, 2014]) X = rng.randn(m, dim) ds = csr_matrix(X) dataset = SparseDataset(from_scipy_sparse_dataset=ds) model = SoftmaxModel(dim) learning_rate = 0.1 batch_size = 5 epoch_num = 2 termination_criterion = EpochCounter(epoch_num) cost = DummyCost() algorithm = SGD(learning_rate, cost, batch_size=batch_size, termination_criterion=termination_criterion, update_callbacks=None, set_batch_size=False) train = Train(dataset, model, algorithm, save_path=None, save_freq=0, extensions=None) train.main_loop()
[ "def", "test_training_a_model", "(", ")", ":", "dim", "=", "3", "m", "=", "10", "rng", "=", "np", ".", "random", ".", "RandomState", "(", "[", "22", ",", "4", ",", "2014", "]", ")", "X", "=", "rng", ".", "randn", "(", "m", ",", "dim", ")", "ds", "=", "csr_matrix", "(", "X", ")", "dataset", "=", "SparseDataset", "(", "from_scipy_sparse_dataset", "=", "ds", ")", "model", "=", "SoftmaxModel", "(", "dim", ")", "learning_rate", "=", "0.1", "batch_size", "=", "5", "epoch_num", "=", "2", "termination_criterion", "=", "EpochCounter", "(", "epoch_num", ")", "cost", "=", "DummyCost", "(", ")", "algorithm", "=", "SGD", "(", "learning_rate", ",", "cost", ",", "batch_size", "=", "batch_size", ",", "termination_criterion", "=", "termination_criterion", ",", "update_callbacks", "=", "None", ",", "set_batch_size", "=", "False", ")", "train", "=", "Train", "(", "dataset", ",", "model", ",", "algorithm", ",", "save_path", "=", "None", ",", "save_freq", "=", "0", ",", "extensions", "=", "None", ")", "train", ".", "main_loop", "(", ")" ]
tests wether sparsedataset can be trained with a dummy model .
train
false
14,649
def getLastRequestHTTPError(): threadData = getCurrentThreadData() return (threadData.lastHTTPError[1] if threadData.lastHTTPError else None)
[ "def", "getLastRequestHTTPError", "(", ")", ":", "threadData", "=", "getCurrentThreadData", "(", ")", "return", "(", "threadData", ".", "lastHTTPError", "[", "1", "]", "if", "threadData", ".", "lastHTTPError", "else", "None", ")" ]
returns last http error code .
train
false
14,650
@register.assignment_tag(takes_context=True) def render_template_for(context, obj, template=None, template_directory=None): context['object'] = obj template_list = [] if template: template_list.append(template) template_dirs = [] if template_directory: template_dirs.append(template_directory) template_dirs.append('community/types') for directory in template_dirs: template_list.append('{}/{}.html'.format(directory, obj.get_media_type_display())) template_list.append('{}/default.html'.format(directory)) output = render_to_string(template_list, context) return output
[ "@", "register", ".", "assignment_tag", "(", "takes_context", "=", "True", ")", "def", "render_template_for", "(", "context", ",", "obj", ",", "template", "=", "None", ",", "template_directory", "=", "None", ")", ":", "context", "[", "'object'", "]", "=", "obj", "template_list", "=", "[", "]", "if", "template", ":", "template_list", ".", "append", "(", "template", ")", "template_dirs", "=", "[", "]", "if", "template_directory", ":", "template_dirs", ".", "append", "(", "template_directory", ")", "template_dirs", ".", "append", "(", "'community/types'", ")", "for", "directory", "in", "template_dirs", ":", "template_list", ".", "append", "(", "'{}/{}.html'", ".", "format", "(", "directory", ",", "obj", ".", "get_media_type_display", "(", ")", ")", ")", "template_list", ".", "append", "(", "'{}/default.html'", ".", "format", "(", "directory", ")", ")", "output", "=", "render_to_string", "(", "template_list", ",", "context", ")", "return", "output" ]
renders a template based on the media_type of the given object in the given template directory .
train
false
14,652
def bool_from_string(subject): if isinstance(subject, bool): return subject elif isinstance(subject, int): return (subject == 1) if hasattr(subject, 'startswith'): if (subject.strip().lower() in ('true', 'on', '1', 'yes', 'y')): return True return False
[ "def", "bool_from_string", "(", "subject", ")", ":", "if", "isinstance", "(", "subject", ",", "bool", ")", ":", "return", "subject", "elif", "isinstance", "(", "subject", ",", "int", ")", ":", "return", "(", "subject", "==", "1", ")", "if", "hasattr", "(", "subject", ",", "'startswith'", ")", ":", "if", "(", "subject", ".", "strip", "(", ")", ".", "lower", "(", ")", "in", "(", "'true'", ",", "'on'", ",", "'1'", ",", "'yes'", ",", "'y'", ")", ")", ":", "return", "True", "return", "False" ]
interpret a string as a boolean .
train
false
14,653
def extract_constant(x, elemwise=True, only_process_constants=False): try: x = get_scalar_constant_value(x, elemwise, only_process_constants) except NotScalarConstantError: pass if (isinstance(x, scal.ScalarVariable) or isinstance(x, scal.sharedvar.ScalarSharedVariable)): if (x.owner and isinstance(x.owner.op, ScalarFromTensor)): x = x.owner.inputs[0] else: x = tensor_from_scalar(x) return x
[ "def", "extract_constant", "(", "x", ",", "elemwise", "=", "True", ",", "only_process_constants", "=", "False", ")", ":", "try", ":", "x", "=", "get_scalar_constant_value", "(", "x", ",", "elemwise", ",", "only_process_constants", ")", "except", "NotScalarConstantError", ":", "pass", "if", "(", "isinstance", "(", "x", ",", "scal", ".", "ScalarVariable", ")", "or", "isinstance", "(", "x", ",", "scal", ".", "sharedvar", ".", "ScalarSharedVariable", ")", ")", ":", "if", "(", "x", ".", "owner", "and", "isinstance", "(", "x", ".", "owner", ".", "op", ",", "ScalarFromTensor", ")", ")", ":", "x", "=", "x", ".", "owner", ".", "inputs", "[", "0", "]", "else", ":", "x", "=", "tensor_from_scalar", "(", "x", ")", "return", "x" ]
extract the constant value of symbol from code if the name symbol is bound to a constant value by the python code object code .
train
false
14,654
def _extract_tomcat_version(tomcat_version_out): match = re.search('Server version: (.*)', tomcat_version_out) if (match is None): return None match_version = match.group(1).split('/')[1].strip() return match_version
[ "def", "_extract_tomcat_version", "(", "tomcat_version_out", ")", ":", "match", "=", "re", ".", "search", "(", "'Server version: (.*)'", ",", "tomcat_version_out", ")", "if", "(", "match", "is", "None", ")", ":", "return", "None", "match_version", "=", "match", ".", "group", "(", "1", ")", ".", "split", "(", "'/'", ")", "[", "1", "]", ".", "strip", "(", ")", "return", "match_version" ]
extracts tomcat version in format like 7 .
train
false
14,659
def test_ast_good_except(): can_compile(u'(try 1 (except))') can_compile(u'(try 1 (except []))') can_compile(u'(try 1 (except [Foobar]))') can_compile(u'(try 1 (except [[]]))') can_compile(u'(try 1 (except [x FooBar]))') can_compile(u'(try 1 (except [x [FooBar BarFoo]]))') can_compile(u'(try 1 (except [x [FooBar BarFoo]]))')
[ "def", "test_ast_good_except", "(", ")", ":", "can_compile", "(", "u'(try 1 (except))'", ")", "can_compile", "(", "u'(try 1 (except []))'", ")", "can_compile", "(", "u'(try 1 (except [Foobar]))'", ")", "can_compile", "(", "u'(try 1 (except [[]]))'", ")", "can_compile", "(", "u'(try 1 (except [x FooBar]))'", ")", "can_compile", "(", "u'(try 1 (except [x [FooBar BarFoo]]))'", ")", "can_compile", "(", "u'(try 1 (except [x [FooBar BarFoo]]))'", ")" ]
make sure ast can compile valid except .
train
false
14,660
def rgw_destroy(**kwargs): return ceph_cfg.rgw_destroy(**kwargs)
[ "def", "rgw_destroy", "(", "**", "kwargs", ")", ":", "return", "ceph_cfg", ".", "rgw_destroy", "(", "**", "kwargs", ")" ]
remove a rgw cli example: .
train
false
14,661
def null_javascript_catalog(request, domain=None, packages=None): return http.HttpResponse((NullSource + InterPolate), 'text/javascript')
[ "def", "null_javascript_catalog", "(", "request", ",", "domain", "=", "None", ",", "packages", "=", "None", ")", ":", "return", "http", ".", "HttpResponse", "(", "(", "NullSource", "+", "InterPolate", ")", ",", "'text/javascript'", ")" ]
returns "identity" versions of the javascript i18n functions -- i .
train
false
14,662
def axlabel(xlabel, ylabel, **kwargs): ax = plt.gca() ax.set_xlabel(xlabel, **kwargs) ax.set_ylabel(ylabel, **kwargs)
[ "def", "axlabel", "(", "xlabel", ",", "ylabel", ",", "**", "kwargs", ")", ":", "ax", "=", "plt", ".", "gca", "(", ")", "ax", ".", "set_xlabel", "(", "xlabel", ",", "**", "kwargs", ")", "ax", ".", "set_ylabel", "(", "ylabel", ",", "**", "kwargs", ")" ]
grab current axis and label it .
train
false
14,664
def _resolve_datacenter(dc, pillarenv): log.debug('Resolving Consul datacenter based on: %s', dc) try: mappings = dc.items() except AttributeError: log.debug("Using pre-defined DC: '%s'", dc) return dc log.debug('Selecting DC based on pillarenv using %d pattern(s)', len(mappings)) log.debug("Pillarenv set to '%s'", pillarenv) sorted_mappings = sorted(mappings, key=(lambda m: ((- len(m[0])), m[0]))) for (pattern, target) in sorted_mappings: match = re.match(pattern, pillarenv) if match: log.debug("Matched pattern: '%s'", pattern) result = target.format(**match.groupdict()) log.debug("Resolved datacenter: '%s'", result) return result log.debug('None of following patterns matched pillarenv=%s: %s', pillarenv, ', '.join((repr(x) for x in mappings)))
[ "def", "_resolve_datacenter", "(", "dc", ",", "pillarenv", ")", ":", "log", ".", "debug", "(", "'Resolving Consul datacenter based on: %s'", ",", "dc", ")", "try", ":", "mappings", "=", "dc", ".", "items", "(", ")", "except", "AttributeError", ":", "log", ".", "debug", "(", "\"Using pre-defined DC: '%s'\"", ",", "dc", ")", "return", "dc", "log", ".", "debug", "(", "'Selecting DC based on pillarenv using %d pattern(s)'", ",", "len", "(", "mappings", ")", ")", "log", ".", "debug", "(", "\"Pillarenv set to '%s'\"", ",", "pillarenv", ")", "sorted_mappings", "=", "sorted", "(", "mappings", ",", "key", "=", "(", "lambda", "m", ":", "(", "(", "-", "len", "(", "m", "[", "0", "]", ")", ")", ",", "m", "[", "0", "]", ")", ")", ")", "for", "(", "pattern", ",", "target", ")", "in", "sorted_mappings", ":", "match", "=", "re", ".", "match", "(", "pattern", ",", "pillarenv", ")", "if", "match", ":", "log", ".", "debug", "(", "\"Matched pattern: '%s'\"", ",", "pattern", ")", "result", "=", "target", ".", "format", "(", "**", "match", ".", "groupdict", "(", ")", ")", "log", ".", "debug", "(", "\"Resolved datacenter: '%s'\"", ",", "result", ")", "return", "result", "log", ".", "debug", "(", "'None of following patterns matched pillarenv=%s: %s'", ",", "pillarenv", ",", "', '", ".", "join", "(", "(", "repr", "(", "x", ")", "for", "x", "in", "mappings", ")", ")", ")" ]
if dc is a string - return it as is .
train
true
14,666
def is_discussion_enabled(course_id): return settings.FEATURES.get('ENABLE_DISCUSSION_SERVICE')
[ "def", "is_discussion_enabled", "(", "course_id", ")", ":", "return", "settings", ".", "FEATURES", ".", "get", "(", "'ENABLE_DISCUSSION_SERVICE'", ")" ]
return true if discussions are enabled; else false .
train
false
14,667
def dense_gnm_random_graph(n, m, seed=None): mmax = ((n * (n - 1)) / 2) if (m >= mmax): G = complete_graph(n) else: G = empty_graph(n) G.name = ('dense_gnm_random_graph(%s,%s)' % (n, m)) if ((n == 1) or (m >= mmax)): return G if (seed is not None): random.seed(seed) u = 0 v = 1 t = 0 k = 0 while True: if (random.randrange((mmax - t)) < (m - k)): G.add_edge(u, v) k += 1 if (k == m): return G t += 1 v += 1 if (v == n): u += 1 v = (u + 1)
[ "def", "dense_gnm_random_graph", "(", "n", ",", "m", ",", "seed", "=", "None", ")", ":", "mmax", "=", "(", "(", "n", "*", "(", "n", "-", "1", ")", ")", "/", "2", ")", "if", "(", "m", ">=", "mmax", ")", ":", "G", "=", "complete_graph", "(", "n", ")", "else", ":", "G", "=", "empty_graph", "(", "n", ")", "G", ".", "name", "=", "(", "'dense_gnm_random_graph(%s,%s)'", "%", "(", "n", ",", "m", ")", ")", "if", "(", "(", "n", "==", "1", ")", "or", "(", "m", ">=", "mmax", ")", ")", ":", "return", "G", "if", "(", "seed", "is", "not", "None", ")", ":", "random", ".", "seed", "(", "seed", ")", "u", "=", "0", "v", "=", "1", "t", "=", "0", "k", "=", "0", "while", "True", ":", "if", "(", "random", ".", "randrange", "(", "(", "mmax", "-", "t", ")", ")", "<", "(", "m", "-", "k", ")", ")", ":", "G", ".", "add_edge", "(", "u", ",", "v", ")", "k", "+=", "1", "if", "(", "k", "==", "m", ")", ":", "return", "G", "t", "+=", "1", "v", "+=", "1", "if", "(", "v", "==", "n", ")", ":", "u", "+=", "1", "v", "=", "(", "u", "+", "1", ")" ]
returns a g_{n .
train
false
14,668
def runtime(format=False): runtime = (SERVER_RUNTIME + (time() - SERVER_RUNTIME_LAST_UPDATED)) if format: return _format(runtime, 31536000, 2628000, 604800, 86400, 3600, 60) return runtime
[ "def", "runtime", "(", "format", "=", "False", ")", ":", "runtime", "=", "(", "SERVER_RUNTIME", "+", "(", "time", "(", ")", "-", "SERVER_RUNTIME_LAST_UPDATED", ")", ")", "if", "format", ":", "return", "_format", "(", "runtime", ",", "31536000", ",", "2628000", ",", "604800", ",", "86400", ",", "3600", ",", "60", ")", "return", "runtime" ]
get a location for runtime data .
train
false
14,669
def get_routes(iface): path = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'route-{0}'.format(iface)) path6 = os.path.join(_RH_NETWORK_SCRIPT_DIR, 'route6-{0}'.format(iface)) routes = _read_file(path) routes.extend(_read_file(path6)) return routes
[ "def", "get_routes", "(", "iface", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "_RH_NETWORK_SCRIPT_DIR", ",", "'route-{0}'", ".", "format", "(", "iface", ")", ")", "path6", "=", "os", ".", "path", ".", "join", "(", "_RH_NETWORK_SCRIPT_DIR", ",", "'route6-{0}'", ".", "format", "(", "iface", ")", ")", "routes", "=", "_read_file", "(", "path", ")", "routes", ".", "extend", "(", "_read_file", "(", "path6", ")", ")", "return", "routes" ]
return the current routing table cli examples: .
train
true
14,671
def _retrieve_info(server): info = GetServerParms(server.host, server.port) if (info is None): server.bad_cons += server.threads else: server.bad_cons = 0 (server.info, server.request) = (info, False) sabnzbd.downloader.Downloader.do.wakeup()
[ "def", "_retrieve_info", "(", "server", ")", ":", "info", "=", "GetServerParms", "(", "server", ".", "host", ",", "server", ".", "port", ")", "if", "(", "info", "is", "None", ")", ":", "server", ".", "bad_cons", "+=", "server", ".", "threads", "else", ":", "server", ".", "bad_cons", "=", "0", "(", "server", ".", "info", ",", "server", ".", "request", ")", "=", "(", "info", ",", "False", ")", "sabnzbd", ".", "downloader", ".", "Downloader", ".", "do", ".", "wakeup", "(", ")" ]
async attempt to run getaddrinfo() for specified server .
train
false
14,673
def add_background_image(fig, im, set_ratios=None): if (im is None): return None if (set_ratios is not None): for ax in fig.axes: ax.set_aspect(set_ratios) ax_im = fig.add_axes([0, 0, 1, 1], label='background') ax_im.imshow(im, aspect='auto') ax_im.set_zorder((-1)) return ax_im
[ "def", "add_background_image", "(", "fig", ",", "im", ",", "set_ratios", "=", "None", ")", ":", "if", "(", "im", "is", "None", ")", ":", "return", "None", "if", "(", "set_ratios", "is", "not", "None", ")", ":", "for", "ax", "in", "fig", ".", "axes", ":", "ax", ".", "set_aspect", "(", "set_ratios", ")", "ax_im", "=", "fig", ".", "add_axes", "(", "[", "0", ",", "0", ",", "1", ",", "1", "]", ",", "label", "=", "'background'", ")", "ax_im", ".", "imshow", "(", "im", ",", "aspect", "=", "'auto'", ")", "ax_im", ".", "set_zorder", "(", "(", "-", "1", ")", ")", "return", "ax_im" ]
add a background image to a plot .
train
false
14,676
def _read_file(folder, filename): path = os.path.join(folder, filename) try: with salt.utils.fopen(path, 'rb') as contents: return contents.readlines() except (OSError, IOError): return ''
[ "def", "_read_file", "(", "folder", ",", "filename", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "folder", ",", "filename", ")", "try", ":", "with", "salt", ".", "utils", ".", "fopen", "(", "path", ",", "'rb'", ")", "as", "contents", ":", "return", "contents", ".", "readlines", "(", ")", "except", "(", "OSError", ",", "IOError", ")", ":", "return", "''" ]
reads and returns the contents of a file .
train
true
14,677
def percentileofscore(a, score, kind='rank'): a = np.array(a) n = len(a) if (kind == 'rank'): if (not np.any((a == score))): a = np.append(a, score) a_len = np.array(lrange(len(a))) else: a_len = (np.array(lrange(len(a))) + 1.0) a = np.sort(a) idx = [(a == score)] pct = ((np.mean(a_len[idx]) / n) * 100.0) return pct elif (kind == 'strict'): return ((sum((a < score)) / float(n)) * 100) elif (kind == 'weak'): return ((sum((a <= score)) / float(n)) * 100) elif (kind == 'mean'): return (((sum((a < score)) + sum((a <= score))) * 50) / float(n)) else: raise ValueError("kind can only be 'rank', 'strict', 'weak' or 'mean'")
[ "def", "percentileofscore", "(", "a", ",", "score", ",", "kind", "=", "'rank'", ")", ":", "a", "=", "np", ".", "array", "(", "a", ")", "n", "=", "len", "(", "a", ")", "if", "(", "kind", "==", "'rank'", ")", ":", "if", "(", "not", "np", ".", "any", "(", "(", "a", "==", "score", ")", ")", ")", ":", "a", "=", "np", ".", "append", "(", "a", ",", "score", ")", "a_len", "=", "np", ".", "array", "(", "lrange", "(", "len", "(", "a", ")", ")", ")", "else", ":", "a_len", "=", "(", "np", ".", "array", "(", "lrange", "(", "len", "(", "a", ")", ")", ")", "+", "1.0", ")", "a", "=", "np", ".", "sort", "(", "a", ")", "idx", "=", "[", "(", "a", "==", "score", ")", "]", "pct", "=", "(", "(", "np", ".", "mean", "(", "a_len", "[", "idx", "]", ")", "/", "n", ")", "*", "100.0", ")", "return", "pct", "elif", "(", "kind", "==", "'strict'", ")", ":", "return", "(", "(", "sum", "(", "(", "a", "<", "score", ")", ")", "/", "float", "(", "n", ")", ")", "*", "100", ")", "elif", "(", "kind", "==", "'weak'", ")", ":", "return", "(", "(", "sum", "(", "(", "a", "<=", "score", ")", ")", "/", "float", "(", "n", ")", ")", "*", "100", ")", "elif", "(", "kind", "==", "'mean'", ")", ":", "return", "(", "(", "(", "sum", "(", "(", "a", "<", "score", ")", ")", "+", "sum", "(", "(", "a", "<=", "score", ")", ")", ")", "*", "50", ")", "/", "float", "(", "n", ")", ")", "else", ":", "raise", "ValueError", "(", "\"kind can only be 'rank', 'strict', 'weak' or 'mean'\"", ")" ]
return the percentile-position of score relative to data .
train
false
14,679
def demo_vader_instance(text): from nltk.sentiment import SentimentIntensityAnalyzer vader_analyzer = SentimentIntensityAnalyzer() print vader_analyzer.polarity_scores(text)
[ "def", "demo_vader_instance", "(", "text", ")", ":", "from", "nltk", ".", "sentiment", "import", "SentimentIntensityAnalyzer", "vader_analyzer", "=", "SentimentIntensityAnalyzer", "(", ")", "print", "vader_analyzer", ".", "polarity_scores", "(", "text", ")" ]
output polarity scores for a text using vader approach .
train
false
14,680
def clean_modules(): for module in list(sys.modules.keys()): if ('seaborn' in module): del sys.modules[module] plt.rcdefaults()
[ "def", "clean_modules", "(", ")", ":", "for", "module", "in", "list", "(", "sys", ".", "modules", ".", "keys", "(", ")", ")", ":", "if", "(", "'seaborn'", "in", "module", ")", ":", "del", "sys", ".", "modules", "[", "module", "]", "plt", ".", "rcdefaults", "(", ")" ]
remove "unload" seaborn from the name space after a script is executed it can load a variety of setting that one does not want to influence in other examples in the gallery .
train
false
14,681
def _check_to_text(self, in_string, encoding, expected): self.assertEqual(to_text(in_string, encoding), expected)
[ "def", "_check_to_text", "(", "self", ",", "in_string", ",", "encoding", ",", "expected", ")", ":", "self", ".", "assertEqual", "(", "to_text", "(", "in_string", ",", "encoding", ")", ",", "expected", ")" ]
test happy path of decoding to text .
train
false
14,684
def console_delete(context, console_id): return IMPL.console_delete(context, console_id)
[ "def", "console_delete", "(", "context", ",", "console_id", ")", ":", "return", "IMPL", ".", "console_delete", "(", "context", ",", "console_id", ")" ]
delete a console .
train
false
14,685
def load_file(filename, maxbytes=_unspecified): filename = _path_string(filename) if (maxbytes is _unspecified): maxbytes = (-1) elif (not isinstance(maxbytes, int)): raise TypeError('maxbytes must be an integer') return _lib.RAND_load_file(filename, maxbytes)
[ "def", "load_file", "(", "filename", ",", "maxbytes", "=", "_unspecified", ")", ":", "filename", "=", "_path_string", "(", "filename", ")", "if", "(", "maxbytes", "is", "_unspecified", ")", ":", "maxbytes", "=", "(", "-", "1", ")", "elif", "(", "not", "isinstance", "(", "maxbytes", ",", "int", ")", ")", ":", "raise", "TypeError", "(", "'maxbytes must be an integer'", ")", "return", "_lib", ".", "RAND_load_file", "(", "filename", ",", "maxbytes", ")" ]
opens filename with encoding and return its contents .
train
false
14,686
def _check_same_ip_to_multiple_host(config): ips_to_hostnames_mapping = dict() for (key, value) in config.iteritems(): if key.endswith('hosts'): for (_key, _value) in value.iteritems(): hostname = _key ip = _value['ip'] if (not (ip in ips_to_hostnames_mapping)): ips_to_hostnames_mapping[ip] = hostname elif (ips_to_hostnames_mapping[ip] != hostname): info = (ip, ips_to_hostnames_mapping[ip], hostname) raise MultipleHostsWithOneIPError(*info) logger.debug('No hosts with duplicated IPs found')
[ "def", "_check_same_ip_to_multiple_host", "(", "config", ")", ":", "ips_to_hostnames_mapping", "=", "dict", "(", ")", "for", "(", "key", ",", "value", ")", "in", "config", ".", "iteritems", "(", ")", ":", "if", "key", ".", "endswith", "(", "'hosts'", ")", ":", "for", "(", "_key", ",", "_value", ")", "in", "value", ".", "iteritems", "(", ")", ":", "hostname", "=", "_key", "ip", "=", "_value", "[", "'ip'", "]", "if", "(", "not", "(", "ip", "in", "ips_to_hostnames_mapping", ")", ")", ":", "ips_to_hostnames_mapping", "[", "ip", "]", "=", "hostname", "elif", "(", "ips_to_hostnames_mapping", "[", "ip", "]", "!=", "hostname", ")", ":", "info", "=", "(", "ip", ",", "ips_to_hostnames_mapping", "[", "ip", "]", ",", "hostname", ")", "raise", "MultipleHostsWithOneIPError", "(", "*", "info", ")", "logger", ".", "debug", "(", "'No hosts with duplicated IPs found'", ")" ]
check for ips assigned to multiple hosts : param: config: dict user provided configuration .
train
false
14,688
def _replace_datalayout(llvmir): lines = llvmir.splitlines() for (i, ln) in enumerate(lines): if ln.startswith('target datalayout'): tmp = 'target datalayout = "{0}"' lines[i] = tmp.format(default_data_layout) break return '\n'.join(lines)
[ "def", "_replace_datalayout", "(", "llvmir", ")", ":", "lines", "=", "llvmir", ".", "splitlines", "(", ")", "for", "(", "i", ",", "ln", ")", "in", "enumerate", "(", "lines", ")", ":", "if", "ln", ".", "startswith", "(", "'target datalayout'", ")", ":", "tmp", "=", "'target datalayout = \"{0}\"'", "lines", "[", "i", "]", "=", "tmp", ".", "format", "(", "default_data_layout", ")", "break", "return", "'\\n'", ".", "join", "(", "lines", ")" ]
find the line containing the datalayout and replace it .
train
false
14,690
@pytest.fixture def Fred(default_groups): fred = User(username='Fred', email='fred@fred.fred', password='fred', primary_group=default_groups[3], activated=True) fred.save() return fred
[ "@", "pytest", ".", "fixture", "def", "Fred", "(", "default_groups", ")", ":", "fred", "=", "User", "(", "username", "=", "'Fred'", ",", "email", "=", "'fred@fred.fred'", ",", "password", "=", "'fred'", ",", "primary_group", "=", "default_groups", "[", "3", "]", ",", "activated", "=", "True", ")", "fred", ".", "save", "(", ")", "return", "fred" ]
fred is an interloper and bad intentioned user .
train
false
14,692
def mkdtemp_clean(suffix='', prefix='tmp', dir=None): the_dir = tempfile.mkdtemp(suffix=suffix, prefix=prefix, dir=dir) atexit.register(cleanup_tempdir, the_dir) return the_dir
[ "def", "mkdtemp_clean", "(", "suffix", "=", "''", ",", "prefix", "=", "'tmp'", ",", "dir", "=", "None", ")", ":", "the_dir", "=", "tempfile", ".", "mkdtemp", "(", "suffix", "=", "suffix", ",", "prefix", "=", "prefix", ",", "dir", "=", "dir", ")", "atexit", ".", "register", "(", "cleanup_tempdir", ",", "the_dir", ")", "return", "the_dir" ]
just like mkdtemp .
train
false
14,693
@requires_segment_info def current_line(pl, segment_info): return str(segment_info[u'curframe'].f_lineno)
[ "@", "requires_segment_info", "def", "current_line", "(", "pl", ",", "segment_info", ")", ":", "return", "str", "(", "segment_info", "[", "u'curframe'", "]", ".", "f_lineno", ")" ]
displays line number that is next to be run .
train
false
14,694
def check_driver_dependencies(driver, dependencies): ret = True for (key, value) in six.iteritems(dependencies): if (value is False): log.warning("Missing dependency: '{0}'. The {1} driver requires '{0}' to be installed.".format(key, driver)) ret = False return ret
[ "def", "check_driver_dependencies", "(", "driver", ",", "dependencies", ")", ":", "ret", "=", "True", "for", "(", "key", ",", "value", ")", "in", "six", ".", "iteritems", "(", "dependencies", ")", ":", "if", "(", "value", "is", "False", ")", ":", "log", ".", "warning", "(", "\"Missing dependency: '{0}'. The {1} driver requires '{0}' to be installed.\"", ".", "format", "(", "key", ",", "driver", ")", ")", "ret", "=", "False", "return", "ret" ]
check if the drivers dependencies are available .
train
true
14,695
def _ellipsis_match(want, got): if (ELLIPSIS_MARKER not in want): return (want == got) ws = want.split(ELLIPSIS_MARKER) assert (len(ws) >= 2) (startpos, endpos) = (0, len(got)) w = ws[0] if w: if got.startswith(w): startpos = len(w) del ws[0] else: return False w = ws[(-1)] if w: if got.endswith(w): endpos -= len(w) del ws[(-1)] else: return False if (startpos > endpos): return False for w in ws: startpos = got.find(w, startpos, endpos) if (startpos < 0): return False startpos += len(w) return True
[ "def", "_ellipsis_match", "(", "want", ",", "got", ")", ":", "if", "(", "ELLIPSIS_MARKER", "not", "in", "want", ")", ":", "return", "(", "want", "==", "got", ")", "ws", "=", "want", ".", "split", "(", "ELLIPSIS_MARKER", ")", "assert", "(", "len", "(", "ws", ")", ">=", "2", ")", "(", "startpos", ",", "endpos", ")", "=", "(", "0", ",", "len", "(", "got", ")", ")", "w", "=", "ws", "[", "0", "]", "if", "w", ":", "if", "got", ".", "startswith", "(", "w", ")", ":", "startpos", "=", "len", "(", "w", ")", "del", "ws", "[", "0", "]", "else", ":", "return", "False", "w", "=", "ws", "[", "(", "-", "1", ")", "]", "if", "w", ":", "if", "got", ".", "endswith", "(", "w", ")", ":", "endpos", "-=", "len", "(", "w", ")", "del", "ws", "[", "(", "-", "1", ")", "]", "else", ":", "return", "False", "if", "(", "startpos", ">", "endpos", ")", ":", "return", "False", "for", "w", "in", "ws", ":", "startpos", "=", "got", ".", "find", "(", "w", ",", "startpos", ",", "endpos", ")", "if", "(", "startpos", "<", "0", ")", ":", "return", "False", "startpos", "+=", "len", "(", "w", ")", "return", "True" ]
essentially the only subtle case: .
train
true
14,697
def store_hdmi_to_file_config_set(kodi_setting, all_settings): kodi_setting = hdmi_safe_group_removal(kodi_setting, all_settings) if (kodi_setting == 'true'): return ('1', '1') else: return ('remove_this_line', 'remove_this_line')
[ "def", "store_hdmi_to_file_config_set", "(", "kodi_setting", ",", "all_settings", ")", ":", "kodi_setting", "=", "hdmi_safe_group_removal", "(", "kodi_setting", ",", "all_settings", ")", "if", "(", "kodi_setting", "==", "'true'", ")", ":", "return", "(", "'1'", ",", "'1'", ")", "else", ":", "return", "(", "'remove_this_line'", ",", "'remove_this_line'", ")" ]
hdmi_force_hotplug=%s hdmi_edid_file=%s .
train
false
14,698
def normalize_rgb_colors_to_hex(css): regex = re.compile('rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)') match = regex.search(css) while match: colors = map((lambda s: s.strip()), match.group(1).split(',')) hexcolor = ('#%.2x%.2x%.2x' % tuple(map(int, colors))) css = css.replace(match.group(), hexcolor) match = regex.search(css) return css
[ "def", "normalize_rgb_colors_to_hex", "(", "css", ")", ":", "regex", "=", "re", ".", "compile", "(", "'rgb\\\\s*\\\\(\\\\s*([0-9,\\\\s]+)\\\\s*\\\\)'", ")", "match", "=", "regex", ".", "search", "(", "css", ")", "while", "match", ":", "colors", "=", "map", "(", "(", "lambda", "s", ":", "s", ".", "strip", "(", ")", ")", ",", "match", ".", "group", "(", "1", ")", ".", "split", "(", "','", ")", ")", "hexcolor", "=", "(", "'#%.2x%.2x%.2x'", "%", "tuple", "(", "map", "(", "int", ",", "colors", ")", ")", ")", "css", "=", "css", ".", "replace", "(", "match", ".", "group", "(", ")", ",", "hexcolor", ")", "match", "=", "regex", ".", "search", "(", "css", ")", "return", "css" ]
convert rgb to #336699 .
train
true
14,699
def getAttributesString(attributes): attributesString = '' attributesKeys = attributes.keys() attributesKeys.sort(compareAttributeKeyAscending) for attributesKey in attributesKeys: valueString = str(attributes[attributesKey]) if ("'" in valueString): attributesString += (' %s="%s"' % (attributesKey, valueString)) else: attributesString += (" %s='%s'" % (attributesKey, valueString)) return attributesString
[ "def", "getAttributesString", "(", "attributes", ")", ":", "attributesString", "=", "''", "attributesKeys", "=", "attributes", ".", "keys", "(", ")", "attributesKeys", ".", "sort", "(", "compareAttributeKeyAscending", ")", "for", "attributesKey", "in", "attributesKeys", ":", "valueString", "=", "str", "(", "attributes", "[", "attributesKey", "]", ")", "if", "(", "\"'\"", "in", "valueString", ")", ":", "attributesString", "+=", "(", "' %s=\"%s\"'", "%", "(", "attributesKey", ",", "valueString", ")", ")", "else", ":", "attributesString", "+=", "(", "\" %s='%s'\"", "%", "(", "attributesKey", ",", "valueString", ")", ")", "return", "attributesString" ]
add the closed xml tag .
train
false
14,702
def get_raw_from_provider(message): account = message.account return account.get_raw_message_contents(message)
[ "def", "get_raw_from_provider", "(", "message", ")", ":", "account", "=", "message", ".", "account", "return", "account", ".", "get_raw_message_contents", "(", "message", ")" ]
get the raw contents of a message from the provider .
train
false
14,703
def get_view_description(view_cls, html=False): description = (view_cls.__doc__ or '') description = formatting.dedent(smart_text(description)) if hasattr(view_cls, 'serializer_class'): doc_url = get_doc_url('api{0}s'.format(view_cls.serializer_class.Meta.model.__name__.lower())) else: doc_url = get_doc_url('api') description = '\n\n'.join((description, DOC_TEXT.format(doc_url))) if html: return formatting.markup_description(description) return description
[ "def", "get_view_description", "(", "view_cls", ",", "html", "=", "False", ")", ":", "description", "=", "(", "view_cls", ".", "__doc__", "or", "''", ")", "description", "=", "formatting", ".", "dedent", "(", "smart_text", "(", "description", ")", ")", "if", "hasattr", "(", "view_cls", ",", "'serializer_class'", ")", ":", "doc_url", "=", "get_doc_url", "(", "'api{0}s'", ".", "format", "(", "view_cls", ".", "serializer_class", ".", "Meta", ".", "model", ".", "__name__", ".", "lower", "(", ")", ")", ")", "else", ":", "doc_url", "=", "get_doc_url", "(", "'api'", ")", "description", "=", "'\\n\\n'", ".", "join", "(", "(", "description", ",", "DOC_TEXT", ".", "format", "(", "doc_url", ")", ")", ")", "if", "html", ":", "return", "formatting", ".", "markup_description", "(", "description", ")", "return", "description" ]
given a view class .
train
false
14,704
def import_field(field_classpath): if (u'.' in field_classpath): fully_qualified = field_classpath else: fully_qualified = (u'django.db.models.%s' % field_classpath) try: return import_dotted_path(fully_qualified) except ImportError: raise ImproperlyConfigured((u"The EXTRA_MODEL_FIELDS setting contains the field '%s' which could not be imported." % field_classpath))
[ "def", "import_field", "(", "field_classpath", ")", ":", "if", "(", "u'.'", "in", "field_classpath", ")", ":", "fully_qualified", "=", "field_classpath", "else", ":", "fully_qualified", "=", "(", "u'django.db.models.%s'", "%", "field_classpath", ")", "try", ":", "return", "import_dotted_path", "(", "fully_qualified", ")", "except", "ImportError", ":", "raise", "ImproperlyConfigured", "(", "(", "u\"The EXTRA_MODEL_FIELDS setting contains the field '%s' which could not be imported.\"", "%", "field_classpath", ")", ")" ]
imports a field by its dotted class path .
train
false
14,705
def set_tmpdir(dirname): global _TMPDIR _TMPDIR = dirname
[ "def", "set_tmpdir", "(", "dirname", ")", ":", "global", "_TMPDIR", "_TMPDIR", "=", "dirname" ]
set the temporary directory to use instead of __pycache__ .
train
false
14,706
def trim_req(req): reqfirst = next(iter(req)) if ('.' in reqfirst): return {reqfirst.split('.')[0]: req[reqfirst]} return req
[ "def", "trim_req", "(", "req", ")", ":", "reqfirst", "=", "next", "(", "iter", "(", "req", ")", ")", "if", "(", "'.'", "in", "reqfirst", ")", ":", "return", "{", "reqfirst", ".", "split", "(", "'.'", ")", "[", "0", "]", ":", "req", "[", "reqfirst", "]", "}", "return", "req" ]
trim any function off of a requisite .
train
true
14,708
def maketrans(fromstr, tostr): if (len(fromstr) != len(tostr)): raise ValueError, 'maketrans arguments must have same length' global _idmapL if (not _idmapL): _idmapL = list(_idmap) L = _idmapL[:] fromstr = map(ord, fromstr) for i in range(len(fromstr)): L[fromstr[i]] = tostr[i] return ''.join(L)
[ "def", "maketrans", "(", "fromstr", ",", "tostr", ")", ":", "if", "(", "len", "(", "fromstr", ")", "!=", "len", "(", "tostr", ")", ")", ":", "raise", "ValueError", ",", "'maketrans arguments must have same length'", "global", "_idmapL", "if", "(", "not", "_idmapL", ")", ":", "_idmapL", "=", "list", "(", "_idmap", ")", "L", "=", "_idmapL", "[", ":", "]", "fromstr", "=", "map", "(", "ord", ",", "fromstr", ")", "for", "i", "in", "range", "(", "len", "(", "fromstr", ")", ")", ":", "L", "[", "fromstr", "[", "i", "]", "]", "=", "tostr", "[", "i", "]", "return", "''", ".", "join", "(", "L", ")" ]
maketrans -> string return a translation table suitable for use in string .
train
true
14,709
def processElementNodeByFunction(elementNode, manipulationFunction): if ('target' not in elementNode.attributes): print 'Warning, there was no target in processElementNodeByFunction in solid for:' print elementNode return target = evaluate.getEvaluatedLinkValue(elementNode, str(elementNode.attributes['target']).strip()) if (target.__class__.__name__ == 'ElementNode'): manipulationFunction(elementNode, target) return path.convertElementNode(elementNode, target) manipulationFunction(elementNode, elementNode)
[ "def", "processElementNodeByFunction", "(", "elementNode", ",", "manipulationFunction", ")", ":", "if", "(", "'target'", "not", "in", "elementNode", ".", "attributes", ")", ":", "print", "'Warning, there was no target in processElementNodeByFunction in solid for:'", "print", "elementNode", "return", "target", "=", "evaluate", ".", "getEvaluatedLinkValue", "(", "elementNode", ",", "str", "(", "elementNode", ".", "attributes", "[", "'target'", "]", ")", ".", "strip", "(", ")", ")", "if", "(", "target", ".", "__class__", ".", "__name__", "==", "'ElementNode'", ")", ":", "manipulationFunction", "(", "elementNode", ",", "target", ")", "return", "path", ".", "convertElementNode", "(", "elementNode", ",", "target", ")", "manipulationFunction", "(", "elementNode", ",", "elementNode", ")" ]
process the xml element by the manipulationfunction .
train
false
14,710
def rand_text_numeric(length, bad=''): return rand_base(length, bad, set(numerals))
[ "def", "rand_text_numeric", "(", "length", ",", "bad", "=", "''", ")", ":", "return", "rand_base", "(", "length", ",", "bad", ",", "set", "(", "numerals", ")", ")" ]
generate a random string with numerals chars .
train
false
14,711
def varAnd(population, toolbox, cxpb, mutpb): offspring = [toolbox.clone(ind) for ind in population] for i in range(1, len(offspring), 2): if (random.random() < cxpb): (offspring[(i - 1)], offspring[i]) = toolbox.mate(offspring[(i - 1)], offspring[i]) del offspring[(i - 1)].fitness.values, offspring[i].fitness.values for i in range(len(offspring)): if (random.random() < mutpb): (offspring[i],) = toolbox.mutate(offspring[i]) del offspring[i].fitness.values return offspring
[ "def", "varAnd", "(", "population", ",", "toolbox", ",", "cxpb", ",", "mutpb", ")", ":", "offspring", "=", "[", "toolbox", ".", "clone", "(", "ind", ")", "for", "ind", "in", "population", "]", "for", "i", "in", "range", "(", "1", ",", "len", "(", "offspring", ")", ",", "2", ")", ":", "if", "(", "random", ".", "random", "(", ")", "<", "cxpb", ")", ":", "(", "offspring", "[", "(", "i", "-", "1", ")", "]", ",", "offspring", "[", "i", "]", ")", "=", "toolbox", ".", "mate", "(", "offspring", "[", "(", "i", "-", "1", ")", "]", ",", "offspring", "[", "i", "]", ")", "del", "offspring", "[", "(", "i", "-", "1", ")", "]", ".", "fitness", ".", "values", ",", "offspring", "[", "i", "]", ".", "fitness", ".", "values", "for", "i", "in", "range", "(", "len", "(", "offspring", ")", ")", ":", "if", "(", "random", ".", "random", "(", ")", "<", "mutpb", ")", ":", "(", "offspring", "[", "i", "]", ",", ")", "=", "toolbox", ".", "mutate", "(", "offspring", "[", "i", "]", ")", "del", "offspring", "[", "i", "]", ".", "fitness", ".", "values", "return", "offspring" ]
part of an evolutionary algorithm applying only the variation part .
train
false
14,712
@tx.atomic def add_vote(obj, user): obj_type = apps.get_model('contenttypes', 'ContentType').objects.get_for_model(obj) with advisory_lock('vote-{}-{}'.format(obj_type.id, obj.id)): (vote, created) = Vote.objects.get_or_create(content_type=obj_type, object_id=obj.id, user=user) if (not created): return (votes, _) = Votes.objects.get_or_create(content_type=obj_type, object_id=obj.id) votes.count = (F('count') + 1) votes.save() return vote
[ "@", "tx", ".", "atomic", "def", "add_vote", "(", "obj", ",", "user", ")", ":", "obj_type", "=", "apps", ".", "get_model", "(", "'contenttypes'", ",", "'ContentType'", ")", ".", "objects", ".", "get_for_model", "(", "obj", ")", "with", "advisory_lock", "(", "'vote-{}-{}'", ".", "format", "(", "obj_type", ".", "id", ",", "obj", ".", "id", ")", ")", ":", "(", "vote", ",", "created", ")", "=", "Vote", ".", "objects", ".", "get_or_create", "(", "content_type", "=", "obj_type", ",", "object_id", "=", "obj", ".", "id", ",", "user", "=", "user", ")", "if", "(", "not", "created", ")", ":", "return", "(", "votes", ",", "_", ")", "=", "Votes", ".", "objects", ".", "get_or_create", "(", "content_type", "=", "obj_type", ",", "object_id", "=", "obj", ".", "id", ")", "votes", ".", "count", "=", "(", "F", "(", "'count'", ")", "+", "1", ")", "votes", ".", "save", "(", ")", "return", "vote" ]
add a vote to an object .
train
false
14,714
def get_employee_emails(company, only_working=True): employee_list = frappe.get_all(u'Employee', fields=[u'name', u'user_id'], filters={u'status': u'Active', u'company': company}) out = [] for e in employee_list: if e.user_id: if (only_working and is_holiday(e.name)): continue out.append(e.user_id) return out
[ "def", "get_employee_emails", "(", "company", ",", "only_working", "=", "True", ")", ":", "employee_list", "=", "frappe", ".", "get_all", "(", "u'Employee'", ",", "fields", "=", "[", "u'name'", ",", "u'user_id'", "]", ",", "filters", "=", "{", "u'status'", ":", "u'Active'", ",", "u'company'", ":", "company", "}", ")", "out", "=", "[", "]", "for", "e", "in", "employee_list", ":", "if", "e", ".", "user_id", ":", "if", "(", "only_working", "and", "is_holiday", "(", "e", ".", "name", ")", ")", ":", "continue", "out", ".", "append", "(", "e", ".", "user_id", ")", "return", "out" ]
returns list of employee user ids for the given company who are working today .
train
false
14,715
def _fix_types(t): try: _ = t[0] t = list(t) except: t = [t] ok = False for tt in t: if _issubclass(tt, nxm_entry): ok = True break if (not ok): t.append(nxm_entry) return t
[ "def", "_fix_types", "(", "t", ")", ":", "try", ":", "_", "=", "t", "[", "0", "]", "t", "=", "list", "(", "t", ")", "except", ":", "t", "=", "[", "t", "]", "ok", "=", "False", "for", "tt", "in", "t", ":", "if", "_issubclass", "(", "tt", ",", "nxm_entry", ")", ":", "ok", "=", "True", "break", "if", "(", "not", "ok", ")", ":", "t", ".", "append", "(", "nxm_entry", ")", "return", "t" ]
helper for _make_nxm normalizes lists of superclasses .
train
false
14,716
def _check_engine(engine): if (engine is None): if _NUMEXPR_INSTALLED: engine = 'numexpr' else: engine = 'python' if (engine not in _engines): raise KeyError('Invalid engine {0!r} passed, valid engines are {1}'.format(engine, list(_engines.keys()))) if (engine == 'numexpr'): if (not _NUMEXPR_INSTALLED): raise ImportError("'numexpr' is not installed or an unsupported version. Cannot use engine='numexpr' for query/eval if 'numexpr' is not installed") return engine
[ "def", "_check_engine", "(", "engine", ")", ":", "if", "(", "engine", "is", "None", ")", ":", "if", "_NUMEXPR_INSTALLED", ":", "engine", "=", "'numexpr'", "else", ":", "engine", "=", "'python'", "if", "(", "engine", "not", "in", "_engines", ")", ":", "raise", "KeyError", "(", "'Invalid engine {0!r} passed, valid engines are {1}'", ".", "format", "(", "engine", ",", "list", "(", "_engines", ".", "keys", "(", ")", ")", ")", ")", "if", "(", "engine", "==", "'numexpr'", ")", ":", "if", "(", "not", "_NUMEXPR_INSTALLED", ")", ":", "raise", "ImportError", "(", "\"'numexpr' is not installed or an unsupported version. Cannot use engine='numexpr' for query/eval if 'numexpr' is not installed\"", ")", "return", "engine" ]
make sure a valid engine is passed .
train
false
14,719
def sanitize_query(query, db_func, on_behalf_of=None): q = copy.copy(query) auth_project = get_auth_project(on_behalf_of) if auth_project: _verify_query_segregation(q, auth_project) proj_q = [i for i in q if (i.field == 'project_id')] valid_keys = inspect.getargspec(db_func)[0] if ((not proj_q) and ('on_behalf_of' not in valid_keys)): q.append(base.Query(field='project_id', op='eq', value=auth_project)) return q
[ "def", "sanitize_query", "(", "query", ",", "db_func", ",", "on_behalf_of", "=", "None", ")", ":", "q", "=", "copy", ".", "copy", "(", "query", ")", "auth_project", "=", "get_auth_project", "(", "on_behalf_of", ")", "if", "auth_project", ":", "_verify_query_segregation", "(", "q", ",", "auth_project", ")", "proj_q", "=", "[", "i", "for", "i", "in", "q", "if", "(", "i", ".", "field", "==", "'project_id'", ")", "]", "valid_keys", "=", "inspect", ".", "getargspec", "(", "db_func", ")", "[", "0", "]", "if", "(", "(", "not", "proj_q", ")", "and", "(", "'on_behalf_of'", "not", "in", "valid_keys", ")", ")", ":", "q", ".", "append", "(", "base", ".", "Query", "(", "field", "=", "'project_id'", ",", "op", "=", "'eq'", ",", "value", "=", "auth_project", ")", ")", "return", "q" ]
check the query .
train
false
14,720
def create_java_stop_cmd(port): stop_cmd = '/usr/bin/python2 {0}/scripts/stop_service.py java {1}'.format(constants.APPSCALE_HOME, port) return stop_cmd
[ "def", "create_java_stop_cmd", "(", "port", ")", ":", "stop_cmd", "=", "'/usr/bin/python2 {0}/scripts/stop_service.py java {1}'", ".", "format", "(", "constants", ".", "APPSCALE_HOME", ",", "port", ")", "return", "stop_cmd" ]
this creates the stop command for an application which is uniquely identified by a port number .
train
false
14,721
def _GenClientLibFromContents(discovery_doc, language, output_path, client_name): body = urllib.urlencode({'lang': language, 'content': discovery_doc}) request = urllib2.Request(CLIENT_LIBRARY_BASE, body) try: with contextlib.closing(urllib2.urlopen(request)) as response: content = response.read() return _WriteFile(output_path, client_name, content) except urllib2.HTTPError as error: raise ServerRequestException(error)
[ "def", "_GenClientLibFromContents", "(", "discovery_doc", ",", "language", ",", "output_path", ",", "client_name", ")", ":", "body", "=", "urllib", ".", "urlencode", "(", "{", "'lang'", ":", "language", ",", "'content'", ":", "discovery_doc", "}", ")", "request", "=", "urllib2", ".", "Request", "(", "CLIENT_LIBRARY_BASE", ",", "body", ")", "try", ":", "with", "contextlib", ".", "closing", "(", "urllib2", ".", "urlopen", "(", "request", ")", ")", "as", "response", ":", "content", "=", "response", ".", "read", "(", ")", "return", "_WriteFile", "(", "output_path", ",", "client_name", ",", "content", ")", "except", "urllib2", ".", "HTTPError", "as", "error", ":", "raise", "ServerRequestException", "(", "error", ")" ]
write a client library from a discovery doc .
train
true
14,722
def runfile(*files): import parse (global_dict, local_dict) = get_twill_glocals() for f in files: parse.execute_file(f, no_reset=True)
[ "def", "runfile", "(", "*", "files", ")", ":", "import", "parse", "(", "global_dict", ",", "local_dict", ")", "=", "get_twill_glocals", "(", ")", "for", "f", "in", "files", ":", "parse", ".", "execute_file", "(", "f", ",", "no_reset", "=", "True", ")" ]
import a python module from a path .
train
false
14,723
def _get_ch_whitener(A, pca, ch_type, rank): (eig, eigvec) = linalg.eigh(A, overwrite_a=True) eigvec = eigvec.T eig[:(- rank)] = 0.0 logger.info(('Setting small %s eigenvalues to zero.' % ch_type)) if (not pca): logger.info(('Not doing PCA for %s.' % ch_type)) else: logger.info(('Doing PCA for %s.' % ch_type)) eigvec = eigvec[:(- rank)].copy() return (eig, eigvec)
[ "def", "_get_ch_whitener", "(", "A", ",", "pca", ",", "ch_type", ",", "rank", ")", ":", "(", "eig", ",", "eigvec", ")", "=", "linalg", ".", "eigh", "(", "A", ",", "overwrite_a", "=", "True", ")", "eigvec", "=", "eigvec", ".", "T", "eig", "[", ":", "(", "-", "rank", ")", "]", "=", "0.0", "logger", ".", "info", "(", "(", "'Setting small %s eigenvalues to zero.'", "%", "ch_type", ")", ")", "if", "(", "not", "pca", ")", ":", "logger", ".", "info", "(", "(", "'Not doing PCA for %s.'", "%", "ch_type", ")", ")", "else", ":", "logger", ".", "info", "(", "(", "'Doing PCA for %s.'", "%", "ch_type", ")", ")", "eigvec", "=", "eigvec", "[", ":", "(", "-", "rank", ")", "]", ".", "copy", "(", ")", "return", "(", "eig", ",", "eigvec", ")" ]
get whitener params for a set of channels .
train
false
14,724
def alltrue(seq): if (not len(seq)): return False for val in seq: if (not val): return False return True
[ "def", "alltrue", "(", "seq", ")", ":", "if", "(", "not", "len", "(", "seq", ")", ")", ":", "return", "False", "for", "val", "in", "seq", ":", "if", "(", "not", "val", ")", ":", "return", "False", "return", "True" ]
return *true* if all elements of *seq* evaluate to *true* .
train
false
14,725
def roberts_neg_diag(image, mask=None): assert_nD(image, 2) image = img_as_float(image) result = convolve(image, ROBERTS_ND_WEIGHTS) return _mask_filter_result(result, mask)
[ "def", "roberts_neg_diag", "(", "image", ",", "mask", "=", "None", ")", ":", "assert_nD", "(", "image", ",", "2", ")", "image", "=", "img_as_float", "(", "image", ")", "result", "=", "convolve", "(", "image", ",", "ROBERTS_ND_WEIGHTS", ")", "return", "_mask_filter_result", "(", "result", ",", "mask", ")" ]
find the cross edges of an image using the roberts cross operator .
train
false
14,726
def get_arguments(): parser = argparse.ArgumentParser() parser.add_argument('-i', '--input_file', required=True, help='csv input file (with extension)', type=str) parser.add_argument('-o', '--output_file', required=True, help='csv output file (without extension)', type=str) parser.add_argument('-r', '--row_limit', required=True, help='row limit to split csv at', type=int) args = parser.parse_args() is_valid_file(parser, args.input_file) is_valid_csv(parser, args.input_file, args.row_limit) return (args.input_file, args.output_file, args.row_limit)
[ "def", "get_arguments", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "'-i'", ",", "'--input_file'", ",", "required", "=", "True", ",", "help", "=", "'csv input file (with extension)'", ",", "type", "=", "str", ")", "parser", ".", "add_argument", "(", "'-o'", ",", "'--output_file'", ",", "required", "=", "True", ",", "help", "=", "'csv output file (without extension)'", ",", "type", "=", "str", ")", "parser", ".", "add_argument", "(", "'-r'", ",", "'--row_limit'", ",", "required", "=", "True", ",", "help", "=", "'row limit to split csv at'", ",", "type", "=", "int", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "is_valid_file", "(", "parser", ",", "args", ".", "input_file", ")", "is_valid_csv", "(", "parser", ",", "args", ".", "input_file", ",", "args", ".", "row_limit", ")", "return", "(", "args", ".", "input_file", ",", "args", ".", "output_file", ",", "args", ".", "row_limit", ")" ]
grab user supplied arguments using the argparse library .
train
false
14,727
def with_defaults(**default_funcs): def decorator(f): @wraps(f) def method(self, *args, **kwargs): for (name, func) in iteritems(default_funcs): if (name not in kwargs): kwargs[name] = func(self) return f(self, *args, **kwargs) return method return decorator
[ "def", "with_defaults", "(", "**", "default_funcs", ")", ":", "def", "decorator", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "method", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "for", "(", "name", ",", "func", ")", "in", "iteritems", "(", "default_funcs", ")", ":", "if", "(", "name", "not", "in", "kwargs", ")", ":", "kwargs", "[", "name", "]", "=", "func", "(", "self", ")", "return", "f", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", "return", "method", "return", "decorator" ]
decorator for providing dynamic default values for a method .
train
false
14,729
def _utcnow(): return datetime.datetime.utcnow()
[ "def", "_utcnow", "(", ")", ":", "return", "datetime", ".", "datetime", ".", "utcnow", "(", ")" ]
mocked in libcloud .
train
false
14,730
def none_to_empty(val): if (val is None): return '' else: return val
[ "def", "none_to_empty", "(", "val", ")", ":", "if", "(", "val", "is", "None", ")", ":", "return", "''", "else", ":", "return", "val" ]
converts none to an empty string .
train
false
14,731
def _get_conv_layers(layer, result=None): if (result is None): result = [] if isinstance(layer, (MLP, CompositeLayer)): for sub_layer in layer.layers: _get_conv_layers(sub_layer, result) elif isinstance(layer, (MaxoutConvC01B, ConvElemwise)): result.append(layer) return result
[ "def", "_get_conv_layers", "(", "layer", ",", "result", "=", "None", ")", ":", "if", "(", "result", "is", "None", ")", ":", "result", "=", "[", "]", "if", "isinstance", "(", "layer", ",", "(", "MLP", ",", "CompositeLayer", ")", ")", ":", "for", "sub_layer", "in", "layer", ".", "layers", ":", "_get_conv_layers", "(", "sub_layer", ",", "result", ")", "elif", "isinstance", "(", "layer", ",", "(", "MaxoutConvC01B", ",", "ConvElemwise", ")", ")", ":", "result", ".", "append", "(", "layer", ")", "return", "result" ]
returns a list of the convolutional layers in a model .
train
false
14,732
def test_cop_update_defaults_with_store_false(): class MyConfigOptionParser(virtualenv.ConfigOptionParser, ): def __init__(self, *args, **kwargs): self.config = virtualenv.ConfigParser.RawConfigParser() self.files = [] optparse.OptionParser.__init__(self, *args, **kwargs) def get_environ_vars(self, prefix='VIRTUALENV_'): (yield ('no_site_packages', '1')) cop = MyConfigOptionParser() cop.add_option('--no-site-packages', dest='system_site_packages', action='store_false', help="Don't give access to the global site-packages dir to the virtual environment (default)") defaults = {} cop.update_defaults(defaults) assert (defaults == {'system_site_packages': 0})
[ "def", "test_cop_update_defaults_with_store_false", "(", ")", ":", "class", "MyConfigOptionParser", "(", "virtualenv", ".", "ConfigOptionParser", ",", ")", ":", "def", "__init__", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "self", ".", "config", "=", "virtualenv", ".", "ConfigParser", ".", "RawConfigParser", "(", ")", "self", ".", "files", "=", "[", "]", "optparse", ".", "OptionParser", ".", "__init__", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", "def", "get_environ_vars", "(", "self", ",", "prefix", "=", "'VIRTUALENV_'", ")", ":", "(", "yield", "(", "'no_site_packages'", ",", "'1'", ")", ")", "cop", "=", "MyConfigOptionParser", "(", ")", "cop", ".", "add_option", "(", "'--no-site-packages'", ",", "dest", "=", "'system_site_packages'", ",", "action", "=", "'store_false'", ",", "help", "=", "\"Don't give access to the global site-packages dir to the virtual environment (default)\"", ")", "defaults", "=", "{", "}", "cop", ".", "update_defaults", "(", "defaults", ")", "assert", "(", "defaults", "==", "{", "'system_site_packages'", ":", "0", "}", ")" ]
store_false options need reverted logic .
train
false
14,733
def task_gen_completion(): cmd = 'nikola tabcompletion --shell {0} --hardcode-tasks > _nikola_{0}' for shell in ('bash', 'zsh'): (yield {'name': shell, 'actions': [cmd.format(shell)], 'targets': ['_nikola_{0}'.format(shell)]})
[ "def", "task_gen_completion", "(", ")", ":", "cmd", "=", "'nikola tabcompletion --shell {0} --hardcode-tasks > _nikola_{0}'", "for", "shell", "in", "(", "'bash'", ",", "'zsh'", ")", ":", "(", "yield", "{", "'name'", ":", "shell", ",", "'actions'", ":", "[", "cmd", ".", "format", "(", "shell", ")", "]", ",", "'targets'", ":", "[", "'_nikola_{0}'", ".", "format", "(", "shell", ")", "]", "}", ")" ]
generate tab-completion scripts .
train
false
14,738
def _deprecate(name): def _(*args, **kwargs): warnings.warn(('unittest.%s is deprecated. Instead use the %r method on unittest.TestCase' % (name, name)), stacklevel=2, category=DeprecationWarning) return getattr(_inst, name)(*args, **kwargs) return _
[ "def", "_deprecate", "(", "name", ")", ":", "def", "_", "(", "*", "args", ",", "**", "kwargs", ")", ":", "warnings", ".", "warn", "(", "(", "'unittest.%s is deprecated. Instead use the %r method on unittest.TestCase'", "%", "(", "name", ",", "name", ")", ")", ",", "stacklevel", "=", "2", ",", "category", "=", "DeprecationWarning", ")", "return", "getattr", "(", "_inst", ",", "name", ")", "(", "*", "args", ",", "**", "kwargs", ")", "return", "_" ]
internal method used to deprecate top-level assertions .
train
false
14,740
def cmdLineQuote(s): s = _cmdLineQuoteRe2.sub('\\1\\1', _cmdLineQuoteRe.sub('\\1\\1\\\\"', s)) return (('"' + s) + '"')
[ "def", "cmdLineQuote", "(", "s", ")", ":", "s", "=", "_cmdLineQuoteRe2", ".", "sub", "(", "'\\\\1\\\\1'", ",", "_cmdLineQuoteRe", ".", "sub", "(", "'\\\\1\\\\1\\\\\\\\\"'", ",", "s", ")", ")", "return", "(", "(", "'\"'", "+", "s", ")", "+", "'\"'", ")" ]
internal method for quoting a single command-line argument .
train
false
14,741
def _get_aln_slice_coords(parsed_hsp): seq = parsed_hsp['seq'] seq_stripped = seq.strip('-') disp_start = int(parsed_hsp['_display_start']) start = int(parsed_hsp['_start']) stop = int(parsed_hsp['_stop']) if (start <= stop): start = (start - disp_start) stop = ((stop - disp_start) + 1) else: start = (disp_start - start) stop = ((disp_start - stop) + 1) stop += seq_stripped.count('-') assert ((0 <= start) and (start < stop) and (stop <= len(seq_stripped))), ('Problem with sequence start/stop,\n%s[%i:%i]\n%s' % (seq, start, stop, parsed_hsp)) return (start, stop)
[ "def", "_get_aln_slice_coords", "(", "parsed_hsp", ")", ":", "seq", "=", "parsed_hsp", "[", "'seq'", "]", "seq_stripped", "=", "seq", ".", "strip", "(", "'-'", ")", "disp_start", "=", "int", "(", "parsed_hsp", "[", "'_display_start'", "]", ")", "start", "=", "int", "(", "parsed_hsp", "[", "'_start'", "]", ")", "stop", "=", "int", "(", "parsed_hsp", "[", "'_stop'", "]", ")", "if", "(", "start", "<=", "stop", ")", ":", "start", "=", "(", "start", "-", "disp_start", ")", "stop", "=", "(", "(", "stop", "-", "disp_start", ")", "+", "1", ")", "else", ":", "start", "=", "(", "disp_start", "-", "start", ")", "stop", "=", "(", "(", "disp_start", "-", "stop", ")", "+", "1", ")", "stop", "+=", "seq_stripped", ".", "count", "(", "'-'", ")", "assert", "(", "(", "0", "<=", "start", ")", "and", "(", "start", "<", "stop", ")", "and", "(", "stop", "<=", "len", "(", "seq_stripped", ")", ")", ")", ",", "(", "'Problem with sequence start/stop,\\n%s[%i:%i]\\n%s'", "%", "(", "seq", ",", "start", ",", "stop", ",", "parsed_hsp", ")", ")", "return", "(", "start", ",", "stop", ")" ]
helper function for the main parsing code .
train
false
14,742
def test_dict(test_data): ds = ChartDataSource.from_data(test_data.dict_data) assert (len(ds.columns) == 2) assert (len(ds.index) == 4)
[ "def", "test_dict", "(", "test_data", ")", ":", "ds", "=", "ChartDataSource", ".", "from_data", "(", "test_data", ".", "dict_data", ")", "assert", "(", "len", "(", "ds", ".", "columns", ")", "==", "2", ")", "assert", "(", "len", "(", "ds", ".", "index", ")", "==", "4", ")" ]
test creating chart data source from dict of arrays .
train
false
14,743
def detect_environment(): global _environment if (_environment is None): _environment = _detect_environment() return _environment
[ "def", "detect_environment", "(", ")", ":", "global", "_environment", "if", "(", "_environment", "is", "None", ")", ":", "_environment", "=", "_detect_environment", "(", ")", "return", "_environment" ]
detect the current environment: default .
train
false
14,744
def get_grouped_distances(dist_matrix_header, dist_matrix, mapping_header, mapping, field, within=True, suppress_symmetry_and_hollowness_check=False): _validate_input(dist_matrix_header, dist_matrix, mapping_header, mapping, field) mapping_data = [mapping_header] mapping_data.extend(mapping) groups = group_by_field(mapping_data, field) return _get_groupings(dist_matrix_header, dist_matrix, groups, within, suppress_symmetry_and_hollowness_check)
[ "def", "get_grouped_distances", "(", "dist_matrix_header", ",", "dist_matrix", ",", "mapping_header", ",", "mapping", ",", "field", ",", "within", "=", "True", ",", "suppress_symmetry_and_hollowness_check", "=", "False", ")", ":", "_validate_input", "(", "dist_matrix_header", ",", "dist_matrix", ",", "mapping_header", ",", "mapping", ",", "field", ")", "mapping_data", "=", "[", "mapping_header", "]", "mapping_data", ".", "extend", "(", "mapping", ")", "groups", "=", "group_by_field", "(", "mapping_data", ",", "field", ")", "return", "_get_groupings", "(", "dist_matrix_header", ",", "dist_matrix", ",", "groups", ",", "within", ",", "suppress_symmetry_and_hollowness_check", ")" ]
returns a list of distance groupings for the specified field .
train
false
14,747
def safe_load_all(stream): return load_all(stream, SafeLoader)
[ "def", "safe_load_all", "(", "stream", ")", ":", "return", "load_all", "(", "stream", ",", "SafeLoader", ")" ]
parse all yaml documents in a stream and produce corresponding python objects .
train
false
14,748
def postgres_passwd(password, username, uppercase=False): retVal = ('md5%s' % md5((password + username)).hexdigest()) return (retVal.upper() if uppercase else retVal.lower())
[ "def", "postgres_passwd", "(", "password", ",", "username", ",", "uppercase", "=", "False", ")", ":", "retVal", "=", "(", "'md5%s'", "%", "md5", "(", "(", "password", "+", "username", ")", ")", ".", "hexdigest", "(", ")", ")", "return", "(", "retVal", ".", "upper", "(", ")", "if", "uppercase", "else", "retVal", ".", "lower", "(", ")", ")" ]
reference(s): URL .
train
false
14,749
def test_no_y_labels(Chart): chart = Chart() chart.y_labels = [] chart.add('_', [1, 2, 3]) chart.add('?', [10, 21, 5]) assert chart.render_pyquery()
[ "def", "test_no_y_labels", "(", "Chart", ")", ":", "chart", "=", "Chart", "(", ")", "chart", ".", "y_labels", "=", "[", "]", "chart", ".", "add", "(", "'_'", ",", "[", "1", ",", "2", ",", "3", "]", ")", "chart", ".", "add", "(", "'?'", ",", "[", "10", ",", "21", ",", "5", "]", ")", "assert", "chart", ".", "render_pyquery", "(", ")" ]
test no y labels chart .
train
false
14,750
def _NewIndexFromPb(index_metadata_pb): index = _NewIndexFromIndexSpecPb(index_metadata_pb.index_spec()) if index_metadata_pb.field_list(): index._schema = _NewSchemaFromPb(index_metadata_pb.field_list()) return index
[ "def", "_NewIndexFromPb", "(", "index_metadata_pb", ")", ":", "index", "=", "_NewIndexFromIndexSpecPb", "(", "index_metadata_pb", ".", "index_spec", "(", ")", ")", "if", "index_metadata_pb", ".", "field_list", "(", ")", ":", "index", ".", "_schema", "=", "_NewSchemaFromPb", "(", "index_metadata_pb", ".", "field_list", "(", ")", ")", "return", "index" ]
creates an index from a search_service_pb .
train
false
14,751
def deepest_path(path_a, path_b): if (path_a == '.'): path_a = '' if (path_b == '.'): path_b = '' if path_a.startswith(path_b): return (path_a or '.') if path_b.startswith(path_a): return (path_b or '.') return None
[ "def", "deepest_path", "(", "path_a", ",", "path_b", ")", ":", "if", "(", "path_a", "==", "'.'", ")", ":", "path_a", "=", "''", "if", "(", "path_b", "==", "'.'", ")", ":", "path_b", "=", "''", "if", "path_a", ".", "startswith", "(", "path_b", ")", ":", "return", "(", "path_a", "or", "'.'", ")", "if", "path_b", ".", "startswith", "(", "path_a", ")", ":", "return", "(", "path_b", "or", "'.'", ")", "return", "None" ]
return the deepest of two paths .
train
false
14,752
def tell(name, query=''): try: cmd = 'tell_{}'.format(name) if (cmd in globals()): items = globals()[cmd](query) else: items = [alfred.Item('tell', 'Invalid action "{}"'.format(name))] except SetupError as e: items = [alfred.Item('error', e.title, e.subtitle, icon='error.png')] except Exception as e: items = [alfred.Item('error', str(e), icon='error.png')] _out(alfred.to_xml(items))
[ "def", "tell", "(", "name", ",", "query", "=", "''", ")", ":", "try", ":", "cmd", "=", "'tell_{}'", ".", "format", "(", "name", ")", "if", "(", "cmd", "in", "globals", "(", ")", ")", ":", "items", "=", "globals", "(", ")", "[", "cmd", "]", "(", "query", ")", "else", ":", "items", "=", "[", "alfred", ".", "Item", "(", "'tell'", ",", "'Invalid action \"{}\"'", ".", "format", "(", "name", ")", ")", "]", "except", "SetupError", "as", "e", ":", "items", "=", "[", "alfred", ".", "Item", "(", "'error'", ",", "e", ".", "title", ",", "e", ".", "subtitle", ",", "icon", "=", "'error.png'", ")", "]", "except", "Exception", "as", "e", ":", "items", "=", "[", "alfred", ".", "Item", "(", "'error'", ",", "str", "(", "e", ")", ",", "icon", "=", "'error.png'", ")", "]", "_out", "(", "alfred", ".", "to_xml", "(", "items", ")", ")" ]
tell something .
train
false
14,753
def show_floatingip(floatingip_id, profile=None): conn = _auth(profile) return conn.show_floatingip(floatingip_id)
[ "def", "show_floatingip", "(", "floatingip_id", ",", "profile", "=", "None", ")", ":", "conn", "=", "_auth", "(", "profile", ")", "return", "conn", ".", "show_floatingip", "(", "floatingip_id", ")" ]
fetches information of a certain floatingip cli example: .
train
false
14,754
def DEFINE_multi_float(name, default, help, lower_bound=None, upper_bound=None, flag_values=FLAGS, **args): parser = FloatParser(lower_bound, upper_bound) serializer = ArgumentSerializer() DEFINE_multi(parser, serializer, name, default, help, flag_values, **args)
[ "def", "DEFINE_multi_float", "(", "name", ",", "default", ",", "help", ",", "lower_bound", "=", "None", ",", "upper_bound", "=", "None", ",", "flag_values", "=", "FLAGS", ",", "**", "args", ")", ":", "parser", "=", "FloatParser", "(", "lower_bound", ",", "upper_bound", ")", "serializer", "=", "ArgumentSerializer", "(", ")", "DEFINE_multi", "(", "parser", ",", "serializer", ",", "name", ",", "default", ",", "help", ",", "flag_values", ",", "**", "args", ")" ]
registers a flag whose value can be a list of arbitrary floats .
train
true
14,756
@contextmanager def _conn(commit=False): defaults = {'host': 'localhost', 'user': 'salt', 'password': 'salt', 'dbname': 'salt', 'port': 5432} conn_kwargs = {} for (key, value) in defaults.items(): conn_kwargs[key] = __opts__.get('queue.{0}.{1}'.format(__virtualname__, key), value) try: conn = psycopg2.connect(**conn_kwargs) except psycopg2.OperationalError as exc: raise SaltMasterError('pgjsonb returner could not connect to database: {exc}'.format(exc=exc)) cursor = conn.cursor() try: (yield cursor) except psycopg2.DatabaseError as err: error = err.args sys.stderr.write(str(error)) cursor.execute('ROLLBACK') raise err else: if commit: cursor.execute('COMMIT') else: cursor.execute('ROLLBACK') finally: conn.close()
[ "@", "contextmanager", "def", "_conn", "(", "commit", "=", "False", ")", ":", "defaults", "=", "{", "'host'", ":", "'localhost'", ",", "'user'", ":", "'salt'", ",", "'password'", ":", "'salt'", ",", "'dbname'", ":", "'salt'", ",", "'port'", ":", "5432", "}", "conn_kwargs", "=", "{", "}", "for", "(", "key", ",", "value", ")", "in", "defaults", ".", "items", "(", ")", ":", "conn_kwargs", "[", "key", "]", "=", "__opts__", ".", "get", "(", "'queue.{0}.{1}'", ".", "format", "(", "__virtualname__", ",", "key", ")", ",", "value", ")", "try", ":", "conn", "=", "psycopg2", ".", "connect", "(", "**", "conn_kwargs", ")", "except", "psycopg2", ".", "OperationalError", "as", "exc", ":", "raise", "SaltMasterError", "(", "'pgjsonb returner could not connect to database: {exc}'", ".", "format", "(", "exc", "=", "exc", ")", ")", "cursor", "=", "conn", ".", "cursor", "(", ")", "try", ":", "(", "yield", "cursor", ")", "except", "psycopg2", ".", "DatabaseError", "as", "err", ":", "error", "=", "err", ".", "args", "sys", ".", "stderr", ".", "write", "(", "str", "(", "error", ")", ")", "cursor", ".", "execute", "(", "'ROLLBACK'", ")", "raise", "err", "else", ":", "if", "commit", ":", "cursor", ".", "execute", "(", "'COMMIT'", ")", "else", ":", "cursor", ".", "execute", "(", "'ROLLBACK'", ")", "finally", ":", "conn", ".", "close", "(", ")" ]
return an postgres cursor .
train
true
14,759
def startReceiver(host, port, username, password, vhost, exchange_name, spec=None, channel=1, verbose=False): factory = createAMQPListener(username, password, vhost, exchange_name, spec=spec, channel=channel, verbose=verbose) reactor.connectTCP(host, port, factory)
[ "def", "startReceiver", "(", "host", ",", "port", ",", "username", ",", "password", ",", "vhost", ",", "exchange_name", ",", "spec", "=", "None", ",", "channel", "=", "1", ",", "verbose", "=", "False", ")", ":", "factory", "=", "createAMQPListener", "(", "username", ",", "password", ",", "vhost", ",", "exchange_name", ",", "spec", "=", "spec", ",", "channel", "=", "channel", ",", "verbose", "=", "verbose", ")", "reactor", ".", "connectTCP", "(", "host", ",", "port", ",", "factory", ")" ]
starts a twisted process that will read messages on the amqp broker and post them as metrics .
train
false
14,761
def _list_modules(): return [desc.module_class for desc in _list_descriptors()]
[ "def", "_list_modules", "(", ")", ":", "return", "[", "desc", ".", "module_class", "for", "desc", "in", "_list_descriptors", "(", ")", "]" ]
return a list of all registered xmodule classes .
train
false
14,762
def distance_matrix(client, origins, destinations, mode=None, language=None, avoid=None, units=None, departure_time=None, arrival_time=None, transit_mode=None, transit_routing_preference=None, traffic_model=None): params = {'origins': convert.location_list(origins), 'destinations': convert.location_list(destinations)} if mode: if (mode not in ['driving', 'walking', 'bicycling', 'transit']): raise ValueError('Invalid travel mode.') params['mode'] = mode if language: params['language'] = language if avoid: if (avoid not in ['tolls', 'highways', 'ferries']): raise ValueError('Invalid route restriction.') params['avoid'] = avoid if units: params['units'] = units if departure_time: params['departure_time'] = convert.time(departure_time) if arrival_time: params['arrival_time'] = convert.time(arrival_time) if (departure_time and arrival_time): raise ValueError('Should not specify both departure_time andarrival_time.') if transit_mode: params['transit_mode'] = convert.join_list('|', transit_mode) if transit_routing_preference: params['transit_routing_preference'] = transit_routing_preference if traffic_model: params['traffic_model'] = traffic_model return client._get('/maps/api/distancematrix/json', params)
[ "def", "distance_matrix", "(", "client", ",", "origins", ",", "destinations", ",", "mode", "=", "None", ",", "language", "=", "None", ",", "avoid", "=", "None", ",", "units", "=", "None", ",", "departure_time", "=", "None", ",", "arrival_time", "=", "None", ",", "transit_mode", "=", "None", ",", "transit_routing_preference", "=", "None", ",", "traffic_model", "=", "None", ")", ":", "params", "=", "{", "'origins'", ":", "convert", ".", "location_list", "(", "origins", ")", ",", "'destinations'", ":", "convert", ".", "location_list", "(", "destinations", ")", "}", "if", "mode", ":", "if", "(", "mode", "not", "in", "[", "'driving'", ",", "'walking'", ",", "'bicycling'", ",", "'transit'", "]", ")", ":", "raise", "ValueError", "(", "'Invalid travel mode.'", ")", "params", "[", "'mode'", "]", "=", "mode", "if", "language", ":", "params", "[", "'language'", "]", "=", "language", "if", "avoid", ":", "if", "(", "avoid", "not", "in", "[", "'tolls'", ",", "'highways'", ",", "'ferries'", "]", ")", ":", "raise", "ValueError", "(", "'Invalid route restriction.'", ")", "params", "[", "'avoid'", "]", "=", "avoid", "if", "units", ":", "params", "[", "'units'", "]", "=", "units", "if", "departure_time", ":", "params", "[", "'departure_time'", "]", "=", "convert", ".", "time", "(", "departure_time", ")", "if", "arrival_time", ":", "params", "[", "'arrival_time'", "]", "=", "convert", ".", "time", "(", "arrival_time", ")", "if", "(", "departure_time", "and", "arrival_time", ")", ":", "raise", "ValueError", "(", "'Should not specify both departure_time andarrival_time.'", ")", "if", "transit_mode", ":", "params", "[", "'transit_mode'", "]", "=", "convert", ".", "join_list", "(", "'|'", ",", "transit_mode", ")", "if", "transit_routing_preference", ":", "params", "[", "'transit_routing_preference'", "]", "=", "transit_routing_preference", "if", "traffic_model", ":", "params", "[", "'traffic_model'", "]", "=", "traffic_model", "return", "client", ".", "_get", "(", "'/maps/api/distancematrix/json'", ",", "params", ")" ]
compute the distance matrix .
train
true
14,763
def fake_add_device(devices, update_befor_add=False): if update_befor_add: for speaker in devices: speaker.update()
[ "def", "fake_add_device", "(", "devices", ",", "update_befor_add", "=", "False", ")", ":", "if", "update_befor_add", ":", "for", "speaker", "in", "devices", ":", "speaker", ".", "update", "(", ")" ]
fake add device / update .
train
false
14,764
def init_service(http): return gapi.build('analytics', 'v3', http=http)
[ "def", "init_service", "(", "http", ")", ":", "return", "gapi", ".", "build", "(", "'analytics'", ",", "'v3'", ",", "http", "=", "http", ")" ]
use the given http object to build the analytics service object .
train
false
14,765
def get_next_pair(): def get_cb(): if (not parts): raise BadInput('missing command') cmd = parts.pop(0).lower() for command in ('return', 'fail', 'passthru'): if command.startswith(cmd): cmd = command break else: raise BadInput(('bad command: %s' % cmd)) if (cmd in ('return', 'fail')): if (not parts): raise BadInput('missing argument') result = parts.pop(0) if (len(result) > 6): raise BadInput('result more than 6 chars long', result) return Callback(cmd, result) else: return Callback(cmd) try: line = raw_input() except EOFError: sys.exit() if (not line): return None parts = line.strip().split() (callback, errback) = (get_cb(), get_cb()) if parts: raise BadInput('extra arguments') return (callback, errback)
[ "def", "get_next_pair", "(", ")", ":", "def", "get_cb", "(", ")", ":", "if", "(", "not", "parts", ")", ":", "raise", "BadInput", "(", "'missing command'", ")", "cmd", "=", "parts", ".", "pop", "(", "0", ")", ".", "lower", "(", ")", "for", "command", "in", "(", "'return'", ",", "'fail'", ",", "'passthru'", ")", ":", "if", "command", ".", "startswith", "(", "cmd", ")", ":", "cmd", "=", "command", "break", "else", ":", "raise", "BadInput", "(", "(", "'bad command: %s'", "%", "cmd", ")", ")", "if", "(", "cmd", "in", "(", "'return'", ",", "'fail'", ")", ")", ":", "if", "(", "not", "parts", ")", ":", "raise", "BadInput", "(", "'missing argument'", ")", "result", "=", "parts", ".", "pop", "(", "0", ")", "if", "(", "len", "(", "result", ")", ">", "6", ")", ":", "raise", "BadInput", "(", "'result more than 6 chars long'", ",", "result", ")", "return", "Callback", "(", "cmd", ",", "result", ")", "else", ":", "return", "Callback", "(", "cmd", ")", "try", ":", "line", "=", "raw_input", "(", ")", "except", "EOFError", ":", "sys", ".", "exit", "(", ")", "if", "(", "not", "line", ")", ":", "return", "None", "parts", "=", "line", ".", "strip", "(", ")", ".", "split", "(", ")", "(", "callback", ",", "errback", ")", "=", "(", "get_cb", "(", ")", ",", "get_cb", "(", ")", ")", "if", "parts", ":", "raise", "BadInput", "(", "'extra arguments'", ")", "return", "(", "callback", ",", "errback", ")" ]
get the next callback/errback pair from the user .
train
false
14,766
def get_tags_url(): return '{base_url}/{owner}/{repo}/tags'.format(**API_PARAMS)
[ "def", "get_tags_url", "(", ")", ":", "return", "'{base_url}/{owner}/{repo}/tags'", ".", "format", "(", "**", "API_PARAMS", ")" ]
returns github api url for querying tags .
train
false
14,767
def _extract_country_code(number): if ((len(number) == 0) or (number[0] == U_ZERO)): return (0, number) for ii in range(1, (min(len(number), _MAX_LENGTH_COUNTRY_CODE) + 1)): try: country_code = int(number[:ii]) if (country_code in COUNTRY_CODE_TO_REGION_CODE): return (country_code, number[ii:]) except Exception: pass return (0, number)
[ "def", "_extract_country_code", "(", "number", ")", ":", "if", "(", "(", "len", "(", "number", ")", "==", "0", ")", "or", "(", "number", "[", "0", "]", "==", "U_ZERO", ")", ")", ":", "return", "(", "0", ",", "number", ")", "for", "ii", "in", "range", "(", "1", ",", "(", "min", "(", "len", "(", "number", ")", ",", "_MAX_LENGTH_COUNTRY_CODE", ")", "+", "1", ")", ")", ":", "try", ":", "country_code", "=", "int", "(", "number", "[", ":", "ii", "]", ")", "if", "(", "country_code", "in", "COUNTRY_CODE_TO_REGION_CODE", ")", ":", "return", "(", "country_code", ",", "number", "[", "ii", ":", "]", ")", "except", "Exception", ":", "pass", "return", "(", "0", ",", "number", ")" ]
extracts country calling code from number .
train
true
14,768
def submit_ticket(email, category, subject, body, tags): zendesk = get_zendesk() new_ticket = {'ticket': {'requester_email': email, 'subject': (settings.ZENDESK_SUBJECT_PREFIX + subject), 'description': body, 'set_tags': category, 'tags': tags}} try: ticket_url = zendesk.create_ticket(data=new_ticket) statsd.incr('questions.zendesk.success') except ZendeskError as e: log.error(('Zendesk error: %s' % e.msg)) statsd.incr('questions.zendesk.error') raise return ticket_url
[ "def", "submit_ticket", "(", "email", ",", "category", ",", "subject", ",", "body", ",", "tags", ")", ":", "zendesk", "=", "get_zendesk", "(", ")", "new_ticket", "=", "{", "'ticket'", ":", "{", "'requester_email'", ":", "email", ",", "'subject'", ":", "(", "settings", ".", "ZENDESK_SUBJECT_PREFIX", "+", "subject", ")", ",", "'description'", ":", "body", ",", "'set_tags'", ":", "category", ",", "'tags'", ":", "tags", "}", "}", "try", ":", "ticket_url", "=", "zendesk", ".", "create_ticket", "(", "data", "=", "new_ticket", ")", "statsd", ".", "incr", "(", "'questions.zendesk.success'", ")", "except", "ZendeskError", "as", "e", ":", "log", ".", "error", "(", "(", "'Zendesk error: %s'", "%", "e", ".", "msg", ")", ")", "statsd", ".", "incr", "(", "'questions.zendesk.error'", ")", "raise", "return", "ticket_url" ]
submit a marketplace ticket to zendesk .
train
false
14,769
def _parse_tcp_line(line): ret = {} comps = line.strip().split() sl = comps[0].rstrip(':') ret[sl] = {} (l_addr, l_port) = comps[1].split(':') (r_addr, r_port) = comps[2].split(':') ret[sl]['local_addr'] = hex2ip(l_addr, True) ret[sl]['local_port'] = int(l_port, 16) ret[sl]['remote_addr'] = hex2ip(r_addr, True) ret[sl]['remote_port'] = int(r_port, 16) return ret
[ "def", "_parse_tcp_line", "(", "line", ")", ":", "ret", "=", "{", "}", "comps", "=", "line", ".", "strip", "(", ")", ".", "split", "(", ")", "sl", "=", "comps", "[", "0", "]", ".", "rstrip", "(", "':'", ")", "ret", "[", "sl", "]", "=", "{", "}", "(", "l_addr", ",", "l_port", ")", "=", "comps", "[", "1", "]", ".", "split", "(", "':'", ")", "(", "r_addr", ",", "r_port", ")", "=", "comps", "[", "2", "]", ".", "split", "(", "':'", ")", "ret", "[", "sl", "]", "[", "'local_addr'", "]", "=", "hex2ip", "(", "l_addr", ",", "True", ")", "ret", "[", "sl", "]", "[", "'local_port'", "]", "=", "int", "(", "l_port", ",", "16", ")", "ret", "[", "sl", "]", "[", "'remote_addr'", "]", "=", "hex2ip", "(", "r_addr", ",", "True", ")", "ret", "[", "sl", "]", "[", "'remote_port'", "]", "=", "int", "(", "r_port", ",", "16", ")", "return", "ret" ]
parse a single line from the contents of /proc/net/tcp or /proc/net/tcp6 .
train
true
14,770
def rcompile(pattern, flags=0, verbose=False): if (not isinstance(pattern, string_type)): return pattern if verbose: flags |= re.VERBOSE return re.compile(pattern, (re.UNICODE | flags))
[ "def", "rcompile", "(", "pattern", ",", "flags", "=", "0", ",", "verbose", "=", "False", ")", ":", "if", "(", "not", "isinstance", "(", "pattern", ",", "string_type", ")", ")", ":", "return", "pattern", "if", "verbose", ":", "flags", "|=", "re", ".", "VERBOSE", "return", "re", ".", "compile", "(", "pattern", ",", "(", "re", ".", "UNICODE", "|", "flags", ")", ")" ]
a wrapper for re .
train
false