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
23,634
def make_api_version(version_data): from readthedocs.builds.models import Version for key in ['resource_uri', 'absolute_url', 'downloads']: if (key in version_data): del version_data[key] project_data = version_data['project'] project = make_api_project(project_data) version_data['project'] = project ver = Version(**version_data) ver.save = _new_save return ver
[ "def", "make_api_version", "(", "version_data", ")", ":", "from", "readthedocs", ".", "builds", ".", "models", "import", "Version", "for", "key", "in", "[", "'resource_uri'", ",", "'absolute_url'", ",", "'downloads'", "]", ":", "if", "(", "key", "in", "versi...
make mock version instance from api return .
train
false
23,635
def assert_version_header_matches_request(api_microversion_header_name, api_microversion, response_header): api_microversion_header_name = api_microversion_header_name.lower() if ((api_microversion_header_name not in response_header) or (api_microversion != response_header[api_microversion_header_name])): msg = ("Microversion header '%s' with value '%s' does not match in response - %s. " % (api_microversion_header_name, api_microversion, response_header)) raise exceptions.InvalidHTTPResponseHeader(msg)
[ "def", "assert_version_header_matches_request", "(", "api_microversion_header_name", ",", "api_microversion", ",", "response_header", ")", ":", "api_microversion_header_name", "=", "api_microversion_header_name", ".", "lower", "(", ")", "if", "(", "(", "api_microversion_heade...
checks api microversion in response header verify whether microversion is present in response header and with specified api_microversion value .
train
false
23,636
def _win32_find_exe(exe): candidates = [exe] if (u'.' not in exe): extensions = getenv(u'PATHEXT', u'').split(os.pathsep) candidates.extend([(exe + ext) for ext in extensions if ext.startswith(u'.')]) for candidate in candidates: if exists(candidate): return candidate if (not os.path.dirname(exe)): for path in getenv(u'PATH').split(os.pathsep): if path: for candidate in candidates: full_path = os.path.join(path, candidate) if exists(full_path): return full_path return exe
[ "def", "_win32_find_exe", "(", "exe", ")", ":", "candidates", "=", "[", "exe", "]", "if", "(", "u'.'", "not", "in", "exe", ")", ":", "extensions", "=", "getenv", "(", "u'PATHEXT'", ",", "u''", ")", ".", "split", "(", "os", ".", "pathsep", ")", "can...
find the actual file for a windows executable .
train
false
23,638
@csrf_exempt def update_subproject(request, project, subproject): if (not appsettings.ENABLE_HOOKS): return HttpResponseNotAllowed([]) obj = get_subproject(request, project, subproject, True) if (not obj.project.enable_hooks): return HttpResponseNotAllowed([]) perform_update(obj) return hook_response()
[ "@", "csrf_exempt", "def", "update_subproject", "(", "request", ",", "project", ",", "subproject", ")", ":", "if", "(", "not", "appsettings", ".", "ENABLE_HOOKS", ")", ":", "return", "HttpResponseNotAllowed", "(", "[", "]", ")", "obj", "=", "get_subproject", ...
api hook for updating git repos .
train
false
23,639
def _json_play_players(play, data): players = OrderedDict() for (playerid, statcats) in data.iteritems(): if (playerid == '0'): continue for info in statcats: if (info['statId'] not in nflgame.statmap.idmap): continue if (playerid not in players): home = play.drive.game.is_home(info['clubcode']) if home: team_name = play.drive.game.home else: team_name = play.drive.game.away stats = nflgame.player.PlayPlayerStats(playerid, info['playerName'], home, team_name) players[playerid] = stats statvals = nflgame.statmap.values(info['statId'], info['yards']) players[playerid]._add_stats(statvals) return players
[ "def", "_json_play_players", "(", "play", ",", "data", ")", ":", "players", "=", "OrderedDict", "(", ")", "for", "(", "playerid", ",", "statcats", ")", "in", "data", ".", "iteritems", "(", ")", ":", "if", "(", "playerid", "==", "'0'", ")", ":", "cont...
takes a single json play entry and converts it to an ordereddict of player statistics .
train
false
23,642
def create_list_of(class_, objects): return [class_.from_metadata(obj) for obj in objects]
[ "def", "create_list_of", "(", "class_", ",", "objects", ")", ":", "return", "[", "class_", ".", "from_metadata", "(", "obj", ")", "for", "obj", "in", "objects", "]" ]
return a list of model objects of class class_ from list of object metadata objects .
train
false
23,643
def test_ast_bad_global(): cant_compile(u'(global)') cant_compile(u'(global (foo))')
[ "def", "test_ast_bad_global", "(", ")", ":", "cant_compile", "(", "u'(global)'", ")", "cant_compile", "(", "u'(global (foo))'", ")" ]
make sure ast cant compile invalid global .
train
false
23,644
def parse_clademodelc(branch_type_no, line_floats, site_classes): if ((not site_classes) or (len(line_floats) == 0)): return for n in range(len(line_floats)): if (site_classes[n].get('branch types') is None): site_classes[n]['branch types'] = {} site_classes[n]['branch types'][branch_type_no] = line_floats[n] return site_classes
[ "def", "parse_clademodelc", "(", "branch_type_no", ",", "line_floats", ",", "site_classes", ")", ":", "if", "(", "(", "not", "site_classes", ")", "or", "(", "len", "(", "line_floats", ")", "==", "0", ")", ")", ":", "return", "for", "n", "in", "range", ...
parse results specific to the clade model c .
train
false
23,646
def safe_creation(context, create_fn, delete_fn, create_bindings, transaction=True): cm = (context.session.begin(subtransactions=True) if transaction else _noop_context_manager()) with cm: obj = create_fn() try: value = create_bindings(obj['id']) except Exception: with excutils.save_and_reraise_exception(): try: delete_fn(obj['id']) except Exception as e: LOG.error(_LE('Cannot clean up created object %(obj)s. Exception: %(exc)s'), {'obj': obj['id'], 'exc': e}) return (obj, value)
[ "def", "safe_creation", "(", "context", ",", "create_fn", ",", "delete_fn", ",", "create_bindings", ",", "transaction", "=", "True", ")", ":", "cm", "=", "(", "context", ".", "session", ".", "begin", "(", "subtransactions", "=", "True", ")", "if", "transac...
this function wraps logic of object creation in safe atomic way .
train
false
23,647
@require_POST @login_required @permitted def endorse_comment(request, course_id, comment_id): course_key = CourseKey.from_string(course_id) comment = cc.Comment.find(comment_id) user = request.user comment.endorsed = (request.POST.get('endorsed', 'false').lower() == 'true') comment.endorsement_user_id = user.id comment.save() comment_endorsed.send(sender=None, user=user, post=comment) return JsonResponse(prepare_content(comment.to_dict(), course_key))
[ "@", "require_POST", "@", "login_required", "@", "permitted", "def", "endorse_comment", "(", "request", ",", "course_id", ",", "comment_id", ")", ":", "course_key", "=", "CourseKey", ".", "from_string", "(", "course_id", ")", "comment", "=", "cc", ".", "Commen...
given a course_id and comment_id .
train
false
23,650
def org_organisation_address(row): if hasattr(row, 'org_organisation'): row = row.org_organisation try: organisation_id = row.id except: return current.messages['NONE'] db = current.db s3db = current.s3db otable = s3db.org_office gtable = s3db.gis_location query = (((otable.deleted != True) & (otable.organisation_id == organisation_id)) & (otable.location_id == gtable.id)) row = db(query).select(gtable.addr_street, limitby=(0, 1)).first() if row: row.addr_street else: return current.messages['NONE']
[ "def", "org_organisation_address", "(", "row", ")", ":", "if", "hasattr", "(", "row", ",", "'org_organisation'", ")", ":", "row", "=", "row", ".", "org_organisation", "try", ":", "organisation_id", "=", "row", ".", "id", "except", ":", "return", "current", ...
the address of the first office .
train
false
23,651
def get_icon_themes(): themes = [] icon_themes_env = core.getenv(u'GIT_COLA_ICON_THEME') if icon_themes_env: themes.extend([x for x in icon_themes_env.split(u':') if x]) icon_themes_cfg = gitcfg.current().get_all(u'cola.icontheme') if icon_themes_cfg: themes.extend(icon_themes_cfg) if (not themes): themes.append(u'light') return themes
[ "def", "get_icon_themes", "(", ")", ":", "themes", "=", "[", "]", "icon_themes_env", "=", "core", ".", "getenv", "(", "u'GIT_COLA_ICON_THEME'", ")", "if", "icon_themes_env", ":", "themes", ".", "extend", "(", "[", "x", "for", "x", "in", "icon_themes_env", ...
return the default icon theme names .
train
false
23,653
def getUnicode(value, encoding=None, noneToNull=False): if (noneToNull and (value is None)): return NULL if isinstance(value, unicode): return value elif isinstance(value, basestring): while True: try: return unicode(value, (encoding or (kb.get('pageEncoding') if kb.get('originalPage') else None) or UNICODE_ENCODING)) except UnicodeDecodeError as ex: try: return unicode(value, UNICODE_ENCODING) except: value = ((value[:ex.start] + ''.join(((INVALID_UNICODE_CHAR_FORMAT % ord(_)) for _ in value[ex.start:ex.end]))) + value[ex.end:]) elif isListLike(value): value = list((getUnicode(_, encoding, noneToNull) for _ in value)) return value else: try: return unicode(value) except UnicodeDecodeError: return unicode(str(value), errors='ignore')
[ "def", "getUnicode", "(", "value", ",", "encoding", "=", "None", ",", "noneToNull", "=", "False", ")", ":", "if", "(", "noneToNull", "and", "(", "value", "is", "None", ")", ")", ":", "return", "NULL", "if", "isinstance", "(", "value", ",", "unicode", ...
return the unicode representation of the supplied value: .
train
false
23,654
def get_custom_data_point(): length = random.randint(0, 10) print 'reporting timeseries value {}'.format(str(length)) return length
[ "def", "get_custom_data_point", "(", ")", ":", "length", "=", "random", ".", "randint", "(", "0", ",", "10", ")", "print", "'reporting timeseries value {}'", ".", "format", "(", "str", "(", "length", ")", ")", "return", "length" ]
dummy method to return a mock measurement for demonstration purposes .
train
false
23,656
def add_accept_handler(sock, callback, io_loop=None): if (io_loop is None): io_loop = IOLoop.current() def accept_handler(fd, events): while True: try: (connection, address) = sock.accept() except socket.error as e: if (e.args[0] in (errno.EWOULDBLOCK, errno.EAGAIN)): return if (e.args[0] == errno.ECONNABORTED): continue raise callback(connection, address) io_loop.add_handler(sock.fileno(), accept_handler, IOLoop.READ)
[ "def", "add_accept_handler", "(", "sock", ",", "callback", ",", "io_loop", "=", "None", ")", ":", "if", "(", "io_loop", "is", "None", ")", ":", "io_loop", "=", "IOLoop", ".", "current", "(", ")", "def", "accept_handler", "(", "fd", ",", "events", ")", ...
adds an .
train
false
23,658
def hosted_zone_absent(name, domain_name=None, region=None, key=None, keyid=None, profile=None): domain_name = (domain_name if domain_name else name) ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} deets = __salt__['boto_route53.describe_hosted_zones'](domain_name=domain_name, region=region, key=key, keyid=keyid, profile=profile) if (not deets): ret['comment'] = 'Hosted Zone {0} already absent'.format(domain_name) log.info(ret['comment']) return ret if __opts__['test']: ret['comment'] = 'Route53 Hosted Zone {0} set to be deleted.'.format(domain_name) ret['result'] = None return ret if __salt__['boto_route53.delete_zone'](zone=domain_name, region=region, key=key, keyid=keyid, profile=profile): ret['comment'] = 'Route53 Hosted Zone {0} deleted'.format(domain_name) log.info(ret['comment']) ret['changes']['old'] = deets ret['changes']['new'] = None return ret
[ "def", "hosted_zone_absent", "(", "name", ",", "domain_name", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "domain_name", "=", "(", "domain_name", "if", "domain_name",...
ensure the route53 hostes zone described is absent name the name of the state definition .
train
true
23,659
def classImplements(cls, *interfaces): spec = implementedBy(cls) spec.declared += tuple(_normalizeargs(interfaces)) bases = [] seen = {} for b in spec.declared: if (b not in seen): seen[b] = 1 bases.append(b) if (spec.inherit is not None): for c in spec.inherit.__bases__: b = implementedBy(c) if (b not in seen): seen[b] = 1 bases.append(b) spec.__bases__ = tuple(bases)
[ "def", "classImplements", "(", "cls", ",", "*", "interfaces", ")", ":", "spec", "=", "implementedBy", "(", "cls", ")", "spec", ".", "declared", "+=", "tuple", "(", "_normalizeargs", "(", "interfaces", ")", ")", "bases", "=", "[", "]", "seen", "=", "{",...
declare additional interfaces implemented for instances of a class the arguments after the class are one or more interfaces or interface specifications .
train
false
23,660
def _api_queue(name, output, kwargs): value = kwargs.get('value', '') return _api_queue_table.get(name, (_api_queue_default, 2))[0](output, value, kwargs)
[ "def", "_api_queue", "(", "name", ",", "output", ",", "kwargs", ")", ":", "value", "=", "kwargs", ".", "get", "(", "'value'", ",", "''", ")", "return", "_api_queue_table", ".", "get", "(", "name", ",", "(", "_api_queue_default", ",", "2", ")", ")", "...
api: dispatcher for mode=queue .
train
false
23,661
def vq(obs, code_book, check_finite=True): obs = _asarray_validated(obs, check_finite=check_finite) code_book = _asarray_validated(code_book, check_finite=check_finite) ct = np.common_type(obs, code_book) c_obs = obs.astype(ct, copy=False) if (code_book.dtype != ct): c_code_book = code_book.astype(ct) else: c_code_book = code_book if (ct in (np.float32, np.float64)): results = _vq.vq(c_obs, c_code_book) else: results = py_vq(obs, code_book) return results
[ "def", "vq", "(", "obs", ",", "code_book", ",", "check_finite", "=", "True", ")", ":", "obs", "=", "_asarray_validated", "(", "obs", ",", "check_finite", "=", "check_finite", ")", "code_book", "=", "_asarray_validated", "(", "code_book", ",", "check_finite", ...
assign codes from a code book to observations .
train
false
23,666
def _api_restart(name, output, kwargs): sabnzbd.trigger_restart() return report(output)
[ "def", "_api_restart", "(", "name", ",", "output", ",", "kwargs", ")", ":", "sabnzbd", ".", "trigger_restart", "(", ")", "return", "report", "(", "output", ")" ]
api: accepts output .
train
false
23,667
def story(z, image_loc, k=100, bw=50, lyric=False): (rawim, im) = load_image(image_loc) feats = compute_features(z['net'], im).flatten() feats /= norm(feats) feats = embedding.encode_images(z['vse'], feats[None, :]) scores = numpy.dot(feats, z['cvec'].T).flatten() sorted_args = numpy.argsort(scores)[::(-1)] sentences = [z['cap'][a] for a in sorted_args[:k]] print 'NEAREST-CAPTIONS: ' for s in sentences[:5]: print s print '' svecs = skipthoughts.encode(z['stv'], sentences, verbose=False) shift = ((svecs.mean(0) - z['bneg']) + z['bpos']) passage = decoder.run_sampler(z['dec'], shift, beam_width=bw) print 'OUTPUT: ' if lyric: for line in passage.split(','): if (line[0] != ' '): print line else: print line[1:] else: print passage
[ "def", "story", "(", "z", ",", "image_loc", ",", "k", "=", "100", ",", "bw", "=", "50", ",", "lyric", "=", "False", ")", ":", "(", "rawim", ",", "im", ")", "=", "load_image", "(", "image_loc", ")", "feats", "=", "compute_features", "(", "z", "[",...
generate a story for an image at location image_loc .
train
false
23,668
def check_string_length(value, name, min_length=0, max_length=None, allow_all_spaces=True): try: strutils.check_string_length(value, name=name, min_length=min_length, max_length=max_length) except (ValueError, TypeError) as exc: raise exception.InvalidInput(reason=exc) if ((not allow_all_spaces) and value.isspace()): msg = _('%(name)s cannot be all spaces.') raise exception.InvalidInput(reason=msg)
[ "def", "check_string_length", "(", "value", ",", "name", ",", "min_length", "=", "0", ",", "max_length", "=", "None", ",", "allow_all_spaces", "=", "True", ")", ":", "try", ":", "strutils", ".", "check_string_length", "(", "value", ",", "name", "=", "name"...
check the length of specified string .
train
false
23,669
def getNewRepository(): return ExportRepository()
[ "def", "getNewRepository", "(", ")", ":", "return", "ExportRepository", "(", ")" ]
get new repository .
train
false
23,670
def is_x64_architecture(): if ('64' in platform.machine()): return True else: return False
[ "def", "is_x64_architecture", "(", ")", ":", "if", "(", "'64'", "in", "platform", ".", "machine", "(", ")", ")", ":", "return", "True", "else", ":", "return", "False" ]
return true if the architecture is x64 .
train
false
23,671
@gen.engine def DetermineStartDate(client, job, callback): start_date = options.options.start_date if options.options.smart_scan: last_run = (yield gen.Task(job.FindLastSuccess, with_payload_key='stats.last_day')) if (last_run is None): logging.info('No previous successful scan found, rerun with --start_date') callback(None) return last_run_start = last_run['start_time'] if ((last_run_start + (options.options.hours_between_runs * constants.SECONDS_PER_HOUR)) > time.time()): logging.info(('Last successful run started at %s, less than %d hours ago; skipping.' % (time.asctime(time.localtime(last_run_start)), options.options.hours_between_runs))) callback(None) return last_day = last_run['stats.last_day'] start_time = (util.ISO8601ToUTCTimestamp(last_day) + constants.SECONDS_PER_DAY) start_date = util.TimestampUTCToISO8601(start_time) logging.info(('Last successful run (%s) scanned up to %s, setting start date to %s' % (time.asctime(time.localtime(last_run_start)), last_day, start_date))) callback(start_date)
[ "@", "gen", ".", "engine", "def", "DetermineStartDate", "(", "client", ",", "job", ",", "callback", ")", ":", "start_date", "=", "options", ".", "options", ".", "start_date", "if", "options", ".", "options", ".", "smart_scan", ":", "last_run", "=", "(", ...
if smart_scan is true .
train
false
23,672
@pytest.fixture() def make_app(test_params): apps = [] syspath = sys.path[:] def make(*args, **kwargs): (status, warning) = (StringIO(), StringIO()) kwargs.setdefault('status', status) kwargs.setdefault('warning', warning) app_ = util.SphinxTestApp(*args, **kwargs) apps.append(app_) if test_params['shared_result']: app_ = SphinxTestAppWrapperForSkipBuilding(app_) return app_ (yield make) sys.path[:] = syspath for app_ in apps: app_.cleanup()
[ "@", "pytest", ".", "fixture", "(", ")", "def", "make_app", "(", "test_params", ")", ":", "apps", "=", "[", "]", "syspath", "=", "sys", ".", "path", "[", ":", "]", "def", "make", "(", "*", "args", ",", "**", "kwargs", ")", ":", "(", "status", "...
factory function that creates a new coolmagicapplication object .
train
false
23,673
def _count(a, axis=None): if hasattr(a, 'count'): num = a.count(axis=axis) if (isinstance(num, np.ndarray) and (num.ndim == 0)): num = int(num) elif (axis is None): num = a.size else: num = a.shape[axis] return num
[ "def", "_count", "(", "a", ",", "axis", "=", "None", ")", ":", "if", "hasattr", "(", "a", ",", "'count'", ")", ":", "num", "=", "a", ".", "count", "(", "axis", "=", "axis", ")", "if", "(", "isinstance", "(", "num", ",", "np", ".", "ndarray", ...
count the number of non-masked elements of an array .
train
false
23,674
@utils.arg('host', metavar='<hostname>', help=_('Name of host.')) @utils.arg('--status', metavar='<enable|disable>', default=None, dest='status', help=_('Either enable or disable a host.')) @utils.arg('--maintenance', metavar='<enable|disable>', default=None, dest='maintenance', help=_('Either put or resume host to/from maintenance.')) def do_host_update(cs, args): updates = {} columns = ['HOST'] if args.status: updates['status'] = args.status columns.append('status') if args.maintenance: updates['maintenance_mode'] = args.maintenance columns.append('maintenance_mode') result = cs.hosts.update(args.host, updates) utils.print_list([result], columns)
[ "@", "utils", ".", "arg", "(", "'host'", ",", "metavar", "=", "'<hostname>'", ",", "help", "=", "_", "(", "'Name of host.'", ")", ")", "@", "utils", ".", "arg", "(", "'--status'", ",", "metavar", "=", "'<enable|disable>'", ",", "default", "=", "None", ...
update host settings .
train
false
23,677
def overload(func): return _overload_dummy
[ "def", "overload", "(", "func", ")", ":", "return", "_overload_dummy" ]
a decorator marking the decorated function as typing and implementing *func* in nopython mode .
train
false
23,678
def _set_users(users): return __salt__['users.set_users'](users, commit=False)
[ "def", "_set_users", "(", "users", ")", ":", "return", "__salt__", "[", "'users.set_users'", "]", "(", "users", ",", "commit", "=", "False", ")" ]
calls users .
train
false
23,679
def create_settings_file(init=True): settings_path = os.path.join(GAMEDIR, 'server', 'conf', 'settings.py') if (not init): if os.path.exists(settings_path): inp = raw_input('server/conf/settings.py already exists. Do you want to reset it? y/[N]> ') if (not (inp.lower() == 'y')): print('Aborted.') sys.exit() else: print('Reset the settings file.') default_settings_path = os.path.join(EVENNIA_TEMPLATE, 'server', 'conf', 'settings.py') shutil.copy(default_settings_path, settings_path) with open(settings_path, 'r') as f: settings_string = f.read() setting_dict = {'settings_default': os.path.join(EVENNIA_LIB, 'settings_default.py'), 'servername': ('"%s"' % GAMEDIR.rsplit(os.path.sep, 1)[1].capitalize()), 'secret_key': ("'%s'" % create_secret_key())} settings_string = settings_string.format(**setting_dict) with open(settings_path, 'w') as f: f.write(settings_string)
[ "def", "create_settings_file", "(", "init", "=", "True", ")", ":", "settings_path", "=", "os", ".", "path", ".", "join", "(", "GAMEDIR", ",", "'server'", ",", "'conf'", ",", "'settings.py'", ")", "if", "(", "not", "init", ")", ":", "if", "os", ".", "...
uses the template settings file to build a working settings file .
train
false
23,680
@utils.arg('--tenant', metavar='<tenant-id>', default=None, help=_('ID of tenant to list the quotas for.')) @utils.arg('--user', metavar='<user-id>', default=None, help=_('ID of user to list the quotas for.')) @utils.arg('--detail', action='store_true', default=False, help=_('Show detailed info (limit, reserved, in-use).')) def do_quota_show(cs, args): if args.tenant: project_id = args.tenant elif isinstance(cs.client, client.SessionClient): auth = cs.client.auth project_id = auth.get_auth_ref(cs.client.session).project_id else: project_id = cs.client.tenant_id _quota_show(cs.quotas.get(project_id, user_id=args.user, detail=args.detail))
[ "@", "utils", ".", "arg", "(", "'--tenant'", ",", "metavar", "=", "'<tenant-id>'", ",", "default", "=", "None", ",", "help", "=", "_", "(", "'ID of tenant to list the quotas for.'", ")", ")", "@", "utils", ".", "arg", "(", "'--user'", ",", "metavar", "=", ...
list the quotas for a tenant/user .
train
false
23,681
@pytest.fixture() def pg_xlog(tmpdir, monkeypatch): monkeypatch.chdir(tmpdir) return PgXlog(tmpdir)
[ "@", "pytest", ".", "fixture", "(", ")", "def", "pg_xlog", "(", "tmpdir", ",", "monkeypatch", ")", ":", "monkeypatch", ".", "chdir", "(", "tmpdir", ")", "return", "PgXlog", "(", "tmpdir", ")" ]
set up xlog utility functions and change directories .
train
false
23,682
def _datetime_to_rfc3339(value, ignore_zone=True): if ((not ignore_zone) and (value.tzinfo is not None)): value = (value.replace(tzinfo=None) - value.utcoffset()) return value.strftime(_RFC3339_MICROS)
[ "def", "_datetime_to_rfc3339", "(", "value", ",", "ignore_zone", "=", "True", ")", ":", "if", "(", "(", "not", "ignore_zone", ")", "and", "(", "value", ".", "tzinfo", "is", "not", "None", ")", ")", ":", "value", "=", "(", "value", ".", "replace", "("...
convert a timestamp to a string .
train
true
23,683
def _unconstrain_sv_less_than_one(constrained, order=None, k_endog=None): from scipy import linalg unconstrained = [] if (order is None): order = len(constrained) if (k_endog is None): k_endog = constrained[0].shape[0] eye = np.eye(k_endog) for i in range(order): P = constrained[i] (B_inv, lower) = linalg.cho_factor((eye - np.dot(P, P.T)), lower=True) unconstrained.append(linalg.solve_triangular(B_inv, P, lower=lower)) return unconstrained
[ "def", "_unconstrain_sv_less_than_one", "(", "constrained", ",", "order", "=", "None", ",", "k_endog", "=", "None", ")", ":", "from", "scipy", "import", "linalg", "unconstrained", "=", "[", "]", "if", "(", "order", "is", "None", ")", ":", "order", "=", "...
transform matrices with singular values less than one to arbitrary matrices .
train
false
23,684
@app.route('/calendars/<public_id>', methods=['GET']) def calendar_read_api(public_id): valid_public_id(public_id) try: calendar = g.db_session.query(Calendar).filter((Calendar.public_id == public_id), (Calendar.namespace_id == g.namespace.id)).one() except NoResultFound: raise NotFoundError("Couldn't find calendar {0}".format(public_id)) return g.encoder.jsonify(calendar)
[ "@", "app", ".", "route", "(", "'/calendars/<public_id>'", ",", "methods", "=", "[", "'GET'", "]", ")", "def", "calendar_read_api", "(", "public_id", ")", ":", "valid_public_id", "(", "public_id", ")", "try", ":", "calendar", "=", "g", ".", "db_session", "...
get all data for an existing calendar .
train
false
23,685
def labels_from_header(header_name, header_value): if header_value: labels = parse_labels_string(header_name, header_value) else: labels = set() return labels
[ "def", "labels_from_header", "(", "header_name", ",", "header_value", ")", ":", "if", "header_value", ":", "labels", "=", "parse_labels_string", "(", "header_name", ",", "header_value", ")", "else", ":", "labels", "=", "set", "(", ")", "return", "labels" ]
helper that builds label set from the corresponding header value .
train
false
23,686
def load_rt(loc='./data/'): (pos, neg) = ([], []) with open((loc + 'rt-polarity.pos'), 'rb') as f: for line in f: pos.append(line.decode('latin-1').strip()) with open((loc + 'rt-polarity.neg'), 'rb') as f: for line in f: neg.append(line.decode('latin-1').strip()) return (pos, neg)
[ "def", "load_rt", "(", "loc", "=", "'./data/'", ")", ":", "(", "pos", ",", "neg", ")", "=", "(", "[", "]", ",", "[", "]", ")", "with", "open", "(", "(", "loc", "+", "'rt-polarity.pos'", ")", ",", "'rb'", ")", "as", "f", ":", "for", "line", "i...
load the mr dataset .
train
false
23,688
def semilinearPrime(x): try: shape = x.shape x.flatten() x = x.tolist() except AttributeError: shape = (1, len(x)) def f(val): if (val < 0): return safeExp(val) else: return 1.0 return array(list(map(f, x))).reshape(shape)
[ "def", "semilinearPrime", "(", "x", ")", ":", "try", ":", "shape", "=", "x", ".", "shape", "x", ".", "flatten", "(", ")", "x", "=", "x", ".", "tolist", "(", ")", "except", "AttributeError", ":", "shape", "=", "(", "1", ",", "len", "(", "x", ")"...
this function is the first derivative of the semilinear function .
train
false
23,689
def mergeOrderings(orderings, seen=None): if (seen is None): seen = {} result = [] orderings.reverse() for ordering in orderings: ordering = list(ordering) ordering.reverse() for o in ordering: if (o not in seen): seen[o] = 1 result.append(o) result.reverse() return result
[ "def", "mergeOrderings", "(", "orderings", ",", "seen", "=", "None", ")", ":", "if", "(", "seen", "is", "None", ")", ":", "seen", "=", "{", "}", "result", "=", "[", "]", "orderings", ".", "reverse", "(", ")", "for", "ordering", "in", "orderings", "...
merge multiple orderings so that within-ordering order is preserved orderings are constrained in such a way that if an object appears in two or more orderings .
train
false
23,690
def wrap_output(output, encoding): return codecs.getwriter(encoding)((output.buffer if hasattr(output, u'buffer') else output))
[ "def", "wrap_output", "(", "output", ",", "encoding", ")", ":", "return", "codecs", ".", "getwriter", "(", "encoding", ")", "(", "(", "output", ".", "buffer", "if", "hasattr", "(", "output", ",", "u'buffer'", ")", "else", "output", ")", ")" ]
return output with specified encoding .
train
true
23,691
def ordered_intersect(*sets): common = frozenset.intersection(*map(frozenset, sets)) return (x for x in unique(concat(sets)) if (x in common))
[ "def", "ordered_intersect", "(", "*", "sets", ")", ":", "common", "=", "frozenset", ".", "intersection", "(", "*", "map", "(", "frozenset", ",", "sets", ")", ")", "return", "(", "x", "for", "x", "in", "unique", "(", "concat", "(", "sets", ")", ")", ...
set intersection of two sequences that preserves order .
train
false
23,693
def determine_64_bit_int(): try: try: import ctypes except ImportError: raise ValueError() if (ctypes.sizeof(ctypes.c_longlong) == 8): return u'long long int' elif (ctypes.sizeof(ctypes.c_long) == 8): return u'long int' elif (ctypes.sizeof(ctypes.c_int) == 8): return u'int' else: raise ValueError() except ValueError: return u'long long int'
[ "def", "determine_64_bit_int", "(", ")", ":", "try", ":", "try", ":", "import", "ctypes", "except", "ImportError", ":", "raise", "ValueError", "(", ")", "if", "(", "ctypes", ".", "sizeof", "(", "ctypes", ".", "c_longlong", ")", "==", "8", ")", ":", "re...
the only configuration parameter needed at compile-time is how to specify a 64-bit signed integer .
train
false
23,694
def get_predicted_pageviews(srs, location=None): (srs, is_single) = tup(srs, ret_is_single=True) sr_names = [sr.name for sr in srs] default_srids = LocalizedDefaultSubreddits.get_global_defaults() if location: no_location = Location(None) r = LocationPromoMetrics.get(DefaultSR, [no_location, location]) location_pageviews = r[(DefaultSR, location)] all_pageviews = r[(DefaultSR, no_location)] if all_pageviews: location_factor = (float(location_pageviews) / float(all_pageviews)) else: location_factor = 0.0 else: location_factor = 1.0 daily_inventory = PromoMetrics.get(MIN_DAILY_CASS_KEY, sr_names=sr_names) ret = {} for sr in srs: if ((not isinstance(sr, FakeSubreddit)) and (sr._id in default_srids)): default_factor = DEFAULT_INVENTORY_FACTOR else: default_factor = INVENTORY_FACTOR base_pageviews = daily_inventory.get(sr.name, 0) ret[sr.name] = int(((base_pageviews * default_factor) * location_factor)) if is_single: return ret[srs[0].name] else: return ret
[ "def", "get_predicted_pageviews", "(", "srs", ",", "location", "=", "None", ")", ":", "(", "srs", ",", "is_single", ")", "=", "tup", "(", "srs", ",", "ret_is_single", "=", "True", ")", "sr_names", "=", "[", "sr", ".", "name", "for", "sr", "in", "srs"...
return predicted number of pageviews for sponsored headlines .
train
false
23,696
def update_node_links(designated_node, target_nodes, description): if (len(target_nodes) == 0): logger.info('No target nodes specified - no node links will be added!') else: logger.info('Repopulating {} with latest {} nodes.'.format(designated_node._id, description)) user = designated_node.creator auth = Auth(user) for pointer in designated_node.nodes_pointer: designated_node.rm_pointer(pointer, auth) for node in target_nodes: designated_node.add_pointer(node, auth, save=True) logger.info('Added node link {} to {}'.format(node, designated_node))
[ "def", "update_node_links", "(", "designated_node", ",", "target_nodes", ",", "description", ")", ":", "if", "(", "len", "(", "target_nodes", ")", "==", "0", ")", ":", "logger", ".", "info", "(", "'No target nodes specified - no node links will be added!'", ")", "...
takes designated node .
train
false
23,698
def compressString(s): gzip.time = FakeTime() zbuf = BytesIO() zfile = gzip.GzipFile(mode='wb', compresslevel=9, fileobj=zbuf) zfile.write(s) zfile.close() return zbuf.getvalue()
[ "def", "compressString", "(", "s", ")", ":", "gzip", ".", "time", "=", "FakeTime", "(", ")", "zbuf", "=", "BytesIO", "(", ")", "zfile", "=", "gzip", ".", "GzipFile", "(", "mode", "=", "'wb'", ",", "compresslevel", "=", "9", ",", "fileobj", "=", "zb...
gzip a given string .
train
false
23,699
def rpn_generate(queue=None, imdb_name=None, rpn_model_path=None, cfg=None, rpn_test_prototxt=None): cfg.TEST.RPN_PRE_NMS_TOP_N = (-1) cfg.TEST.RPN_POST_NMS_TOP_N = 2000 print 'RPN model: {}'.format(rpn_model_path) print 'Using config:' pprint.pprint(cfg) import caffe _init_caffe(cfg) imdb = get_imdb(imdb_name) print 'Loaded dataset `{:s}` for proposal generation'.format(imdb.name) rpn_net = caffe.Net(rpn_test_prototxt, rpn_model_path, caffe.TEST) output_dir = get_output_dir(imdb) print 'Output will be saved to `{:s}`'.format(output_dir) rpn_proposals = imdb_proposals(rpn_net, imdb) rpn_net_name = os.path.splitext(os.path.basename(rpn_model_path))[0] rpn_proposals_path = os.path.join(output_dir, (rpn_net_name + '_proposals.pkl')) with open(rpn_proposals_path, 'wb') as f: cPickle.dump(rpn_proposals, f, cPickle.HIGHEST_PROTOCOL) print 'Wrote RPN proposals to {}'.format(rpn_proposals_path) queue.put({'proposal_path': rpn_proposals_path})
[ "def", "rpn_generate", "(", "queue", "=", "None", ",", "imdb_name", "=", "None", ",", "rpn_model_path", "=", "None", ",", "cfg", "=", "None", ",", "rpn_test_prototxt", "=", "None", ")", ":", "cfg", ".", "TEST", ".", "RPN_PRE_NMS_TOP_N", "=", "(", "-", ...
use a trained rpn to generate proposals .
train
false
23,700
def clean_search_unit(pk, lang): if appsettings.OFFLOAD_INDEXING: add_index_update(pk, False, True, lang) else: delete_search_unit(pk, lang)
[ "def", "clean_search_unit", "(", "pk", ",", "lang", ")", ":", "if", "appsettings", ".", "OFFLOAD_INDEXING", ":", "add_index_update", "(", "pk", ",", "False", ",", "True", ",", "lang", ")", "else", ":", "delete_search_unit", "(", "pk", ",", "lang", ")" ]
cleanups search index on unit deletion .
train
false
23,701
def topic_sibling_documents_link(obj): if (not obj.parent_topic): return '' count = obj.parent_topic.children.count() if (not count): return '' link = ('%s?%s' % (reverse('admin:wiki_document_changelist', args=[]), ('parent_topic__exact=%s' % obj.parent_topic.id))) what = (((count == 1) and 'sibling') or 'siblings') return ('<a href="%s">%s&nbsp;%s</a>' % (link, count, what))
[ "def", "topic_sibling_documents_link", "(", "obj", ")", ":", "if", "(", "not", "obj", ".", "parent_topic", ")", ":", "return", "''", "count", "=", "obj", ".", "parent_topic", ".", "children", ".", "count", "(", ")", "if", "(", "not", "count", ")", ":",...
html link to a list of sibling documents .
train
false
23,702
def build_block_parser(md_instance, **kwargs): parser = BlockParser(md_instance) parser.blockprocessors[u'empty'] = EmptyBlockProcessor(parser) parser.blockprocessors[u'indent'] = ListIndentProcessor(parser) parser.blockprocessors[u'code'] = CodeBlockProcessor(parser) parser.blockprocessors[u'hashheader'] = HashHeaderProcessor(parser) parser.blockprocessors[u'setextheader'] = SetextHeaderProcessor(parser) parser.blockprocessors[u'hr'] = HRProcessor(parser) parser.blockprocessors[u'olist'] = OListProcessor(parser) parser.blockprocessors[u'ulist'] = UListProcessor(parser) parser.blockprocessors[u'quote'] = BlockQuoteProcessor(parser) parser.blockprocessors[u'paragraph'] = ParagraphProcessor(parser) return parser
[ "def", "build_block_parser", "(", "md_instance", ",", "**", "kwargs", ")", ":", "parser", "=", "BlockParser", "(", "md_instance", ")", "parser", ".", "blockprocessors", "[", "u'empty'", "]", "=", "EmptyBlockProcessor", "(", "parser", ")", "parser", ".", "block...
build the default block parser used by markdown .
train
false
23,705
def _wrap_lines(msg): lines = msg.splitlines() fixed_l = [] for line in lines: fixed_l.append(textwrap.fill(line, 80, break_long_words=False, break_on_hyphens=False)) return os.linesep.join(fixed_l)
[ "def", "_wrap_lines", "(", "msg", ")", ":", "lines", "=", "msg", ".", "splitlines", "(", ")", "fixed_l", "=", "[", "]", "for", "line", "in", "lines", ":", "fixed_l", ".", "append", "(", "textwrap", ".", "fill", "(", "line", ",", "80", ",", "break_l...
format lines nicely to 80 chars .
train
false
23,706
def add_contributor_json(user, current_user=None): if current_user: n_projects_in_common = current_user.n_projects_in_common(user) else: n_projects_in_common = 0 current_employment = None education = None if user.jobs: current_employment = user.jobs[0]['institution'] if user.schools: education = user.schools[0]['institution'] return {'fullname': user.fullname, 'email': user.username, 'id': user._primary_key, 'employment': current_employment, 'education': education, 'n_projects_in_common': n_projects_in_common, 'registered': user.is_registered, 'active': user.is_active, 'gravatar_url': gravatar(user, use_ssl=True, size=settings.PROFILE_IMAGE_MEDIUM), 'profile_url': user.profile_url}
[ "def", "add_contributor_json", "(", "user", ",", "current_user", "=", "None", ")", ":", "if", "current_user", ":", "n_projects_in_common", "=", "current_user", ".", "n_projects_in_common", "(", "user", ")", "else", ":", "n_projects_in_common", "=", "0", "current_e...
generate a dictionary representation of a user .
train
false
23,707
def get_messages(request): return getattr(request, '_messages', [])
[ "def", "get_messages", "(", "request", ")", ":", "return", "getattr", "(", "request", ",", "'_messages'", ",", "[", "]", ")" ]
returns the message storage on the request if it exists .
train
false
23,708
def hot(): rc(u'image', cmap=u'hot') im = gci() if (im is not None): im.set_cmap(cm.hot)
[ "def", "hot", "(", ")", ":", "rc", "(", "u'image'", ",", "cmap", "=", "u'hot'", ")", "im", "=", "gci", "(", ")", "if", "(", "im", "is", "not", "None", ")", ":", "im", ".", "set_cmap", "(", "cm", ".", "hot", ")" ]
returns a list of hit terms via google trends .
train
false
23,709
def regressionWrapper(model, modelType, testSample): if ((modelType == 'svm') or (modelType == 'randomforest')): return model.predict(testSample.reshape(1, (-1)))[0] return None
[ "def", "regressionWrapper", "(", "model", ",", "modelType", ",", "testSample", ")", ":", "if", "(", "(", "modelType", "==", "'svm'", ")", "or", "(", "modelType", "==", "'randomforest'", ")", ")", ":", "return", "model", ".", "predict", "(", "testSample", ...
this function is used as a wrapper to pattern classification .
train
false
23,711
def _get_tag_int(fid, node, name, id_): tag = find_tag(fid, node, id_) if (tag is None): fid.close() raise ValueError((name + ' tag not found')) return int(tag.data)
[ "def", "_get_tag_int", "(", "fid", ",", "node", ",", "name", ",", "id_", ")", ":", "tag", "=", "find_tag", "(", "fid", ",", "node", ",", "id_", ")", "if", "(", "tag", "is", "None", ")", ":", "fid", ".", "close", "(", ")", "raise", "ValueError", ...
check we have an appropriate tag .
train
false
23,713
def on_off(tag): return ['OFF', 'ON'][tag]
[ "def", "on_off", "(", "tag", ")", ":", "return", "[", "'OFF'", ",", "'ON'", "]", "[", "tag", "]" ]
return an on/off string for a 1/0 input .
train
false
23,714
def typestats(objects=None, shortnames=True): if (objects is None): objects = gc.get_objects() try: if shortnames: typename = _short_typename else: typename = _long_typename stats = {} for o in objects: n = typename(o) stats[n] = (stats.get(n, 0) + 1) return stats finally: del objects
[ "def", "typestats", "(", "objects", "=", "None", ",", "shortnames", "=", "True", ")", ":", "if", "(", "objects", "is", "None", ")", ":", "objects", "=", "gc", ".", "get_objects", "(", ")", "try", ":", "if", "shortnames", ":", "typename", "=", "_short...
count the number of instances for each type tracked by the gc .
train
false
23,715
def remove_session(session): Session.remove_one(session)
[ "def", "remove_session", "(", "session", ")", ":", "Session", ".", "remove_one", "(", "session", ")" ]
remove a session from database .
train
false
23,716
def test_success_junit_xml(test_name, class_name='Results', testcase_name='test_ran'): testsuite = ET.Element('testsuite') testsuite.set('tests', '1') testsuite.set('failures', '0') testsuite.set('time', '1') testsuite.set('errors', '0') testsuite.set('name', test_name) testcase = ET.SubElement(testsuite, 'testcase') testcase.set('name', testcase_name) testcase.set('status', 'run') testcase.set('time', '1') testcase.set('classname', class_name) return ET.tostring(testsuite, encoding='utf-8', method='xml')
[ "def", "test_success_junit_xml", "(", "test_name", ",", "class_name", "=", "'Results'", ",", "testcase_name", "=", "'test_ran'", ")", ":", "testsuite", "=", "ET", ".", "Element", "(", "'testsuite'", ")", "testsuite", ".", "set", "(", "'tests'", ",", "'1'", "...
generate junit xml file for a unary test suite where the test succeeded .
train
false
23,717
def varexp(line): ip = get_ipython() (funcname, name) = line.split() import spyder.pyplot __fig__ = spyder.pyplot.figure() __items__ = getattr(spyder.pyplot, funcname[2:])(ip.user_ns[name]) spyder.pyplot.show() del __fig__, __items__
[ "def", "varexp", "(", "line", ")", ":", "ip", "=", "get_ipython", "(", ")", "(", "funcname", ",", "name", ")", "=", "line", ".", "split", "(", ")", "import", "spyder", ".", "pyplot", "__fig__", "=", "spyder", ".", "pyplot", ".", "figure", "(", ")",...
spyders variable explorer magic used to generate plots .
train
true
23,718
def test_initial_column_fill_values(): class TestHeader(ascii.BasicHeader, ): def _set_cols_from_names(self): self.cols = [ascii.Column(name=x) for x in self.names] for col in self.cols: col.fill_values = {'--': '0'} class Tester(ascii.Basic, ): header_class = TestHeader reader = ascii.get_reader(Reader=Tester) assert (reader.read('# Column definition is the first uncommented line\n# Default delimiter is the space character.\na b c\n# Data starts after the header column definition, blank lines ignored\n-- 2 3\n4 5 6 ')['a'][0] is np.ma.masked)
[ "def", "test_initial_column_fill_values", "(", ")", ":", "class", "TestHeader", "(", "ascii", ".", "BasicHeader", ",", ")", ":", "def", "_set_cols_from_names", "(", "self", ")", ":", "self", ".", "cols", "=", "[", "ascii", ".", "Column", "(", "name", "=", ...
regression test for #5336 .
train
false
23,719
def get_stripped_lines(string, ignore_lines_starting_with=''): string = unicode(string) lines = [unicode(l.strip()) for l in string.splitlines()] if ignore_lines_starting_with: filter_func = (lambda x: (x and (not x.startswith(ignore_lines_starting_with)))) else: filter_func = (lambda x: x) lines = filter(filter_func, lines) return lines
[ "def", "get_stripped_lines", "(", "string", ",", "ignore_lines_starting_with", "=", "''", ")", ":", "string", "=", "unicode", "(", "string", ")", "lines", "=", "[", "unicode", "(", "l", ".", "strip", "(", ")", ")", "for", "l", "in", "string", ".", "spl...
split lines at newline char .
train
false
23,720
def set_selectors(facts): deployment_type = facts['common']['deployment_type'] if (deployment_type == 'online'): selector = 'type=infra' else: selector = 'region=infra' if ('hosted' not in facts): facts['hosted'] = {} if ('router' not in facts['hosted']): facts['hosted']['router'] = {} if (('selector' not in facts['hosted']['router']) or (facts['hosted']['router']['selector'] in [None, 'None'])): facts['hosted']['router']['selector'] = selector if ('registry' not in facts['hosted']): facts['hosted']['registry'] = {} if (('selector' not in facts['hosted']['registry']) or (facts['hosted']['registry']['selector'] in [None, 'None'])): facts['hosted']['registry']['selector'] = selector if ('metrics' not in facts['hosted']): facts['hosted']['metrics'] = {} if (('selector' not in facts['hosted']['metrics']) or (facts['hosted']['metrics']['selector'] in [None, 'None'])): facts['hosted']['metrics']['selector'] = None if ('logging' not in facts['hosted']): facts['hosted']['logging'] = {} if (('selector' not in facts['hosted']['logging']) or (facts['hosted']['logging']['selector'] in [None, 'None'])): facts['hosted']['logging']['selector'] = None return facts
[ "def", "set_selectors", "(", "facts", ")", ":", "deployment_type", "=", "facts", "[", "'common'", "]", "[", "'deployment_type'", "]", "if", "(", "deployment_type", "==", "'online'", ")", ":", "selector", "=", "'type=infra'", "else", ":", "selector", "=", "'r...
set selectors facts if not already present in facts dict args: facts : existing facts returns: dict: the facts dict updated with the generated selectors facts if they were not already present .
train
false
23,721
def read_in(path): with open(path, 'r') as file_fd: return file_fd.read()
[ "def", "read_in", "(", "path", ")", ":", "with", "open", "(", "path", ",", "'r'", ")", "as", "file_fd", ":", "return", "file_fd", ".", "read", "(", ")" ]
read in a file .
train
false
23,723
def get_parent_url(module, xml=None): if hasattr(module, 'xml_attributes'): return module.xml_attributes.get('parent_url', module.xml_attributes.get('parent_sequential_url')) if (xml is not None): create_xml_attributes(module, xml) return get_parent_url(module) return None
[ "def", "get_parent_url", "(", "module", ",", "xml", "=", "None", ")", ":", "if", "hasattr", "(", "module", ",", "'xml_attributes'", ")", ":", "return", "module", ".", "xml_attributes", ".", "get", "(", "'parent_url'", ",", "module", ".", "xml_attributes", ...
get the parent_url .
train
false
23,724
@task @log_call @hosts([(u'root@%s' % host) for host in env.hosts]) def secure(new_user=env.user): run(u'apt-get update -q') run(u'apt-get upgrade -y -q') run((u"adduser --gecos '' %s" % new_user)) run((u'usermod -G sudo %s' % new_user)) run(u"sed -i 's:RootLogin yes:RootLogin no:' /etc/ssh/sshd_config") run(u'service ssh restart') print(green((u"Security steps completed. Log in to the server as '%s' from now on." % new_user), bold=True))
[ "@", "task", "@", "log_call", "@", "hosts", "(", "[", "(", "u'root@%s'", "%", "host", ")", "for", "host", "in", "env", ".", "hosts", "]", ")", "def", "secure", "(", "new_user", "=", "env", ".", "user", ")", ":", "run", "(", "u'apt-get update -q'", ...
minimal security steps for brand new servers .
train
false
23,726
@utils.singledispatch def typeof_impl(val, c): tp = _typeof_buffer(val, c) if (tp is not None): return tp from . import cffi_utils if cffi_utils.SUPPORTED: if cffi_utils.is_cffi_func(val): return cffi_utils.make_function_type(val) if cffi_utils.is_ffi_instance(val): return types.ffi return getattr(val, '_numba_type_', None)
[ "@", "utils", ".", "singledispatch", "def", "typeof_impl", "(", "val", ",", "c", ")", ":", "tp", "=", "_typeof_buffer", "(", "val", ",", "c", ")", "if", "(", "tp", "is", "not", "None", ")", ":", "return", "tp", "from", ".", "import", "cffi_utils", ...
generic typeof() implementation .
train
false
23,727
def process_envs(attrs=None, where=None): return _osquery_cmd(table='process_envs', attrs=attrs, where=where)
[ "def", "process_envs", "(", "attrs", "=", "None", ",", "where", "=", "None", ")", ":", "return", "_osquery_cmd", "(", "table", "=", "'process_envs'", ",", "attrs", "=", "attrs", ",", "where", "=", "where", ")" ]
return process_envs information from osquery cli example: .
train
false
23,730
def read_ref(refname, repo_dir=None): refs = list_refs(refnames=[refname], repo_dir=repo_dir, limit_to_heads=True) l = tuple(islice(refs, 2)) if l: assert (len(l) == 1) return l[0][1] else: return None
[ "def", "read_ref", "(", "refname", ",", "repo_dir", "=", "None", ")", ":", "refs", "=", "list_refs", "(", "refnames", "=", "[", "refname", "]", ",", "repo_dir", "=", "repo_dir", ",", "limit_to_heads", "=", "True", ")", "l", "=", "tuple", "(", "islice",...
get the commit id of the most recent commit made on a given ref .
train
false
23,731
def test_20news_length_consistency(): try: data = datasets.fetch_20newsgroups(subset='all', download_if_missing=False, shuffle=False) except IOError: raise SkipTest('Download 20 newsgroups to run this test') data = datasets.fetch_20newsgroups(subset='all') assert_equal(len(data['data']), len(data.data)) assert_equal(len(data['target']), len(data.target)) assert_equal(len(data['filenames']), len(data.filenames))
[ "def", "test_20news_length_consistency", "(", ")", ":", "try", ":", "data", "=", "datasets", ".", "fetch_20newsgroups", "(", "subset", "=", "'all'", ",", "download_if_missing", "=", "False", ",", "shuffle", "=", "False", ")", "except", "IOError", ":", "raise",...
checks the length consistencies within the bunch this is a non-regression test for a bug present in 0 .
train
false
23,732
def generate_go_binary(target, source, env): return _generate_go_package(target, source, env)
[ "def", "generate_go_binary", "(", "target", ",", "source", ",", "env", ")", ":", "return", "_generate_go_package", "(", "target", ",", "source", ",", "env", ")" ]
generate go command executable .
train
false
23,733
def endpoint_delete(service, profile=None, **connection_args): kstone = auth(profile, **connection_args) endpoint = endpoint_get(service, profile, **connection_args) if ((not endpoint) or ('Error' in endpoint)): return {'Error': 'Could not find any endpoints for the service'} kstone.endpoints.delete(endpoint['id']) endpoint = endpoint_get(service, profile, **connection_args) if ((not endpoint) or ('Error' in endpoint)): return True
[ "def", "endpoint_delete", "(", "service", ",", "profile", "=", "None", ",", "**", "connection_args", ")", ":", "kstone", "=", "auth", "(", "profile", ",", "**", "connection_args", ")", "endpoint", "=", "endpoint_get", "(", "service", ",", "profile", ",", "...
delete endpoints of an openstack service cli examples: .
train
true
23,734
def pg_varchar(size=0): if size: if (not isinstance(size, int)): raise ValueError(('VARCHAR parameter should be an int, got %s' % type(size))) if (size > 0): return ('VARCHAR(%d)' % size) return 'VARCHAR'
[ "def", "pg_varchar", "(", "size", "=", "0", ")", ":", "if", "size", ":", "if", "(", "not", "isinstance", "(", "size", ",", "int", ")", ")", ":", "raise", "ValueError", "(", "(", "'VARCHAR parameter should be an int, got %s'", "%", "type", "(", "size", ")...
returns the varchar declaration for the provided size: * if no size return an infinite varchar * otherwise return a varchar(n) :type int size: varchar size .
train
false
23,736
def rehash(): return (win32gui.SendMessageTimeout(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment', 0, 10000)[0] == 1)
[ "def", "rehash", "(", ")", ":", "return", "(", "win32gui", ".", "SendMessageTimeout", "(", "win32con", ".", "HWND_BROADCAST", ",", "win32con", ".", "WM_SETTINGCHANGE", ",", "0", ",", "'Environment'", ",", "0", ",", "10000", ")", "[", "0", "]", "==", "1",...
run pyenv rehash to update the installed shims .
train
false
23,737
def tx_from_str(txt): import json txt = txt.strip() try: txt.decode('hex') is_hex = True except: is_hex = False if is_hex: return txt tx_dict = json.loads(str(txt)) assert ('hex' in tx_dict.keys()) return tx_dict['hex']
[ "def", "tx_from_str", "(", "txt", ")", ":", "import", "json", "txt", "=", "txt", ".", "strip", "(", ")", "try", ":", "txt", ".", "decode", "(", "'hex'", ")", "is_hex", "=", "True", "except", ":", "is_hex", "=", "False", "if", "is_hex", ":", "return...
json or raw hexadecimal .
train
false
23,740
def test_cd_home_dir(): homepath = '~/somepath' with cd(homepath): eq_(env.cwd, homepath)
[ "def", "test_cd_home_dir", "(", ")", ":", "homepath", "=", "'~/somepath'", "with", "cd", "(", "homepath", ")", ":", "eq_", "(", "env", ".", "cwd", ",", "homepath", ")" ]
cd() should work with home directories .
train
false
23,741
def check_experiment_dirs(expt_dir): output_subdir = os.path.join(expt_dir, 'output') check_dir(output_subdir) job_subdir = os.path.join(expt_dir, 'jobs') check_dir(job_subdir)
[ "def", "check_experiment_dirs", "(", "expt_dir", ")", ":", "output_subdir", "=", "os", ".", "path", ".", "join", "(", "expt_dir", ",", "'output'", ")", "check_dir", "(", "output_subdir", ")", "job_subdir", "=", "os", ".", "path", ".", "join", "(", "expt_di...
make output and jobs sub directories .
train
false
23,742
def get_valid_backend_qos_spec_from_volume_type(volume, volume_type): spec_key_values = get_backend_qos_spec_from_volume_type(volume_type) if (spec_key_values is None): return None validate_qos_spec(spec_key_values) return map_qos_spec(spec_key_values, volume)
[ "def", "get_valid_backend_qos_spec_from_volume_type", "(", "volume", ",", "volume_type", ")", ":", "spec_key_values", "=", "get_backend_qos_spec_from_volume_type", "(", "volume_type", ")", "if", "(", "spec_key_values", "is", "None", ")", ":", "return", "None", "validate...
given a volume type .
train
false
23,743
def IncrementId(high_id_key): (unused_start, end) = datastore.AllocateIds(high_id_key, max=high_id_key.id()) assert (end >= high_id_key.id())
[ "def", "IncrementId", "(", "high_id_key", ")", ":", "(", "unused_start", ",", "end", ")", "=", "datastore", ".", "AllocateIds", "(", "high_id_key", ",", "max", "=", "high_id_key", ".", "id", "(", ")", ")", "assert", "(", "end", ">=", "high_id_key", ".", ...
increment unique id counter associated with high_id_key beyond high_id_key .
train
false
23,745
def get_zip_class(): class ContextualZipFile(zipfile.ZipFile, ): def __enter__(self): return self def __exit__(self, type, value, traceback): self.close return (zipfile.ZipFile if hasattr(zipfile.ZipFile, '__exit__') else ContextualZipFile)
[ "def", "get_zip_class", "(", ")", ":", "class", "ContextualZipFile", "(", "zipfile", ".", "ZipFile", ",", ")", ":", "def", "__enter__", "(", "self", ")", ":", "return", "self", "def", "__exit__", "(", "self", ",", "type", ",", "value", ",", "traceback", ...
supplement zipfile class to support context manager for python 2 .
train
true
23,746
def all_continuous(vars): vars_ = [var for var in vars if (not isinstance(var, pm.model.ObservedRV))] if any([(var.dtype in pm.discrete_types) for var in vars_]): return False else: return True
[ "def", "all_continuous", "(", "vars", ")", ":", "vars_", "=", "[", "var", "for", "var", "in", "vars", "if", "(", "not", "isinstance", "(", "var", ",", "pm", ".", "model", ".", "ObservedRV", ")", ")", "]", "if", "any", "(", "[", "(", "var", ".", ...
check that vars not include discrete variables .
train
false
23,747
def add_container_page_publishing_info(xblock, xblock_info): def safe_get_username(user_id): '\n Guard against bad user_ids, like the infamous "**replace_user**".\n Note that this will ignore our special known IDs (ModuleStoreEnum.UserID).\n We should consider adding special handling for those values.\n\n :param user_id: the user id to get the username of\n :return: username, or None if the user does not exist or user_id is None\n ' if user_id: try: return User.objects.get(id=user_id).username except: pass return None xblock_info['edited_by'] = safe_get_username(xblock.subtree_edited_by) xblock_info['published_by'] = safe_get_username(xblock.published_by) xblock_info['currently_visible_to_students'] = is_currently_visible_to_students(xblock) xblock_info['has_content_group_components'] = has_children_visible_to_specific_content_groups(xblock) if xblock_info['release_date']: xblock_info['release_date_from'] = _get_release_date_from(xblock) if (xblock_info['visibility_state'] == VisibilityState.staff_only): xblock_info['staff_lock_from'] = _get_staff_lock_from(xblock) else: xblock_info['staff_lock_from'] = None
[ "def", "add_container_page_publishing_info", "(", "xblock", ",", "xblock_info", ")", ":", "def", "safe_get_username", "(", "user_id", ")", ":", "if", "user_id", ":", "try", ":", "return", "User", ".", "objects", ".", "get", "(", "id", "=", "user_id", ")", ...
adds information about the xblocks publish state to the supplied xblock_info for the container page .
train
false
23,748
def libvlc_video_take_snapshot(p_mi, num, psz_filepath, i_width, i_height): f = (_Cfunctions.get('libvlc_video_take_snapshot', None) or _Cfunction('libvlc_video_take_snapshot', ((1,), (1,), (1,), (1,), (1,)), None, ctypes.c_int, MediaPlayer, ctypes.c_uint, ctypes.c_char_p, ctypes.c_int, ctypes.c_int)) return f(p_mi, num, psz_filepath, i_width, i_height)
[ "def", "libvlc_video_take_snapshot", "(", "p_mi", ",", "num", ",", "psz_filepath", ",", "i_width", ",", "i_height", ")", ":", "f", "=", "(", "_Cfunctions", ".", "get", "(", "'libvlc_video_take_snapshot'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_vid...
take a snapshot of the current video window .
train
true
23,749
def unique_combinations(items, n): if (n == 0): (yield []) else: for i in xrange(((len(items) - n) + 1)): for cc in unique_combinations(items[(i + 1):], (n - 1)): (yield ([items[i]] + cc))
[ "def", "unique_combinations", "(", "items", ",", "n", ")", ":", "if", "(", "n", "==", "0", ")", ":", "(", "yield", "[", "]", ")", "else", ":", "for", "i", "in", "xrange", "(", "(", "(", "len", "(", "items", ")", "-", "n", ")", "+", "1", ")"...
return n-length tuples .
train
false
23,750
@Profiler.profile def test_dbapi_raw_w_connect(n): _test_dbapi_raw(n, True)
[ "@", "Profiler", ".", "profile", "def", "test_dbapi_raw_w_connect", "(", "n", ")", ":", "_test_dbapi_raw", "(", "n", ",", "True", ")" ]
individual insert/commit pairs w/ dbapi + connection each time .
train
false
23,751
def cr_uid(method): method._api = 'cr_uid' return method
[ "def", "cr_uid", "(", "method", ")", ":", "method", ".", "_api", "=", "'cr_uid'", "return", "method" ]
decorate a traditional-style method that takes cr .
train
false
23,754
def _convert_to_initializer(initializer): if isinstance(initializer, str): return getattr(tf, (initializer + '_initializer')) elif isinstance(initializer, np.ndarray): return tf.constant_initializer(initializer) else: return initializer
[ "def", "_convert_to_initializer", "(", "initializer", ")", ":", "if", "isinstance", "(", "initializer", ",", "str", ")", ":", "return", "getattr", "(", "tf", ",", "(", "initializer", "+", "'_initializer'", ")", ")", "elif", "isinstance", "(", "initializer", ...
returns a tensorflow initializer .
train
false
23,755
def search_paths_from_description(desc): paths = [] if desc.package: dirname = package_dirname(desc.package) paths.append(('', dirname)) elif desc.qualified_name: dirname = package_dirname(package(desc.qualified_name)) paths.append(('', dirname)) if hasattr(desc, 'search_paths'): paths.extend(desc.search_paths) return paths
[ "def", "search_paths_from_description", "(", "desc", ")", ":", "paths", "=", "[", "]", "if", "desc", ".", "package", ":", "dirname", "=", "package_dirname", "(", "desc", ".", "package", ")", "paths", ".", "append", "(", "(", "''", ",", "dirname", ")", ...
return the search paths for the category/widgetdescription .
train
false
23,756
def auth_str_equal(provided, known): result = 0 p_len = len(provided) k_len = len(known) for i in xrange(p_len): a = (ord(provided[i]) if (i < p_len) else 0) b = (ord(known[i]) if (i < k_len) else 0) result |= (a ^ b) return ((p_len == k_len) & (result == 0))
[ "def", "auth_str_equal", "(", "provided", ",", "known", ")", ":", "result", "=", "0", "p_len", "=", "len", "(", "provided", ")", "k_len", "=", "len", "(", "known", ")", "for", "i", "in", "xrange", "(", "p_len", ")", ":", "a", "=", "(", "ord", "("...
constant-time string comparison .
train
false
23,757
def demo_multiposition_feature(): postag(templates=[Template(Pos([(-3), (-2), (-1)]))])
[ "def", "demo_multiposition_feature", "(", ")", ":", "postag", "(", "templates", "=", "[", "Template", "(", "Pos", "(", "[", "(", "-", "3", ")", ",", "(", "-", "2", ")", ",", "(", "-", "1", ")", "]", ")", ")", "]", ")" ]
the feature/s of a template takes a list of positions relative to the current word where the feature should be looked for .
train
false
23,758
def _password_validators_help_text_html(password_validators=None): help_texts = password_validators_help_texts(password_validators) help_items = [format_html('<li>{}</li>', help_text) for help_text in help_texts] return (('<ul>%s</ul>' % ''.join(help_items)) if help_items else '')
[ "def", "_password_validators_help_text_html", "(", "password_validators", "=", "None", ")", ":", "help_texts", "=", "password_validators_help_texts", "(", "password_validators", ")", "help_items", "=", "[", "format_html", "(", "'<li>{}</li>'", ",", "help_text", ")", "fo...
return an html string with all help texts of all configured validators in an <ul> .
train
false
23,759
@utils.expects_func_args('instance') def reverts_task_state(function): @functools.wraps(function) def decorated_function(self, context, *args, **kwargs): try: return function(self, context, *args, **kwargs) except exception.UnexpectedTaskStateError as e: with excutils.save_and_reraise_exception(): LOG.info(_LI('Task possibly preempted: %s'), e.format_message()) except Exception: with excutils.save_and_reraise_exception(): wrapped_func = safe_utils.get_wrapped_function(function) keyed_args = inspect.getcallargs(wrapped_func, self, context, *args, **kwargs) instance = keyed_args['instance'] original_task_state = instance.task_state try: self._instance_update(context, instance, task_state=None) LOG.info(_LI('Successfully reverted task state from %s on failure for instance.'), original_task_state, instance=instance) except exception.InstanceNotFound: pass except Exception as e: msg = _LW('Failed to revert task state for instance. Error: %s') LOG.warning(msg, e, instance=instance) return decorated_function
[ "@", "utils", ".", "expects_func_args", "(", "'instance'", ")", "def", "reverts_task_state", "(", "function", ")", ":", "@", "functools", ".", "wraps", "(", "function", ")", "def", "decorated_function", "(", "self", ",", "context", ",", "*", "args", ",", "...
decorator to revert task_state on failure .
train
false
23,760
def validate_matrix_shape(name, shape, nrows, ncols, nobs): ndim = len(shape) if (ndim not in [2, 3]): raise ValueError(('Invalid value for %s matrix. Requires a 2- or 3-dimensional array, got %d dimensions' % (name, ndim))) if (not (shape[0] == nrows)): raise ValueError(('Invalid dimensions for %s matrix: requires %d rows, got %d' % (name, nrows, shape[0]))) if (not (shape[1] == ncols)): raise ValueError(('Invalid dimensions for %s matrix: requires %d columns, got %d' % (name, ncols, shape[1]))) if ((nobs is None) and (not ((ndim == 2) or (shape[(-1)] == 1)))): raise ValueError(('Invalid dimensions for %s matrix: time-varying matrices cannot be given unless `nobs` is specified (implicitly when a dataset is bound or else set explicity)' % name)) if ((ndim == 3) and (nobs is not None) and (not (shape[(-1)] in [1, nobs]))): raise ValueError(('Invalid dimensions for time-varying %s matrix. Requires shape (*,*,%d), got %s' % (name, nobs, str(shape))))
[ "def", "validate_matrix_shape", "(", "name", ",", "shape", ",", "nrows", ",", "ncols", ",", "nobs", ")", ":", "ndim", "=", "len", "(", "shape", ")", "if", "(", "ndim", "not", "in", "[", "2", ",", "3", "]", ")", ":", "raise", "ValueError", "(", "(...
validate the shape of a possibly time-varying matrix .
train
false
23,761
def get_average(temp_base): if (not hasattr(get_average, 'temp')): get_average.temp = [temp_base, temp_base, temp_base] get_average.temp[2] = get_average.temp[1] get_average.temp[1] = get_average.temp[0] get_average.temp[0] = temp_base temp_avg = (((get_average.temp[0] + get_average.temp[1]) + get_average.temp[2]) / 3) return temp_avg
[ "def", "get_average", "(", "temp_base", ")", ":", "if", "(", "not", "hasattr", "(", "get_average", ",", "'temp'", ")", ")", ":", "get_average", ".", "temp", "=", "[", "temp_base", ",", "temp_base", ",", "temp_base", "]", "get_average", ".", "temp", "[", ...
use moving average to get better readings .
train
false
23,763
@profiler.trace def rule_list_for_tenant(request, tenant_id, **kwargs): rules = rule_list(request, tenant_id=tenant_id, shared=False, **kwargs) shared_rules = rule_list(request, shared=True, **kwargs) return (rules + shared_rules)
[ "@", "profiler", ".", "trace", "def", "rule_list_for_tenant", "(", "request", ",", "tenant_id", ",", "**", "kwargs", ")", ":", "rules", "=", "rule_list", "(", "request", ",", "tenant_id", "=", "tenant_id", ",", "shared", "=", "False", ",", "**", "kwargs", ...
return a rule list available for the tenant .
train
false
23,765
def _future_expose_api_anonymous_and_sessionless(func, to_json=True): return _future_expose_api(func, to_json=to_json, user_required=False, user_or_session_required=False)
[ "def", "_future_expose_api_anonymous_and_sessionless", "(", "func", ",", "to_json", "=", "True", ")", ":", "return", "_future_expose_api", "(", "func", ",", "to_json", "=", "to_json", ",", "user_required", "=", "False", ",", "user_or_session_required", "=", "False",...
expose this function via the api but dont require a user or a galaxy_session .
train
false
23,766
def running_under_virtualenv(): return hasattr(sys, 'real_prefix')
[ "def", "running_under_virtualenv", "(", ")", ":", "return", "hasattr", "(", "sys", ",", "'real_prefix'", ")" ]
return true if were running inside a virtualenv .
train
false
23,767
def setitem(a, b, c): a[b] = c
[ "def", "setitem", "(", "a", ",", "b", ",", "c", ")", ":", "a", "[", "b", "]", "=", "c" ]
same as a[b] = c .
train
false
23,768
def show_offload(devname): try: sg = ((ethtool.get_sg(devname) and 'on') or 'off') except IOError: sg = 'not supported' try: tso = ((ethtool.get_tso(devname) and 'on') or 'off') except IOError: tso = 'not supported' try: ufo = ((ethtool.get_ufo(devname) and 'on') or 'off') except IOError: ufo = 'not supported' try: gso = ((ethtool.get_gso(devname) and 'on') or 'off') except IOError: gso = 'not supported' offload = {'scatter_gather': sg, 'tcp_segmentation_offload': tso, 'udp_fragmentation_offload': ufo, 'generic_segmentation_offload': gso} return offload
[ "def", "show_offload", "(", "devname", ")", ":", "try", ":", "sg", "=", "(", "(", "ethtool", ".", "get_sg", "(", "devname", ")", "and", "'on'", ")", "or", "'off'", ")", "except", "IOError", ":", "sg", "=", "'not supported'", "try", ":", "tso", "=", ...
queries the specified network device for the state of protocol offload and other features cli example: .
train
true