labNo float64 1 10 ⌀ | taskNo float64 0 4 ⌀ | questioner stringclasses 2
values | question stringlengths 9 201 | code stringlengths 18 30.3k | startLine float64 0 192 ⌀ | endLine float64 0 196 ⌀ | questionType stringclasses 4
values | answer stringlengths 2 905 | src stringclasses 3
values | code_processed stringlengths 12 28.3k ⌀ | id stringlengths 2 5 ⌀ | raw_code stringlengths 20 30.3k ⌀ | raw_comment stringlengths 10 242 ⌀ | comment stringlengths 9 207 ⌀ | q_code stringlengths 66 30.3k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
null | null | null | What does this function do? | def absent(dest, username, check_mode):
if (StrictVersion(passlib.__version__) >= StrictVersion('1.6')):
ht = HtpasswdFile(dest, new=False)
else:
ht = HtpasswdFile(dest)
if (username not in ht.users()):
return (('%s not present' % username), False)
else:
if (not check_mode):
ht.delete(username)
ht.sav... | null | null | null | Ensures user is absent
Returns (msg, changed) | pcsd | def absent dest username check mode if Strict Version passlib version >= Strict Version '1 6' ht = Htpasswd File dest new=False else ht = Htpasswd File dest if username not in ht users return '%s not present' % username False else if not check mode ht delete username ht save return 'Remove %s' % username True | 7607 | def absent(dest, username, check_mode):
if (StrictVersion(passlib.__version__) >= StrictVersion('1.6')):
ht = HtpasswdFile(dest, new=False)
else:
ht = HtpasswdFile(dest)
if (username not in ht.users()):
return (('%s not present' % username), False)
else:
if (not check_mode):
ht.delete(username)
ht.sav... | Ensures user is absent
Returns (msg, changed) | ensures user is absent | Question:
What does this function do?
Code:
def absent(dest, username, check_mode):
if (StrictVersion(passlib.__version__) >= StrictVersion('1.6')):
ht = HtpasswdFile(dest, new=False)
else:
ht = HtpasswdFile(dest)
if (username not in ht.users()):
return (('%s not present' % username), False)
else:
if (no... |
null | null | null | What does this function do? | def update_index(sender, instance, created, **kwargs):
if (isinstance(instance, Object) and instance.is_searchable()):
search_item = instance.get_search_item()
ix = index.open_dir(settings.WHOOSH_INDEX)
try:
writer = ix.writer()
try:
if created:
writer.add_document(id=search_item['id'], name=searc... | null | null | null | Add Object to search index | pcsd | def update index sender instance created **kwargs if isinstance instance Object and instance is searchable search item = instance get search item ix = index open dir settings WHOOSH INDEX try writer = ix writer try if created writer add document id=search item['id'] name=search item['name'] type=search item['type'] con... | 7610 | def update_index(sender, instance, created, **kwargs):
if (isinstance(instance, Object) and instance.is_searchable()):
search_item = instance.get_search_item()
ix = index.open_dir(settings.WHOOSH_INDEX)
try:
writer = ix.writer()
try:
if created:
writer.add_document(id=search_item['id'], name=searc... | Add Object to search index | add object to search index | Question:
What does this function do?
Code:
def update_index(sender, instance, created, **kwargs):
if (isinstance(instance, Object) and instance.is_searchable()):
search_item = instance.get_search_item()
ix = index.open_dir(settings.WHOOSH_INDEX)
try:
writer = ix.writer()
try:
if created:
write... |
null | null | null | What does this function do? | @utils.arg('snapshot', metavar='<snapshot>', help='ID of the snapshot.')
@utils.arg('display_name', nargs='?', metavar='<display-name>', help='New display-name for the snapshot.')
@utils.arg('--display-description', metavar='<display-description>', help='Optional snapshot description. (Default=None)', default=None)
@ut... | null | null | null | Rename a snapshot. | pcsd | @utils arg 'snapshot' metavar='<snapshot>' help='ID of the snapshot ' @utils arg 'display name' nargs='?' metavar='<display-name>' help='New display-name for the snapshot ' @utils arg '--display-description' metavar='<display-description>' help='Optional snapshot description Default=None ' default=None @utils service t... | 7621 | @utils.arg('snapshot', metavar='<snapshot>', help='ID of the snapshot.')
@utils.arg('display_name', nargs='?', metavar='<display-name>', help='New display-name for the snapshot.')
@utils.arg('--display-description', metavar='<display-description>', help='Optional snapshot description. (Default=None)', default=None)
@ut... | Rename a snapshot. | rename a snapshot . | Question:
What does this function do?
Code:
@utils.arg('snapshot', metavar='<snapshot>', help='ID of the snapshot.')
@utils.arg('display_name', nargs='?', metavar='<display-name>', help='New display-name for the snapshot.')
@utils.arg('--display-description', metavar='<display-description>', help='Optional snapshot ... |
null | null | null | What does this function do? | def _read_filter(fid):
f = dict()
f['freq'] = _read_double(fid)[0]
f['class'] = _read_int(fid)
f['type'] = _read_int(fid)
f['npar'] = _read_int2(fid)
f['pars'] = _read_double(fid, f['npar'])
return f
| null | null | null | Read filter information. | pcsd | def read filter fid f = dict f['freq'] = read double fid [0] f['class'] = read int fid f['type'] = read int fid f['npar'] = read int2 fid f['pars'] = read double fid f['npar'] return f | 7623 | def _read_filter(fid):
f = dict()
f['freq'] = _read_double(fid)[0]
f['class'] = _read_int(fid)
f['type'] = _read_int(fid)
f['npar'] = _read_int2(fid)
f['pars'] = _read_double(fid, f['npar'])
return f
| Read filter information. | read filter information . | Question:
What does this function do?
Code:
def _read_filter(fid):
f = dict()
f['freq'] = _read_double(fid)[0]
f['class'] = _read_int(fid)
f['type'] = _read_int(fid)
f['npar'] = _read_int2(fid)
f['pars'] = _read_double(fid, f['npar'])
return f
|
null | null | null | What does this function do? | def parse_geometry(geometry, ratio=None):
m = geometry_pat.match(geometry)
def syntax_error():
return ThumbnailParseError(('Geometry does not have the correct syntax: %s' % geometry))
if (not m):
raise syntax_error()
x = m.group('x')
y = m.group('y')
if ((x is None) and (y is None)):
raise syntax_error()
i... | null | null | null | Parses a geometry string syntax and returns a (width, height) tuple | pcsd | def parse geometry geometry ratio=None m = geometry pat match geometry def syntax error return Thumbnail Parse Error 'Geometry does not have the correct syntax %s' % geometry if not m raise syntax error x = m group 'x' y = m group 'y' if x is None and y is None raise syntax error if x is not None x = int x if y is not ... | 7624 | def parse_geometry(geometry, ratio=None):
m = geometry_pat.match(geometry)
def syntax_error():
return ThumbnailParseError(('Geometry does not have the correct syntax: %s' % geometry))
if (not m):
raise syntax_error()
x = m.group('x')
y = m.group('y')
if ((x is None) and (y is None)):
raise syntax_error()
i... | Parses a geometry string syntax and returns a (width, height) tuple | parses a geometry string syntax and returns a tuple | Question:
What does this function do?
Code:
def parse_geometry(geometry, ratio=None):
m = geometry_pat.match(geometry)
def syntax_error():
return ThumbnailParseError(('Geometry does not have the correct syntax: %s' % geometry))
if (not m):
raise syntax_error()
x = m.group('x')
y = m.group('y')
if ((x is No... |
null | null | null | What does this function do? | def write_chunk(outfile, tag, data=''):
outfile.write(struct.pack('!I', len(data)))
outfile.write(tag)
outfile.write(data)
checksum = zlib.crc32(tag)
checksum = zlib.crc32(data, checksum)
outfile.write(struct.pack('!i', checksum))
| null | null | null | Write a PNG chunk to the output file, including length and
checksum. | pcsd | def write chunk outfile tag data='' outfile write struct pack '!I' len data outfile write tag outfile write data checksum = zlib crc32 tag checksum = zlib crc32 data checksum outfile write struct pack '!i' checksum | 7627 | def write_chunk(outfile, tag, data=''):
outfile.write(struct.pack('!I', len(data)))
outfile.write(tag)
outfile.write(data)
checksum = zlib.crc32(tag)
checksum = zlib.crc32(data, checksum)
outfile.write(struct.pack('!i', checksum))
| Write a PNG chunk to the output file, including length and
checksum. | write a png chunk to the output file , including length and checksum . | Question:
What does this function do?
Code:
def write_chunk(outfile, tag, data=''):
outfile.write(struct.pack('!I', len(data)))
outfile.write(tag)
outfile.write(data)
checksum = zlib.crc32(tag)
checksum = zlib.crc32(data, checksum)
outfile.write(struct.pack('!i', checksum))
|
null | null | null | What does this function do? | @require_POST
@login_required
@permission_required('flagit.can_moderate')
def update(request, flagged_object_id):
flagged = get_object_or_404(FlaggedObject, pk=flagged_object_id)
new_status = request.POST.get('status')
if new_status:
flagged.status = new_status
flagged.save()
return HttpResponseRedirect(reverse... | null | null | null | Update the status of a flagged object. | pcsd | @require POST @login required @permission required 'flagit can moderate' def update request flagged object id flagged = get object or 404 Flagged Object pk=flagged object id new status = request POST get 'status' if new status flagged status = new status flagged save return Http Response Redirect reverse 'flagit queue' | 7636 | @require_POST
@login_required
@permission_required('flagit.can_moderate')
def update(request, flagged_object_id):
flagged = get_object_or_404(FlaggedObject, pk=flagged_object_id)
new_status = request.POST.get('status')
if new_status:
flagged.status = new_status
flagged.save()
return HttpResponseRedirect(reverse... | Update the status of a flagged object. | update the status of a flagged object . | Question:
What does this function do?
Code:
@require_POST
@login_required
@permission_required('flagit.can_moderate')
def update(request, flagged_object_id):
flagged = get_object_or_404(FlaggedObject, pk=flagged_object_id)
new_status = request.POST.get('status')
if new_status:
flagged.status = new_status
flag... |
null | null | null | What does this function do? | @service.jsonrpc
def login():
return True
| null | null | null | dummy function to test credentials | pcsd | @service jsonrpc def login return True | 7642 | @service.jsonrpc
def login():
return True
| dummy function to test credentials | dummy function to test credentials | Question:
What does this function do?
Code:
@service.jsonrpc
def login():
return True
|
null | null | null | What does this function do? | def instance_get_all_by_host(context, host, columns_to_join=None):
return IMPL.instance_get_all_by_host(context, host, columns_to_join)
| null | null | null | Get all instances belonging to a host. | pcsd | def instance get all by host context host columns to join=None return IMPL instance get all by host context host columns to join | 7643 | def instance_get_all_by_host(context, host, columns_to_join=None):
return IMPL.instance_get_all_by_host(context, host, columns_to_join)
| Get all instances belonging to a host. | get all instances belonging to a host . | Question:
What does this function do?
Code:
def instance_get_all_by_host(context, host, columns_to_join=None):
return IMPL.instance_get_all_by_host(context, host, columns_to_join)
|
null | null | null | What does this function do? | def _pack(coefs_, intercepts_):
return np.hstack([l.ravel() for l in (coefs_ + intercepts_)])
| null | null | null | Pack the parameters into a single vector. | pcsd | def pack coefs intercepts return np hstack [l ravel for l in coefs + intercepts ] | 7649 | def _pack(coefs_, intercepts_):
return np.hstack([l.ravel() for l in (coefs_ + intercepts_)])
| Pack the parameters into a single vector. | pack the parameters into a single vector . | Question:
What does this function do?
Code:
def _pack(coefs_, intercepts_):
return np.hstack([l.ravel() for l in (coefs_ + intercepts_)])
|
null | null | null | What does this function do? | def telescopic(L, R, limits):
(i, a, b) = limits
if (L.is_Add or R.is_Add):
return None
k = Wild('k')
sol = (- R).match(L.subs(i, (i + k)))
s = None
if (sol and (k in sol)):
s = sol[k]
if (not (s.is_Integer and (L.subs(i, (i + s)) == (- R)))):
s = None
if (s is None):
m = Dummy('m')
try:
sol = (s... | null | null | null | Tries to perform the summation using the telescopic property
return None if not possible | pcsd | def telescopic L R limits i a b = limits if L is Add or R is Add return None k = Wild 'k' sol = - R match L subs i i + k s = None if sol and k in sol s = sol[k] if not s is Integer and L subs i i + s == - R s = None if s is None m = Dummy 'm' try sol = solve L subs i i + m + R m or [] except Not Implemented Error retur... | 7650 | def telescopic(L, R, limits):
(i, a, b) = limits
if (L.is_Add or R.is_Add):
return None
k = Wild('k')
sol = (- R).match(L.subs(i, (i + k)))
s = None
if (sol and (k in sol)):
s = sol[k]
if (not (s.is_Integer and (L.subs(i, (i + s)) == (- R)))):
s = None
if (s is None):
m = Dummy('m')
try:
sol = (s... | Tries to perform the summation using the telescopic property
return None if not possible | tries to perform the summation using the telescopic property return none if not possible | Question:
What does this function do?
Code:
def telescopic(L, R, limits):
(i, a, b) = limits
if (L.is_Add or R.is_Add):
return None
k = Wild('k')
sol = (- R).match(L.subs(i, (i + k)))
s = None
if (sol and (k in sol)):
s = sol[k]
if (not (s.is_Integer and (L.subs(i, (i + s)) == (- R)))):
s = None
if (... |
null | null | null | What does this function do? | @receiver(post_save, sender=User)
def user_post_save_callback(sender, **kwargs):
user = kwargs['instance']
emit_field_changed_events(user, user, sender._meta.db_table, excluded_fields=['last_login', 'first_name', 'last_name'], hidden_fields=['password'])
| null | null | null | Emit analytics events after saving the User. | pcsd | @receiver post save sender=User def user post save callback sender **kwargs user = kwargs['instance'] emit field changed events user user sender meta db table excluded fields=['last login' 'first name' 'last name'] hidden fields=['password'] | 7655 | @receiver(post_save, sender=User)
def user_post_save_callback(sender, **kwargs):
user = kwargs['instance']
emit_field_changed_events(user, user, sender._meta.db_table, excluded_fields=['last_login', 'first_name', 'last_name'], hidden_fields=['password'])
| Emit analytics events after saving the User. | emit analytics events after saving the user . | Question:
What does this function do?
Code:
@receiver(post_save, sender=User)
def user_post_save_callback(sender, **kwargs):
user = kwargs['instance']
emit_field_changed_events(user, user, sender._meta.db_table, excluded_fields=['last_login', 'first_name', 'last_name'], hidden_fields=['password'])
|
null | null | null | What does this function do? | @treeio_login_required
def ajax_contact_lookup(request, response_format='html'):
contacts = []
if (request.GET and ('term' in request.GET)):
user = request.user.profile
contacts = Object.filter_permitted(user, Contact.objects, mode='x').filter(Q(name__icontains=request.GET['term']))[:10]
return render_to_respons... | null | null | null | Returns a list of matching contacts | pcsd | @treeio login required def ajax contact lookup request response format='html' contacts = [] if request GET and 'term' in request GET user = request user profile contacts = Object filter permitted user Contact objects mode='x' filter Q name icontains=request GET['term'] [ 10] return render to response 'identities/ajax c... | 7662 | @treeio_login_required
def ajax_contact_lookup(request, response_format='html'):
contacts = []
if (request.GET and ('term' in request.GET)):
user = request.user.profile
contacts = Object.filter_permitted(user, Contact.objects, mode='x').filter(Q(name__icontains=request.GET['term']))[:10]
return render_to_respons... | Returns a list of matching contacts | returns a list of matching contacts | Question:
What does this function do?
Code:
@treeio_login_required
def ajax_contact_lookup(request, response_format='html'):
contacts = []
if (request.GET and ('term' in request.GET)):
user = request.user.profile
contacts = Object.filter_permitted(user, Contact.objects, mode='x').filter(Q(name__icontains=reque... |
null | null | null | What does this function do? | def subscription_check():
subscriptions = Subscription.objects.all()
for subscription in subscriptions:
subscription.check_status()
| null | null | null | Automatically depreciate assets as per their depreciation rate | pcsd | def subscription check subscriptions = Subscription objects all for subscription in subscriptions subscription check status | 7665 | def subscription_check():
subscriptions = Subscription.objects.all()
for subscription in subscriptions:
subscription.check_status()
| Automatically depreciate assets as per their depreciation rate | automatically depreciate assets as per their depreciation rate | Question:
What does this function do?
Code:
def subscription_check():
subscriptions = Subscription.objects.all()
for subscription in subscriptions:
subscription.check_status()
|
null | null | null | What does this function do? | def _setwindowsize(folder_alias, (w, h)):
finder = _getfinder()
args = {}
attrs = {}
_code = 'core'
_subcode = 'setd'
aevar00 = [w, h]
aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'), form='alis', seld=folder_alias, fr=None)
aeobj_1 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form='prop', s... | null | null | null | Set the size of a Finder window for folder to (w, h) | pcsd | def setwindowsize folder alias w h finder = getfinder args = {} attrs = {} code = 'core' subcode = 'setd' aevar00 = [w h] aeobj 0 = aetypes Object Specifier want=aetypes Type 'cfol' form='alis' seld=folder alias fr=None aeobj 1 = aetypes Object Specifier want=aetypes Type 'prop' form='prop' seld=aetypes Type 'cwnd' fr=... | 7669 | def _setwindowsize(folder_alias, (w, h)):
finder = _getfinder()
args = {}
attrs = {}
_code = 'core'
_subcode = 'setd'
aevar00 = [w, h]
aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'), form='alis', seld=folder_alias, fr=None)
aeobj_1 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form='prop', s... | Set the size of a Finder window for folder to (w, h) | set the size of a finder window for folder to | Question:
What does this function do?
Code:
def _setwindowsize(folder_alias, (w, h)):
finder = _getfinder()
args = {}
attrs = {}
_code = 'core'
_subcode = 'setd'
aevar00 = [w, h]
aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'), form='alis', seld=folder_alias, fr=None)
aeobj_1 = aetypes.ObjectSpec... |
null | null | null | What does this function do? | def is_nonstring_iterable(obj):
return (isinstance(obj, Iterable) and (not isinstance(obj, string_types)))
| null | null | null | Returns whether the obj is an iterable, but not a string | pcsd | def is nonstring iterable obj return isinstance obj Iterable and not isinstance obj string types | 7677 | def is_nonstring_iterable(obj):
return (isinstance(obj, Iterable) and (not isinstance(obj, string_types)))
| Returns whether the obj is an iterable, but not a string | returns whether the obj is an iterable , but not a string | Question:
What does this function do?
Code:
def is_nonstring_iterable(obj):
return (isinstance(obj, Iterable) and (not isinstance(obj, string_types)))
|
null | null | null | What does this function do? | def mp_icon(filename):
try:
import pkg_resources
name = __name__
if (name == '__main__'):
name = 'MAVProxy.modules.mavproxy_map.mp_tile'
stream = pkg_resources.resource_stream(name, ('data/%s' % filename)).read()
raw = np.fromstring(stream, dtype=np.uint8)
except Exception:
stream = open(os.path.join(_... | null | null | null | load an icon from the data directory | pcsd | def mp icon filename try import pkg resources name = name if name == ' main ' name = 'MAV Proxy modules mavproxy map mp tile' stream = pkg resources resource stream name 'data/%s' % filename read raw = np fromstring stream dtype=np uint8 except Exception stream = open os path join file 'data' filename read raw = np fro... | 7683 | def mp_icon(filename):
try:
import pkg_resources
name = __name__
if (name == '__main__'):
name = 'MAVProxy.modules.mavproxy_map.mp_tile'
stream = pkg_resources.resource_stream(name, ('data/%s' % filename)).read()
raw = np.fromstring(stream, dtype=np.uint8)
except Exception:
stream = open(os.path.join(_... | load an icon from the data directory | load an icon from the data directory | Question:
What does this function do?
Code:
def mp_icon(filename):
try:
import pkg_resources
name = __name__
if (name == '__main__'):
name = 'MAVProxy.modules.mavproxy_map.mp_tile'
stream = pkg_resources.resource_stream(name, ('data/%s' % filename)).read()
raw = np.fromstring(stream, dtype=np.uint8)
e... |
null | null | null | What does this function do? | def assignment():
def prep(r):
mission_date = s3db.deploy_mission.created_on
mission_date.represent = (lambda d: s3base.S3DateTime.date_represent(d, utc=True))
if r.record:
table = r.resource.table
table.mission_id.writable = False
table.human_resource_id.writable = False
if (r.representation == 'popu... | null | null | null | RESTful CRUD Controller | pcsd | def assignment def prep r mission date = s3db deploy mission created on mission date represent = lambda d s3base S3Date Time date represent d utc=True if r record table = r resource table table mission id writable = False table human resource id writable = False if r representation == 'popup' r resource configure inser... | 7692 | def assignment():
def prep(r):
mission_date = s3db.deploy_mission.created_on
mission_date.represent = (lambda d: s3base.S3DateTime.date_represent(d, utc=True))
if r.record:
table = r.resource.table
table.mission_id.writable = False
table.human_resource_id.writable = False
if (r.representation == 'popu... | RESTful CRUD Controller | restful crud controller | Question:
What does this function do?
Code:
def assignment():
def prep(r):
mission_date = s3db.deploy_mission.created_on
mission_date.represent = (lambda d: s3base.S3DateTime.date_represent(d, utc=True))
if r.record:
table = r.resource.table
table.mission_id.writable = False
table.human_resource_id.w... |
null | null | null | What does this function do? | def res_json(res, jsontype='JSON', exception=PluginError):
try:
jsondata = res.json()
except ValueError as err:
if (len(res.text) > 35):
snippet = (res.text[:35] + '...')
else:
snippet = res.text
raise exception('Unable to parse {0}: {1} ({2})'.format(jsontype, err, snippet))
return jsondata
| null | null | null | This function is deprecated. | pcsd | def res json res jsontype='JSON' exception=Plugin Error try jsondata = res json except Value Error as err if len res text > 35 snippet = res text[ 35] + ' ' else snippet = res text raise exception 'Unable to parse {0} {1} {2} ' format jsontype err snippet return jsondata | 7712 | def res_json(res, jsontype='JSON', exception=PluginError):
try:
jsondata = res.json()
except ValueError as err:
if (len(res.text) > 35):
snippet = (res.text[:35] + '...')
else:
snippet = res.text
raise exception('Unable to parse {0}: {1} ({2})'.format(jsontype, err, snippet))
return jsondata
| This function is deprecated. | this function is deprecated . | Question:
What does this function do?
Code:
def res_json(res, jsontype='JSON', exception=PluginError):
try:
jsondata = res.json()
except ValueError as err:
if (len(res.text) > 35):
snippet = (res.text[:35] + '...')
else:
snippet = res.text
raise exception('Unable to parse {0}: {1} ({2})'.format(jsont... |
null | null | null | What does this function do? | def lookup_needs_distinct(opts, lookup_path):
field_name = lookup_path.split('__', 1)[0]
field = opts.get_field_by_name(field_name)[0]
if ((hasattr(field, 'rel') and isinstance(field.rel, models.ManyToManyRel)) or (isinstance(field, models.related.RelatedObject) and (not field.field.unique))):
return True
return ... | null | null | null | Returns True if \'distinct()\' should be used to query the given lookup path. | pcsd | def lookup needs distinct opts lookup path field name = lookup path split ' ' 1 [0] field = opts get field by name field name [0] if hasattr field 'rel' and isinstance field rel models Many To Many Rel or isinstance field models related Related Object and not field field unique return True return False | 7722 | def lookup_needs_distinct(opts, lookup_path):
field_name = lookup_path.split('__', 1)[0]
field = opts.get_field_by_name(field_name)[0]
if ((hasattr(field, 'rel') and isinstance(field.rel, models.ManyToManyRel)) or (isinstance(field, models.related.RelatedObject) and (not field.field.unique))):
return True
return ... | Returns True if \'distinct()\' should be used to query the given lookup path. | returns true if distinct ( ) should be used to query the given lookup path . | Question:
What does this function do?
Code:
def lookup_needs_distinct(opts, lookup_path):
field_name = lookup_path.split('__', 1)[0]
field = opts.get_field_by_name(field_name)[0]
if ((hasattr(field, 'rel') and isinstance(field.rel, models.ManyToManyRel)) or (isinstance(field, models.related.RelatedObject) and (no... |
null | null | null | What does this function do? | def s3_endpoint_for_region(region):
region = _fix_region(region)
if ((not region) or (region == _S3_REGION_WITH_NO_LOCATION_CONSTRAINT)):
return _S3_REGIONLESS_ENDPOINT
else:
return (_S3_REGION_ENDPOINT % {'region': region})
| null | null | null | Get the host for S3 in the given AWS region.
This will accept ``\'\'`` for region as well, so it\'s fine to
use location constraint in place of region. | pcsd | def s3 endpoint for region region region = fix region region if not region or region == S3 REGION WITH NO LOCATION CONSTRAINT return S3 REGIONLESS ENDPOINT else return S3 REGION ENDPOINT % {'region' region} | 7723 | def s3_endpoint_for_region(region):
region = _fix_region(region)
if ((not region) or (region == _S3_REGION_WITH_NO_LOCATION_CONSTRAINT)):
return _S3_REGIONLESS_ENDPOINT
else:
return (_S3_REGION_ENDPOINT % {'region': region})
| Get the host for S3 in the given AWS region.
This will accept ``\'\'`` for region as well, so it\'s fine to
use location constraint in place of region. | get the host for s3 in the given aws region . | Question:
What does this function do?
Code:
def s3_endpoint_for_region(region):
region = _fix_region(region)
if ((not region) or (region == _S3_REGION_WITH_NO_LOCATION_CONSTRAINT)):
return _S3_REGIONLESS_ENDPOINT
else:
return (_S3_REGION_ENDPOINT % {'region': region})
|
null | null | null | What does this function do? | def DefineFlags(flag_values=FLAGS):
module_bar.DefineFlags(flag_values=flag_values)
gflags.DEFINE_boolean('tmod_foo_bool', True, 'Boolean flag from module foo.', flag_values=flag_values)
gflags.DEFINE_string('tmod_foo_str', 'default', 'String flag.', flag_values=flag_values)
gflags.DEFINE_integer('tmod_foo_int', 3,... | null | null | null | Defines a few flags. | pcsd | def Define Flags flag values=FLAGS module bar Define Flags flag values=flag values gflags DEFINE boolean 'tmod foo bool' True 'Boolean flag from module foo ' flag values=flag values gflags DEFINE string 'tmod foo str' 'default' 'String flag ' flag values=flag values gflags DEFINE integer 'tmod foo int' 3 'Sample int fl... | 7731 | def DefineFlags(flag_values=FLAGS):
module_bar.DefineFlags(flag_values=flag_values)
gflags.DEFINE_boolean('tmod_foo_bool', True, 'Boolean flag from module foo.', flag_values=flag_values)
gflags.DEFINE_string('tmod_foo_str', 'default', 'String flag.', flag_values=flag_values)
gflags.DEFINE_integer('tmod_foo_int', 3,... | Defines a few flags. | defines a few flags . | Question:
What does this function do?
Code:
def DefineFlags(flag_values=FLAGS):
module_bar.DefineFlags(flag_values=flag_values)
gflags.DEFINE_boolean('tmod_foo_bool', True, 'Boolean flag from module foo.', flag_values=flag_values)
gflags.DEFINE_string('tmod_foo_str', 'default', 'String flag.', flag_values=flag_va... |
null | null | null | What does this function do? | def make_wiki():
from simplewiki import SimpleWiki
database_uri = os.environ.get('SIMPLEWIKI_DATABASE_URI')
return SimpleWiki((database_uri or 'sqlite:////tmp/simplewiki.db'))
| null | null | null | Helper function that creates a new wiki instance. | pcsd | def make wiki from simplewiki import Simple Wiki database uri = os environ get 'SIMPLEWIKI DATABASE URI' return Simple Wiki database uri or 'sqlite ////tmp/simplewiki db' | 7732 | def make_wiki():
from simplewiki import SimpleWiki
database_uri = os.environ.get('SIMPLEWIKI_DATABASE_URI')
return SimpleWiki((database_uri or 'sqlite:////tmp/simplewiki.db'))
| Helper function that creates a new wiki instance. | helper function that creates a new wiki instance . | Question:
What does this function do?
Code:
def make_wiki():
from simplewiki import SimpleWiki
database_uri = os.environ.get('SIMPLEWIKI_DATABASE_URI')
return SimpleWiki((database_uri or 'sqlite:////tmp/simplewiki.db'))
|
null | null | null | What does this function do? | def get_namespace(tag):
m = re.match('^{(.*?)}', tag)
namespace = (m.group(1) if m else '')
if (not namespace.startswith('http://www.mediawiki.org/xml/export-')):
raise ValueError(('%s not recognized as MediaWiki dump namespace' % namespace))
return namespace
| null | null | null | Returns the namespace of tag. | pcsd | def get namespace tag m = re match '^{ *? }' tag namespace = m group 1 if m else '' if not namespace startswith 'http //www mediawiki org/xml/export-' raise Value Error '%s not recognized as Media Wiki dump namespace' % namespace return namespace | 7739 | def get_namespace(tag):
m = re.match('^{(.*?)}', tag)
namespace = (m.group(1) if m else '')
if (not namespace.startswith('http://www.mediawiki.org/xml/export-')):
raise ValueError(('%s not recognized as MediaWiki dump namespace' % namespace))
return namespace
| Returns the namespace of tag. | returns the namespace of tag . | Question:
What does this function do?
Code:
def get_namespace(tag):
m = re.match('^{(.*?)}', tag)
namespace = (m.group(1) if m else '')
if (not namespace.startswith('http://www.mediawiki.org/xml/export-')):
raise ValueError(('%s not recognized as MediaWiki dump namespace' % namespace))
return namespace
|
null | null | null | What does this function do? | def scan(opts):
ret = {}
for (root, dirs, files) in os.walk(opts['root']):
for fn_ in files:
full = os.path.join(root, fn_)
if full.endswith('.py'):
ret.update(mod_data(opts, full))
return ret
| null | null | null | Scan the provided root for python source files | pcsd | def scan opts ret = {} for root dirs files in os walk opts['root'] for fn in files full = os path join root fn if full endswith ' py' ret update mod data opts full return ret | 7745 | def scan(opts):
ret = {}
for (root, dirs, files) in os.walk(opts['root']):
for fn_ in files:
full = os.path.join(root, fn_)
if full.endswith('.py'):
ret.update(mod_data(opts, full))
return ret
| Scan the provided root for python source files | scan the provided root for python source files | Question:
What does this function do?
Code:
def scan(opts):
ret = {}
for (root, dirs, files) in os.walk(opts['root']):
for fn_ in files:
full = os.path.join(root, fn_)
if full.endswith('.py'):
ret.update(mod_data(opts, full))
return ret
|
null | null | null | What does this function do? | @domain_constructor(loss_target=0)
def quadratic1():
return {'loss': ((hp.uniform('x', (-5), 5) - 3) ** 2), 'status': base.STATUS_OK}
| null | null | null | About the simplest problem you could ask for:
optimize a one-variable quadratic function. | pcsd | @domain constructor loss target=0 def quadratic1 return {'loss' hp uniform 'x' -5 5 - 3 ** 2 'status' base STATUS OK} | 7747 | @domain_constructor(loss_target=0)
def quadratic1():
return {'loss': ((hp.uniform('x', (-5), 5) - 3) ** 2), 'status': base.STATUS_OK}
| About the simplest problem you could ask for:
optimize a one-variable quadratic function. | about the simplest problem you could ask for : optimize a one - variable quadratic function . | Question:
What does this function do?
Code:
@domain_constructor(loss_target=0)
def quadratic1():
return {'loss': ((hp.uniform('x', (-5), 5) - 3) ** 2), 'status': base.STATUS_OK}
|
null | null | null | What does this function do? | def get_module_by_usage_id(request, course_id, usage_id, disable_staff_debug_info=False, course=None):
user = request.user
try:
course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id)
usage_key = course_id.make_usage_key_from_deprecated_string(unquote_slashes(usage_id))
except InvalidKeyError:
ra... | null | null | null | Gets a module instance based on its `usage_id` in a course, for a given request/user
Returns (instance, tracking_context) | pcsd | def get module by usage id request course id usage id disable staff debug info=False course=None user = request user try course id = Slash Separated Course Key from deprecated string course id usage key = course id make usage key from deprecated string unquote slashes usage id except Invalid Key Error raise Http404 'In... | 7750 | def get_module_by_usage_id(request, course_id, usage_id, disable_staff_debug_info=False, course=None):
user = request.user
try:
course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id)
usage_key = course_id.make_usage_key_from_deprecated_string(unquote_slashes(usage_id))
except InvalidKeyError:
ra... | Gets a module instance based on its `usage_id` in a course, for a given request/user
Returns (instance, tracking_context) | gets a module instance based on its usage _ id in a course , for a given request / user | Question:
What does this function do?
Code:
def get_module_by_usage_id(request, course_id, usage_id, disable_staff_debug_info=False, course=None):
user = request.user
try:
course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id)
usage_key = course_id.make_usage_key_from_deprecated_string(unquote_s... |
null | null | null | What does this function do? | def is_valid_dot_atom(value):
return (isinstance(value, six.string_types) and (not (value[0] == '.')) and (not (value[(-1)] == '.')) and set(value).issubset(valid_dot_atom_characters))
| null | null | null | Validate an input string as an RFC 2822 dot-atom-text value. | pcsd | def is valid dot atom value return isinstance value six string types and not value[0] == ' ' and not value[ -1 ] == ' ' and set value issubset valid dot atom characters | 7756 | def is_valid_dot_atom(value):
return (isinstance(value, six.string_types) and (not (value[0] == '.')) and (not (value[(-1)] == '.')) and set(value).issubset(valid_dot_atom_characters))
| Validate an input string as an RFC 2822 dot-atom-text value. | validate an input string as an rfc 2822 dot - atom - text value . | Question:
What does this function do?
Code:
def is_valid_dot_atom(value):
return (isinstance(value, six.string_types) and (not (value[0] == '.')) and (not (value[(-1)] == '.')) and set(value).issubset(valid_dot_atom_characters))
|
null | null | null | What does this function do? | def _num_cpus_windows():
return os.environ.get('NUMBER_OF_PROCESSORS')
| null | null | null | Return the number of active CPUs on a Windows system. | pcsd | def num cpus windows return os environ get 'NUMBER OF PROCESSORS' | 7762 | def _num_cpus_windows():
return os.environ.get('NUMBER_OF_PROCESSORS')
| Return the number of active CPUs on a Windows system. | return the number of active cpus on a windows system . | Question:
What does this function do?
Code:
def _num_cpus_windows():
return os.environ.get('NUMBER_OF_PROCESSORS')
|
null | null | null | What does this function do? | def wrap_socket(socket, domain, ca_crt, ca_key, ca_pass, certs_folder, success=None, failure=None, io=None, **options):
options.setdefault('do_handshake_on_connect', False)
options.setdefault('ssl_version', ssl.PROTOCOL_SSLv23)
options.setdefault('server_side', True)
if (domain.count('.') >= 3):
(key, cert) = gen... | null | null | null | Wrap an active socket in an SSL socket. | pcsd | def wrap socket socket domain ca crt ca key ca pass certs folder success=None failure=None io=None **options options setdefault 'do handshake on connect' False options setdefault 'ssl version' ssl PROTOCOL SS Lv23 options setdefault 'server side' True if domain count ' ' >= 3 key cert = gen signed cert '* ' + ' ' join ... | 7778 | def wrap_socket(socket, domain, ca_crt, ca_key, ca_pass, certs_folder, success=None, failure=None, io=None, **options):
options.setdefault('do_handshake_on_connect', False)
options.setdefault('ssl_version', ssl.PROTOCOL_SSLv23)
options.setdefault('server_side', True)
if (domain.count('.') >= 3):
(key, cert) = gen... | Wrap an active socket in an SSL socket. | wrap an active socket in an ssl socket . | Question:
What does this function do?
Code:
def wrap_socket(socket, domain, ca_crt, ca_key, ca_pass, certs_folder, success=None, failure=None, io=None, **options):
options.setdefault('do_handshake_on_connect', False)
options.setdefault('ssl_version', ssl.PROTOCOL_SSLv23)
options.setdefault('server_side', True)
i... |
null | null | null | What does this function do? | def drain_consumer(consumer, limit=1, timeout=None, callbacks=None):
acc = deque()
def on_message(body, message):
acc.append((body, message))
consumer.callbacks = ([on_message] + (callbacks or []))
with consumer:
for _ in eventloop(consumer.channel.connection.client, limit=limit, timeout=timeout, ignore_timeout... | null | null | null | Drain messages from consumer instance. | pcsd | def drain consumer consumer limit=1 timeout=None callbacks=None acc = deque def on message body message acc append body message consumer callbacks = [on message] + callbacks or [] with consumer for in eventloop consumer channel connection client limit=limit timeout=timeout ignore timeouts=True try yield acc popleft exc... | 7781 | def drain_consumer(consumer, limit=1, timeout=None, callbacks=None):
acc = deque()
def on_message(body, message):
acc.append((body, message))
consumer.callbacks = ([on_message] + (callbacks or []))
with consumer:
for _ in eventloop(consumer.channel.connection.client, limit=limit, timeout=timeout, ignore_timeout... | Drain messages from consumer instance. | drain messages from consumer instance . | Question:
What does this function do?
Code:
def drain_consumer(consumer, limit=1, timeout=None, callbacks=None):
acc = deque()
def on_message(body, message):
acc.append((body, message))
consumer.callbacks = ([on_message] + (callbacks or []))
with consumer:
for _ in eventloop(consumer.channel.connection.clien... |
null | null | null | What does this function do? | @contextfilter
def group_by_letter(context, object_list):
res = {}
for x in object_list:
r = re.search('^[a-zA-Z]', x.name)
if r:
key = r.group().lower()
if (key not in res):
res[key] = [x]
else:
res[key].append(x)
n = re.search('^[0-9_]', x.name)
if n:
if ('#' not in res):
res['#'] = ... | null | null | null | Group contacts by letter | pcsd | @contextfilter def group by letter context object list res = {} for x in object list r = re search '^[a-z A-Z]' x name if r key = r group lower if key not in res res[key] = [x] else res[key] append x n = re search '^[0-9 ]' x name if n if '#' not in res res['#'] = [x] else res['#'] append x if not n and not r if '#' no... | 7782 | @contextfilter
def group_by_letter(context, object_list):
res = {}
for x in object_list:
r = re.search('^[a-zA-Z]', x.name)
if r:
key = r.group().lower()
if (key not in res):
res[key] = [x]
else:
res[key].append(x)
n = re.search('^[0-9_]', x.name)
if n:
if ('#' not in res):
res['#'] = ... | Group contacts by letter | group contacts by letter | Question:
What does this function do?
Code:
@contextfilter
def group_by_letter(context, object_list):
res = {}
for x in object_list:
r = re.search('^[a-zA-Z]', x.name)
if r:
key = r.group().lower()
if (key not in res):
res[key] = [x]
else:
res[key].append(x)
n = re.search('^[0-9_]', x.name)
... |
null | null | null | What does this function do? | def read_forward_solution_eeg(*args, **kwargs):
fwd = read_forward_solution(*args, **kwargs)
fwd = pick_types_forward(fwd, meg=False, eeg=True)
return fwd
| null | null | null | Read EEG forward. | pcsd | def read forward solution eeg *args **kwargs fwd = read forward solution *args **kwargs fwd = pick types forward fwd meg=False eeg=True return fwd | 7790 | def read_forward_solution_eeg(*args, **kwargs):
fwd = read_forward_solution(*args, **kwargs)
fwd = pick_types_forward(fwd, meg=False, eeg=True)
return fwd
| Read EEG forward. | read eeg forward . | Question:
What does this function do?
Code:
def read_forward_solution_eeg(*args, **kwargs):
fwd = read_forward_solution(*args, **kwargs)
fwd = pick_types_forward(fwd, meg=False, eeg=True)
return fwd
|
null | null | null | What does this function do? | def append_period(text):
if (text[(-1)] == '"'):
return (text[0:(-1)] + '."')
return text
| null | null | null | Append a period at the end of the sentence | pcsd | def append period text if text[ -1 ] == '"' return text[0 -1 ] + ' "' return text | 7803 | def append_period(text):
if (text[(-1)] == '"'):
return (text[0:(-1)] + '."')
return text
| Append a period at the end of the sentence | append a period at the end of the sentence | Question:
What does this function do?
Code:
def append_period(text):
if (text[(-1)] == '"'):
return (text[0:(-1)] + '."')
return text
|
null | null | null | What does this function do? | def parse(tmpl_str):
validate_template_limit(six.text_type(tmpl_str))
tpl = simple_parse(tmpl_str)
if (not (('HeatTemplateFormatVersion' in tpl) or ('heat_template_version' in tpl) or ('AWSTemplateFormatVersion' in tpl))):
raise ValueError(_('Template format version not found.'))
return tpl
| null | null | null | Takes a string and returns a dict containing the parsed structure.
This includes determination of whether the string is using the
JSON or YAML format. | pcsd | def parse tmpl str validate template limit six text type tmpl str tpl = simple parse tmpl str if not 'Heat Template Format Version' in tpl or 'heat template version' in tpl or 'AWS Template Format Version' in tpl raise Value Error 'Template format version not found ' return tpl | 7808 | def parse(tmpl_str):
validate_template_limit(six.text_type(tmpl_str))
tpl = simple_parse(tmpl_str)
if (not (('HeatTemplateFormatVersion' in tpl) or ('heat_template_version' in tpl) or ('AWSTemplateFormatVersion' in tpl))):
raise ValueError(_('Template format version not found.'))
return tpl
| Takes a string and returns a dict containing the parsed structure.
This includes determination of whether the string is using the
JSON or YAML format. | takes a string and returns a dict containing the parsed structure . | Question:
What does this function do?
Code:
def parse(tmpl_str):
validate_template_limit(six.text_type(tmpl_str))
tpl = simple_parse(tmpl_str)
if (not (('HeatTemplateFormatVersion' in tpl) or ('heat_template_version' in tpl) or ('AWSTemplateFormatVersion' in tpl))):
raise ValueError(_('Template format version n... |
null | null | null | What does this function do? | def filter(names, pat):
import os, posixpath
result = []
pat = os.path.normcase(pat)
try:
re_pat = _cache[pat]
except KeyError:
res = translate(pat)
if (len(_cache) >= _MAXCACHE):
_cache.clear()
_cache[pat] = re_pat = re.compile(res)
match = re_pat.match
if (os.path is posixpath):
for name in names:... | null | null | null | Return the subset of the list NAMES that match PAT | pcsd | def filter names pat import os posixpath result = [] pat = os path normcase pat try re pat = cache[pat] except Key Error res = translate pat if len cache >= MAXCACHE cache clear cache[pat] = re pat = re compile res match = re pat match if os path is posixpath for name in names if match name result append name else for ... | 7818 | def filter(names, pat):
import os, posixpath
result = []
pat = os.path.normcase(pat)
try:
re_pat = _cache[pat]
except KeyError:
res = translate(pat)
if (len(_cache) >= _MAXCACHE):
_cache.clear()
_cache[pat] = re_pat = re.compile(res)
match = re_pat.match
if (os.path is posixpath):
for name in names:... | Return the subset of the list NAMES that match PAT | return the subset of the list names that match pat | Question:
What does this function do?
Code:
def filter(names, pat):
import os, posixpath
result = []
pat = os.path.normcase(pat)
try:
re_pat = _cache[pat]
except KeyError:
res = translate(pat)
if (len(_cache) >= _MAXCACHE):
_cache.clear()
_cache[pat] = re_pat = re.compile(res)
match = re_pat.match
... |
null | null | null | What does this function do? | def md5sum(filename, use_sudo=False):
func = ((use_sudo and run_as_root) or run)
with settings(hide('running', 'stdout', 'stderr', 'warnings'), warn_only=True):
if exists(u'/usr/bin/md5sum'):
res = func((u'/usr/bin/md5sum %(filename)s' % locals()))
elif exists(u'/sbin/md5'):
res = func((u'/sbin/md5 -r %(fil... | null | null | null | Compute the MD5 sum of a file. | pcsd | def md5sum filename use sudo=False func = use sudo and run as root or run with settings hide 'running' 'stdout' 'stderr' 'warnings' warn only=True if exists u'/usr/bin/md5sum' res = func u'/usr/bin/md5sum % filename s' % locals elif exists u'/sbin/md5' res = func u'/sbin/md5 -r % filename s' % locals elif exists u'/opt... | 7820 | def md5sum(filename, use_sudo=False):
func = ((use_sudo and run_as_root) or run)
with settings(hide('running', 'stdout', 'stderr', 'warnings'), warn_only=True):
if exists(u'/usr/bin/md5sum'):
res = func((u'/usr/bin/md5sum %(filename)s' % locals()))
elif exists(u'/sbin/md5'):
res = func((u'/sbin/md5 -r %(fil... | Compute the MD5 sum of a file. | compute the md5 sum of a file . | Question:
What does this function do?
Code:
def md5sum(filename, use_sudo=False):
func = ((use_sudo and run_as_root) or run)
with settings(hide('running', 'stdout', 'stderr', 'warnings'), warn_only=True):
if exists(u'/usr/bin/md5sum'):
res = func((u'/usr/bin/md5sum %(filename)s' % locals()))
elif exists(u'/... |
null | null | null | What does this function do? | def check_token(code, tokens):
lx = XonshLexer()
tks = list(lx.get_tokens(code))
for tk in tokens:
while tks:
if (tk == tks[0]):
break
tks = tks[1:]
else:
msg = 'Token {!r} missing: {!r}'.format(tk, list(lx.get_tokens(code)))
pytest.fail(msg)
break
| null | null | null | Make sure that all tokens appears in code in order | pcsd | def check token code tokens lx = Xonsh Lexer tks = list lx get tokens code for tk in tokens while tks if tk == tks[0] break tks = tks[1 ] else msg = 'Token {!r} missing {!r}' format tk list lx get tokens code pytest fail msg break | 7825 | def check_token(code, tokens):
lx = XonshLexer()
tks = list(lx.get_tokens(code))
for tk in tokens:
while tks:
if (tk == tks[0]):
break
tks = tks[1:]
else:
msg = 'Token {!r} missing: {!r}'.format(tk, list(lx.get_tokens(code)))
pytest.fail(msg)
break
| Make sure that all tokens appears in code in order | make sure that all tokens appears in code in order | Question:
What does this function do?
Code:
def check_token(code, tokens):
lx = XonshLexer()
tks = list(lx.get_tokens(code))
for tk in tokens:
while tks:
if (tk == tks[0]):
break
tks = tks[1:]
else:
msg = 'Token {!r} missing: {!r}'.format(tk, list(lx.get_tokens(code)))
pytest.fail(msg)
brea... |
null | null | null | What does this function do? | def get_vm_size(vm_):
vm_size = config.get_cloud_config_value('size', vm_, __opts__)
ram = avail_sizes()[vm_size]['RAM']
if vm_size.startswith('Linode'):
vm_size = vm_size.replace('Linode ', '')
if (ram == int(vm_size)):
return ram
else:
raise SaltCloudNotFound('The specified size, {0}, could not be found.'.... | null | null | null | Returns the VM\'s size.
vm\_
The VM to get the size for. | pcsd | def get vm size vm vm size = config get cloud config value 'size' vm opts ram = avail sizes [vm size]['RAM'] if vm size startswith 'Linode' vm size = vm size replace 'Linode ' '' if ram == int vm size return ram else raise Salt Cloud Not Found 'The specified size {0} could not be found ' format vm size | 7832 | def get_vm_size(vm_):
vm_size = config.get_cloud_config_value('size', vm_, __opts__)
ram = avail_sizes()[vm_size]['RAM']
if vm_size.startswith('Linode'):
vm_size = vm_size.replace('Linode ', '')
if (ram == int(vm_size)):
return ram
else:
raise SaltCloudNotFound('The specified size, {0}, could not be found.'.... | Returns the VM\'s size.
vm\_
The VM to get the size for. | returns the vms size . | Question:
What does this function do?
Code:
def get_vm_size(vm_):
vm_size = config.get_cloud_config_value('size', vm_, __opts__)
ram = avail_sizes()[vm_size]['RAM']
if vm_size.startswith('Linode'):
vm_size = vm_size.replace('Linode ', '')
if (ram == int(vm_size)):
return ram
else:
raise SaltCloudNotFound(... |
null | null | null | What does this function do? | def get_format(format_type):
format_type = smart_str(format_type)
if settings.USE_L10N:
cache_key = (format_type, get_language())
try:
return (_format_cache[cache_key] or getattr(settings, format_type))
except KeyError:
for module in get_format_modules():
try:
val = getattr(module, format_type)
... | null | null | null | For a specific format type, returns the format for the current
language (locale), defaults to the format in the settings.
format_type is the name of the format, e.g. \'DATE_FORMAT\' | pcsd | def get format format type format type = smart str format type if settings USE L10N cache key = format type get language try return format cache[cache key] or getattr settings format type except Key Error for module in get format modules try val = getattr module format type format cache[cache key] = val return val exce... | 7839 | def get_format(format_type):
format_type = smart_str(format_type)
if settings.USE_L10N:
cache_key = (format_type, get_language())
try:
return (_format_cache[cache_key] or getattr(settings, format_type))
except KeyError:
for module in get_format_modules():
try:
val = getattr(module, format_type)
... | For a specific format type, returns the format for the current
language (locale), defaults to the format in the settings.
format_type is the name of the format, e.g. \'DATE_FORMAT\' | for a specific format type , returns the format for the current language , defaults to the format in the settings . | Question:
What does this function do?
Code:
def get_format(format_type):
format_type = smart_str(format_type)
if settings.USE_L10N:
cache_key = (format_type, get_language())
try:
return (_format_cache[cache_key] or getattr(settings, format_type))
except KeyError:
for module in get_format_modules():
... |
null | null | null | What does this function do? | def _partition_estimators(n_estimators, n_jobs):
n_jobs = min(_get_n_jobs(n_jobs), n_estimators)
n_estimators_per_job = ((n_estimators // n_jobs) * np.ones(n_jobs, dtype=np.int))
n_estimators_per_job[:(n_estimators % n_jobs)] += 1
starts = np.cumsum(n_estimators_per_job)
return (n_jobs, n_estimators_per_job.tolist... | null | null | null | Private function used to partition estimators between jobs. | pcsd | def partition estimators n estimators n jobs n jobs = min get n jobs n jobs n estimators n estimators per job = n estimators // n jobs * np ones n jobs dtype=np int n estimators per job[ n estimators % n jobs ] += 1 starts = np cumsum n estimators per job return n jobs n estimators per job tolist [0] + starts tolist | 7840 | def _partition_estimators(n_estimators, n_jobs):
n_jobs = min(_get_n_jobs(n_jobs), n_estimators)
n_estimators_per_job = ((n_estimators // n_jobs) * np.ones(n_jobs, dtype=np.int))
n_estimators_per_job[:(n_estimators % n_jobs)] += 1
starts = np.cumsum(n_estimators_per_job)
return (n_jobs, n_estimators_per_job.tolist... | Private function used to partition estimators between jobs. | private function used to partition estimators between jobs . | Question:
What does this function do?
Code:
def _partition_estimators(n_estimators, n_jobs):
n_jobs = min(_get_n_jobs(n_jobs), n_estimators)
n_estimators_per_job = ((n_estimators // n_jobs) * np.ones(n_jobs, dtype=np.int))
n_estimators_per_job[:(n_estimators % n_jobs)] += 1
starts = np.cumsum(n_estimators_per_jo... |
null | null | null | What does this function do? | def get_user_password():
return ('root', '')
| null | null | null | Returns a tuple (user, password). | pcsd | def get user password return 'root' '' | 7844 | def get_user_password():
return ('root', '')
| Returns a tuple (user, password). | returns a tuple . | Question:
What does this function do?
Code:
def get_user_password():
return ('root', '')
|
null | null | null | What does this function do? | def add_advanced_component(page, menu_index, name):
page.wait_for_component_menu()
click_css(page, 'button>span.large-advanced-icon', menu_index, require_notification=False)
page.wait_for_element_visibility('.new-component-advanced', 'Advanced component menu is visible')
component_css = 'button[data-category={}]'.f... | null | null | null | Adds an instance of the advanced component with the specified name.
menu_index specifies which instance of the menus should be used (based on vertical
placement within the page). | pcsd | def add advanced component page menu index name page wait for component menu click css page 'button>span large-advanced-icon' menu index require notification=False page wait for element visibility ' new-component-advanced' 'Advanced component menu is visible' component css = 'button[data-category={}]' format name page ... | 7854 | def add_advanced_component(page, menu_index, name):
page.wait_for_component_menu()
click_css(page, 'button>span.large-advanced-icon', menu_index, require_notification=False)
page.wait_for_element_visibility('.new-component-advanced', 'Advanced component menu is visible')
component_css = 'button[data-category={}]'.f... | Adds an instance of the advanced component with the specified name.
menu_index specifies which instance of the menus should be used (based on vertical
placement within the page). | adds an instance of the advanced component with the specified name . | Question:
What does this function do?
Code:
def add_advanced_component(page, menu_index, name):
page.wait_for_component_menu()
click_css(page, 'button>span.large-advanced-icon', menu_index, require_notification=False)
page.wait_for_element_visibility('.new-component-advanced', 'Advanced component menu is visible'... |
null | null | null | What does this function do? | def _add_object(obj_type, image, image2, xpos, ypos):
obj_size = random.randint(8, 10)
channel = random.randint(0, 2)
move = random.randint(6, 10)
obj = np.zeros([obj_size, obj_size, 3])
if (obj_type == 'rectangle'):
xpos2 = (xpos + move)
ypos2 = ypos
for i in xrange(obj_size):
obj[i, 0:(i + 1), channel] ... | null | null | null | Add a moving obj to two consecutive images. | pcsd | def add object obj type image image2 xpos ypos obj size = random randint 8 10 channel = random randint 0 2 move = random randint 6 10 obj = np zeros [obj size obj size 3] if obj type == 'rectangle' xpos2 = xpos + move ypos2 = ypos for i in xrange obj size obj[i 0 i + 1 channel] = [1 0 for in xrange i + 1 ] elif obj typ... | 7858 | def _add_object(obj_type, image, image2, xpos, ypos):
obj_size = random.randint(8, 10)
channel = random.randint(0, 2)
move = random.randint(6, 10)
obj = np.zeros([obj_size, obj_size, 3])
if (obj_type == 'rectangle'):
xpos2 = (xpos + move)
ypos2 = ypos
for i in xrange(obj_size):
obj[i, 0:(i + 1), channel] ... | Add a moving obj to two consecutive images. | add a moving obj to two consecutive images . | Question:
What does this function do?
Code:
def _add_object(obj_type, image, image2, xpos, ypos):
obj_size = random.randint(8, 10)
channel = random.randint(0, 2)
move = random.randint(6, 10)
obj = np.zeros([obj_size, obj_size, 3])
if (obj_type == 'rectangle'):
xpos2 = (xpos + move)
ypos2 = ypos
for i in x... |
null | null | null | What does this function do? | def _AppendOrReturn(append, element):
if ((append is not None) and (element is not None)):
if (isinstance(element, list) or isinstance(element, tuple)):
append.extend(element)
else:
append.append(element)
else:
return element
| null | null | null | If |append| is None, simply return |element|. If |append| is not None,
then add |element| to it, adding each item in |element| if it\'s a list or
tuple. | pcsd | def Append Or Return append element if append is not None and element is not None if isinstance element list or isinstance element tuple append extend element else append append element else return element | 7871 | def _AppendOrReturn(append, element):
if ((append is not None) and (element is not None)):
if (isinstance(element, list) or isinstance(element, tuple)):
append.extend(element)
else:
append.append(element)
else:
return element
| If |append| is None, simply return |element|. If |append| is not None,
then add |element| to it, adding each item in |element| if it\'s a list or
tuple. | if | append | is none , simply return | element | . | Question:
What does this function do?
Code:
def _AppendOrReturn(append, element):
if ((append is not None) and (element is not None)):
if (isinstance(element, list) or isinstance(element, tuple)):
append.extend(element)
else:
append.append(element)
else:
return element
|
null | null | null | What does this function do? | @pytest.mark.parametrize(u'text,expected_tokens', [(u"l'avion", [u"l'", u'avion']), (u"j'ai", [u"j'", u'ai'])])
def test_issue768(fr_tokenizer_w_infix, text, expected_tokens):
tokens = fr_tokenizer_w_infix(text)
assert (len(tokens) == 2)
assert ([t.text for t in tokens] == expected_tokens)
| null | null | null | Allow zero-width \'infix\' token during the tokenization process. | pcsd | @pytest mark parametrize u'text expected tokens' [ u"l'avion" [u"l'" u'avion'] u"j'ai" [u"j'" u'ai'] ] def test issue768 fr tokenizer w infix text expected tokens tokens = fr tokenizer w infix text assert len tokens == 2 assert [t text for t in tokens] == expected tokens | 7877 | @pytest.mark.parametrize(u'text,expected_tokens', [(u"l'avion", [u"l'", u'avion']), (u"j'ai", [u"j'", u'ai'])])
def test_issue768(fr_tokenizer_w_infix, text, expected_tokens):
tokens = fr_tokenizer_w_infix(text)
assert (len(tokens) == 2)
assert ([t.text for t in tokens] == expected_tokens)
| Allow zero-width \'infix\' token during the tokenization process. | allow zero - width infix token during the tokenization process . | Question:
What does this function do?
Code:
@pytest.mark.parametrize(u'text,expected_tokens', [(u"l'avion", [u"l'", u'avion']), (u"j'ai", [u"j'", u'ai'])])
def test_issue768(fr_tokenizer_w_infix, text, expected_tokens):
tokens = fr_tokenizer_w_infix(text)
assert (len(tokens) == 2)
assert ([t.text for t in tokens]... |
null | null | null | What does this function do? | def morsel_to_cookie(morsel):
c = create_cookie(name=morsel.key, value=morsel.value, version=(morsel['version'] or 0), port=None, port_specified=False, domain=morsel['domain'], domain_specified=bool(morsel['domain']), domain_initial_dot=morsel['domain'].startswith('.'), path=morsel['path'], path_specified=bool(morsel[... | null | null | null | Convert a Morsel object into a Cookie containing the one k/v pair. | pcsd | def morsel to cookie morsel c = create cookie name=morsel key value=morsel value version= morsel['version'] or 0 port=None port specified=False domain=morsel['domain'] domain specified=bool morsel['domain'] domain initial dot=morsel['domain'] startswith ' ' path=morsel['path'] path specified=bool morsel['path'] secure=... | 7880 | def morsel_to_cookie(morsel):
c = create_cookie(name=morsel.key, value=morsel.value, version=(morsel['version'] or 0), port=None, port_specified=False, domain=morsel['domain'], domain_specified=bool(morsel['domain']), domain_initial_dot=morsel['domain'].startswith('.'), path=morsel['path'], path_specified=bool(morsel[... | Convert a Morsel object into a Cookie containing the one k/v pair. | convert a morsel object into a cookie containing the one k / v pair . | Question:
What does this function do?
Code:
def morsel_to_cookie(morsel):
c = create_cookie(name=morsel.key, value=morsel.value, version=(morsel['version'] or 0), port=None, port_specified=False, domain=morsel['domain'], domain_specified=bool(morsel['domain']), domain_initial_dot=morsel['domain'].startswith('.'), p... |
null | null | null | What does this function do? | def __virtual__():
if (not salt.utils.is_windows()):
return (False, 'WUA: Only available on Window systems')
if (not salt.utils.win_update.HAS_PYWIN32):
return (False, 'WUA: Requires PyWin32 libraries')
return __virtualname__
| null | null | null | Only valid on Windows machines | pcsd | def virtual if not salt utils is windows return False 'WUA Only available on Window systems' if not salt utils win update HAS PYWIN32 return False 'WUA Requires Py Win32 libraries' return virtualname | 7890 | def __virtual__():
if (not salt.utils.is_windows()):
return (False, 'WUA: Only available on Window systems')
if (not salt.utils.win_update.HAS_PYWIN32):
return (False, 'WUA: Requires PyWin32 libraries')
return __virtualname__
| Only valid on Windows machines | only valid on windows machines | Question:
What does this function do?
Code:
def __virtual__():
if (not salt.utils.is_windows()):
return (False, 'WUA: Only available on Window systems')
if (not salt.utils.win_update.HAS_PYWIN32):
return (False, 'WUA: Requires PyWin32 libraries')
return __virtualname__
|
null | null | null | What does this function do? | def _check_second_range(sec):
if np.any((sec == 60.0)):
warn(IllegalSecondWarning(sec, u'Treating as 0 sec, +1 min'))
elif (sec is None):
pass
elif (np.any((sec < (-60.0))) or np.any((sec > 60.0))):
raise IllegalSecondError(sec)
| null | null | null | Checks that the given value is in the range [0,60]. If the value
is equal to 60, then a warning is raised. | pcsd | def check second range sec if np any sec == 60 0 warn Illegal Second Warning sec u'Treating as 0 sec +1 min' elif sec is None pass elif np any sec < -60 0 or np any sec > 60 0 raise Illegal Second Error sec | 7892 | def _check_second_range(sec):
if np.any((sec == 60.0)):
warn(IllegalSecondWarning(sec, u'Treating as 0 sec, +1 min'))
elif (sec is None):
pass
elif (np.any((sec < (-60.0))) or np.any((sec > 60.0))):
raise IllegalSecondError(sec)
| Checks that the given value is in the range [0,60]. If the value
is equal to 60, then a warning is raised. | checks that the given value is in the range [ 0 , 60 ] . | Question:
What does this function do?
Code:
def _check_second_range(sec):
if np.any((sec == 60.0)):
warn(IllegalSecondWarning(sec, u'Treating as 0 sec, +1 min'))
elif (sec is None):
pass
elif (np.any((sec < (-60.0))) or np.any((sec > 60.0))):
raise IllegalSecondError(sec)
|
null | null | null | What does this function do? | @pytest.fixture
def guest():
return Guest()
| null | null | null | Return a guest (not logged in) user. | pcsd | @pytest fixture def guest return Guest | 7898 | @pytest.fixture
def guest():
return Guest()
| Return a guest (not logged in) user. | return a guest user . | Question:
What does this function do?
Code:
@pytest.fixture
def guest():
return Guest()
|
null | null | null | What does this function do? | def expect_failure_with_message(message):
def test_decorator(func):
def test_decorated(self, *args, **kwargs):
self.assertRaisesRegexp(segmentio.EventValidationError, message, func, self, *args, **kwargs)
self.assert_no_events_emitted()
return test_decorated
return test_decorator
| null | null | null | Ensure the test raises an exception and does not emit an event | pcsd | def expect failure with message message def test decorator func def test decorated self *args **kwargs self assert Raises Regexp segmentio Event Validation Error message func self *args **kwargs self assert no events emitted return test decorated return test decorator | 7902 | def expect_failure_with_message(message):
def test_decorator(func):
def test_decorated(self, *args, **kwargs):
self.assertRaisesRegexp(segmentio.EventValidationError, message, func, self, *args, **kwargs)
self.assert_no_events_emitted()
return test_decorated
return test_decorator
| Ensure the test raises an exception and does not emit an event | ensure the test raises an exception and does not emit an event | Question:
What does this function do?
Code:
def expect_failure_with_message(message):
def test_decorator(func):
def test_decorated(self, *args, **kwargs):
self.assertRaisesRegexp(segmentio.EventValidationError, message, func, self, *args, **kwargs)
self.assert_no_events_emitted()
return test_decorated
re... |
null | null | null | What does this function do? | def energy(H, q, p):
return (H.pot.energy(p) - H.logp(q))
| null | null | null | Compute the total energy for the Hamiltonian at a given position/momentum | pcsd | def energy H q p return H pot energy p - H logp q | 7904 | def energy(H, q, p):
return (H.pot.energy(p) - H.logp(q))
| Compute the total energy for the Hamiltonian at a given position/momentum | compute the total energy for the hamiltonian at a given position / momentum | Question:
What does this function do?
Code:
def energy(H, q, p):
return (H.pot.energy(p) - H.logp(q))
|
null | null | null | What does this function do? | def escape(s):
return urllib.quote(s, safe='~')
| null | null | null | Escape a URL including any /. | pcsd | def escape s return urllib quote s safe='~' | 7908 | def escape(s):
return urllib.quote(s, safe='~')
| Escape a URL including any /. | escape a url including any / . | Question:
What does this function do?
Code:
def escape(s):
return urllib.quote(s, safe='~')
|
null | null | null | What does this function do? | def make_messages(locale=None, domain='django', verbosity='1', all=False, extensions=None, symlinks=False, ignore_patterns=[]):
from google.appengine._internal.django.conf import settings
if settings.configured:
settings.USE_I18N = True
else:
settings.configure(USE_I18N=True)
from google.appengine._internal.dja... | null | null | null | Uses the locale directory from the Django SVN tree or an application/
project to process all | pcsd | def make messages locale=None domain='django' verbosity='1' all=False extensions=None symlinks=False ignore patterns=[] from google appengine internal django conf import settings if settings configured settings USE I18N = True else settings configure USE I18N=True from google appengine internal django utils translation... | 7910 | def make_messages(locale=None, domain='django', verbosity='1', all=False, extensions=None, symlinks=False, ignore_patterns=[]):
from google.appengine._internal.django.conf import settings
if settings.configured:
settings.USE_I18N = True
else:
settings.configure(USE_I18N=True)
from google.appengine._internal.dja... | Uses the locale directory from the Django SVN tree or an application/
project to process all | uses the locale directory from the django svn tree or an application / project to process all | Question:
What does this function do?
Code:
def make_messages(locale=None, domain='django', verbosity='1', all=False, extensions=None, symlinks=False, ignore_patterns=[]):
from google.appengine._internal.django.conf import settings
if settings.configured:
settings.USE_I18N = True
else:
settings.configure(USE_... |
null | null | null | What does this function do? | def find_free_port(host, currentport):
n = 0
while ((n < 10) and (currentport <= 49151)):
try:
cherrypy.process.servers.check_port(host, currentport, timeout=0.025)
return currentport
except:
currentport += 5
n += 1
return 0
| null | null | null | Return a free port, 0 when nothing is free | pcsd | def find free port host currentport n = 0 while n < 10 and currentport <= 49151 try cherrypy process servers check port host currentport timeout=0 025 return currentport except currentport += 5 n += 1 return 0 | 7921 | def find_free_port(host, currentport):
n = 0
while ((n < 10) and (currentport <= 49151)):
try:
cherrypy.process.servers.check_port(host, currentport, timeout=0.025)
return currentport
except:
currentport += 5
n += 1
return 0
| Return a free port, 0 when nothing is free | return a free port , 0 when nothing is free | Question:
What does this function do?
Code:
def find_free_port(host, currentport):
n = 0
while ((n < 10) and (currentport <= 49151)):
try:
cherrypy.process.servers.check_port(host, currentport, timeout=0.025)
return currentport
except:
currentport += 5
n += 1
return 0
|
null | null | null | What does this function do? | def bisection(payload, expression, length=None, charsetType=None, firstChar=None, lastChar=None, dump=False):
abortedFlag = False
showEta = False
partialValue = u''
finalValue = None
retrievedLength = 0
asciiTbl = getCharset(charsetType)
threadData = getCurrentThreadData()
timeBasedCompare = (kb.technique in (P... | null | null | null | Bisection algorithm that can be used to perform blind SQL injection
on an affected host | pcsd | def bisection payload expression length=None charset Type=None first Char=None last Char=None dump=False aborted Flag = False show Eta = False partial Value = u'' final Value = None retrieved Length = 0 ascii Tbl = get Charset charset Type thread Data = get Current Thread Data time Based Compare = kb technique in PAYLO... | 7924 | def bisection(payload, expression, length=None, charsetType=None, firstChar=None, lastChar=None, dump=False):
abortedFlag = False
showEta = False
partialValue = u''
finalValue = None
retrievedLength = 0
asciiTbl = getCharset(charsetType)
threadData = getCurrentThreadData()
timeBasedCompare = (kb.technique in (P... | Bisection algorithm that can be used to perform blind SQL injection
on an affected host | bisection algorithm that can be used to perform blind sql injection on an affected host | Question:
What does this function do?
Code:
def bisection(payload, expression, length=None, charsetType=None, firstChar=None, lastChar=None, dump=False):
abortedFlag = False
showEta = False
partialValue = u''
finalValue = None
retrievedLength = 0
asciiTbl = getCharset(charsetType)
threadData = getCurrentThrea... |
null | null | null | What does this function do? | def certificates(config, unused_plugins):
cert_manager.certificates(config)
| null | null | null | Display information about certs configured with Certbot | pcsd | def certificates config unused plugins cert manager certificates config | 7933 | def certificates(config, unused_plugins):
cert_manager.certificates(config)
| Display information about certs configured with Certbot | display information about certs configured with certbot | Question:
What does this function do?
Code:
def certificates(config, unused_plugins):
cert_manager.certificates(config)
|
null | null | null | What does this function do? | def transfer_accept(context, transfer_id, user_id, project_id):
return IMPL.transfer_accept(context, transfer_id, user_id, project_id)
| null | null | null | Accept a volume transfer. | pcsd | def transfer accept context transfer id user id project id return IMPL transfer accept context transfer id user id project id | 7934 | def transfer_accept(context, transfer_id, user_id, project_id):
return IMPL.transfer_accept(context, transfer_id, user_id, project_id)
| Accept a volume transfer. | accept a volume transfer . | Question:
What does this function do?
Code:
def transfer_accept(context, transfer_id, user_id, project_id):
return IMPL.transfer_accept(context, transfer_id, user_id, project_id)
|
null | null | null | What does this function do? | def upgrade(migrate_engine):
if (migrate_engine.name in ('sqlite', 'postgresql')):
for (table_name, index_name, column_names) in INDEXES:
ensure_index_exists(migrate_engine, table_name, index_name, column_names)
elif (migrate_engine.name == 'mysql'):
ensure_index_removed(migrate_engine, 'dns_domains', 'project... | null | null | null | Add indexes missing on SQLite and PostgreSQL. | pcsd | def upgrade migrate engine if migrate engine name in 'sqlite' 'postgresql' for table name index name column names in INDEXES ensure index exists migrate engine table name index name column names elif migrate engine name == 'mysql' ensure index removed migrate engine 'dns domains' 'project id' ensure index exists migrat... | 7950 | def upgrade(migrate_engine):
if (migrate_engine.name in ('sqlite', 'postgresql')):
for (table_name, index_name, column_names) in INDEXES:
ensure_index_exists(migrate_engine, table_name, index_name, column_names)
elif (migrate_engine.name == 'mysql'):
ensure_index_removed(migrate_engine, 'dns_domains', 'project... | Add indexes missing on SQLite and PostgreSQL. | add indexes missing on sqlite and postgresql . | Question:
What does this function do?
Code:
def upgrade(migrate_engine):
if (migrate_engine.name in ('sqlite', 'postgresql')):
for (table_name, index_name, column_names) in INDEXES:
ensure_index_exists(migrate_engine, table_name, index_name, column_names)
elif (migrate_engine.name == 'mysql'):
ensure_index_... |
null | null | null | What does this function do? | def partition_entropy_by(inputs, attribute):
partitions = partition_by(inputs, attribute)
return partition_entropy(partitions.values())
| null | null | null | computes the entropy corresponding to the given partition | pcsd | def partition entropy by inputs attribute partitions = partition by inputs attribute return partition entropy partitions values | 7952 | def partition_entropy_by(inputs, attribute):
partitions = partition_by(inputs, attribute)
return partition_entropy(partitions.values())
| computes the entropy corresponding to the given partition | computes the entropy corresponding to the given partition | Question:
What does this function do?
Code:
def partition_entropy_by(inputs, attribute):
partitions = partition_by(inputs, attribute)
return partition_entropy(partitions.values())
|
null | null | null | What does this function do? | def imports_on_separate_lines(logical_line):
line = logical_line
if line.startswith('import '):
found = line.find(',')
if (found > (-1)):
return (found, 'E401 multiple imports on one line')
| null | null | null | Imports should usually be on separate lines. | pcsd | def imports on separate lines logical line line = logical line if line startswith 'import ' found = line find ' ' if found > -1 return found 'E401 multiple imports on one line' | 7955 | def imports_on_separate_lines(logical_line):
line = logical_line
if line.startswith('import '):
found = line.find(',')
if (found > (-1)):
return (found, 'E401 multiple imports on one line')
| Imports should usually be on separate lines. | imports should usually be on separate lines . | Question:
What does this function do?
Code:
def imports_on_separate_lines(logical_line):
line = logical_line
if line.startswith('import '):
found = line.find(',')
if (found > (-1)):
return (found, 'E401 multiple imports on one line')
|
null | null | null | What does this function do? | @verbose
def _read_cov(fid, node, cov_kind, limited=False, verbose=None):
covs = dir_tree_find(node, FIFF.FIFFB_MNE_COV)
if (len(covs) == 0):
raise ValueError('No covariance matrices found')
for p in range(len(covs)):
tag = find_tag(fid, covs[p], FIFF.FIFF_MNE_COV_KIND)
if ((tag is not None) and (int(tag.data)... | null | null | null | Read a noise covariance matrix. | pcsd | @verbose def read cov fid node cov kind limited=False verbose=None covs = dir tree find node FIFF FIFFB MNE COV if len covs == 0 raise Value Error 'No covariance matrices found' for p in range len covs tag = find tag fid covs[p] FIFF FIFF MNE COV KIND if tag is not None and int tag data == cov kind this = covs[p] tag =... | 7957 | @verbose
def _read_cov(fid, node, cov_kind, limited=False, verbose=None):
covs = dir_tree_find(node, FIFF.FIFFB_MNE_COV)
if (len(covs) == 0):
raise ValueError('No covariance matrices found')
for p in range(len(covs)):
tag = find_tag(fid, covs[p], FIFF.FIFF_MNE_COV_KIND)
if ((tag is not None) and (int(tag.data)... | Read a noise covariance matrix. | read a noise covariance matrix . | Question:
What does this function do?
Code:
@verbose
def _read_cov(fid, node, cov_kind, limited=False, verbose=None):
covs = dir_tree_find(node, FIFF.FIFFB_MNE_COV)
if (len(covs) == 0):
raise ValueError('No covariance matrices found')
for p in range(len(covs)):
tag = find_tag(fid, covs[p], FIFF.FIFF_MNE_COV_K... |
null | null | null | What does this function do? | def stem(word):
return fix_ending(remove_ending(word))
| null | null | null | Returns the stemmed version of the argument string. | pcsd | def stem word return fix ending remove ending word | 7963 | def stem(word):
return fix_ending(remove_ending(word))
| Returns the stemmed version of the argument string. | returns the stemmed version of the argument string . | Question:
What does this function do?
Code:
def stem(word):
return fix_ending(remove_ending(word))
|
null | null | null | What does this function do? | def _image_tag_delete_all(context, image_id, delete_time=None, session=None):
tags_updated_count = _image_child_entry_delete_all(models.ImageTag, image_id, delete_time, session)
return tags_updated_count
| null | null | null | Delete all image tags for given image | pcsd | def image tag delete all context image id delete time=None session=None tags updated count = image child entry delete all models Image Tag image id delete time session return tags updated count | 7966 | def _image_tag_delete_all(context, image_id, delete_time=None, session=None):
tags_updated_count = _image_child_entry_delete_all(models.ImageTag, image_id, delete_time, session)
return tags_updated_count
| Delete all image tags for given image | delete all image tags for given image | Question:
What does this function do?
Code:
def _image_tag_delete_all(context, image_id, delete_time=None, session=None):
tags_updated_count = _image_child_entry_delete_all(models.ImageTag, image_id, delete_time, session)
return tags_updated_count
|
null | null | null | What does this function do? | def clip(x, min_value, max_value):
if ((max_value is not None) and (max_value < min_value)):
max_value = min_value
if (max_value is None):
max_value = np.inf
min_value = _to_tensor(min_value, x.dtype.base_dtype)
max_value = _to_tensor(max_value, x.dtype.base_dtype)
return tf.clip_by_value(x, min_value, max_val... | null | null | null | Element-wise value clipping.
# Returns
A tensor. | pcsd | def clip x min value max value if max value is not None and max value < min value max value = min value if max value is None max value = np inf min value = to tensor min value x dtype base dtype max value = to tensor max value x dtype base dtype return tf clip by value x min value max value | 7969 | def clip(x, min_value, max_value):
if ((max_value is not None) and (max_value < min_value)):
max_value = min_value
if (max_value is None):
max_value = np.inf
min_value = _to_tensor(min_value, x.dtype.base_dtype)
max_value = _to_tensor(max_value, x.dtype.base_dtype)
return tf.clip_by_value(x, min_value, max_val... | Element-wise value clipping.
# Returns
A tensor. | element - wise value clipping . | Question:
What does this function do?
Code:
def clip(x, min_value, max_value):
if ((max_value is not None) and (max_value < min_value)):
max_value = min_value
if (max_value is None):
max_value = np.inf
min_value = _to_tensor(min_value, x.dtype.base_dtype)
max_value = _to_tensor(max_value, x.dtype.base_dtype)... |
null | null | null | What does this function do? | def initialize_scheduler():
from headphones import updater, searcher, librarysync, postprocessor, torrentfinished
with SCHED_LOCK:
start_jobs = (not len(SCHED.get_jobs()))
minutes = CONFIG.SEARCH_INTERVAL
schedule_job(searcher.searchforalbum, 'Search for Wanted', hours=0, minutes=minutes)
minutes = CONFIG.DOW... | null | null | null | Start the scheduled background tasks. Re-schedule if interval settings changed. | pcsd | def initialize scheduler from headphones import updater searcher librarysync postprocessor torrentfinished with SCHED LOCK start jobs = not len SCHED get jobs minutes = CONFIG SEARCH INTERVAL schedule job searcher searchforalbum 'Search for Wanted' hours=0 minutes=minutes minutes = CONFIG DOWNLOAD SCAN INTERVAL schedul... | 7976 | def initialize_scheduler():
from headphones import updater, searcher, librarysync, postprocessor, torrentfinished
with SCHED_LOCK:
start_jobs = (not len(SCHED.get_jobs()))
minutes = CONFIG.SEARCH_INTERVAL
schedule_job(searcher.searchforalbum, 'Search for Wanted', hours=0, minutes=minutes)
minutes = CONFIG.DOW... | Start the scheduled background tasks. Re-schedule if interval settings changed. | start the scheduled background tasks . | Question:
What does this function do?
Code:
def initialize_scheduler():
from headphones import updater, searcher, librarysync, postprocessor, torrentfinished
with SCHED_LOCK:
start_jobs = (not len(SCHED.get_jobs()))
minutes = CONFIG.SEARCH_INTERVAL
schedule_job(searcher.searchforalbum, 'Search for Wanted', h... |
null | null | null | What does this function do? | def create_bucket(bucket_name):
storage_client = storage.Client()
bucket = storage_client.create_bucket(bucket_name)
print 'Bucket {} created'.format(bucket.name)
| null | null | null | Creates a new bucket. | pcsd | def create bucket bucket name storage client = storage Client bucket = storage client create bucket bucket name print 'Bucket {} created' format bucket name | 7979 | def create_bucket(bucket_name):
storage_client = storage.Client()
bucket = storage_client.create_bucket(bucket_name)
print 'Bucket {} created'.format(bucket.name)
| Creates a new bucket. | creates a new bucket . | Question:
What does this function do?
Code:
def create_bucket(bucket_name):
storage_client = storage.Client()
bucket = storage_client.create_bucket(bucket_name)
print 'Bucket {} created'.format(bucket.name)
|
null | null | null | What does this function do? | def register(linter):
linter.register_checker(TypeChecker(linter))
| null | null | null | required method to auto register this checker | pcsd | def register linter linter register checker Type Checker linter | 7984 | def register(linter):
linter.register_checker(TypeChecker(linter))
| required method to auto register this checker | required method to auto register this checker | Question:
What does this function do?
Code:
def register(linter):
linter.register_checker(TypeChecker(linter))
|
null | null | null | What does this function do? | def _CheckFacetDepth(depth):
if (depth is None):
return None
else:
return _CheckInteger(depth, 'depth', zero_ok=False, upper_bound=MAXIMUM_DEPTH_FOR_FACETED_SEARCH)
| null | null | null | Checks the facet depth to return is an integer within range. | pcsd | def Check Facet Depth depth if depth is None return None else return Check Integer depth 'depth' zero ok=False upper bound=MAXIMUM DEPTH FOR FACETED SEARCH | 7988 | def _CheckFacetDepth(depth):
if (depth is None):
return None
else:
return _CheckInteger(depth, 'depth', zero_ok=False, upper_bound=MAXIMUM_DEPTH_FOR_FACETED_SEARCH)
| Checks the facet depth to return is an integer within range. | checks the facet depth to return is an integer within range . | Question:
What does this function do?
Code:
def _CheckFacetDepth(depth):
if (depth is None):
return None
else:
return _CheckInteger(depth, 'depth', zero_ok=False, upper_bound=MAXIMUM_DEPTH_FOR_FACETED_SEARCH)
|
null | null | null | What does this function do? | def _edge_betweenness(G, source, nodes=None, cutoff=False):
(pred, length) = nx.predecessor(G, source, cutoff=cutoff, return_seen=True)
onodes = [n for (n, d) in sorted(length.items(), key=itemgetter(1))]
between = {}
for (u, v) in G.edges(nodes):
between[(u, v)] = 1.0
between[(v, u)] = 1.0
while onodes:
v =... | null | null | null | Edge betweenness helper. | pcsd | def edge betweenness G source nodes=None cutoff=False pred length = nx predecessor G source cutoff=cutoff return seen=True onodes = [n for n d in sorted length items key=itemgetter 1 ] between = {} for u v in G edges nodes between[ u v ] = 1 0 between[ v u ] = 1 0 while onodes v = onodes pop if v in pred num paths = le... | 7990 | def _edge_betweenness(G, source, nodes=None, cutoff=False):
(pred, length) = nx.predecessor(G, source, cutoff=cutoff, return_seen=True)
onodes = [n for (n, d) in sorted(length.items(), key=itemgetter(1))]
between = {}
for (u, v) in G.edges(nodes):
between[(u, v)] = 1.0
between[(v, u)] = 1.0
while onodes:
v =... | Edge betweenness helper. | edge betweenness helper . | Question:
What does this function do?
Code:
def _edge_betweenness(G, source, nodes=None, cutoff=False):
(pred, length) = nx.predecessor(G, source, cutoff=cutoff, return_seen=True)
onodes = [n for (n, d) in sorted(length.items(), key=itemgetter(1))]
between = {}
for (u, v) in G.edges(nodes):
between[(u, v)] = 1... |
null | null | null | What does this function do? | def main():
args = vars(ArgParser().parse_args())
r_time = 0
ports = [4505, 4506]
print('Sniffing device {0}'.format(args['iface']))
stat = {'4506/new': 0, '4506/est': 0, '4506/fin': 0, '4505/new': 0, '4505/est': 0, '4505/fin': 0, 'ips/4505': 0, 'ips/4506': 0}
if args['only_ip']:
print('IPs making new connectio... | null | null | null | main loop for whole script | pcsd | def main args = vars Arg Parser parse args r time = 0 ports = [4505 4506] print 'Sniffing device {0}' format args['iface'] stat = {'4506/new' 0 '4506/est' 0 '4506/fin' 0 '4505/new' 0 '4505/est' 0 '4505/fin' 0 'ips/4505' 0 'ips/4506' 0} if args['only ip'] print 'I Ps making new connections ports {0} interval {1} ' forma... | 7998 | def main():
args = vars(ArgParser().parse_args())
r_time = 0
ports = [4505, 4506]
print('Sniffing device {0}'.format(args['iface']))
stat = {'4506/new': 0, '4506/est': 0, '4506/fin': 0, '4505/new': 0, '4505/est': 0, '4505/fin': 0, 'ips/4505': 0, 'ips/4506': 0}
if args['only_ip']:
print('IPs making new connectio... | main loop for whole script | main loop for whole script | Question:
What does this function do?
Code:
def main():
args = vars(ArgParser().parse_args())
r_time = 0
ports = [4505, 4506]
print('Sniffing device {0}'.format(args['iface']))
stat = {'4506/new': 0, '4506/est': 0, '4506/fin': 0, '4505/new': 0, '4505/est': 0, '4505/fin': 0, 'ips/4505': 0, 'ips/4506': 0}
if arg... |
null | null | null | What does this function do? | @status('Getting the list of files that have been added/changed', info=(lambda x: n_files_str(len(x))))
def changed_files():
if os.path.isdir(os.path.join(SRCDIR, '.hg')):
cmd = 'hg status --added --modified --no-status'
if mq_patches_applied():
cmd += ' --rev qparent'
with subprocess.Popen(cmd.split(), stdou... | null | null | null | Get the list of changed or added files from Mercurial or git. | pcsd | @status 'Getting the list of files that have been added/changed' info= lambda x n files str len x def changed files if os path isdir os path join SRCDIR ' hg' cmd = 'hg status --added --modified --no-status' if mq patches applied cmd += ' --rev qparent' with subprocess Popen cmd split stdout=subprocess PIPE as st retur... | 7999 | @status('Getting the list of files that have been added/changed', info=(lambda x: n_files_str(len(x))))
def changed_files():
if os.path.isdir(os.path.join(SRCDIR, '.hg')):
cmd = 'hg status --added --modified --no-status'
if mq_patches_applied():
cmd += ' --rev qparent'
with subprocess.Popen(cmd.split(), stdou... | Get the list of changed or added files from Mercurial or git. | get the list of changed or added files from mercurial or git . | Question:
What does this function do?
Code:
@status('Getting the list of files that have been added/changed', info=(lambda x: n_files_str(len(x))))
def changed_files():
if os.path.isdir(os.path.join(SRCDIR, '.hg')):
cmd = 'hg status --added --modified --no-status'
if mq_patches_applied():
cmd += ' --rev qpar... |
null | null | null | What does this function do? | def restore_warnings_state(state):
warnings.warn(warn_txt, DeprecationWarning, stacklevel=2)
warnings.filters = state[:]
| null | null | null | Restores the state of the warnings module when passed an object that was
returned by get_warnings_state() | pcsd | def restore warnings state state warnings warn warn txt Deprecation Warning stacklevel=2 warnings filters = state[ ] | 8001 | def restore_warnings_state(state):
warnings.warn(warn_txt, DeprecationWarning, stacklevel=2)
warnings.filters = state[:]
| Restores the state of the warnings module when passed an object that was
returned by get_warnings_state() | restores the state of the warnings module when passed an object that was returned by get _ warnings _ state ( ) | Question:
What does this function do?
Code:
def restore_warnings_state(state):
warnings.warn(warn_txt, DeprecationWarning, stacklevel=2)
warnings.filters = state[:]
|
null | null | null | What does this function do? | def get_model_field_name(field):
field = slugify(field)
field = field.replace('-', '_')
field = field.replace(':', '_')
if (field in ('id',)):
field += '_'
if (field.upper() in PG_RESERVED_KEYWORDS):
field += '_'
if (field[(-1):] == '_'):
field += 'field'
try:
int(field)
float(field)
field = ('_%s' %... | null | null | null | Get the field name usable without quotes. | pcsd | def get model field name field field = slugify field field = field replace '-' ' ' field = field replace ' ' ' ' if field in 'id' field += ' ' if field upper in PG RESERVED KEYWORDS field += ' ' if field[ -1 ] == ' ' field += 'field' try int field float field field = ' %s' % field except Value Error pass return field | 8003 | def get_model_field_name(field):
field = slugify(field)
field = field.replace('-', '_')
field = field.replace(':', '_')
if (field in ('id',)):
field += '_'
if (field.upper() in PG_RESERVED_KEYWORDS):
field += '_'
if (field[(-1):] == '_'):
field += 'field'
try:
int(field)
float(field)
field = ('_%s' %... | Get the field name usable without quotes. | get the field name usable without quotes . | Question:
What does this function do?
Code:
def get_model_field_name(field):
field = slugify(field)
field = field.replace('-', '_')
field = field.replace(':', '_')
if (field in ('id',)):
field += '_'
if (field.upper() in PG_RESERVED_KEYWORDS):
field += '_'
if (field[(-1):] == '_'):
field += 'field'
try:... |
null | null | null | What does this function do? | def register(linter):
linter.register_reporter(TextReporter)
linter.register_reporter(ParseableTextReporter)
linter.register_reporter(VSTextReporter)
linter.register_reporter(ColorizedTextReporter)
| null | null | null | Register the reporter classes with the linter. | pcsd | def register linter linter register reporter Text Reporter linter register reporter Parseable Text Reporter linter register reporter VS Text Reporter linter register reporter Colorized Text Reporter | 8010 | def register(linter):
linter.register_reporter(TextReporter)
linter.register_reporter(ParseableTextReporter)
linter.register_reporter(VSTextReporter)
linter.register_reporter(ColorizedTextReporter)
| Register the reporter classes with the linter. | register the reporter classes with the linter . | Question:
What does this function do?
Code:
def register(linter):
linter.register_reporter(TextReporter)
linter.register_reporter(ParseableTextReporter)
linter.register_reporter(VSTextReporter)
linter.register_reporter(ColorizedTextReporter)
|
null | null | null | What does this function do? | def update_patch_log(patchmodule):
frappe.get_doc({u'doctype': u'Patch Log', u'patch': patchmodule}).insert()
| null | null | null | update patch_file in patch log | pcsd | def update patch log patchmodule frappe get doc {u'doctype' u'Patch Log' u'patch' patchmodule} insert | 8012 | def update_patch_log(patchmodule):
frappe.get_doc({u'doctype': u'Patch Log', u'patch': patchmodule}).insert()
| update patch_file in patch log | update patch _ file in patch log | Question:
What does this function do?
Code:
def update_patch_log(patchmodule):
frappe.get_doc({u'doctype': u'Patch Log', u'patch': patchmodule}).insert()
|
null | null | null | What does this function do? | def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
actual_decorator = user_passes_test((lambda u: u.is_authenticated), login_url=login_url, redirect_field_name=redirect_field_name)
if function:
return actual_decorator(function)
return actual_decorator
| null | null | null | Decorator for views that checks that the user is logged in, redirecting
to the log-in page if necessary. | pcsd | def login required function=None redirect field name=REDIRECT FIELD NAME login url=None actual decorator = user passes test lambda u u is authenticated login url=login url redirect field name=redirect field name if function return actual decorator function return actual decorator | 8013 | def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
actual_decorator = user_passes_test((lambda u: u.is_authenticated), login_url=login_url, redirect_field_name=redirect_field_name)
if function:
return actual_decorator(function)
return actual_decorator
| Decorator for views that checks that the user is logged in, redirecting
to the log-in page if necessary. | decorator for views that checks that the user is logged in , redirecting to the log - in page if necessary . | Question:
What does this function do?
Code:
def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
actual_decorator = user_passes_test((lambda u: u.is_authenticated), login_url=login_url, redirect_field_name=redirect_field_name)
if function:
return actual_decorator(function)
... |
null | null | null | What does this function do? | def index2():
table = s3db.table('cr_shelter', None)
module_name = settings.modules[module].name_nice
response.title = module_name
response.view = 'inv/index.html'
if s3.debug:
from s3.s3data import S3DataTable
representation = request.extension
if ((representation == 'html') or (get_vars.id == 'warehouse_li... | null | null | null | Alternative Application Home page
- custom View | pcsd | def index2 table = s3db table 'cr shelter' None module name = settings modules[module] name nice response title = module name response view = 'inv/index html' if s3 debug from s3 s3data import S3Data Table representation = request extension if representation == 'html' or get vars id == 'warehouse list 1' resource = s3d... | 8016 | def index2():
table = s3db.table('cr_shelter', None)
module_name = settings.modules[module].name_nice
response.title = module_name
response.view = 'inv/index.html'
if s3.debug:
from s3.s3data import S3DataTable
representation = request.extension
if ((representation == 'html') or (get_vars.id == 'warehouse_li... | Alternative Application Home page
- custom View | alternative application home page - custom view | Question:
What does this function do?
Code:
def index2():
table = s3db.table('cr_shelter', None)
module_name = settings.modules[module].name_nice
response.title = module_name
response.view = 'inv/index.html'
if s3.debug:
from s3.s3data import S3DataTable
representation = request.extension
if ((representat... |
null | null | null | What does this function do? | def is_valid_ip(ip):
if ((not ip) or ('\x00' in ip)):
return False
try:
res = socket.getaddrinfo(ip, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_NUMERICHOST)
return bool(res)
except socket.gaierror as e:
if (e.args[0] == socket.EAI_NONAME):
return False
raise
return True
| null | null | null | Returns true if the given string is a well-formed IP address.
Supports IPv4 and IPv6. | pcsd | def is valid ip ip if not ip or '\x00' in ip return False try res = socket getaddrinfo ip 0 socket AF UNSPEC socket SOCK STREAM 0 socket AI NUMERICHOST return bool res except socket gaierror as e if e args[0] == socket EAI NONAME return False raise return True | 8019 | def is_valid_ip(ip):
if ((not ip) or ('\x00' in ip)):
return False
try:
res = socket.getaddrinfo(ip, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_NUMERICHOST)
return bool(res)
except socket.gaierror as e:
if (e.args[0] == socket.EAI_NONAME):
return False
raise
return True
| Returns true if the given string is a well-formed IP address.
Supports IPv4 and IPv6. | returns true if the given string is a well - formed ip address . | Question:
What does this function do?
Code:
def is_valid_ip(ip):
if ((not ip) or ('\x00' in ip)):
return False
try:
res = socket.getaddrinfo(ip, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_NUMERICHOST)
return bool(res)
except socket.gaierror as e:
if (e.args[0] == socket.EAI_NONAME):
return F... |
null | null | null | What does this function do? | def true(*args, **kwargs):
return True
| null | null | null | Always returns True. | pcsd | def true *args **kwargs return True | 8026 | def true(*args, **kwargs):
return True
| Always returns True. | always returns true . | Question:
What does this function do?
Code:
def true(*args, **kwargs):
return True
|
null | null | null | What does this function do? | def print_name_status(changes):
for change in changes:
if (not change):
continue
if (type(change) is list):
change = change[0]
if (change.type == CHANGE_ADD):
path1 = change.new.path
path2 = ''
kind = 'A'
elif (change.type == CHANGE_DELETE):
path1 = change.old.path
path2 = ''
kind = 'D'... | null | null | null | Print a simple status summary, listing changed files. | pcsd | def print name status changes for change in changes if not change continue if type change is list change = change[0] if change type == CHANGE ADD path1 = change new path path2 = '' kind = 'A' elif change type == CHANGE DELETE path1 = change old path path2 = '' kind = 'D' elif change type == CHANGE MODIFY path1 = change... | 8031 | def print_name_status(changes):
for change in changes:
if (not change):
continue
if (type(change) is list):
change = change[0]
if (change.type == CHANGE_ADD):
path1 = change.new.path
path2 = ''
kind = 'A'
elif (change.type == CHANGE_DELETE):
path1 = change.old.path
path2 = ''
kind = 'D'... | Print a simple status summary, listing changed files. | print a simple status summary , listing changed files . | Question:
What does this function do?
Code:
def print_name_status(changes):
for change in changes:
if (not change):
continue
if (type(change) is list):
change = change[0]
if (change.type == CHANGE_ADD):
path1 = change.new.path
path2 = ''
kind = 'A'
elif (change.type == CHANGE_DELETE):
path... |
null | null | null | What does this function do? | def stop(port):
global client_cancel
client_cancel = True
try:
if transparent_torification:
s = socket.socket()
s.connect(('127.0.0.1', port))
s.sendall('GET /{0:s}/shutdown HTTP/1.1\r\n\r\n'.format(shutdown_slug))
else:
urlopen('http://127.0.0.1:{0:d}/{1:s}/shutdown'.format(port, shutdown_slug)).rea... | null | null | null | Stop the flask web server by loading /shutdown. | pcsd | def stop port global client cancel client cancel = True try if transparent torification s = socket socket s connect '127 0 0 1' port s sendall 'GET /{0 s}/shutdown HTTP/1 1\r \r ' format shutdown slug else urlopen 'http //127 0 0 1 {0 d}/{1 s}/shutdown' format port shutdown slug read except pass | 8042 | def stop(port):
global client_cancel
client_cancel = True
try:
if transparent_torification:
s = socket.socket()
s.connect(('127.0.0.1', port))
s.sendall('GET /{0:s}/shutdown HTTP/1.1\r\n\r\n'.format(shutdown_slug))
else:
urlopen('http://127.0.0.1:{0:d}/{1:s}/shutdown'.format(port, shutdown_slug)).rea... | Stop the flask web server by loading /shutdown. | stop the flask web server by loading / shutdown . | Question:
What does this function do?
Code:
def stop(port):
global client_cancel
client_cancel = True
try:
if transparent_torification:
s = socket.socket()
s.connect(('127.0.0.1', port))
s.sendall('GET /{0:s}/shutdown HTTP/1.1\r\n\r\n'.format(shutdown_slug))
else:
urlopen('http://127.0.0.1:{0:d}/{... |
null | null | null | What does this function do? | def OSXGetRawDevice(path):
device_map = GetMountpoints()
path = utils.SmartUnicode(path)
mount_point = path = utils.NormalizePath(path, '/')
result = rdf_paths.PathSpec(pathtype=rdf_paths.PathSpec.PathType.OS)
while mount_point:
try:
(result.path, fs_type) = device_map[mount_point]
if (fs_type in ['ext2', ... | null | null | null | Resolve the raw device that contains the path. | pcsd | def OSX Get Raw Device path device map = Get Mountpoints path = utils Smart Unicode path mount point = path = utils Normalize Path path '/' result = rdf paths Path Spec pathtype=rdf paths Path Spec Path Type OS while mount point try result path fs type = device map[mount point] if fs type in ['ext2' 'ext3' 'ext4' 'vfat... | 8048 | def OSXGetRawDevice(path):
device_map = GetMountpoints()
path = utils.SmartUnicode(path)
mount_point = path = utils.NormalizePath(path, '/')
result = rdf_paths.PathSpec(pathtype=rdf_paths.PathSpec.PathType.OS)
while mount_point:
try:
(result.path, fs_type) = device_map[mount_point]
if (fs_type in ['ext2', ... | Resolve the raw device that contains the path. | resolve the raw device that contains the path . | Question:
What does this function do?
Code:
def OSXGetRawDevice(path):
device_map = GetMountpoints()
path = utils.SmartUnicode(path)
mount_point = path = utils.NormalizePath(path, '/')
result = rdf_paths.PathSpec(pathtype=rdf_paths.PathSpec.PathType.OS)
while mount_point:
try:
(result.path, fs_type) = devi... |
null | null | null | What does this function do? | def get_seq_number(name):
(head, tail) = os.path.splitext(name)
if (tail == '.ts'):
(match, set, num) = match_ts(name)
else:
num = tail[1:]
if num.isdigit():
return int(num)
else:
return 0
| null | null | null | Return sequence number if name as an int | pcsd | def get seq number name head tail = os path splitext name if tail == ' ts' match set num = match ts name else num = tail[1 ] if num isdigit return int num else return 0 | 8055 | def get_seq_number(name):
(head, tail) = os.path.splitext(name)
if (tail == '.ts'):
(match, set, num) = match_ts(name)
else:
num = tail[1:]
if num.isdigit():
return int(num)
else:
return 0
| Return sequence number if name as an int | return sequence number if name as an int | Question:
What does this function do?
Code:
def get_seq_number(name):
(head, tail) = os.path.splitext(name)
if (tail == '.ts'):
(match, set, num) = match_ts(name)
else:
num = tail[1:]
if num.isdigit():
return int(num)
else:
return 0
|
null | null | null | What does this function do? | def _make_cipher(initialization_vector, secret):
return AES.new(secret[:KEY_SIZE], AES.MODE_CBC, initialization_vector[:AES.block_size])
| null | null | null | Return a block cipher object for use in `encrypt` and `decrypt`. | pcsd | def make cipher initialization vector secret return AES new secret[ KEY SIZE] AES MODE CBC initialization vector[ AES block size] | 8058 | def _make_cipher(initialization_vector, secret):
return AES.new(secret[:KEY_SIZE], AES.MODE_CBC, initialization_vector[:AES.block_size])
| Return a block cipher object for use in `encrypt` and `decrypt`. | return a block cipher object for use in encrypt and decrypt . | Question:
What does this function do?
Code:
def _make_cipher(initialization_vector, secret):
return AES.new(secret[:KEY_SIZE], AES.MODE_CBC, initialization_vector[:AES.block_size])
|
null | null | null | What does this function do? | def check_auth(name, sock_dir=None, queue=None, timeout=300):
event = salt.utils.event.SaltEvent('master', sock_dir, listen=True)
starttime = time.mktime(time.localtime())
newtimeout = timeout
log.debug('In check_auth, waiting for {0} to become available'.format(name))
while (newtimeout > 0):
newtimeout = (timeo... | null | null | null | This function is called from a multiprocess instance, to wait for a minion
to become available to receive salt commands | pcsd | def check auth name sock dir=None queue=None timeout=300 event = salt utils event Salt Event 'master' sock dir listen=True starttime = time mktime time localtime newtimeout = timeout log debug 'In check auth waiting for {0} to become available' format name while newtimeout > 0 newtimeout = timeout - time mktime time lo... | 8062 | def check_auth(name, sock_dir=None, queue=None, timeout=300):
event = salt.utils.event.SaltEvent('master', sock_dir, listen=True)
starttime = time.mktime(time.localtime())
newtimeout = timeout
log.debug('In check_auth, waiting for {0} to become available'.format(name))
while (newtimeout > 0):
newtimeout = (timeo... | This function is called from a multiprocess instance, to wait for a minion
to become available to receive salt commands | this function is called from a multiprocess instance , to wait for a minion to become available to receive salt commands | Question:
What does this function do?
Code:
def check_auth(name, sock_dir=None, queue=None, timeout=300):
event = salt.utils.event.SaltEvent('master', sock_dir, listen=True)
starttime = time.mktime(time.localtime())
newtimeout = timeout
log.debug('In check_auth, waiting for {0} to become available'.format(name))... |
null | null | null | What does this function do? | def in6_ptoc(addr):
try:
d = struct.unpack('!IIII', inet_pton(socket.AF_INET6, addr))
except:
return None
res = 0
m = [(2 ** 96), (2 ** 64), (2 ** 32), 1]
for i in xrange(4):
res += (d[i] * m[i])
rem = res
res = []
while rem:
res.append(_rfc1924map[(rem % 85)])
rem = (rem / 85)
res.reverse()
return ... | null | null | null | Converts an IPv6 address in printable representation to RFC
1924 Compact Representation ;-)
Returns None on error. | pcsd | def in6 ptoc addr try d = struct unpack '!IIII' inet pton socket AF INET6 addr except return None res = 0 m = [ 2 ** 96 2 ** 64 2 ** 32 1] for i in xrange 4 res += d[i] * m[i] rem = res res = [] while rem res append rfc1924map[ rem % 85 ] rem = rem / 85 res reverse return '' join res | 8063 | def in6_ptoc(addr):
try:
d = struct.unpack('!IIII', inet_pton(socket.AF_INET6, addr))
except:
return None
res = 0
m = [(2 ** 96), (2 ** 64), (2 ** 32), 1]
for i in xrange(4):
res += (d[i] * m[i])
rem = res
res = []
while rem:
res.append(_rfc1924map[(rem % 85)])
rem = (rem / 85)
res.reverse()
return ... | Converts an IPv6 address in printable representation to RFC
1924 Compact Representation ;-)
Returns None on error. | converts an ipv6 address in printable representation to rfc 1924 compact representation ; - ) | Question:
What does this function do?
Code:
def in6_ptoc(addr):
try:
d = struct.unpack('!IIII', inet_pton(socket.AF_INET6, addr))
except:
return None
res = 0
m = [(2 ** 96), (2 ** 64), (2 ** 32), 1]
for i in xrange(4):
res += (d[i] * m[i])
rem = res
res = []
while rem:
res.append(_rfc1924map[(rem % 8... |
null | null | null | What does this function do? | def swapaxes(y, axis1, axis2):
y = as_tensor_variable(y)
ndim = y.ndim
li = list(range(0, ndim))
(li[axis1], li[axis2]) = (li[axis2], li[axis1])
return y.dimshuffle(li)
| null | null | null | swap axes of inputted tensor | pcsd | def swapaxes y axis1 axis2 y = as tensor variable y ndim = y ndim li = list range 0 ndim li[axis1] li[axis2] = li[axis2] li[axis1] return y dimshuffle li | 8065 | def swapaxes(y, axis1, axis2):
y = as_tensor_variable(y)
ndim = y.ndim
li = list(range(0, ndim))
(li[axis1], li[axis2]) = (li[axis2], li[axis1])
return y.dimshuffle(li)
| swap axes of inputted tensor | swap axes of inputted tensor | Question:
What does this function do?
Code:
def swapaxes(y, axis1, axis2):
y = as_tensor_variable(y)
ndim = y.ndim
li = list(range(0, ndim))
(li[axis1], li[axis2]) = (li[axis2], li[axis1])
return y.dimshuffle(li)
|
null | null | null | What does this function do? | def acos(x):
np = import_module('numpy')
if isinstance(x, (int, float)):
if (abs(x) > 1):
return interval((- np.inf), np.inf, is_valid=False)
else:
return interval(np.arccos(x), np.arccos(x))
elif isinstance(x, interval):
if ((x.is_valid is False) or (x.start > 1) or (x.end < (-1))):
return interval((... | null | null | null | Evaluates the inverse cos of an interval | pcsd | def acos x np = import module 'numpy' if isinstance x int float if abs x > 1 return interval - np inf np inf is valid=False else return interval np arccos x np arccos x elif isinstance x interval if x is valid is False or x start > 1 or x end < -1 return interval - np inf np inf is valid=False elif x start < -1 or x en... | 8072 | def acos(x):
np = import_module('numpy')
if isinstance(x, (int, float)):
if (abs(x) > 1):
return interval((- np.inf), np.inf, is_valid=False)
else:
return interval(np.arccos(x), np.arccos(x))
elif isinstance(x, interval):
if ((x.is_valid is False) or (x.start > 1) or (x.end < (-1))):
return interval((... | Evaluates the inverse cos of an interval | evaluates the inverse cos of an interval | Question:
What does this function do?
Code:
def acos(x):
np = import_module('numpy')
if isinstance(x, (int, float)):
if (abs(x) > 1):
return interval((- np.inf), np.inf, is_valid=False)
else:
return interval(np.arccos(x), np.arccos(x))
elif isinstance(x, interval):
if ((x.is_valid is False) or (x.star... |
null | null | null | What does this function do? | def _objective_func(f, x, k_params, alpha, *args):
x_arr = np.asarray(x)
params = x_arr[:k_params].ravel()
u = x_arr[k_params:]
objective_func_arr = (f(params, *args) + (alpha * u).sum())
return matrix(objective_func_arr)
| null | null | null | The regularized objective function. | pcsd | def objective func f x k params alpha *args x arr = np asarray x params = x arr[ k params] ravel u = x arr[k params ] objective func arr = f params *args + alpha * u sum return matrix objective func arr | 8075 | def _objective_func(f, x, k_params, alpha, *args):
x_arr = np.asarray(x)
params = x_arr[:k_params].ravel()
u = x_arr[k_params:]
objective_func_arr = (f(params, *args) + (alpha * u).sum())
return matrix(objective_func_arr)
| The regularized objective function. | the regularized objective function . | Question:
What does this function do?
Code:
def _objective_func(f, x, k_params, alpha, *args):
x_arr = np.asarray(x)
params = x_arr[:k_params].ravel()
u = x_arr[k_params:]
objective_func_arr = (f(params, *args) + (alpha * u).sum())
return matrix(objective_func_arr)
|
null | null | null | What does this function do? | def norm_l21_tf(Z, shape, n_orient):
if Z.shape[0]:
Z2 = Z.reshape(*shape)
l21_norm = np.sqrt(stft_norm2(Z2).reshape((-1), n_orient).sum(axis=1))
l21_norm = l21_norm.sum()
else:
l21_norm = 0.0
return l21_norm
| null | null | null | L21 norm for TF. | pcsd | def norm l21 tf Z shape n orient if Z shape[0] Z2 = Z reshape *shape l21 norm = np sqrt stft norm2 Z2 reshape -1 n orient sum axis=1 l21 norm = l21 norm sum else l21 norm = 0 0 return l21 norm | 8077 | def norm_l21_tf(Z, shape, n_orient):
if Z.shape[0]:
Z2 = Z.reshape(*shape)
l21_norm = np.sqrt(stft_norm2(Z2).reshape((-1), n_orient).sum(axis=1))
l21_norm = l21_norm.sum()
else:
l21_norm = 0.0
return l21_norm
| L21 norm for TF. | l21 norm for tf . | Question:
What does this function do?
Code:
def norm_l21_tf(Z, shape, n_orient):
if Z.shape[0]:
Z2 = Z.reshape(*shape)
l21_norm = np.sqrt(stft_norm2(Z2).reshape((-1), n_orient).sum(axis=1))
l21_norm = l21_norm.sum()
else:
l21_norm = 0.0
return l21_norm
|
null | null | null | What does this function do? | @register.inclusion_tag('zinnia/tags/dummy.html')
def get_featured_entries(number=5, template='zinnia/tags/entries_featured.html'):
return {'template': template, 'entries': Entry.published.filter(featured=True)[:number]}
| null | null | null | Return the featured entries. | pcsd | @register inclusion tag 'zinnia/tags/dummy html' def get featured entries number=5 template='zinnia/tags/entries featured html' return {'template' template 'entries' Entry published filter featured=True [ number]} | 8082 | @register.inclusion_tag('zinnia/tags/dummy.html')
def get_featured_entries(number=5, template='zinnia/tags/entries_featured.html'):
return {'template': template, 'entries': Entry.published.filter(featured=True)[:number]}
| Return the featured entries. | return the featured entries . | Question:
What does this function do?
Code:
@register.inclusion_tag('zinnia/tags/dummy.html')
def get_featured_entries(number=5, template='zinnia/tags/entries_featured.html'):
return {'template': template, 'entries': Entry.published.filter(featured=True)[:number]}
|
null | null | null | What does this function do? | def build_model(tparams, options):
opt_ret = dict()
trng = RandomStreams(1234)
x = tensor.matrix('x', dtype='int64')
mask = tensor.matrix('mask', dtype='float32')
ctx = tensor.matrix('ctx', dtype='float32')
n_timesteps = x.shape[0]
n_samples = x.shape[1]
emb = tparams['Wemb'][x.flatten()].reshape([n_timesteps, ... | null | null | null | Computation graph for the model | pcsd | def build model tparams options opt ret = dict trng = Random Streams 1234 x = tensor matrix 'x' dtype='int64' mask = tensor matrix 'mask' dtype='float32' ctx = tensor matrix 'ctx' dtype='float32' n timesteps = x shape[0] n samples = x shape[1] emb = tparams['Wemb'][x flatten ] reshape [n timesteps n samples options['di... | 8084 | def build_model(tparams, options):
opt_ret = dict()
trng = RandomStreams(1234)
x = tensor.matrix('x', dtype='int64')
mask = tensor.matrix('mask', dtype='float32')
ctx = tensor.matrix('ctx', dtype='float32')
n_timesteps = x.shape[0]
n_samples = x.shape[1]
emb = tparams['Wemb'][x.flatten()].reshape([n_timesteps, ... | Computation graph for the model | computation graph for the model | Question:
What does this function do?
Code:
def build_model(tparams, options):
opt_ret = dict()
trng = RandomStreams(1234)
x = tensor.matrix('x', dtype='int64')
mask = tensor.matrix('mask', dtype='float32')
ctx = tensor.matrix('ctx', dtype='float32')
n_timesteps = x.shape[0]
n_samples = x.shape[1]
emb = tpar... |
null | null | null | What does this function do? | @api_wrapper
def get_volume(module, system):
try:
return system.volumes.get(name=module.params['name'])
except:
return None
| null | null | null | Return Volume or None | pcsd | @api wrapper def get volume module system try return system volumes get name=module params['name'] except return None | 8095 | @api_wrapper
def get_volume(module, system):
try:
return system.volumes.get(name=module.params['name'])
except:
return None
| Return Volume or None | return volume or none | Question:
What does this function do?
Code:
@api_wrapper
def get_volume(module, system):
try:
return system.volumes.get(name=module.params['name'])
except:
return None
|
null | null | null | What does this function do? | def addValueToOutput(depth, keyInput, output, value):
depthStart = (' ' * depth)
output.write(('%s%s:' % (depthStart, keyInput)))
if (value.__class__ == dict):
output.write('\n')
keys = value.keys()
keys.sort()
for key in keys:
addValueToOutput((depth + 1), key, output, value[key])
return
if (value.__... | null | null | null | Add value to the output. | pcsd | def add Value To Output depth key Input output value depth Start = ' ' * depth output write '%s%s ' % depth Start key Input if value class == dict output write ' ' keys = value keys keys sort for key in keys add Value To Output depth + 1 key output value[key] return if value class == list output write ' ' for element I... | 8096 | def addValueToOutput(depth, keyInput, output, value):
depthStart = (' ' * depth)
output.write(('%s%s:' % (depthStart, keyInput)))
if (value.__class__ == dict):
output.write('\n')
keys = value.keys()
keys.sort()
for key in keys:
addValueToOutput((depth + 1), key, output, value[key])
return
if (value.__... | Add value to the output. | add value to the output . | Question:
What does this function do?
Code:
def addValueToOutput(depth, keyInput, output, value):
depthStart = (' ' * depth)
output.write(('%s%s:' % (depthStart, keyInput)))
if (value.__class__ == dict):
output.write('\n')
keys = value.keys()
keys.sort()
for key in keys:
addValueToOutput((depth + 1), ... |
null | null | null | What does this function do? | def format_freshdesk_ticket_creation_message(ticket):
cleaned_description = convert_html_to_markdown(ticket.description)
content = ('%s <%s> created [ticket #%s](%s):\n\n' % (ticket.requester_name, ticket.requester_email, ticket.id, ticket.url))
content += ('~~~ quote\n%s\n~~~\n\n' % (cleaned_description,))
content... | null | null | null | They send us the description as HTML. | pcsd | def format freshdesk ticket creation message ticket cleaned description = convert html to markdown ticket description content = '%s <%s> created [ticket #%s] %s ' % ticket requester name ticket requester email ticket id ticket url content += '~~~ quote %s ~~~ ' % cleaned description content += 'Type **%s** Priority **%... | 8098 | def format_freshdesk_ticket_creation_message(ticket):
cleaned_description = convert_html_to_markdown(ticket.description)
content = ('%s <%s> created [ticket #%s](%s):\n\n' % (ticket.requester_name, ticket.requester_email, ticket.id, ticket.url))
content += ('~~~ quote\n%s\n~~~\n\n' % (cleaned_description,))
content... | They send us the description as HTML. | they send us the description as html . | Question:
What does this function do?
Code:
def format_freshdesk_ticket_creation_message(ticket):
cleaned_description = convert_html_to_markdown(ticket.description)
content = ('%s <%s> created [ticket #%s](%s):\n\n' % (ticket.requester_name, ticket.requester_email, ticket.id, ticket.url))
content += ('~~~ quote\n... |
null | null | null | What does this function do? | def worker(buffer, n, offset, mod, process_packet):
def update_timer():
if ((time.time() - os.stat(TRAILS_FILE).st_mtime) >= config.UPDATE_PERIOD):
_ = None
while True:
_ = load_trails(True)
if _:
trails.clear()
trails.update(_)
break
else:
time.sleep(LOAD_TRAILS_RETRY_SLEEP_TIM... | null | null | null | Worker process used in multiprocessing mode | pcsd | def worker buffer n offset mod process packet def update timer if time time - os stat TRAILS FILE st mtime >= config UPDATE PERIOD = None while True = load trails True if trails clear trails update break else time sleep LOAD TRAILS RETRY SLEEP TIME threading Timer config UPDATE PERIOD update timer start update timer co... | 8107 | def worker(buffer, n, offset, mod, process_packet):
def update_timer():
if ((time.time() - os.stat(TRAILS_FILE).st_mtime) >= config.UPDATE_PERIOD):
_ = None
while True:
_ = load_trails(True)
if _:
trails.clear()
trails.update(_)
break
else:
time.sleep(LOAD_TRAILS_RETRY_SLEEP_TIM... | Worker process used in multiprocessing mode | worker process used in multiprocessing mode | Question:
What does this function do?
Code:
def worker(buffer, n, offset, mod, process_packet):
def update_timer():
if ((time.time() - os.stat(TRAILS_FILE).st_mtime) >= config.UPDATE_PERIOD):
_ = None
while True:
_ = load_trails(True)
if _:
trails.clear()
trails.update(_)
break
el... |
null | null | null | What does this function do? | def build_fragments_list(boot_info):
res = []
segment_run_table = boot_info[u'segments'][0]
segment_run_entry = segment_run_table[u'segment_run'][0]
n_frags = segment_run_entry[1]
fragment_run_entry_table = boot_info[u'fragments'][0][u'fragments']
first_frag_number = fragment_run_entry_table[0][u'first']
for (i,... | null | null | null | Return a list of (segment, fragment) for each fragment in the video | pcsd | def build fragments list boot info res = [] segment run table = boot info[u'segments'][0] segment run entry = segment run table[u'segment run'][0] n frags = segment run entry[1] fragment run entry table = boot info[u'fragments'][0][u'fragments'] first frag number = fragment run entry table[0][u'first'] for i frag numbe... | 8110 | def build_fragments_list(boot_info):
res = []
segment_run_table = boot_info[u'segments'][0]
segment_run_entry = segment_run_table[u'segment_run'][0]
n_frags = segment_run_entry[1]
fragment_run_entry_table = boot_info[u'fragments'][0][u'fragments']
first_frag_number = fragment_run_entry_table[0][u'first']
for (i,... | Return a list of (segment, fragment) for each fragment in the video | return a list of for each fragment in the video | Question:
What does this function do?
Code:
def build_fragments_list(boot_info):
res = []
segment_run_table = boot_info[u'segments'][0]
segment_run_entry = segment_run_table[u'segment_run'][0]
n_frags = segment_run_entry[1]
fragment_run_entry_table = boot_info[u'fragments'][0][u'fragments']
first_frag_number =... |
null | null | null | What does this function do? | def _map_rect_to_scene(self, rect):
return self.sceneTransform().mapRect(rect)
| null | null | null | Only available in newer PyQt4 versions | pcsd | def map rect to scene self rect return self scene Transform map Rect rect | 8120 | def _map_rect_to_scene(self, rect):
return self.sceneTransform().mapRect(rect)
| Only available in newer PyQt4 versions | only available in newer pyqt4 versions | Question:
What does this function do?
Code:
def _map_rect_to_scene(self, rect):
return self.sceneTransform().mapRect(rect)
|
null | null | null | What does this function do? | def select_indirect_adjacent(cache, left, right):
right = (always_in if (right is None) else frozenset(right))
for parent in left:
for sibling in cache.itersiblings(parent):
if (sibling in right):
(yield sibling)
| null | null | null | right is a sibling after left, immediately or not | pcsd | def select indirect adjacent cache left right right = always in if right is None else frozenset right for parent in left for sibling in cache itersiblings parent if sibling in right yield sibling | 8122 | def select_indirect_adjacent(cache, left, right):
right = (always_in if (right is None) else frozenset(right))
for parent in left:
for sibling in cache.itersiblings(parent):
if (sibling in right):
(yield sibling)
| right is a sibling after left, immediately or not | right is a sibling after left , immediately or not | Question:
What does this function do?
Code:
def select_indirect_adjacent(cache, left, right):
right = (always_in if (right is None) else frozenset(right))
for parent in left:
for sibling in cache.itersiblings(parent):
if (sibling in right):
(yield sibling)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.