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
32,699
def genprimes(): D = {} q = 2 while 1: if (q not in D): (yield q) D[(q * q)] = [q] else: for p in D[q]: D.setdefault((p + q), []).append(p) del D[q] q += 1
[ "def", "genprimes", "(", ")", ":", "D", "=", "{", "}", "q", "=", "2", "while", "1", ":", "if", "(", "q", "not", "in", "D", ")", ":", "(", "yield", "q", ")", "D", "[", "(", "q", "*", "q", ")", "]", "=", "[", "q", "]", "else", ":", "for...
yields the sequence of prime numbers via the sieve of eratosthenes .
train
false
32,700
def test_str_to_utf8(): s = '\\u01ff\\u02ff' u = utils.to_utf8(s) assert_equal(type(s), type(str())) assert_equal(type(u), type(u'\u01ff\u02ff'))
[ "def", "test_str_to_utf8", "(", ")", ":", "s", "=", "'\\\\u01ff\\\\u02ff'", "u", "=", "utils", ".", "to_utf8", "(", "s", ")", "assert_equal", "(", "type", "(", "s", ")", ",", "type", "(", "str", "(", ")", ")", ")", "assert_equal", "(", "type", "(", ...
test the to_utf8 function: string to unicode .
train
false
32,701
def _FetchLog(http_client, log_url, output_file, callback): def _OnFetch(response): if (response.code == 200): with open(output_file, 'w') as f: f.write(response.body) logging.info(('wrote %d bytes to %s' % (len(response.body), output_file))) else: logging.error(('failed to fetch %s' % log_url)) callback() http_client.fetch(log_url, callback=_OnFetch, method='GET')
[ "def", "_FetchLog", "(", "http_client", ",", "log_url", ",", "output_file", ",", "callback", ")", ":", "def", "_OnFetch", "(", "response", ")", ":", "if", "(", "response", ".", "code", "==", "200", ")", ":", "with", "open", "(", "output_file", ",", "'w...
fetches the log file at "log_url" and stores it in "output_file" .
train
false
32,702
def instance_tag_exists(context, instance_uuid, tag): return IMPL.instance_tag_exists(context, instance_uuid, tag)
[ "def", "instance_tag_exists", "(", "context", ",", "instance_uuid", ",", "tag", ")", ":", "return", "IMPL", ".", "instance_tag_exists", "(", "context", ",", "instance_uuid", ",", "tag", ")" ]
check if specified tag exist on the instance .
train
false
32,703
@hook.on_start def set_headers(bot): global headers headers = {'User-Agent': bot.user_agent}
[ "@", "hook", ".", "on_start", "def", "set_headers", "(", "bot", ")", ":", "global", "headers", "headers", "=", "{", "'User-Agent'", ":", "bot", ".", "user_agent", "}" ]
runs on initial plugin load and sets the http headers for this plugin .
train
false
32,705
def _average_path_length(n_samples_leaf): if isinstance(n_samples_leaf, INTEGER_TYPES): if (n_samples_leaf <= 1): return 1.0 else: return ((2.0 * (np.log(n_samples_leaf) + 0.5772156649)) - ((2.0 * (n_samples_leaf - 1.0)) / n_samples_leaf)) else: n_samples_leaf_shape = n_samples_leaf.shape n_samples_leaf = n_samples_leaf.reshape((1, (-1))) average_path_length = np.zeros(n_samples_leaf.shape) mask = (n_samples_leaf <= 1) not_mask = np.logical_not(mask) average_path_length[mask] = 1.0 average_path_length[not_mask] = ((2.0 * (np.log(n_samples_leaf[not_mask]) + 0.5772156649)) - ((2.0 * (n_samples_leaf[not_mask] - 1.0)) / n_samples_leaf[not_mask])) return average_path_length.reshape(n_samples_leaf_shape)
[ "def", "_average_path_length", "(", "n_samples_leaf", ")", ":", "if", "isinstance", "(", "n_samples_leaf", ",", "INTEGER_TYPES", ")", ":", "if", "(", "n_samples_leaf", "<=", "1", ")", ":", "return", "1.0", "else", ":", "return", "(", "(", "2.0", "*", "(", ...
the average path length in a n_samples itree .
train
false
32,706
def is_text_or_none(string): return ((string is None) or isinstance(string, string_types))
[ "def", "is_text_or_none", "(", "string", ")", ":", "return", "(", "(", "string", "is", "None", ")", "or", "isinstance", "(", "string", ",", "string_types", ")", ")" ]
wrapper around isinstance or is none .
train
false
32,708
def archive(job_pk): create_app_context() job = ArchiveJob.load(job_pk) (src, dst, user) = job.info() logger = get_task_logger(__name__) logger.info('Received archive task for Node: {0} into Node: {1}'.format(src._id, dst._id)) return celery.chain([celery.group((stat_addon.si(addon_short_name=target.name, job_pk=job_pk) for target in job.target_addons.all())), archive_node.s(job_pk=job_pk)])
[ "def", "archive", "(", "job_pk", ")", ":", "create_app_context", "(", ")", "job", "=", "ArchiveJob", ".", "load", "(", "job_pk", ")", "(", "src", ",", "dst", ",", "user", ")", "=", "job", ".", "info", "(", ")", "logger", "=", "get_task_logger", "(", ...
create an archive .
train
false
32,709
@hook.command('youtime', 'ytime') def youtime(text): if (not dev_key): return 'This command requires a Google Developers Console API key.' json = requests.get(search_api_url, params={'q': text, 'key': dev_key, 'type': 'video'}).json() if json.get('error'): if (json['error']['code'] == 403): return err_no_api else: return 'Error performing search.' if (json['pageInfo']['totalResults'] == 0): return 'No results found.' video_id = json['items'][0]['id']['videoId'] json = requests.get(api_url.format(video_id, dev_key)).json() if json.get('error'): return data = json['items'] snippet = data[0]['snippet'] content_details = data[0]['contentDetails'] statistics = data[0]['statistics'] if (not content_details.get('duration')): return length = isodate.parse_duration(content_details['duration']) l_sec = int(length.total_seconds()) views = int(statistics['viewCount']) total = int((l_sec * views)) length_text = timeformat.format_time(l_sec, simple=True) total_text = timeformat.format_time(total, accuracy=8) return 'The video \x02{}\x02 has a length of {} and has been viewed {:,} times for a total run time of {}!'.format(snippet['title'], length_text, views, total_text)
[ "@", "hook", ".", "command", "(", "'youtime'", ",", "'ytime'", ")", "def", "youtime", "(", "text", ")", ":", "if", "(", "not", "dev_key", ")", ":", "return", "'This command requires a Google Developers Console API key.'", "json", "=", "requests", ".", "get", "...
youtime <query> -- gets the total run time of the first youtube search result for <query> .
train
false
32,710
def generate_aes_iv(key): return md5((key + md5(key).hexdigest())).hexdigest()[:AES.block_size]
[ "def", "generate_aes_iv", "(", "key", ")", ":", "return", "md5", "(", "(", "key", "+", "md5", "(", "key", ")", ".", "hexdigest", "(", ")", ")", ")", ".", "hexdigest", "(", ")", "[", ":", "AES", ".", "block_size", "]" ]
return the initialization vector software secure expects for a given aes key .
train
false
32,711
def get_network_domain(driver, locator, location): if is_uuid(locator): net_id = locator else: name = locator networks = driver.ex_list_network_domains(location=location) found_networks = [network for network in networks if (network.name == name)] if (not found_networks): raise UnknownNetworkError(("Network '%s' could not be found" % name)) net_id = found_networks[0].id return driver.ex_get_network_domain(net_id)
[ "def", "get_network_domain", "(", "driver", ",", "locator", ",", "location", ")", ":", "if", "is_uuid", "(", "locator", ")", ":", "net_id", "=", "locator", "else", ":", "name", "=", "locator", "networks", "=", "driver", ".", "ex_list_network_domains", "(", ...
get a network domain object by its name or id .
train
false
32,713
def _to_pascal_case(snake_case): space_case = re.sub('_', ' ', snake_case) wordlist = [] for word in space_case.split(): wordlist.append(word[0].upper()) wordlist.append(word[1:]) return ''.join(wordlist)
[ "def", "_to_pascal_case", "(", "snake_case", ")", ":", "space_case", "=", "re", ".", "sub", "(", "'_'", ",", "' '", ",", "snake_case", ")", "wordlist", "=", "[", "]", "for", "word", "in", "space_case", ".", "split", "(", ")", ":", "wordlist", ".", "a...
convert a snake_case string to its pascalcase equivalent .
train
false
32,714
@pytest.mark.django_db def test_theme_selection(): with override_current_theme_class(): with override_provides('xtheme', ['shuup_tests.xtheme.utils:FauxTheme', 'shuup_tests.xtheme.utils:FauxTheme2', 'shuup_tests.xtheme.utils:H2G2Theme']): ThemeSettings.objects.all().delete() for theme in get_provide_objects('xtheme'): set_current_theme(theme.identifier) je = get_jinja2_engine() wrapper = (noop() if (theme.identifier == 'h2g2') else pytest.raises(TemplateDoesNotExist)) with wrapper: t = je.get_template('42.jinja') content = t.render().strip() assert ('a slice of lemon wrapped around a large gold brick' in content.replace('\n', ' '))
[ "@", "pytest", ".", "mark", ".", "django_db", "def", "test_theme_selection", "(", ")", ":", "with", "override_current_theme_class", "(", ")", ":", "with", "override_provides", "(", "'xtheme'", ",", "[", "'shuup_tests.xtheme.utils:FauxTheme'", ",", "'shuup_tests.xtheme...
test that a theme with a template_dir actually affects template directory selection .
train
false
32,717
def curstate(): return _state
[ "def", "curstate", "(", ")", ":", "return", "_state" ]
return the current state object returns: state : the current default state object .
train
false
32,718
def addOrbits(distanceFeedRate, loop, orbitalFeedRatePerSecond, temperatureChangeTime, z): timeInOrbit = 0.0 while (timeInOrbit < temperatureChangeTime): for point in loop: distanceFeedRate.addGcodeMovementZWithFeedRate((60.0 * orbitalFeedRatePerSecond), point, z) timeInOrbit += (euclidean.getLoopLength(loop) / orbitalFeedRatePerSecond)
[ "def", "addOrbits", "(", "distanceFeedRate", ",", "loop", ",", "orbitalFeedRatePerSecond", ",", "temperatureChangeTime", ",", "z", ")", ":", "timeInOrbit", "=", "0.0", "while", "(", "timeInOrbit", "<", "temperatureChangeTime", ")", ":", "for", "point", "in", "lo...
add orbits with the extruder off .
train
false
32,720
def get_form_target(): if ((get_comment_app_name() != DEFAULT_COMMENTS_APP) and hasattr(get_comment_app(), 'get_form_target')): return get_comment_app().get_form_target() else: return urlresolvers.reverse('django.contrib.comments.views.comments.post_comment')
[ "def", "get_form_target", "(", ")", ":", "if", "(", "(", "get_comment_app_name", "(", ")", "!=", "DEFAULT_COMMENTS_APP", ")", "and", "hasattr", "(", "get_comment_app", "(", ")", ",", "'get_form_target'", ")", ")", ":", "return", "get_comment_app", "(", ")", ...
returns the target url for the comment form submission view .
train
false
32,721
def test_denoise_tv_chambolle_1d(): x = (125 + (100 * np.sin(np.linspace(0, (8 * np.pi), 1000)))) x += (20 * np.random.rand(x.size)) x = np.clip(x, 0, 255) res = restoration.denoise_tv_chambolle(x.astype(np.uint8), weight=0.1) assert_((res.dtype == np.float)) assert_(((res.std() * 255) < x.std()))
[ "def", "test_denoise_tv_chambolle_1d", "(", ")", ":", "x", "=", "(", "125", "+", "(", "100", "*", "np", ".", "sin", "(", "np", ".", "linspace", "(", "0", ",", "(", "8", "*", "np", ".", "pi", ")", ",", "1000", ")", ")", ")", ")", "x", "+=", ...
apply the tv denoising algorithm on a 1d sinusoid .
train
false
32,722
def expected_freq(observed): observed = np.asarray(observed, dtype=np.float64) margsums = margins(observed) d = observed.ndim expected = (reduce(np.multiply, margsums) / (observed.sum() ** (d - 1))) return expected
[ "def", "expected_freq", "(", "observed", ")", ":", "observed", "=", "np", ".", "asarray", "(", "observed", ",", "dtype", "=", "np", ".", "float64", ")", "margsums", "=", "margins", "(", "observed", ")", "d", "=", "observed", ".", "ndim", "expected", "=...
compute the expected frequencies from a contingency table .
train
false
32,723
def _inherited(parent_attr, direct_attr): getter = (lambda self: (getattr(self.parent, parent_attr) if (self.parent and (self.parent.id != self.id)) else getattr(self, direct_attr))) setter = (lambda self, val: (setattr(self.parent, parent_attr, val) if (self.parent and (self.parent.id != self.id)) else setattr(self, direct_attr, val))) return property(getter, setter)
[ "def", "_inherited", "(", "parent_attr", ",", "direct_attr", ")", ":", "getter", "=", "(", "lambda", "self", ":", "(", "getattr", "(", "self", ".", "parent", ",", "parent_attr", ")", "if", "(", "self", ".", "parent", "and", "(", "self", ".", "parent", ...
return a descriptor delegating to an attr of the original document .
train
false
32,725
def test_cmp_issue_4357(): assert (not (Symbol == 1)) assert (Symbol != 1) assert (not (Symbol == 'x')) assert (Symbol != 'x')
[ "def", "test_cmp_issue_4357", "(", ")", ":", "assert", "(", "not", "(", "Symbol", "==", "1", ")", ")", "assert", "(", "Symbol", "!=", "1", ")", "assert", "(", "not", "(", "Symbol", "==", "'x'", ")", ")", "assert", "(", "Symbol", "!=", "'x'", ")" ]
check that basic subclasses can be compared with sympifiable objects .
train
false
32,727
def _process_communicate_handle_oserror(process, data, files): try: (output, err) = process.communicate(data) except OSError as e: if (e.errno != errno.EPIPE): raise (retcode, err) = _check_files_accessible(files) if process.stderr: msg = process.stderr.read() if isinstance(msg, six.binary_type): msg = msg.decode('utf-8') if err: err = (_('Hit OSError in _process_communicate_handle_oserror(): %(stderr)s\nLikely due to %(file)s: %(error)s') % {'stderr': msg, 'file': err[0], 'error': err[1]}) else: err = (_('Hit OSError in _process_communicate_handle_oserror(): %s') % msg) output = '' else: retcode = process.poll() if (err is not None): if isinstance(err, six.binary_type): err = err.decode('utf-8') return (output, err, retcode)
[ "def", "_process_communicate_handle_oserror", "(", "process", ",", "data", ",", "files", ")", ":", "try", ":", "(", "output", ",", "err", ")", "=", "process", ".", "communicate", "(", "data", ")", "except", "OSError", "as", "e", ":", "if", "(", "e", "....
wrapper around process .
train
false
32,728
def wait_for_status(client, stream_name, status, wait_timeout=300, check_mode=False): polling_increment_secs = 5 wait_timeout = (time.time() + wait_timeout) status_achieved = False stream = dict() err_msg = '' while (wait_timeout > time.time()): try: (find_success, find_msg, stream) = find_stream(client, stream_name, check_mode=check_mode) if check_mode: status_achieved = True break elif (status != 'DELETING'): if (find_success and stream): if (stream.get('StreamStatus') == status): status_achieved = True break elif ((status == 'DELETING') and (not check_mode)): if (not find_success): status_achieved = True break else: time.sleep(polling_increment_secs) except botocore.exceptions.ClientError as e: err_msg = str(e) if (not status_achieved): err_msg = 'Wait time out reached, while waiting for results' else: err_msg = 'Status {0} achieved successfully'.format(status) return (status_achieved, err_msg, stream)
[ "def", "wait_for_status", "(", "client", ",", "stream_name", ",", "status", ",", "wait_timeout", "=", "300", ",", "check_mode", "=", "False", ")", ":", "polling_increment_secs", "=", "5", "wait_timeout", "=", "(", "time", ".", "time", "(", ")", "+", "wait_...
wait for the nat gateway to reach a status args: client : boto3 client wait_timeout : number of seconds to wait .
train
false
32,729
def p_parameters(p): if (len(p) == 3): p[0] = [] else: p[0] = p[2]
[ "def", "p_parameters", "(", "p", ")", ":", "if", "(", "len", "(", "p", ")", "==", "3", ")", ":", "p", "[", "0", "]", "=", "[", "]", "else", ":", "p", "[", "0", "]", "=", "p", "[", "2", "]" ]
parameters : lpar rpar | lpar varargslist rpar .
train
false
32,730
def reset(): _runtime.reset()
[ "def", "reset", "(", ")", ":", "_runtime", ".", "reset", "(", ")" ]
reset a vm by emulating the reset button on a physical machine cli example: .
train
false
32,732
def dictfindall(dictionary, element): res = [] for (key, value) in iteritems(dictionary): if (element is value): res.append(key) return res
[ "def", "dictfindall", "(", "dictionary", ",", "element", ")", ":", "res", "=", "[", "]", "for", "(", "key", ",", "value", ")", "in", "iteritems", "(", "dictionary", ")", ":", "if", "(", "element", "is", "value", ")", ":", "res", ".", "append", "(",...
returns the keys whose values in dictionary are element or .
train
false
32,733
def get_default_gateway(): try: return next(iter((x.split()[(-1)] for x in __salt__['cmd.run'](['netsh', 'interface', 'ip', 'show', 'config'], python_shell=False).splitlines() if ('Default Gateway:' in x)))) except StopIteration: raise CommandExecutionError('Unable to find default gateway')
[ "def", "get_default_gateway", "(", ")", ":", "try", ":", "return", "next", "(", "iter", "(", "(", "x", ".", "split", "(", ")", "[", "(", "-", "1", ")", "]", "for", "x", "in", "__salt__", "[", "'cmd.run'", "]", "(", "[", "'netsh'", ",", "'interfac...
set dns source to dhcp on windows cli example: .
train
true
32,734
def sentiment_text(text): language_client = language.Client() document = language_client.document_from_text(text) sentiment = document.analyze_sentiment() print 'Score: {}'.format(sentiment.score) print 'Magnitude: {}'.format(sentiment.magnitude)
[ "def", "sentiment_text", "(", "text", ")", ":", "language_client", "=", "language", ".", "Client", "(", ")", "document", "=", "language_client", ".", "document_from_text", "(", "text", ")", "sentiment", "=", "document", ".", "analyze_sentiment", "(", ")", "pri...
detects sentiment in the text .
train
false
32,735
def bool_to_bitarray(value): value = value.flat bit_no = 7 byte = 0 bytes = [] for v in value: if v: byte |= (1 << bit_no) if (bit_no == 0): bytes.append(byte) bit_no = 7 byte = 0 else: bit_no -= 1 if (bit_no != 7): bytes.append(byte) return struct_pack(u'{}B'.format(len(bytes)), *bytes)
[ "def", "bool_to_bitarray", "(", "value", ")", ":", "value", "=", "value", ".", "flat", "bit_no", "=", "7", "byte", "=", "0", "bytes", "=", "[", "]", "for", "v", "in", "value", ":", "if", "v", ":", "byte", "|=", "(", "1", "<<", "bit_no", ")", "i...
converts a numpy boolean array to a bit array .
train
false
32,738
def first_level_directory(path): (head, tail) = split(path) while (head and tail): (head, tail) = split(head) if tail: return tail return head
[ "def", "first_level_directory", "(", "path", ")", ":", "(", "head", ",", "tail", ")", "=", "split", "(", "path", ")", "while", "(", "head", "and", "tail", ")", ":", "(", "head", ",", "tail", ")", "=", "split", "(", "head", ")", "if", "tail", ":",...
return the first level directory of a path .
train
false
32,739
@py.test.mark.parametrize('item_name', [item.name for item in six._urllib_robotparser_moved_attributes]) def test_move_items_urllib_robotparser(item_name): if (sys.version_info[:2] >= (2, 6)): assert (item_name in dir(six.moves.urllib.robotparser)) getattr(six.moves.urllib.robotparser, item_name)
[ "@", "py", ".", "test", ".", "mark", ".", "parametrize", "(", "'item_name'", ",", "[", "item", ".", "name", "for", "item", "in", "six", ".", "_urllib_robotparser_moved_attributes", "]", ")", "def", "test_move_items_urllib_robotparser", "(", "item_name", ")", "...
ensure that everything loads correctly .
train
false
32,740
def _combine_matchers(target, kwargs, require_spec): if (not target): if (not kwargs): if require_spec: raise ValueError('you must specify a target object or keyword arguments.') return (lambda x: True) return _attribute_matcher(kwargs) match_obj = _object_matcher(target) if (not kwargs): return match_obj match_kwargs = _attribute_matcher(kwargs) return (lambda x: (match_obj(x) and match_kwargs(x)))
[ "def", "_combine_matchers", "(", "target", ",", "kwargs", ",", "require_spec", ")", ":", "if", "(", "not", "target", ")", ":", "if", "(", "not", "kwargs", ")", ":", "if", "require_spec", ":", "raise", "ValueError", "(", "'you must specify a target object or ke...
merge target specifications with keyword arguments .
train
false
32,741
def _asarray(a, dtype, order=None): if (str(dtype) == 'floatX'): dtype = theano.config.floatX dtype = numpy.dtype(dtype) rval = numpy.asarray(a, dtype=dtype, order=order) if (rval.dtype.num != dtype.num): if (dtype.str == rval.dtype.str): return rval.view(dtype=dtype) else: raise TypeError(('numpy.array did not return the data type we asked for (%s %s #%s), instead it returned type %s %s #%s: function theano._asarray may need to be modified to handle this data type.' % (dtype, dtype.str, dtype.num, rval.dtype, rval.str, rval.dtype.num))) else: return rval
[ "def", "_asarray", "(", "a", ",", "dtype", ",", "order", "=", "None", ")", ":", "if", "(", "str", "(", "dtype", ")", "==", "'floatX'", ")", ":", "dtype", "=", "theano", ".", "config", ".", "floatX", "dtype", "=", "numpy", ".", "dtype", "(", "dtyp...
convert the input to a numpy array .
train
false
32,742
def FisherZ(name, d1, d2): return rv(name, FisherZDistribution, (d1, d2))
[ "def", "FisherZ", "(", "name", ",", "d1", ",", "d2", ")", ":", "return", "rv", "(", "name", ",", "FisherZDistribution", ",", "(", "d1", ",", "d2", ")", ")" ]
create a continuous random variable with an fishers z distribution .
train
false
32,743
def delete_test(id): models.Test.smart_get(id).delete()
[ "def", "delete_test", "(", "id", ")", ":", "models", ".", "Test", ".", "smart_get", "(", "id", ")", ".", "delete", "(", ")" ]
delete test .
train
false
32,745
def field_definition(resource, chained_fields): definition = config.DOMAIN[resource] subfields = chained_fields.split('.') for field in subfields: if (field not in definition.get('schema', {})): if ('data_relation' in definition): sub_resource = definition['data_relation']['resource'] definition = config.DOMAIN[sub_resource] if (field not in definition['schema']): return definition = definition['schema'][field] field_type = definition.get('type') if (field_type == 'list'): definition = definition['schema'] elif (field_type == 'objectid'): pass return definition
[ "def", "field_definition", "(", "resource", ",", "chained_fields", ")", ":", "definition", "=", "config", ".", "DOMAIN", "[", "resource", "]", "subfields", "=", "chained_fields", ".", "split", "(", "'.'", ")", "for", "field", "in", "subfields", ":", "if", ...
resolves query string to resource with dot notation like people .
train
false
32,746
def get_hot_items(srs, item_type, src): hot_srs = {sr._id: sr for sr in srs} hot_link_fullnames = normalized_hot([sr._id for sr in srs]) hot_links = Link._by_fullname(hot_link_fullnames, return_dict=False) hot_items = [] for l in hot_links: hot_items.append(ExploreItem(item_type, src, hot_srs[l.sr_id], l)) return hot_items
[ "def", "get_hot_items", "(", "srs", ",", "item_type", ",", "src", ")", ":", "hot_srs", "=", "{", "sr", ".", "_id", ":", "sr", "for", "sr", "in", "srs", "}", "hot_link_fullnames", "=", "normalized_hot", "(", "[", "sr", ".", "_id", "for", "sr", "in", ...
get hot links from specified srs .
train
false
32,747
def _section_membership(course, access, is_white_label): course_key = course.id ccx_enabled = (settings.FEATURES.get('CUSTOM_COURSES_EDX', False) and course.enable_ccx) section_data = {'section_key': 'membership', 'section_display_name': _('Membership'), 'access': access, 'ccx_is_enabled': ccx_enabled, 'is_white_label': is_white_label, 'enroll_button_url': reverse('students_update_enrollment', kwargs={'course_id': unicode(course_key)}), 'unenroll_button_url': reverse('students_update_enrollment', kwargs={'course_id': unicode(course_key)}), 'upload_student_csv_button_url': reverse('register_and_enroll_students', kwargs={'course_id': unicode(course_key)}), 'modify_beta_testers_button_url': reverse('bulk_beta_modify_access', kwargs={'course_id': unicode(course_key)}), 'list_course_role_members_url': reverse('list_course_role_members', kwargs={'course_id': unicode(course_key)}), 'modify_access_url': reverse('modify_access', kwargs={'course_id': unicode(course_key)}), 'list_forum_members_url': reverse('list_forum_members', kwargs={'course_id': unicode(course_key)}), 'update_forum_role_membership_url': reverse('update_forum_role_membership', kwargs={'course_id': unicode(course_key)})} return section_data
[ "def", "_section_membership", "(", "course", ",", "access", ",", "is_white_label", ")", ":", "course_key", "=", "course", ".", "id", "ccx_enabled", "=", "(", "settings", ".", "FEATURES", ".", "get", "(", "'CUSTOM_COURSES_EDX'", ",", "False", ")", "and", "cou...
provide data for the corresponding dashboard section .
train
false
32,748
def thorium(opts, functions, runners): pack = {'__salt__': functions, '__runner__': runners, '__context__': {}} ret = LazyLoader(_module_dirs(opts, 'thorium'), opts, tag='thorium', pack=pack) ret.pack['__thorium__'] = ret return ret
[ "def", "thorium", "(", "opts", ",", "functions", ",", "runners", ")", ":", "pack", "=", "{", "'__salt__'", ":", "functions", ",", "'__runner__'", ":", "runners", ",", "'__context__'", ":", "{", "}", "}", "ret", "=", "LazyLoader", "(", "_module_dirs", "("...
load the thorium runtime modules .
train
true
32,752
def with_setup(setup=None, teardown=None): def decorate(func, setup=setup, teardown=teardown): if setup: if hasattr(func, 'setup'): _old_s = func.setup def _s(): setup() _old_s() func.setup = _s else: func.setup = setup if teardown: if hasattr(func, 'teardown'): _old_t = func.teardown def _t(): _old_t() teardown() func.teardown = _t else: func.teardown = teardown return func return decorate
[ "def", "with_setup", "(", "setup", "=", "None", ",", "teardown", "=", "None", ")", ":", "def", "decorate", "(", "func", ",", "setup", "=", "setup", ",", "teardown", "=", "teardown", ")", ":", "if", "setup", ":", "if", "hasattr", "(", "func", ",", "...
decorator to add setup and/or teardown methods to a test function:: @with_setup def test_something(): note that with_setup is useful *only* for test functions .
train
true
32,754
def getNormal(begin, center, end): centerMinusBegin = (center - begin).getNormalized() endMinusCenter = (end - center).getNormalized() return centerMinusBegin.cross(endMinusCenter)
[ "def", "getNormal", "(", "begin", ",", "center", ",", "end", ")", ":", "centerMinusBegin", "=", "(", "center", "-", "begin", ")", ".", "getNormalized", "(", ")", "endMinusCenter", "=", "(", "end", "-", "center", ")", ".", "getNormalized", "(", ")", "re...
get normal .
train
false
32,756
def get_lr_scalers_from_layers(owner): rval = OrderedDict() params = owner.get_params() for layer in owner.layers: contrib = layer.get_lr_scalers() assert isinstance(contrib, OrderedDict) assert (not any([(key in rval) for key in contrib])) assert all([(key in params) for key in contrib]) rval.update(contrib) assert all([isinstance(val, float) for val in rval.values()]) return rval
[ "def", "get_lr_scalers_from_layers", "(", "owner", ")", ":", "rval", "=", "OrderedDict", "(", ")", "params", "=", "owner", ".", "get_params", "(", ")", "for", "layer", "in", "owner", ".", "layers", ":", "contrib", "=", "layer", ".", "get_lr_scalers", "(", ...
get the learning rate scalers for all member layers of owner .
train
false
32,757
def lock_holders(path, zk_hosts, identifier=None, max_concurrency=1, timeout=None, ephemeral_lease=False): zk = _get_zk_conn(zk_hosts) if (path not in SEMAPHORE_MAP): SEMAPHORE_MAP[path] = _Semaphore(zk, path, identifier, max_leases=max_concurrency, ephemeral_lease=ephemeral_lease) return SEMAPHORE_MAP[path].lease_holders()
[ "def", "lock_holders", "(", "path", ",", "zk_hosts", ",", "identifier", "=", "None", ",", "max_concurrency", "=", "1", ",", "timeout", "=", "None", ",", "ephemeral_lease", "=", "False", ")", ":", "zk", "=", "_get_zk_conn", "(", "zk_hosts", ")", "if", "("...
return an un-ordered list of lock holders path the path in zookeeper where the lock is zk_hosts zookeeper connect string identifier name to identify this minion .
train
false
32,758
@register.simple_tag(name='favicon_path') def favicon_path(default=getattr(settings, 'FAVICON_PATH', 'images/favicon.ico')): return staticfiles_storage.url(configuration_helpers.get_value('favicon_path', default))
[ "@", "register", ".", "simple_tag", "(", "name", "=", "'favicon_path'", ")", "def", "favicon_path", "(", "default", "=", "getattr", "(", "settings", ",", "'FAVICON_PATH'", ",", "'images/favicon.ico'", ")", ")", ":", "return", "staticfiles_storage", ".", "url", ...
django template tag that outputs the configured favicon: {% favicon_path %} .
train
false
32,759
def file_contents(matcher): def get_content(file_path): return file_path.getContent() def content_mismatches(original): return mismatch(original.mismatched, ('%s has unexpected contents:\n%s' % (original.mismatched.path, original.describe())), original.get_details()) return MatchesAll(file_exists(), OnMismatch(content_mismatches, AfterPreprocessing(get_content, matcher, annotate=False)), first_only=True)
[ "def", "file_contents", "(", "matcher", ")", ":", "def", "get_content", "(", "file_path", ")", ":", "return", "file_path", ".", "getContent", "(", ")", "def", "content_mismatches", "(", "original", ")", ":", "return", "mismatch", "(", "original", ".", "misma...
match if a files contents match matcher .
train
false
32,760
def create_function_query(session, model, functions): processed = [] for function in functions: if ('name' not in function): raise KeyError('Missing `name` key in function object') if ('field' not in function): raise KeyError('Missing `field` key in function object') (funcname, fieldname) = (function['name'], function['field']) funcobj = getattr(func, funcname) try: field = getattr(model, fieldname) except AttributeError as exception: exception.field = fieldname raise exception processed.append(funcobj(field)) return session.query(*processed)
[ "def", "create_function_query", "(", "session", ",", "model", ",", "functions", ")", ":", "processed", "=", "[", "]", "for", "function", "in", "functions", ":", "if", "(", "'name'", "not", "in", "function", ")", ":", "raise", "KeyError", "(", "'Missing `na...
creates a sqlalchemy query representing the given sqlalchemy functions .
train
false
32,761
def _get_visible_update(course_update_items): if isinstance(course_update_items, dict): if (course_update_items.get('status') != CourseInfoModule.STATUS_DELETED): return _make_update_dict(course_update_items) else: return {'error': _('Course update not found.'), 'status': 404} return [_make_update_dict(update) for update in course_update_items if (update.get('status') != CourseInfoModule.STATUS_DELETED)]
[ "def", "_get_visible_update", "(", "course_update_items", ")", ":", "if", "isinstance", "(", "course_update_items", ",", "dict", ")", ":", "if", "(", "course_update_items", ".", "get", "(", "'status'", ")", "!=", "CourseInfoModule", ".", "STATUS_DELETED", ")", "...
filter course update items which have status "deleted" .
train
false
32,762
def get_cluster_ref_from_name(session, cluster_name): cls = session._call_method(vim_util, 'get_objects', 'ClusterComputeResource', ['name']) for cluster in cls: if (cluster.propSet[0].val == cluster_name): return cluster.obj return None
[ "def", "get_cluster_ref_from_name", "(", "session", ",", "cluster_name", ")", ":", "cls", "=", "session", ".", "_call_method", "(", "vim_util", ",", "'get_objects'", ",", "'ClusterComputeResource'", ",", "[", "'name'", "]", ")", "for", "cluster", "in", "cls", ...
get reference to the cluster with the name specified .
train
false
32,763
def rad(d): return ((d * pi) / 180)
[ "def", "rad", "(", "d", ")", ":", "return", "(", "(", "d", "*", "pi", ")", "/", "180", ")" ]
convert degrees in radiants .
train
false
32,764
def error_msg_from_exception(e): msg = u'' if hasattr(e, u'message'): if (type(e.message) is dict): msg = e.message.get(u'message') elif e.message: msg = u'{}'.format(e.message) return (msg or u'{}'.format(e))
[ "def", "error_msg_from_exception", "(", "e", ")", ":", "msg", "=", "u''", "if", "hasattr", "(", "e", ",", "u'message'", ")", ":", "if", "(", "type", "(", "e", ".", "message", ")", "is", "dict", ")", ":", "msg", "=", "e", ".", "message", ".", "get...
translate exception into error message database have different ways to handle exception .
train
false
32,765
def strip_string(msg, flags): stripped = strip_format(msg, flags) stripped = EMAIL_RE.sub(u'', stripped) stripped = URL_RE.sub(u'', stripped) stripped = HASH_RE.sub(u'', stripped) stripped = DOMAIN_RE.sub(u'', stripped) stripped = PATH_RE.sub(u'', stripped) stripped = TEMPLATE_RE.sub(u'', stripped) return stripped
[ "def", "strip_string", "(", "msg", ",", "flags", ")", ":", "stripped", "=", "strip_format", "(", "msg", ",", "flags", ")", "stripped", "=", "EMAIL_RE", ".", "sub", "(", "u''", ",", "stripped", ")", "stripped", "=", "URL_RE", ".", "sub", "(", "u''", "...
strips not translated parts from the string .
train
false
32,766
def l2_norm(f, lim): return sqrt(integrate((Abs(f) ** 2), lim))
[ "def", "l2_norm", "(", "f", ",", "lim", ")", ":", "return", "sqrt", "(", "integrate", "(", "(", "Abs", "(", "f", ")", "**", "2", ")", ",", "lim", ")", ")" ]
returns the l2-norm of the given vector .
train
false
32,767
def test_feature_max_length_on_step_with_table_keys(): feature = Feature.from_string(FEATURE7) assert_equals(feature.max_length, 74)
[ "def", "test_feature_max_length_on_step_with_table_keys", "(", ")", ":", "feature", "=", "Feature", ".", "from_string", "(", "FEATURE7", ")", "assert_equals", "(", "feature", ".", "max_length", ",", "74", ")" ]
the max length of a feature considering when the table keys of some of the steps are longer than the remaining things .
train
false
32,768
def _get_weight_from_block(persisted_block, block): if persisted_block: return persisted_block.weight else: return getattr(block, 'weight', None)
[ "def", "_get_weight_from_block", "(", "persisted_block", ",", "block", ")", ":", "if", "persisted_block", ":", "return", "persisted_block", ".", "weight", "else", ":", "return", "getattr", "(", "block", ",", "'weight'", ",", "None", ")" ]
returns the weighted value from the persisted_block if found .
train
false
32,770
def pportD0(state): global dataReg if (state == 0): dataReg = (dataReg & (~ 1)) else: dataReg = (dataReg | 1) port.DlPortWritePortUchar(baseAddress, dataReg)
[ "def", "pportD0", "(", "state", ")", ":", "global", "dataReg", "if", "(", "state", "==", "0", ")", ":", "dataReg", "=", "(", "dataReg", "&", "(", "~", "1", ")", ")", "else", ":", "dataReg", "=", "(", "dataReg", "|", "1", ")", "port", ".", "DlPo...
toggle data register d0 bit .
train
false
32,772
def get_average_rating(ratings): rating_weightings = {'1': 1, '2': 2, '3': 3, '4': 4, '5': 5} if ratings: rating_sum = 0.0 number_of_ratings = get_number_of_ratings(ratings) if (number_of_ratings == 0): return 0 for (rating_value, rating_count) in ratings.items(): rating_sum += (rating_weightings[rating_value] * rating_count) return (rating_sum / (number_of_ratings * 1.0))
[ "def", "get_average_rating", "(", "ratings", ")", ":", "rating_weightings", "=", "{", "'1'", ":", "1", ",", "'2'", ":", "2", ",", "'3'", ":", "3", ",", "'4'", ":", "4", ",", "'5'", ":", "5", "}", "if", "ratings", ":", "rating_sum", "=", "0.0", "n...
returns the average rating of the ratings as a float .
train
false
32,773
def get_basedir(path): return (path[:path.index(os.sep)] if (os.sep in path) else path)
[ "def", "get_basedir", "(", "path", ")", ":", "return", "(", "path", "[", ":", "path", ".", "index", "(", "os", ".", "sep", ")", "]", "if", "(", "os", ".", "sep", "in", "path", ")", "else", "path", ")" ]
returns the base directory of a path .
train
true
32,774
def with_site_configuration(domain='test.localhost', configuration=None): def _decorator(func): @wraps(func) def _decorated(*args, **kwargs): (site, __) = Site.objects.get_or_create(domain=domain, name=domain) (site_configuration, created) = SiteConfiguration.objects.get_or_create(site=site, defaults={'enabled': True, 'values': configuration}) if (not created): site_configuration.values = configuration site_configuration.save() with patch('openedx.core.djangoapps.site_configuration.helpers.get_current_site_configuration', return_value=site_configuration): with patch('openedx.core.djangoapps.theming.helpers.get_current_site', return_value=site): with patch('django.contrib.sites.models.SiteManager.get_current', return_value=site): return func(*args, **kwargs) return _decorated return _decorator
[ "def", "with_site_configuration", "(", "domain", "=", "'test.localhost'", ",", "configuration", "=", "None", ")", ":", "def", "_decorator", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "_decorated", "(", "*", "args", ",", "**", "kwargs", ...
a decorator to run a test with a configuration enabled .
train
false
32,775
def _make_url_query(args): return ('?' + '&'.join((('%s=%s' % (key, args[key])) for key in args)))
[ "def", "_make_url_query", "(", "args", ")", ":", "return", "(", "'?'", "+", "'&'", ".", "join", "(", "(", "(", "'%s=%s'", "%", "(", "key", ",", "args", "[", "key", "]", ")", ")", "for", "key", "in", "args", ")", ")", ")" ]
helper function to return a query url string from a dict .
train
false
32,776
def GetArtifactKnowledgeBase(client_obj, allow_uninitialized=False): client_schema = client_obj.Schema kb = client_obj.Get(client_schema.KNOWLEDGE_BASE) if (not allow_uninitialized): if (not kb): raise artifact_utils.KnowledgeBaseUninitializedError(('KnowledgeBase empty for %s.' % client_obj.urn)) if (not kb.os): raise artifact_utils.KnowledgeBaseAttributesMissingError(('KnowledgeBase missing OS for %s. Knowledgebase content: %s' % (client_obj.urn, kb))) if (not kb): kb = client_schema.KNOWLEDGE_BASE() SetCoreGRRKnowledgeBaseValues(kb, client_obj) if (kb.os == 'Windows'): if ((not kb.environ_allusersappdata) and kb.environ_allusersprofile): if (kb.os_major_version >= 6): kb.environ_allusersappdata = u'c:\\programdata' kb.environ_allusersprofile = u'c:\\programdata' else: kb.environ_allusersappdata = u'c:\\documents and settings\\All Users\\Application Data' kb.environ_allusersprofile = u'c:\\documents and settings\\All Users' return kb
[ "def", "GetArtifactKnowledgeBase", "(", "client_obj", ",", "allow_uninitialized", "=", "False", ")", ":", "client_schema", "=", "client_obj", ".", "Schema", "kb", "=", "client_obj", ".", "Get", "(", "client_schema", ".", "KNOWLEDGE_BASE", ")", "if", "(", "not", ...
this generates an artifact knowledge base from a grr client .
train
false
32,777
def is_cuda_ndarray(obj): return getattr(obj, '__cuda_ndarray__', False)
[ "def", "is_cuda_ndarray", "(", "obj", ")", ":", "return", "getattr", "(", "obj", ",", "'__cuda_ndarray__'", ",", "False", ")" ]
check if an object is a cuda ndarray .
train
false
32,779
def genHalfAndHalf(pset, min_, max_, type_=None): method = random.choice((genGrow, genFull)) return method(pset, min_, max_, type_)
[ "def", "genHalfAndHalf", "(", "pset", ",", "min_", ",", "max_", ",", "type_", "=", "None", ")", ":", "method", "=", "random", ".", "choice", "(", "(", "genGrow", ",", "genFull", ")", ")", "return", "method", "(", "pset", ",", "min_", ",", "max_", "...
generate an expression with a primitiveset *pset* .
train
false
32,780
def add_block_ids(payload): if ('data' in payload): for ele in payload['data']: if ('module_id' in ele): ele['block_id'] = UsageKey.from_string(ele['module_id']).block_id
[ "def", "add_block_ids", "(", "payload", ")", ":", "if", "(", "'data'", "in", "payload", ")", ":", "for", "ele", "in", "payload", "[", "'data'", "]", ":", "if", "(", "'module_id'", "in", "ele", ")", ":", "ele", "[", "'block_id'", "]", "=", "UsageKey",...
rather than manually parsing block_ids from module_ids on the client .
train
false
32,782
def b58encode(value): encoded = '' while (value >= __b58base): (div, mod) = divmod(value, __b58base) encoded = (__b58chars[mod] + encoded) value = div encoded = (__b58chars[value] + encoded) return encoded
[ "def", "b58encode", "(", "value", ")", ":", "encoded", "=", "''", "while", "(", "value", ">=", "__b58base", ")", ":", "(", "div", ",", "mod", ")", "=", "divmod", "(", "value", ",", "__b58base", ")", "encoded", "=", "(", "__b58chars", "[", "mod", "]...
encode v .
train
false
32,783
def pem_finger(path=None, key=None, sum_type='sha256'): if (not key): if (not os.path.isfile(path)): return '' with fopen(path, 'rb') as fp_: key = ''.join([x for x in fp_.readlines() if x.strip()][1:(-1)]) pre = getattr(hashlib, sum_type)(key).hexdigest() finger = '' for ind in range(len(pre)): if (ind % 2): finger += '{0}:'.format(pre[ind]) else: finger += pre[ind] return finger.rstrip(':')
[ "def", "pem_finger", "(", "path", "=", "None", ",", "key", "=", "None", ",", "sum_type", "=", "'sha256'", ")", ":", "if", "(", "not", "key", ")", ":", "if", "(", "not", "os", ".", "path", ".", "isfile", "(", "path", ")", ")", ":", "return", "''...
pass in either a raw pem string .
train
false
32,786
def _is_shorthand_ip(ip_str): if (ip_str.count('::') == 1): return True if filter((lambda x: (len(x) < 4)), ip_str.split(':')): return True return False
[ "def", "_is_shorthand_ip", "(", "ip_str", ")", ":", "if", "(", "ip_str", ".", "count", "(", "'::'", ")", "==", "1", ")", ":", "return", "True", "if", "filter", "(", "(", "lambda", "x", ":", "(", "len", "(", "x", ")", "<", "4", ")", ")", ",", ...
determine if the address is shortened .
train
false
32,788
def _gather_logs(start, stop='HEAD'): get_logs_cmd = GIT_CMD_GET_LOGS_FORMAT_STRING.format(GROUP_SEP, start, stop) out = _run_cmd(get_logs_cmd).split('\x00') if ((len(out) == 1) and (out[0] == '')): return [] else: return [Log(*line.strip().split(GROUP_SEP)) for line in out]
[ "def", "_gather_logs", "(", "start", ",", "stop", "=", "'HEAD'", ")", ":", "get_logs_cmd", "=", "GIT_CMD_GET_LOGS_FORMAT_STRING", ".", "format", "(", "GROUP_SEP", ",", "start", ",", "stop", ")", "out", "=", "_run_cmd", "(", "get_logs_cmd", ")", ".", "split",...
gathers the logs between the start and endpoint .
train
false
32,789
def themes(): for i in os.listdir(_THEMES_PATH): e = os.path.join(_THEMES_PATH, i) if os.path.isdir(e): if os.path.islink(e): (yield (e, os.readlink(e))) else: (yield (e, None))
[ "def", "themes", "(", ")", ":", "for", "i", "in", "os", ".", "listdir", "(", "_THEMES_PATH", ")", ":", "e", "=", "os", ".", "path", ".", "join", "(", "_THEMES_PATH", ",", "i", ")", "if", "os", ".", "path", ".", "isdir", "(", "e", ")", ":", "i...
returns the list of the themes .
train
false
32,790
@task(rate_limit='15/m') @timeit def compress_image(for_obj, for_field): for_ = getattr(for_obj, for_field) if (not (for_ and os.path.isfile(for_.path))): log_msg = 'No file to compress for: {model} {id}, {for_f}' log.info(log_msg.format(model=for_obj.__class__.__name__, id=for_obj.id, for_f=for_field)) return if (not (os.path.splitext(for_.path)[1].lower() == '.png')): log_msg = 'File is not PNG for: {model} {id}, {for_f}' log.info(log_msg.format(model=for_obj.__class__.__name__, id=for_obj.id, for_f=for_field)) return log_msg = 'Compressing {model} {id}: {for_f}' log.info(log_msg.format(model=for_obj.__class__.__name__, id=for_obj.id, for_f=for_field)) file_path = for_.path if (settings.OPTIPNG_PATH is not None): subprocess.call([settings.OPTIPNG_PATH, '-quiet', '-preserve', file_path])
[ "@", "task", "(", "rate_limit", "=", "'15/m'", ")", "@", "timeit", "def", "compress_image", "(", "for_obj", ",", "for_field", ")", ":", "for_", "=", "getattr", "(", "for_obj", ",", "for_field", ")", "if", "(", "not", "(", "for_", "and", "os", ".", "p...
compress an image of given field for given object .
train
false
32,791
def __InitConnection(): if (os.getenv(_ENV_KEY) and hasattr(_thread_local, 'connection_stack')): return _thread_local.connection_stack = [datastore_rpc.Connection(adapter=_adapter)] os.environ[_ENV_KEY] = '1'
[ "def", "__InitConnection", "(", ")", ":", "if", "(", "os", ".", "getenv", "(", "_ENV_KEY", ")", "and", "hasattr", "(", "_thread_local", ",", "'connection_stack'", ")", ")", ":", "return", "_thread_local", ".", "connection_stack", "=", "[", "datastore_rpc", "...
internal method to make sure the connection state has been initialized .
train
false
32,792
def get_proc_dir(cachedir, **kwargs): fn_ = os.path.join(cachedir, 'proc') mode = kwargs.pop('mode', None) if (mode is None): mode = {} else: mode = {'mode': mode} if (not os.path.isdir(fn_)): os.makedirs(fn_, **mode) d_stat = os.stat(fn_) if mode: mode_part = S_IMODE(d_stat.st_mode) if (mode_part != mode['mode']): os.chmod(fn_, ((d_stat.st_mode ^ mode_part) | mode['mode'])) if hasattr(os, 'chown'): uid = kwargs.pop('uid', (-1)) gid = kwargs.pop('gid', (-1)) if (((d_stat.st_uid != uid) or (d_stat.st_gid != gid)) and [i for i in (uid, gid) if (i != (-1))]): os.chown(fn_, uid, gid) return fn_
[ "def", "get_proc_dir", "(", "cachedir", ",", "**", "kwargs", ")", ":", "fn_", "=", "os", ".", "path", ".", "join", "(", "cachedir", ",", "'proc'", ")", "mode", "=", "kwargs", ".", "pop", "(", "'mode'", ",", "None", ")", "if", "(", "mode", "is", "...
given the cache directory .
train
true
32,793
def assert_datasource_unframe_protocol(event): assert (event.type in DATASOURCE_TYPE)
[ "def", "assert_datasource_unframe_protocol", "(", "event", ")", ":", "assert", "(", "event", ".", "type", "in", "DATASOURCE_TYPE", ")" ]
assert that an event is valid output of zp .
train
false
32,794
def getAngleAroundZAxisDifference(subtractFromVec3, subtractVec3): subtractVectorMirror = complex(subtractVec3.x, (- subtractVec3.y)) differenceVector = getRoundZAxisByPlaneAngle(subtractVectorMirror, subtractFromVec3) return math.atan2(differenceVector.y, differenceVector.x)
[ "def", "getAngleAroundZAxisDifference", "(", "subtractFromVec3", ",", "subtractVec3", ")", ":", "subtractVectorMirror", "=", "complex", "(", "subtractVec3", ".", "x", ",", "(", "-", "subtractVec3", ".", "y", ")", ")", "differenceVector", "=", "getRoundZAxisByPlaneAn...
get the angle around the z axis difference between a pair of vector3s .
train
false
32,795
def add_regexp_listener(dbapi_con, con_record): def regexp(expr, item): reg = re.compile(expr) return (reg.search(unicode(item)) is not None) dbapi_con.create_function('regexp', 2, regexp)
[ "def", "add_regexp_listener", "(", "dbapi_con", ",", "con_record", ")", ":", "def", "regexp", "(", "expr", ",", "item", ")", ":", "reg", "=", "re", ".", "compile", "(", "expr", ")", "return", "(", "reg", ".", "search", "(", "unicode", "(", "item", ")...
add regexp function to sqlite connections .
train
false
32,796
def get_head_types(pat): if isinstance(pat, (pytree.NodePattern, pytree.LeafPattern)): return set([pat.type]) if isinstance(pat, pytree.NegatedPattern): if pat.content: return get_head_types(pat.content) return set([None]) if isinstance(pat, pytree.WildcardPattern): r = set() for p in pat.content: for x in p: r.update(get_head_types(x)) return r raise Exception(("Oh no! I don't understand pattern %s" % pat))
[ "def", "get_head_types", "(", "pat", ")", ":", "if", "isinstance", "(", "pat", ",", "(", "pytree", ".", "NodePattern", ",", "pytree", ".", "LeafPattern", ")", ")", ":", "return", "set", "(", "[", "pat", ".", "type", "]", ")", "if", "isinstance", "(",...
accepts a pytree pattern node and returns a set of the pattern types which will match first .
train
true
32,797
def flash(message, category='message'): flashes = session.get('_flashes', []) flashes.append((category, message)) session['_flashes'] = flashes message_flashed.send(current_app._get_current_object(), message=message, category=category)
[ "def", "flash", "(", "message", ",", "category", "=", "'message'", ")", ":", "flashes", "=", "session", ".", "get", "(", "'_flashes'", ",", "[", "]", ")", "flashes", ".", "append", "(", "(", "category", ",", "message", ")", ")", "session", "[", "'_fl...
flashes a message to the next request .
train
true
32,799
def orchestrate_single(fun, name, test=None, queue=False, pillar=None, **kwargs): if ((pillar is not None) and (not isinstance(pillar, dict))): raise SaltInvocationError('Pillar data must be formatted as a dictionary') __opts__['file_client'] = 'local' minion = salt.minion.MasterMinion(__opts__) running = minion.functions['state.single'](fun, name, test=None, queue=False, pillar=pillar, **kwargs) ret = {minion.opts['id']: running} __jid_event__.fire_event({'data': ret, 'outputter': 'highstate'}, 'progress') return ret
[ "def", "orchestrate_single", "(", "fun", ",", "name", ",", "test", "=", "None", ",", "queue", "=", "False", ",", "pillar", "=", "None", ",", "**", "kwargs", ")", ":", "if", "(", "(", "pillar", "is", "not", "None", ")", "and", "(", "not", "isinstanc...
execute a single state orchestration routine .
train
true
32,800
def LogIf(condition, message): if condition: __Log__.debug(message)
[ "def", "LogIf", "(", "condition", ",", "message", ")", ":", "if", "condition", ":", "__Log__", ".", "debug", "(", "message", ")" ]
log a message if the condition is met .
train
false
32,801
def with_support(*args, **kwargs): settings = default_settings.copy() settings.update(kwargs) def generator(func): @wraps(func) def new_func(*args2, **kwargs2): support = WebSupport(**settings) func(support, *args2, **kwargs2) return new_func return generator
[ "def", "with_support", "(", "*", "args", ",", "**", "kwargs", ")", ":", "settings", "=", "default_settings", ".", "copy", "(", ")", "settings", ".", "update", "(", "kwargs", ")", "def", "generator", "(", "func", ")", ":", "@", "wraps", "(", "func", "...
make a websupport object and pass it the test .
train
false
32,802
def _encode_optimized(item): if isinstance(item, bytes): if ((len(item) == 1) and (ord(item) < 128)): return item prefix = length_prefix(len(item), 128) else: item = ''.join([_encode_optimized(x) for x in item]) prefix = length_prefix(len(item), 192) return (prefix + item)
[ "def", "_encode_optimized", "(", "item", ")", ":", "if", "isinstance", "(", "item", ",", "bytes", ")", ":", "if", "(", "(", "len", "(", "item", ")", "==", "1", ")", "and", "(", "ord", "(", "item", ")", "<", "128", ")", ")", ":", "return", "item...
rlp encode bytes .
train
true
32,803
def corrcoef(*args): warnings.warn('Use numpy.corrcoef', DeprecationWarning) kw = dict(rowvar=False) return np.corrcoef(*args, **kw)
[ "def", "corrcoef", "(", "*", "args", ")", ":", "warnings", ".", "warn", "(", "'Use numpy.corrcoef'", ",", "DeprecationWarning", ")", "kw", "=", "dict", "(", "rowvar", "=", "False", ")", "return", "np", ".", "corrcoef", "(", "*", "args", ",", "**", "kw"...
corrcoef where *x* is a matrix returns a matrix of correlation coefficients for the columns of *x* corrcoef where *x* and *y* are vectors returns the matrix of correlation coefficients for *x* and *y* .
train
false
32,804
def doc_shortcode(*args, **kwargs): text = kwargs['data'] (success, twin_slugs, title, permalink, slug) = _doc_link(text, text, LOGGER) if success: if twin_slugs: LOGGER.warn('More than one post with the same slug. Using "{0}" for doc shortcode'.format(permalink)) return '<a href="{0}">{1}</a>'.format(permalink, title) else: LOGGER.error('"{0}" slug doesn\'t exist.'.format(slug)) return '<span class="error text-error" style="color: red;">Invalid link: {0}</span>'.format(text)
[ "def", "doc_shortcode", "(", "*", "args", ",", "**", "kwargs", ")", ":", "text", "=", "kwargs", "[", "'data'", "]", "(", "success", ",", "twin_slugs", ",", "title", ",", "permalink", ",", "slug", ")", "=", "_doc_link", "(", "text", ",", "text", ",", ...
implement the doc shortcode .
train
false
32,805
@cleanup def test_determinism_markers(): _determinism_check(u'm', format=u'pdf')
[ "@", "cleanup", "def", "test_determinism_markers", "(", ")", ":", "_determinism_check", "(", "u'm'", ",", "format", "=", "u'pdf'", ")" ]
test for reproducible pdf output: figure with different markers .
train
false
32,806
def get_format_from_width(width, unsigned=True): if (width == 1): if unsigned: return paUInt8 else: return paInt8 elif (width == 2): return paInt16 elif (width == 3): return paInt24 elif (width == 4): return paFloat32 else: raise ValueError(('Invalid width: %d' % width))
[ "def", "get_format_from_width", "(", "width", ",", "unsigned", "=", "True", ")", ":", "if", "(", "width", "==", "1", ")", ":", "if", "unsigned", ":", "return", "paUInt8", "else", ":", "return", "paInt8", "elif", "(", "width", "==", "2", ")", ":", "re...
returns a portaudio format constant for the specified *width* .
train
false
32,807
def test_iht_sk_estimator(): check_estimator(InstanceHardnessThreshold)
[ "def", "test_iht_sk_estimator", "(", ")", ":", "check_estimator", "(", "InstanceHardnessThreshold", ")" ]
test the sklearn estimator compatibility .
train
false
32,808
def obtain_hostname(show_ver): match = re.search('(.+) uptime is .+', show_ver) if match: return match.group(1) else: return None
[ "def", "obtain_hostname", "(", "show_ver", ")", ":", "match", "=", "re", ".", "search", "(", "'(.+) uptime is .+'", ",", "show_ver", ")", "if", "match", ":", "return", "match", ".", "group", "(", "1", ")", "else", ":", "return", "None" ]
example string from cisco ios: twb-sf-881 uptime is 14 weeks .
train
false
32,809
def _create_cookie_data(email, admin): if email: user_id_digest = hashlib.md5(email.lower()).digest() user_id = ('1' + ''.join([('%02d' % ord(x)) for x in user_id_digest])[:20]) else: user_id = '' return ('%s:%s:%s' % (email, admin, user_id))
[ "def", "_create_cookie_data", "(", "email", ",", "admin", ")", ":", "if", "email", ":", "user_id_digest", "=", "hashlib", ".", "md5", "(", "email", ".", "lower", "(", ")", ")", ".", "digest", "(", ")", "user_id", "=", "(", "'1'", "+", "''", ".", "j...
creates cookie payload data .
train
false
32,812
def reprovision_and_retry(func): @functools.wraps(func) def wrapper(*a, **kw): errback = kw.get('errback', None) if (errback is None): def errback(e): raise e def errback_wrapper(e): if (isinstance(e, UnknownAppID) and ('INITIAL' in OPTIONS)): try: for initial in OPTIONS['INITIAL']: provision(*initial) func(*a, **kw) except Exception as new_exc: errback(new_exc) else: errback(e) kw['errback'] = errback_wrapper return func(*a, **kw) return wrapper
[ "def", "reprovision_and_retry", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "a", ",", "**", "kw", ")", ":", "errback", "=", "kw", ".", "get", "(", "'errback'", ",", "None", ")", "if", "(", ...
wraps the errback callback of the api functions .
train
true
32,813
def validate_signature_against_kwargs(function, keyword_arguments): arg_spec = getargspec(function) accepted_arguments = frozenset(arg_spec.args) optional_arguments = frozenset() if (arg_spec.defaults is not None): optional_arguments = frozenset(arg_spec.args[(- len(arg_spec.defaults)):]) if (arg_spec.keywords is None): unexpected_arguments = frozenset((keyword_arguments - accepted_arguments)) else: unexpected_arguments = frozenset() missing_arguments = frozenset(((accepted_arguments - keyword_arguments) - optional_arguments)) if ((missing_arguments != frozenset()) or (unexpected_arguments != frozenset())): raise InvalidSignature(unexpected_arguments=unexpected_arguments, missing_arguments=missing_arguments, missing_optional_arguments=frozenset((optional_arguments - keyword_arguments)))
[ "def", "validate_signature_against_kwargs", "(", "function", ",", "keyword_arguments", ")", ":", "arg_spec", "=", "getargspec", "(", "function", ")", "accepted_arguments", "=", "frozenset", "(", "arg_spec", ".", "args", ")", "optional_arguments", "=", "frozenset", "...
validates that function can be called with keyword arguments with exactly the specified keyword_arguments_keys and no positional arguments .
train
false
32,814
def binary_predicate(func, *args): argtypes = [GEOM_PTR, GEOM_PTR] if args: argtypes += args func.argtypes = argtypes func.restype = c_char func.errcheck = check_predicate return func
[ "def", "binary_predicate", "(", "func", ",", "*", "args", ")", ":", "argtypes", "=", "[", "GEOM_PTR", ",", "GEOM_PTR", "]", "if", "args", ":", "argtypes", "+=", "args", "func", ".", "argtypes", "=", "argtypes", "func", ".", "restype", "=", "c_char", "f...
for geos binary predicate functions .
train
false
32,815
def set_log_file(log_file): global _log _log = open(log_file, 'w', 1)
[ "def", "set_log_file", "(", "log_file", ")", ":", "global", "_log", "_log", "=", "open", "(", "log_file", ",", "'w'", ",", "1", ")" ]
set the global log file .
train
false
32,816
def dijkstra(graph, start, end=None): D = {} P = {} Q = _priorityDictionary() Q[start] = 0 for v in Q: D[v] = Q[v] if (v == end): break for w in graph.out_nbrs(v): edge_id = graph.edge_by_node(v, w) vwLength = (D[v] + graph.edge_data(edge_id)) if (w in D): if (vwLength < D[w]): raise GraphError('Dijkstra: found better path to already-final vertex') elif ((w not in Q) or (vwLength < Q[w])): Q[w] = vwLength P[w] = v return (D, P)
[ "def", "dijkstra", "(", "graph", ",", "start", ",", "end", "=", "None", ")", ":", "D", "=", "{", "}", "P", "=", "{", "}", "Q", "=", "_priorityDictionary", "(", ")", "Q", "[", "start", "]", "=", "0", "for", "v", "in", "Q", ":", "D", "[", "v"...
dijkstras algorithm for shortest paths david eppstein .
train
true
32,819
def translate_to_c(filename): ast = parse_file(filename, use_cpp=True) generator = c_generator.CGenerator() print(generator.visit(ast))
[ "def", "translate_to_c", "(", "filename", ")", ":", "ast", "=", "parse_file", "(", "filename", ",", "use_cpp", "=", "True", ")", "generator", "=", "c_generator", ".", "CGenerator", "(", ")", "print", "(", "generator", ".", "visit", "(", "ast", ")", ")" ]
simply use the c_generator module to emit a parsed ast .
train
false
32,820
@step(u'a file named "{filename}" does not exist') def step_file_named_filename_does_not_exist(context, filename): step_file_named_filename_should_not_exist(context, filename)
[ "@", "step", "(", "u'a file named \"{filename}\" does not exist'", ")", "def", "step_file_named_filename_does_not_exist", "(", "context", ",", "filename", ")", ":", "step_file_named_filename_should_not_exist", "(", "context", ",", "filename", ")" ]
verifies that a file with this filename does not exist .
train
false
32,821
def test_conv_str_choices_invalid(): param = inspect.Parameter('foo', inspect.Parameter.POSITIONAL_ONLY) with pytest.raises(cmdexc.ArgumentTypeError) as excinfo: argparser.type_conv(param, str, 'val3', str_choices=['val1', 'val2']) msg = 'foo: Invalid value val3 - expected one of: val1, val2' assert (str(excinfo.value) == msg)
[ "def", "test_conv_str_choices_invalid", "(", ")", ":", "param", "=", "inspect", ".", "Parameter", "(", "'foo'", ",", "inspect", ".", "Parameter", ".", "POSITIONAL_ONLY", ")", "with", "pytest", ".", "raises", "(", "cmdexc", ".", "ArgumentTypeError", ")", "as", ...
calling str type with str_choices and invalid value .
train
false
32,822
def fromBase64(s): if (base64Pattern.match(s) is None): raise SASLIncorrectEncodingError() try: return b64decode(s) except Exception as e: raise SASLIncorrectEncodingError(str(e))
[ "def", "fromBase64", "(", "s", ")", ":", "if", "(", "base64Pattern", ".", "match", "(", "s", ")", "is", "None", ")", ":", "raise", "SASLIncorrectEncodingError", "(", ")", "try", ":", "return", "b64decode", "(", "s", ")", "except", "Exception", "as", "e...
decode base64 encoded string .
train
false
32,823
def dilated_convolution_2d(x, W, b=None, stride=1, pad=0, dilate=1, use_cudnn=True, cover_all=False): func = DilatedConvolution2DFunction(stride, pad, dilate, use_cudnn, cover_all) if (b is None): return func(x, W) else: return func(x, W, b)
[ "def", "dilated_convolution_2d", "(", "x", ",", "W", ",", "b", "=", "None", ",", "stride", "=", "1", ",", "pad", "=", "0", ",", "dilate", "=", "1", ",", "use_cudnn", "=", "True", ",", "cover_all", "=", "False", ")", ":", "func", "=", "DilatedConvol...
two-dimensional dilated convolution function .
train
false
32,824
def render_purchase_form_html(cart, **kwargs): return PROCESSOR_MODULE.render_purchase_form_html(cart, **kwargs)
[ "def", "render_purchase_form_html", "(", "cart", ",", "**", "kwargs", ")", ":", "return", "PROCESSOR_MODULE", ".", "render_purchase_form_html", "(", "cart", ",", "**", "kwargs", ")" ]
renders the html of the hidden post form that must be used to initiate a purchase with cybersource args: cart : the order model representing items in the users cart .
train
false
32,825
def rec_drop_fields(rec, names): names = set(names) newdtype = np.dtype([(name, rec.dtype[name]) for name in rec.dtype.names if (name not in names)]) newrec = np.recarray(rec.shape, dtype=newdtype) for field in newdtype.names: newrec[field] = rec[field] return newrec
[ "def", "rec_drop_fields", "(", "rec", ",", "names", ")", ":", "names", "=", "set", "(", "names", ")", "newdtype", "=", "np", ".", "dtype", "(", "[", "(", "name", ",", "rec", ".", "dtype", "[", "name", "]", ")", "for", "name", "in", "rec", ".", ...
return a new numpy record array with fields in *names* dropped .
train
false
32,826
def Logout(continue_url, outfile): output_headers = [] output_headers.append(ClearUserInfoCookie()) outfile.write('Status: 302 Redirecting to continue URL\r\n') for header in output_headers: outfile.write(header) outfile.write(('Location: %s\r\n' % continue_url)) outfile.write('\r\n')
[ "def", "Logout", "(", "continue_url", ",", "outfile", ")", ":", "output_headers", "=", "[", "]", "output_headers", ".", "append", "(", "ClearUserInfoCookie", "(", ")", ")", "outfile", ".", "write", "(", "'Status: 302 Redirecting to continue URL\\r\\n'", ")", "for"...
the handler for having users log out .
train
false
32,828
def renamer(old, new, fsync=True): dirpath = os.path.dirname(new) try: count = makedirs_count(dirpath) os.rename(old, new) except OSError: count = makedirs_count(dirpath) os.rename(old, new) if fsync: for i in range(0, (count + 1)): fsync_dir(dirpath) dirpath = os.path.dirname(dirpath)
[ "def", "renamer", "(", "old", ",", "new", ",", "fsync", "=", "True", ")", ":", "dirpath", "=", "os", ".", "path", ".", "dirname", "(", "new", ")", "try", ":", "count", "=", "makedirs_count", "(", "dirpath", ")", "os", ".", "rename", "(", "old", "...
attempt to fix / hide race conditions like empty object directories being removed by backend processes during uploads .
train
false