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 |
|---|---|---|---|---|---|
20,367 | def _add_missing_symbol(symbol, addr):
if (not ll.address_of_symbol(symbol)):
ll.add_symbol(symbol, addr)
| [
"def",
"_add_missing_symbol",
"(",
"symbol",
",",
"addr",
")",
":",
"if",
"(",
"not",
"ll",
".",
"address_of_symbol",
"(",
"symbol",
")",
")",
":",
"ll",
".",
"add_symbol",
"(",
"symbol",
",",
"addr",
")"
] | add missing symbol into llvm internal symtab . | train | false |
20,369 | def rowcol_pair_to_cellrange(row1, col1, row2, col2, row1_abs=False, col1_abs=False, row2_abs=False, col2_abs=False):
assert (row1 <= row2)
assert (col1 <= col2)
return ((rowcol_to_cell(row1, col1, row1_abs, col1_abs) + ':') + rowcol_to_cell(row2, col2, row2_abs, col2_abs))
| [
"def",
"rowcol_pair_to_cellrange",
"(",
"row1",
",",
"col1",
",",
"row2",
",",
"col2",
",",
"row1_abs",
"=",
"False",
",",
"col1_abs",
"=",
"False",
",",
"row2_abs",
"=",
"False",
",",
"col2_abs",
"=",
"False",
")",
":",
"assert",
"(",
"row1",
"<=",
"row2",
")",
"assert",
"(",
"col1",
"<=",
"col2",
")",
"return",
"(",
"(",
"rowcol_to_cell",
"(",
"row1",
",",
"col1",
",",
"row1_abs",
",",
"col1_abs",
")",
"+",
"':'",
")",
"+",
"rowcol_to_cell",
"(",
"row2",
",",
"col2",
",",
"row2_abs",
",",
"col2_abs",
")",
")"
] | convert two pairs into a cell range string in a1:b2 notation . | train | false |
20,370 | def _AddActionStep(actions_dict, inputs, outputs, description, command):
assert inputs
action = {'inputs': inputs, 'outputs': outputs, 'description': description, 'command': command}
chosen_input = inputs[0]
if (chosen_input not in actions_dict):
actions_dict[chosen_input] = []
actions_dict[chosen_input].append(action)
| [
"def",
"_AddActionStep",
"(",
"actions_dict",
",",
"inputs",
",",
"outputs",
",",
"description",
",",
"command",
")",
":",
"assert",
"inputs",
"action",
"=",
"{",
"'inputs'",
":",
"inputs",
",",
"'outputs'",
":",
"outputs",
",",
"'description'",
":",
"description",
",",
"'command'",
":",
"command",
"}",
"chosen_input",
"=",
"inputs",
"[",
"0",
"]",
"if",
"(",
"chosen_input",
"not",
"in",
"actions_dict",
")",
":",
"actions_dict",
"[",
"chosen_input",
"]",
"=",
"[",
"]",
"actions_dict",
"[",
"chosen_input",
"]",
".",
"append",
"(",
"action",
")"
] | merge action into an existing list of actions . | train | false |
20,371 | def _write_file_routes(iface, data, folder, pattern):
filename = os.path.join(folder, pattern.format(iface))
if (not os.path.exists(folder)):
msg = '{0} cannot be written. {1} does not exist'
msg = msg.format(filename, folder)
log.error(msg)
raise AttributeError(msg)
with salt.utils.flopen(filename, 'w') as fout:
fout.write(data)
__salt__['file.set_mode'](filename, '0755')
return filename
| [
"def",
"_write_file_routes",
"(",
"iface",
",",
"data",
",",
"folder",
",",
"pattern",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"folder",
",",
"pattern",
".",
"format",
"(",
"iface",
")",
")",
"if",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"folder",
")",
")",
":",
"msg",
"=",
"'{0} cannot be written. {1} does not exist'",
"msg",
"=",
"msg",
".",
"format",
"(",
"filename",
",",
"folder",
")",
"log",
".",
"error",
"(",
"msg",
")",
"raise",
"AttributeError",
"(",
"msg",
")",
"with",
"salt",
".",
"utils",
".",
"flopen",
"(",
"filename",
",",
"'w'",
")",
"as",
"fout",
":",
"fout",
".",
"write",
"(",
"data",
")",
"__salt__",
"[",
"'file.set_mode'",
"]",
"(",
"filename",
",",
"'0755'",
")",
"return",
"filename"
] | writes a file to disk . | train | false |
20,372 | def test_renn_fit_single_class():
renn = RepeatedEditedNearestNeighbours(random_state=RND_SEED)
y_single_class = np.zeros((X.shape[0],))
assert_warns(UserWarning, renn.fit, X, y_single_class)
| [
"def",
"test_renn_fit_single_class",
"(",
")",
":",
"renn",
"=",
"RepeatedEditedNearestNeighbours",
"(",
"random_state",
"=",
"RND_SEED",
")",
"y_single_class",
"=",
"np",
".",
"zeros",
"(",
"(",
"X",
".",
"shape",
"[",
"0",
"]",
",",
")",
")",
"assert_warns",
"(",
"UserWarning",
",",
"renn",
".",
"fit",
",",
"X",
",",
"y_single_class",
")"
] | test either if an error when there is a single class . | train | false |
20,373 | def generate_nonce():
return random.randrange(1000000000, 2000000000)
| [
"def",
"generate_nonce",
"(",
")",
":",
"return",
"random",
".",
"randrange",
"(",
"1000000000",
",",
"2000000000",
")"
] | generate pseudorandom nonce that is unlikely to repeat . | train | false |
20,374 | @commands(u'gettz', u'gettimezone')
@example(u'.gettz [nick]')
def get_user_tz(bot, trigger):
if (not pytz):
bot.reply(u"Sorry, I don't have timezone support installed.")
else:
nick = trigger.group(2)
if (not nick):
nick = trigger.nick
nick = nick.strip()
tz = bot.db.get_nick_value(nick, u'timezone')
if tz:
bot.say((u"%s's time zone is %s." % (nick, tz)))
else:
bot.say((u'%s has not set their time zone' % nick))
| [
"@",
"commands",
"(",
"u'gettz'",
",",
"u'gettimezone'",
")",
"@",
"example",
"(",
"u'.gettz [nick]'",
")",
"def",
"get_user_tz",
"(",
"bot",
",",
"trigger",
")",
":",
"if",
"(",
"not",
"pytz",
")",
":",
"bot",
".",
"reply",
"(",
"u\"Sorry, I don't have timezone support installed.\"",
")",
"else",
":",
"nick",
"=",
"trigger",
".",
"group",
"(",
"2",
")",
"if",
"(",
"not",
"nick",
")",
":",
"nick",
"=",
"trigger",
".",
"nick",
"nick",
"=",
"nick",
".",
"strip",
"(",
")",
"tz",
"=",
"bot",
".",
"db",
".",
"get_nick_value",
"(",
"nick",
",",
"u'timezone'",
")",
"if",
"tz",
":",
"bot",
".",
"say",
"(",
"(",
"u\"%s's time zone is %s.\"",
"%",
"(",
"nick",
",",
"tz",
")",
")",
")",
"else",
":",
"bot",
".",
"say",
"(",
"(",
"u'%s has not set their time zone'",
"%",
"nick",
")",
")"
] | gets a users preferred time zone . | train | false |
20,375 | def typeStr(obj):
typ = type(obj)
if (typ == getattr(types, 'InstanceType', None)):
return ('<instance of %s>' % obj.__class__.__name__)
else:
return str(typ)
| [
"def",
"typeStr",
"(",
"obj",
")",
":",
"typ",
"=",
"type",
"(",
"obj",
")",
"if",
"(",
"typ",
"==",
"getattr",
"(",
"types",
",",
"'InstanceType'",
",",
"None",
")",
")",
":",
"return",
"(",
"'<instance of %s>'",
"%",
"obj",
".",
"__class__",
".",
"__name__",
")",
"else",
":",
"return",
"str",
"(",
"typ",
")"
] | create a more useful type string by making <instance> types report their class . | train | false |
20,377 | def literal_string(s):
return ((u"'" + s.replace(u"'", u"''").replace(u'\x00', '')) + u"'")
| [
"def",
"literal_string",
"(",
"s",
")",
":",
"return",
"(",
"(",
"u\"'\"",
"+",
"s",
".",
"replace",
"(",
"u\"'\"",
",",
"u\"''\"",
")",
".",
"replace",
"(",
"u'\\x00'",
",",
"''",
")",
")",
"+",
"u\"'\"",
")"
] | return s as a postgres literal string . | train | false |
20,379 | def set_process_name(process_name):
_set_argv(process_name)
if (platform.system() == 'Linux'):
_set_prctl_name(process_name)
elif (platform.system() in ('Darwin', 'FreeBSD', 'OpenBSD')):
_set_proc_title(process_name)
| [
"def",
"set_process_name",
"(",
"process_name",
")",
":",
"_set_argv",
"(",
"process_name",
")",
"if",
"(",
"platform",
".",
"system",
"(",
")",
"==",
"'Linux'",
")",
":",
"_set_prctl_name",
"(",
"process_name",
")",
"elif",
"(",
"platform",
".",
"system",
"(",
")",
"in",
"(",
"'Darwin'",
",",
"'FreeBSD'",
",",
"'OpenBSD'",
")",
")",
":",
"_set_proc_title",
"(",
"process_name",
")"
] | renames our current process from "python <args>" to a custom name . | train | false |
20,380 | def loadExperiment(path):
if (not os.path.isdir(path)):
path = os.path.dirname(path)
descriptionPyModule = loadExperimentDescriptionScriptFromDir(path)
expIface = getExperimentDescriptionInterfaceFromModule(descriptionPyModule)
return (expIface.getModelDescription(), expIface.getModelControl())
| [
"def",
"loadExperiment",
"(",
"path",
")",
":",
"if",
"(",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
"descriptionPyModule",
"=",
"loadExperimentDescriptionScriptFromDir",
"(",
"path",
")",
"expIface",
"=",
"getExperimentDescriptionInterfaceFromModule",
"(",
"descriptionPyModule",
")",
"return",
"(",
"expIface",
".",
"getModelDescription",
"(",
")",
",",
"expIface",
".",
"getModelControl",
"(",
")",
")"
] | loads the experiment description file from the path . | train | true |
20,382 | def retention_policy_get(database, name, user=None, password=None, host=None, port=None):
client = _client(user=user, password=password, host=host, port=port)
for policy in client.get_list_retention_policies(database):
if (policy['name'] == name):
return policy
return None
| [
"def",
"retention_policy_get",
"(",
"database",
",",
"name",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"client",
"=",
"_client",
"(",
"user",
"=",
"user",
",",
"password",
"=",
"password",
",",
"host",
"=",
"host",
",",
"port",
"=",
"port",
")",
"for",
"policy",
"in",
"client",
".",
"get_list_retention_policies",
"(",
"database",
")",
":",
"if",
"(",
"policy",
"[",
"'name'",
"]",
"==",
"name",
")",
":",
"return",
"policy",
"return",
"None"
] | get an existing retention policy . | train | true |
20,384 | def get_current_job(connection=None):
job_id = _job_stack.top
if (job_id is None):
return None
return Job.fetch(job_id, connection=connection)
| [
"def",
"get_current_job",
"(",
"connection",
"=",
"None",
")",
":",
"job_id",
"=",
"_job_stack",
".",
"top",
"if",
"(",
"job_id",
"is",
"None",
")",
":",
"return",
"None",
"return",
"Job",
".",
"fetch",
"(",
"job_id",
",",
"connection",
"=",
"connection",
")"
] | returns the job instance that is currently being executed . | train | false |
20,386 | def id_function(fixture_value):
(addon_status, file_status, review_type) = fixture_value
return '{0}-{1}-{2}'.format(amo.STATUS_CHOICES_API[addon_status], amo.STATUS_CHOICES_API[file_status], review_type)
| [
"def",
"id_function",
"(",
"fixture_value",
")",
":",
"(",
"addon_status",
",",
"file_status",
",",
"review_type",
")",
"=",
"fixture_value",
"return",
"'{0}-{1}-{2}'",
".",
"format",
"(",
"amo",
".",
"STATUS_CHOICES_API",
"[",
"addon_status",
"]",
",",
"amo",
".",
"STATUS_CHOICES_API",
"[",
"file_status",
"]",
",",
"review_type",
")"
] | convert a param from the use_case fixture to a nicer name . | train | false |
20,388 | def removePrefixFromDictionary(dictionary, prefix):
for key in dictionary.keys():
if key.startswith(prefix):
del dictionary[key]
| [
"def",
"removePrefixFromDictionary",
"(",
"dictionary",
",",
"prefix",
")",
":",
"for",
"key",
"in",
"dictionary",
".",
"keys",
"(",
")",
":",
"if",
"key",
".",
"startswith",
"(",
"prefix",
")",
":",
"del",
"dictionary",
"[",
"key",
"]"
] | remove the attributes starting with the prefix from the dictionary . | train | false |
20,389 | def makeZip(fileList, archive):
try:
a = zipfile.ZipFile(archive, u'w', zipfile.ZIP_DEFLATED, allowZip64=True)
for f in fileList:
a.write(f)
a.close()
return True
except Exception as e:
sickrage.srCore.srLogger.error((u'Zip creation error: %r ' % repr(e)))
return False
| [
"def",
"makeZip",
"(",
"fileList",
",",
"archive",
")",
":",
"try",
":",
"a",
"=",
"zipfile",
".",
"ZipFile",
"(",
"archive",
",",
"u'w'",
",",
"zipfile",
".",
"ZIP_DEFLATED",
",",
"allowZip64",
"=",
"True",
")",
"for",
"f",
"in",
"fileList",
":",
"a",
".",
"write",
"(",
"f",
")",
"a",
".",
"close",
"(",
")",
"return",
"True",
"except",
"Exception",
"as",
"e",
":",
"sickrage",
".",
"srCore",
".",
"srLogger",
".",
"error",
"(",
"(",
"u'Zip creation error: %r '",
"%",
"repr",
"(",
"e",
")",
")",
")",
"return",
"False"
] | create a zip of files . | train | false |
20,390 | @receiver(user_logged_in)
def post_login_handler(sender, request, user, **kwargs):
if (getattr(user, u'backend', u'').endswith(u'.EmailAuth') and (not user.has_usable_password())):
request.session[u'show_set_password'] = True
profile = Profile.objects.get_or_create(user=user)[0]
if (user.has_usable_password() and user.email and (not user.social_auth.filter(provider=u'email').exists())):
social = user.social_auth.create(provider=u'email', uid=user.email)
VerifiedEmail.objects.create(social=social, email=user.email)
set_lang(request, profile)
if (not user.email):
messages.error(request, _(u'You can not submit translations as you do not have assigned any email address.'))
| [
"@",
"receiver",
"(",
"user_logged_in",
")",
"def",
"post_login_handler",
"(",
"sender",
",",
"request",
",",
"user",
",",
"**",
"kwargs",
")",
":",
"if",
"(",
"getattr",
"(",
"user",
",",
"u'backend'",
",",
"u''",
")",
".",
"endswith",
"(",
"u'.EmailAuth'",
")",
"and",
"(",
"not",
"user",
".",
"has_usable_password",
"(",
")",
")",
")",
":",
"request",
".",
"session",
"[",
"u'show_set_password'",
"]",
"=",
"True",
"profile",
"=",
"Profile",
".",
"objects",
".",
"get_or_create",
"(",
"user",
"=",
"user",
")",
"[",
"0",
"]",
"if",
"(",
"user",
".",
"has_usable_password",
"(",
")",
"and",
"user",
".",
"email",
"and",
"(",
"not",
"user",
".",
"social_auth",
".",
"filter",
"(",
"provider",
"=",
"u'email'",
")",
".",
"exists",
"(",
")",
")",
")",
":",
"social",
"=",
"user",
".",
"social_auth",
".",
"create",
"(",
"provider",
"=",
"u'email'",
",",
"uid",
"=",
"user",
".",
"email",
")",
"VerifiedEmail",
".",
"objects",
".",
"create",
"(",
"social",
"=",
"social",
",",
"email",
"=",
"user",
".",
"email",
")",
"set_lang",
"(",
"request",
",",
"profile",
")",
"if",
"(",
"not",
"user",
".",
"email",
")",
":",
"messages",
".",
"error",
"(",
"request",
",",
"_",
"(",
"u'You can not submit translations as you do not have assigned any email address.'",
")",
")"
] | signal handler for setting user language and migrating profile if needed . | train | false |
20,391 | def require_moderator(handler):
def test_is_moderator(self, **kwargs):
'Check that the user is a moderator.'
if (not self.user_id):
self.redirect(current_user_services.create_login_url(self.request.uri))
return
if (not rights_manager.Actor(self.user_id).is_moderator()):
raise self.UnauthorizedUserException('You do not have the credentials to access this page.')
return handler(self, **kwargs)
return test_is_moderator
| [
"def",
"require_moderator",
"(",
"handler",
")",
":",
"def",
"test_is_moderator",
"(",
"self",
",",
"**",
"kwargs",
")",
":",
"if",
"(",
"not",
"self",
".",
"user_id",
")",
":",
"self",
".",
"redirect",
"(",
"current_user_services",
".",
"create_login_url",
"(",
"self",
".",
"request",
".",
"uri",
")",
")",
"return",
"if",
"(",
"not",
"rights_manager",
".",
"Actor",
"(",
"self",
".",
"user_id",
")",
".",
"is_moderator",
"(",
")",
")",
":",
"raise",
"self",
".",
"UnauthorizedUserException",
"(",
"'You do not have the credentials to access this page.'",
")",
"return",
"handler",
"(",
"self",
",",
"**",
"kwargs",
")",
"return",
"test_is_moderator"
] | decorator that checks if the current user is a moderator . | train | false |
20,392 | def log_to_stream(name=None, stream=None, format=None, level=None, debug=False):
if (level is None):
level = (logging.DEBUG if debug else logging.INFO)
if (format is None):
format = '%(message)s'
if (stream is None):
stream = sys.stderr
handler = logging.StreamHandler(stream)
handler.setLevel(level)
handler.setFormatter(logging.Formatter(format))
logger = logging.getLogger(name)
logger.setLevel(level)
logger.addHandler(handler)
| [
"def",
"log_to_stream",
"(",
"name",
"=",
"None",
",",
"stream",
"=",
"None",
",",
"format",
"=",
"None",
",",
"level",
"=",
"None",
",",
"debug",
"=",
"False",
")",
":",
"if",
"(",
"level",
"is",
"None",
")",
":",
"level",
"=",
"(",
"logging",
".",
"DEBUG",
"if",
"debug",
"else",
"logging",
".",
"INFO",
")",
"if",
"(",
"format",
"is",
"None",
")",
":",
"format",
"=",
"'%(message)s'",
"if",
"(",
"stream",
"is",
"None",
")",
":",
"stream",
"=",
"sys",
".",
"stderr",
"handler",
"=",
"logging",
".",
"StreamHandler",
"(",
"stream",
")",
"handler",
".",
"setLevel",
"(",
"level",
")",
"handler",
".",
"setFormatter",
"(",
"logging",
".",
"Formatter",
"(",
"format",
")",
")",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"name",
")",
"logger",
".",
"setLevel",
"(",
"level",
")",
"logger",
".",
"addHandler",
"(",
"handler",
")"
] | set up logging . | train | false |
20,393 | def purge_processor(caller):
try:
del caller.ndb.batch_stack
del caller.ndb.batch_stackptr
del caller.ndb.batch_pythonpath
del caller.ndb.batch_batchmode
except:
pass
if caller.ndb.batch_cmdset_backup:
caller.cmdset.cmdset_stack = caller.ndb.batch_cmdset_backup
caller.cmdset.update()
del caller.ndb.batch_cmdset_backup
else:
caller.cmdset.clear()
caller.scripts.validate()
| [
"def",
"purge_processor",
"(",
"caller",
")",
":",
"try",
":",
"del",
"caller",
".",
"ndb",
".",
"batch_stack",
"del",
"caller",
".",
"ndb",
".",
"batch_stackptr",
"del",
"caller",
".",
"ndb",
".",
"batch_pythonpath",
"del",
"caller",
".",
"ndb",
".",
"batch_batchmode",
"except",
":",
"pass",
"if",
"caller",
".",
"ndb",
".",
"batch_cmdset_backup",
":",
"caller",
".",
"cmdset",
".",
"cmdset_stack",
"=",
"caller",
".",
"ndb",
".",
"batch_cmdset_backup",
"caller",
".",
"cmdset",
".",
"update",
"(",
")",
"del",
"caller",
".",
"ndb",
".",
"batch_cmdset_backup",
"else",
":",
"caller",
".",
"cmdset",
".",
"clear",
"(",
")",
"caller",
".",
"scripts",
".",
"validate",
"(",
")"
] | this purges all effects running on the caller . | train | false |
20,394 | def apply_transition_sequence(parser, doc, sequence):
for action_name in sequence:
if (u'-' in action_name):
(move, label) = action_name.split(u'-')
parser.add_label(label)
with parser.step_through(doc) as stepwise:
for transition in sequence:
stepwise.transition(transition)
| [
"def",
"apply_transition_sequence",
"(",
"parser",
",",
"doc",
",",
"sequence",
")",
":",
"for",
"action_name",
"in",
"sequence",
":",
"if",
"(",
"u'-'",
"in",
"action_name",
")",
":",
"(",
"move",
",",
"label",
")",
"=",
"action_name",
".",
"split",
"(",
"u'-'",
")",
"parser",
".",
"add_label",
"(",
"label",
")",
"with",
"parser",
".",
"step_through",
"(",
"doc",
")",
"as",
"stepwise",
":",
"for",
"transition",
"in",
"sequence",
":",
"stepwise",
".",
"transition",
"(",
"transition",
")"
] | perform a series of pre-specified transitions . | train | false |
20,395 | def utf8_recoder(stream, encoding):
for line in codecs.getreader(encoding)(stream):
(yield line.encode('utf-8'))
| [
"def",
"utf8_recoder",
"(",
"stream",
",",
"encoding",
")",
":",
"for",
"line",
"in",
"codecs",
".",
"getreader",
"(",
"encoding",
")",
"(",
"stream",
")",
":",
"(",
"yield",
"line",
".",
"encode",
"(",
"'utf-8'",
")",
")"
] | generator that reads an encoded stream and reencodes to utf-8 . | train | false |
20,396 | def _filter_for_numa_threads(possible, wantthreads):
mostthreads = 0
for topology in possible:
if (topology.threads > wantthreads):
continue
if (topology.threads > mostthreads):
mostthreads = topology.threads
bestthreads = []
for topology in possible:
if (topology.threads != mostthreads):
continue
bestthreads.append(topology)
return bestthreads
| [
"def",
"_filter_for_numa_threads",
"(",
"possible",
",",
"wantthreads",
")",
":",
"mostthreads",
"=",
"0",
"for",
"topology",
"in",
"possible",
":",
"if",
"(",
"topology",
".",
"threads",
">",
"wantthreads",
")",
":",
"continue",
"if",
"(",
"topology",
".",
"threads",
">",
"mostthreads",
")",
":",
"mostthreads",
"=",
"topology",
".",
"threads",
"bestthreads",
"=",
"[",
"]",
"for",
"topology",
"in",
"possible",
":",
"if",
"(",
"topology",
".",
"threads",
"!=",
"mostthreads",
")",
":",
"continue",
"bestthreads",
".",
"append",
"(",
"topology",
")",
"return",
"bestthreads"
] | filter topologies which closest match to numa threads . | train | false |
20,398 | def parsefield(line, i, n):
start = i
while (i < n):
c = line[i]
if (c == ';'):
break
elif (c == '\\'):
i = (i + 2)
else:
i = (i + 1)
return (line[start:i].strip(), i)
| [
"def",
"parsefield",
"(",
"line",
",",
"i",
",",
"n",
")",
":",
"start",
"=",
"i",
"while",
"(",
"i",
"<",
"n",
")",
":",
"c",
"=",
"line",
"[",
"i",
"]",
"if",
"(",
"c",
"==",
"';'",
")",
":",
"break",
"elif",
"(",
"c",
"==",
"'\\\\'",
")",
":",
"i",
"=",
"(",
"i",
"+",
"2",
")",
"else",
":",
"i",
"=",
"(",
"i",
"+",
"1",
")",
"return",
"(",
"line",
"[",
"start",
":",
"i",
"]",
".",
"strip",
"(",
")",
",",
"i",
")"
] | separate one key-value pair in a mailcap entry . | train | false |
20,399 | def test_require_single_existing_key():
require('version')
| [
"def",
"test_require_single_existing_key",
"(",
")",
":",
"require",
"(",
"'version'",
")"
] | when given a single existing key . | train | false |
20,400 | def test_senn_sk_estimator():
check_estimator(SMOTEENN)
| [
"def",
"test_senn_sk_estimator",
"(",
")",
":",
"check_estimator",
"(",
"SMOTEENN",
")"
] | test the sklearn estimator compatibility . | train | false |
20,401 | @api_error_handler
@require_POST
def share_document(request):
perms_dict = json.loads(request.POST.get('data'))
uuid = json.loads(request.POST.get('uuid'))
if ((not uuid) or (not perms_dict)):
raise PopupException(_('share_document requires uuid and perms_dict'))
doc = Document2.objects.get_by_uuid(user=request.user, uuid=uuid)
for (name, perm) in perms_dict.iteritems():
users = groups = None
if perm.get('user_ids'):
users = User.objects.in_bulk(perm.get('user_ids'))
else:
users = []
if perm.get('group_ids'):
groups = Group.objects.in_bulk(perm.get('group_ids'))
else:
groups = []
doc = doc.share(request.user, name=name, users=users, groups=groups)
return JsonResponse({'status': 0, 'document': doc.to_dict()})
| [
"@",
"api_error_handler",
"@",
"require_POST",
"def",
"share_document",
"(",
"request",
")",
":",
"perms_dict",
"=",
"json",
".",
"loads",
"(",
"request",
".",
"POST",
".",
"get",
"(",
"'data'",
")",
")",
"uuid",
"=",
"json",
".",
"loads",
"(",
"request",
".",
"POST",
".",
"get",
"(",
"'uuid'",
")",
")",
"if",
"(",
"(",
"not",
"uuid",
")",
"or",
"(",
"not",
"perms_dict",
")",
")",
":",
"raise",
"PopupException",
"(",
"_",
"(",
"'share_document requires uuid and perms_dict'",
")",
")",
"doc",
"=",
"Document2",
".",
"objects",
".",
"get_by_uuid",
"(",
"user",
"=",
"request",
".",
"user",
",",
"uuid",
"=",
"uuid",
")",
"for",
"(",
"name",
",",
"perm",
")",
"in",
"perms_dict",
".",
"iteritems",
"(",
")",
":",
"users",
"=",
"groups",
"=",
"None",
"if",
"perm",
".",
"get",
"(",
"'user_ids'",
")",
":",
"users",
"=",
"User",
".",
"objects",
".",
"in_bulk",
"(",
"perm",
".",
"get",
"(",
"'user_ids'",
")",
")",
"else",
":",
"users",
"=",
"[",
"]",
"if",
"perm",
".",
"get",
"(",
"'group_ids'",
")",
":",
"groups",
"=",
"Group",
".",
"objects",
".",
"in_bulk",
"(",
"perm",
".",
"get",
"(",
"'group_ids'",
")",
")",
"else",
":",
"groups",
"=",
"[",
"]",
"doc",
"=",
"doc",
".",
"share",
"(",
"request",
".",
"user",
",",
"name",
"=",
"name",
",",
"users",
"=",
"users",
",",
"groups",
"=",
"groups",
")",
"return",
"JsonResponse",
"(",
"{",
"'status'",
":",
"0",
",",
"'document'",
":",
"doc",
".",
"to_dict",
"(",
")",
"}",
")"
] | set who else or which other group can interact with the document . | train | false |
20,402 | def parse_dist_meta():
pats = {re_meta: _add_default, re_doc: _add_doc}
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, NAME, '__init__.py')) as meta_fh:
distmeta = {}
for line in meta_fh:
if (line.strip() == '# -eof meta-'):
break
for (pattern, handler) in pats.items():
m = pattern.match(line.strip())
if m:
distmeta.update(handler(m))
return distmeta
| [
"def",
"parse_dist_meta",
"(",
")",
":",
"pats",
"=",
"{",
"re_meta",
":",
"_add_default",
",",
"re_doc",
":",
"_add_doc",
"}",
"here",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"here",
",",
"NAME",
",",
"'__init__.py'",
")",
")",
"as",
"meta_fh",
":",
"distmeta",
"=",
"{",
"}",
"for",
"line",
"in",
"meta_fh",
":",
"if",
"(",
"line",
".",
"strip",
"(",
")",
"==",
"'# -eof meta-'",
")",
":",
"break",
"for",
"(",
"pattern",
",",
"handler",
")",
"in",
"pats",
".",
"items",
"(",
")",
":",
"m",
"=",
"pattern",
".",
"match",
"(",
"line",
".",
"strip",
"(",
")",
")",
"if",
"m",
":",
"distmeta",
".",
"update",
"(",
"handler",
"(",
"m",
")",
")",
"return",
"distmeta"
] | extract metadata information from $dist/__init__ . | train | false |
20,403 | def name_to_tag(name):
if (len(name) > 10):
name = name[:10]
return name.replace(' ', '_').strip()
| [
"def",
"name_to_tag",
"(",
"name",
")",
":",
"if",
"(",
"len",
"(",
"name",
")",
">",
"10",
")",
":",
"name",
"=",
"name",
"[",
":",
"10",
"]",
"return",
"name",
".",
"replace",
"(",
"' '",
",",
"'_'",
")",
".",
"strip",
"(",
")"
] | returns sanitized str name: no more than 10 characters . | train | false |
20,404 | def create_species_bunch(species_name, train, test, coverages, xgrid, ygrid):
bunch = Bunch(name=' '.join(species_name.split('_')[:2]))
species_name = species_name.encode('ascii')
points = dict(test=test, train=train)
for (label, pts) in points.items():
pts = pts[(pts['species'] == species_name)]
bunch[('pts_%s' % label)] = pts
ix = np.searchsorted(xgrid, pts['dd long'])
iy = np.searchsorted(ygrid, pts['dd lat'])
bunch[('cov_%s' % label)] = coverages[:, (- iy), ix].T
return bunch
| [
"def",
"create_species_bunch",
"(",
"species_name",
",",
"train",
",",
"test",
",",
"coverages",
",",
"xgrid",
",",
"ygrid",
")",
":",
"bunch",
"=",
"Bunch",
"(",
"name",
"=",
"' '",
".",
"join",
"(",
"species_name",
".",
"split",
"(",
"'_'",
")",
"[",
":",
"2",
"]",
")",
")",
"species_name",
"=",
"species_name",
".",
"encode",
"(",
"'ascii'",
")",
"points",
"=",
"dict",
"(",
"test",
"=",
"test",
",",
"train",
"=",
"train",
")",
"for",
"(",
"label",
",",
"pts",
")",
"in",
"points",
".",
"items",
"(",
")",
":",
"pts",
"=",
"pts",
"[",
"(",
"pts",
"[",
"'species'",
"]",
"==",
"species_name",
")",
"]",
"bunch",
"[",
"(",
"'pts_%s'",
"%",
"label",
")",
"]",
"=",
"pts",
"ix",
"=",
"np",
".",
"searchsorted",
"(",
"xgrid",
",",
"pts",
"[",
"'dd long'",
"]",
")",
"iy",
"=",
"np",
".",
"searchsorted",
"(",
"ygrid",
",",
"pts",
"[",
"'dd lat'",
"]",
")",
"bunch",
"[",
"(",
"'cov_%s'",
"%",
"label",
")",
"]",
"=",
"coverages",
"[",
":",
",",
"(",
"-",
"iy",
")",
",",
"ix",
"]",
".",
"T",
"return",
"bunch"
] | create a bunch with information about a particular organism this will use the test/train record arrays to extract the data specific to the given species name . | train | false |
20,405 | def cvsecs(time):
if is_string(time):
if ((',' not in time) and ('.' not in time)):
time = (time + '.0')
expr = '(\\d+):(\\d+):(\\d+)[,|.](\\d+)'
finds = re.findall(expr, time)[0]
nums = list(map(float, finds))
return ((((3600 * int(finds[0])) + (60 * int(finds[1]))) + int(finds[2])) + (nums[3] / (10 ** len(finds[3]))))
elif isinstance(time, tuple):
if (len(time) == 3):
(hr, mn, sec) = time
elif (len(time) == 2):
(hr, mn, sec) = (0, time[0], time[1])
return (((3600 * hr) + (60 * mn)) + sec)
else:
return time
| [
"def",
"cvsecs",
"(",
"time",
")",
":",
"if",
"is_string",
"(",
"time",
")",
":",
"if",
"(",
"(",
"','",
"not",
"in",
"time",
")",
"and",
"(",
"'.'",
"not",
"in",
"time",
")",
")",
":",
"time",
"=",
"(",
"time",
"+",
"'.0'",
")",
"expr",
"=",
"'(\\\\d+):(\\\\d+):(\\\\d+)[,|.](\\\\d+)'",
"finds",
"=",
"re",
".",
"findall",
"(",
"expr",
",",
"time",
")",
"[",
"0",
"]",
"nums",
"=",
"list",
"(",
"map",
"(",
"float",
",",
"finds",
")",
")",
"return",
"(",
"(",
"(",
"(",
"3600",
"*",
"int",
"(",
"finds",
"[",
"0",
"]",
")",
")",
"+",
"(",
"60",
"*",
"int",
"(",
"finds",
"[",
"1",
"]",
")",
")",
")",
"+",
"int",
"(",
"finds",
"[",
"2",
"]",
")",
")",
"+",
"(",
"nums",
"[",
"3",
"]",
"/",
"(",
"10",
"**",
"len",
"(",
"finds",
"[",
"3",
"]",
")",
")",
")",
")",
"elif",
"isinstance",
"(",
"time",
",",
"tuple",
")",
":",
"if",
"(",
"len",
"(",
"time",
")",
"==",
"3",
")",
":",
"(",
"hr",
",",
"mn",
",",
"sec",
")",
"=",
"time",
"elif",
"(",
"len",
"(",
"time",
")",
"==",
"2",
")",
":",
"(",
"hr",
",",
"mn",
",",
"sec",
")",
"=",
"(",
"0",
",",
"time",
"[",
"0",
"]",
",",
"time",
"[",
"1",
"]",
")",
"return",
"(",
"(",
"(",
"3600",
"*",
"hr",
")",
"+",
"(",
"60",
"*",
"mn",
")",
")",
"+",
"sec",
")",
"else",
":",
"return",
"time"
] | will convert any time into seconds . | train | false |
20,406 | def predict_shell(args):
(ns, _) = SHELL_PREDICTOR_PARSER.parse_known_args(args)
if ((ns.c is None) and (ns.filename is None)):
pred = False
else:
pred = True
return pred
| [
"def",
"predict_shell",
"(",
"args",
")",
":",
"(",
"ns",
",",
"_",
")",
"=",
"SHELL_PREDICTOR_PARSER",
".",
"parse_known_args",
"(",
"args",
")",
"if",
"(",
"(",
"ns",
".",
"c",
"is",
"None",
")",
"and",
"(",
"ns",
".",
"filename",
"is",
"None",
")",
")",
":",
"pred",
"=",
"False",
"else",
":",
"pred",
"=",
"True",
"return",
"pred"
] | precict the backgroundability of the normal shell interface . | train | false |
20,407 | def x509_parse_cert(cert, binary=False):
if binary:
bio = BIO.MemoryBuffer(cert)
x509 = X509.load_cert_bio(bio, X509.FORMAT_DER)
elif cert.startswith('-----BEGIN CERTIFICATE-----'):
bio = BIO.MemoryBuffer(cert)
x509 = X509.load_cert_bio(bio, X509.FORMAT_PEM)
else:
x509 = X509.load_cert(cert, 1)
return x509
| [
"def",
"x509_parse_cert",
"(",
"cert",
",",
"binary",
"=",
"False",
")",
":",
"if",
"binary",
":",
"bio",
"=",
"BIO",
".",
"MemoryBuffer",
"(",
"cert",
")",
"x509",
"=",
"X509",
".",
"load_cert_bio",
"(",
"bio",
",",
"X509",
".",
"FORMAT_DER",
")",
"elif",
"cert",
".",
"startswith",
"(",
"'-----BEGIN CERTIFICATE-----'",
")",
":",
"bio",
"=",
"BIO",
".",
"MemoryBuffer",
"(",
"cert",
")",
"x509",
"=",
"X509",
".",
"load_cert_bio",
"(",
"bio",
",",
"X509",
".",
"FORMAT_PEM",
")",
"else",
":",
"x509",
"=",
"X509",
".",
"load_cert",
"(",
"cert",
",",
"1",
")",
"return",
"x509"
] | create a x509 certificate from binary der . | train | false |
20,408 | def out(address, data):
global dataReg
global ctrlReg
if (address == baseAddress):
dataReg = data
elif (address == ctrlRegAdrs):
ctrlReg = data
port.DlPortWritePortUchar(address, data)
| [
"def",
"out",
"(",
"address",
",",
"data",
")",
":",
"global",
"dataReg",
"global",
"ctrlReg",
"if",
"(",
"address",
"==",
"baseAddress",
")",
":",
"dataReg",
"=",
"data",
"elif",
"(",
"address",
"==",
"ctrlRegAdrs",
")",
":",
"ctrlReg",
"=",
"data",
"port",
".",
"DlPortWritePortUchar",
"(",
"address",
",",
"data",
")"
] | the usual out function . | train | false |
20,409 | def _check_numpy():
requirement_met = False
try:
import numpy
except ImportError:
pass
else:
from .utils import minversion
requirement_met = minversion(numpy, __minimum_numpy_version__)
if (not requirement_met):
msg = 'Numpy version {0} or later must be installed to use Astropy'.format(__minimum_numpy_version__)
raise ImportError(msg)
return numpy
| [
"def",
"_check_numpy",
"(",
")",
":",
"requirement_met",
"=",
"False",
"try",
":",
"import",
"numpy",
"except",
"ImportError",
":",
"pass",
"else",
":",
"from",
".",
"utils",
"import",
"minversion",
"requirement_met",
"=",
"minversion",
"(",
"numpy",
",",
"__minimum_numpy_version__",
")",
"if",
"(",
"not",
"requirement_met",
")",
":",
"msg",
"=",
"'Numpy version {0} or later must be installed to use Astropy'",
".",
"format",
"(",
"__minimum_numpy_version__",
")",
"raise",
"ImportError",
"(",
"msg",
")",
"return",
"numpy"
] | check that numpy is installed and it is of the minimum version we require . | train | false |
20,410 | def test_new_init():
for x in (_struct.Struct.__new__(_struct.Struct), _struct.Struct.__new__(_struct.Struct, a=2)):
AreEqual(x.size, (-1))
AreEqual(x.format, None)
AssertErrorWithMessage(_struct.error, 'pack requires exactly -1 arguments', x.pack)
AssertErrorWithMessage(_struct.error, 'unpack requires a string argument of length -1', x.unpack, '')
a = _struct.Struct('c')
try:
a.__init__('bad')
AssertUnreachable()
except _struct.error as e:
pass
AreEqual(a.format, 'bad')
AreEqual(a.pack('1'), '1')
AreEqual(a.unpack('1'), ('1',))
a.__init__('i')
AreEqual(a.format, 'i')
AreEqual(a.pack(0), '\x00\x00\x00\x00')
AreEqual(a.unpack('\x00\x00\x00\x00'), (0,))
| [
"def",
"test_new_init",
"(",
")",
":",
"for",
"x",
"in",
"(",
"_struct",
".",
"Struct",
".",
"__new__",
"(",
"_struct",
".",
"Struct",
")",
",",
"_struct",
".",
"Struct",
".",
"__new__",
"(",
"_struct",
".",
"Struct",
",",
"a",
"=",
"2",
")",
")",
":",
"AreEqual",
"(",
"x",
".",
"size",
",",
"(",
"-",
"1",
")",
")",
"AreEqual",
"(",
"x",
".",
"format",
",",
"None",
")",
"AssertErrorWithMessage",
"(",
"_struct",
".",
"error",
",",
"'pack requires exactly -1 arguments'",
",",
"x",
".",
"pack",
")",
"AssertErrorWithMessage",
"(",
"_struct",
".",
"error",
",",
"'unpack requires a string argument of length -1'",
",",
"x",
".",
"unpack",
",",
"''",
")",
"a",
"=",
"_struct",
".",
"Struct",
"(",
"'c'",
")",
"try",
":",
"a",
".",
"__init__",
"(",
"'bad'",
")",
"AssertUnreachable",
"(",
")",
"except",
"_struct",
".",
"error",
"as",
"e",
":",
"pass",
"AreEqual",
"(",
"a",
".",
"format",
",",
"'bad'",
")",
"AreEqual",
"(",
"a",
".",
"pack",
"(",
"'1'",
")",
",",
"'1'",
")",
"AreEqual",
"(",
"a",
".",
"unpack",
"(",
"'1'",
")",
",",
"(",
"'1'",
",",
")",
")",
"a",
".",
"__init__",
"(",
"'i'",
")",
"AreEqual",
"(",
"a",
".",
"format",
",",
"'i'",
")",
"AreEqual",
"(",
"a",
".",
"pack",
"(",
"0",
")",
",",
"'\\x00\\x00\\x00\\x00'",
")",
"AreEqual",
"(",
"a",
".",
"unpack",
"(",
"'\\x00\\x00\\x00\\x00'",
")",
",",
"(",
"0",
",",
")",
")"
] | tests for calling __new__/__init__ directly on the struct object . | train | false |
20,412 | def _fit_dipole_fixed(min_dist_to_inner_skull, B_orig, t, guess_rrs, guess_data, fwd_data, whitener, proj_op, fmin_cobyla, ori):
B = np.dot(whitener, B_orig)
B2 = np.dot(B, B)
if (B2 == 0):
warn(('Zero field found for time %s' % t))
return (np.zeros(3), 0, np.zeros(3), 0)
(Q, gof, residual) = _fit_Q(guess_data, whitener, proj_op, B, B2, B_orig, rd=None, ori=ori)
if (ori is None):
amp = np.sqrt(np.dot(Q, Q))
norm = (1.0 if (amp == 0.0) else amp)
ori = (Q / norm)
else:
amp = np.dot(Q, ori)
return (guess_rrs[0], amp, ori, gof, residual)
| [
"def",
"_fit_dipole_fixed",
"(",
"min_dist_to_inner_skull",
",",
"B_orig",
",",
"t",
",",
"guess_rrs",
",",
"guess_data",
",",
"fwd_data",
",",
"whitener",
",",
"proj_op",
",",
"fmin_cobyla",
",",
"ori",
")",
":",
"B",
"=",
"np",
".",
"dot",
"(",
"whitener",
",",
"B_orig",
")",
"B2",
"=",
"np",
".",
"dot",
"(",
"B",
",",
"B",
")",
"if",
"(",
"B2",
"==",
"0",
")",
":",
"warn",
"(",
"(",
"'Zero field found for time %s'",
"%",
"t",
")",
")",
"return",
"(",
"np",
".",
"zeros",
"(",
"3",
")",
",",
"0",
",",
"np",
".",
"zeros",
"(",
"3",
")",
",",
"0",
")",
"(",
"Q",
",",
"gof",
",",
"residual",
")",
"=",
"_fit_Q",
"(",
"guess_data",
",",
"whitener",
",",
"proj_op",
",",
"B",
",",
"B2",
",",
"B_orig",
",",
"rd",
"=",
"None",
",",
"ori",
"=",
"ori",
")",
"if",
"(",
"ori",
"is",
"None",
")",
":",
"amp",
"=",
"np",
".",
"sqrt",
"(",
"np",
".",
"dot",
"(",
"Q",
",",
"Q",
")",
")",
"norm",
"=",
"(",
"1.0",
"if",
"(",
"amp",
"==",
"0.0",
")",
"else",
"amp",
")",
"ori",
"=",
"(",
"Q",
"/",
"norm",
")",
"else",
":",
"amp",
"=",
"np",
".",
"dot",
"(",
"Q",
",",
"ori",
")",
"return",
"(",
"guess_rrs",
"[",
"0",
"]",
",",
"amp",
",",
"ori",
",",
"gof",
",",
"residual",
")"
] | fit a data using a fixed position . | train | false |
20,415 | def create_addon(name, icon_type, application, **extra_kwargs):
kwargs = {'status': STATUS_PUBLIC, 'name': name, 'slug': slugify(name), 'bayesian_rating': random.uniform(1, 5), 'average_daily_users': random.randint(200, 2000), 'weekly_downloads': random.randint(200, 2000), 'created': datetime.now(), 'last_updated': datetime.now(), 'icon_type': icon_type}
kwargs.update(extra_kwargs)
addon = Addon.objects.create(type=ADDON_EXTENSION, **kwargs)
generate_version(addon=addon, app=application)
addon.update_version()
addon.status = STATUS_PUBLIC
addon.save()
return addon
| [
"def",
"create_addon",
"(",
"name",
",",
"icon_type",
",",
"application",
",",
"**",
"extra_kwargs",
")",
":",
"kwargs",
"=",
"{",
"'status'",
":",
"STATUS_PUBLIC",
",",
"'name'",
":",
"name",
",",
"'slug'",
":",
"slugify",
"(",
"name",
")",
",",
"'bayesian_rating'",
":",
"random",
".",
"uniform",
"(",
"1",
",",
"5",
")",
",",
"'average_daily_users'",
":",
"random",
".",
"randint",
"(",
"200",
",",
"2000",
")",
",",
"'weekly_downloads'",
":",
"random",
".",
"randint",
"(",
"200",
",",
"2000",
")",
",",
"'created'",
":",
"datetime",
".",
"now",
"(",
")",
",",
"'last_updated'",
":",
"datetime",
".",
"now",
"(",
")",
",",
"'icon_type'",
":",
"icon_type",
"}",
"kwargs",
".",
"update",
"(",
"extra_kwargs",
")",
"addon",
"=",
"Addon",
".",
"objects",
".",
"create",
"(",
"type",
"=",
"ADDON_EXTENSION",
",",
"**",
"kwargs",
")",
"generate_version",
"(",
"addon",
"=",
"addon",
",",
"app",
"=",
"application",
")",
"addon",
".",
"update_version",
"(",
")",
"addon",
".",
"status",
"=",
"STATUS_PUBLIC",
"addon",
".",
"save",
"(",
")",
"return",
"addon"
] | create a skeleton addon . | train | false |
20,417 | def decode_pep3118_format(fmt, itemsize):
if (fmt in _pep3118_int_types):
name = ('int%d' % ((itemsize * 8),))
if fmt.isupper():
name = ('u' + name)
return types.Integer(name)
try:
return _pep3118_scalar_map[fmt.lstrip('=')]
except KeyError:
raise ValueError(('unsupported PEP 3118 format %r' % (fmt,)))
| [
"def",
"decode_pep3118_format",
"(",
"fmt",
",",
"itemsize",
")",
":",
"if",
"(",
"fmt",
"in",
"_pep3118_int_types",
")",
":",
"name",
"=",
"(",
"'int%d'",
"%",
"(",
"(",
"itemsize",
"*",
"8",
")",
",",
")",
")",
"if",
"fmt",
".",
"isupper",
"(",
")",
":",
"name",
"=",
"(",
"'u'",
"+",
"name",
")",
"return",
"types",
".",
"Integer",
"(",
"name",
")",
"try",
":",
"return",
"_pep3118_scalar_map",
"[",
"fmt",
".",
"lstrip",
"(",
"'='",
")",
"]",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"(",
"'unsupported PEP 3118 format %r'",
"%",
"(",
"fmt",
",",
")",
")",
")"
] | return the numba type for an item with format string *fmt* and size *itemsize* . | train | false |
20,419 | def get_d3_sequential_open_distrib(course_id):
sequential_open_distrib = get_sequential_open_distrib(course_id)
d3_data = []
course = modulestore().get_course(course_id, depth=2)
for section in course.get_children():
curr_section = {}
curr_section['display_name'] = own_metadata(section).get('display_name', '')
data = []
c_subsection = 0
for subsection in section.get_children():
c_subsection += 1
subsection_name = own_metadata(subsection).get('display_name', '')
num_students = 0
if (subsection.location in sequential_open_distrib):
num_students = sequential_open_distrib[subsection.location]
stack_data = []
tooltip = {'type': 'subsection', 'num_students': num_students, 'subsection_num': c_subsection, 'subsection_name': subsection_name}
stack_data.append({'color': 0, 'value': num_students, 'tooltip': tooltip, 'module_url': subsection.location.to_deprecated_string()})
subsection = {'xValue': 'SS {0}'.format(c_subsection), 'stackData': stack_data}
data.append(subsection)
curr_section['data'] = data
d3_data.append(curr_section)
return d3_data
| [
"def",
"get_d3_sequential_open_distrib",
"(",
"course_id",
")",
":",
"sequential_open_distrib",
"=",
"get_sequential_open_distrib",
"(",
"course_id",
")",
"d3_data",
"=",
"[",
"]",
"course",
"=",
"modulestore",
"(",
")",
".",
"get_course",
"(",
"course_id",
",",
"depth",
"=",
"2",
")",
"for",
"section",
"in",
"course",
".",
"get_children",
"(",
")",
":",
"curr_section",
"=",
"{",
"}",
"curr_section",
"[",
"'display_name'",
"]",
"=",
"own_metadata",
"(",
"section",
")",
".",
"get",
"(",
"'display_name'",
",",
"''",
")",
"data",
"=",
"[",
"]",
"c_subsection",
"=",
"0",
"for",
"subsection",
"in",
"section",
".",
"get_children",
"(",
")",
":",
"c_subsection",
"+=",
"1",
"subsection_name",
"=",
"own_metadata",
"(",
"subsection",
")",
".",
"get",
"(",
"'display_name'",
",",
"''",
")",
"num_students",
"=",
"0",
"if",
"(",
"subsection",
".",
"location",
"in",
"sequential_open_distrib",
")",
":",
"num_students",
"=",
"sequential_open_distrib",
"[",
"subsection",
".",
"location",
"]",
"stack_data",
"=",
"[",
"]",
"tooltip",
"=",
"{",
"'type'",
":",
"'subsection'",
",",
"'num_students'",
":",
"num_students",
",",
"'subsection_num'",
":",
"c_subsection",
",",
"'subsection_name'",
":",
"subsection_name",
"}",
"stack_data",
".",
"append",
"(",
"{",
"'color'",
":",
"0",
",",
"'value'",
":",
"num_students",
",",
"'tooltip'",
":",
"tooltip",
",",
"'module_url'",
":",
"subsection",
".",
"location",
".",
"to_deprecated_string",
"(",
")",
"}",
")",
"subsection",
"=",
"{",
"'xValue'",
":",
"'SS {0}'",
".",
"format",
"(",
"c_subsection",
")",
",",
"'stackData'",
":",
"stack_data",
"}",
"data",
".",
"append",
"(",
"subsection",
")",
"curr_section",
"[",
"'data'",
"]",
"=",
"data",
"d3_data",
".",
"append",
"(",
"curr_section",
")",
"return",
"d3_data"
] | returns how many students opened a sequential/subsection for each section . | train | false |
20,420 | def is_single_statement(sql):
return (len(sqlparse.split(sql)) <= 1)
| [
"def",
"is_single_statement",
"(",
"sql",
")",
":",
"return",
"(",
"len",
"(",
"sqlparse",
".",
"split",
"(",
"sql",
")",
")",
"<=",
"1",
")"
] | returns true if received sql string contains at most one statement . | train | false |
20,422 | def getEvaluatedValueObliviously(key, xmlElement):
value = str(xmlElement.attributeDictionary[key]).strip()
if ((key == 'id') or (key == 'name')):
return value
return getEvaluatedLinkValue(value, xmlElement)
| [
"def",
"getEvaluatedValueObliviously",
"(",
"key",
",",
"xmlElement",
")",
":",
"value",
"=",
"str",
"(",
"xmlElement",
".",
"attributeDictionary",
"[",
"key",
"]",
")",
".",
"strip",
"(",
")",
"if",
"(",
"(",
"key",
"==",
"'id'",
")",
"or",
"(",
"key",
"==",
"'name'",
")",
")",
":",
"return",
"value",
"return",
"getEvaluatedLinkValue",
"(",
"value",
",",
"xmlElement",
")"
] | get the evaluated value . | train | false |
20,424 | def _ParseHeader(header):
(key, _, value) = header.partition(':')
return (key.strip(), value.strip())
| [
"def",
"_ParseHeader",
"(",
"header",
")",
":",
"(",
"key",
",",
"_",
",",
"value",
")",
"=",
"header",
".",
"partition",
"(",
"':'",
")",
"return",
"(",
"key",
".",
"strip",
"(",
")",
",",
"value",
".",
"strip",
"(",
")",
")"
] | parses a str header into a pair . | train | false |
20,426 | def QuadraticU(name, a, b):
return rv(name, QuadraticUDistribution, (a, b))
| [
"def",
"QuadraticU",
"(",
"name",
",",
"a",
",",
"b",
")",
":",
"return",
"rv",
"(",
"name",
",",
"QuadraticUDistribution",
",",
"(",
"a",
",",
"b",
")",
")"
] | create a continuous random variable with a u-quadratic distribution . | train | false |
20,427 | def get_root_folder(service_instance):
try:
log.trace('Retrieving root folder')
return service_instance.RetrieveContent().rootFolder
except vim.fault.VimFault as exc:
raise salt.exceptions.VMwareApiError(exc.msg)
except vmodl.RuntimeFault as exc:
raise salt.exceptions.VMwareRuntimeError(exc.msg)
| [
"def",
"get_root_folder",
"(",
"service_instance",
")",
":",
"try",
":",
"log",
".",
"trace",
"(",
"'Retrieving root folder'",
")",
"return",
"service_instance",
".",
"RetrieveContent",
"(",
")",
".",
"rootFolder",
"except",
"vim",
".",
"fault",
".",
"VimFault",
"as",
"exc",
":",
"raise",
"salt",
".",
"exceptions",
".",
"VMwareApiError",
"(",
"exc",
".",
"msg",
")",
"except",
"vmodl",
".",
"RuntimeFault",
"as",
"exc",
":",
"raise",
"salt",
".",
"exceptions",
".",
"VMwareRuntimeError",
"(",
"exc",
".",
"msg",
")"
] | returns the root folder of a vcenter . | train | false |
20,428 | def _set_ticks_labels(ax, data, labels, positions, plot_opts):
ax.set_xlim([(np.min(positions) - 0.5), (np.max(positions) + 0.5)])
ax.set_xticks(positions)
label_fontsize = plot_opts.get('label_fontsize')
label_rotation = plot_opts.get('label_rotation')
if (label_fontsize or label_rotation):
from matplotlib.artist import setp
if (labels is not None):
if (not (len(labels) == len(data))):
msg = 'Length of `labels` should equal length of `data`.'
raise ValueError(msg)
xticknames = ax.set_xticklabels(labels)
if label_fontsize:
setp(xticknames, fontsize=label_fontsize)
if label_rotation:
setp(xticknames, rotation=label_rotation)
return
| [
"def",
"_set_ticks_labels",
"(",
"ax",
",",
"data",
",",
"labels",
",",
"positions",
",",
"plot_opts",
")",
":",
"ax",
".",
"set_xlim",
"(",
"[",
"(",
"np",
".",
"min",
"(",
"positions",
")",
"-",
"0.5",
")",
",",
"(",
"np",
".",
"max",
"(",
"positions",
")",
"+",
"0.5",
")",
"]",
")",
"ax",
".",
"set_xticks",
"(",
"positions",
")",
"label_fontsize",
"=",
"plot_opts",
".",
"get",
"(",
"'label_fontsize'",
")",
"label_rotation",
"=",
"plot_opts",
".",
"get",
"(",
"'label_rotation'",
")",
"if",
"(",
"label_fontsize",
"or",
"label_rotation",
")",
":",
"from",
"matplotlib",
".",
"artist",
"import",
"setp",
"if",
"(",
"labels",
"is",
"not",
"None",
")",
":",
"if",
"(",
"not",
"(",
"len",
"(",
"labels",
")",
"==",
"len",
"(",
"data",
")",
")",
")",
":",
"msg",
"=",
"'Length of `labels` should equal length of `data`.'",
"raise",
"ValueError",
"(",
"msg",
")",
"xticknames",
"=",
"ax",
".",
"set_xticklabels",
"(",
"labels",
")",
"if",
"label_fontsize",
":",
"setp",
"(",
"xticknames",
",",
"fontsize",
"=",
"label_fontsize",
")",
"if",
"label_rotation",
":",
"setp",
"(",
"xticknames",
",",
"rotation",
"=",
"label_rotation",
")",
"return"
] | set ticks and labels on horizontal axis . | train | false |
20,429 | def _update_const_classes():
klasses = (bool, int, float, complex, str)
if (sys.version_info < (3, 0)):
klasses += (unicode, long)
if (sys.version_info >= (2, 6)):
klasses += (bytes,)
for kls in klasses:
CONST_CLS[kls] = Const
| [
"def",
"_update_const_classes",
"(",
")",
":",
"klasses",
"=",
"(",
"bool",
",",
"int",
",",
"float",
",",
"complex",
",",
"str",
")",
"if",
"(",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"0",
")",
")",
":",
"klasses",
"+=",
"(",
"unicode",
",",
"long",
")",
"if",
"(",
"sys",
".",
"version_info",
">=",
"(",
"2",
",",
"6",
")",
")",
":",
"klasses",
"+=",
"(",
"bytes",
",",
")",
"for",
"kls",
"in",
"klasses",
":",
"CONST_CLS",
"[",
"kls",
"]",
"=",
"Const"
] | update constant classes . | train | false |
20,430 | def uninstall_hook_for_submodules(cr, registry, model):
env = api.Environment(cr, SUPERUSER_ID, {})
with cr.savepoint():
Image = env['base_multi_image.image']
images = Image.search([('owner_model', '=', model)])
images.unlink()
| [
"def",
"uninstall_hook_for_submodules",
"(",
"cr",
",",
"registry",
",",
"model",
")",
":",
"env",
"=",
"api",
".",
"Environment",
"(",
"cr",
",",
"SUPERUSER_ID",
",",
"{",
"}",
")",
"with",
"cr",
".",
"savepoint",
"(",
")",
":",
"Image",
"=",
"env",
"[",
"'base_multi_image.image'",
"]",
"images",
"=",
"Image",
".",
"search",
"(",
"[",
"(",
"'owner_model'",
",",
"'='",
",",
"model",
")",
"]",
")",
"images",
".",
"unlink",
"(",
")"
] | remove multi-images for a given model . | train | false |
20,432 | def get_quota(trans, id):
id = trans.security.decode_id(id)
quota = trans.sa_session.query(trans.model.Quota).get(id)
return quota
| [
"def",
"get_quota",
"(",
"trans",
",",
"id",
")",
":",
"id",
"=",
"trans",
".",
"security",
".",
"decode_id",
"(",
"id",
")",
"quota",
"=",
"trans",
".",
"sa_session",
".",
"query",
"(",
"trans",
".",
"model",
".",
"Quota",
")",
".",
"get",
"(",
"id",
")",
"return",
"quota"
] | get a quota from the database by id . | train | false |
20,433 | def _make_attribute_test_cases():
attribute_names = itertools.product(ID_ATTR_NAMES, CATEGORY_ATTR_NAMES, TARGET_ATTR_NAMES)
for (id_attr, category_attr, target_attr) in attribute_names:
(yield (AttributePair(id_attr, _random_string()), AttributePair(category_attr, _random_string()), AttributePair(target_attr, _random_string())))
| [
"def",
"_make_attribute_test_cases",
"(",
")",
":",
"attribute_names",
"=",
"itertools",
".",
"product",
"(",
"ID_ATTR_NAMES",
",",
"CATEGORY_ATTR_NAMES",
",",
"TARGET_ATTR_NAMES",
")",
"for",
"(",
"id_attr",
",",
"category_attr",
",",
"target_attr",
")",
"in",
"attribute_names",
":",
"(",
"yield",
"(",
"AttributePair",
"(",
"id_attr",
",",
"_random_string",
"(",
")",
")",
",",
"AttributePair",
"(",
"category_attr",
",",
"_random_string",
"(",
")",
")",
",",
"AttributePair",
"(",
"target_attr",
",",
"_random_string",
"(",
")",
")",
")",
")"
] | builds test cases for attribute-dependent tests . | train | false |
20,434 | @hgcommand
def change(ui, repo, *pats, **opts):
if codereview_disabled:
raise hg_util.Abort(codereview_disabled)
dirty = {}
if ((len(pats) > 0) and GoodCLName(pats[0])):
name = pats[0]
if (len(pats) != 1):
raise hg_util.Abort('cannot specify CL name and file patterns')
pats = pats[1:]
(cl, err) = LoadCL(ui, repo, name, web=True)
if (err != ''):
raise hg_util.Abort(err)
if ((not cl.local) and (opts['stdin'] or (not opts['stdout']))):
raise hg_util.Abort(('cannot change non-local CL ' + name))
else:
name = 'new'
cl = CL('new')
if (not workbranch(repo[None].branch())):
raise hg_util.Abort("cannot create CL outside default branch; switch with 'hg update default'")
dirty[cl] = True
files = ChangedFiles(ui, repo, pats, taken=Taken(ui, repo))
if (opts['delete'] or opts['deletelocal']):
if (opts['delete'] and opts['deletelocal']):
raise hg_util.Abort('cannot use -d and -D together')
flag = '-d'
if opts['deletelocal']:
flag = '-D'
if (name == 'new'):
raise hg_util.Abort((('cannot use ' + flag) + ' with file patterns'))
if (opts['stdin'] or opts['stdout']):
raise hg_util.Abort((('cannot use ' + flag) + ' with -i or -o'))
if (not cl.local):
raise hg_util.Abort(('cannot change non-local CL ' + name))
if opts['delete']:
if cl.copied_from:
raise hg_util.Abort('original author must delete CL; hg change -D will remove locally')
PostMessage(ui, cl.name, '*** Abandoned ***', send_mail=cl.mailed)
EditDesc(cl.name, closed=True, private=cl.private)
cl.Delete(ui, repo)
return
if opts['stdin']:
s = sys.stdin.read()
(clx, line, err) = ParseCL(s, name)
if (err != ''):
raise hg_util.Abort(('error parsing change list: line %d: %s' % (line, err)))
if (clx.desc is not None):
cl.desc = clx.desc
dirty[cl] = True
if (clx.reviewer is not None):
cl.reviewer = clx.reviewer
dirty[cl] = True
if (clx.cc is not None):
cl.cc = clx.cc
dirty[cl] = True
if (clx.files is not None):
cl.files = clx.files
dirty[cl] = True
if (clx.private != cl.private):
cl.private = clx.private
dirty[cl] = True
if ((not opts['stdin']) and (not opts['stdout'])):
if (name == 'new'):
cl.files = files
err = EditCL(ui, repo, cl)
if (err != ''):
raise hg_util.Abort(err)
dirty[cl] = True
for (d, _) in dirty.items():
name = d.name
d.Flush(ui, repo)
if (name == 'new'):
d.Upload(ui, repo, quiet=True)
if opts['stdout']:
ui.write(cl.EditorText())
elif opts['pending']:
ui.write(cl.PendingText())
elif (name == 'new'):
if ui.quiet:
ui.write(cl.name)
else:
ui.write((('CL created: ' + cl.url) + '\n'))
return
| [
"@",
"hgcommand",
"def",
"change",
"(",
"ui",
",",
"repo",
",",
"*",
"pats",
",",
"**",
"opts",
")",
":",
"if",
"codereview_disabled",
":",
"raise",
"hg_util",
".",
"Abort",
"(",
"codereview_disabled",
")",
"dirty",
"=",
"{",
"}",
"if",
"(",
"(",
"len",
"(",
"pats",
")",
">",
"0",
")",
"and",
"GoodCLName",
"(",
"pats",
"[",
"0",
"]",
")",
")",
":",
"name",
"=",
"pats",
"[",
"0",
"]",
"if",
"(",
"len",
"(",
"pats",
")",
"!=",
"1",
")",
":",
"raise",
"hg_util",
".",
"Abort",
"(",
"'cannot specify CL name and file patterns'",
")",
"pats",
"=",
"pats",
"[",
"1",
":",
"]",
"(",
"cl",
",",
"err",
")",
"=",
"LoadCL",
"(",
"ui",
",",
"repo",
",",
"name",
",",
"web",
"=",
"True",
")",
"if",
"(",
"err",
"!=",
"''",
")",
":",
"raise",
"hg_util",
".",
"Abort",
"(",
"err",
")",
"if",
"(",
"(",
"not",
"cl",
".",
"local",
")",
"and",
"(",
"opts",
"[",
"'stdin'",
"]",
"or",
"(",
"not",
"opts",
"[",
"'stdout'",
"]",
")",
")",
")",
":",
"raise",
"hg_util",
".",
"Abort",
"(",
"(",
"'cannot change non-local CL '",
"+",
"name",
")",
")",
"else",
":",
"name",
"=",
"'new'",
"cl",
"=",
"CL",
"(",
"'new'",
")",
"if",
"(",
"not",
"workbranch",
"(",
"repo",
"[",
"None",
"]",
".",
"branch",
"(",
")",
")",
")",
":",
"raise",
"hg_util",
".",
"Abort",
"(",
"\"cannot create CL outside default branch; switch with 'hg update default'\"",
")",
"dirty",
"[",
"cl",
"]",
"=",
"True",
"files",
"=",
"ChangedFiles",
"(",
"ui",
",",
"repo",
",",
"pats",
",",
"taken",
"=",
"Taken",
"(",
"ui",
",",
"repo",
")",
")",
"if",
"(",
"opts",
"[",
"'delete'",
"]",
"or",
"opts",
"[",
"'deletelocal'",
"]",
")",
":",
"if",
"(",
"opts",
"[",
"'delete'",
"]",
"and",
"opts",
"[",
"'deletelocal'",
"]",
")",
":",
"raise",
"hg_util",
".",
"Abort",
"(",
"'cannot use -d and -D together'",
")",
"flag",
"=",
"'-d'",
"if",
"opts",
"[",
"'deletelocal'",
"]",
":",
"flag",
"=",
"'-D'",
"if",
"(",
"name",
"==",
"'new'",
")",
":",
"raise",
"hg_util",
".",
"Abort",
"(",
"(",
"(",
"'cannot use '",
"+",
"flag",
")",
"+",
"' with file patterns'",
")",
")",
"if",
"(",
"opts",
"[",
"'stdin'",
"]",
"or",
"opts",
"[",
"'stdout'",
"]",
")",
":",
"raise",
"hg_util",
".",
"Abort",
"(",
"(",
"(",
"'cannot use '",
"+",
"flag",
")",
"+",
"' with -i or -o'",
")",
")",
"if",
"(",
"not",
"cl",
".",
"local",
")",
":",
"raise",
"hg_util",
".",
"Abort",
"(",
"(",
"'cannot change non-local CL '",
"+",
"name",
")",
")",
"if",
"opts",
"[",
"'delete'",
"]",
":",
"if",
"cl",
".",
"copied_from",
":",
"raise",
"hg_util",
".",
"Abort",
"(",
"'original author must delete CL; hg change -D will remove locally'",
")",
"PostMessage",
"(",
"ui",
",",
"cl",
".",
"name",
",",
"'*** Abandoned ***'",
",",
"send_mail",
"=",
"cl",
".",
"mailed",
")",
"EditDesc",
"(",
"cl",
".",
"name",
",",
"closed",
"=",
"True",
",",
"private",
"=",
"cl",
".",
"private",
")",
"cl",
".",
"Delete",
"(",
"ui",
",",
"repo",
")",
"return",
"if",
"opts",
"[",
"'stdin'",
"]",
":",
"s",
"=",
"sys",
".",
"stdin",
".",
"read",
"(",
")",
"(",
"clx",
",",
"line",
",",
"err",
")",
"=",
"ParseCL",
"(",
"s",
",",
"name",
")",
"if",
"(",
"err",
"!=",
"''",
")",
":",
"raise",
"hg_util",
".",
"Abort",
"(",
"(",
"'error parsing change list: line %d: %s'",
"%",
"(",
"line",
",",
"err",
")",
")",
")",
"if",
"(",
"clx",
".",
"desc",
"is",
"not",
"None",
")",
":",
"cl",
".",
"desc",
"=",
"clx",
".",
"desc",
"dirty",
"[",
"cl",
"]",
"=",
"True",
"if",
"(",
"clx",
".",
"reviewer",
"is",
"not",
"None",
")",
":",
"cl",
".",
"reviewer",
"=",
"clx",
".",
"reviewer",
"dirty",
"[",
"cl",
"]",
"=",
"True",
"if",
"(",
"clx",
".",
"cc",
"is",
"not",
"None",
")",
":",
"cl",
".",
"cc",
"=",
"clx",
".",
"cc",
"dirty",
"[",
"cl",
"]",
"=",
"True",
"if",
"(",
"clx",
".",
"files",
"is",
"not",
"None",
")",
":",
"cl",
".",
"files",
"=",
"clx",
".",
"files",
"dirty",
"[",
"cl",
"]",
"=",
"True",
"if",
"(",
"clx",
".",
"private",
"!=",
"cl",
".",
"private",
")",
":",
"cl",
".",
"private",
"=",
"clx",
".",
"private",
"dirty",
"[",
"cl",
"]",
"=",
"True",
"if",
"(",
"(",
"not",
"opts",
"[",
"'stdin'",
"]",
")",
"and",
"(",
"not",
"opts",
"[",
"'stdout'",
"]",
")",
")",
":",
"if",
"(",
"name",
"==",
"'new'",
")",
":",
"cl",
".",
"files",
"=",
"files",
"err",
"=",
"EditCL",
"(",
"ui",
",",
"repo",
",",
"cl",
")",
"if",
"(",
"err",
"!=",
"''",
")",
":",
"raise",
"hg_util",
".",
"Abort",
"(",
"err",
")",
"dirty",
"[",
"cl",
"]",
"=",
"True",
"for",
"(",
"d",
",",
"_",
")",
"in",
"dirty",
".",
"items",
"(",
")",
":",
"name",
"=",
"d",
".",
"name",
"d",
".",
"Flush",
"(",
"ui",
",",
"repo",
")",
"if",
"(",
"name",
"==",
"'new'",
")",
":",
"d",
".",
"Upload",
"(",
"ui",
",",
"repo",
",",
"quiet",
"=",
"True",
")",
"if",
"opts",
"[",
"'stdout'",
"]",
":",
"ui",
".",
"write",
"(",
"cl",
".",
"EditorText",
"(",
")",
")",
"elif",
"opts",
"[",
"'pending'",
"]",
":",
"ui",
".",
"write",
"(",
"cl",
".",
"PendingText",
"(",
")",
")",
"elif",
"(",
"name",
"==",
"'new'",
")",
":",
"if",
"ui",
".",
"quiet",
":",
"ui",
".",
"write",
"(",
"cl",
".",
"name",
")",
"else",
":",
"ui",
".",
"write",
"(",
"(",
"(",
"'CL created: '",
"+",
"cl",
".",
"url",
")",
"+",
"'\\n'",
")",
")",
"return"
] | calculate the relative change between a value and a reference point . | train | false |
20,435 | def dropout_channels(incoming, *args, **kwargs):
ndim = len(getattr(incoming, 'output_shape', incoming))
kwargs['shared_axes'] = tuple(range(2, ndim))
return DropoutLayer(incoming, *args, **kwargs)
| [
"def",
"dropout_channels",
"(",
"incoming",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"ndim",
"=",
"len",
"(",
"getattr",
"(",
"incoming",
",",
"'output_shape'",
",",
"incoming",
")",
")",
"kwargs",
"[",
"'shared_axes'",
"]",
"=",
"tuple",
"(",
"range",
"(",
"2",
",",
"ndim",
")",
")",
"return",
"DropoutLayer",
"(",
"incoming",
",",
"*",
"args",
",",
"**",
"kwargs",
")"
] | convenience function to drop full channels of feature maps . | train | false |
20,436 | def DetermineRunner(bbdir):
try:
import buildbot_worker.scripts.runner
tacfile = os.path.join(bbdir, 'buildbot.tac')
if os.path.exists(tacfile):
with open(tacfile, 'r') as f:
contents = f.read()
if ('import Worker' in contents):
return buildbot_worker.scripts.runner.run
except ImportError:
pass
import buildbot.scripts.runner
return buildbot.scripts.runner.run
| [
"def",
"DetermineRunner",
"(",
"bbdir",
")",
":",
"try",
":",
"import",
"buildbot_worker",
".",
"scripts",
".",
"runner",
"tacfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"bbdir",
",",
"'buildbot.tac'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"tacfile",
")",
":",
"with",
"open",
"(",
"tacfile",
",",
"'r'",
")",
"as",
"f",
":",
"contents",
"=",
"f",
".",
"read",
"(",
")",
"if",
"(",
"'import Worker'",
"in",
"contents",
")",
":",
"return",
"buildbot_worker",
".",
"scripts",
".",
"runner",
".",
"run",
"except",
"ImportError",
":",
"pass",
"import",
"buildbot",
".",
"scripts",
".",
"runner",
"return",
"buildbot",
".",
"scripts",
".",
"runner",
".",
"run"
] | checks if the given directory is a worker or a master and returns the appropriate run function . | train | true |
20,437 | def isfile(path):
try:
st = os.stat(path)
except OSError:
return False
return stat.S_ISREG(st.st_mode)
| [
"def",
"isfile",
"(",
"path",
")",
":",
"try",
":",
"st",
"=",
"os",
".",
"stat",
"(",
"path",
")",
"except",
"OSError",
":",
"return",
"False",
"return",
"stat",
".",
"S_ISREG",
"(",
"st",
".",
"st_mode",
")"
] | test whether a path is a file . | train | true |
20,439 | @click.command(name='exec', context_settings=dict(ignore_unknown_options=True, allow_extra_args=True))
@click.option('-c', default='', help='Read script from string.')
@click.argument('file', default=None, required=False)
def exec_(c, file):
if (c and file):
file = None
if (not (c or file)):
file = '-'
if file:
if (file == '-'):
file = '<string>'
c = click.get_text_stream('stdin').read()
else:
try:
with open(file, 'rb') as fp:
c = fp.read().decode('utf8')
except (IOError, OSError) as e:
raise click.ClickException(six.text_type(e))
else:
file = '<string>'
header = []
if ('from __future__' in c):
body = []
state = 0
for line in c.splitlines():
if line.startswith('from __future__'):
state = 1
elif (line and (not line.startswith('#', '"', "'")) and (state == 1)):
state = 2
if (state == 2):
body.append(line)
else:
header.append(line)
body = '\n'.join(body)
else:
header = []
body = c
if ('from sentry.runner import configure' not in c):
header.extend(['from sentry.runner import configure; configure()', 'from django.conf import settings', 'from sentry.models import *'])
header.append('class ScriptError(Exception): pass')
script = (SCRIPT_TEMPLATE % {'body': body.replace('\n', ('\n' + (' ' * 4))), 'header': '\n'.join(header), 'filename': file})
sys.argv = sys.argv[1:]
g = {'__name__': '__main__', '__file__': '<script>'}
six.exec_(compile(script, file, 'exec'), g, g)
| [
"@",
"click",
".",
"command",
"(",
"name",
"=",
"'exec'",
",",
"context_settings",
"=",
"dict",
"(",
"ignore_unknown_options",
"=",
"True",
",",
"allow_extra_args",
"=",
"True",
")",
")",
"@",
"click",
".",
"option",
"(",
"'-c'",
",",
"default",
"=",
"''",
",",
"help",
"=",
"'Read script from string.'",
")",
"@",
"click",
".",
"argument",
"(",
"'file'",
",",
"default",
"=",
"None",
",",
"required",
"=",
"False",
")",
"def",
"exec_",
"(",
"c",
",",
"file",
")",
":",
"if",
"(",
"c",
"and",
"file",
")",
":",
"file",
"=",
"None",
"if",
"(",
"not",
"(",
"c",
"or",
"file",
")",
")",
":",
"file",
"=",
"'-'",
"if",
"file",
":",
"if",
"(",
"file",
"==",
"'-'",
")",
":",
"file",
"=",
"'<string>'",
"c",
"=",
"click",
".",
"get_text_stream",
"(",
"'stdin'",
")",
".",
"read",
"(",
")",
"else",
":",
"try",
":",
"with",
"open",
"(",
"file",
",",
"'rb'",
")",
"as",
"fp",
":",
"c",
"=",
"fp",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'utf8'",
")",
"except",
"(",
"IOError",
",",
"OSError",
")",
"as",
"e",
":",
"raise",
"click",
".",
"ClickException",
"(",
"six",
".",
"text_type",
"(",
"e",
")",
")",
"else",
":",
"file",
"=",
"'<string>'",
"header",
"=",
"[",
"]",
"if",
"(",
"'from __future__'",
"in",
"c",
")",
":",
"body",
"=",
"[",
"]",
"state",
"=",
"0",
"for",
"line",
"in",
"c",
".",
"splitlines",
"(",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"'from __future__'",
")",
":",
"state",
"=",
"1",
"elif",
"(",
"line",
"and",
"(",
"not",
"line",
".",
"startswith",
"(",
"'#'",
",",
"'\"'",
",",
"\"'\"",
")",
")",
"and",
"(",
"state",
"==",
"1",
")",
")",
":",
"state",
"=",
"2",
"if",
"(",
"state",
"==",
"2",
")",
":",
"body",
".",
"append",
"(",
"line",
")",
"else",
":",
"header",
".",
"append",
"(",
"line",
")",
"body",
"=",
"'\\n'",
".",
"join",
"(",
"body",
")",
"else",
":",
"header",
"=",
"[",
"]",
"body",
"=",
"c",
"if",
"(",
"'from sentry.runner import configure'",
"not",
"in",
"c",
")",
":",
"header",
".",
"extend",
"(",
"[",
"'from sentry.runner import configure; configure()'",
",",
"'from django.conf import settings'",
",",
"'from sentry.models import *'",
"]",
")",
"header",
".",
"append",
"(",
"'class ScriptError(Exception): pass'",
")",
"script",
"=",
"(",
"SCRIPT_TEMPLATE",
"%",
"{",
"'body'",
":",
"body",
".",
"replace",
"(",
"'\\n'",
",",
"(",
"'\\n'",
"+",
"(",
"' '",
"*",
"4",
")",
")",
")",
",",
"'header'",
":",
"'\\n'",
".",
"join",
"(",
"header",
")",
",",
"'filename'",
":",
"file",
"}",
")",
"sys",
".",
"argv",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"g",
"=",
"{",
"'__name__'",
":",
"'__main__'",
",",
"'__file__'",
":",
"'<script>'",
"}",
"six",
".",
"exec_",
"(",
"compile",
"(",
"script",
",",
"file",
",",
"'exec'",
")",
",",
"g",
",",
"g",
")"
] | run a command on a vm . | train | false |
20,441 | def echo_module(mod, write=sys.stdout.write):
for (fname, fn) in inspect.getmembers(mod, inspect.isfunction):
setattr(mod, fname, echo(fn, write))
for (_, klass) in inspect.getmembers(mod, inspect.isclass):
echo_class(klass, write)
| [
"def",
"echo_module",
"(",
"mod",
",",
"write",
"=",
"sys",
".",
"stdout",
".",
"write",
")",
":",
"for",
"(",
"fname",
",",
"fn",
")",
"in",
"inspect",
".",
"getmembers",
"(",
"mod",
",",
"inspect",
".",
"isfunction",
")",
":",
"setattr",
"(",
"mod",
",",
"fname",
",",
"echo",
"(",
"fn",
",",
"write",
")",
")",
"for",
"(",
"_",
",",
"klass",
")",
"in",
"inspect",
".",
"getmembers",
"(",
"mod",
",",
"inspect",
".",
"isclass",
")",
":",
"echo_class",
"(",
"klass",
",",
"write",
")"
] | echo calls to functions and methods in a module . | train | false |
20,442 | @task(aliases=['mongo'])
def mongoserver(ctx, daemon=False, config=None):
if (not config):
platform_configs = {'darwin': '/usr/local/etc/tokumx.conf', 'linux': '/etc/tokumx.conf'}
platform = str(sys.platform).lower()
config = platform_configs.get(platform)
port = settings.DB_PORT
cmd = 'mongod --port {0}'.format(port)
if config:
cmd += ' --config {0}'.format(config)
if daemon:
cmd += ' --fork'
ctx.run(cmd, echo=True)
| [
"@",
"task",
"(",
"aliases",
"=",
"[",
"'mongo'",
"]",
")",
"def",
"mongoserver",
"(",
"ctx",
",",
"daemon",
"=",
"False",
",",
"config",
"=",
"None",
")",
":",
"if",
"(",
"not",
"config",
")",
":",
"platform_configs",
"=",
"{",
"'darwin'",
":",
"'/usr/local/etc/tokumx.conf'",
",",
"'linux'",
":",
"'/etc/tokumx.conf'",
"}",
"platform",
"=",
"str",
"(",
"sys",
".",
"platform",
")",
".",
"lower",
"(",
")",
"config",
"=",
"platform_configs",
".",
"get",
"(",
"platform",
")",
"port",
"=",
"settings",
".",
"DB_PORT",
"cmd",
"=",
"'mongod --port {0}'",
".",
"format",
"(",
"port",
")",
"if",
"config",
":",
"cmd",
"+=",
"' --config {0}'",
".",
"format",
"(",
"config",
")",
"if",
"daemon",
":",
"cmd",
"+=",
"' --fork'",
"ctx",
".",
"run",
"(",
"cmd",
",",
"echo",
"=",
"True",
")"
] | run the mongod process . | train | false |
20,444 | def stupefyEntities(str):
str = re.sub('–', '-', str)
str = re.sub('—', '--', str)
str = re.sub('‘', "'", str)
str = re.sub('’', "'", str)
str = re.sub('“', '"', str)
str = re.sub('”', '"', str)
str = re.sub('…', '...', str)
return str
| [
"def",
"stupefyEntities",
"(",
"str",
")",
":",
"str",
"=",
"re",
".",
"sub",
"(",
"'–'",
",",
"'-'",
",",
"str",
")",
"str",
"=",
"re",
".",
"sub",
"(",
"'—'",
",",
"'--'",
",",
"str",
")",
"str",
"=",
"re",
".",
"sub",
"(",
"'‘'",
",",
"\"'\"",
",",
"str",
")",
"str",
"=",
"re",
".",
"sub",
"(",
"'’'",
",",
"\"'\"",
",",
"str",
")",
"str",
"=",
"re",
".",
"sub",
"(",
"'“'",
",",
"'\"'",
",",
"str",
")",
"str",
"=",
"re",
".",
"sub",
"(",
"'”'",
",",
"'\"'",
",",
"str",
")",
"str",
"=",
"re",
".",
"sub",
"(",
"'…'",
",",
"'...'",
",",
"str",
")",
"return",
"str"
] | parameter: string . | train | false |
20,445 | def snapshot_metadata_delete(context, snapshot_id, key):
IMPL.snapshot_metadata_delete(context, snapshot_id, key)
| [
"def",
"snapshot_metadata_delete",
"(",
"context",
",",
"snapshot_id",
",",
"key",
")",
":",
"IMPL",
".",
"snapshot_metadata_delete",
"(",
"context",
",",
"snapshot_id",
",",
"key",
")"
] | delete the given metadata item . | train | false |
20,447 | def date_updated(node):
try:
return node.logs.latest().date
except IndexError:
return node.date_created
| [
"def",
"date_updated",
"(",
"node",
")",
":",
"try",
":",
"return",
"node",
".",
"logs",
".",
"latest",
"(",
")",
".",
"date",
"except",
"IndexError",
":",
"return",
"node",
".",
"date_created"
] | the most recent datetime when this node was modified . | train | false |
20,448 | def isinteractive():
return matplotlib.is_interactive()
| [
"def",
"isinteractive",
"(",
")",
":",
"return",
"matplotlib",
".",
"is_interactive",
"(",
")"
] | return the interactive status . | train | false |
20,450 | def invertDataBit(bit):
global dataReg
dataReg = (dataReg ^ (2 ** bit))
port.DlPortWritePortUchar(baseAddress, dataReg)
| [
"def",
"invertDataBit",
"(",
"bit",
")",
":",
"global",
"dataReg",
"dataReg",
"=",
"(",
"dataReg",
"^",
"(",
"2",
"**",
"bit",
")",
")",
"port",
".",
"DlPortWritePortUchar",
"(",
"baseAddress",
",",
"dataReg",
")"
] | inverts any data register bit . | train | false |
20,452 | def client_side(func):
def inner(*args, **kwargs):
if (args and hasattr(args[0], 'is_server') and voltron.debugger):
raise ClientSideOnlyException('This method can only be called on a client-side instance')
return func(*args, **kwargs)
return inner
| [
"def",
"client_side",
"(",
"func",
")",
":",
"def",
"inner",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"(",
"args",
"and",
"hasattr",
"(",
"args",
"[",
"0",
"]",
",",
"'is_server'",
")",
"and",
"voltron",
".",
"debugger",
")",
":",
"raise",
"ClientSideOnlyException",
"(",
"'This method can only be called on a client-side instance'",
")",
"return",
"func",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"return",
"inner"
] | decorator to designate an api method applicable only to client-side instances . | train | true |
20,453 | def password_param(registry, xml_parent, data):
base_param(registry, xml_parent, data, True, 'hudson.model.PasswordParameterDefinition')
| [
"def",
"password_param",
"(",
"registry",
",",
"xml_parent",
",",
"data",
")",
":",
"base_param",
"(",
"registry",
",",
"xml_parent",
",",
"data",
",",
"True",
",",
"'hudson.model.PasswordParameterDefinition'",
")"
] | yaml: password a password parameter . | train | false |
20,454 | def parsePasswordHash(password):
blank = (' ' * 8)
if ((not password) or (password == ' ')):
password = NULL
if (Backend.isDbms(DBMS.MSSQL) and (password != NULL) and isHexEncodedString(password)):
hexPassword = password
password = ('%s\n' % hexPassword)
password += ('%sheader: %s\n' % (blank, hexPassword[:6]))
password += ('%ssalt: %s\n' % (blank, hexPassword[6:14]))
password += ('%smixedcase: %s\n' % (blank, hexPassword[14:54]))
if (not Backend.isVersionWithin(('2005', '2008'))):
password += ('%suppercase: %s' % (blank, hexPassword[54:]))
return password
| [
"def",
"parsePasswordHash",
"(",
"password",
")",
":",
"blank",
"=",
"(",
"' '",
"*",
"8",
")",
"if",
"(",
"(",
"not",
"password",
")",
"or",
"(",
"password",
"==",
"' '",
")",
")",
":",
"password",
"=",
"NULL",
"if",
"(",
"Backend",
".",
"isDbms",
"(",
"DBMS",
".",
"MSSQL",
")",
"and",
"(",
"password",
"!=",
"NULL",
")",
"and",
"isHexEncodedString",
"(",
"password",
")",
")",
":",
"hexPassword",
"=",
"password",
"password",
"=",
"(",
"'%s\\n'",
"%",
"hexPassword",
")",
"password",
"+=",
"(",
"'%sheader: %s\\n'",
"%",
"(",
"blank",
",",
"hexPassword",
"[",
":",
"6",
"]",
")",
")",
"password",
"+=",
"(",
"'%ssalt: %s\\n'",
"%",
"(",
"blank",
",",
"hexPassword",
"[",
"6",
":",
"14",
"]",
")",
")",
"password",
"+=",
"(",
"'%smixedcase: %s\\n'",
"%",
"(",
"blank",
",",
"hexPassword",
"[",
"14",
":",
"54",
"]",
")",
")",
"if",
"(",
"not",
"Backend",
".",
"isVersionWithin",
"(",
"(",
"'2005'",
",",
"'2008'",
")",
")",
")",
":",
"password",
"+=",
"(",
"'%suppercase: %s'",
"%",
"(",
"blank",
",",
"hexPassword",
"[",
"54",
":",
"]",
")",
")",
"return",
"password"
] | in case of microsoft sql server password hash value is expanded to its components . | train | false |
20,455 | def _log_changes(ret, changekey, changevalue):
cl = ret['changes'].get('new', [])
cl.append({changekey: _object_reducer(changevalue)})
ret['changes']['new'] = cl
return ret
| [
"def",
"_log_changes",
"(",
"ret",
",",
"changekey",
",",
"changevalue",
")",
":",
"cl",
"=",
"ret",
"[",
"'changes'",
"]",
".",
"get",
"(",
"'new'",
",",
"[",
"]",
")",
"cl",
".",
"append",
"(",
"{",
"changekey",
":",
"_object_reducer",
"(",
"changevalue",
")",
"}",
")",
"ret",
"[",
"'changes'",
"]",
"[",
"'new'",
"]",
"=",
"cl",
"return",
"ret"
] | for logging create/update/delete operations to aws apigateway . | train | true |
20,456 | def filter_index(collection, predicate=None, index=None):
if ((index is None) and isinstance(predicate, int)):
index = predicate
predicate = None
if predicate:
collection = collection.__class__(filter(predicate, collection))
if (index is not None):
try:
collection = collection[index]
except IndexError:
collection = None
return collection
| [
"def",
"filter_index",
"(",
"collection",
",",
"predicate",
"=",
"None",
",",
"index",
"=",
"None",
")",
":",
"if",
"(",
"(",
"index",
"is",
"None",
")",
"and",
"isinstance",
"(",
"predicate",
",",
"int",
")",
")",
":",
"index",
"=",
"predicate",
"predicate",
"=",
"None",
"if",
"predicate",
":",
"collection",
"=",
"collection",
".",
"__class__",
"(",
"filter",
"(",
"predicate",
",",
"collection",
")",
")",
"if",
"(",
"index",
"is",
"not",
"None",
")",
":",
"try",
":",
"collection",
"=",
"collection",
"[",
"index",
"]",
"except",
"IndexError",
":",
"collection",
"=",
"None",
"return",
"collection"
] | filter collection with predicate function and index . | train | true |
20,457 | def ConfigureRemoteApiFromServer(server, path, app_id, services=None, default_auth_domain=None, use_remote_datastore=True):
if (services is None):
services = set(ALL_SERVICES)
else:
services = set(services)
unsupported = services.difference(ALL_SERVICES)
if unsupported:
raise ConfigurationError(('Unsupported service(s): %s' % (', '.join(unsupported),)))
os.environ['APPLICATION_ID'] = app_id
os.environ.setdefault('AUTH_DOMAIN', (default_auth_domain or 'gmail.com'))
apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
if (('datastore_v3' in services) and use_remote_datastore):
services.remove('datastore_v3')
datastore_stub = RemoteDatastoreStub(server, path)
apiproxy_stub_map.apiproxy.RegisterStub('datastore_v3', datastore_stub)
stub = RemoteStub(server, path)
for service in services:
apiproxy_stub_map.apiproxy.RegisterStub(service, stub)
| [
"def",
"ConfigureRemoteApiFromServer",
"(",
"server",
",",
"path",
",",
"app_id",
",",
"services",
"=",
"None",
",",
"default_auth_domain",
"=",
"None",
",",
"use_remote_datastore",
"=",
"True",
")",
":",
"if",
"(",
"services",
"is",
"None",
")",
":",
"services",
"=",
"set",
"(",
"ALL_SERVICES",
")",
"else",
":",
"services",
"=",
"set",
"(",
"services",
")",
"unsupported",
"=",
"services",
".",
"difference",
"(",
"ALL_SERVICES",
")",
"if",
"unsupported",
":",
"raise",
"ConfigurationError",
"(",
"(",
"'Unsupported service(s): %s'",
"%",
"(",
"', '",
".",
"join",
"(",
"unsupported",
")",
",",
")",
")",
")",
"os",
".",
"environ",
"[",
"'APPLICATION_ID'",
"]",
"=",
"app_id",
"os",
".",
"environ",
".",
"setdefault",
"(",
"'AUTH_DOMAIN'",
",",
"(",
"default_auth_domain",
"or",
"'gmail.com'",
")",
")",
"apiproxy_stub_map",
".",
"apiproxy",
"=",
"apiproxy_stub_map",
".",
"APIProxyStubMap",
"(",
")",
"if",
"(",
"(",
"'datastore_v3'",
"in",
"services",
")",
"and",
"use_remote_datastore",
")",
":",
"services",
".",
"remove",
"(",
"'datastore_v3'",
")",
"datastore_stub",
"=",
"RemoteDatastoreStub",
"(",
"server",
",",
"path",
")",
"apiproxy_stub_map",
".",
"apiproxy",
".",
"RegisterStub",
"(",
"'datastore_v3'",
",",
"datastore_stub",
")",
"stub",
"=",
"RemoteStub",
"(",
"server",
",",
"path",
")",
"for",
"service",
"in",
"services",
":",
"apiproxy_stub_map",
".",
"apiproxy",
".",
"RegisterStub",
"(",
"service",
",",
"stub",
")"
] | does necessary setup to allow easy remote access to app engine apis . | train | false |
20,458 | def get_name(principal):
sid_obj = principal
try:
sid_obj = win32security.LookupAccountName(None, principal)[0]
except (pywintypes.error, TypeError):
pass
try:
sid_obj = win32security.ConvertStringSidToSid(principal)
except (pywintypes.error, TypeError):
pass
try:
return win32security.LookupAccountSid(None, sid_obj)[0]
except TypeError:
raise CommandExecutionError('Could not find User for {0}'.format(principal))
| [
"def",
"get_name",
"(",
"principal",
")",
":",
"sid_obj",
"=",
"principal",
"try",
":",
"sid_obj",
"=",
"win32security",
".",
"LookupAccountName",
"(",
"None",
",",
"principal",
")",
"[",
"0",
"]",
"except",
"(",
"pywintypes",
".",
"error",
",",
"TypeError",
")",
":",
"pass",
"try",
":",
"sid_obj",
"=",
"win32security",
".",
"ConvertStringSidToSid",
"(",
"principal",
")",
"except",
"(",
"pywintypes",
".",
"error",
",",
"TypeError",
")",
":",
"pass",
"try",
":",
"return",
"win32security",
".",
"LookupAccountSid",
"(",
"None",
",",
"sid_obj",
")",
"[",
"0",
"]",
"except",
"TypeError",
":",
"raise",
"CommandExecutionError",
"(",
"'Could not find User for {0}'",
".",
"format",
"(",
"principal",
")",
")"
] | generates a pretty name from a database table name . | train | false |
20,460 | def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error):
line = clean_lines.elided[linenum]
match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)
if match:
error(filename, linenum, 'build/explicit_make_pair', 4, 'For C++11-compatibility, omit template arguments from make_pair OR use pair directly OR if appropriate, construct a pair directly')
| [
"def",
"CheckMakePairUsesDeduction",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"error",
")",
":",
"line",
"=",
"clean_lines",
".",
"elided",
"[",
"linenum",
"]",
"match",
"=",
"_RE_PATTERN_EXPLICIT_MAKEPAIR",
".",
"search",
"(",
"line",
")",
"if",
"match",
":",
"error",
"(",
"filename",
",",
"linenum",
",",
"'build/explicit_make_pair'",
",",
"4",
",",
"'For C++11-compatibility, omit template arguments from make_pair OR use pair directly OR if appropriate, construct a pair directly'",
")"
] | check that make_pairs template arguments are deduced . | train | true |
20,462 | def getNewRepository():
return ExportRepository()
| [
"def",
"getNewRepository",
"(",
")",
":",
"return",
"ExportRepository",
"(",
")"
] | get new repository . | train | false |
20,463 | def assert_submitted(course, problem_type, choices):
all_choices = ['choice_0', 'choice_1', 'choice_2', 'choice_3']
for this_choice in all_choices:
def submit_problem():
element = world.css_find(inputfield(course, problem_type, choice=this_choice))
if (this_choice in choices):
assert element.checked
else:
assert (not element.checked)
world.retry_on_exception(submit_problem)
| [
"def",
"assert_submitted",
"(",
"course",
",",
"problem_type",
",",
"choices",
")",
":",
"all_choices",
"=",
"[",
"'choice_0'",
",",
"'choice_1'",
",",
"'choice_2'",
",",
"'choice_3'",
"]",
"for",
"this_choice",
"in",
"all_choices",
":",
"def",
"submit_problem",
"(",
")",
":",
"element",
"=",
"world",
".",
"css_find",
"(",
"inputfield",
"(",
"course",
",",
"problem_type",
",",
"choice",
"=",
"this_choice",
")",
")",
"if",
"(",
"this_choice",
"in",
"choices",
")",
":",
"assert",
"element",
".",
"checked",
"else",
":",
"assert",
"(",
"not",
"element",
".",
"checked",
")",
"world",
".",
"retry_on_exception",
"(",
"submit_problem",
")"
] | assert that choice names given in *choices* are the only ones submitted . | train | false |
20,464 | @task(rate_limit='15/m')
@timeit
def generate_thumbnail(for_obj, from_field, to_field, max_size=settings.THUMBNAIL_SIZE):
from_ = getattr(for_obj, from_field)
to_ = getattr(for_obj, to_field)
if (not (from_ and os.path.isfile(from_.path))):
log_msg = 'No file to generate from: {model} {id}, {from_f} -> {to_f}'
log.info(log_msg.format(model=for_obj.__class__.__name__, id=for_obj.id, from_f=from_field, to_f=to_field))
return
log_msg = 'Generating thumbnail for {model} {id}: {from_f} -> {to_f}'
log.info(log_msg.format(model=for_obj.__class__.__name__, id=for_obj.id, from_f=from_field, to_f=to_field))
thumb_content = _create_image_thumbnail(from_.path, longest_side=max_size)
file_path = from_.path
if to_:
to_.delete(save=False)
to_.save(file_path, thumb_content, save=False)
for_obj.update(**{to_field: to_.name})
| [
"@",
"task",
"(",
"rate_limit",
"=",
"'15/m'",
")",
"@",
"timeit",
"def",
"generate_thumbnail",
"(",
"for_obj",
",",
"from_field",
",",
"to_field",
",",
"max_size",
"=",
"settings",
".",
"THUMBNAIL_SIZE",
")",
":",
"from_",
"=",
"getattr",
"(",
"for_obj",
",",
"from_field",
")",
"to_",
"=",
"getattr",
"(",
"for_obj",
",",
"to_field",
")",
"if",
"(",
"not",
"(",
"from_",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"from_",
".",
"path",
")",
")",
")",
":",
"log_msg",
"=",
"'No file to generate from: {model} {id}, {from_f} -> {to_f}'",
"log",
".",
"info",
"(",
"log_msg",
".",
"format",
"(",
"model",
"=",
"for_obj",
".",
"__class__",
".",
"__name__",
",",
"id",
"=",
"for_obj",
".",
"id",
",",
"from_f",
"=",
"from_field",
",",
"to_f",
"=",
"to_field",
")",
")",
"return",
"log_msg",
"=",
"'Generating thumbnail for {model} {id}: {from_f} -> {to_f}'",
"log",
".",
"info",
"(",
"log_msg",
".",
"format",
"(",
"model",
"=",
"for_obj",
".",
"__class__",
".",
"__name__",
",",
"id",
"=",
"for_obj",
".",
"id",
",",
"from_f",
"=",
"from_field",
",",
"to_f",
"=",
"to_field",
")",
")",
"thumb_content",
"=",
"_create_image_thumbnail",
"(",
"from_",
".",
"path",
",",
"longest_side",
"=",
"max_size",
")",
"file_path",
"=",
"from_",
".",
"path",
"if",
"to_",
":",
"to_",
".",
"delete",
"(",
"save",
"=",
"False",
")",
"to_",
".",
"save",
"(",
"file_path",
",",
"thumb_content",
",",
"save",
"=",
"False",
")",
"for_obj",
".",
"update",
"(",
"**",
"{",
"to_field",
":",
"to_",
".",
"name",
"}",
")"
] | generate a thumbnail . | train | false |
20,468 | def _activity_stream_get_filtered_users():
users = config.get('ckan.hide_activity_from_users')
if users:
users_list = users.split()
else:
context = {'model': model, 'ignore_auth': True}
site_user = logic.get_action('get_site_user')(context)
users_list = [site_user.get('name')]
return model.User.user_ids_for_name_or_id(users_list)
| [
"def",
"_activity_stream_get_filtered_users",
"(",
")",
":",
"users",
"=",
"config",
".",
"get",
"(",
"'ckan.hide_activity_from_users'",
")",
"if",
"users",
":",
"users_list",
"=",
"users",
".",
"split",
"(",
")",
"else",
":",
"context",
"=",
"{",
"'model'",
":",
"model",
",",
"'ignore_auth'",
":",
"True",
"}",
"site_user",
"=",
"logic",
".",
"get_action",
"(",
"'get_site_user'",
")",
"(",
"context",
")",
"users_list",
"=",
"[",
"site_user",
".",
"get",
"(",
"'name'",
")",
"]",
"return",
"model",
".",
"User",
".",
"user_ids_for_name_or_id",
"(",
"users_list",
")"
] | get the list of users from the :ref:ckan . | train | false |
20,469 | def applyTransform(im, transform, inPlace=0):
try:
if inPlace:
transform.apply_in_place(im)
imOut = None
else:
imOut = transform.apply(im)
except (TypeError, ValueError) as v:
raise PyCMSError(v)
return imOut
| [
"def",
"applyTransform",
"(",
"im",
",",
"transform",
",",
"inPlace",
"=",
"0",
")",
":",
"try",
":",
"if",
"inPlace",
":",
"transform",
".",
"apply_in_place",
"(",
"im",
")",
"imOut",
"=",
"None",
"else",
":",
"imOut",
"=",
"transform",
".",
"apply",
"(",
"im",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
"as",
"v",
":",
"raise",
"PyCMSError",
"(",
"v",
")",
"return",
"imOut"
] | applies a transform to a given image . | train | false |
20,470 | def fermat_little_theorem(p):
a = randint(1, (p - 1))
return fast_exponentiation(a, (p - 1), p)
| [
"def",
"fermat_little_theorem",
"(",
"p",
")",
":",
"a",
"=",
"randint",
"(",
"1",
",",
"(",
"p",
"-",
"1",
")",
")",
"return",
"fast_exponentiation",
"(",
"a",
",",
"(",
"p",
"-",
"1",
")",
",",
"p",
")"
] | returns 1 if p may be prime . | train | false |
20,471 | def nonblocking(pipe):
flags = fcntl.fcntl(pipe, fcntl.F_GETFL)
fcntl.fcntl(pipe, fcntl.F_SETFL, (flags | os.O_NONBLOCK))
return pipe
| [
"def",
"nonblocking",
"(",
"pipe",
")",
":",
"flags",
"=",
"fcntl",
".",
"fcntl",
"(",
"pipe",
",",
"fcntl",
".",
"F_GETFL",
")",
"fcntl",
".",
"fcntl",
"(",
"pipe",
",",
"fcntl",
".",
"F_SETFL",
",",
"(",
"flags",
"|",
"os",
".",
"O_NONBLOCK",
")",
")",
"return",
"pipe"
] | set python file object to nonblocking mode . | train | false |
20,472 | @requires_statsmodels
def test_yule_walker():
from statsmodels.regression.linear_model import yule_walker as sm_yw
d = np.random.randn(100)
(sm_rho, sm_sigma) = sm_yw(d, order=2)
(rho, sigma) = _yule_walker(d[np.newaxis], order=2)
assert_array_almost_equal(sm_sigma, sigma)
assert_array_almost_equal(sm_rho, rho)
| [
"@",
"requires_statsmodels",
"def",
"test_yule_walker",
"(",
")",
":",
"from",
"statsmodels",
".",
"regression",
".",
"linear_model",
"import",
"yule_walker",
"as",
"sm_yw",
"d",
"=",
"np",
".",
"random",
".",
"randn",
"(",
"100",
")",
"(",
"sm_rho",
",",
"sm_sigma",
")",
"=",
"sm_yw",
"(",
"d",
",",
"order",
"=",
"2",
")",
"(",
"rho",
",",
"sigma",
")",
"=",
"_yule_walker",
"(",
"d",
"[",
"np",
".",
"newaxis",
"]",
",",
"order",
"=",
"2",
")",
"assert_array_almost_equal",
"(",
"sm_sigma",
",",
"sigma",
")",
"assert_array_almost_equal",
"(",
"sm_rho",
",",
"rho",
")"
] | test yule-walker against statsmodels . | train | false |
20,473 | def parse_pages(pdf_buffer, password):
parser = PDFParser(pdf_buffer)
document = PDFDocument(parser, password)
resource_manager = PDFResourceManager()
la_params = LAParams()
device = PDFPageAggregator(resource_manager, laparams=la_params)
interpreter = PDFPageInterpreter(resource_manager, device)
text_content = []
for page in PDFPage.create_pages(document):
interpreter.process_page(page)
layout = device.get_result()
text_content.append(parse_lt_objects(layout._objs))
return text_content
| [
"def",
"parse_pages",
"(",
"pdf_buffer",
",",
"password",
")",
":",
"parser",
"=",
"PDFParser",
"(",
"pdf_buffer",
")",
"document",
"=",
"PDFDocument",
"(",
"parser",
",",
"password",
")",
"resource_manager",
"=",
"PDFResourceManager",
"(",
")",
"la_params",
"=",
"LAParams",
"(",
")",
"device",
"=",
"PDFPageAggregator",
"(",
"resource_manager",
",",
"laparams",
"=",
"la_params",
")",
"interpreter",
"=",
"PDFPageInterpreter",
"(",
"resource_manager",
",",
"device",
")",
"text_content",
"=",
"[",
"]",
"for",
"page",
"in",
"PDFPage",
".",
"create_pages",
"(",
"document",
")",
":",
"interpreter",
".",
"process_page",
"(",
"page",
")",
"layout",
"=",
"device",
".",
"get_result",
"(",
")",
"text_content",
".",
"append",
"(",
"parse_lt_objects",
"(",
"layout",
".",
"_objs",
")",
")",
"return",
"text_content"
] | with an pdf buffer object . | train | false |
20,474 | def unsure_pyname(pyname, unbound=True):
if (pyname is None):
return True
if (unbound and (not isinstance(pyname, pynames.UnboundName))):
return False
if (pyname.get_object() == pyobjects.get_unknown()):
return True
| [
"def",
"unsure_pyname",
"(",
"pyname",
",",
"unbound",
"=",
"True",
")",
":",
"if",
"(",
"pyname",
"is",
"None",
")",
":",
"return",
"True",
"if",
"(",
"unbound",
"and",
"(",
"not",
"isinstance",
"(",
"pyname",
",",
"pynames",
".",
"UnboundName",
")",
")",
")",
":",
"return",
"False",
"if",
"(",
"pyname",
".",
"get_object",
"(",
")",
"==",
"pyobjects",
".",
"get_unknown",
"(",
")",
")",
":",
"return",
"True"
] | return true if we dont know what this name references . | train | true |
20,476 | @step('I run ipdb')
def run_ipdb(_step):
import ipdb
ipdb.set_trace()
assert True
| [
"@",
"step",
"(",
"'I run ipdb'",
")",
"def",
"run_ipdb",
"(",
"_step",
")",
":",
"import",
"ipdb",
"ipdb",
".",
"set_trace",
"(",
")",
"assert",
"True"
] | run ipdb as step for easy debugging . | train | false |
20,477 | def cell(value):
def f():
print a
a = value
return f.__closure__[0]
| [
"def",
"cell",
"(",
"value",
")",
":",
"def",
"f",
"(",
")",
":",
"print",
"a",
"a",
"=",
"value",
"return",
"f",
".",
"__closure__",
"[",
"0",
"]"
] | create a cell containing the given value . | train | false |
20,478 | @login_required
@require_http_methods(['GET', 'POST'])
def remove_member(request, group_slug, user_id):
prof = get_object_or_404(GroupProfile, slug=group_slug)
user = get_object_or_404(User, id=user_id)
if (not _user_can_edit(request.user, prof)):
raise PermissionDenied
if (request.method == 'POST'):
if (user in prof.leaders.all()):
prof.leaders.remove(user)
user.groups.remove(prof.group)
msg = _('{user} removed from the group successfully!').format(user=user.username)
messages.add_message(request, messages.SUCCESS, msg)
return HttpResponseRedirect(prof.get_absolute_url())
return render(request, 'groups/confirm_remove_member.html', {'profile': prof, 'member': user})
| [
"@",
"login_required",
"@",
"require_http_methods",
"(",
"[",
"'GET'",
",",
"'POST'",
"]",
")",
"def",
"remove_member",
"(",
"request",
",",
"group_slug",
",",
"user_id",
")",
":",
"prof",
"=",
"get_object_or_404",
"(",
"GroupProfile",
",",
"slug",
"=",
"group_slug",
")",
"user",
"=",
"get_object_or_404",
"(",
"User",
",",
"id",
"=",
"user_id",
")",
"if",
"(",
"not",
"_user_can_edit",
"(",
"request",
".",
"user",
",",
"prof",
")",
")",
":",
"raise",
"PermissionDenied",
"if",
"(",
"request",
".",
"method",
"==",
"'POST'",
")",
":",
"if",
"(",
"user",
"in",
"prof",
".",
"leaders",
".",
"all",
"(",
")",
")",
":",
"prof",
".",
"leaders",
".",
"remove",
"(",
"user",
")",
"user",
".",
"groups",
".",
"remove",
"(",
"prof",
".",
"group",
")",
"msg",
"=",
"_",
"(",
"'{user} removed from the group successfully!'",
")",
".",
"format",
"(",
"user",
"=",
"user",
".",
"username",
")",
"messages",
".",
"add_message",
"(",
"request",
",",
"messages",
".",
"SUCCESS",
",",
"msg",
")",
"return",
"HttpResponseRedirect",
"(",
"prof",
".",
"get_absolute_url",
"(",
")",
")",
"return",
"render",
"(",
"request",
",",
"'groups/confirm_remove_member.html'",
",",
"{",
"'profile'",
":",
"prof",
",",
"'member'",
":",
"user",
"}",
")"
] | remove a member from the group . | train | false |
20,480 | def _report_no_chall_path():
msg = 'Client with the currently selected authenticator does not support any combination of challenges that will satisfy the CA.'
logger.fatal(msg)
raise errors.AuthorizationError(msg)
| [
"def",
"_report_no_chall_path",
"(",
")",
":",
"msg",
"=",
"'Client with the currently selected authenticator does not support any combination of challenges that will satisfy the CA.'",
"logger",
".",
"fatal",
"(",
"msg",
")",
"raise",
"errors",
".",
"AuthorizationError",
"(",
"msg",
")"
] | logs and raises an error that no satisfiable chall path exists . | train | false |
20,481 | def sort_pcap(inpath, outpath):
inc = SortCap(inpath)
batch_sort(inc, outpath, output_class=(lambda path: SortCap(path, linktype=inc.linktype)))
return 0
| [
"def",
"sort_pcap",
"(",
"inpath",
",",
"outpath",
")",
":",
"inc",
"=",
"SortCap",
"(",
"inpath",
")",
"batch_sort",
"(",
"inc",
",",
"outpath",
",",
"output_class",
"=",
"(",
"lambda",
"path",
":",
"SortCap",
"(",
"path",
",",
"linktype",
"=",
"inc",
".",
"linktype",
")",
")",
")",
"return",
"0"
] | use sortcap class together with batch_sort to sort a pcap . | train | false |
20,482 | @plugins.notify_info_yielded(u'albuminfo_received')
def albums_for_id(album_id):
a = album_for_mbid(album_id)
if a:
(yield a)
for a in plugins.album_for_id(album_id):
if a:
(yield a)
| [
"@",
"plugins",
".",
"notify_info_yielded",
"(",
"u'albuminfo_received'",
")",
"def",
"albums_for_id",
"(",
"album_id",
")",
":",
"a",
"=",
"album_for_mbid",
"(",
"album_id",
")",
"if",
"a",
":",
"(",
"yield",
"a",
")",
"for",
"a",
"in",
"plugins",
".",
"album_for_id",
"(",
"album_id",
")",
":",
"if",
"a",
":",
"(",
"yield",
"a",
")"
] | get a list of albums for an id . | train | false |
20,483 | def measure_all(qubit, format='sympy', normalize=True):
m = qubit_to_matrix(qubit, format)
if (format == 'sympy'):
results = []
if normalize:
m = m.normalized()
size = max(m.shape)
nqubits = int((math.log(size) / math.log(2)))
for i in range(size):
if (m[i] != 0.0):
results.append((Qubit(IntQubit(i, nqubits)), (m[i] * conjugate(m[i]))))
return results
else:
raise NotImplementedError("This function can't handle non-sympy matrix formats yet")
| [
"def",
"measure_all",
"(",
"qubit",
",",
"format",
"=",
"'sympy'",
",",
"normalize",
"=",
"True",
")",
":",
"m",
"=",
"qubit_to_matrix",
"(",
"qubit",
",",
"format",
")",
"if",
"(",
"format",
"==",
"'sympy'",
")",
":",
"results",
"=",
"[",
"]",
"if",
"normalize",
":",
"m",
"=",
"m",
".",
"normalized",
"(",
")",
"size",
"=",
"max",
"(",
"m",
".",
"shape",
")",
"nqubits",
"=",
"int",
"(",
"(",
"math",
".",
"log",
"(",
"size",
")",
"/",
"math",
".",
"log",
"(",
"2",
")",
")",
")",
"for",
"i",
"in",
"range",
"(",
"size",
")",
":",
"if",
"(",
"m",
"[",
"i",
"]",
"!=",
"0.0",
")",
":",
"results",
".",
"append",
"(",
"(",
"Qubit",
"(",
"IntQubit",
"(",
"i",
",",
"nqubits",
")",
")",
",",
"(",
"m",
"[",
"i",
"]",
"*",
"conjugate",
"(",
"m",
"[",
"i",
"]",
")",
")",
")",
")",
"return",
"results",
"else",
":",
"raise",
"NotImplementedError",
"(",
"\"This function can't handle non-sympy matrix formats yet\"",
")"
] | perform an ensemble measurement of all qubits . | train | false |
20,484 | def fixup_simple_stmt(parent, i, stmt_node):
for (semi_ind, node) in enumerate(stmt_node.children):
if (node.type == token.SEMI):
break
else:
return
node.remove()
new_expr = Node(syms.expr_stmt, [])
new_stmt = Node(syms.simple_stmt, [new_expr])
while stmt_node.children[semi_ind:]:
move_node = stmt_node.children[semi_ind]
new_expr.append_child(move_node.clone())
move_node.remove()
parent.insert_child(i, new_stmt)
new_leaf1 = new_stmt.children[0].children[0]
old_leaf1 = stmt_node.children[0].children[0]
new_leaf1.set_prefix(old_leaf1.get_prefix())
| [
"def",
"fixup_simple_stmt",
"(",
"parent",
",",
"i",
",",
"stmt_node",
")",
":",
"for",
"(",
"semi_ind",
",",
"node",
")",
"in",
"enumerate",
"(",
"stmt_node",
".",
"children",
")",
":",
"if",
"(",
"node",
".",
"type",
"==",
"token",
".",
"SEMI",
")",
":",
"break",
"else",
":",
"return",
"node",
".",
"remove",
"(",
")",
"new_expr",
"=",
"Node",
"(",
"syms",
".",
"expr_stmt",
",",
"[",
"]",
")",
"new_stmt",
"=",
"Node",
"(",
"syms",
".",
"simple_stmt",
",",
"[",
"new_expr",
"]",
")",
"while",
"stmt_node",
".",
"children",
"[",
"semi_ind",
":",
"]",
":",
"move_node",
"=",
"stmt_node",
".",
"children",
"[",
"semi_ind",
"]",
"new_expr",
".",
"append_child",
"(",
"move_node",
".",
"clone",
"(",
")",
")",
"move_node",
".",
"remove",
"(",
")",
"parent",
".",
"insert_child",
"(",
"i",
",",
"new_stmt",
")",
"new_leaf1",
"=",
"new_stmt",
".",
"children",
"[",
"0",
"]",
".",
"children",
"[",
"0",
"]",
"old_leaf1",
"=",
"stmt_node",
".",
"children",
"[",
"0",
"]",
".",
"children",
"[",
"0",
"]",
"new_leaf1",
".",
"set_prefix",
"(",
"old_leaf1",
".",
"get_prefix",
"(",
")",
")"
] | if there is a semi-colon all the parts count as part of the same simple_stmt . | train | true |
20,485 | def isXQuartz():
assert (_tk_type is not None)
return (_tk_type == 'xquartz')
| [
"def",
"isXQuartz",
"(",
")",
":",
"assert",
"(",
"_tk_type",
"is",
"not",
"None",
")",
"return",
"(",
"_tk_type",
"==",
"'xquartz'",
")"
] | returns true if idle is using an os x x11 tk . | train | false |
20,487 | def sync_overlays():
layman = init_layman()
for name in layman.get_installed():
sync_overlay(name)
| [
"def",
"sync_overlays",
"(",
")",
":",
"layman",
"=",
"init_layman",
"(",
")",
"for",
"name",
"in",
"layman",
".",
"get_installed",
"(",
")",
":",
"sync_overlay",
"(",
"name",
")"
] | synchronize all of the installed overlays . | train | false |
20,489 | def combine_datetime_timedelta_units(datetime_unit, timedelta_unit):
dt_unit_code = DATETIME_UNITS[datetime_unit]
td_unit_code = DATETIME_UNITS[timedelta_unit]
if (dt_unit_code == 14):
return timedelta_unit
elif (td_unit_code == 14):
return datetime_unit
if ((td_unit_code < 2) and (dt_unit_code >= 2)):
return None
if (dt_unit_code > td_unit_code):
return datetime_unit
else:
return timedelta_unit
| [
"def",
"combine_datetime_timedelta_units",
"(",
"datetime_unit",
",",
"timedelta_unit",
")",
":",
"dt_unit_code",
"=",
"DATETIME_UNITS",
"[",
"datetime_unit",
"]",
"td_unit_code",
"=",
"DATETIME_UNITS",
"[",
"timedelta_unit",
"]",
"if",
"(",
"dt_unit_code",
"==",
"14",
")",
":",
"return",
"timedelta_unit",
"elif",
"(",
"td_unit_code",
"==",
"14",
")",
":",
"return",
"datetime_unit",
"if",
"(",
"(",
"td_unit_code",
"<",
"2",
")",
"and",
"(",
"dt_unit_code",
">=",
"2",
")",
")",
":",
"return",
"None",
"if",
"(",
"dt_unit_code",
">",
"td_unit_code",
")",
":",
"return",
"datetime_unit",
"else",
":",
"return",
"timedelta_unit"
] | return the unit result of combining *datetime_unit* with *timedelta_unit* . | train | false |
20,490 | def g_fit(data, williams=True):
r_data = [array(i).mean() for i in data]
(G, p) = power_divergence(r_data, lambda_='log-likelihood')
if williams:
G_corr = williams_correction(sum(r_data), len(r_data), G)
return (G_corr, chi2prob(G_corr, (len(r_data) - 1), direction='high'))
else:
return (G, p)
| [
"def",
"g_fit",
"(",
"data",
",",
"williams",
"=",
"True",
")",
":",
"r_data",
"=",
"[",
"array",
"(",
"i",
")",
".",
"mean",
"(",
")",
"for",
"i",
"in",
"data",
"]",
"(",
"G",
",",
"p",
")",
"=",
"power_divergence",
"(",
"r_data",
",",
"lambda_",
"=",
"'log-likelihood'",
")",
"if",
"williams",
":",
"G_corr",
"=",
"williams_correction",
"(",
"sum",
"(",
"r_data",
")",
",",
"len",
"(",
"r_data",
")",
",",
"G",
")",
"return",
"(",
"G_corr",
",",
"chi2prob",
"(",
"G_corr",
",",
"(",
"len",
"(",
"r_data",
")",
"-",
"1",
")",
",",
"direction",
"=",
"'high'",
")",
")",
"else",
":",
"return",
"(",
"G",
",",
"p",
")"
] | calculate the g statistic aka log-likelihood ratio test . | train | false |
20,491 | def get_resources_nodes(call=None, resFilter=None):
log.debug('Getting resource: nodes.. (filter: {0})'.format(resFilter))
resources = query('get', 'cluster/resources')
ret = {}
for resource in resources:
if (('type' in resource) and (resource['type'] == 'node')):
name = resource['node']
ret[name] = resource
if (resFilter is not None):
log.debug('Filter given: {0}, returning requested resource: nodes'.format(resFilter))
return ret[resFilter]
log.debug('Filter not given: {0}, returning all resource: nodes'.format(ret))
return ret
| [
"def",
"get_resources_nodes",
"(",
"call",
"=",
"None",
",",
"resFilter",
"=",
"None",
")",
":",
"log",
".",
"debug",
"(",
"'Getting resource: nodes.. (filter: {0})'",
".",
"format",
"(",
"resFilter",
")",
")",
"resources",
"=",
"query",
"(",
"'get'",
",",
"'cluster/resources'",
")",
"ret",
"=",
"{",
"}",
"for",
"resource",
"in",
"resources",
":",
"if",
"(",
"(",
"'type'",
"in",
"resource",
")",
"and",
"(",
"resource",
"[",
"'type'",
"]",
"==",
"'node'",
")",
")",
":",
"name",
"=",
"resource",
"[",
"'node'",
"]",
"ret",
"[",
"name",
"]",
"=",
"resource",
"if",
"(",
"resFilter",
"is",
"not",
"None",
")",
":",
"log",
".",
"debug",
"(",
"'Filter given: {0}, returning requested resource: nodes'",
".",
"format",
"(",
"resFilter",
")",
")",
"return",
"ret",
"[",
"resFilter",
"]",
"log",
".",
"debug",
"(",
"'Filter not given: {0}, returning all resource: nodes'",
".",
"format",
"(",
"ret",
")",
")",
"return",
"ret"
] | retrieve all hypervisors available on this environment cli example: . | train | true |
20,492 | def fast_replace(data, keys, values, skip_checks=False):
assert np.allclose(keys.shape, values.shape)
if (not skip_checks):
msg = 'data has elements not in keys'
assert (data.max() <= keys.max()), msg
sdx = np.argsort(keys)
(keys, values) = (keys[sdx], values[sdx])
idx = np.digitize(data, keys, right=True)
new_data = values[idx]
return new_data
| [
"def",
"fast_replace",
"(",
"data",
",",
"keys",
",",
"values",
",",
"skip_checks",
"=",
"False",
")",
":",
"assert",
"np",
".",
"allclose",
"(",
"keys",
".",
"shape",
",",
"values",
".",
"shape",
")",
"if",
"(",
"not",
"skip_checks",
")",
":",
"msg",
"=",
"'data has elements not in keys'",
"assert",
"(",
"data",
".",
"max",
"(",
")",
"<=",
"keys",
".",
"max",
"(",
")",
")",
",",
"msg",
"sdx",
"=",
"np",
".",
"argsort",
"(",
"keys",
")",
"(",
"keys",
",",
"values",
")",
"=",
"(",
"keys",
"[",
"sdx",
"]",
",",
"values",
"[",
"sdx",
"]",
")",
"idx",
"=",
"np",
".",
"digitize",
"(",
"data",
",",
"keys",
",",
"right",
"=",
"True",
")",
"new_data",
"=",
"values",
"[",
"idx",
"]",
"return",
"new_data"
] | do a search-and-replace in array data . | train | false |
20,493 | def generate_xmap(x_len, y_len, all_cids, all_xcoords, all_ycoords):
img_height = (x_len * 80)
img_width = (y_len * 80)
xmap = []
for (cid, x, y) in zip(all_cids, all_xcoords, all_ycoords):
xmap.append((AREA_SRC % (x, (img_height - y), cid, cid)))
return (xmap, img_height, img_width)
| [
"def",
"generate_xmap",
"(",
"x_len",
",",
"y_len",
",",
"all_cids",
",",
"all_xcoords",
",",
"all_ycoords",
")",
":",
"img_height",
"=",
"(",
"x_len",
"*",
"80",
")",
"img_width",
"=",
"(",
"y_len",
"*",
"80",
")",
"xmap",
"=",
"[",
"]",
"for",
"(",
"cid",
",",
"x",
",",
"y",
")",
"in",
"zip",
"(",
"all_cids",
",",
"all_xcoords",
",",
"all_ycoords",
")",
":",
"xmap",
".",
"append",
"(",
"(",
"AREA_SRC",
"%",
"(",
"x",
",",
"(",
"img_height",
"-",
"y",
")",
",",
"cid",
",",
"cid",
")",
")",
")",
"return",
"(",
"xmap",
",",
"img_height",
",",
"img_width",
")"
] | generates the html interactive image map . | train | false |
20,494 | def getVarContent(jsCode, varContent):
clearBytes = ''
varContent = varContent.replace('\n', '')
varContent = varContent.replace('\r', '')
varContent = varContent.replace(' DCTB ', '')
varContent = varContent.replace(' ', '')
parts = varContent.split('+')
for part in parts:
if re.match('["\'].*?["\']', part, re.DOTALL):
clearBytes += part[1:(-1)]
else:
part = escapeString(part)
varContent = re.findall((part + '\\s*?=\\s*?(.*?)[,;]'), jsCode, re.DOTALL)
if (varContent != []):
clearBytes += getVarContent(jsCode, varContent[0])
return clearBytes
| [
"def",
"getVarContent",
"(",
"jsCode",
",",
"varContent",
")",
":",
"clearBytes",
"=",
"''",
"varContent",
"=",
"varContent",
".",
"replace",
"(",
"'\\n'",
",",
"''",
")",
"varContent",
"=",
"varContent",
".",
"replace",
"(",
"'\\r'",
",",
"''",
")",
"varContent",
"=",
"varContent",
".",
"replace",
"(",
"' DCTB '",
",",
"''",
")",
"varContent",
"=",
"varContent",
".",
"replace",
"(",
"' '",
",",
"''",
")",
"parts",
"=",
"varContent",
".",
"split",
"(",
"'+'",
")",
"for",
"part",
"in",
"parts",
":",
"if",
"re",
".",
"match",
"(",
"'[\"\\'].*?[\"\\']'",
",",
"part",
",",
"re",
".",
"DOTALL",
")",
":",
"clearBytes",
"+=",
"part",
"[",
"1",
":",
"(",
"-",
"1",
")",
"]",
"else",
":",
"part",
"=",
"escapeString",
"(",
"part",
")",
"varContent",
"=",
"re",
".",
"findall",
"(",
"(",
"part",
"+",
"'\\\\s*?=\\\\s*?(.*?)[,;]'",
")",
",",
"jsCode",
",",
"re",
".",
"DOTALL",
")",
"if",
"(",
"varContent",
"!=",
"[",
"]",
")",
":",
"clearBytes",
"+=",
"getVarContent",
"(",
"jsCode",
",",
"varContent",
"[",
"0",
"]",
")",
"return",
"clearBytes"
] | given the javascript code and the content of a variable this method tries to obtain the real value of the variable . | train | false |
20,500 | def acl_delete(consul_url=None, **kwargs):
ret = {}
data = {}
if (not consul_url):
consul_url = _get_config()
if (not consul_url):
log.error('No Consul URL found.')
ret['message'] = 'No Consul URL found.'
ret['res'] = False
return ret
if ('id' not in kwargs):
ret['message'] = 'Required parameter "id" is missing.'
ret['res'] = False
return ret
function = 'acl/delete/{0}'.format(kwargs['id'])
res = _query(consul_url=consul_url, data=data, method='PUT', function=function)
if res['res']:
ret['res'] = True
ret['message'] = 'ACL {0} deleted.'.format(kwargs['id'])
else:
ret['res'] = False
ret['message'] = 'Removing ACL {0} failed.'.format(kwargs['id'])
return ret
| [
"def",
"acl_delete",
"(",
"consul_url",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"ret",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"if",
"(",
"not",
"consul_url",
")",
":",
"consul_url",
"=",
"_get_config",
"(",
")",
"if",
"(",
"not",
"consul_url",
")",
":",
"log",
".",
"error",
"(",
"'No Consul URL found.'",
")",
"ret",
"[",
"'message'",
"]",
"=",
"'No Consul URL found.'",
"ret",
"[",
"'res'",
"]",
"=",
"False",
"return",
"ret",
"if",
"(",
"'id'",
"not",
"in",
"kwargs",
")",
":",
"ret",
"[",
"'message'",
"]",
"=",
"'Required parameter \"id\" is missing.'",
"ret",
"[",
"'res'",
"]",
"=",
"False",
"return",
"ret",
"function",
"=",
"'acl/delete/{0}'",
".",
"format",
"(",
"kwargs",
"[",
"'id'",
"]",
")",
"res",
"=",
"_query",
"(",
"consul_url",
"=",
"consul_url",
",",
"data",
"=",
"data",
",",
"method",
"=",
"'PUT'",
",",
"function",
"=",
"function",
")",
"if",
"res",
"[",
"'res'",
"]",
":",
"ret",
"[",
"'res'",
"]",
"=",
"True",
"ret",
"[",
"'message'",
"]",
"=",
"'ACL {0} deleted.'",
".",
"format",
"(",
"kwargs",
"[",
"'id'",
"]",
")",
"else",
":",
"ret",
"[",
"'res'",
"]",
"=",
"False",
"ret",
"[",
"'message'",
"]",
"=",
"'Removing ACL {0} failed.'",
".",
"format",
"(",
"kwargs",
"[",
"'id'",
"]",
")",
"return",
"ret"
] | delete an acl token . | train | true |
20,502 | @check_login_required
@check_local_site_access
def users_list(request, local_site=None, template_name=u'datagrids/datagrid.html'):
grid = UsersDataGrid(request, local_site=local_site)
return grid.render_to_response(template_name)
| [
"@",
"check_login_required",
"@",
"check_local_site_access",
"def",
"users_list",
"(",
"request",
",",
"local_site",
"=",
"None",
",",
"template_name",
"=",
"u'datagrids/datagrid.html'",
")",
":",
"grid",
"=",
"UsersDataGrid",
"(",
"request",
",",
"local_site",
"=",
"local_site",
")",
"return",
"grid",
".",
"render_to_response",
"(",
"template_name",
")"
] | display a list of all users . | train | false |
20,503 | def addXMLFromXYZ(depth, index, output, x, y, z):
attributeDictionary = {'index': str(index)}
if (x != 0.0):
attributeDictionary['x'] = str(x)
if (y != 0.0):
attributeDictionary['y'] = str(y)
if (z != 0.0):
attributeDictionary['z'] = str(z)
addClosedXMLTag(attributeDictionary, 'vertex', depth, output)
| [
"def",
"addXMLFromXYZ",
"(",
"depth",
",",
"index",
",",
"output",
",",
"x",
",",
"y",
",",
"z",
")",
":",
"attributeDictionary",
"=",
"{",
"'index'",
":",
"str",
"(",
"index",
")",
"}",
"if",
"(",
"x",
"!=",
"0.0",
")",
":",
"attributeDictionary",
"[",
"'x'",
"]",
"=",
"str",
"(",
"x",
")",
"if",
"(",
"y",
"!=",
"0.0",
")",
":",
"attributeDictionary",
"[",
"'y'",
"]",
"=",
"str",
"(",
"y",
")",
"if",
"(",
"z",
"!=",
"0.0",
")",
":",
"attributeDictionary",
"[",
"'z'",
"]",
"=",
"str",
"(",
"z",
")",
"addClosedXMLTag",
"(",
"attributeDictionary",
",",
"'vertex'",
",",
"depth",
",",
"output",
")"
] | add xml from x . | train | false |
20,504 | def _stringify(value):
if isinstance(value, (list, tuple)):
if (len(value) == 1):
value = _stringify(value[0])
if (value[0] == '{'):
value = ('{%s}' % value)
else:
value = ('{%s}' % _join(value))
else:
if isinstance(value, str):
value = unicode(value, 'utf-8')
elif (not isinstance(value, unicode)):
value = str(value)
if (not value):
value = '{}'
elif _magic_re.search(value):
value = _magic_re.sub('\\\\\\1', value)
value = _space_re.sub('\\\\\\1', value)
elif ((value[0] == '"') or _space_re.search(value)):
value = ('{%s}' % value)
return value
| [
"def",
"_stringify",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"if",
"(",
"len",
"(",
"value",
")",
"==",
"1",
")",
":",
"value",
"=",
"_stringify",
"(",
"value",
"[",
"0",
"]",
")",
"if",
"(",
"value",
"[",
"0",
"]",
"==",
"'{'",
")",
":",
"value",
"=",
"(",
"'{%s}'",
"%",
"value",
")",
"else",
":",
"value",
"=",
"(",
"'{%s}'",
"%",
"_join",
"(",
"value",
")",
")",
"else",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"value",
"=",
"unicode",
"(",
"value",
",",
"'utf-8'",
")",
"elif",
"(",
"not",
"isinstance",
"(",
"value",
",",
"unicode",
")",
")",
":",
"value",
"=",
"str",
"(",
"value",
")",
"if",
"(",
"not",
"value",
")",
":",
"value",
"=",
"'{}'",
"elif",
"_magic_re",
".",
"search",
"(",
"value",
")",
":",
"value",
"=",
"_magic_re",
".",
"sub",
"(",
"'\\\\\\\\\\\\1'",
",",
"value",
")",
"value",
"=",
"_space_re",
".",
"sub",
"(",
"'\\\\\\\\\\\\1'",
",",
"value",
")",
"elif",
"(",
"(",
"value",
"[",
"0",
"]",
"==",
"'\"'",
")",
"or",
"_space_re",
".",
"search",
"(",
"value",
")",
")",
":",
"value",
"=",
"(",
"'{%s}'",
"%",
"value",
")",
"return",
"value"
] | internal function . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.