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 |
|---|---|---|---|---|---|
25,408 | def get_notifier(transport, publisher_id):
notifier = oslo_messaging.Notifier(transport, serializer=_SERIALIZER)
return notifier.prepare(publisher_id=publisher_id)
| [
"def",
"get_notifier",
"(",
"transport",
",",
"publisher_id",
")",
":",
"notifier",
"=",
"oslo_messaging",
".",
"Notifier",
"(",
"transport",
",",
"serializer",
"=",
"_SERIALIZER",
")",
"return",
"notifier",
".",
"prepare",
"(",
"publisher_id",
"=",
"publisher_i... | return a configured oslo_messaging notifier . | train | false |
25,409 | def _defined_names(current):
names = []
if is_node(current, 'testlist_star_expr', 'testlist_comp', 'exprlist'):
for child in current.children[::2]:
names += _defined_names(child)
elif is_node(current, 'atom', 'star_expr'):
names += _defined_names(current.children[1])
elif is_node(current, 'power', 'atom_expr'):
if (current.children[(-2)] != '**'):
trailer = current.children[(-1)]
if (trailer.children[0] == '.'):
names.append(trailer.children[1])
else:
names.append(current)
return names
| [
"def",
"_defined_names",
"(",
"current",
")",
":",
"names",
"=",
"[",
"]",
"if",
"is_node",
"(",
"current",
",",
"'testlist_star_expr'",
",",
"'testlist_comp'",
",",
"'exprlist'",
")",
":",
"for",
"child",
"in",
"current",
".",
"children",
"[",
":",
":",
... | a helper function to find the defined names in statements . | train | false |
25,412 | def do_authentication(hass, config):
from oauth2client.client import OAuth2WebServerFlow, OAuth2DeviceCodeError, FlowExchangeError
from oauth2client.file import Storage
oauth = OAuth2WebServerFlow(config[CONF_CLIENT_ID], config[CONF_CLIENT_SECRET], 'https://www.googleapis.com/auth/calendar.readonly', 'Home-Assistant.io')
persistent_notification = loader.get_component('persistent_notification')
try:
dev_flow = oauth.step1_get_device_and_user_codes()
except OAuth2DeviceCodeError as err:
persistent_notification.create(hass, 'Error: {}<br />You will need to restart hass after fixing.'.format(err), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID)
return False
persistent_notification.create(hass, 'In order to authorize Home-Assistant to view your calendarsYou must visit: <a href="{}" target="_blank">{}</a> and entercode: {}'.format(dev_flow.verification_url, dev_flow.verification_url, dev_flow.user_code), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID)
def step2_exchange(now):
'Keep trying to validate the user_code until it expires.'
if (now >= dt.as_local(dev_flow.user_code_expiry)):
persistent_notification.create(hass, 'Authenication code expired, please restart Home-Assistant and try again', title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID)
listener()
try:
credentials = oauth.step2_exchange(device_flow_info=dev_flow)
except FlowExchangeError:
return
storage = Storage(hass.config.path(TOKEN_FILE))
storage.put(credentials)
do_setup(hass, config)
listener()
persistent_notification.create(hass, 'We are all setup now. Check {} for calendars that have been found'.format(YAML_DEVICES), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID)
listener = track_time_change(hass, step2_exchange, second=range(0, 60, dev_flow.interval))
return True
| [
"def",
"do_authentication",
"(",
"hass",
",",
"config",
")",
":",
"from",
"oauth2client",
".",
"client",
"import",
"OAuth2WebServerFlow",
",",
"OAuth2DeviceCodeError",
",",
"FlowExchangeError",
"from",
"oauth2client",
".",
"file",
"import",
"Storage",
"oauth",
"=",
... | display the login form . | train | false |
25,413 | @pytest.fixture(autouse=True)
def fake_dns(monkeypatch):
dns = FakeDNS()
monkeypatch.setattr('qutebrowser.utils.urlutils.QHostInfo.fromName', dns.fromname_mock)
return dns
| [
"@",
"pytest",
".",
"fixture",
"(",
"autouse",
"=",
"True",
")",
"def",
"fake_dns",
"(",
"monkeypatch",
")",
":",
"dns",
"=",
"FakeDNS",
"(",
")",
"monkeypatch",
".",
"setattr",
"(",
"'qutebrowser.utils.urlutils.QHostInfo.fromName'",
",",
"dns",
".",
"fromname... | patched qhostinfo . | train | false |
25,414 | @pytest.mark.xfail
def test_equality_masked_bug():
t = table.Table.read([' a b c d', ' 2 c 7.0 0', ' 2 b 5.0 1', ' 2 b 6.0 2', ' 2 a 4.0 3', ' 0 a 0.0 4', ' 1 b 3.0 5', ' 1 a 2.0 6', ' 1 a 1.0 7'], format='ascii')
t = table.Table(t, masked=True)
t2 = table.Table.read([' a b c d', ' 2 c 7.0 0', ' 2 b 5.0 1', ' 3 b 6.0 2', ' 2 a 4.0 3', ' 0 a 1.0 4', ' 1 b 3.0 5', ' 1 c 2.0 6', ' 1 a 1.0 7'], format='ascii')
assert np.all(((t.as_array() == t2) == np.array([0, 1, 0, 1, 0, 1, 0, 1], dtype=bool)))
| [
"@",
"pytest",
".",
"mark",
".",
"xfail",
"def",
"test_equality_masked_bug",
"(",
")",
":",
"t",
"=",
"table",
".",
"Table",
".",
"read",
"(",
"[",
"' a b c d'",
",",
"' 2 c 7.0 0'",
",",
"' 2 b 5.0 1'",
",",
"' 2 b 6.0 2'",
",",
"' 2 a 4.0 3'",
",",
"' ... | this highlights a numpy bug . | train | false |
25,415 | def _activities_at_offset(q, limit, offset):
return _activities_limit(q, limit, offset).all()
| [
"def",
"_activities_at_offset",
"(",
"q",
",",
"limit",
",",
"offset",
")",
":",
"return",
"_activities_limit",
"(",
"q",
",",
"limit",
",",
"offset",
")",
".",
"all",
"(",
")"
] | return a list of all activities at an offset with a limit . | train | false |
25,416 | def is_id(id_string):
reg_ex = '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'
return bool(re.match(reg_ex, id_string))
| [
"def",
"is_id",
"(",
"id_string",
")",
":",
"reg_ex",
"=",
"'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'",
"return",
"bool",
"(",
"re",
".",
"match",
"(",
"reg_ex",
",",
"id_string",
")",
")"
] | tells the client if the string looks like a revision id or not . | train | false |
25,417 | @testing.requires_testing_data
def test_raw_copy():
raw = read_raw_fif(fif_fname, preload=True)
(data, _) = raw[:, :]
copied = raw.copy()
(copied_data, _) = copied[:, :]
assert_array_equal(data, copied_data)
assert_equal(sorted(raw.__dict__.keys()), sorted(copied.__dict__.keys()))
raw = read_raw_fif(fif_fname, preload=False)
(data, _) = raw[:, :]
copied = raw.copy()
(copied_data, _) = copied[:, :]
assert_array_equal(data, copied_data)
assert_equal(sorted(raw.__dict__.keys()), sorted(copied.__dict__.keys()))
| [
"@",
"testing",
".",
"requires_testing_data",
"def",
"test_raw_copy",
"(",
")",
":",
"raw",
"=",
"read_raw_fif",
"(",
"fif_fname",
",",
"preload",
"=",
"True",
")",
"(",
"data",
",",
"_",
")",
"=",
"raw",
"[",
":",
",",
":",
"]",
"copied",
"=",
"raw"... | test raw copy . | train | false |
25,418 | def package_resource_name(name):
if (PRN_SEPARATOR in name):
val = tuple(name.split(PRN_SEPARATOR))
if (len(val) != 2):
raise ValueError(('invalid name [%s]' % name))
else:
return val
else:
return ('', name)
| [
"def",
"package_resource_name",
"(",
"name",
")",
":",
"if",
"(",
"PRN_SEPARATOR",
"in",
"name",
")",
":",
"val",
"=",
"tuple",
"(",
"name",
".",
"split",
"(",
"PRN_SEPARATOR",
")",
")",
"if",
"(",
"len",
"(",
"val",
")",
"!=",
"2",
")",
":",
"rais... | split a name into its package and resource name parts . | train | false |
25,419 | @core_helper
def full_current_url():
return url_for(request.environ['CKAN_CURRENT_URL'], qualified=True)
| [
"@",
"core_helper",
"def",
"full_current_url",
"(",
")",
":",
"return",
"url_for",
"(",
"request",
".",
"environ",
"[",
"'CKAN_CURRENT_URL'",
"]",
",",
"qualified",
"=",
"True",
")"
] | returns the fully qualified current url useful for sharing etc . | train | false |
25,420 | def DER_cert_to_PEM_cert(der_cert_bytes):
if hasattr(base64, 'standard_b64encode'):
f = base64.standard_b64encode(der_cert_bytes)
rval = (PEM_HEADER + '\n')
while (len(f) > 0):
l = min(len(f), 64)
rval += (f[:l] + '\n')
f = f[l:]
rval += (PEM_FOOTER + '\n')
return rval
else:
return ((((PEM_HEADER + '\n') + base64.encodestring(der_cert_bytes)) + PEM_FOOTER) + '\n')
| [
"def",
"DER_cert_to_PEM_cert",
"(",
"der_cert_bytes",
")",
":",
"if",
"hasattr",
"(",
"base64",
",",
"'standard_b64encode'",
")",
":",
"f",
"=",
"base64",
".",
"standard_b64encode",
"(",
"der_cert_bytes",
")",
"rval",
"=",
"(",
"PEM_HEADER",
"+",
"'\\n'",
")",... | takes a certificate in binary der format and returns the pem version of it as a string . | train | false |
25,421 | def return_merged_clips(data):
def max(a, b):
"It returns the max of the two given numbers.\n\n It won't take into account the zero values.\n "
if ((not a) and (not b)):
return None
if (not a):
return b
if (not b):
return a
if (a >= b):
return a
else:
return b
def min(a, b):
"It returns the min of the two given numbers.\n\n It won't take into account the zero values.\n "
if ((not a) and (not b)):
return None
if (not a):
return b
if (not b):
return a
if (a <= b):
return a
else:
return b
left = max(data['clip_adapter_left'], data['clip_qual_left'])
right = min(data['clip_adapter_right'], data['clip_qual_right'])
if (left is None):
left = 1
if (right is None):
right = data['number_of_bases']
return (left, right)
| [
"def",
"return_merged_clips",
"(",
"data",
")",
":",
"def",
"max",
"(",
"a",
",",
"b",
")",
":",
"if",
"(",
"(",
"not",
"a",
")",
"and",
"(",
"not",
"b",
")",
")",
":",
"return",
"None",
"if",
"(",
"not",
"a",
")",
":",
"return",
"b",
"if",
... | it returns the left and right positions to clip . | train | false |
25,422 | def _ScopesToString(scopes):
if isinstance(scopes, types.StringTypes):
return scopes
else:
return ' '.join(scopes)
| [
"def",
"_ScopesToString",
"(",
"scopes",
")",
":",
"if",
"isinstance",
"(",
"scopes",
",",
"types",
".",
"StringTypes",
")",
":",
"return",
"scopes",
"else",
":",
"return",
"' '",
".",
"join",
"(",
"scopes",
")"
] | converts scope value to a string . | train | false |
25,424 | def get_system_tor_version(tor_cmd='tor'):
if (tor_cmd not in VERSION_CACHE):
version_cmd = ('%s --version' % tor_cmd)
try:
version_output = stem.util.system.call(version_cmd)
except OSError as exc:
if ('No such file or directory' in str(exc)):
if os.path.isabs(tor_cmd):
exc = ("Unable to check tor's version. '%s' doesn't exist." % tor_cmd)
else:
exc = ("Unable to run '%s'. Mabye tor isn't in your PATH?" % version_cmd)
raise IOError(exc)
if version_output:
last_line = version_output[(-1)]
if (last_line.startswith('Tor version ') and last_line.endswith('.')):
try:
version_str = last_line[12:(-1)]
VERSION_CACHE[tor_cmd] = Version(version_str)
except ValueError as exc:
raise IOError(exc)
else:
raise IOError(("Unexpected response from '%s': %s" % (version_cmd, last_line)))
else:
raise IOError(("'%s' didn't have any output" % version_cmd))
return VERSION_CACHE[tor_cmd]
| [
"def",
"get_system_tor_version",
"(",
"tor_cmd",
"=",
"'tor'",
")",
":",
"if",
"(",
"tor_cmd",
"not",
"in",
"VERSION_CACHE",
")",
":",
"version_cmd",
"=",
"(",
"'%s --version'",
"%",
"tor_cmd",
")",
"try",
":",
"version_output",
"=",
"stem",
".",
"util",
"... | queries tor for its version . | train | false |
25,425 | def exampleAllHosts(vlan):
host = partial(VLANHost, vlan=vlan)
topo = SingleSwitchTopo(k=2)
net = Mininet(host=host, topo=topo)
net.start()
CLI(net)
net.stop()
| [
"def",
"exampleAllHosts",
"(",
"vlan",
")",
":",
"host",
"=",
"partial",
"(",
"VLANHost",
",",
"vlan",
"=",
"vlan",
")",
"topo",
"=",
"SingleSwitchTopo",
"(",
"k",
"=",
"2",
")",
"net",
"=",
"Mininet",
"(",
"host",
"=",
"host",
",",
"topo",
"=",
"t... | simple example of how vlanhost can be used in a script . | train | false |
25,427 | def safe_unicode(e):
try:
return unicode_type(e)
except UnicodeError:
pass
try:
return str_to_unicode(str(e))
except UnicodeError:
pass
try:
return str_to_unicode(repr(e))
except UnicodeError:
pass
return u'Unrecoverably corrupt evalue'
| [
"def",
"safe_unicode",
"(",
"e",
")",
":",
"try",
":",
"return",
"unicode_type",
"(",
"e",
")",
"except",
"UnicodeError",
":",
"pass",
"try",
":",
"return",
"str_to_unicode",
"(",
"str",
"(",
"e",
")",
")",
"except",
"UnicodeError",
":",
"pass",
"try",
... | unicode(e) with various fallbacks . | train | false |
25,428 | def quota_get_all(context, project_id):
return IMPL.quota_get_all(context, project_id)
| [
"def",
"quota_get_all",
"(",
"context",
",",
"project_id",
")",
":",
"return",
"IMPL",
".",
"quota_get_all",
"(",
"context",
",",
"project_id",
")"
] | retrieve all user quotas associated with a given project . | train | false |
25,430 | def _sigma(values):
return math.sqrt(_variance(values))
| [
"def",
"_sigma",
"(",
"values",
")",
":",
"return",
"math",
".",
"sqrt",
"(",
"_variance",
"(",
"values",
")",
")"
] | calculate the sigma for a list of integers . | train | false |
25,432 | def test_fake_parentheses():
src = dedent("\n def x():\n a = (')'\n if 1 else 2)\n def y():\n pass\n def z():\n pass\n ")
check_fp(src, 3, 2, 1)
| [
"def",
"test_fake_parentheses",
"(",
")",
":",
"src",
"=",
"dedent",
"(",
"\"\\n def x():\\n a = (')'\\n if 1 else 2)\\n def y():\\n pass\\n def z():\\n pass\\n \"",
")",
"check_fp",
"(",
"src",
",",
"3",
",",
"2",
",",
"1",
... | the fast parser splitting counts parentheses . | train | false |
25,434 | def enterprise_enabled():
return ('enterprise' in settings.INSTALLED_APPS)
| [
"def",
"enterprise_enabled",
"(",
")",
":",
"return",
"(",
"'enterprise'",
"in",
"settings",
".",
"INSTALLED_APPS",
")"
] | determines whether the enterprise app is installed . | train | false |
25,435 | def coffeescript_files():
dirs = ' '.join(((Env.REPO_ROOT / coffee_dir) for coffee_dir in COFFEE_DIRS))
return cmd('find', dirs, '-type f', '-name "*.coffee"')
| [
"def",
"coffeescript_files",
"(",
")",
":",
"dirs",
"=",
"' '",
".",
"join",
"(",
"(",
"(",
"Env",
".",
"REPO_ROOT",
"/",
"coffee_dir",
")",
"for",
"coffee_dir",
"in",
"COFFEE_DIRS",
")",
")",
"return",
"cmd",
"(",
"'find'",
",",
"dirs",
",",
"'-type f... | return find command for paths containing coffee files . | train | false |
25,437 | def get_region(region_name, **kw_params):
for region in regions(**kw_params):
if (region.name == region_name):
return region
return None
| [
"def",
"get_region",
"(",
"region_name",
",",
"**",
"kw_params",
")",
":",
"for",
"region",
"in",
"regions",
"(",
"**",
"kw_params",
")",
":",
"if",
"(",
"region",
".",
"name",
"==",
"region_name",
")",
":",
"return",
"region",
"return",
"None"
] | get the region for the current request lifecycle . | train | true |
25,438 | def get_using_python_pkgname():
path = get_using_python_path()
if path.startswith(PATH_PYTHONS):
path = path.replace(PATH_PYTHONS, '').strip(os.sep)
(pkgname, rest) = path.split(os.sep, 1)
return pkgname
if path.startswith(PATH_VENVS):
path = path.replace(PATH_VENVS, '').strip(os.sep)
(pkgname, rest) = path.split(os.sep, 1)
return pkgname
return None
| [
"def",
"get_using_python_pkgname",
"(",
")",
":",
"path",
"=",
"get_using_python_path",
"(",
")",
"if",
"path",
".",
"startswith",
"(",
"PATH_PYTHONS",
")",
":",
"path",
"=",
"path",
".",
"replace",
"(",
"PATH_PYTHONS",
",",
"''",
")",
".",
"strip",
"(",
... | return: python-<version> or none . | train | false |
25,439 | def leave_room(room):
socketio = flask.current_app.extensions['socketio']
socketio.server.leave_room(flask.request.sid, room, namespace=flask.request.namespace)
| [
"def",
"leave_room",
"(",
"room",
")",
":",
"socketio",
"=",
"flask",
".",
"current_app",
".",
"extensions",
"[",
"'socketio'",
"]",
"socketio",
".",
"server",
".",
"leave_room",
"(",
"flask",
".",
"request",
".",
"sid",
",",
"room",
",",
"namespace",
"=... | leave a room . | train | false |
25,440 | def extract_views_from_urlpatterns(urlpatterns, base=''):
views = []
for p in urlpatterns:
if hasattr(p, '_get_callback'):
try:
views.append((p._get_callback(), (base + p.regex.pattern)))
except ViewDoesNotExist:
continue
elif hasattr(p, '_get_url_patterns'):
try:
patterns = p.url_patterns
except ImportError:
continue
views.extend(extract_views_from_urlpatterns(patterns, (base + p.regex.pattern)))
else:
raise TypeError((_('%s does not appear to be a urlpattern object') % p))
return views
| [
"def",
"extract_views_from_urlpatterns",
"(",
"urlpatterns",
",",
"base",
"=",
"''",
")",
":",
"views",
"=",
"[",
"]",
"for",
"p",
"in",
"urlpatterns",
":",
"if",
"hasattr",
"(",
"p",
",",
"'_get_callback'",
")",
":",
"try",
":",
"views",
".",
"append",
... | return a list of views from a list of urlpatterns . | train | false |
25,443 | def get_avatar_image(request, user, size):
cache_key = u'-'.join((u'avatar-img', user.username, str(size)))
try:
cache = caches[u'avatar']
except InvalidCacheBackendError:
cache = caches[u'default']
image = cache.get(cache_key)
if (image is None):
try:
image = download_avatar_image(user, size)
cache.set(cache_key, image)
except IOError as error:
report_error(error, sys.exc_info(), request, extra_data={u'avatar': user.username}, level=u'debug')
LOGGER.error(u'Failed to fetch avatar for %s: %s', user.username, str(error))
return get_fallback_avatar(size)
return image
| [
"def",
"get_avatar_image",
"(",
"request",
",",
"user",
",",
"size",
")",
":",
"cache_key",
"=",
"u'-'",
".",
"join",
"(",
"(",
"u'avatar-img'",
",",
"user",
".",
"username",
",",
"str",
"(",
"size",
")",
")",
")",
"try",
":",
"cache",
"=",
"caches",... | returns avatar image from cache or downloads it . | train | false |
25,444 | def format_national_number_with_carrier_code(numobj, carrier_code):
country_code = numobj.country_code
nsn = national_significant_number(numobj)
if (not _has_valid_country_calling_code(country_code)):
return nsn
region_code = region_code_for_country_code(country_code)
metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_code, region_code)
formatted_number = _format_nsn(nsn, metadata, PhoneNumberFormat.NATIONAL, carrier_code)
formatted_number = _maybe_append_formatted_extension(numobj, metadata, PhoneNumberFormat.NATIONAL, formatted_number)
formatted_number = _prefix_number_with_country_calling_code(country_code, PhoneNumberFormat.NATIONAL, formatted_number)
return formatted_number
| [
"def",
"format_national_number_with_carrier_code",
"(",
"numobj",
",",
"carrier_code",
")",
":",
"country_code",
"=",
"numobj",
".",
"country_code",
"nsn",
"=",
"national_significant_number",
"(",
"numobj",
")",
"if",
"(",
"not",
"_has_valid_country_calling_code",
"(",
... | format a number in national format for dialing using the specified carrier . | train | true |
25,445 | def last_blank(src):
if (not src):
return False
ll = src.splitlines()[(-1)]
return ((ll == '') or ll.isspace())
| [
"def",
"last_blank",
"(",
"src",
")",
":",
"if",
"(",
"not",
"src",
")",
":",
"return",
"False",
"ll",
"=",
"src",
".",
"splitlines",
"(",
")",
"[",
"(",
"-",
"1",
")",
"]",
"return",
"(",
"(",
"ll",
"==",
"''",
")",
"or",
"ll",
".",
"isspace... | determine if the input source ends in a blank . | train | true |
25,446 | def run_test_server():
httpd = BaseHTTPServer.HTTPServer(('127.0.0.1', 0), Handler)
thread = threading.Thread(target=httpd.handle_request)
thread.daemon = True
thread.start()
def finish():
print ('Closing thread ' + str(thread))
thread.join(10.0)
assert_false(thread.isAlive())
return (httpd, finish)
| [
"def",
"run_test_server",
"(",
")",
":",
"httpd",
"=",
"BaseHTTPServer",
".",
"HTTPServer",
"(",
"(",
"'127.0.0.1'",
",",
"0",
")",
",",
"Handler",
")",
"thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"httpd",
".",
"handle_request",
")",
"... | returns the server . | train | false |
25,447 | def remove_protocol_and_user_from_clone_url(repository_clone_url):
if (repository_clone_url.find('@') > 0):
items = repository_clone_url.split('@')
tmp_url = items[1]
elif (repository_clone_url.find('//') > 0):
items = repository_clone_url.split('//')
tmp_url = items[1]
else:
tmp_url = repository_clone_url
return tmp_url.rstrip('/')
| [
"def",
"remove_protocol_and_user_from_clone_url",
"(",
"repository_clone_url",
")",
":",
"if",
"(",
"repository_clone_url",
".",
"find",
"(",
"'@'",
")",
">",
"0",
")",
":",
"items",
"=",
"repository_clone_url",
".",
"split",
"(",
"'@'",
")",
"tmp_url",
"=",
"... | return a url that can be used to clone a repository . | train | false |
25,448 | def build_evolutions():
file = open('data/v1/evolutions.csv', 'rb')
rdr = csv.reader(file, delimiter=',')
method = [' ', 'level_up', 'trade', 'stone', 'other']
for row in rdr:
if (row[0] != 'id'):
frm = Pokemon.objects.filter(pkdx_id=(int(row[1]) - 1))
if (not frm.exists()):
frm = Pokemon.objects.filter(pkdx_id=1)[0]
else:
frm = frm[0]
to = Pokemon.objects.filter(pkdx_id=int(row[1]))
if (not to.exists()):
to = Pokemon.objects.filter(pkdx_id=2)[0]
else:
to = to[0]
if (method[int(row[2])] == 'level_up'):
e = Evolution(frm=frm, to=to, method=method[int(row[2])], level=(row[4] if (row[4] != '') else 0))
e.save()
print ('created link %s' % e.__unicode__())
| [
"def",
"build_evolutions",
"(",
")",
":",
"file",
"=",
"open",
"(",
"'data/v1/evolutions.csv'",
",",
"'rb'",
")",
"rdr",
"=",
"csv",
".",
"reader",
"(",
"file",
",",
"delimiter",
"=",
"','",
")",
"method",
"=",
"[",
"' '",
",",
"'level_up'",
",",
"'tra... | build all the evolution links . | train | false |
25,449 | def get_boot_arch():
ret = salt.utils.mac_utils.execute_return_result('systemsetup -getkernelbootarchitecturesetting')
arch = salt.utils.mac_utils.parse_return(ret)
if ('default' in arch):
return 'default'
elif ('i386' in arch):
return 'i386'
elif ('x86_64' in arch):
return 'x86_64'
return 'unknown'
| [
"def",
"get_boot_arch",
"(",
")",
":",
"ret",
"=",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_result",
"(",
"'systemsetup -getkernelbootarchitecturesetting'",
")",
"arch",
"=",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"parse_return",
"(",
"... | get the kernel architecture setting from com . | train | false |
25,450 | def swap_resources_into_scope(expr, scope):
resources = expr._resources()
symbol_dict = dict(((t, symbol(t._name, t.dshape)) for t in resources))
resources = dict(((symbol_dict[k], v) for (k, v) in resources.items()))
other_scope = dict(((k, v) for (k, v) in scope.items() if (k not in symbol_dict)))
new_scope = toolz.merge(resources, other_scope)
expr = expr._subs(symbol_dict)
return (expr, new_scope)
| [
"def",
"swap_resources_into_scope",
"(",
"expr",
",",
"scope",
")",
":",
"resources",
"=",
"expr",
".",
"_resources",
"(",
")",
"symbol_dict",
"=",
"dict",
"(",
"(",
"(",
"t",
",",
"symbol",
"(",
"t",
".",
"_name",
",",
"t",
".",
"dshape",
")",
")",
... | translate interactive expressions into normal abstract expressions interactive blaze expressions link to data on their leaves . | train | false |
25,451 | def save_new_exploration_from_yaml_and_assets(committer_id, yaml_content, exploration_id, assets_list):
if (assets_list is None):
assets_list = []
yaml_dict = utils.dict_from_yaml(yaml_content)
if ('schema_version' not in yaml_dict):
raise Exception('Invalid YAML file: missing schema version')
exp_schema_version = yaml_dict['schema_version']
if (exp_schema_version <= exp_domain.Exploration.LAST_UNTITLED_SCHEMA_VERSION):
exploration = exp_domain.Exploration.from_untitled_yaml(exploration_id, feconf.DEFAULT_EXPLORATION_TITLE, feconf.DEFAULT_EXPLORATION_CATEGORY, yaml_content)
else:
exploration = exp_domain.Exploration.from_yaml(exploration_id, yaml_content)
commit_message = ("New exploration created from YAML file with title '%s'." % exploration.title)
_create_exploration(committer_id, exploration, commit_message, [{'cmd': CMD_CREATE_NEW, 'title': exploration.title, 'category': exploration.category}])
for (asset_filename, asset_content) in assets_list:
fs = fs_domain.AbstractFileSystem(fs_domain.ExplorationFileSystem(exploration_id))
fs.commit(committer_id, asset_filename, asset_content)
| [
"def",
"save_new_exploration_from_yaml_and_assets",
"(",
"committer_id",
",",
"yaml_content",
",",
"exploration_id",
",",
"assets_list",
")",
":",
"if",
"(",
"assets_list",
"is",
"None",
")",
":",
"assets_list",
"=",
"[",
"]",
"yaml_dict",
"=",
"utils",
".",
"di... | note that the default title and category will be used if the yaml schema version is less than exp_domain . | train | false |
25,452 | def number_of_parameter_banks(device, device_dict=DEVICE_DICT):
if (device != None):
if (device.class_name in device_dict.keys()):
device_bank = device_dict[device.class_name]
return len(device_bank)
else:
if (device.class_name in MAX_DEVICES):
try:
banks = device.get_bank_count()
except:
banks = 0
if (banks != 0):
return banks
param_count = len(device.parameters[1:])
return ((param_count / 8) + (1 if (param_count % 8) else 0))
return 0
| [
"def",
"number_of_parameter_banks",
"(",
"device",
",",
"device_dict",
"=",
"DEVICE_DICT",
")",
":",
"if",
"(",
"device",
"!=",
"None",
")",
":",
"if",
"(",
"device",
".",
"class_name",
"in",
"device_dict",
".",
"keys",
"(",
")",
")",
":",
"device_bank",
... | determine the amount of parameter banks the given device has . | train | false |
25,453 | def extract_reads_from_interleaved(input_fp, forward_id, reverse_id, output_dir):
forward_fp = join(output_dir, 'forward_reads.fastq')
reverse_fp = join(output_dir, 'reverse_reads.fastq')
ffp = open(forward_fp, 'w')
rfp = open(reverse_fp, 'w')
for (label, seq, qual) in parse_fastq(qiime_open(input_fp), strict=False, enforce_qual_range=False):
fastq_string = format_fastq_record(label, seq, qual)
if (forward_id in label):
ffp.write(fastq_string)
elif ((reverse_id in label) and (forward_id not in label)):
rfp.write(fastq_string)
else:
ffp.close()
rfp.close()
raise ValueError(("One of the input sequences doesn't have either identifier or it has both.\nLabel: %s\nForward: %s\n Reverse: %s" % (label, forward_id, reverse_id)))
ffp.close()
rfp.close()
| [
"def",
"extract_reads_from_interleaved",
"(",
"input_fp",
",",
"forward_id",
",",
"reverse_id",
",",
"output_dir",
")",
":",
"forward_fp",
"=",
"join",
"(",
"output_dir",
",",
"'forward_reads.fastq'",
")",
"reverse_fp",
"=",
"join",
"(",
"output_dir",
",",
"'rever... | parses a single fastq file and creates two new files: forward and reverse . | train | false |
25,454 | def getNewRepository():
return ExportRepository()
| [
"def",
"getNewRepository",
"(",
")",
":",
"return",
"ExportRepository",
"(",
")"
] | get new repository . | train | false |
25,456 | def _resource_endpoint(object_uri):
obj_parts = object_uri.split('/')
plural_endpoint = ((len(obj_parts) % 2) == 0)
if plural_endpoint:
obj_parts = obj_parts[:(-1)]
if (len(obj_parts) <= 2):
return ('', False)
resource_name = obj_parts[(-2)]
resource_name = resource_name.rstrip('s')
return (resource_name, plural_endpoint)
| [
"def",
"_resource_endpoint",
"(",
"object_uri",
")",
":",
"obj_parts",
"=",
"object_uri",
".",
"split",
"(",
"'/'",
")",
"plural_endpoint",
"=",
"(",
"(",
"len",
"(",
"obj_parts",
")",
"%",
"2",
")",
"==",
"0",
")",
"if",
"plural_endpoint",
":",
"obj_par... | determine the resource name and whether it is the plural endpoint from the specified object_uri . | train | false |
25,457 | def createRC4(key, IV, implList=None):
if (implList == None):
implList = ['cryptlib', 'openssl', 'pycrypto', 'python']
if (len(IV) != 0):
raise AssertionError()
for impl in implList:
if ((impl == 'cryptlib') and cryptomath.cryptlibpyLoaded):
return Cryptlib_RC4.new(key)
elif ((impl == 'openssl') and cryptomath.m2cryptoLoaded):
return OpenSSL_RC4.new(key)
elif ((impl == 'pycrypto') and cryptomath.pycryptoLoaded):
return PyCrypto_RC4.new(key)
elif (impl == 'python'):
return Python_RC4.new(key)
raise NotImplementedError()
| [
"def",
"createRC4",
"(",
"key",
",",
"IV",
",",
"implList",
"=",
"None",
")",
":",
"if",
"(",
"implList",
"==",
"None",
")",
":",
"implList",
"=",
"[",
"'cryptlib'",
",",
"'openssl'",
",",
"'pycrypto'",
",",
"'python'",
"]",
"if",
"(",
"len",
"(",
... | create a new rc4 object . | train | false |
25,458 | def _create_eax_cipher(factory, **kwargs):
try:
key = kwargs.pop('key')
nonce = kwargs.pop('nonce', None)
if (nonce is None):
nonce = get_random_bytes(16)
mac_len = kwargs.pop('mac_len', factory.block_size)
except KeyError as e:
raise TypeError(('Missing parameter: ' + str(e)))
return EaxMode(factory, key, nonce, mac_len, kwargs)
| [
"def",
"_create_eax_cipher",
"(",
"factory",
",",
"**",
"kwargs",
")",
":",
"try",
":",
"key",
"=",
"kwargs",
".",
"pop",
"(",
"'key'",
")",
"nonce",
"=",
"kwargs",
".",
"pop",
"(",
"'nonce'",
",",
"None",
")",
"if",
"(",
"nonce",
"is",
"None",
")"... | create a new block cipher . | train | false |
25,459 | def xmodule_js_files(request):
urls = get_xmodule_urls()
return HttpResponse(json.dumps(urls), content_type='application/json')
| [
"def",
"xmodule_js_files",
"(",
"request",
")",
":",
"urls",
"=",
"get_xmodule_urls",
"(",
")",
"return",
"HttpResponse",
"(",
"json",
".",
"dumps",
"(",
"urls",
")",
",",
"content_type",
"=",
"'application/json'",
")"
] | view function that returns xmodule urls as a json list; meant to be used as an api . | train | false |
25,460 | def p_declaration_specifiers_4(t):
pass
| [
"def",
"p_declaration_specifiers_4",
"(",
"t",
")",
":",
"pass"
] | declaration_specifiers : storage_class_specifier . | train | false |
25,461 | def version_details(client, module):
lambda_facts = dict()
function_name = module.params.get('function_name')
if function_name:
params = dict()
if module.params.get('max_items'):
params['MaxItems'] = module.params.get('max_items')
if module.params.get('next_marker'):
params['Marker'] = module.params.get('next_marker')
try:
lambda_facts.update(versions=client.list_versions_by_function(FunctionName=function_name, **params)['Versions'])
except ClientError as e:
if (e.response['Error']['Code'] == 'ResourceNotFoundException'):
lambda_facts.update(versions=[])
else:
module.fail_json(msg='Unable to get {0} versions, error: {1}'.format(function_name, e))
else:
module.fail_json(msg='Parameter function_name required for query=versions.')
return {function_name: camel_dict_to_snake_dict(lambda_facts)}
| [
"def",
"version_details",
"(",
"client",
",",
"module",
")",
":",
"lambda_facts",
"=",
"dict",
"(",
")",
"function_name",
"=",
"module",
".",
"params",
".",
"get",
"(",
"'function_name'",
")",
"if",
"function_name",
":",
"params",
"=",
"dict",
"(",
")",
... | returns all lambda function versions . | train | false |
25,462 | def order_column(column, order):
if (not order):
return column
elif order.lower().startswith('asc'):
return column.asc()
elif order.lower().startswith('desc'):
return column.desc()
else:
raise (ArgumentError('Unknown order %s for column %s') % (order, column))
| [
"def",
"order_column",
"(",
"column",
",",
"order",
")",
":",
"if",
"(",
"not",
"order",
")",
":",
"return",
"column",
"elif",
"order",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"'asc'",
")",
":",
"return",
"column",
".",
"asc",
"(",
")",
"el... | orders a column according to order specified as string . | train | false |
25,464 | def create_cgsnapshot(ctxt, consistencygroup_id, name='test_cgsnapshot', description='this is a test cgsnapshot', status='creating', recursive_create_if_needed=True, return_vo=True, **kwargs):
values = {'user_id': (ctxt.user_id or fake.USER_ID), 'project_id': (ctxt.project_id or fake.PROJECT_ID), 'status': status, 'name': name, 'description': description, 'consistencygroup_id': consistencygroup_id}
values.update(kwargs)
if (recursive_create_if_needed and consistencygroup_id):
create_cg = False
try:
objects.ConsistencyGroup.get_by_id(ctxt, consistencygroup_id)
create_vol = (not db.volume_get_all_by_group(ctxt, consistencygroup_id))
except exception.ConsistencyGroupNotFound:
create_cg = True
create_vol = True
if create_cg:
create_consistencygroup(ctxt, id=consistencygroup_id)
if create_vol:
create_volume(ctxt, consistencygroup_id=consistencygroup_id)
cgsnap = db.cgsnapshot_create(ctxt, values)
if (not return_vo):
return cgsnap
return objects.CGSnapshot.get_by_id(ctxt, cgsnap.id)
| [
"def",
"create_cgsnapshot",
"(",
"ctxt",
",",
"consistencygroup_id",
",",
"name",
"=",
"'test_cgsnapshot'",
",",
"description",
"=",
"'this is a test cgsnapshot'",
",",
"status",
"=",
"'creating'",
",",
"recursive_create_if_needed",
"=",
"True",
",",
"return_vo",
"=",... | create a cgsnapshot object in the db . | train | false |
25,465 | def construct(**kwargs):
point_x = kwargs.pop('point_x', None)
point_y = kwargs.pop('point_y', None)
if ('point' in kwargs):
raise TypeError('Unknown keyword: point')
if (None not in (point_x, point_y)):
kwargs['point'] = EccPoint(point_x, point_y)
eq1 = pow(Integer(point_y), 2, _curve.p)
x = Integer(point_x)
eq2 = pow(x, 3, _curve.p)
x *= (-3)
eq2 += x
eq2 += _curve.b
eq2 %= _curve.p
if (eq1 != eq2):
raise ValueError('The point is not on the curve')
d = kwargs.get('d', None)
if ((d is not None) and ('point' in kwargs)):
pub_key = (_curve.G * d)
if ((pub_key.x != point_x) or (pub_key.y != point_y)):
raise ValueError('Private and public ECC keys do not match')
return EccKey(**kwargs)
| [
"def",
"construct",
"(",
"**",
"kwargs",
")",
":",
"point_x",
"=",
"kwargs",
".",
"pop",
"(",
"'point_x'",
",",
"None",
")",
"point_y",
"=",
"kwargs",
".",
"pop",
"(",
"'point_y'",
",",
"None",
")",
"if",
"(",
"'point'",
"in",
"kwargs",
")",
":",
"... | construct(tuple:|):dsaobj construct a dsa object from a 4- or 5-tuple of numbers . | train | false |
25,466 | def walk_excl(path, **kwargs):
for (dirpath, dirnames, filenames) in os.walk(path, **kwargs):
dirnames[:] = [dn for dn in dirnames if (not is_excluded_filename(dn))]
(yield (dirpath, dirnames, filenames))
| [
"def",
"walk_excl",
"(",
"path",
",",
"**",
"kwargs",
")",
":",
"for",
"(",
"dirpath",
",",
"dirnames",
",",
"filenames",
")",
"in",
"os",
".",
"walk",
"(",
"path",
",",
"**",
"kwargs",
")",
":",
"dirnames",
"[",
":",
"]",
"=",
"[",
"dn",
"for",
... | do os . | train | false |
25,467 | def libvlc_vlm_add_vod(p_instance, psz_name, psz_input, i_options, ppsz_options, b_enabled, psz_mux):
f = (_Cfunctions.get('libvlc_vlm_add_vod', None) or _Cfunction('libvlc_vlm_add_vod', ((1,), (1,), (1,), (1,), (1,), (1,), (1,)), None, ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int, ListPOINTER(ctypes.c_char_p), ctypes.c_int, ctypes.c_char_p))
return f(p_instance, psz_name, psz_input, i_options, ppsz_options, b_enabled, psz_mux)
| [
"def",
"libvlc_vlm_add_vod",
"(",
"p_instance",
",",
"psz_name",
",",
"psz_input",
",",
"i_options",
",",
"ppsz_options",
",",
"b_enabled",
",",
"psz_mux",
")",
":",
"f",
"=",
"(",
"_Cfunctions",
".",
"get",
"(",
"'libvlc_vlm_add_vod'",
",",
"None",
")",
"or... | add a vod . | train | true |
25,468 | def get_internal_wsgi_application():
from django.conf import settings
app_path = getattr(settings, u'WSGI_APPLICATION')
if (app_path is None):
return get_wsgi_application()
return import_by_path(app_path, error_prefix=(u"WSGI application '%s' could not be loaded; " % app_path))
| [
"def",
"get_internal_wsgi_application",
"(",
")",
":",
"from",
"django",
".",
"conf",
"import",
"settings",
"app_path",
"=",
"getattr",
"(",
"settings",
",",
"u'WSGI_APPLICATION'",
")",
"if",
"(",
"app_path",
"is",
"None",
")",
":",
"return",
"get_wsgi_applicati... | loads and returns the wsgi application as configured by the user in settings . | train | false |
25,469 | def explicit_line_join(logical_line, tokens):
prev_start = prev_end = parens = 0
backslash = None
for (token_type, text, start, end, line) in tokens:
if ((start[0] != prev_start) and parens and backslash):
(yield (backslash, 'E502 the backslash is redundant between brackets'))
if (end[0] != prev_end):
if line.rstrip('\r\n').endswith('\\'):
backslash = (end[0], (len(line.splitlines()[(-1)]) - 1))
else:
backslash = None
prev_start = prev_end = end[0]
else:
prev_start = start[0]
if (token_type == tokenize.OP):
if (text in '([{'):
parens += 1
elif (text in ')]}'):
parens -= 1
| [
"def",
"explicit_line_join",
"(",
"logical_line",
",",
"tokens",
")",
":",
"prev_start",
"=",
"prev_end",
"=",
"parens",
"=",
"0",
"backslash",
"=",
"None",
"for",
"(",
"token_type",
",",
"text",
",",
"start",
",",
"end",
",",
"line",
")",
"in",
"tokens"... | avoid explicit line join between brackets . | train | true |
25,470 | def _variable_with_weight_decay(name, shape, stddev, wd):
var = _variable_on_cpu(name, shape, tf.truncated_normal_initializer(stddev=stddev))
if (wd is not None):
weight_decay = tf.mul(tf.nn.l2_loss(var), wd, name='weight_loss')
tf.add_to_collection('losses', weight_decay)
return var
| [
"def",
"_variable_with_weight_decay",
"(",
"name",
",",
"shape",
",",
"stddev",
",",
"wd",
")",
":",
"var",
"=",
"_variable_on_cpu",
"(",
"name",
",",
"shape",
",",
"tf",
".",
"truncated_normal_initializer",
"(",
"stddev",
"=",
"stddev",
")",
")",
"if",
"(... | helper to create an initialized variable with weight decay . | train | false |
25,471 | def get_redirect_url_for_global_staff(course_key, _next):
redirect_url = '{url}?next={redirect}'.format(url=reverse('enroll_staff', args=[unicode(course_key)]), redirect=_next)
return redirect_url
| [
"def",
"get_redirect_url_for_global_staff",
"(",
"course_key",
",",
"_next",
")",
":",
"redirect_url",
"=",
"'{url}?next={redirect}'",
".",
"format",
"(",
"url",
"=",
"reverse",
"(",
"'enroll_staff'",
",",
"args",
"=",
"[",
"unicode",
"(",
"course_key",
")",
"]"... | returns the redirect url for staff enrollment args: course_key: course key string _next: redirect url of course component . | train | false |
25,472 | @require_POST
@login_required
def lock_question(request, question_id):
question = get_object_or_404(Question, pk=question_id)
if (not question.allows_lock(request.user)):
raise PermissionDenied
question.is_locked = (not question.is_locked)
log.info(('User %s set is_locked=%s on question with id=%s ' % (request.user, question.is_locked, question.id)))
question.save()
if question.is_locked:
statsd.incr('questions.lock')
else:
statsd.incr('questions.unlock')
return HttpResponseRedirect(question.get_absolute_url())
| [
"@",
"require_POST",
"@",
"login_required",
"def",
"lock_question",
"(",
"request",
",",
"question_id",
")",
":",
"question",
"=",
"get_object_or_404",
"(",
"Question",
",",
"pk",
"=",
"question_id",
")",
"if",
"(",
"not",
"question",
".",
"allows_lock",
"(",
... | lock or unlock a question . | train | false |
25,473 | def set_post_mortem():
if IS_IPYKERNEL:
from IPython.core.getipython import get_ipython
def ipython_post_mortem_debug(shell, etype, evalue, tb, tb_offset=None):
post_mortem_excepthook(etype, evalue, tb)
ipython_shell = get_ipython()
ipython_shell.set_custom_exc((Exception,), ipython_post_mortem_debug)
else:
sys.excepthook = post_mortem_excepthook
| [
"def",
"set_post_mortem",
"(",
")",
":",
"if",
"IS_IPYKERNEL",
":",
"from",
"IPython",
".",
"core",
".",
"getipython",
"import",
"get_ipython",
"def",
"ipython_post_mortem_debug",
"(",
"shell",
",",
"etype",
",",
"evalue",
",",
"tb",
",",
"tb_offset",
"=",
"... | enable the post mortem debugging excepthook . | train | false |
25,476 | @register(u'yank')
def yank(event):
event.current_buffer.paste_clipboard_data(event.cli.clipboard.get_data(), count=event.arg, paste_mode=PasteMode.EMACS)
| [
"@",
"register",
"(",
"u'yank'",
")",
"def",
"yank",
"(",
"event",
")",
":",
"event",
".",
"current_buffer",
".",
"paste_clipboard_data",
"(",
"event",
".",
"cli",
".",
"clipboard",
".",
"get_data",
"(",
")",
",",
"count",
"=",
"event",
".",
"arg",
","... | paste before cursor . | train | true |
25,477 | def test_x_squared_norms_init_centroids():
from sklearn.cluster.k_means_ import _init_centroids
X_norms = np.sum((X ** 2), axis=1)
precompute = _init_centroids(X, 3, 'k-means++', random_state=0, x_squared_norms=X_norms)
assert_array_equal(precompute, _init_centroids(X, 3, 'k-means++', random_state=0))
| [
"def",
"test_x_squared_norms_init_centroids",
"(",
")",
":",
"from",
"sklearn",
".",
"cluster",
".",
"k_means_",
"import",
"_init_centroids",
"X_norms",
"=",
"np",
".",
"sum",
"(",
"(",
"X",
"**",
"2",
")",
",",
"axis",
"=",
"1",
")",
"precompute",
"=",
... | test that x_squared_norms can be none in _init_centroids . | train | false |
25,478 | def getReplaced(exportText):
replaceText = settings.getFileInAlterationsOrGivenDirectory(os.path.dirname(__file__), 'Replace.csv')
if (replaceText == ''):
return exportText
lines = archive.getTextLines(replaceText)
for line in lines:
splitLine = line.replace('\\n', ' DCTB ').split(' DCTB ')
if (len(splitLine) > 1):
exportText = exportText.replace(splitLine[0], '\n'.join(splitLine[1:]))
return exportText
| [
"def",
"getReplaced",
"(",
"exportText",
")",
":",
"replaceText",
"=",
"settings",
".",
"getFileInAlterationsOrGivenDirectory",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'Replace.csv'",
")",
"if",
"(",
"replaceText",
"==",
"''",
")",
... | get text with strings replaced according to replace . | train | false |
25,479 | def django_to_jinja(template_name, context, **kw):
context_instance = kw.pop('context_instance')
source = loader.render_to_string(template_name, context, context_instance)
request = context_instance['request']
return jingo.render(request, jingo.env.from_string(source))
| [
"def",
"django_to_jinja",
"(",
"template_name",
",",
"context",
",",
"**",
"kw",
")",
":",
"context_instance",
"=",
"kw",
".",
"pop",
"(",
"'context_instance'",
")",
"source",
"=",
"loader",
".",
"render_to_string",
"(",
"template_name",
",",
"context",
",",
... | we monkeypatch django admins render_to_response to work in our jinja environment . | train | false |
25,483 | @pytest.fixture
def member2_with_email():
user = _require_user('member2_with_email', 'Member2 with email')
user.email = 'member2_with_email@this.test'
user.save()
return user
| [
"@",
"pytest",
".",
"fixture",
"def",
"member2_with_email",
"(",
")",
":",
"user",
"=",
"_require_user",
"(",
"'member2_with_email'",
",",
"'Member2 with email'",
")",
"user",
".",
"email",
"=",
"'member2_with_email@this.test'",
"user",
".",
"save",
"(",
")",
"r... | require a member2 user . | train | false |
25,485 | def gamma(x):
return exp(gammaln(x))
| [
"def",
"gamma",
"(",
"x",
")",
":",
"return",
"exp",
"(",
"gammaln",
"(",
"x",
")",
")"
] | returns the gamma function at x . | train | false |
25,486 | def add_team_count(topics, course_id):
topic_ids = [topic['id'] for topic in topics]
teams_per_topic = CourseTeam.objects.filter(course_id=course_id, topic_id__in=topic_ids).values('topic_id').annotate(team_count=Count('topic_id'))
topics_to_team_count = {d['topic_id']: d['team_count'] for d in teams_per_topic}
for topic in topics:
topic['team_count'] = topics_to_team_count.get(topic['id'], 0)
| [
"def",
"add_team_count",
"(",
"topics",
",",
"course_id",
")",
":",
"topic_ids",
"=",
"[",
"topic",
"[",
"'id'",
"]",
"for",
"topic",
"in",
"topics",
"]",
"teams_per_topic",
"=",
"CourseTeam",
".",
"objects",
".",
"filter",
"(",
"course_id",
"=",
"course_i... | helper method to add team_count for a list of topics . | train | false |
25,487 | def remove_team(name, profile='github'):
team_info = get_team(name, profile=profile)
if (not team_info):
log.error('Team {0} to be removed does not exist.'.format(name))
return False
try:
client = _get_client(profile)
organization = client.get_organization(_get_config_value(profile, 'org_name'))
team = organization.get_team(team_info['id'])
team.delete()
return (list_teams(ignore_cache=True, profile=profile).get(name) is None)
except github.GithubException as e:
log.exception('Error deleting a team: {0}'.format(str(e)))
return False
| [
"def",
"remove_team",
"(",
"name",
",",
"profile",
"=",
"'github'",
")",
":",
"team_info",
"=",
"get_team",
"(",
"name",
",",
"profile",
"=",
"profile",
")",
"if",
"(",
"not",
"team_info",
")",
":",
"log",
".",
"error",
"(",
"'Team {0} to be removed does n... | remove a github team . | train | true |
25,488 | def _RetainHorizontalSpacing(uwline):
for tok in uwline.tokens:
tok.RetainHorizontalSpacing(uwline.first.column, uwline.depth)
| [
"def",
"_RetainHorizontalSpacing",
"(",
"uwline",
")",
":",
"for",
"tok",
"in",
"uwline",
".",
"tokens",
":",
"tok",
".",
"RetainHorizontalSpacing",
"(",
"uwline",
".",
"first",
".",
"column",
",",
"uwline",
".",
"depth",
")"
] | retain all horizontal spacing between tokens . | train | false |
25,489 | def sync_overlay(name):
layman = init_layman()
if (not layman.sync(name)):
messages = [str(item[1]) for item in layman.sync_results[2]]
raise ModuleError(messages)
| [
"def",
"sync_overlay",
"(",
"name",
")",
":",
"layman",
"=",
"init_layman",
"(",
")",
"if",
"(",
"not",
"layman",
".",
"sync",
"(",
"name",
")",
")",
":",
"messages",
"=",
"[",
"str",
"(",
"item",
"[",
"1",
"]",
")",
"for",
"item",
"in",
"layman"... | synchronizes the specified overlay repository . | train | false |
25,490 | def unread_message_count(request):
count = 0
if (hasattr(request, 'user') and request.user.is_authenticated()):
count = unread_count_for(request.user)
return {'unread_message_count': count}
| [
"def",
"unread_message_count",
"(",
"request",
")",
":",
"count",
"=",
"0",
"if",
"(",
"hasattr",
"(",
"request",
",",
"'user'",
")",
"and",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
")",
":",
"count",
"=",
"unread_count_for",
"(",
"requ... | adds the unread private messages count to the context . | train | false |
25,492 | @users.command('update')
@click.option('--username', '-u', help='The username of the user.')
@click.option('--email', '-e', type=EmailType(), help='The email address of the user.')
@click.option('--password', '-p', help='The password of the user.')
@click.option('--group', '-g', help='The group of the user.', type=click.Choice(['admin', 'super_mod', 'mod', 'member']))
def change_user(username, password, email, group):
user = save_user_prompt(username, password, email, group)
if (user is None):
raise FlaskBBCLIError('The user with username {} does not exist.'.format(username), fg='red')
click.secho('[+] User {} updated.'.format(user.username), fg='cyan')
| [
"@",
"users",
".",
"command",
"(",
"'update'",
")",
"@",
"click",
".",
"option",
"(",
"'--username'",
",",
"'-u'",
",",
"help",
"=",
"'The username of the user.'",
")",
"@",
"click",
".",
"option",
"(",
"'--email'",
",",
"'-e'",
",",
"type",
"=",
"EmailT... | updates an user . | train | false |
25,494 | def bubble_sort(collection):
length = len(collection)
for i in range((length - 1), (-1), (-1)):
for j in range(i):
if (collection[j] > collection[(j + 1)]):
(collection[j], collection[(j + 1)]) = (collection[(j + 1)], collection[j])
return collection
| [
"def",
"bubble_sort",
"(",
"collection",
")",
":",
"length",
"=",
"len",
"(",
"collection",
")",
"for",
"i",
"in",
"range",
"(",
"(",
"length",
"-",
"1",
")",
",",
"(",
"-",
"1",
")",
",",
"(",
"-",
"1",
")",
")",
":",
"for",
"j",
"in",
"rang... | pure implementation of bubble sort algorithm in python . | train | false |
25,495 | def show_hidden(str, show_all=False):
return (show_all or str.startswith('__') or (not str.startswith('_')))
| [
"def",
"show_hidden",
"(",
"str",
",",
"show_all",
"=",
"False",
")",
":",
"return",
"(",
"show_all",
"or",
"str",
".",
"startswith",
"(",
"'__'",
")",
"or",
"(",
"not",
"str",
".",
"startswith",
"(",
"'_'",
")",
")",
")"
] | return true for strings starting with single _ if show_all is true . | train | false |
25,496 | def clear_wivet():
clear_url = get_wivet_http('/offscanpages/remove-all-stats.php?sure=yes')
response = urllib2.urlopen(clear_url)
html = response.read()
assert ('Done!' in html), html
| [
"def",
"clear_wivet",
"(",
")",
":",
"clear_url",
"=",
"get_wivet_http",
"(",
"'/offscanpages/remove-all-stats.php?sure=yes'",
")",
"response",
"=",
"urllib2",
".",
"urlopen",
"(",
"clear_url",
")",
"html",
"=",
"response",
".",
"read",
"(",
")",
"assert",
"(",
... | utility function that will clear all the previous stats from my wivet instance . | train | false |
25,498 | def seq1(seq, custom_map=None, undef_code='X'):
if (custom_map is None):
custom_map = {'Ter': '*'}
onecode = dict(((k.upper(), v) for (k, v) in IUPACData.protein_letters_3to1_extended.items()))
onecode.update(((k.upper(), v) for (k, v) in custom_map.items()))
seqlist = [seq[(3 * i):(3 * (i + 1))] for i in range((len(seq) // 3))]
return ''.join((onecode.get(aa.upper(), undef_code) for aa in seqlist))
| [
"def",
"seq1",
"(",
"seq",
",",
"custom_map",
"=",
"None",
",",
"undef_code",
"=",
"'X'",
")",
":",
"if",
"(",
"custom_map",
"is",
"None",
")",
":",
"custom_map",
"=",
"{",
"'Ter'",
":",
"'*'",
"}",
"onecode",
"=",
"dict",
"(",
"(",
"(",
"k",
"."... | turns a three-letter code protein sequence into one with single letter codes . | train | false |
25,499 | def getGeometryOutputByLoopFunction(manipulationFunction, sideLoop, xmlElement):
sideLoop.rotate(xmlElement)
sideLoop.loop = euclidean.getLoopWithoutCloseSequentialPoints(sideLoop.close, sideLoop.loop)
return getUnpackedLoops(manipulationFunction(sideLoop.close, sideLoop.loop, '', sideLoop.sideLength, xmlElement))
| [
"def",
"getGeometryOutputByLoopFunction",
"(",
"manipulationFunction",
",",
"sideLoop",
",",
"xmlElement",
")",
":",
"sideLoop",
".",
"rotate",
"(",
"xmlElement",
")",
"sideLoop",
".",
"loop",
"=",
"euclidean",
".",
"getLoopWithoutCloseSequentialPoints",
"(",
"sideLoo... | get geometry output by side loop . | train | false |
25,500 | def is_patched(module, attribute_name):
attribute = getattr(module, attribute_name)
return hasattr(attribute, __BACKUP_ATTRIBUTE_NAME)
| [
"def",
"is_patched",
"(",
"module",
",",
"attribute_name",
")",
":",
"attribute",
"=",
"getattr",
"(",
"module",
",",
"attribute_name",
")",
"return",
"hasattr",
"(",
"attribute",
",",
"__BACKUP_ATTRIBUTE_NAME",
")"
] | check if an attribute has been monkey-patched . | train | false |
25,503 | def test_sanity_from_thread():
global TIMER_HELPER_FINISHED
TIMER_HELPER_FINISHED = False
start_new_thread(test_sanity, tuple())
print 'Waiting for test_sanity to finish',
while (not TIMER_HELPER_FINISHED):
print '.',
sleep(0.1)
| [
"def",
"test_sanity_from_thread",
"(",
")",
":",
"global",
"TIMER_HELPER_FINISHED",
"TIMER_HELPER_FINISHED",
"=",
"False",
"start_new_thread",
"(",
"test_sanity",
",",
"tuple",
"(",
")",
")",
"print",
"'Waiting for test_sanity to finish'",
",",
"while",
"(",
"not",
"T... | simply runs test_sanity from a thread . | train | false |
25,504 | def ReserveKeys(keys):
datastore._GetConnection()._reserve_keys(ConvertKeys(keys))
| [
"def",
"ReserveKeys",
"(",
"keys",
")",
":",
"datastore",
".",
"_GetConnection",
"(",
")",
".",
"_reserve_keys",
"(",
"ConvertKeys",
"(",
"keys",
")",
")"
] | reserve all ids in the paths of the given keys . | train | false |
25,505 | def GetPackageModuleName(fileName):
(path, fname) = os.path.split(fileName)
path = origPath = win32ui.FullPath(path)
fname = os.path.splitext(fname)[0]
modBits = []
newPathReturn = None
if (not IsOnPythonPath(path)):
while (len(path) > 3):
(path, modBit) = os.path.split(path)
modBits.append(modBit)
if (IsOnPythonPath(path) and (modBit in sys.modules) and (os.path.exists(os.path.join(path, '__init__.py')) or os.path.exists(os.path.join(path, '__init__.pyc')) or os.path.exists(os.path.join(path, '__init__.pyo')))):
modBits.reverse()
return ((('.'.join(modBits) + '.') + fname), newPathReturn)
else:
newPathReturn = origPath
return (fname, newPathReturn)
| [
"def",
"GetPackageModuleName",
"(",
"fileName",
")",
":",
"(",
"path",
",",
"fname",
")",
"=",
"os",
".",
"path",
".",
"split",
"(",
"fileName",
")",
"path",
"=",
"origPath",
"=",
"win32ui",
".",
"FullPath",
"(",
"path",
")",
"fname",
"=",
"os",
".",... | given a filename . | train | false |
25,506 | def upper_triangle(matlist, K):
copy_matlist = copy.deepcopy(matlist)
(lower_triangle, upper_triangle) = LU(copy_matlist, K)
return upper_triangle
| [
"def",
"upper_triangle",
"(",
"matlist",
",",
"K",
")",
":",
"copy_matlist",
"=",
"copy",
".",
"deepcopy",
"(",
"matlist",
")",
"(",
"lower_triangle",
",",
"upper_triangle",
")",
"=",
"LU",
"(",
"copy_matlist",
",",
"K",
")",
"return",
"upper_triangle"
] | transforms a given matrix to an upper triangle matrix by performing row operations on it . | train | false |
25,507 | def hmc_updates(positions, stepsize, avg_acceptance_rate, final_pos, accept, target_acceptance_rate, stepsize_inc, stepsize_dec, stepsize_min, stepsize_max, avg_acceptance_slowness):
accept_matrix = accept.dimshuffle(0, *(('x',) * (final_pos.ndim - 1)))
new_positions = TT.switch(accept_matrix, final_pos, positions)
_new_stepsize = TT.switch((avg_acceptance_rate > target_acceptance_rate), (stepsize * stepsize_inc), (stepsize * stepsize_dec))
new_stepsize = TT.clip(_new_stepsize, stepsize_min, stepsize_max)
mean_dtype = theano.scalar.upcast(accept.dtype, avg_acceptance_rate.dtype)
new_acceptance_rate = TT.add((avg_acceptance_slowness * avg_acceptance_rate), ((1.0 - avg_acceptance_slowness) * accept.mean(dtype=mean_dtype)))
return [(positions, new_positions), (stepsize, new_stepsize), (avg_acceptance_rate, new_acceptance_rate)]
| [
"def",
"hmc_updates",
"(",
"positions",
",",
"stepsize",
",",
"avg_acceptance_rate",
",",
"final_pos",
",",
"accept",
",",
"target_acceptance_rate",
",",
"stepsize_inc",
",",
"stepsize_dec",
",",
"stepsize_min",
",",
"stepsize_max",
",",
"avg_acceptance_slowness",
")"... | this function is executed after n_steps of hmc sampling . | train | false |
25,509 | def ErrorCriteria(errors):
ERROR_ALERT_THRESHOLD = 5
alerts = []
warnings = []
if (errors['cluster_total'] > ERROR_ALERT_THRESHOLD):
alerts.append(CLUSTER_TOKEN)
elif (errors['cluster_total'] > 0):
warnings.append(CLUSTER_TOKEN)
return (alerts, warnings)
| [
"def",
"ErrorCriteria",
"(",
"errors",
")",
":",
"ERROR_ALERT_THRESHOLD",
"=",
"5",
"alerts",
"=",
"[",
"]",
"warnings",
"=",
"[",
"]",
"if",
"(",
"errors",
"[",
"'cluster_total'",
"]",
">",
"ERROR_ALERT_THRESHOLD",
")",
":",
"alerts",
".",
"append",
"(",
... | monitor the number of unexpected errors logged in the cluster . | train | false |
25,510 | def supersample(clip, d, nframes):
def fl(gf, t):
tt = np.linspace((t - d), (t + d), nframes)
avg = np.mean((1.0 * np.array([gf(t_) for t_ in tt], dtype='uint16')), axis=0)
return avg.astype('uint8')
return clip.fl(fl)
| [
"def",
"supersample",
"(",
"clip",
",",
"d",
",",
"nframes",
")",
":",
"def",
"fl",
"(",
"gf",
",",
"t",
")",
":",
"tt",
"=",
"np",
".",
"linspace",
"(",
"(",
"t",
"-",
"d",
")",
",",
"(",
"t",
"+",
"d",
")",
",",
"nframes",
")",
"avg",
"... | replaces each frame at time t by the mean of nframes equally spaced frames taken in the interval [t-d . | train | false |
25,511 | def login_rate_limit():
return '{count}/{timeout}minutes'.format(count=flaskbb_config['AUTH_REQUESTS'], timeout=flaskbb_config['AUTH_TIMEOUT'])
| [
"def",
"login_rate_limit",
"(",
")",
":",
"return",
"'{count}/{timeout}minutes'",
".",
"format",
"(",
"count",
"=",
"flaskbb_config",
"[",
"'AUTH_REQUESTS'",
"]",
",",
"timeout",
"=",
"flaskbb_config",
"[",
"'AUTH_TIMEOUT'",
"]",
")"
] | dynamically load the rate limiting config from the database . | train | false |
25,512 | def delete_redemption_entry(request, code_redemption, course_key):
user = code_redemption.redeemed_by
email_address = code_redemption.redeemed_by.email
full_name = code_redemption.redeemed_by.profile.name
CourseEnrollment.unenroll(user, course_key, skip_refund=True)
course = get_course_by_id(course_key, depth=0)
email_params = get_email_params(course, True, secure=request.is_secure())
email_params['message'] = 'enrolled_unenroll'
email_params['email_address'] = email_address
email_params['full_name'] = full_name
send_mail_to_student(email_address, email_params)
log.info('deleting redemption entry (%s) from the database.', code_redemption.id)
code_redemption.delete()
| [
"def",
"delete_redemption_entry",
"(",
"request",
",",
"code_redemption",
",",
"course_key",
")",
":",
"user",
"=",
"code_redemption",
".",
"redeemed_by",
"email_address",
"=",
"code_redemption",
".",
"redeemed_by",
".",
"email",
"full_name",
"=",
"code_redemption",
... | delete the redemption entry from the table and unenroll the user who used the registration code for the enrollment and send him/her the unenrollment email . | train | false |
25,517 | def current_timestamp():
return calendar.timegm(datetime.datetime.utcnow().utctimetuple())
| [
"def",
"current_timestamp",
"(",
")",
":",
"return",
"calendar",
".",
"timegm",
"(",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
".",
"utctimetuple",
"(",
")",
")"
] | returns current utc timestamp . | train | false |
25,518 | def _mount_filesystem(dev_path, dir):
try:
(_out, err) = utils.execute('mount', '-t', 'ext2,ext3,ext4,reiserfs', dev_path, dir, run_as_root=True)
except exception.ProcessExecutionError as e:
err = str(e)
return err
| [
"def",
"_mount_filesystem",
"(",
"dev_path",
",",
"dir",
")",
":",
"try",
":",
"(",
"_out",
",",
"err",
")",
"=",
"utils",
".",
"execute",
"(",
"'mount'",
",",
"'-t'",
",",
"'ext2,ext3,ext4,reiserfs'",
",",
"dev_path",
",",
"dir",
",",
"run_as_root",
"="... | mounts the device specified by dev_path in dir . | train | false |
25,520 | def addFacesByLoopReversed(faces, indexedLoop):
addFacesByLoop(faces, indexedLoop[::(-1)])
| [
"def",
"addFacesByLoopReversed",
"(",
"faces",
",",
"indexedLoop",
")",
":",
"addFacesByLoop",
"(",
"faces",
",",
"indexedLoop",
"[",
":",
":",
"(",
"-",
"1",
")",
"]",
")"
] | add faces from a reversed convex polygon . | train | false |
25,521 | def pythonexecutable():
return {'pythonexecutable': sys.executable}
| [
"def",
"pythonexecutable",
"(",
")",
":",
"return",
"{",
"'pythonexecutable'",
":",
"sys",
".",
"executable",
"}"
] | return the python executable in use . | train | false |
25,524 | def source_modified(uowcommit, source, source_mapper, synchronize_pairs):
for (l, r) in synchronize_pairs:
try:
prop = source_mapper._columntoproperty[l]
except exc.UnmappedColumnError:
_raise_col_to_prop(False, source_mapper, l, None, r)
history = uowcommit.get_attribute_history(source, prop.key, attributes.PASSIVE_NO_INITIALIZE)
if bool(history.deleted):
return True
else:
return False
| [
"def",
"source_modified",
"(",
"uowcommit",
",",
"source",
",",
"source_mapper",
",",
"synchronize_pairs",
")",
":",
"for",
"(",
"l",
",",
"r",
")",
"in",
"synchronize_pairs",
":",
"try",
":",
"prop",
"=",
"source_mapper",
".",
"_columntoproperty",
"[",
"l",... | return true if the source object has changes from an old to a new value on the given synchronize pairs . | train | false |
25,525 | def ApprovalRevokeRaw(aff4_path, token, remove_from_cache=False):
try:
urn = rdf_client.ClientURN(aff4_path)
except type_info.TypeValueError:
urn = rdfvalue.RDFURN(aff4_path)
approval_urn = aff4.ROOT_URN.Add('ACL').Add(urn.Path()).Add(token.username).Add(utils.EncodeReasonString(token.reason))
super_token = access_control.ACLToken(username='raw-approval-superuser')
super_token.supervisor = True
approval_request = aff4.FACTORY.Open(approval_urn, mode='rw', token=super_token)
approval_request.DeleteAttribute(approval_request.Schema.APPROVER)
approval_request.Close()
if remove_from_cache:
data_store.DB.security_manager.acl_cache.ExpireObject(utils.SmartUnicode(approval_urn))
| [
"def",
"ApprovalRevokeRaw",
"(",
"aff4_path",
",",
"token",
",",
"remove_from_cache",
"=",
"False",
")",
":",
"try",
":",
"urn",
"=",
"rdf_client",
".",
"ClientURN",
"(",
"aff4_path",
")",
"except",
"type_info",
".",
"TypeValueError",
":",
"urn",
"=",
"rdfva... | revokes an approval for a given token . | train | true |
25,526 | def _theano_energy_function(H, q, **theano_kwargs):
p = tt.dvector('p')
p.tag.test_value = q.tag.test_value
total_energy = (H.pot.energy(p) - H.logp(q))
energy_function = theano.function(inputs=[q, p], outputs=total_energy, **theano_kwargs)
energy_function.trust_input = True
return (energy_function, p)
| [
"def",
"_theano_energy_function",
"(",
"H",
",",
"q",
",",
"**",
"theano_kwargs",
")",
":",
"p",
"=",
"tt",
".",
"dvector",
"(",
"'p'",
")",
"p",
".",
"tag",
".",
"test_value",
"=",
"q",
".",
"tag",
".",
"test_value",
"total_energy",
"=",
"(",
"H",
... | creates a hamiltonian with shared inputs . | train | false |
25,528 | def run_stderr(cmd, cwd=None, stdin=None, runas=None, shell=DEFAULT_SHELL, python_shell=None, env=None, clean_env=False, template=None, rstrip=True, umask=None, output_loglevel='debug', log_callback=None, timeout=None, reset_system_locale=True, ignore_retcode=False, saltenv='base', use_vt=False, password=None, **kwargs):
python_shell = _python_shell_default(python_shell, kwargs.get('__pub_jid', ''))
ret = _run(cmd, runas=runas, cwd=cwd, stdin=stdin, shell=shell, python_shell=python_shell, env=env, clean_env=clean_env, template=template, rstrip=rstrip, umask=umask, output_loglevel=output_loglevel, log_callback=log_callback, timeout=timeout, reset_system_locale=reset_system_locale, ignore_retcode=ignore_retcode, use_vt=use_vt, saltenv=saltenv, password=password, **kwargs)
log_callback = _check_cb(log_callback)
lvl = _check_loglevel(output_loglevel)
if (lvl is not None):
if ((not ignore_retcode) and (ret['retcode'] != 0)):
if (lvl < LOG_LEVELS['error']):
lvl = LOG_LEVELS['error']
msg = "Command '{0}' failed with return code: {1}".format(cmd, ret['retcode'])
log.error(log_callback(msg))
if ret['stdout']:
log.log(lvl, 'stdout: {0}'.format(log_callback(ret['stdout'])))
if ret['stderr']:
log.log(lvl, 'stderr: {0}'.format(log_callback(ret['stderr'])))
if ret['retcode']:
log.log(lvl, 'retcode: {0}'.format(ret['retcode']))
return ret['stderr']
| [
"def",
"run_stderr",
"(",
"cmd",
",",
"cwd",
"=",
"None",
",",
"stdin",
"=",
"None",
",",
"runas",
"=",
"None",
",",
"shell",
"=",
"DEFAULT_SHELL",
",",
"python_shell",
"=",
"None",
",",
"env",
"=",
"None",
",",
"clean_env",
"=",
"False",
",",
"templ... | run :py:func:cmd . | train | false |
25,529 | def set_coalesce(devname, **kwargs):
try:
coalesce = ethtool.get_coalesce(devname)
except IOError:
log.error('Interrupt coalescing not supported on {0}'.format(devname))
return 'Not supported'
changed = False
for (param, value) in kwargs.items():
if (param in ethtool_coalesce_map):
param = ethtool_coalesce_map[param]
if (param in coalesce):
if (coalesce[param] != value):
coalesce[param] = value
changed = True
try:
if changed:
ethtool.set_coalesce(devname, coalesce)
return show_coalesce(devname)
except IOError:
log.error('Invalid coalesce arguments on {0}: {1}'.format(devname, coalesce))
return 'Invalid arguments'
| [
"def",
"set_coalesce",
"(",
"devname",
",",
"**",
"kwargs",
")",
":",
"try",
":",
"coalesce",
"=",
"ethtool",
".",
"get_coalesce",
"(",
"devname",
")",
"except",
"IOError",
":",
"log",
".",
"error",
"(",
"'Interrupt coalescing not supported on {0}'",
".",
"for... | changes the coalescing settings of the specified network device cli example: . | train | true |
25,530 | def set_attrs(obj, attrs):
o = setattr
if hasattr(obj, '__setitem__'):
o = type(obj).__setitem__
[o(obj, k, v) for (k, v) in attrs.iteritems()]
| [
"def",
"set_attrs",
"(",
"obj",
",",
"attrs",
")",
":",
"o",
"=",
"setattr",
"if",
"hasattr",
"(",
"obj",
",",
"'__setitem__'",
")",
":",
"o",
"=",
"type",
"(",
"obj",
")",
".",
"__setitem__",
"[",
"o",
"(",
"obj",
",",
"k",
",",
"v",
")",
"for... | applies a collection of attributes c{attrs} to object c{obj} in the most generic way possible . | train | true |
25,531 | def autoflush():
logs_buffer().autoflush()
| [
"def",
"autoflush",
"(",
")",
":",
"logs_buffer",
"(",
")",
".",
"autoflush",
"(",
")"
] | if autoflush conditions have been met . | train | false |
25,532 | def output_merge(cls, alpha_in, beta_in, out_in):
def wrapper(maker):
@local_optimizer([GpuElemwise])
@wraps(maker)
def opt(node):
if (isinstance(node.op, GpuElemwise) and (node.op.scalar_op == scal.add) and (node.nin == 2)):
targ = find_node(node.inputs[0], cls)
W = node.inputs[1]
if (targ is None):
targ = find_node(node.inputs[1], cls)
W = node.inputs[0]
if (targ is None):
return None
if (W.dtype != targ.outputs[0].dtype):
return None
if (not is_equal(targ.inputs[beta_in], 0.0)):
return None
if (W.broadcastable != targ.inputs[out_in].broadcastable):
return None
inputs = list(targ.inputs)
inputs[out_in] = W
inputs[beta_in] = _one.clone()
return maker(targ, *inputs)
return opt
return wrapper
| [
"def",
"output_merge",
"(",
"cls",
",",
"alpha_in",
",",
"beta_in",
",",
"out_in",
")",
":",
"def",
"wrapper",
"(",
"maker",
")",
":",
"@",
"local_optimizer",
"(",
"[",
"GpuElemwise",
"]",
")",
"@",
"wraps",
"(",
"maker",
")",
"def",
"opt",
"(",
"nod... | decorator to merge addition by a value on the output . | train | false |
25,533 | def connectedServerAndClient(ServerClass=SimpleSymmetricProtocol, ClientClass=SimpleSymmetricProtocol, *a, **kw):
return iosim.connectedServerAndClient(ServerClass, ClientClass, *a, **kw)
| [
"def",
"connectedServerAndClient",
"(",
"ServerClass",
"=",
"SimpleSymmetricProtocol",
",",
"ClientClass",
"=",
"SimpleSymmetricProtocol",
",",
"*",
"a",
",",
"**",
"kw",
")",
":",
"return",
"iosim",
".",
"connectedServerAndClient",
"(",
"ServerClass",
",",
"ClientC... | connect a client and server l{broker} together with an l{iopump} . | train | false |
25,534 | def _read_valuation_line(s):
pieces = _VAL_SPLIT_RE.split(s)
symbol = pieces[0]
value = pieces[1]
if value.startswith(u'{'):
value = value[1:(-1)]
tuple_strings = _TUPLES_RE.findall(value)
if tuple_strings:
set_elements = []
for ts in tuple_strings:
ts = ts[1:(-1)]
element = tuple(_ELEMENT_SPLIT_RE.split(ts))
set_elements.append(element)
else:
set_elements = _ELEMENT_SPLIT_RE.split(value)
value = set(set_elements)
return (symbol, value)
| [
"def",
"_read_valuation_line",
"(",
"s",
")",
":",
"pieces",
"=",
"_VAL_SPLIT_RE",
".",
"split",
"(",
"s",
")",
"symbol",
"=",
"pieces",
"[",
"0",
"]",
"value",
"=",
"pieces",
"[",
"1",
"]",
"if",
"value",
".",
"startswith",
"(",
"u'{'",
")",
":",
... | read a line in a valuation file . | train | false |
25,535 | def maximum_spanning_edges(G, algorithm='kruskal', weight='weight', data=True):
return _spanning_edges(G, minimum=False, algorithm=algorithm, weight=weight, data=data)
| [
"def",
"maximum_spanning_edges",
"(",
"G",
",",
"algorithm",
"=",
"'kruskal'",
",",
"weight",
"=",
"'weight'",
",",
"data",
"=",
"True",
")",
":",
"return",
"_spanning_edges",
"(",
"G",
",",
"minimum",
"=",
"False",
",",
"algorithm",
"=",
"algorithm",
",",... | generate edges in a maximum spanning forest of an undirected weighted graph . | train | false |
25,536 | @retry(exception=AssertionError, logfun=None, timeout=GLOBAL_TIMEOUT, interval=0.001)
def call_until(fun, expr):
ret = fun()
assert eval(expr)
return ret
| [
"@",
"retry",
"(",
"exception",
"=",
"AssertionError",
",",
"logfun",
"=",
"None",
",",
"timeout",
"=",
"GLOBAL_TIMEOUT",
",",
"interval",
"=",
"0.001",
")",
"def",
"call_until",
"(",
"fun",
",",
"expr",
")",
":",
"ret",
"=",
"fun",
"(",
")",
"assert",... | keep calling function for timeout secs and exit if eval() expression is true . | train | false |
25,537 | def getConstructor(object):
try:
return object.__init__.im_func
except AttributeError:
for base in object.__bases__:
constructor = getConstructor(base)
if (constructor is not None):
return constructor
return None
| [
"def",
"getConstructor",
"(",
"object",
")",
":",
"try",
":",
"return",
"object",
".",
"__init__",
".",
"im_func",
"except",
"AttributeError",
":",
"for",
"base",
"in",
"object",
".",
"__bases__",
":",
"constructor",
"=",
"getConstructor",
"(",
"base",
")",
... | return constructor for class object . | train | false |
25,538 | @utils.arg('server', metavar='<server>', help=_('ID of server.'))
def do_virtual_interface_list(cs, args):
server = _find_server(cs, args.server)
interface_list = cs.virtual_interfaces.list(base.getid(server))
_print_virtual_interface_list(cs, interface_list)
| [
"@",
"utils",
".",
"arg",
"(",
"'server'",
",",
"metavar",
"=",
"'<server>'",
",",
"help",
"=",
"_",
"(",
"'ID of server.'",
")",
")",
"def",
"do_virtual_interface_list",
"(",
"cs",
",",
"args",
")",
":",
"server",
"=",
"_find_server",
"(",
"cs",
",",
... | show virtual interface info about the given server . | train | false |
25,540 | @task
def clean_python(ctx, dry_run=False):
cleanup_dirs(['build', 'dist', '*.egg-info', '**/__pycache__'], dry_run=dry_run)
if (not dry_run):
ctx.run('py.cleanup')
cleanup_files(['**/*.pyc', '**/*.pyo', '**/*$py.class'], dry_run=dry_run)
| [
"@",
"task",
"def",
"clean_python",
"(",
"ctx",
",",
"dry_run",
"=",
"False",
")",
":",
"cleanup_dirs",
"(",
"[",
"'build'",
",",
"'dist'",
",",
"'*.egg-info'",
",",
"'**/__pycache__'",
"]",
",",
"dry_run",
"=",
"dry_run",
")",
"if",
"(",
"not",
"dry_run... | cleanup python related files/dirs: * . | train | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.