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 fix_eols(s): s = re.sub('(?<!\\r)\\n', CRLF, s) s = re.sub('\\r(?!\\n)', CRLF, s) return s
null
null
null
Replace all line-ending characters with
pcsd
def fix eols s s = re sub ' ?<!\\r \ ' CRLF s s = re sub '\\r ?!\ ' CRLF s return s
5963
def fix_eols(s): s = re.sub('(?<!\\r)\\n', CRLF, s) s = re.sub('\\r(?!\\n)', CRLF, s) return s
Replace all line-ending characters with
replace all line - ending characters with
Question: What does this function do? Code: def fix_eols(s): s = re.sub('(?<!\\r)\\n', CRLF, s) s = re.sub('\\r(?!\\n)', CRLF, s) return s
null
null
null
What does this function do?
@app.route('/library') def library(): papers = papers_from_library() ret = encode_json(papers, 500) if g.user: msg = ('%d papers in your library:' % (len(ret),)) else: msg = 'You must be logged in. Once you are, you can save papers to your library (with the save icon on the right of each paper) and they will show up here.' ctx = default_context(papers, render_format='library', msg=msg) return render_template('main.html', **ctx)
null
null
null
render user\'s library
pcsd
@app route '/library' def library papers = papers from library ret = encode json papers 500 if g user msg = '%d papers in your library ' % len ret else msg = 'You must be logged in Once you are you can save papers to your library with the save icon on the right of each paper and they will show up here ' ctx = default context papers render format='library' msg=msg return render template 'main html' **ctx
5968
@app.route('/library') def library(): papers = papers_from_library() ret = encode_json(papers, 500) if g.user: msg = ('%d papers in your library:' % (len(ret),)) else: msg = 'You must be logged in. Once you are, you can save papers to your library (with the save icon on the right of each paper) and they will show up here.' ctx = default_context(papers, render_format='library', msg=msg) return render_template('main.html', **ctx)
render user\'s library
render users library
Question: What does this function do? Code: @app.route('/library') def library(): papers = papers_from_library() ret = encode_json(papers, 500) if g.user: msg = ('%d papers in your library:' % (len(ret),)) else: msg = 'You must be logged in. Once you are, you can save papers to your library (with the save icon on the right of each paper) and they will show up here.' ctx = default_context(papers, render_format='library', msg=msg) return render_template('main.html', **ctx)
null
null
null
What does this function do?
def _get_options(ret): attrs = {'host': 'host', 'port': 'port', 'skip': 'skip_on_error', 'mode': 'mode'} _options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__) return _options
null
null
null
Returns options used for the carbon returner.
pcsd
def get options ret attrs = {'host' 'host' 'port' 'port' 'skip' 'skip on error' 'mode' 'mode'} options = salt returners get returner options virtualname ret attrs salt = salt opts = opts return options
5970
def _get_options(ret): attrs = {'host': 'host', 'port': 'port', 'skip': 'skip_on_error', 'mode': 'mode'} _options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__) return _options
Returns options used for the carbon returner.
returns options used for the carbon returner .
Question: What does this function do? Code: def _get_options(ret): attrs = {'host': 'host', 'port': 'port', 'skip': 'skip_on_error', 'mode': 'mode'} _options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__) return _options
null
null
null
What does this function do?
def get_conn(host=None, username=None, password=None): if (not HAS_IMPACKET): return False conn = impacket.smbconnection.SMBConnection(remoteName='*SMBSERVER', remoteHost=host) conn.login(user=username, password=password) return conn
null
null
null
Get an SMB connection
pcsd
def get conn host=None username=None password=None if not HAS IMPACKET return False conn = impacket smbconnection SMB Connection remote Name='*SMBSERVER' remote Host=host conn login user=username password=password return conn
5974
def get_conn(host=None, username=None, password=None): if (not HAS_IMPACKET): return False conn = impacket.smbconnection.SMBConnection(remoteName='*SMBSERVER', remoteHost=host) conn.login(user=username, password=password) return conn
Get an SMB connection
get an smb connection
Question: What does this function do? Code: def get_conn(host=None, username=None, password=None): if (not HAS_IMPACKET): return False conn = impacket.smbconnection.SMBConnection(remoteName='*SMBSERVER', remoteHost=host) conn.login(user=username, password=password) return conn
null
null
null
What does this function do?
@click.command(name='import') @click.argument('src', type=click.File('rb')) @configuration def import_(src): from django.core import serializers for obj in serializers.deserialize('json', src, stream=True, use_natural_keys=True): obj.save()
null
null
null
Imports data from a Sentry export.
pcsd
@click command name='import' @click argument 'src' type=click File 'rb' @configuration def import src from django core import serializers for obj in serializers deserialize 'json' src stream=True use natural keys=True obj save
5975
@click.command(name='import') @click.argument('src', type=click.File('rb')) @configuration def import_(src): from django.core import serializers for obj in serializers.deserialize('json', src, stream=True, use_natural_keys=True): obj.save()
Imports data from a Sentry export.
imports data from a sentry export .
Question: What does this function do? Code: @click.command(name='import') @click.argument('src', type=click.File('rb')) @configuration def import_(src): from django.core import serializers for obj in serializers.deserialize('json', src, stream=True, use_natural_keys=True): obj.save()
null
null
null
What does this function do?
def create_document_editor_user(): User = get_user_model() (user, user_created) = User.objects.get_or_create(username='conantheeditor', defaults=dict(email='user_%s@example.com', is_active=True, is_staff=False, is_superuser=False)) if user_created: user.set_password('testpass') user.groups = [create_document_editor_group()] user.save() return user
null
null
null
Get or create a user empowered with document editing.
pcsd
def create document editor user User = get user model user user created = User objects get or create username='conantheeditor' defaults=dict email='user %s@example com' is active=True is staff=False is superuser=False if user created user set password 'testpass' user groups = [create document editor group ] user save return user
5977
def create_document_editor_user(): User = get_user_model() (user, user_created) = User.objects.get_or_create(username='conantheeditor', defaults=dict(email='user_%s@example.com', is_active=True, is_staff=False, is_superuser=False)) if user_created: user.set_password('testpass') user.groups = [create_document_editor_group()] user.save() return user
Get or create a user empowered with document editing.
get or create a user empowered with document editing .
Question: What does this function do? Code: def create_document_editor_user(): User = get_user_model() (user, user_created) = User.objects.get_or_create(username='conantheeditor', defaults=dict(email='user_%s@example.com', is_active=True, is_staff=False, is_superuser=False)) if user_created: user.set_password('testpass') user.groups = [create_document_editor_group()] user.save() return user
null
null
null
What does this function do?
def recompose_xfm(in_bval, in_xfms): import numpy as np import os.path as op bvals = np.loadtxt(in_bval) out_matrix = np.array(([np.eye(4)] * len(bvals))) xfms = iter([np.loadtxt(xfm) for xfm in in_xfms]) out_files = [] for (i, b) in enumerate(bvals): if (b == 0.0): mat = np.eye(4) else: mat = next(xfms) out_name = op.abspath((u'eccor_%04d.mat' % i)) out_files.append(out_name) np.savetxt(out_name, mat) return out_files
null
null
null
Insert identity transformation matrices in b0 volumes to build up a list
pcsd
def recompose xfm in bval in xfms import numpy as np import os path as op bvals = np loadtxt in bval out matrix = np array [np eye 4 ] * len bvals xfms = iter [np loadtxt xfm for xfm in in xfms] out files = [] for i b in enumerate bvals if b == 0 0 mat = np eye 4 else mat = next xfms out name = op abspath u'eccor %04d mat' % i out files append out name np savetxt out name mat return out files
5979
def recompose_xfm(in_bval, in_xfms): import numpy as np import os.path as op bvals = np.loadtxt(in_bval) out_matrix = np.array(([np.eye(4)] * len(bvals))) xfms = iter([np.loadtxt(xfm) for xfm in in_xfms]) out_files = [] for (i, b) in enumerate(bvals): if (b == 0.0): mat = np.eye(4) else: mat = next(xfms) out_name = op.abspath((u'eccor_%04d.mat' % i)) out_files.append(out_name) np.savetxt(out_name, mat) return out_files
Insert identity transformation matrices in b0 volumes to build up a list
insert identity transformation matrices in b0 volumes to build up a list
Question: What does this function do? Code: def recompose_xfm(in_bval, in_xfms): import numpy as np import os.path as op bvals = np.loadtxt(in_bval) out_matrix = np.array(([np.eye(4)] * len(bvals))) xfms = iter([np.loadtxt(xfm) for xfm in in_xfms]) out_files = [] for (i, b) in enumerate(bvals): if (b == 0.0): mat = np.eye(4) else: mat = next(xfms) out_name = op.abspath((u'eccor_%04d.mat' % i)) out_files.append(out_name) np.savetxt(out_name, mat) return out_files
null
null
null
What does this function do?
def teardown_module(): os.remove(FAKEFILE)
null
null
null
Tear down the module.
pcsd
def teardown module os remove FAKEFILE
5980
def teardown_module(): os.remove(FAKEFILE)
Tear down the module.
tear down the module .
Question: What does this function do? Code: def teardown_module(): os.remove(FAKEFILE)
null
null
null
What does this function do?
def to_int(val): try: return int(str(val), 0) except: return None
null
null
null
Convert a string to int number
pcsd
def to int val try return int str val 0 except return None
5982
def to_int(val): try: return int(str(val), 0) except: return None
Convert a string to int number
convert a string to int number
Question: What does this function do? Code: def to_int(val): try: return int(str(val), 0) except: return None
null
null
null
What does this function do?
def reshape(x, shape): return tf.reshape(x, shape)
null
null
null
Reshapes a tensor to the specified shape. # Returns A tensor.
pcsd
def reshape x shape return tf reshape x shape
5989
def reshape(x, shape): return tf.reshape(x, shape)
Reshapes a tensor to the specified shape. # Returns A tensor.
reshapes a tensor to the specified shape .
Question: What does this function do? Code: def reshape(x, shape): return tf.reshape(x, shape)
null
null
null
What does this function do?
def _check_to_bytes(self, in_string, encoding, expected): self.assertEqual(to_bytes(in_string, encoding), expected)
null
null
null
test happy path of encoding to bytes
pcsd
def check to bytes self in string encoding expected self assert Equal to bytes in string encoding expected
5994
def _check_to_bytes(self, in_string, encoding, expected): self.assertEqual(to_bytes(in_string, encoding), expected)
test happy path of encoding to bytes
test happy path of encoding to bytes
Question: What does this function do? Code: def _check_to_bytes(self, in_string, encoding, expected): self.assertEqual(to_bytes(in_string, encoding), expected)
null
null
null
What does this function do?
def get_ref_to_doc(refname, title=''): ref = addnodes.pending_xref(reftype='ref', reftarget=refname, refexplicit=(title != ''), refdomain='std') ref += nodes.literal(title, title, classes=['xref']) return ref
null
null
null
Returns a node that links to a document with the given ref name.
pcsd
def get ref to doc refname title='' ref = addnodes pending xref reftype='ref' reftarget=refname refexplicit= title != '' refdomain='std' ref += nodes literal title title classes=['xref'] return ref
6006
def get_ref_to_doc(refname, title=''): ref = addnodes.pending_xref(reftype='ref', reftarget=refname, refexplicit=(title != ''), refdomain='std') ref += nodes.literal(title, title, classes=['xref']) return ref
Returns a node that links to a document with the given ref name.
returns a node that links to a document with the given ref name .
Question: What does this function do? Code: def get_ref_to_doc(refname, title=''): ref = addnodes.pending_xref(reftype='ref', reftarget=refname, refexplicit=(title != ''), refdomain='std') ref += nodes.literal(title, title, classes=['xref']) return ref
null
null
null
What does this function do?
@pytest.mark.parametrize('parallel', [True, False]) def test_no_header_supplied_names(parallel, read_basic, read_no_header): table = read_no_header('A B C\n1 2 3\n4 5 6', names=('X', 'Y', 'Z'), parallel=parallel) expected = Table([['A', '1', '4'], ['B', '2', '5'], ['C', '3', '6']], names=('X', 'Y', 'Z')) assert_table_equal(table, expected)
null
null
null
If header_start=None and names is passed as a parameter, header data should not be read and names should be used instead.
pcsd
@pytest mark parametrize 'parallel' [True False] def test no header supplied names parallel read basic read no header table = read no header 'A B C 1 2 3 4 5 6' names= 'X' 'Y' 'Z' parallel=parallel expected = Table [['A' '1' '4'] ['B' '2' '5'] ['C' '3' '6']] names= 'X' 'Y' 'Z' assert table equal table expected
6007
@pytest.mark.parametrize('parallel', [True, False]) def test_no_header_supplied_names(parallel, read_basic, read_no_header): table = read_no_header('A B C\n1 2 3\n4 5 6', names=('X', 'Y', 'Z'), parallel=parallel) expected = Table([['A', '1', '4'], ['B', '2', '5'], ['C', '3', '6']], names=('X', 'Y', 'Z')) assert_table_equal(table, expected)
If header_start=None and names is passed as a parameter, header data should not be read and names should be used instead.
if header _ start = none and names is passed as a parameter , header data should not be read and names should be used instead .
Question: What does this function do? Code: @pytest.mark.parametrize('parallel', [True, False]) def test_no_header_supplied_names(parallel, read_basic, read_no_header): table = read_no_header('A B C\n1 2 3\n4 5 6', names=('X', 'Y', 'Z'), parallel=parallel) expected = Table([['A', '1', '4'], ['B', '2', '5'], ['C', '3', '6']], names=('X', 'Y', 'Z')) assert_table_equal(table, expected)
null
null
null
What does this function do?
def _CanBreakBefore(prev_token, cur_token): pval = prev_token.value cval = cur_token.value if py3compat.PY3: if ((pval == 'yield') and (cval == 'from')): return False if ((pval in {'async', 'await'}) and (cval in {'def', 'with', 'for'})): return False if (cur_token.split_penalty >= split_penalty.UNBREAKABLE): return False if (pval == '@'): return False if (cval == ':'): return False if (cval == ','): return False if (prev_token.is_name and (cval == '(')): return False if (prev_token.is_name and (cval == '[')): return False if (prev_token.is_name and (cval == '.')): return False if (cur_token.is_comment and (prev_token.lineno == cur_token.lineno)): return False if (format_token.Subtype.UNARY_OPERATOR in prev_token.subtypes): return False return True
null
null
null
Return True if a line break may occur before the current token.
pcsd
def Can Break Before prev token cur token pval = prev token value cval = cur token value if py3compat PY3 if pval == 'yield' and cval == 'from' return False if pval in {'async' 'await'} and cval in {'def' 'with' 'for'} return False if cur token split penalty >= split penalty UNBREAKABLE return False if pval == '@' return False if cval == ' ' return False if cval == ' ' return False if prev token is name and cval == ' ' return False if prev token is name and cval == '[' return False if prev token is name and cval == ' ' return False if cur token is comment and prev token lineno == cur token lineno return False if format token Subtype UNARY OPERATOR in prev token subtypes return False return True
6015
def _CanBreakBefore(prev_token, cur_token): pval = prev_token.value cval = cur_token.value if py3compat.PY3: if ((pval == 'yield') and (cval == 'from')): return False if ((pval in {'async', 'await'}) and (cval in {'def', 'with', 'for'})): return False if (cur_token.split_penalty >= split_penalty.UNBREAKABLE): return False if (pval == '@'): return False if (cval == ':'): return False if (cval == ','): return False if (prev_token.is_name and (cval == '(')): return False if (prev_token.is_name and (cval == '[')): return False if (prev_token.is_name and (cval == '.')): return False if (cur_token.is_comment and (prev_token.lineno == cur_token.lineno)): return False if (format_token.Subtype.UNARY_OPERATOR in prev_token.subtypes): return False return True
Return True if a line break may occur before the current token.
return true if a line break may occur before the current token .
Question: What does this function do? Code: def _CanBreakBefore(prev_token, cur_token): pval = prev_token.value cval = cur_token.value if py3compat.PY3: if ((pval == 'yield') and (cval == 'from')): return False if ((pval in {'async', 'await'}) and (cval in {'def', 'with', 'for'})): return False if (cur_token.split_penalty >= split_penalty.UNBREAKABLE): return False if (pval == '@'): return False if (cval == ':'): return False if (cval == ','): return False if (prev_token.is_name and (cval == '(')): return False if (prev_token.is_name and (cval == '[')): return False if (prev_token.is_name and (cval == '.')): return False if (cur_token.is_comment and (prev_token.lineno == cur_token.lineno)): return False if (format_token.Subtype.UNARY_OPERATOR in prev_token.subtypes): return False return True
null
null
null
What does this function do?
def donor(): tablename = 'org_donor' table = s3db[tablename] tablename = 'org_donor' s3.crud_strings[tablename] = Storage(label_create=ADD_DONOR, title_display=T('Donor Details'), title_list=T('Donors Report'), title_update=T('Edit Donor'), label_list_button=T('List Donors'), label_delete_button=T('Delete Donor'), msg_record_created=T('Donor added'), msg_record_modified=T('Donor updated'), msg_record_deleted=T('Donor deleted'), msg_list_empty=T('No Donors currently registered')) s3db.configure(tablename, listadd=False) output = s3_rest_controller() return output
null
null
null
RESTful CRUD controller
pcsd
def donor tablename = 'org donor' table = s3db[tablename] tablename = 'org donor' s3 crud strings[tablename] = Storage label create=ADD DONOR title display=T 'Donor Details' title list=T 'Donors Report' title update=T 'Edit Donor' label list button=T 'List Donors' label delete button=T 'Delete Donor' msg record created=T 'Donor added' msg record modified=T 'Donor updated' msg record deleted=T 'Donor deleted' msg list empty=T 'No Donors currently registered' s3db configure tablename listadd=False output = s3 rest controller return output
6021
def donor(): tablename = 'org_donor' table = s3db[tablename] tablename = 'org_donor' s3.crud_strings[tablename] = Storage(label_create=ADD_DONOR, title_display=T('Donor Details'), title_list=T('Donors Report'), title_update=T('Edit Donor'), label_list_button=T('List Donors'), label_delete_button=T('Delete Donor'), msg_record_created=T('Donor added'), msg_record_modified=T('Donor updated'), msg_record_deleted=T('Donor deleted'), msg_list_empty=T('No Donors currently registered')) s3db.configure(tablename, listadd=False) output = s3_rest_controller() return output
RESTful CRUD controller
restful crud controller
Question: What does this function do? Code: def donor(): tablename = 'org_donor' table = s3db[tablename] tablename = 'org_donor' s3.crud_strings[tablename] = Storage(label_create=ADD_DONOR, title_display=T('Donor Details'), title_list=T('Donors Report'), title_update=T('Edit Donor'), label_list_button=T('List Donors'), label_delete_button=T('Delete Donor'), msg_record_created=T('Donor added'), msg_record_modified=T('Donor updated'), msg_record_deleted=T('Donor deleted'), msg_list_empty=T('No Donors currently registered')) s3db.configure(tablename, listadd=False) output = s3_rest_controller() return output
null
null
null
What does this function do?
def p_specifier_qualifier_list_4(t): pass
null
null
null
specifier_qualifier_list : type_qualifier
pcsd
def p specifier qualifier list 4 t pass
6028
def p_specifier_qualifier_list_4(t): pass
specifier_qualifier_list : type_qualifier
specifier _ qualifier _ list : type _ qualifier
Question: What does this function do? Code: def p_specifier_qualifier_list_4(t): pass
null
null
null
What does this function do?
def _query(action=None, command=None, args=None, method='GET', header_dict=None, data=None): apiid = __opts__.get('stormpath', {}).get('apiid', None) apikey = __opts__.get('stormpath', {}).get('apikey', None) path = 'https://api.stormpath.com/v1/' if action: path += action if command: path += '/{0}'.format(command) log.debug('Stormpath URL: {0}'.format(path)) if (not isinstance(args, dict)): args = {} if (header_dict is None): header_dict = {} if (method != 'POST'): header_dict['Accept'] = 'application/json' decode = True if (method == 'DELETE'): decode = False return_content = None result = salt.utils.http.query(path, method, username=apiid, password=apikey, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', text=True, status=True, opts=__opts__) log.debug('Stormpath Response Status Code: {0}'.format(result['status'])) return [result['status'], result.get('dict', {})]
null
null
null
Make a web call to Stormpath.
pcsd
def query action=None command=None args=None method='GET' header dict=None data=None apiid = opts get 'stormpath' {} get 'apiid' None apikey = opts get 'stormpath' {} get 'apikey' None path = 'https //api stormpath com/v1/' if action path += action if command path += '/{0}' format command log debug 'Stormpath URL {0}' format path if not isinstance args dict args = {} if header dict is None header dict = {} if method != 'POST' header dict['Accept'] = 'application/json' decode = True if method == 'DELETE' decode = False return content = None result = salt utils http query path method username=apiid password=apikey params=args data=data header dict=header dict decode=decode decode type='json' text=True status=True opts= opts log debug 'Stormpath Response Status Code {0}' format result['status'] return [result['status'] result get 'dict' {} ]
6042
def _query(action=None, command=None, args=None, method='GET', header_dict=None, data=None): apiid = __opts__.get('stormpath', {}).get('apiid', None) apikey = __opts__.get('stormpath', {}).get('apikey', None) path = 'https://api.stormpath.com/v1/' if action: path += action if command: path += '/{0}'.format(command) log.debug('Stormpath URL: {0}'.format(path)) if (not isinstance(args, dict)): args = {} if (header_dict is None): header_dict = {} if (method != 'POST'): header_dict['Accept'] = 'application/json' decode = True if (method == 'DELETE'): decode = False return_content = None result = salt.utils.http.query(path, method, username=apiid, password=apikey, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', text=True, status=True, opts=__opts__) log.debug('Stormpath Response Status Code: {0}'.format(result['status'])) return [result['status'], result.get('dict', {})]
Make a web call to Stormpath.
make a web call to stormpath .
Question: What does this function do? Code: def _query(action=None, command=None, args=None, method='GET', header_dict=None, data=None): apiid = __opts__.get('stormpath', {}).get('apiid', None) apikey = __opts__.get('stormpath', {}).get('apikey', None) path = 'https://api.stormpath.com/v1/' if action: path += action if command: path += '/{0}'.format(command) log.debug('Stormpath URL: {0}'.format(path)) if (not isinstance(args, dict)): args = {} if (header_dict is None): header_dict = {} if (method != 'POST'): header_dict['Accept'] = 'application/json' decode = True if (method == 'DELETE'): decode = False return_content = None result = salt.utils.http.query(path, method, username=apiid, password=apikey, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', text=True, status=True, opts=__opts__) log.debug('Stormpath Response Status Code: {0}'.format(result['status'])) return [result['status'], result.get('dict', {})]
null
null
null
What does this function do?
@contextfunction def show_hint(context, hint=None, object=None): request = context['request'] response_format = 'html' user = None if request.user.username: try: user = request.user.profile except Exception: pass return Markup(render_to_string(('core/hints/' + hint), {'user': user, 'object': object}, response_format=response_format))
null
null
null
Generic hint framework
pcsd
@contextfunction def show hint context hint=None object=None request = context['request'] response format = 'html' user = None if request user username try user = request user profile except Exception pass return Markup render to string 'core/hints/' + hint {'user' user 'object' object} response format=response format
6043
@contextfunction def show_hint(context, hint=None, object=None): request = context['request'] response_format = 'html' user = None if request.user.username: try: user = request.user.profile except Exception: pass return Markup(render_to_string(('core/hints/' + hint), {'user': user, 'object': object}, response_format=response_format))
Generic hint framework
generic hint framework
Question: What does this function do? Code: @contextfunction def show_hint(context, hint=None, object=None): request = context['request'] response_format = 'html' user = None if request.user.username: try: user = request.user.profile except Exception: pass return Markup(render_to_string(('core/hints/' + hint), {'user': user, 'object': object}, response_format=response_format))
null
null
null
What does this function do?
def getEvaluatedBooleanDefault(defaultBoolean, key, xmlElement=None): if (xmlElement == None): return None if (key in xmlElement.attributeDictionary): return euclidean.getBooleanFromValue(getEvaluatedValueObliviously(key, xmlElement)) return defaultBoolean
null
null
null
Get the evaluated boolean as a float.
pcsd
def get Evaluated Boolean Default default Boolean key xml Element=None if xml Element == None return None if key in xml Element attribute Dictionary return euclidean get Boolean From Value get Evaluated Value Obliviously key xml Element return default Boolean
6049
def getEvaluatedBooleanDefault(defaultBoolean, key, xmlElement=None): if (xmlElement == None): return None if (key in xmlElement.attributeDictionary): return euclidean.getBooleanFromValue(getEvaluatedValueObliviously(key, xmlElement)) return defaultBoolean
Get the evaluated boolean as a float.
get the evaluated boolean as a float .
Question: What does this function do? Code: def getEvaluatedBooleanDefault(defaultBoolean, key, xmlElement=None): if (xmlElement == None): return None if (key in xmlElement.attributeDictionary): return euclidean.getBooleanFromValue(getEvaluatedValueObliviously(key, xmlElement)) return defaultBoolean
null
null
null
What does this function do?
def MakeID3v1(id3): v1 = {} for (v2id, name) in {'TIT2': 'title', 'TPE1': 'artist', 'TALB': 'album'}.items(): if (v2id in id3): text = id3[v2id].text[0].encode('latin1', 'replace')[:30] else: text = '' v1[name] = (text + ('\x00' * (30 - len(text)))) if ('COMM' in id3): cmnt = id3['COMM'].text[0].encode('latin1', 'replace')[:28] else: cmnt = '' v1['comment'] = (cmnt + ('\x00' * (29 - len(cmnt)))) if ('TRCK' in id3): try: v1['track'] = chr_((+ id3['TRCK'])) except ValueError: v1['track'] = '\x00' else: v1['track'] = '\x00' if ('TCON' in id3): try: genre = id3['TCON'].genres[0] except IndexError: pass else: if (genre in TCON.GENRES): v1['genre'] = chr_(TCON.GENRES.index(genre)) if ('genre' not in v1): v1['genre'] = '\xff' if ('TDRC' in id3): year = text_type(id3['TDRC']).encode('ascii') elif ('TYER' in id3): year = text_type(id3['TYER']).encode('ascii') else: year = '' v1['year'] = (year + '\x00\x00\x00\x00')[:4] return ((((((('TAG' + v1['title']) + v1['artist']) + v1['album']) + v1['year']) + v1['comment']) + v1['track']) + v1['genre'])
null
null
null
Return an ID3v1.1 tag string from a dict of ID3v2.4 frames.
pcsd
def Make ID3v1 id3 v1 = {} for v2id name in {'TIT2' 'title' 'TPE1' 'artist' 'TALB' 'album'} items if v2id in id3 text = id3[v2id] text[0] encode 'latin1' 'replace' [ 30] else text = '' v1[name] = text + '\x00' * 30 - len text if 'COMM' in id3 cmnt = id3['COMM'] text[0] encode 'latin1' 'replace' [ 28] else cmnt = '' v1['comment'] = cmnt + '\x00' * 29 - len cmnt if 'TRCK' in id3 try v1['track'] = chr + id3['TRCK'] except Value Error v1['track'] = '\x00' else v1['track'] = '\x00' if 'TCON' in id3 try genre = id3['TCON'] genres[0] except Index Error pass else if genre in TCON GENRES v1['genre'] = chr TCON GENRES index genre if 'genre' not in v1 v1['genre'] = '\xff' if 'TDRC' in id3 year = text type id3['TDRC'] encode 'ascii' elif 'TYER' in id3 year = text type id3['TYER'] encode 'ascii' else year = '' v1['year'] = year + '\x00\x00\x00\x00' [ 4] return 'TAG' + v1['title'] + v1['artist'] + v1['album'] + v1['year'] + v1['comment'] + v1['track'] + v1['genre']
6057
def MakeID3v1(id3): v1 = {} for (v2id, name) in {'TIT2': 'title', 'TPE1': 'artist', 'TALB': 'album'}.items(): if (v2id in id3): text = id3[v2id].text[0].encode('latin1', 'replace')[:30] else: text = '' v1[name] = (text + ('\x00' * (30 - len(text)))) if ('COMM' in id3): cmnt = id3['COMM'].text[0].encode('latin1', 'replace')[:28] else: cmnt = '' v1['comment'] = (cmnt + ('\x00' * (29 - len(cmnt)))) if ('TRCK' in id3): try: v1['track'] = chr_((+ id3['TRCK'])) except ValueError: v1['track'] = '\x00' else: v1['track'] = '\x00' if ('TCON' in id3): try: genre = id3['TCON'].genres[0] except IndexError: pass else: if (genre in TCON.GENRES): v1['genre'] = chr_(TCON.GENRES.index(genre)) if ('genre' not in v1): v1['genre'] = '\xff' if ('TDRC' in id3): year = text_type(id3['TDRC']).encode('ascii') elif ('TYER' in id3): year = text_type(id3['TYER']).encode('ascii') else: year = '' v1['year'] = (year + '\x00\x00\x00\x00')[:4] return ((((((('TAG' + v1['title']) + v1['artist']) + v1['album']) + v1['year']) + v1['comment']) + v1['track']) + v1['genre'])
Return an ID3v1.1 tag string from a dict of ID3v2.4 frames.
return an id3v1 . 1 tag string from a dict of id3v2 . 4 frames .
Question: What does this function do? Code: def MakeID3v1(id3): v1 = {} for (v2id, name) in {'TIT2': 'title', 'TPE1': 'artist', 'TALB': 'album'}.items(): if (v2id in id3): text = id3[v2id].text[0].encode('latin1', 'replace')[:30] else: text = '' v1[name] = (text + ('\x00' * (30 - len(text)))) if ('COMM' in id3): cmnt = id3['COMM'].text[0].encode('latin1', 'replace')[:28] else: cmnt = '' v1['comment'] = (cmnt + ('\x00' * (29 - len(cmnt)))) if ('TRCK' in id3): try: v1['track'] = chr_((+ id3['TRCK'])) except ValueError: v1['track'] = '\x00' else: v1['track'] = '\x00' if ('TCON' in id3): try: genre = id3['TCON'].genres[0] except IndexError: pass else: if (genre in TCON.GENRES): v1['genre'] = chr_(TCON.GENRES.index(genre)) if ('genre' not in v1): v1['genre'] = '\xff' if ('TDRC' in id3): year = text_type(id3['TDRC']).encode('ascii') elif ('TYER' in id3): year = text_type(id3['TYER']).encode('ascii') else: year = '' v1['year'] = (year + '\x00\x00\x00\x00')[:4] return ((((((('TAG' + v1['title']) + v1['artist']) + v1['album']) + v1['year']) + v1['comment']) + v1['track']) + v1['genre'])
null
null
null
What does this function do?
def get_connection(using=None): if (using is None): using = DEFAULT_DB_ALIAS return connections[using]
null
null
null
Get a database connection by name, or the default database connection if no name is provided.
pcsd
def get connection using=None if using is None using = DEFAULT DB ALIAS return connections[using]
6059
def get_connection(using=None): if (using is None): using = DEFAULT_DB_ALIAS return connections[using]
Get a database connection by name, or the default database connection if no name is provided.
get a database connection by name , or the default database connection if no name is provided .
Question: What does this function do? Code: def get_connection(using=None): if (using is None): using = DEFAULT_DB_ALIAS return connections[using]
null
null
null
What does this function do?
def owner(path, use_sudo=False): func = ((use_sudo and run_as_root) or run) with settings(hide('running', 'stdout'), warn_only=True): result = func(('stat -c %%U "%(path)s"' % locals())) if (result.failed and ('stat: illegal option' in result)): return func(('stat -f %%Su "%(path)s"' % locals())) else: return result
null
null
null
Get the owner name of a file or directory.
pcsd
def owner path use sudo=False func = use sudo and run as root or run with settings hide 'running' 'stdout' warn only=True result = func 'stat -c %%U "% path s"' % locals if result failed and 'stat illegal option' in result return func 'stat -f %%Su "% path s"' % locals else return result
6071
def owner(path, use_sudo=False): func = ((use_sudo and run_as_root) or run) with settings(hide('running', 'stdout'), warn_only=True): result = func(('stat -c %%U "%(path)s"' % locals())) if (result.failed and ('stat: illegal option' in result)): return func(('stat -f %%Su "%(path)s"' % locals())) else: return result
Get the owner name of a file or directory.
get the owner name of a file or directory .
Question: What does this function do? Code: def owner(path, use_sudo=False): func = ((use_sudo and run_as_root) or run) with settings(hide('running', 'stdout'), warn_only=True): result = func(('stat -c %%U "%(path)s"' % locals())) if (result.failed and ('stat: illegal option' in result)): return func(('stat -f %%Su "%(path)s"' % locals())) else: return result
null
null
null
What does this function do?
def cbranch_or_continue(builder, cond, bbtrue): bbcont = builder.append_basic_block('.continue') builder.cbranch(cond, bbtrue, bbcont) builder.position_at_end(bbcont) return bbcont
null
null
null
Branch conditionally or continue. Note: a new block is created and builder is moved to the end of the new block.
pcsd
def cbranch or continue builder cond bbtrue bbcont = builder append basic block ' continue' builder cbranch cond bbtrue bbcont builder position at end bbcont return bbcont
6075
def cbranch_or_continue(builder, cond, bbtrue): bbcont = builder.append_basic_block('.continue') builder.cbranch(cond, bbtrue, bbcont) builder.position_at_end(bbcont) return bbcont
Branch conditionally or continue. Note: a new block is created and builder is moved to the end of the new block.
branch conditionally or continue .
Question: What does this function do? Code: def cbranch_or_continue(builder, cond, bbtrue): bbcont = builder.append_basic_block('.continue') builder.cbranch(cond, bbtrue, bbcont) builder.position_at_end(bbcont) return bbcont
null
null
null
What does this function do?
def default_catalogue_backend(): msg = ("There is no '%s' backend in CATALOGUE" % DEFAULT_CATALOGUE_ALIAS) assert (DEFAULT_CATALOGUE_ALIAS in settings.CATALOGUE), msg return settings.CATALOGUE[DEFAULT_CATALOGUE_ALIAS]
null
null
null
Get the default backend
pcsd
def default catalogue backend msg = "There is no '%s' backend in CATALOGUE" % DEFAULT CATALOGUE ALIAS assert DEFAULT CATALOGUE ALIAS in settings CATALOGUE msg return settings CATALOGUE[DEFAULT CATALOGUE ALIAS]
6076
def default_catalogue_backend(): msg = ("There is no '%s' backend in CATALOGUE" % DEFAULT_CATALOGUE_ALIAS) assert (DEFAULT_CATALOGUE_ALIAS in settings.CATALOGUE), msg return settings.CATALOGUE[DEFAULT_CATALOGUE_ALIAS]
Get the default backend
get the default backend
Question: What does this function do? Code: def default_catalogue_backend(): msg = ("There is no '%s' backend in CATALOGUE" % DEFAULT_CATALOGUE_ALIAS) assert (DEFAULT_CATALOGUE_ALIAS in settings.CATALOGUE), msg return settings.CATALOGUE[DEFAULT_CATALOGUE_ALIAS]
null
null
null
What does this function do?
def create(): redirect(URL(f='new_assessment.iframe', vars={'viewing': ('survey_series.%s' % request.args[0])}))
null
null
null
Enter a new assessment. - provides a simpler URL to access from mobile devices...
pcsd
def create redirect URL f='new assessment iframe' vars={'viewing' 'survey series %s' % request args[0] }
6079
def create(): redirect(URL(f='new_assessment.iframe', vars={'viewing': ('survey_series.%s' % request.args[0])}))
Enter a new assessment. - provides a simpler URL to access from mobile devices...
enter a new assessment .
Question: What does this function do? Code: def create(): redirect(URL(f='new_assessment.iframe', vars={'viewing': ('survey_series.%s' % request.args[0])}))
null
null
null
What does this function do?
def IsPythonVersionCorrect(path): from ycmd import utils if (not EndsWithPython(path)): return False command = [path, u'-S', u'-c', u'import sys;major, minor = sys.version_info[ :2 ];good_python = ( major == 2 and minor >= 6 ) or ( major == 3 and minor >= 3 ) or major > 3;sys.exit( not good_python )'] return (utils.SafePopen(command).wait() == 0)
null
null
null
Check if given path is the Python interpreter version 2.6+ or 3.3+.
pcsd
def Is Python Version Correct path from ycmd import utils if not Ends With Python path return False command = [path u'-S' u'-c' u'import sys major minor = sys version info[ 2 ] good python = major == 2 and minor >= 6 or major == 3 and minor >= 3 or major > 3 sys exit not good python '] return utils Safe Popen command wait == 0
6084
def IsPythonVersionCorrect(path): from ycmd import utils if (not EndsWithPython(path)): return False command = [path, u'-S', u'-c', u'import sys;major, minor = sys.version_info[ :2 ];good_python = ( major == 2 and minor >= 6 ) or ( major == 3 and minor >= 3 ) or major > 3;sys.exit( not good_python )'] return (utils.SafePopen(command).wait() == 0)
Check if given path is the Python interpreter version 2.6+ or 3.3+.
check if given path is the python interpreter version 2 . 6 + or 3 . 3 + .
Question: What does this function do? Code: def IsPythonVersionCorrect(path): from ycmd import utils if (not EndsWithPython(path)): return False command = [path, u'-S', u'-c', u'import sys;major, minor = sys.version_info[ :2 ];good_python = ( major == 2 and minor >= 6 ) or ( major == 3 and minor >= 3 ) or major > 3;sys.exit( not good_python )'] return (utils.SafePopen(command).wait() == 0)
null
null
null
What does this function do?
def p_relational_expression_3(t): pass
null
null
null
relational_expression : relational_expression GT shift_expression
pcsd
def p relational expression 3 t pass
6088
def p_relational_expression_3(t): pass
relational_expression : relational_expression GT shift_expression
relational _ expression : relational _ expression gt shift _ expression
Question: What does this function do? Code: def p_relational_expression_3(t): pass
null
null
null
What does this function do?
def remote_interpreter(conn, namespace=None): if (namespace is None): namespace = {'conn': conn} std = RedirectedStd(conn) try: std.redirect() conn.modules[__name__]._remote_interpreter_server_side(**namespace) finally: std.restore()
null
null
null
starts an interactive interpreter on the server
pcsd
def remote interpreter conn namespace=None if namespace is None namespace = {'conn' conn} std = Redirected Std conn try std redirect conn modules[ name ] remote interpreter server side **namespace finally std restore
6089
def remote_interpreter(conn, namespace=None): if (namespace is None): namespace = {'conn': conn} std = RedirectedStd(conn) try: std.redirect() conn.modules[__name__]._remote_interpreter_server_side(**namespace) finally: std.restore()
starts an interactive interpreter on the server
starts an interactive interpreter on the server
Question: What does this function do? Code: def remote_interpreter(conn, namespace=None): if (namespace is None): namespace = {'conn': conn} std = RedirectedStd(conn) try: std.redirect() conn.modules[__name__]._remote_interpreter_server_side(**namespace) finally: std.restore()
null
null
null
What does this function do?
def check_space(in_files, force, _testhook_free_space=None): in_file = in_files[0] dir_path = os.path.dirname(os.path.realpath(in_file)) target = os.statvfs(dir_path) if (_testhook_free_space is None): free_space = (target.f_frsize * target.f_bavail) else: free_space = _testhook_free_space valid_files = [f for f in in_files if os.path.isfile(f)] file_sizes = [os.stat(f).st_size for f in valid_files] total_size = sum(file_sizes) size_diff = (total_size - free_space) if (size_diff > 0): print((u'ERROR: Not enough free space on disk for output files;\n Need at least %.1f GB more.' % (float(size_diff) / 1000000000.0)), file=sys.stderr) print((u' Estimated output size: %.1f GB' % ((float(total_size) / 1000000000.0),)), file=sys.stderr) print((u' Free space: %.1f GB' % ((float(free_space) / 1000000000.0),)), file=sys.stderr) if (not force): print(u'NOTE: This can be overridden using the --force argument', file=sys.stderr) sys.exit(1)
null
null
null
Check for available disk space. Estimate size of input files passed, then calculate disk space available and exit if disk space is insufficient.
pcsd
def check space in files force testhook free space=None in file = in files[0] dir path = os path dirname os path realpath in file target = os statvfs dir path if testhook free space is None free space = target f frsize * target f bavail else free space = testhook free space valid files = [f for f in in files if os path isfile f ] file sizes = [os stat f st size for f in valid files] total size = sum file sizes size diff = total size - free space if size diff > 0 print u'ERROR Not enough free space on disk for output files Need at least % 1f GB more ' % float size diff / 1000000000 0 file=sys stderr print u' Estimated output size % 1f GB' % float total size / 1000000000 0 file=sys stderr print u' Free space % 1f GB' % float free space / 1000000000 0 file=sys stderr if not force print u'NOTE This can be overridden using the --force argument' file=sys stderr sys exit 1
6094
def check_space(in_files, force, _testhook_free_space=None): in_file = in_files[0] dir_path = os.path.dirname(os.path.realpath(in_file)) target = os.statvfs(dir_path) if (_testhook_free_space is None): free_space = (target.f_frsize * target.f_bavail) else: free_space = _testhook_free_space valid_files = [f for f in in_files if os.path.isfile(f)] file_sizes = [os.stat(f).st_size for f in valid_files] total_size = sum(file_sizes) size_diff = (total_size - free_space) if (size_diff > 0): print((u'ERROR: Not enough free space on disk for output files;\n Need at least %.1f GB more.' % (float(size_diff) / 1000000000.0)), file=sys.stderr) print((u' Estimated output size: %.1f GB' % ((float(total_size) / 1000000000.0),)), file=sys.stderr) print((u' Free space: %.1f GB' % ((float(free_space) / 1000000000.0),)), file=sys.stderr) if (not force): print(u'NOTE: This can be overridden using the --force argument', file=sys.stderr) sys.exit(1)
Check for available disk space. Estimate size of input files passed, then calculate disk space available and exit if disk space is insufficient.
check for available disk space .
Question: What does this function do? Code: def check_space(in_files, force, _testhook_free_space=None): in_file = in_files[0] dir_path = os.path.dirname(os.path.realpath(in_file)) target = os.statvfs(dir_path) if (_testhook_free_space is None): free_space = (target.f_frsize * target.f_bavail) else: free_space = _testhook_free_space valid_files = [f for f in in_files if os.path.isfile(f)] file_sizes = [os.stat(f).st_size for f in valid_files] total_size = sum(file_sizes) size_diff = (total_size - free_space) if (size_diff > 0): print((u'ERROR: Not enough free space on disk for output files;\n Need at least %.1f GB more.' % (float(size_diff) / 1000000000.0)), file=sys.stderr) print((u' Estimated output size: %.1f GB' % ((float(total_size) / 1000000000.0),)), file=sys.stderr) print((u' Free space: %.1f GB' % ((float(free_space) / 1000000000.0),)), file=sys.stderr) if (not force): print(u'NOTE: This can be overridden using the --force argument', file=sys.stderr) sys.exit(1)
null
null
null
What does this function do?
def get_printout(out, opts=None, **kwargs): if (opts is None): opts = {} if (('output' in opts) and (opts['output'] != 'highstate')): out = opts['output'] if (out == 'text'): out = 'txt' elif ((out is None) or (out == '')): out = 'nested' if opts.get('progress', False): out = 'progress' opts.update(kwargs) if ('color' not in opts): def is_pipe(): '\n Check if sys.stdout is a pipe or not\n ' try: fileno = sys.stdout.fileno() except AttributeError: fileno = (-1) return (not os.isatty(fileno)) if opts.get('force_color', False): opts['color'] = True elif (opts.get('no_color', False) or is_pipe() or salt.utils.is_windows()): opts['color'] = False else: opts['color'] = True outputters = salt.loader.outputters(opts) if (out not in outputters): if (out != 'grains'): log.error('Invalid outputter {0} specified, fall back to nested'.format(out)) return outputters['nested'] return outputters[out]
null
null
null
Return a printer function
pcsd
def get printout out opts=None **kwargs if opts is None opts = {} if 'output' in opts and opts['output'] != 'highstate' out = opts['output'] if out == 'text' out = 'txt' elif out is None or out == '' out = 'nested' if opts get 'progress' False out = 'progress' opts update kwargs if 'color' not in opts def is pipe ' Check if sys stdout is a pipe or not ' try fileno = sys stdout fileno except Attribute Error fileno = -1 return not os isatty fileno if opts get 'force color' False opts['color'] = True elif opts get 'no color' False or is pipe or salt utils is windows opts['color'] = False else opts['color'] = True outputters = salt loader outputters opts if out not in outputters if out != 'grains' log error 'Invalid outputter {0} specified fall back to nested' format out return outputters['nested'] return outputters[out]
6104
def get_printout(out, opts=None, **kwargs): if (opts is None): opts = {} if (('output' in opts) and (opts['output'] != 'highstate')): out = opts['output'] if (out == 'text'): out = 'txt' elif ((out is None) or (out == '')): out = 'nested' if opts.get('progress', False): out = 'progress' opts.update(kwargs) if ('color' not in opts): def is_pipe(): '\n Check if sys.stdout is a pipe or not\n ' try: fileno = sys.stdout.fileno() except AttributeError: fileno = (-1) return (not os.isatty(fileno)) if opts.get('force_color', False): opts['color'] = True elif (opts.get('no_color', False) or is_pipe() or salt.utils.is_windows()): opts['color'] = False else: opts['color'] = True outputters = salt.loader.outputters(opts) if (out not in outputters): if (out != 'grains'): log.error('Invalid outputter {0} specified, fall back to nested'.format(out)) return outputters['nested'] return outputters[out]
Return a printer function
return a printer function
Question: What does this function do? Code: def get_printout(out, opts=None, **kwargs): if (opts is None): opts = {} if (('output' in opts) and (opts['output'] != 'highstate')): out = opts['output'] if (out == 'text'): out = 'txt' elif ((out is None) or (out == '')): out = 'nested' if opts.get('progress', False): out = 'progress' opts.update(kwargs) if ('color' not in opts): def is_pipe(): '\n Check if sys.stdout is a pipe or not\n ' try: fileno = sys.stdout.fileno() except AttributeError: fileno = (-1) return (not os.isatty(fileno)) if opts.get('force_color', False): opts['color'] = True elif (opts.get('no_color', False) or is_pipe() or salt.utils.is_windows()): opts['color'] = False else: opts['color'] = True outputters = salt.loader.outputters(opts) if (out not in outputters): if (out != 'grains'): log.error('Invalid outputter {0} specified, fall back to nested'.format(out)) return outputters['nested'] return outputters[out]
null
null
null
What does this function do?
def scan_used_functions(example_file, gallery_conf): example_code_obj = identify_names(open(example_file).read()) if example_code_obj: codeobj_fname = (example_file[:(-3)] + '_codeobj.pickle') with open(codeobj_fname, 'wb') as fid: pickle.dump(example_code_obj, fid, pickle.HIGHEST_PROTOCOL) backrefs = set(('{module_short}.{name}'.format(**entry) for entry in example_code_obj.values() if entry['module'].startswith(gallery_conf['doc_module']))) return backrefs
null
null
null
save variables so we can later add links to the documentation
pcsd
def scan used functions example file gallery conf example code obj = identify names open example file read if example code obj codeobj fname = example file[ -3 ] + ' codeobj pickle' with open codeobj fname 'wb' as fid pickle dump example code obj fid pickle HIGHEST PROTOCOL backrefs = set '{module short} {name}' format **entry for entry in example code obj values if entry['module'] startswith gallery conf['doc module'] return backrefs
6105
def scan_used_functions(example_file, gallery_conf): example_code_obj = identify_names(open(example_file).read()) if example_code_obj: codeobj_fname = (example_file[:(-3)] + '_codeobj.pickle') with open(codeobj_fname, 'wb') as fid: pickle.dump(example_code_obj, fid, pickle.HIGHEST_PROTOCOL) backrefs = set(('{module_short}.{name}'.format(**entry) for entry in example_code_obj.values() if entry['module'].startswith(gallery_conf['doc_module']))) return backrefs
save variables so we can later add links to the documentation
save variables so we can later add links to the documentation
Question: What does this function do? Code: def scan_used_functions(example_file, gallery_conf): example_code_obj = identify_names(open(example_file).read()) if example_code_obj: codeobj_fname = (example_file[:(-3)] + '_codeobj.pickle') with open(codeobj_fname, 'wb') as fid: pickle.dump(example_code_obj, fid, pickle.HIGHEST_PROTOCOL) backrefs = set(('{module_short}.{name}'.format(**entry) for entry in example_code_obj.values() if entry['module'].startswith(gallery_conf['doc_module']))) return backrefs
null
null
null
What does this function do?
def file_upload_echo_content(request): r = dict([(k, f.read()) for (k, f) in request.FILES.items()]) return HttpResponse(simplejson.dumps(r))
null
null
null
Simple view to echo back the content of uploaded files for tests.
pcsd
def file upload echo content request r = dict [ k f read for k f in request FILES items ] return Http Response simplejson dumps r
6106
def file_upload_echo_content(request): r = dict([(k, f.read()) for (k, f) in request.FILES.items()]) return HttpResponse(simplejson.dumps(r))
Simple view to echo back the content of uploaded files for tests.
simple view to echo back the content of uploaded files for tests .
Question: What does this function do? Code: def file_upload_echo_content(request): r = dict([(k, f.read()) for (k, f) in request.FILES.items()]) return HttpResponse(simplejson.dumps(r))
null
null
null
What does this function do?
def _playback_progress(idx, allsongs, repeat=False): cw = util.getxy().width out = ' %s%-XXs%s%s\n'.replace('XX', str((cw - 9))) out = (out % (c.ul, 'Title', 'Time', c.w)) show_key_help = (util.is_known_player(config.PLAYER.get) and config.SHOW_MPLAYER_KEYS.get) multi = (len(allsongs) > 1) for (n, song) in enumerate(allsongs): length_orig = util.fmt_time(song.length) length = ((' ' * (8 - len(length_orig))) + length_orig) i = (util.uea_pad((cw - 14), song.title), length, length_orig) fmt = (c.w, ' ', c.b, i[0], c.w, c.y, i[1], c.w) if (n == idx): fmt = (c.y, '> ', c.p, i[0], c.w, c.p, i[1], c.w) cur = i out += ('%s%s%s%s%s %s%s%s\n' % fmt) out += ('\n' * (3 - len(allsongs))) pos = ((8 * ' '), c.y, (idx + 1), c.w, c.y, len(allsongs), c.w) playing = ('{}{}{}{} of {}{}{}\n\n'.format(*pos) if multi else '\n\n') keys = _mplayer_help(short=((not multi) and (not repeat))) out = (out if multi else content.generate_songlist_display(song=allsongs[0])) if show_key_help: out += ('\n' + keys) else: playing = ('{}{}{}{} of {}{}{}\n'.format(*pos) if multi else '\n') out += (('\n' + (' ' * (cw - 19))) if multi else '') fmt = (playing, c.r, cur[0].strip()[:(cw - 19)], c.w, c.w, cur[2], c.w) out += ('%s %s%s%s %s[%s]%s' % fmt) out += (' REPEAT MODE' if repeat else '') return out
null
null
null
Generate string to show selected tracks, indicate current track.
pcsd
def playback progress idx allsongs repeat=False cw = util getxy width out = ' %s%-X Xs%s%s ' replace 'XX' str cw - 9 out = out % c ul 'Title' 'Time' c w show key help = util is known player config PLAYER get and config SHOW MPLAYER KEYS get multi = len allsongs > 1 for n song in enumerate allsongs length orig = util fmt time song length length = ' ' * 8 - len length orig + length orig i = util uea pad cw - 14 song title length length orig fmt = c w ' ' c b i[0] c w c y i[1] c w if n == idx fmt = c y '> ' c p i[0] c w c p i[1] c w cur = i out += '%s%s%s%s%s %s%s%s ' % fmt out += ' ' * 3 - len allsongs pos = 8 * ' ' c y idx + 1 c w c y len allsongs c w playing = '{}{}{}{} of {}{}{} ' format *pos if multi else ' ' keys = mplayer help short= not multi and not repeat out = out if multi else content generate songlist display song=allsongs[0] if show key help out += ' ' + keys else playing = '{}{}{}{} of {}{}{} ' format *pos if multi else ' ' out += ' ' + ' ' * cw - 19 if multi else '' fmt = playing c r cur[0] strip [ cw - 19 ] c w c w cur[2] c w out += '%s %s%s%s %s[%s]%s' % fmt out += ' REPEAT MODE' if repeat else '' return out
6109
def _playback_progress(idx, allsongs, repeat=False): cw = util.getxy().width out = ' %s%-XXs%s%s\n'.replace('XX', str((cw - 9))) out = (out % (c.ul, 'Title', 'Time', c.w)) show_key_help = (util.is_known_player(config.PLAYER.get) and config.SHOW_MPLAYER_KEYS.get) multi = (len(allsongs) > 1) for (n, song) in enumerate(allsongs): length_orig = util.fmt_time(song.length) length = ((' ' * (8 - len(length_orig))) + length_orig) i = (util.uea_pad((cw - 14), song.title), length, length_orig) fmt = (c.w, ' ', c.b, i[0], c.w, c.y, i[1], c.w) if (n == idx): fmt = (c.y, '> ', c.p, i[0], c.w, c.p, i[1], c.w) cur = i out += ('%s%s%s%s%s %s%s%s\n' % fmt) out += ('\n' * (3 - len(allsongs))) pos = ((8 * ' '), c.y, (idx + 1), c.w, c.y, len(allsongs), c.w) playing = ('{}{}{}{} of {}{}{}\n\n'.format(*pos) if multi else '\n\n') keys = _mplayer_help(short=((not multi) and (not repeat))) out = (out if multi else content.generate_songlist_display(song=allsongs[0])) if show_key_help: out += ('\n' + keys) else: playing = ('{}{}{}{} of {}{}{}\n'.format(*pos) if multi else '\n') out += (('\n' + (' ' * (cw - 19))) if multi else '') fmt = (playing, c.r, cur[0].strip()[:(cw - 19)], c.w, c.w, cur[2], c.w) out += ('%s %s%s%s %s[%s]%s' % fmt) out += (' REPEAT MODE' if repeat else '') return out
Generate string to show selected tracks, indicate current track.
generate string to show selected tracks , indicate current track .
Question: What does this function do? Code: def _playback_progress(idx, allsongs, repeat=False): cw = util.getxy().width out = ' %s%-XXs%s%s\n'.replace('XX', str((cw - 9))) out = (out % (c.ul, 'Title', 'Time', c.w)) show_key_help = (util.is_known_player(config.PLAYER.get) and config.SHOW_MPLAYER_KEYS.get) multi = (len(allsongs) > 1) for (n, song) in enumerate(allsongs): length_orig = util.fmt_time(song.length) length = ((' ' * (8 - len(length_orig))) + length_orig) i = (util.uea_pad((cw - 14), song.title), length, length_orig) fmt = (c.w, ' ', c.b, i[0], c.w, c.y, i[1], c.w) if (n == idx): fmt = (c.y, '> ', c.p, i[0], c.w, c.p, i[1], c.w) cur = i out += ('%s%s%s%s%s %s%s%s\n' % fmt) out += ('\n' * (3 - len(allsongs))) pos = ((8 * ' '), c.y, (idx + 1), c.w, c.y, len(allsongs), c.w) playing = ('{}{}{}{} of {}{}{}\n\n'.format(*pos) if multi else '\n\n') keys = _mplayer_help(short=((not multi) and (not repeat))) out = (out if multi else content.generate_songlist_display(song=allsongs[0])) if show_key_help: out += ('\n' + keys) else: playing = ('{}{}{}{} of {}{}{}\n'.format(*pos) if multi else '\n') out += (('\n' + (' ' * (cw - 19))) if multi else '') fmt = (playing, c.r, cur[0].strip()[:(cw - 19)], c.w, c.w, cur[2], c.w) out += ('%s %s%s%s %s[%s]%s' % fmt) out += (' REPEAT MODE' if repeat else '') return out
null
null
null
What does this function do?
def dumpNetConnections(net): nodes = ((net.controllers + net.switches) + net.hosts) dumpNodeConnections(nodes)
null
null
null
Dump connections in network
pcsd
def dump Net Connections net nodes = net controllers + net switches + net hosts dump Node Connections nodes
6110
def dumpNetConnections(net): nodes = ((net.controllers + net.switches) + net.hosts) dumpNodeConnections(nodes)
Dump connections in network
dump connections in network
Question: What does this function do? Code: def dumpNetConnections(net): nodes = ((net.controllers + net.switches) + net.hosts) dumpNodeConnections(nodes)
null
null
null
What does this function do?
def sample_distribution(distribution): r = random.uniform(0, 1) s = 0 for i in range(len(distribution)): s += distribution[i] if (s >= r): return i return (len(distribution) - 1)
null
null
null
Sample one element from a distribution assumed to be an array of normalized probabilities.
pcsd
def sample distribution distribution r = random uniform 0 1 s = 0 for i in range len distribution s += distribution[i] if s >= r return i return len distribution - 1
6118
def sample_distribution(distribution): r = random.uniform(0, 1) s = 0 for i in range(len(distribution)): s += distribution[i] if (s >= r): return i return (len(distribution) - 1)
Sample one element from a distribution assumed to be an array of normalized probabilities.
sample one element from a distribution assumed to be an array of normalized probabilities .
Question: What does this function do? Code: def sample_distribution(distribution): r = random.uniform(0, 1) s = 0 for i in range(len(distribution)): s += distribution[i] if (s >= r): return i return (len(distribution) - 1)
null
null
null
What does this function do?
def _make_unique(l): return sorted(set(l))
null
null
null
Check that all values in list are unique and return a pruned and sorted list.
pcsd
def make unique l return sorted set l
6121
def _make_unique(l): return sorted(set(l))
Check that all values in list are unique and return a pruned and sorted list.
check that all values in list are unique and return a pruned and sorted list .
Question: What does this function do? Code: def _make_unique(l): return sorted(set(l))
null
null
null
What does this function do?
def parse_positional_flags(source, info, flags_on, flags_off): version = ((info.flags & _ALL_VERSIONS) or DEFAULT_VERSION) if (version == VERSION0): if flags_off: raise error('bad inline flags: cannot turn flags off', source.string, source.pos) new_global_flags = (flags_on & (~ info.global_flags)) if new_global_flags: info.global_flags |= new_global_flags raise _UnscopedFlagSet(info.global_flags) else: info.flags = ((info.flags | flags_on) & (~ flags_off)) source.ignore_space = bool((info.flags & VERBOSE))
null
null
null
Parses positional flags.
pcsd
def parse positional flags source info flags on flags off version = info flags & ALL VERSIONS or DEFAULT VERSION if version == VERSION0 if flags off raise error 'bad inline flags cannot turn flags off' source string source pos new global flags = flags on & ~ info global flags if new global flags info global flags |= new global flags raise Unscoped Flag Set info global flags else info flags = info flags | flags on & ~ flags off source ignore space = bool info flags & VERBOSE
6128
def parse_positional_flags(source, info, flags_on, flags_off): version = ((info.flags & _ALL_VERSIONS) or DEFAULT_VERSION) if (version == VERSION0): if flags_off: raise error('bad inline flags: cannot turn flags off', source.string, source.pos) new_global_flags = (flags_on & (~ info.global_flags)) if new_global_flags: info.global_flags |= new_global_flags raise _UnscopedFlagSet(info.global_flags) else: info.flags = ((info.flags | flags_on) & (~ flags_off)) source.ignore_space = bool((info.flags & VERBOSE))
Parses positional flags.
parses positional flags .
Question: What does this function do? Code: def parse_positional_flags(source, info, flags_on, flags_off): version = ((info.flags & _ALL_VERSIONS) or DEFAULT_VERSION) if (version == VERSION0): if flags_off: raise error('bad inline flags: cannot turn flags off', source.string, source.pos) new_global_flags = (flags_on & (~ info.global_flags)) if new_global_flags: info.global_flags |= new_global_flags raise _UnscopedFlagSet(info.global_flags) else: info.flags = ((info.flags | flags_on) & (~ flags_off)) source.ignore_space = bool((info.flags & VERBOSE))
null
null
null
What does this function do?
def create_txn(asset, dt, price, amount): if (not isinstance(asset, Asset)): raise ValueError('pass an asset to create_txn') mock_order = Order(dt, asset, amount, id=None) return create_transaction(mock_order, dt, price, amount)
null
null
null
Create a fake transaction to be filled and processed prior to the execution of a given trade event.
pcsd
def create txn asset dt price amount if not isinstance asset Asset raise Value Error 'pass an asset to create txn' mock order = Order dt asset amount id=None return create transaction mock order dt price amount
6132
def create_txn(asset, dt, price, amount): if (not isinstance(asset, Asset)): raise ValueError('pass an asset to create_txn') mock_order = Order(dt, asset, amount, id=None) return create_transaction(mock_order, dt, price, amount)
Create a fake transaction to be filled and processed prior to the execution of a given trade event.
create a fake transaction to be filled and processed prior to the execution of a given trade event .
Question: What does this function do? Code: def create_txn(asset, dt, price, amount): if (not isinstance(asset, Asset)): raise ValueError('pass an asset to create_txn') mock_order = Order(dt, asset, amount, id=None) return create_transaction(mock_order, dt, price, amount)
null
null
null
What does this function do?
def detect_distro_type(): if os.path.exists('/etc/redhat-release'): return 'redhat' elif os.path.exists('/etc/debian_version'): return 'debian' elif os.path.exists('/etc/SuSE-release'): return 'suse' else: return None
null
null
null
Simple distro detection based on release/version files
pcsd
def detect distro type if os path exists '/etc/redhat-release' return 'redhat' elif os path exists '/etc/debian version' return 'debian' elif os path exists '/etc/Su SE-release' return 'suse' else return None
6140
def detect_distro_type(): if os.path.exists('/etc/redhat-release'): return 'redhat' elif os.path.exists('/etc/debian_version'): return 'debian' elif os.path.exists('/etc/SuSE-release'): return 'suse' else: return None
Simple distro detection based on release/version files
simple distro detection based on release / version files
Question: What does this function do? Code: def detect_distro_type(): if os.path.exists('/etc/redhat-release'): return 'redhat' elif os.path.exists('/etc/debian_version'): return 'debian' elif os.path.exists('/etc/SuSE-release'): return 'suse' else: return None
null
null
null
What does this function do?
@pytest.mark.parametrize('url, expected', (('http://192.168.0.1:5000/', True), ('http://192.168.0.1/', True), ('http://172.16.1.1/', True), ('http://172.16.1.1:5000/', True), ('http://localhost.localdomain:5000/v1.0/', True), ('http://172.16.1.12/', False), ('http://172.16.1.12:5000/', False), ('http://google.com:5000/v1.0/', False))) def test_should_bypass_proxies(url, expected, monkeypatch): monkeypatch.setenv('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1') monkeypatch.setenv('NO_PROXY', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1') assert (should_bypass_proxies(url) == expected)
null
null
null
Tests for function should_bypass_proxies to check if proxy can be bypassed or not
pcsd
@pytest mark parametrize 'url expected' 'http //192 168 0 1 5000/' True 'http //192 168 0 1/' True 'http //172 16 1 1/' True 'http //172 16 1 1 5000/' True 'http //localhost localdomain 5000/v1 0/' True 'http //172 16 1 12/' False 'http //172 16 1 12 5000/' False 'http //google com 5000/v1 0/' False def test should bypass proxies url expected monkeypatch monkeypatch setenv 'no proxy' '192 168 0 0/24 127 0 0 1 localhost localdomain 172 16 1 1' monkeypatch setenv 'NO PROXY' '192 168 0 0/24 127 0 0 1 localhost localdomain 172 16 1 1' assert should bypass proxies url == expected
6144
@pytest.mark.parametrize('url, expected', (('http://192.168.0.1:5000/', True), ('http://192.168.0.1/', True), ('http://172.16.1.1/', True), ('http://172.16.1.1:5000/', True), ('http://localhost.localdomain:5000/v1.0/', True), ('http://172.16.1.12/', False), ('http://172.16.1.12:5000/', False), ('http://google.com:5000/v1.0/', False))) def test_should_bypass_proxies(url, expected, monkeypatch): monkeypatch.setenv('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1') monkeypatch.setenv('NO_PROXY', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1') assert (should_bypass_proxies(url) == expected)
Tests for function should_bypass_proxies to check if proxy can be bypassed or not
tests for function should _ bypass _ proxies to check if proxy can be bypassed or not
Question: What does this function do? Code: @pytest.mark.parametrize('url, expected', (('http://192.168.0.1:5000/', True), ('http://192.168.0.1/', True), ('http://172.16.1.1/', True), ('http://172.16.1.1:5000/', True), ('http://localhost.localdomain:5000/v1.0/', True), ('http://172.16.1.12/', False), ('http://172.16.1.12:5000/', False), ('http://google.com:5000/v1.0/', False))) def test_should_bypass_proxies(url, expected, monkeypatch): monkeypatch.setenv('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1') monkeypatch.setenv('NO_PROXY', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1') assert (should_bypass_proxies(url) == expected)
null
null
null
What does this function do?
def numel(x, **kwargs): return chunk.sum(np.ones_like(x), **kwargs)
null
null
null
A reduction to count the number of elements
pcsd
def numel x **kwargs return chunk sum np ones like x **kwargs
6148
def numel(x, **kwargs): return chunk.sum(np.ones_like(x), **kwargs)
A reduction to count the number of elements
a reduction to count the number of elements
Question: What does this function do? Code: def numel(x, **kwargs): return chunk.sum(np.ones_like(x), **kwargs)
null
null
null
What does this function do?
def _resolve_name(name, package, level): level -= 1 try: if (package.count('.') < level): raise ValueError('attempted relative import beyond top-level package') except AttributeError: raise ValueError("'package' not set to a string") try: dot_rindex = package.rindex('.', level)[0] base = package[:dot_rindex] except ValueError: base = package if name: return ('%s.%s' % (base, name)) else: return base
null
null
null
Return the absolute name of the module to be imported.
pcsd
def resolve name name package level level -= 1 try if package count ' ' < level raise Value Error 'attempted relative import beyond top-level package' except Attribute Error raise Value Error "'package' not set to a string" try dot rindex = package rindex ' ' level [0] base = package[ dot rindex] except Value Error base = package if name return '%s %s' % base name else return base
6154
def _resolve_name(name, package, level): level -= 1 try: if (package.count('.') < level): raise ValueError('attempted relative import beyond top-level package') except AttributeError: raise ValueError("'package' not set to a string") try: dot_rindex = package.rindex('.', level)[0] base = package[:dot_rindex] except ValueError: base = package if name: return ('%s.%s' % (base, name)) else: return base
Return the absolute name of the module to be imported.
return the absolute name of the module to be imported .
Question: What does this function do? Code: def _resolve_name(name, package, level): level -= 1 try: if (package.count('.') < level): raise ValueError('attempted relative import beyond top-level package') except AttributeError: raise ValueError("'package' not set to a string") try: dot_rindex = package.rindex('.', level)[0] base = package[:dot_rindex] except ValueError: base = package if name: return ('%s.%s' % (base, name)) else: return base
null
null
null
What does this function do?
def todolist(): app = (request.vars.app or '') app_path = apath(('%(app)s' % {'app': app}), r=request) dirs = ['models', 'controllers', 'modules', 'private'] def listfiles(app, dir, regexp='.*\\.py$'): files = sorted(listdir(apath(('%(app)s/%(dir)s/' % {'app': app, 'dir': dir}), r=request), regexp)) files = [x.replace(os.path.sep, '/') for x in files if (not x.endswith('.bak'))] return files pattern = '#\\s*(todo)+\\s+(.*)' regex = re.compile(pattern, re.IGNORECASE) output = [] for d in dirs: for f in listfiles(app, d): matches = [] filename = apath(os.path.join(app, d, f), r=request) with safe_open(filename, 'r') as f_s: src = f_s.read() for m in regex.finditer(src): start = m.start() lineno = (src.count('\n', 0, start) + 1) matches.append({'text': m.group(0), 'lineno': lineno}) if (len(matches) != 0): output.append({'filename': f, 'matches': matches, 'dir': d}) return {'todo': output, 'app': app}
null
null
null
Returns all TODO of the requested app
pcsd
def todolist app = request vars app or '' app path = apath '% app s' % {'app' app} r=request dirs = ['models' 'controllers' 'modules' 'private'] def listfiles app dir regexp=' *\\ py$' files = sorted listdir apath '% app s/% dir s/' % {'app' app 'dir' dir} r=request regexp files = [x replace os path sep '/' for x in files if not x endswith ' bak' ] return files pattern = '#\\s* todo +\\s+ * ' regex = re compile pattern re IGNORECASE output = [] for d in dirs for f in listfiles app d matches = [] filename = apath os path join app d f r=request with safe open filename 'r' as f s src = f s read for m in regex finditer src start = m start lineno = src count ' ' 0 start + 1 matches append {'text' m group 0 'lineno' lineno} if len matches != 0 output append {'filename' f 'matches' matches 'dir' d} return {'todo' output 'app' app}
6159
def todolist(): app = (request.vars.app or '') app_path = apath(('%(app)s' % {'app': app}), r=request) dirs = ['models', 'controllers', 'modules', 'private'] def listfiles(app, dir, regexp='.*\\.py$'): files = sorted(listdir(apath(('%(app)s/%(dir)s/' % {'app': app, 'dir': dir}), r=request), regexp)) files = [x.replace(os.path.sep, '/') for x in files if (not x.endswith('.bak'))] return files pattern = '#\\s*(todo)+\\s+(.*)' regex = re.compile(pattern, re.IGNORECASE) output = [] for d in dirs: for f in listfiles(app, d): matches = [] filename = apath(os.path.join(app, d, f), r=request) with safe_open(filename, 'r') as f_s: src = f_s.read() for m in regex.finditer(src): start = m.start() lineno = (src.count('\n', 0, start) + 1) matches.append({'text': m.group(0), 'lineno': lineno}) if (len(matches) != 0): output.append({'filename': f, 'matches': matches, 'dir': d}) return {'todo': output, 'app': app}
Returns all TODO of the requested app
returns all todo of the requested app
Question: What does this function do? Code: def todolist(): app = (request.vars.app or '') app_path = apath(('%(app)s' % {'app': app}), r=request) dirs = ['models', 'controllers', 'modules', 'private'] def listfiles(app, dir, regexp='.*\\.py$'): files = sorted(listdir(apath(('%(app)s/%(dir)s/' % {'app': app, 'dir': dir}), r=request), regexp)) files = [x.replace(os.path.sep, '/') for x in files if (not x.endswith('.bak'))] return files pattern = '#\\s*(todo)+\\s+(.*)' regex = re.compile(pattern, re.IGNORECASE) output = [] for d in dirs: for f in listfiles(app, d): matches = [] filename = apath(os.path.join(app, d, f), r=request) with safe_open(filename, 'r') as f_s: src = f_s.read() for m in regex.finditer(src): start = m.start() lineno = (src.count('\n', 0, start) + 1) matches.append({'text': m.group(0), 'lineno': lineno}) if (len(matches) != 0): output.append({'filename': f, 'matches': matches, 'dir': d}) return {'todo': output, 'app': app}
null
null
null
What does this function do?
def base_repr(number, base=2, padding=0): chars = u'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' if (number < base): return (((padding - 1) * chars[0]) + chars[int(number)]) max_exponent = int((math.log(number) / math.log(base))) max_power = (long(base) ** max_exponent) lead_digit = int((number / max_power)) return (chars[lead_digit] + base_repr((number - (max_power * lead_digit)), base, max((padding - 1), max_exponent)))
null
null
null
Return the representation of a *number* in any given *base*.
pcsd
def base repr number base=2 padding=0 chars = u'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' if number < base return padding - 1 * chars[0] + chars[int number ] max exponent = int math log number / math log base max power = long base ** max exponent lead digit = int number / max power return chars[lead digit] + base repr number - max power * lead digit base max padding - 1 max exponent
6161
def base_repr(number, base=2, padding=0): chars = u'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' if (number < base): return (((padding - 1) * chars[0]) + chars[int(number)]) max_exponent = int((math.log(number) / math.log(base))) max_power = (long(base) ** max_exponent) lead_digit = int((number / max_power)) return (chars[lead_digit] + base_repr((number - (max_power * lead_digit)), base, max((padding - 1), max_exponent)))
Return the representation of a *number* in any given *base*.
return the representation of a * number * in any given * base * .
Question: What does this function do? Code: def base_repr(number, base=2, padding=0): chars = u'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' if (number < base): return (((padding - 1) * chars[0]) + chars[int(number)]) max_exponent = int((math.log(number) / math.log(base))) max_power = (long(base) ** max_exponent) lead_digit = int((number / max_power)) return (chars[lead_digit] + base_repr((number - (max_power * lead_digit)), base, max((padding - 1), max_exponent)))
null
null
null
What does this function do?
def floor(mat, target=None): if (not target): target = mat err_code = _eigenmat.apply_floor(mat.p_mat, target.p_mat) if err_code: raise generate_exception(err_code) return target
null
null
null
Apply the floor function to each element of the matrix mat.
pcsd
def floor mat target=None if not target target = mat err code = eigenmat apply floor mat p mat target p mat if err code raise generate exception err code return target
6162
def floor(mat, target=None): if (not target): target = mat err_code = _eigenmat.apply_floor(mat.p_mat, target.p_mat) if err_code: raise generate_exception(err_code) return target
Apply the floor function to each element of the matrix mat.
apply the floor function to each element of the matrix mat .
Question: What does this function do? Code: def floor(mat, target=None): if (not target): target = mat err_code = _eigenmat.apply_floor(mat.p_mat, target.p_mat) if err_code: raise generate_exception(err_code) return target
null
null
null
What does this function do?
def get_rdm_disk(hardware_devices, uuid): if (hardware_devices.__class__.__name__ == 'ArrayOfVirtualDevice'): hardware_devices = hardware_devices.VirtualDevice for device in hardware_devices: if ((device.__class__.__name__ == 'VirtualDisk') and (device.backing.__class__.__name__ == 'VirtualDiskRawDiskMappingVer1BackingInfo') and (device.backing.lunUuid == uuid)): return device
null
null
null
Gets the RDM disk key.
pcsd
def get rdm disk hardware devices uuid if hardware devices class name == 'Array Of Virtual Device' hardware devices = hardware devices Virtual Device for device in hardware devices if device class name == 'Virtual Disk' and device backing class name == 'Virtual Disk Raw Disk Mapping Ver1Backing Info' and device backing lun Uuid == uuid return device
6172
def get_rdm_disk(hardware_devices, uuid): if (hardware_devices.__class__.__name__ == 'ArrayOfVirtualDevice'): hardware_devices = hardware_devices.VirtualDevice for device in hardware_devices: if ((device.__class__.__name__ == 'VirtualDisk') and (device.backing.__class__.__name__ == 'VirtualDiskRawDiskMappingVer1BackingInfo') and (device.backing.lunUuid == uuid)): return device
Gets the RDM disk key.
gets the rdm disk key .
Question: What does this function do? Code: def get_rdm_disk(hardware_devices, uuid): if (hardware_devices.__class__.__name__ == 'ArrayOfVirtualDevice'): hardware_devices = hardware_devices.VirtualDevice for device in hardware_devices: if ((device.__class__.__name__ == 'VirtualDisk') and (device.backing.__class__.__name__ == 'VirtualDiskRawDiskMappingVer1BackingInfo') and (device.backing.lunUuid == uuid)): return device
null
null
null
What does this function do?
def get_session_config(): return copy.deepcopy(_session['config'])
null
null
null
Returns either module config or file config.
pcsd
def get session config return copy deepcopy session['config']
6175
def get_session_config(): return copy.deepcopy(_session['config'])
Returns either module config or file config.
returns either module config or file config .
Question: What does this function do? Code: def get_session_config(): return copy.deepcopy(_session['config'])
null
null
null
What does this function do?
@utils.arg('host', metavar='<hostname>', help=_('Name of host.')) @utils.arg('--action', metavar='<action>', dest='action', choices=['startup', 'shutdown', 'reboot'], help=_('A power action: startup, reboot, or shutdown.')) def do_host_action(cs, args): result = cs.hosts.host_action(args.host, args.action) utils.print_list([result], ['HOST', 'power_action'])
null
null
null
Perform a power action on a host.
pcsd
@utils arg 'host' metavar='<hostname>' help= 'Name of host ' @utils arg '--action' metavar='<action>' dest='action' choices=['startup' 'shutdown' 'reboot'] help= 'A power action startup reboot or shutdown ' def do host action cs args result = cs hosts host action args host args action utils print list [result] ['HOST' 'power action']
6181
@utils.arg('host', metavar='<hostname>', help=_('Name of host.')) @utils.arg('--action', metavar='<action>', dest='action', choices=['startup', 'shutdown', 'reboot'], help=_('A power action: startup, reboot, or shutdown.')) def do_host_action(cs, args): result = cs.hosts.host_action(args.host, args.action) utils.print_list([result], ['HOST', 'power_action'])
Perform a power action on a host.
perform a power action on a host .
Question: What does this function do? Code: @utils.arg('host', metavar='<hostname>', help=_('Name of host.')) @utils.arg('--action', metavar='<action>', dest='action', choices=['startup', 'shutdown', 'reboot'], help=_('A power action: startup, reboot, or shutdown.')) def do_host_action(cs, args): result = cs.hosts.host_action(args.host, args.action) utils.print_list([result], ['HOST', 'power_action'])
null
null
null
What does this function do?
def urlnormalize(href): try: parts = urlparse(href) except ValueError as e: raise ValueError(('Failed to parse the URL: %r with underlying error: %s' % (href, as_unicode(e)))) if ((not parts.scheme) or (parts.scheme == 'file')): (path, frag) = urldefrag(href) parts = ('', '', path, '', '', frag) parts = (part.replace('\\', '/') for part in parts) parts = (urlunquote(part) for part in parts) parts = (urlquote(part) for part in parts) return urlunparse(parts)
null
null
null
Convert a URL into normalized form, with all and only URL-unsafe characters URL quoted.
pcsd
def urlnormalize href try parts = urlparse href except Value Error as e raise Value Error 'Failed to parse the URL %r with underlying error %s' % href as unicode e if not parts scheme or parts scheme == 'file' path frag = urldefrag href parts = '' '' path '' '' frag parts = part replace '\\' '/' for part in parts parts = urlunquote part for part in parts parts = urlquote part for part in parts return urlunparse parts
6187
def urlnormalize(href): try: parts = urlparse(href) except ValueError as e: raise ValueError(('Failed to parse the URL: %r with underlying error: %s' % (href, as_unicode(e)))) if ((not parts.scheme) or (parts.scheme == 'file')): (path, frag) = urldefrag(href) parts = ('', '', path, '', '', frag) parts = (part.replace('\\', '/') for part in parts) parts = (urlunquote(part) for part in parts) parts = (urlquote(part) for part in parts) return urlunparse(parts)
Convert a URL into normalized form, with all and only URL-unsafe characters URL quoted.
convert a url into normalized form , with all and only url - unsafe characters url quoted .
Question: What does this function do? Code: def urlnormalize(href): try: parts = urlparse(href) except ValueError as e: raise ValueError(('Failed to parse the URL: %r with underlying error: %s' % (href, as_unicode(e)))) if ((not parts.scheme) or (parts.scheme == 'file')): (path, frag) = urldefrag(href) parts = ('', '', path, '', '', frag) parts = (part.replace('\\', '/') for part in parts) parts = (urlunquote(part) for part in parts) parts = (urlquote(part) for part in parts) return urlunparse(parts)
null
null
null
What does this function do?
def roster(opts, runner, whitelist=None): return LazyLoader(_module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={'__runner__': runner})
null
null
null
Returns the roster modules
pcsd
def roster opts runner whitelist=None return Lazy Loader module dirs opts 'roster' opts tag='roster' whitelist=whitelist pack={' runner ' runner}
6189
def roster(opts, runner, whitelist=None): return LazyLoader(_module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={'__runner__': runner})
Returns the roster modules
returns the roster modules
Question: What does this function do? Code: def roster(opts, runner, whitelist=None): return LazyLoader(_module_dirs(opts, 'roster'), opts, tag='roster', whitelist=whitelist, pack={'__runner__': runner})
null
null
null
What does this function do?
def create_or_update_tool_dependency(app, tool_shed_repository, name, version, type, status, set_status=True): context = app.install_model.context if version: tool_dependency = get_tool_dependency_by_name_version_type_repository(app, tool_shed_repository, name, version, type) else: tool_dependency = get_tool_dependency_by_name_type_repository(app, tool_shed_repository, name, type) if tool_dependency: if set_status: set_tool_dependency_attributes(app, tool_dependency=tool_dependency, status=status) else: debug_msg = ('Creating a new record for version %s of tool dependency %s for revision %s of repository %s. ' % (str(version), str(name), str(tool_shed_repository.changeset_revision), str(tool_shed_repository.name))) debug_msg += ('The status is being set to %s.' % str(status)) log.debug(debug_msg) tool_dependency = app.install_model.ToolDependency(tool_shed_repository.id, name, version, type, status) context.add(tool_dependency) context.flush() return tool_dependency
null
null
null
Create or update a tool_dependency record in the Galaxy database.
pcsd
def create or update tool dependency app tool shed repository name version type status set status=True context = app install model context if version tool dependency = get tool dependency by name version type repository app tool shed repository name version type else tool dependency = get tool dependency by name type repository app tool shed repository name type if tool dependency if set status set tool dependency attributes app tool dependency=tool dependency status=status else debug msg = 'Creating a new record for version %s of tool dependency %s for revision %s of repository %s ' % str version str name str tool shed repository changeset revision str tool shed repository name debug msg += 'The status is being set to %s ' % str status log debug debug msg tool dependency = app install model Tool Dependency tool shed repository id name version type status context add tool dependency context flush return tool dependency
6192
def create_or_update_tool_dependency(app, tool_shed_repository, name, version, type, status, set_status=True): context = app.install_model.context if version: tool_dependency = get_tool_dependency_by_name_version_type_repository(app, tool_shed_repository, name, version, type) else: tool_dependency = get_tool_dependency_by_name_type_repository(app, tool_shed_repository, name, type) if tool_dependency: if set_status: set_tool_dependency_attributes(app, tool_dependency=tool_dependency, status=status) else: debug_msg = ('Creating a new record for version %s of tool dependency %s for revision %s of repository %s. ' % (str(version), str(name), str(tool_shed_repository.changeset_revision), str(tool_shed_repository.name))) debug_msg += ('The status is being set to %s.' % str(status)) log.debug(debug_msg) tool_dependency = app.install_model.ToolDependency(tool_shed_repository.id, name, version, type, status) context.add(tool_dependency) context.flush() return tool_dependency
Create or update a tool_dependency record in the Galaxy database.
create or update a tool _ dependency record in the galaxy database .
Question: What does this function do? Code: def create_or_update_tool_dependency(app, tool_shed_repository, name, version, type, status, set_status=True): context = app.install_model.context if version: tool_dependency = get_tool_dependency_by_name_version_type_repository(app, tool_shed_repository, name, version, type) else: tool_dependency = get_tool_dependency_by_name_type_repository(app, tool_shed_repository, name, type) if tool_dependency: if set_status: set_tool_dependency_attributes(app, tool_dependency=tool_dependency, status=status) else: debug_msg = ('Creating a new record for version %s of tool dependency %s for revision %s of repository %s. ' % (str(version), str(name), str(tool_shed_repository.changeset_revision), str(tool_shed_repository.name))) debug_msg += ('The status is being set to %s.' % str(status)) log.debug(debug_msg) tool_dependency = app.install_model.ToolDependency(tool_shed_repository.id, name, version, type, status) context.add(tool_dependency) context.flush() return tool_dependency
null
null
null
What does this function do?
def evalRnnOnSeqDataset(net, DS, verbose=False, silent=False): r = 0.0 samples = 0.0 for seq in DS: net.reset() for (i, t) in seq: res = net.activate(i) if verbose: print(t, res) r += sum(((t - res) ** 2)) samples += 1 if verbose: print(('-' * 20)) r /= samples if (not silent): print('MSE:', r) return r
null
null
null
evaluate the network on all the sequences of a dataset.
pcsd
def eval Rnn On Seq Dataset net DS verbose=False silent=False r = 0 0 samples = 0 0 for seq in DS net reset for i t in seq res = net activate i if verbose print t res r += sum t - res ** 2 samples += 1 if verbose print '-' * 20 r /= samples if not silent print 'MSE ' r return r
6193
def evalRnnOnSeqDataset(net, DS, verbose=False, silent=False): r = 0.0 samples = 0.0 for seq in DS: net.reset() for (i, t) in seq: res = net.activate(i) if verbose: print(t, res) r += sum(((t - res) ** 2)) samples += 1 if verbose: print(('-' * 20)) r /= samples if (not silent): print('MSE:', r) return r
evaluate the network on all the sequences of a dataset.
evaluate the network on all the sequences of a dataset .
Question: What does this function do? Code: def evalRnnOnSeqDataset(net, DS, verbose=False, silent=False): r = 0.0 samples = 0.0 for seq in DS: net.reset() for (i, t) in seq: res = net.activate(i) if verbose: print(t, res) r += sum(((t - res) ** 2)) samples += 1 if verbose: print(('-' * 20)) r /= samples if (not silent): print('MSE:', r) return r
null
null
null
What does this function do?
def remove_old_versions(db): start = ('%s.%s.0' % (major, minor)) migrate_features = 1 if snapshot: add_data(db, 'Upgrade', [(upgrade_code_snapshot, start, current_version, None, migrate_features, None, 'REMOVEOLDSNAPSHOT')]) props = 'REMOVEOLDSNAPSHOT' else: add_data(db, 'Upgrade', [(upgrade_code, start, current_version, None, migrate_features, None, 'REMOVEOLDVERSION'), (upgrade_code_snapshot, start, ('%s.%d.0' % (major, (int(minor) + 1))), None, migrate_features, None, 'REMOVEOLDSNAPSHOT')]) props = 'REMOVEOLDSNAPSHOT;REMOVEOLDVERSION' props += ';TARGETDIR;DLLDIR' add_data(db, 'Property', [('SecureCustomProperties', props)])
null
null
null
Fill the upgrade table.
pcsd
def remove old versions db start = '%s %s 0' % major minor migrate features = 1 if snapshot add data db 'Upgrade' [ upgrade code snapshot start current version None migrate features None 'REMOVEOLDSNAPSHOT' ] props = 'REMOVEOLDSNAPSHOT' else add data db 'Upgrade' [ upgrade code start current version None migrate features None 'REMOVEOLDVERSION' upgrade code snapshot start '%s %d 0' % major int minor + 1 None migrate features None 'REMOVEOLDSNAPSHOT' ] props = 'REMOVEOLDSNAPSHOT REMOVEOLDVERSION' props += ' TARGETDIR DLLDIR' add data db 'Property' [ 'Secure Custom Properties' props ]
6195
def remove_old_versions(db): start = ('%s.%s.0' % (major, minor)) migrate_features = 1 if snapshot: add_data(db, 'Upgrade', [(upgrade_code_snapshot, start, current_version, None, migrate_features, None, 'REMOVEOLDSNAPSHOT')]) props = 'REMOVEOLDSNAPSHOT' else: add_data(db, 'Upgrade', [(upgrade_code, start, current_version, None, migrate_features, None, 'REMOVEOLDVERSION'), (upgrade_code_snapshot, start, ('%s.%d.0' % (major, (int(minor) + 1))), None, migrate_features, None, 'REMOVEOLDSNAPSHOT')]) props = 'REMOVEOLDSNAPSHOT;REMOVEOLDVERSION' props += ';TARGETDIR;DLLDIR' add_data(db, 'Property', [('SecureCustomProperties', props)])
Fill the upgrade table.
fill the upgrade table .
Question: What does this function do? Code: def remove_old_versions(db): start = ('%s.%s.0' % (major, minor)) migrate_features = 1 if snapshot: add_data(db, 'Upgrade', [(upgrade_code_snapshot, start, current_version, None, migrate_features, None, 'REMOVEOLDSNAPSHOT')]) props = 'REMOVEOLDSNAPSHOT' else: add_data(db, 'Upgrade', [(upgrade_code, start, current_version, None, migrate_features, None, 'REMOVEOLDVERSION'), (upgrade_code_snapshot, start, ('%s.%d.0' % (major, (int(minor) + 1))), None, migrate_features, None, 'REMOVEOLDSNAPSHOT')]) props = 'REMOVEOLDSNAPSHOT;REMOVEOLDVERSION' props += ';TARGETDIR;DLLDIR' add_data(db, 'Property', [('SecureCustomProperties', props)])
null
null
null
What does this function do?
@bdd.then(bdd.parsers.parse('The unordered requests should be:\n{pages}')) def list_of_requests_unordered(httpbin, pages): expected_requests = [httpbin.ExpectedRequest('GET', ('/' + path.strip())) for path in pages.split('\n')] actual_requests = httpbin.get_requests() actual_requests = [httpbin.ExpectedRequest.from_request(req) for req in actual_requests] assert (collections.Counter(actual_requests) == collections.Counter(expected_requests))
null
null
null
Make sure the given requests were done (in no particular order).
pcsd
@bdd then bdd parsers parse 'The unordered requests should be {pages}' def list of requests unordered httpbin pages expected requests = [httpbin Expected Request 'GET' '/' + path strip for path in pages split ' ' ] actual requests = httpbin get requests actual requests = [httpbin Expected Request from request req for req in actual requests] assert collections Counter actual requests == collections Counter expected requests
6197
@bdd.then(bdd.parsers.parse('The unordered requests should be:\n{pages}')) def list_of_requests_unordered(httpbin, pages): expected_requests = [httpbin.ExpectedRequest('GET', ('/' + path.strip())) for path in pages.split('\n')] actual_requests = httpbin.get_requests() actual_requests = [httpbin.ExpectedRequest.from_request(req) for req in actual_requests] assert (collections.Counter(actual_requests) == collections.Counter(expected_requests))
Make sure the given requests were done (in no particular order).
make sure the given requests were done .
Question: What does this function do? Code: @bdd.then(bdd.parsers.parse('The unordered requests should be:\n{pages}')) def list_of_requests_unordered(httpbin, pages): expected_requests = [httpbin.ExpectedRequest('GET', ('/' + path.strip())) for path in pages.split('\n')] actual_requests = httpbin.get_requests() actual_requests = [httpbin.ExpectedRequest.from_request(req) for req in actual_requests] assert (collections.Counter(actual_requests) == collections.Counter(expected_requests))
null
null
null
What does this function do?
def add_to_deleted_document(doc): if ((doc.doctype != u'Deleted Document') and (frappe.flags.in_install != u'frappe')): frappe.get_doc(dict(doctype=u'Deleted Document', deleted_doctype=doc.doctype, deleted_name=doc.name, data=doc.as_json())).db_insert()
null
null
null
Add this document to Deleted Document table. Called after delete
pcsd
def add to deleted document doc if doc doctype != u'Deleted Document' and frappe flags in install != u'frappe' frappe get doc dict doctype=u'Deleted Document' deleted doctype=doc doctype deleted name=doc name data=doc as json db insert
6208
def add_to_deleted_document(doc): if ((doc.doctype != u'Deleted Document') and (frappe.flags.in_install != u'frappe')): frappe.get_doc(dict(doctype=u'Deleted Document', deleted_doctype=doc.doctype, deleted_name=doc.name, data=doc.as_json())).db_insert()
Add this document to Deleted Document table. Called after delete
add this document to deleted document table .
Question: What does this function do? Code: def add_to_deleted_document(doc): if ((doc.doctype != u'Deleted Document') and (frappe.flags.in_install != u'frappe')): frappe.get_doc(dict(doctype=u'Deleted Document', deleted_doctype=doc.doctype, deleted_name=doc.name, data=doc.as_json())).db_insert()
null
null
null
What does this function do?
def _format_info(data): return {'name': data.gr_name, 'gid': data.gr_gid, 'passwd': data.gr_passwd, 'members': data.gr_mem}
null
null
null
Return formatted information in a pretty way.
pcsd
def format info data return {'name' data gr name 'gid' data gr gid 'passwd' data gr passwd 'members' data gr mem}
6225
def _format_info(data): return {'name': data.gr_name, 'gid': data.gr_gid, 'passwd': data.gr_passwd, 'members': data.gr_mem}
Return formatted information in a pretty way.
return formatted information in a pretty way .
Question: What does this function do? Code: def _format_info(data): return {'name': data.gr_name, 'gid': data.gr_gid, 'passwd': data.gr_passwd, 'members': data.gr_mem}
null
null
null
What does this function do?
def GetImages(region, owner_ids=None): ec2 = _Connect(region) if (not owner_ids): return None return ec2.get_all_images(owners=owner_ids)
null
null
null
Return the list of images owned IDs from \'owner_ids\'. If None or empty, we return nothing.
pcsd
def Get Images region owner ids=None ec2 = Connect region if not owner ids return None return ec2 get all images owners=owner ids
6233
def GetImages(region, owner_ids=None): ec2 = _Connect(region) if (not owner_ids): return None return ec2.get_all_images(owners=owner_ids)
Return the list of images owned IDs from \'owner_ids\'. If None or empty, we return nothing.
return the list of images owned ids from owner _ ids .
Question: What does this function do? Code: def GetImages(region, owner_ids=None): ec2 = _Connect(region) if (not owner_ids): return None return ec2.get_all_images(owners=owner_ids)
null
null
null
What does this function do?
def try_import(import_str, default=None): try: return import_module(import_str) except ImportError: return default
null
null
null
Try to import a module and if it fails return default.
pcsd
def try import import str default=None try return import module import str except Import Error return default
6237
def try_import(import_str, default=None): try: return import_module(import_str) except ImportError: return default
Try to import a module and if it fails return default.
try to import a module and if it fails return default .
Question: What does this function do? Code: def try_import(import_str, default=None): try: return import_module(import_str) except ImportError: return default
null
null
null
What does this function do?
@lru_cache() def time_to_days(value): if (value.tzinfo is not None): value = value.astimezone(UTC) return (((((value.hour * 3600) + (value.minute * 60)) + value.second) + (value.microsecond / (10 ** 6))) / SECS_PER_DAY)
null
null
null
Convert a time value to fractions of day
pcsd
@lru cache def time to days value if value tzinfo is not None value = value astimezone UTC return value hour * 3600 + value minute * 60 + value second + value microsecond / 10 ** 6 / SECS PER DAY
6242
@lru_cache() def time_to_days(value): if (value.tzinfo is not None): value = value.astimezone(UTC) return (((((value.hour * 3600) + (value.minute * 60)) + value.second) + (value.microsecond / (10 ** 6))) / SECS_PER_DAY)
Convert a time value to fractions of day
convert a time value to fractions of day
Question: What does this function do? Code: @lru_cache() def time_to_days(value): if (value.tzinfo is not None): value = value.astimezone(UTC) return (((((value.hour * 3600) + (value.minute * 60)) + value.second) + (value.microsecond / (10 ** 6))) / SECS_PER_DAY)
null
null
null
What does this function do?
def S_IMODE(mode): return (mode & 4095)
null
null
null
Return the portion of the file\'s mode that can be set by os.chmod().
pcsd
def S IMODE mode return mode & 4095
6245
def S_IMODE(mode): return (mode & 4095)
Return the portion of the file\'s mode that can be set by os.chmod().
return the portion of the files mode that can be set by os . chmod ( ) .
Question: What does this function do? Code: def S_IMODE(mode): return (mode & 4095)
null
null
null
What does this function do?
def get_template(template_name, globals=None): try: return get_env().get_template(template_name, globals=globals) except TemplateNotFound as e: raise TemplateDoesNotExist(str(e))
null
null
null
Load a template.
pcsd
def get template template name globals=None try return get env get template template name globals=globals except Template Not Found as e raise Template Does Not Exist str e
6246
def get_template(template_name, globals=None): try: return get_env().get_template(template_name, globals=globals) except TemplateNotFound as e: raise TemplateDoesNotExist(str(e))
Load a template.
load a template .
Question: What does this function do? Code: def get_template(template_name, globals=None): try: return get_env().get_template(template_name, globals=globals) except TemplateNotFound as e: raise TemplateDoesNotExist(str(e))
null
null
null
What does this function do?
def get_effective_router(appname): if ((not routers) or (appname not in routers)): return None return Storage(routers[appname])
null
null
null
Returns a private copy of the effective router for the specified application
pcsd
def get effective router appname if not routers or appname not in routers return None return Storage routers[appname]
6252
def get_effective_router(appname): if ((not routers) or (appname not in routers)): return None return Storage(routers[appname])
Returns a private copy of the effective router for the specified application
returns a private copy of the effective router for the specified application
Question: What does this function do? Code: def get_effective_router(appname): if ((not routers) or (appname not in routers)): return None return Storage(routers[appname])
null
null
null
What does this function do?
@pytest.mark.network def test_download_setuptools(script): result = script.pip('download', 'setuptools') setuptools_prefix = str((Path('scratch') / 'setuptools')) assert any((path.startswith(setuptools_prefix) for path in result.files_created))
null
null
null
It should download (in the scratch path) and not install if requested.
pcsd
@pytest mark network def test download setuptools script result = script pip 'download' 'setuptools' setuptools prefix = str Path 'scratch' / 'setuptools' assert any path startswith setuptools prefix for path in result files created
6256
@pytest.mark.network def test_download_setuptools(script): result = script.pip('download', 'setuptools') setuptools_prefix = str((Path('scratch') / 'setuptools')) assert any((path.startswith(setuptools_prefix) for path in result.files_created))
It should download (in the scratch path) and not install if requested.
it should download and not install if requested .
Question: What does this function do? Code: @pytest.mark.network def test_download_setuptools(script): result = script.pip('download', 'setuptools') setuptools_prefix = str((Path('scratch') / 'setuptools')) assert any((path.startswith(setuptools_prefix) for path in result.files_created))
null
null
null
What does this function do?
def create_groups(update): (guest_group, created) = Group.objects.get_or_create(name=u'Guests') if (created or update or (guest_group.permissions.count() == 0)): guest_group.permissions.add(Permission.objects.get(codename=u'can_see_git_repository'), Permission.objects.get(codename=u'add_suggestion')) (group, created) = Group.objects.get_or_create(name=u'Users') if (created or update or (group.permissions.count() == 0)): group.permissions.add(Permission.objects.get(codename=u'upload_translation'), Permission.objects.get(codename=u'overwrite_translation'), Permission.objects.get(codename=u'save_translation'), Permission.objects.get(codename=u'save_template'), Permission.objects.get(codename=u'accept_suggestion'), Permission.objects.get(codename=u'delete_suggestion'), Permission.objects.get(codename=u'vote_suggestion'), Permission.objects.get(codename=u'ignore_check'), Permission.objects.get(codename=u'upload_dictionary'), Permission.objects.get(codename=u'add_dictionary'), Permission.objects.get(codename=u'change_dictionary'), Permission.objects.get(codename=u'delete_dictionary'), Permission.objects.get(codename=u'lock_translation'), Permission.objects.get(codename=u'can_see_git_repository'), Permission.objects.get(codename=u'add_comment'), Permission.objects.get(codename=u'add_suggestion'), Permission.objects.get(codename=u'use_mt'), Permission.objects.get(codename=u'add_translation'), Permission.objects.get(codename=u'delete_translation')) owner_permissions = (Permission.objects.get(codename=u'author_translation'), Permission.objects.get(codename=u'upload_translation'), Permission.objects.get(codename=u'overwrite_translation'), Permission.objects.get(codename=u'commit_translation'), Permission.objects.get(codename=u'update_translation'), Permission.objects.get(codename=u'push_translation'), Permission.objects.get(codename=u'automatic_translation'), Permission.objects.get(codename=u'save_translation'), Permission.objects.get(codename=u'save_template'), Permission.objects.get(codename=u'accept_suggestion'), Permission.objects.get(codename=u'vote_suggestion'), Permission.objects.get(codename=u'override_suggestion'), Permission.objects.get(codename=u'delete_comment'), Permission.objects.get(codename=u'delete_suggestion'), Permission.objects.get(codename=u'ignore_check'), Permission.objects.get(codename=u'upload_dictionary'), Permission.objects.get(codename=u'add_dictionary'), Permission.objects.get(codename=u'change_dictionary'), Permission.objects.get(codename=u'delete_dictionary'), Permission.objects.get(codename=u'lock_subproject'), Permission.objects.get(codename=u'reset_translation'), Permission.objects.get(codename=u'lock_translation'), Permission.objects.get(codename=u'can_see_git_repository'), Permission.objects.get(codename=u'add_comment'), Permission.objects.get(codename=u'delete_comment'), Permission.objects.get(codename=u'add_suggestion'), Permission.objects.get(codename=u'use_mt'), Permission.objects.get(codename=u'edit_priority'), Permission.objects.get(codename=u'edit_flags'), Permission.objects.get(codename=u'manage_acl'), Permission.objects.get(codename=u'download_changes'), Permission.objects.get(codename=u'view_reports'), Permission.objects.get(codename=u'add_translation'), Permission.objects.get(codename=u'delete_translation'), Permission.objects.get(codename=u'change_subproject'), Permission.objects.get(codename=u'change_project'), Permission.objects.get(codename=u'upload_screenshot')) (group, created) = Group.objects.get_or_create(name=u'Managers') if (created or update or (group.permissions.count() == 0)): group.permissions.add(*owner_permissions) (group, created) = Group.objects.get_or_create(name=u'Owners') if (created or update or (group.permissions.count() == 0)): group.permissions.add(*owner_permissions) created = True try: anon_user = User.objects.get(username=ANONYMOUS_USER_NAME) created = False if anon_user.is_active: raise ValueError(u'Anonymous user ({}) already exists and enabled, please change ANONYMOUS_USER_NAME setting.'.format(ANONYMOUS_USER_NAME)) except User.DoesNotExist: anon_user = User.objects.create(username=ANONYMOUS_USER_NAME, email=u'noreply@weblate.org', is_active=False) if (created or update): anon_user.set_unusable_password() anon_user.groups.clear() anon_user.groups.add(guest_group)
null
null
null
Creates standard groups and gives them permissions.
pcsd
def create groups update guest group created = Group objects get or create name=u'Guests' if created or update or guest group permissions count == 0 guest group permissions add Permission objects get codename=u'can see git repository' Permission objects get codename=u'add suggestion' group created = Group objects get or create name=u'Users' if created or update or group permissions count == 0 group permissions add Permission objects get codename=u'upload translation' Permission objects get codename=u'overwrite translation' Permission objects get codename=u'save translation' Permission objects get codename=u'save template' Permission objects get codename=u'accept suggestion' Permission objects get codename=u'delete suggestion' Permission objects get codename=u'vote suggestion' Permission objects get codename=u'ignore check' Permission objects get codename=u'upload dictionary' Permission objects get codename=u'add dictionary' Permission objects get codename=u'change dictionary' Permission objects get codename=u'delete dictionary' Permission objects get codename=u'lock translation' Permission objects get codename=u'can see git repository' Permission objects get codename=u'add comment' Permission objects get codename=u'add suggestion' Permission objects get codename=u'use mt' Permission objects get codename=u'add translation' Permission objects get codename=u'delete translation' owner permissions = Permission objects get codename=u'author translation' Permission objects get codename=u'upload translation' Permission objects get codename=u'overwrite translation' Permission objects get codename=u'commit translation' Permission objects get codename=u'update translation' Permission objects get codename=u'push translation' Permission objects get codename=u'automatic translation' Permission objects get codename=u'save translation' Permission objects get codename=u'save template' Permission objects get codename=u'accept suggestion' Permission objects get codename=u'vote suggestion' Permission objects get codename=u'override suggestion' Permission objects get codename=u'delete comment' Permission objects get codename=u'delete suggestion' Permission objects get codename=u'ignore check' Permission objects get codename=u'upload dictionary' Permission objects get codename=u'add dictionary' Permission objects get codename=u'change dictionary' Permission objects get codename=u'delete dictionary' Permission objects get codename=u'lock subproject' Permission objects get codename=u'reset translation' Permission objects get codename=u'lock translation' Permission objects get codename=u'can see git repository' Permission objects get codename=u'add comment' Permission objects get codename=u'delete comment' Permission objects get codename=u'add suggestion' Permission objects get codename=u'use mt' Permission objects get codename=u'edit priority' Permission objects get codename=u'edit flags' Permission objects get codename=u'manage acl' Permission objects get codename=u'download changes' Permission objects get codename=u'view reports' Permission objects get codename=u'add translation' Permission objects get codename=u'delete translation' Permission objects get codename=u'change subproject' Permission objects get codename=u'change project' Permission objects get codename=u'upload screenshot' group created = Group objects get or create name=u'Managers' if created or update or group permissions count == 0 group permissions add *owner permissions group created = Group objects get or create name=u'Owners' if created or update or group permissions count == 0 group permissions add *owner permissions created = True try anon user = User objects get username=ANONYMOUS USER NAME created = False if anon user is active raise Value Error u'Anonymous user {} already exists and enabled please change ANONYMOUS USER NAME setting ' format ANONYMOUS USER NAME except User Does Not Exist anon user = User objects create username=ANONYMOUS USER NAME email=u'noreply@weblate org' is active=False if created or update anon user set unusable password anon user groups clear anon user groups add guest group
6257
def create_groups(update): (guest_group, created) = Group.objects.get_or_create(name=u'Guests') if (created or update or (guest_group.permissions.count() == 0)): guest_group.permissions.add(Permission.objects.get(codename=u'can_see_git_repository'), Permission.objects.get(codename=u'add_suggestion')) (group, created) = Group.objects.get_or_create(name=u'Users') if (created or update or (group.permissions.count() == 0)): group.permissions.add(Permission.objects.get(codename=u'upload_translation'), Permission.objects.get(codename=u'overwrite_translation'), Permission.objects.get(codename=u'save_translation'), Permission.objects.get(codename=u'save_template'), Permission.objects.get(codename=u'accept_suggestion'), Permission.objects.get(codename=u'delete_suggestion'), Permission.objects.get(codename=u'vote_suggestion'), Permission.objects.get(codename=u'ignore_check'), Permission.objects.get(codename=u'upload_dictionary'), Permission.objects.get(codename=u'add_dictionary'), Permission.objects.get(codename=u'change_dictionary'), Permission.objects.get(codename=u'delete_dictionary'), Permission.objects.get(codename=u'lock_translation'), Permission.objects.get(codename=u'can_see_git_repository'), Permission.objects.get(codename=u'add_comment'), Permission.objects.get(codename=u'add_suggestion'), Permission.objects.get(codename=u'use_mt'), Permission.objects.get(codename=u'add_translation'), Permission.objects.get(codename=u'delete_translation')) owner_permissions = (Permission.objects.get(codename=u'author_translation'), Permission.objects.get(codename=u'upload_translation'), Permission.objects.get(codename=u'overwrite_translation'), Permission.objects.get(codename=u'commit_translation'), Permission.objects.get(codename=u'update_translation'), Permission.objects.get(codename=u'push_translation'), Permission.objects.get(codename=u'automatic_translation'), Permission.objects.get(codename=u'save_translation'), Permission.objects.get(codename=u'save_template'), Permission.objects.get(codename=u'accept_suggestion'), Permission.objects.get(codename=u'vote_suggestion'), Permission.objects.get(codename=u'override_suggestion'), Permission.objects.get(codename=u'delete_comment'), Permission.objects.get(codename=u'delete_suggestion'), Permission.objects.get(codename=u'ignore_check'), Permission.objects.get(codename=u'upload_dictionary'), Permission.objects.get(codename=u'add_dictionary'), Permission.objects.get(codename=u'change_dictionary'), Permission.objects.get(codename=u'delete_dictionary'), Permission.objects.get(codename=u'lock_subproject'), Permission.objects.get(codename=u'reset_translation'), Permission.objects.get(codename=u'lock_translation'), Permission.objects.get(codename=u'can_see_git_repository'), Permission.objects.get(codename=u'add_comment'), Permission.objects.get(codename=u'delete_comment'), Permission.objects.get(codename=u'add_suggestion'), Permission.objects.get(codename=u'use_mt'), Permission.objects.get(codename=u'edit_priority'), Permission.objects.get(codename=u'edit_flags'), Permission.objects.get(codename=u'manage_acl'), Permission.objects.get(codename=u'download_changes'), Permission.objects.get(codename=u'view_reports'), Permission.objects.get(codename=u'add_translation'), Permission.objects.get(codename=u'delete_translation'), Permission.objects.get(codename=u'change_subproject'), Permission.objects.get(codename=u'change_project'), Permission.objects.get(codename=u'upload_screenshot')) (group, created) = Group.objects.get_or_create(name=u'Managers') if (created or update or (group.permissions.count() == 0)): group.permissions.add(*owner_permissions) (group, created) = Group.objects.get_or_create(name=u'Owners') if (created or update or (group.permissions.count() == 0)): group.permissions.add(*owner_permissions) created = True try: anon_user = User.objects.get(username=ANONYMOUS_USER_NAME) created = False if anon_user.is_active: raise ValueError(u'Anonymous user ({}) already exists and enabled, please change ANONYMOUS_USER_NAME setting.'.format(ANONYMOUS_USER_NAME)) except User.DoesNotExist: anon_user = User.objects.create(username=ANONYMOUS_USER_NAME, email=u'noreply@weblate.org', is_active=False) if (created or update): anon_user.set_unusable_password() anon_user.groups.clear() anon_user.groups.add(guest_group)
Creates standard groups and gives them permissions.
creates standard groups and gives them permissions .
Question: What does this function do? Code: def create_groups(update): (guest_group, created) = Group.objects.get_or_create(name=u'Guests') if (created or update or (guest_group.permissions.count() == 0)): guest_group.permissions.add(Permission.objects.get(codename=u'can_see_git_repository'), Permission.objects.get(codename=u'add_suggestion')) (group, created) = Group.objects.get_or_create(name=u'Users') if (created or update or (group.permissions.count() == 0)): group.permissions.add(Permission.objects.get(codename=u'upload_translation'), Permission.objects.get(codename=u'overwrite_translation'), Permission.objects.get(codename=u'save_translation'), Permission.objects.get(codename=u'save_template'), Permission.objects.get(codename=u'accept_suggestion'), Permission.objects.get(codename=u'delete_suggestion'), Permission.objects.get(codename=u'vote_suggestion'), Permission.objects.get(codename=u'ignore_check'), Permission.objects.get(codename=u'upload_dictionary'), Permission.objects.get(codename=u'add_dictionary'), Permission.objects.get(codename=u'change_dictionary'), Permission.objects.get(codename=u'delete_dictionary'), Permission.objects.get(codename=u'lock_translation'), Permission.objects.get(codename=u'can_see_git_repository'), Permission.objects.get(codename=u'add_comment'), Permission.objects.get(codename=u'add_suggestion'), Permission.objects.get(codename=u'use_mt'), Permission.objects.get(codename=u'add_translation'), Permission.objects.get(codename=u'delete_translation')) owner_permissions = (Permission.objects.get(codename=u'author_translation'), Permission.objects.get(codename=u'upload_translation'), Permission.objects.get(codename=u'overwrite_translation'), Permission.objects.get(codename=u'commit_translation'), Permission.objects.get(codename=u'update_translation'), Permission.objects.get(codename=u'push_translation'), Permission.objects.get(codename=u'automatic_translation'), Permission.objects.get(codename=u'save_translation'), Permission.objects.get(codename=u'save_template'), Permission.objects.get(codename=u'accept_suggestion'), Permission.objects.get(codename=u'vote_suggestion'), Permission.objects.get(codename=u'override_suggestion'), Permission.objects.get(codename=u'delete_comment'), Permission.objects.get(codename=u'delete_suggestion'), Permission.objects.get(codename=u'ignore_check'), Permission.objects.get(codename=u'upload_dictionary'), Permission.objects.get(codename=u'add_dictionary'), Permission.objects.get(codename=u'change_dictionary'), Permission.objects.get(codename=u'delete_dictionary'), Permission.objects.get(codename=u'lock_subproject'), Permission.objects.get(codename=u'reset_translation'), Permission.objects.get(codename=u'lock_translation'), Permission.objects.get(codename=u'can_see_git_repository'), Permission.objects.get(codename=u'add_comment'), Permission.objects.get(codename=u'delete_comment'), Permission.objects.get(codename=u'add_suggestion'), Permission.objects.get(codename=u'use_mt'), Permission.objects.get(codename=u'edit_priority'), Permission.objects.get(codename=u'edit_flags'), Permission.objects.get(codename=u'manage_acl'), Permission.objects.get(codename=u'download_changes'), Permission.objects.get(codename=u'view_reports'), Permission.objects.get(codename=u'add_translation'), Permission.objects.get(codename=u'delete_translation'), Permission.objects.get(codename=u'change_subproject'), Permission.objects.get(codename=u'change_project'), Permission.objects.get(codename=u'upload_screenshot')) (group, created) = Group.objects.get_or_create(name=u'Managers') if (created or update or (group.permissions.count() == 0)): group.permissions.add(*owner_permissions) (group, created) = Group.objects.get_or_create(name=u'Owners') if (created or update or (group.permissions.count() == 0)): group.permissions.add(*owner_permissions) created = True try: anon_user = User.objects.get(username=ANONYMOUS_USER_NAME) created = False if anon_user.is_active: raise ValueError(u'Anonymous user ({}) already exists and enabled, please change ANONYMOUS_USER_NAME setting.'.format(ANONYMOUS_USER_NAME)) except User.DoesNotExist: anon_user = User.objects.create(username=ANONYMOUS_USER_NAME, email=u'noreply@weblate.org', is_active=False) if (created or update): anon_user.set_unusable_password() anon_user.groups.clear() anon_user.groups.add(guest_group)
null
null
null
What does this function do?
def is_image_extendable(image): LOG.debug('Checking if we can extend filesystem inside %(image)s.', {'image': image}) if ((not isinstance(image, imgmodel.LocalImage)) or (image.format != imgmodel.FORMAT_RAW)): fs = None try: fs = vfs.VFS.instance_for_image(image, None) fs.setup(mount=False) if (fs.get_image_fs() in SUPPORTED_FS_TO_EXTEND): return True except exception.NovaException as e: LOG.warning(_LW('Unable to mount image %(image)s with error %(error)s. Cannot resize.'), {'image': image, 'error': e}) finally: if (fs is not None): fs.teardown() return False else: try: utils.execute('e2label', image.path) except processutils.ProcessExecutionError as e: LOG.debug('Unable to determine label for image %(image)s with error %(error)s. Cannot resize.', {'image': image, 'error': e}) return False return True
null
null
null
Check whether we can extend the image.
pcsd
def is image extendable image LOG debug 'Checking if we can extend filesystem inside % image s ' {'image' image} if not isinstance image imgmodel Local Image or image format != imgmodel FORMAT RAW fs = None try fs = vfs VFS instance for image image None fs setup mount=False if fs get image fs in SUPPORTED FS TO EXTEND return True except exception Nova Exception as e LOG warning LW 'Unable to mount image % image s with error % error s Cannot resize ' {'image' image 'error' e} finally if fs is not None fs teardown return False else try utils execute 'e2label' image path except processutils Process Execution Error as e LOG debug 'Unable to determine label for image % image s with error % error s Cannot resize ' {'image' image 'error' e} return False return True
6259
def is_image_extendable(image): LOG.debug('Checking if we can extend filesystem inside %(image)s.', {'image': image}) if ((not isinstance(image, imgmodel.LocalImage)) or (image.format != imgmodel.FORMAT_RAW)): fs = None try: fs = vfs.VFS.instance_for_image(image, None) fs.setup(mount=False) if (fs.get_image_fs() in SUPPORTED_FS_TO_EXTEND): return True except exception.NovaException as e: LOG.warning(_LW('Unable to mount image %(image)s with error %(error)s. Cannot resize.'), {'image': image, 'error': e}) finally: if (fs is not None): fs.teardown() return False else: try: utils.execute('e2label', image.path) except processutils.ProcessExecutionError as e: LOG.debug('Unable to determine label for image %(image)s with error %(error)s. Cannot resize.', {'image': image, 'error': e}) return False return True
Check whether we can extend the image.
check whether we can extend the image .
Question: What does this function do? Code: def is_image_extendable(image): LOG.debug('Checking if we can extend filesystem inside %(image)s.', {'image': image}) if ((not isinstance(image, imgmodel.LocalImage)) or (image.format != imgmodel.FORMAT_RAW)): fs = None try: fs = vfs.VFS.instance_for_image(image, None) fs.setup(mount=False) if (fs.get_image_fs() in SUPPORTED_FS_TO_EXTEND): return True except exception.NovaException as e: LOG.warning(_LW('Unable to mount image %(image)s with error %(error)s. Cannot resize.'), {'image': image, 'error': e}) finally: if (fs is not None): fs.teardown() return False else: try: utils.execute('e2label', image.path) except processutils.ProcessExecutionError as e: LOG.debug('Unable to determine label for image %(image)s with error %(error)s. Cannot resize.', {'image': image, 'error': e}) return False return True
null
null
null
What does this function do?
@login_required def edit_answer(request, question_id, answer_id): answer = get_object_or_404(Answer, pk=answer_id, question=question_id) answer_preview = None if (not answer.allows_edit(request.user)): raise PermissionDenied upload_imageattachment(request, answer) if (request.method == 'GET'): form = AnswerForm({'content': answer.content}) return render(request, 'questions/edit_answer.html', {'form': form, 'answer': answer}) form = AnswerForm(request.POST) if form.is_valid(): answer.content = form.cleaned_data['content'] answer.updated_by = request.user if ('preview' in request.POST): answer.updated = datetime.now() answer_preview = answer else: log.warning(('User %s is editing answer with id=%s' % (request.user, answer.id))) answer.save() return HttpResponseRedirect(answer.get_absolute_url()) return render(request, 'questions/edit_answer.html', {'form': form, 'answer': answer, 'answer_preview': answer_preview})
null
null
null
Edit an answer.
pcsd
@login required def edit answer request question id answer id answer = get object or 404 Answer pk=answer id question=question id answer preview = None if not answer allows edit request user raise Permission Denied upload imageattachment request answer if request method == 'GET' form = Answer Form {'content' answer content} return render request 'questions/edit answer html' {'form' form 'answer' answer} form = Answer Form request POST if form is valid answer content = form cleaned data['content'] answer updated by = request user if 'preview' in request POST answer updated = datetime now answer preview = answer else log warning 'User %s is editing answer with id=%s' % request user answer id answer save return Http Response Redirect answer get absolute url return render request 'questions/edit answer html' {'form' form 'answer' answer 'answer preview' answer preview}
6262
@login_required def edit_answer(request, question_id, answer_id): answer = get_object_or_404(Answer, pk=answer_id, question=question_id) answer_preview = None if (not answer.allows_edit(request.user)): raise PermissionDenied upload_imageattachment(request, answer) if (request.method == 'GET'): form = AnswerForm({'content': answer.content}) return render(request, 'questions/edit_answer.html', {'form': form, 'answer': answer}) form = AnswerForm(request.POST) if form.is_valid(): answer.content = form.cleaned_data['content'] answer.updated_by = request.user if ('preview' in request.POST): answer.updated = datetime.now() answer_preview = answer else: log.warning(('User %s is editing answer with id=%s' % (request.user, answer.id))) answer.save() return HttpResponseRedirect(answer.get_absolute_url()) return render(request, 'questions/edit_answer.html', {'form': form, 'answer': answer, 'answer_preview': answer_preview})
Edit an answer.
edit an answer .
Question: What does this function do? Code: @login_required def edit_answer(request, question_id, answer_id): answer = get_object_or_404(Answer, pk=answer_id, question=question_id) answer_preview = None if (not answer.allows_edit(request.user)): raise PermissionDenied upload_imageattachment(request, answer) if (request.method == 'GET'): form = AnswerForm({'content': answer.content}) return render(request, 'questions/edit_answer.html', {'form': form, 'answer': answer}) form = AnswerForm(request.POST) if form.is_valid(): answer.content = form.cleaned_data['content'] answer.updated_by = request.user if ('preview' in request.POST): answer.updated = datetime.now() answer_preview = answer else: log.warning(('User %s is editing answer with id=%s' % (request.user, answer.id))) answer.save() return HttpResponseRedirect(answer.get_absolute_url()) return render(request, 'questions/edit_answer.html', {'form': form, 'answer': answer, 'answer_preview': answer_preview})
null
null
null
What does this function do?
def load_filters(filters_path): filterlist = [] for filterdir in filters_path: if (not os.path.isdir(filterdir)): continue for filterfile in os.listdir(filterdir): filterconfig = ConfigParser.RawConfigParser() filterconfig.read(os.path.join(filterdir, filterfile)) for (name, value) in filterconfig.items('Filters'): filterdefinition = [string.strip(s) for s in value.split(',')] newfilter = build_filter(*filterdefinition) if (newfilter is None): continue filterlist.append(newfilter) return filterlist
null
null
null
Load filters from a list of directories
pcsd
def load filters filters path filterlist = [] for filterdir in filters path if not os path isdir filterdir continue for filterfile in os listdir filterdir filterconfig = Config Parser Raw Config Parser filterconfig read os path join filterdir filterfile for name value in filterconfig items 'Filters' filterdefinition = [string strip s for s in value split ' ' ] newfilter = build filter *filterdefinition if newfilter is None continue filterlist append newfilter return filterlist
6269
def load_filters(filters_path): filterlist = [] for filterdir in filters_path: if (not os.path.isdir(filterdir)): continue for filterfile in os.listdir(filterdir): filterconfig = ConfigParser.RawConfigParser() filterconfig.read(os.path.join(filterdir, filterfile)) for (name, value) in filterconfig.items('Filters'): filterdefinition = [string.strip(s) for s in value.split(',')] newfilter = build_filter(*filterdefinition) if (newfilter is None): continue filterlist.append(newfilter) return filterlist
Load filters from a list of directories
load filters from a list of directories
Question: What does this function do? Code: def load_filters(filters_path): filterlist = [] for filterdir in filters_path: if (not os.path.isdir(filterdir)): continue for filterfile in os.listdir(filterdir): filterconfig = ConfigParser.RawConfigParser() filterconfig.read(os.path.join(filterdir, filterfile)) for (name, value) in filterconfig.items('Filters'): filterdefinition = [string.strip(s) for s in value.split(',')] newfilter = build_filter(*filterdefinition) if (newfilter is None): continue filterlist.append(newfilter) return filterlist
null
null
null
What does this function do?
def tumblr2fields(api_key, blogname): from time import strftime, localtime try: import json except ImportError: import simplejson as json try: import urllib.request as urllib_request except ImportError: import urllib2 as urllib_request def get_tumblr_posts(api_key, blogname, offset=0): url = (u'http://api.tumblr.com/v2/blog/%s.tumblr.com/posts?api_key=%s&offset=%d&filter=raw' % (blogname, api_key, offset)) request = urllib_request.Request(url) handle = urllib_request.urlopen(request) posts = json.loads(handle.read().decode(u'utf-8')) return posts.get(u'response').get(u'posts') offset = 0 posts = get_tumblr_posts(api_key, blogname, offset) while (len(posts) > 0): for post in posts: title = (post.get(u'title') or post.get(u'source_title') or post.get(u'type').capitalize()) slug = (post.get(u'slug') or slugify(title)) tags = post.get(u'tags') timestamp = post.get(u'timestamp') date = strftime(u'%Y-%m-%d %H:%M:%S', localtime(int(timestamp))) slug = (strftime(u'%Y-%m-%d-', localtime(int(timestamp))) + slug) format = post.get(u'format') content = post.get(u'body') type = post.get(u'type') if (type == u'photo'): if (format == u'markdown'): fmtstr = u'![%s](%s)' else: fmtstr = u'<img alt="%s" src="%s" />' content = u'' for photo in post.get(u'photos'): content += u'\n'.join((fmtstr % (photo.get(u'caption'), photo.get(u'original_size').get(u'url')))) content += (u'\n\n' + post.get(u'caption')) elif (type == u'quote'): if (format == u'markdown'): fmtstr = u'\n\n&mdash; %s' else: fmtstr = u'<p>&mdash; %s</p>' content = (post.get(u'text') + (fmtstr % post.get(u'source'))) elif (type == u'link'): if (format == u'markdown'): fmtstr = u'[via](%s)\n\n' else: fmtstr = u'<p><a href="%s">via</a></p>\n' content = ((fmtstr % post.get(u'url')) + post.get(u'description')) elif (type == u'audio'): if (format == u'markdown'): fmtstr = u'[via](%s)\n\n' else: fmtstr = u'<p><a href="%s">via</a></p>\n' content = (((fmtstr % post.get(u'source_url')) + post.get(u'caption')) + post.get(u'player')) elif (type == u'video'): if (format == u'markdown'): fmtstr = u'[via](%s)\n\n' else: fmtstr = u'<p><a href="%s">via</a></p>\n' source = (fmtstr % post.get(u'source_url')) caption = post.get(u'caption') players = u'\n'.join((player.get(u'embed_code') for player in post.get(u'player'))) content = ((source + caption) + players) elif (type == u'answer'): title = post.get(u'question') content = (u'<p><a href="%s" rel="external nofollow">%s</a>: %s</p>\n %s' % (post.get(u'asking_name'), post.get(u'asking_url'), post.get(u'question'), post.get(u'answer'))) content = (content.rstrip() + u'\n') kind = u'article' status = u'published' (yield (title, content, slug, date, post.get(u'blog_name'), [type], tags, status, kind, format)) offset += len(posts) posts = get_tumblr_posts(api_key, blogname, offset)
null
null
null
Imports Tumblr posts (API v2)
pcsd
def tumblr2fields api key blogname from time import strftime localtime try import json except Import Error import simplejson as json try import urllib request as urllib request except Import Error import urllib2 as urllib request def get tumblr posts api key blogname offset=0 url = u'http //api tumblr com/v2/blog/%s tumblr com/posts?api key=%s&offset=%d&filter=raw' % blogname api key offset request = urllib request Request url handle = urllib request urlopen request posts = json loads handle read decode u'utf-8' return posts get u'response' get u'posts' offset = 0 posts = get tumblr posts api key blogname offset while len posts > 0 for post in posts title = post get u'title' or post get u'source title' or post get u'type' capitalize slug = post get u'slug' or slugify title tags = post get u'tags' timestamp = post get u'timestamp' date = strftime u'%Y-%m-%d %H %M %S' localtime int timestamp slug = strftime u'%Y-%m-%d-' localtime int timestamp + slug format = post get u'format' content = post get u'body' type = post get u'type' if type == u'photo' if format == u'markdown' fmtstr = u'![%s] %s ' else fmtstr = u'<img alt="%s" src="%s" />' content = u'' for photo in post get u'photos' content += u' ' join fmtstr % photo get u'caption' photo get u'original size' get u'url' content += u' ' + post get u'caption' elif type == u'quote' if format == u'markdown' fmtstr = u' &mdash %s' else fmtstr = u'<p>&mdash %s</p>' content = post get u'text' + fmtstr % post get u'source' elif type == u'link' if format == u'markdown' fmtstr = u'[via] %s ' else fmtstr = u'<p><a href="%s">via</a></p> ' content = fmtstr % post get u'url' + post get u'description' elif type == u'audio' if format == u'markdown' fmtstr = u'[via] %s ' else fmtstr = u'<p><a href="%s">via</a></p> ' content = fmtstr % post get u'source url' + post get u'caption' + post get u'player' elif type == u'video' if format == u'markdown' fmtstr = u'[via] %s ' else fmtstr = u'<p><a href="%s">via</a></p> ' source = fmtstr % post get u'source url' caption = post get u'caption' players = u' ' join player get u'embed code' for player in post get u'player' content = source + caption + players elif type == u'answer' title = post get u'question' content = u'<p><a href="%s" rel="external nofollow">%s</a> %s</p> %s' % post get u'asking name' post get u'asking url' post get u'question' post get u'answer' content = content rstrip + u' ' kind = u'article' status = u'published' yield title content slug date post get u'blog name' [type] tags status kind format offset += len posts posts = get tumblr posts api key blogname offset
6274
def tumblr2fields(api_key, blogname): from time import strftime, localtime try: import json except ImportError: import simplejson as json try: import urllib.request as urllib_request except ImportError: import urllib2 as urllib_request def get_tumblr_posts(api_key, blogname, offset=0): url = (u'http://api.tumblr.com/v2/blog/%s.tumblr.com/posts?api_key=%s&offset=%d&filter=raw' % (blogname, api_key, offset)) request = urllib_request.Request(url) handle = urllib_request.urlopen(request) posts = json.loads(handle.read().decode(u'utf-8')) return posts.get(u'response').get(u'posts') offset = 0 posts = get_tumblr_posts(api_key, blogname, offset) while (len(posts) > 0): for post in posts: title = (post.get(u'title') or post.get(u'source_title') or post.get(u'type').capitalize()) slug = (post.get(u'slug') or slugify(title)) tags = post.get(u'tags') timestamp = post.get(u'timestamp') date = strftime(u'%Y-%m-%d %H:%M:%S', localtime(int(timestamp))) slug = (strftime(u'%Y-%m-%d-', localtime(int(timestamp))) + slug) format = post.get(u'format') content = post.get(u'body') type = post.get(u'type') if (type == u'photo'): if (format == u'markdown'): fmtstr = u'![%s](%s)' else: fmtstr = u'<img alt="%s" src="%s" />' content = u'' for photo in post.get(u'photos'): content += u'\n'.join((fmtstr % (photo.get(u'caption'), photo.get(u'original_size').get(u'url')))) content += (u'\n\n' + post.get(u'caption')) elif (type == u'quote'): if (format == u'markdown'): fmtstr = u'\n\n&mdash; %s' else: fmtstr = u'<p>&mdash; %s</p>' content = (post.get(u'text') + (fmtstr % post.get(u'source'))) elif (type == u'link'): if (format == u'markdown'): fmtstr = u'[via](%s)\n\n' else: fmtstr = u'<p><a href="%s">via</a></p>\n' content = ((fmtstr % post.get(u'url')) + post.get(u'description')) elif (type == u'audio'): if (format == u'markdown'): fmtstr = u'[via](%s)\n\n' else: fmtstr = u'<p><a href="%s">via</a></p>\n' content = (((fmtstr % post.get(u'source_url')) + post.get(u'caption')) + post.get(u'player')) elif (type == u'video'): if (format == u'markdown'): fmtstr = u'[via](%s)\n\n' else: fmtstr = u'<p><a href="%s">via</a></p>\n' source = (fmtstr % post.get(u'source_url')) caption = post.get(u'caption') players = u'\n'.join((player.get(u'embed_code') for player in post.get(u'player'))) content = ((source + caption) + players) elif (type == u'answer'): title = post.get(u'question') content = (u'<p><a href="%s" rel="external nofollow">%s</a>: %s</p>\n %s' % (post.get(u'asking_name'), post.get(u'asking_url'), post.get(u'question'), post.get(u'answer'))) content = (content.rstrip() + u'\n') kind = u'article' status = u'published' (yield (title, content, slug, date, post.get(u'blog_name'), [type], tags, status, kind, format)) offset += len(posts) posts = get_tumblr_posts(api_key, blogname, offset)
Imports Tumblr posts (API v2)
imports tumblr posts
Question: What does this function do? Code: def tumblr2fields(api_key, blogname): from time import strftime, localtime try: import json except ImportError: import simplejson as json try: import urllib.request as urllib_request except ImportError: import urllib2 as urllib_request def get_tumblr_posts(api_key, blogname, offset=0): url = (u'http://api.tumblr.com/v2/blog/%s.tumblr.com/posts?api_key=%s&offset=%d&filter=raw' % (blogname, api_key, offset)) request = urllib_request.Request(url) handle = urllib_request.urlopen(request) posts = json.loads(handle.read().decode(u'utf-8')) return posts.get(u'response').get(u'posts') offset = 0 posts = get_tumblr_posts(api_key, blogname, offset) while (len(posts) > 0): for post in posts: title = (post.get(u'title') or post.get(u'source_title') or post.get(u'type').capitalize()) slug = (post.get(u'slug') or slugify(title)) tags = post.get(u'tags') timestamp = post.get(u'timestamp') date = strftime(u'%Y-%m-%d %H:%M:%S', localtime(int(timestamp))) slug = (strftime(u'%Y-%m-%d-', localtime(int(timestamp))) + slug) format = post.get(u'format') content = post.get(u'body') type = post.get(u'type') if (type == u'photo'): if (format == u'markdown'): fmtstr = u'![%s](%s)' else: fmtstr = u'<img alt="%s" src="%s" />' content = u'' for photo in post.get(u'photos'): content += u'\n'.join((fmtstr % (photo.get(u'caption'), photo.get(u'original_size').get(u'url')))) content += (u'\n\n' + post.get(u'caption')) elif (type == u'quote'): if (format == u'markdown'): fmtstr = u'\n\n&mdash; %s' else: fmtstr = u'<p>&mdash; %s</p>' content = (post.get(u'text') + (fmtstr % post.get(u'source'))) elif (type == u'link'): if (format == u'markdown'): fmtstr = u'[via](%s)\n\n' else: fmtstr = u'<p><a href="%s">via</a></p>\n' content = ((fmtstr % post.get(u'url')) + post.get(u'description')) elif (type == u'audio'): if (format == u'markdown'): fmtstr = u'[via](%s)\n\n' else: fmtstr = u'<p><a href="%s">via</a></p>\n' content = (((fmtstr % post.get(u'source_url')) + post.get(u'caption')) + post.get(u'player')) elif (type == u'video'): if (format == u'markdown'): fmtstr = u'[via](%s)\n\n' else: fmtstr = u'<p><a href="%s">via</a></p>\n' source = (fmtstr % post.get(u'source_url')) caption = post.get(u'caption') players = u'\n'.join((player.get(u'embed_code') for player in post.get(u'player'))) content = ((source + caption) + players) elif (type == u'answer'): title = post.get(u'question') content = (u'<p><a href="%s" rel="external nofollow">%s</a>: %s</p>\n %s' % (post.get(u'asking_name'), post.get(u'asking_url'), post.get(u'question'), post.get(u'answer'))) content = (content.rstrip() + u'\n') kind = u'article' status = u'published' (yield (title, content, slug, date, post.get(u'blog_name'), [type], tags, status, kind, format)) offset += len(posts) posts = get_tumblr_posts(api_key, blogname, offset)
null
null
null
What does this function do?
def get_volume_extra_specs(volume): ctxt = context.get_admin_context() type_id = volume.get('volume_type_id') if (type_id is None): return {} volume_type = volume_types.get_volume_type(ctxt, type_id) if (volume_type is None): return {} extra_specs = volume_type.get('extra_specs', {}) log_extra_spec_warnings(extra_specs) return extra_specs
null
null
null
Provides extra specs associated with volume.
pcsd
def get volume extra specs volume ctxt = context get admin context type id = volume get 'volume type id' if type id is None return {} volume type = volume types get volume type ctxt type id if volume type is None return {} extra specs = volume type get 'extra specs' {} log extra spec warnings extra specs return extra specs
6283
def get_volume_extra_specs(volume): ctxt = context.get_admin_context() type_id = volume.get('volume_type_id') if (type_id is None): return {} volume_type = volume_types.get_volume_type(ctxt, type_id) if (volume_type is None): return {} extra_specs = volume_type.get('extra_specs', {}) log_extra_spec_warnings(extra_specs) return extra_specs
Provides extra specs associated with volume.
provides extra specs associated with volume .
Question: What does this function do? Code: def get_volume_extra_specs(volume): ctxt = context.get_admin_context() type_id = volume.get('volume_type_id') if (type_id is None): return {} volume_type = volume_types.get_volume_type(ctxt, type_id) if (volume_type is None): return {} extra_specs = volume_type.get('extra_specs', {}) log_extra_spec_warnings(extra_specs) return extra_specs
null
null
null
What does this function do?
def download_attachments(output_path, urls): locations = [] for url in urls: path = urlparse(url).path path = path.split(u'/') filename = path.pop((-1)) localpath = u'' for item in path: if ((sys.platform != u'win32') or (u':' not in item)): localpath = os.path.join(localpath, item) full_path = os.path.join(output_path, localpath) if (not os.path.exists(full_path)): os.makedirs(full_path) print(u'downloading {}'.format(filename)) try: urlretrieve(url, os.path.join(full_path, filename)) locations.append(os.path.join(localpath, filename)) except (URLError, IOError) as e: logger.warning(u'No file could be downloaded from %s\n%s', url, e) return locations
null
null
null
Downloads WordPress attachments and returns a list of paths to attachments that can be associated with a post (relative path to output directory). Files that fail to download, will not be added to posts
pcsd
def download attachments output path urls locations = [] for url in urls path = urlparse url path path = path split u'/' filename = path pop -1 localpath = u'' for item in path if sys platform != u'win32' or u' ' not in item localpath = os path join localpath item full path = os path join output path localpath if not os path exists full path os makedirs full path print u'downloading {}' format filename try urlretrieve url os path join full path filename locations append os path join localpath filename except URL Error IO Error as e logger warning u'No file could be downloaded from %s %s' url e return locations
6289
def download_attachments(output_path, urls): locations = [] for url in urls: path = urlparse(url).path path = path.split(u'/') filename = path.pop((-1)) localpath = u'' for item in path: if ((sys.platform != u'win32') or (u':' not in item)): localpath = os.path.join(localpath, item) full_path = os.path.join(output_path, localpath) if (not os.path.exists(full_path)): os.makedirs(full_path) print(u'downloading {}'.format(filename)) try: urlretrieve(url, os.path.join(full_path, filename)) locations.append(os.path.join(localpath, filename)) except (URLError, IOError) as e: logger.warning(u'No file could be downloaded from %s\n%s', url, e) return locations
Downloads WordPress attachments and returns a list of paths to attachments that can be associated with a post (relative path to output directory). Files that fail to download, will not be added to posts
downloads wordpress attachments and returns a list of paths to attachments that can be associated with a post .
Question: What does this function do? Code: def download_attachments(output_path, urls): locations = [] for url in urls: path = urlparse(url).path path = path.split(u'/') filename = path.pop((-1)) localpath = u'' for item in path: if ((sys.platform != u'win32') or (u':' not in item)): localpath = os.path.join(localpath, item) full_path = os.path.join(output_path, localpath) if (not os.path.exists(full_path)): os.makedirs(full_path) print(u'downloading {}'.format(filename)) try: urlretrieve(url, os.path.join(full_path, filename)) locations.append(os.path.join(localpath, filename)) except (URLError, IOError) as e: logger.warning(u'No file could be downloaded from %s\n%s', url, e) return locations
null
null
null
What does this function do?
def read_packet(sock, timeout=None): sock.settimeout(timeout) (dlen, data) = (None, None) try: if (os.name == 'nt'): datalen = sock.recv(SZ) (dlen,) = struct.unpack('l', datalen) data = '' while (len(data) < dlen): data += sock.recv(dlen) else: datalen = temp_fail_retry(socket.error, sock.recv, SZ, socket.MSG_WAITALL) if (len(datalen) == SZ): (dlen,) = struct.unpack('l', datalen) data = temp_fail_retry(socket.error, sock.recv, dlen, socket.MSG_WAITALL) except socket.timeout: raise except socket.error: data = None finally: sock.settimeout(None) if (data is not None): try: return pickle.loads(data) except Exception: if DEBUG_EDITOR: traceback.print_exc(file=STDERR) return
null
null
null
Read data from socket *sock* Returns None if something went wrong
pcsd
def read packet sock timeout=None sock settimeout timeout dlen data = None None try if os name == 'nt' datalen = sock recv SZ dlen = struct unpack 'l' datalen data = '' while len data < dlen data += sock recv dlen else datalen = temp fail retry socket error sock recv SZ socket MSG WAITALL if len datalen == SZ dlen = struct unpack 'l' datalen data = temp fail retry socket error sock recv dlen socket MSG WAITALL except socket timeout raise except socket error data = None finally sock settimeout None if data is not None try return pickle loads data except Exception if DEBUG EDITOR traceback print exc file=STDERR return
6293
def read_packet(sock, timeout=None): sock.settimeout(timeout) (dlen, data) = (None, None) try: if (os.name == 'nt'): datalen = sock.recv(SZ) (dlen,) = struct.unpack('l', datalen) data = '' while (len(data) < dlen): data += sock.recv(dlen) else: datalen = temp_fail_retry(socket.error, sock.recv, SZ, socket.MSG_WAITALL) if (len(datalen) == SZ): (dlen,) = struct.unpack('l', datalen) data = temp_fail_retry(socket.error, sock.recv, dlen, socket.MSG_WAITALL) except socket.timeout: raise except socket.error: data = None finally: sock.settimeout(None) if (data is not None): try: return pickle.loads(data) except Exception: if DEBUG_EDITOR: traceback.print_exc(file=STDERR) return
Read data from socket *sock* Returns None if something went wrong
read data from socket * sock *
Question: What does this function do? Code: def read_packet(sock, timeout=None): sock.settimeout(timeout) (dlen, data) = (None, None) try: if (os.name == 'nt'): datalen = sock.recv(SZ) (dlen,) = struct.unpack('l', datalen) data = '' while (len(data) < dlen): data += sock.recv(dlen) else: datalen = temp_fail_retry(socket.error, sock.recv, SZ, socket.MSG_WAITALL) if (len(datalen) == SZ): (dlen,) = struct.unpack('l', datalen) data = temp_fail_retry(socket.error, sock.recv, dlen, socket.MSG_WAITALL) except socket.timeout: raise except socket.error: data = None finally: sock.settimeout(None) if (data is not None): try: return pickle.loads(data) except Exception: if DEBUG_EDITOR: traceback.print_exc(file=STDERR) return
null
null
null
What does this function do?
def delayed_fail(): time.sleep(5) raise ValueError('Expected failure.')
null
null
null
Delayed failure to make sure that processes are running before the error is raised. TODO handle more directly (without sleeping)
pcsd
def delayed fail time sleep 5 raise Value Error 'Expected failure '
6311
def delayed_fail(): time.sleep(5) raise ValueError('Expected failure.')
Delayed failure to make sure that processes are running before the error is raised. TODO handle more directly (without sleeping)
delayed failure to make sure that processes are running before the error is raised .
Question: What does this function do? Code: def delayed_fail(): time.sleep(5) raise ValueError('Expected failure.')
null
null
null
What does this function do?
@register.simple_tag def simple_one_default(one, two='hi'): return ('simple_one_default - Expected result: %s, %s' % (one, two))
null
null
null
Expected simple_one_default __doc__
pcsd
@register simple tag def simple one default one two='hi' return 'simple one default - Expected result %s %s' % one two
6321
@register.simple_tag def simple_one_default(one, two='hi'): return ('simple_one_default - Expected result: %s, %s' % (one, two))
Expected simple_one_default __doc__
expected simple _ one _ default _ _ doc _ _
Question: What does this function do? Code: @register.simple_tag def simple_one_default(one, two='hi'): return ('simple_one_default - Expected result: %s, %s' % (one, two))
null
null
null
What does this function do?
def parse_args(): parser = argparse.ArgumentParser(description='Train a Fast R-CNN network') parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [0]', default=0, type=int) parser.add_argument('--solver', dest='solver', help='solver prototxt', default=None, type=str) parser.add_argument('--iters', dest='max_iters', help='number of iterations to train', default=40000, type=int) parser.add_argument('--weights', dest='pretrained_model', help='initialize with pretrained model weights', default=None, type=str) parser.add_argument('--cfg', dest='cfg_file', help='optional config file', default=None, type=str) parser.add_argument('--imdb', dest='imdb_name', help='dataset to train on', default='voc_2007_trainval', type=str) parser.add_argument('--rand', dest='randomize', help='randomize (do not use a fixed seed)', action='store_true') parser.add_argument('--set', dest='set_cfgs', help='set config keys', default=None, nargs=argparse.REMAINDER) if (len(sys.argv) == 1): parser.print_help() sys.exit(1) args = parser.parse_args() return args
null
null
null
Parse input arguments
pcsd
def parse args parser = argparse Argument Parser description='Train a Fast R-CNN network' parser add argument '--gpu' dest='gpu id' help='GPU device id to use [0]' default=0 type=int parser add argument '--solver' dest='solver' help='solver prototxt' default=None type=str parser add argument '--iters' dest='max iters' help='number of iterations to train' default=40000 type=int parser add argument '--weights' dest='pretrained model' help='initialize with pretrained model weights' default=None type=str parser add argument '--cfg' dest='cfg file' help='optional config file' default=None type=str parser add argument '--imdb' dest='imdb name' help='dataset to train on' default='voc 2007 trainval' type=str parser add argument '--rand' dest='randomize' help='randomize do not use a fixed seed ' action='store true' parser add argument '--set' dest='set cfgs' help='set config keys' default=None nargs=argparse REMAINDER if len sys argv == 1 parser print help sys exit 1 args = parser parse args return args
6324
def parse_args(): parser = argparse.ArgumentParser(description='Train a Fast R-CNN network') parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [0]', default=0, type=int) parser.add_argument('--solver', dest='solver', help='solver prototxt', default=None, type=str) parser.add_argument('--iters', dest='max_iters', help='number of iterations to train', default=40000, type=int) parser.add_argument('--weights', dest='pretrained_model', help='initialize with pretrained model weights', default=None, type=str) parser.add_argument('--cfg', dest='cfg_file', help='optional config file', default=None, type=str) parser.add_argument('--imdb', dest='imdb_name', help='dataset to train on', default='voc_2007_trainval', type=str) parser.add_argument('--rand', dest='randomize', help='randomize (do not use a fixed seed)', action='store_true') parser.add_argument('--set', dest='set_cfgs', help='set config keys', default=None, nargs=argparse.REMAINDER) if (len(sys.argv) == 1): parser.print_help() sys.exit(1) args = parser.parse_args() return args
Parse input arguments
parse input arguments
Question: What does this function do? Code: def parse_args(): parser = argparse.ArgumentParser(description='Train a Fast R-CNN network') parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [0]', default=0, type=int) parser.add_argument('--solver', dest='solver', help='solver prototxt', default=None, type=str) parser.add_argument('--iters', dest='max_iters', help='number of iterations to train', default=40000, type=int) parser.add_argument('--weights', dest='pretrained_model', help='initialize with pretrained model weights', default=None, type=str) parser.add_argument('--cfg', dest='cfg_file', help='optional config file', default=None, type=str) parser.add_argument('--imdb', dest='imdb_name', help='dataset to train on', default='voc_2007_trainval', type=str) parser.add_argument('--rand', dest='randomize', help='randomize (do not use a fixed seed)', action='store_true') parser.add_argument('--set', dest='set_cfgs', help='set config keys', default=None, nargs=argparse.REMAINDER) if (len(sys.argv) == 1): parser.print_help() sys.exit(1) args = parser.parse_args() return args
null
null
null
What does this function do?
def get_default_secret_key(): secret_access_key_script = AWS_ACCOUNTS['default'].SECRET_ACCESS_KEY_SCRIPT.get() return (secret_access_key_script or get_s3a_secret_key())
null
null
null
Attempt to set AWS secret key from script, else core-site, else None
pcsd
def get default secret key secret access key script = AWS ACCOUNTS['default'] SECRET ACCESS KEY SCRIPT get return secret access key script or get s3a secret key
6330
def get_default_secret_key(): secret_access_key_script = AWS_ACCOUNTS['default'].SECRET_ACCESS_KEY_SCRIPT.get() return (secret_access_key_script or get_s3a_secret_key())
Attempt to set AWS secret key from script, else core-site, else None
attempt to set aws secret key from script , else core - site , else none
Question: What does this function do? Code: def get_default_secret_key(): secret_access_key_script = AWS_ACCOUNTS['default'].SECRET_ACCESS_KEY_SCRIPT.get() return (secret_access_key_script or get_s3a_secret_key())
null
null
null
What does this function do?
def baseline(): assess_tables() return s3_rest_controller()
null
null
null
RESTful CRUD controller
pcsd
def baseline assess tables return s3 rest controller
6334
def baseline(): assess_tables() return s3_rest_controller()
RESTful CRUD controller
restful crud controller
Question: What does this function do? Code: def baseline(): assess_tables() return s3_rest_controller()
null
null
null
What does this function do?
def getLocationFromSplitLine(oldLocation, splitLine): if (oldLocation == None): oldLocation = Vector3() return Vector3(getDoubleFromCharacterSplitLineValue('X', splitLine, oldLocation.x), getDoubleFromCharacterSplitLineValue('Y', splitLine, oldLocation.y), getDoubleFromCharacterSplitLineValue('Z', splitLine, oldLocation.z))
null
null
null
Get the location from the split line.
pcsd
def get Location From Split Line old Location split Line if old Location == None old Location = Vector3 return Vector3 get Double From Character Split Line Value 'X' split Line old Location x get Double From Character Split Line Value 'Y' split Line old Location y get Double From Character Split Line Value 'Z' split Line old Location z
6335
def getLocationFromSplitLine(oldLocation, splitLine): if (oldLocation == None): oldLocation = Vector3() return Vector3(getDoubleFromCharacterSplitLineValue('X', splitLine, oldLocation.x), getDoubleFromCharacterSplitLineValue('Y', splitLine, oldLocation.y), getDoubleFromCharacterSplitLineValue('Z', splitLine, oldLocation.z))
Get the location from the split line.
get the location from the split line .
Question: What does this function do? Code: def getLocationFromSplitLine(oldLocation, splitLine): if (oldLocation == None): oldLocation = Vector3() return Vector3(getDoubleFromCharacterSplitLineValue('X', splitLine, oldLocation.x), getDoubleFromCharacterSplitLineValue('Y', splitLine, oldLocation.y), getDoubleFromCharacterSplitLineValue('Z', splitLine, oldLocation.z))
null
null
null
What does this function do?
def generate_x509_cert(user_id, project_id, bits=2048): subject = _user_cert_subject(user_id, project_id) with utils.tempdir() as tmpdir: keyfile = os.path.abspath(os.path.join(tmpdir, 'temp.key')) csrfile = os.path.abspath(os.path.join(tmpdir, 'temp.csr')) utils.execute('openssl', 'genrsa', '-out', keyfile, str(bits)) utils.execute('openssl', 'req', '-new', '-key', keyfile, '-out', csrfile, '-batch', '-subj', subject) with open(keyfile) as f: private_key = f.read() with open(csrfile) as f: csr = f.read() (serial, signed_csr) = sign_csr(csr, project_id) fname = os.path.join(ca_folder(project_id), ('newcerts/%s.pem' % serial)) cert = {'user_id': user_id, 'project_id': project_id, 'file_name': fname} db.certificate_create(context.get_admin_context(), cert) return (private_key, signed_csr)
null
null
null
Generate and sign a cert for user in project.
pcsd
def generate x509 cert user id project id bits=2048 subject = user cert subject user id project id with utils tempdir as tmpdir keyfile = os path abspath os path join tmpdir 'temp key' csrfile = os path abspath os path join tmpdir 'temp csr' utils execute 'openssl' 'genrsa' '-out' keyfile str bits utils execute 'openssl' 'req' '-new' '-key' keyfile '-out' csrfile '-batch' '-subj' subject with open keyfile as f private key = f read with open csrfile as f csr = f read serial signed csr = sign csr csr project id fname = os path join ca folder project id 'newcerts/%s pem' % serial cert = {'user id' user id 'project id' project id 'file name' fname} db certificate create context get admin context cert return private key signed csr
6337
def generate_x509_cert(user_id, project_id, bits=2048): subject = _user_cert_subject(user_id, project_id) with utils.tempdir() as tmpdir: keyfile = os.path.abspath(os.path.join(tmpdir, 'temp.key')) csrfile = os.path.abspath(os.path.join(tmpdir, 'temp.csr')) utils.execute('openssl', 'genrsa', '-out', keyfile, str(bits)) utils.execute('openssl', 'req', '-new', '-key', keyfile, '-out', csrfile, '-batch', '-subj', subject) with open(keyfile) as f: private_key = f.read() with open(csrfile) as f: csr = f.read() (serial, signed_csr) = sign_csr(csr, project_id) fname = os.path.join(ca_folder(project_id), ('newcerts/%s.pem' % serial)) cert = {'user_id': user_id, 'project_id': project_id, 'file_name': fname} db.certificate_create(context.get_admin_context(), cert) return (private_key, signed_csr)
Generate and sign a cert for user in project.
generate and sign a cert for user in project .
Question: What does this function do? Code: def generate_x509_cert(user_id, project_id, bits=2048): subject = _user_cert_subject(user_id, project_id) with utils.tempdir() as tmpdir: keyfile = os.path.abspath(os.path.join(tmpdir, 'temp.key')) csrfile = os.path.abspath(os.path.join(tmpdir, 'temp.csr')) utils.execute('openssl', 'genrsa', '-out', keyfile, str(bits)) utils.execute('openssl', 'req', '-new', '-key', keyfile, '-out', csrfile, '-batch', '-subj', subject) with open(keyfile) as f: private_key = f.read() with open(csrfile) as f: csr = f.read() (serial, signed_csr) = sign_csr(csr, project_id) fname = os.path.join(ca_folder(project_id), ('newcerts/%s.pem' % serial)) cert = {'user_id': user_id, 'project_id': project_id, 'file_name': fname} db.certificate_create(context.get_admin_context(), cert) return (private_key, signed_csr)
null
null
null
What does this function do?
def randrange_fmt(mode, char, obj): x = randrange(*fmtdict[mode][char]) if (char == 'c'): x = bytes([x]) if ((obj == 'numpy') and (x == '\x00')): x = '\x01' if (char == '?'): x = bool(x) if ((char == 'f') or (char == 'd')): x = struct.pack(char, x) x = struct.unpack(char, x)[0] return x
null
null
null
Return random item for a type specified by a mode and a single format character.
pcsd
def randrange fmt mode char obj x = randrange *fmtdict[mode][char] if char == 'c' x = bytes [x] if obj == 'numpy' and x == '\x00' x = '\x01' if char == '?' x = bool x if char == 'f' or char == 'd' x = struct pack char x x = struct unpack char x [0] return x
6341
def randrange_fmt(mode, char, obj): x = randrange(*fmtdict[mode][char]) if (char == 'c'): x = bytes([x]) if ((obj == 'numpy') and (x == '\x00')): x = '\x01' if (char == '?'): x = bool(x) if ((char == 'f') or (char == 'd')): x = struct.pack(char, x) x = struct.unpack(char, x)[0] return x
Return random item for a type specified by a mode and a single format character.
return random item for a type specified by a mode and a single format character .
Question: What does this function do? Code: def randrange_fmt(mode, char, obj): x = randrange(*fmtdict[mode][char]) if (char == 'c'): x = bytes([x]) if ((obj == 'numpy') and (x == '\x00')): x = '\x01' if (char == '?'): x = bool(x) if ((char == 'f') or (char == 'd')): x = struct.pack(char, x) x = struct.unpack(char, x)[0] return x
null
null
null
What does this function do?
def remove_dir_if_empty(path, ignore_metadata_caches=False): try: os.rmdir(path) except OSError as e: if ((e.errno == errno.ENOTEMPTY) or (len(os.listdir(path)) > 0)): if ignore_metadata_caches: try: found = False for x in os.listdir(path): if (x.lower() in {'.ds_store', 'thumbs.db'}): found = True x = os.path.join(path, x) if os.path.isdir(x): import shutil shutil.rmtree(x) else: os.remove(x) except Exception: found = False if found: remove_dir_if_empty(path) return raise
null
null
null
Remove a directory if it is empty or contains only the folder metadata caches from different OSes. To delete the folder if it contains only metadata caches, set ignore_metadata_caches to True.
pcsd
def remove dir if empty path ignore metadata caches=False try os rmdir path except OS Error as e if e errno == errno ENOTEMPTY or len os listdir path > 0 if ignore metadata caches try found = False for x in os listdir path if x lower in {' ds store' 'thumbs db'} found = True x = os path join path x if os path isdir x import shutil shutil rmtree x else os remove x except Exception found = False if found remove dir if empty path return raise
6342
def remove_dir_if_empty(path, ignore_metadata_caches=False): try: os.rmdir(path) except OSError as e: if ((e.errno == errno.ENOTEMPTY) or (len(os.listdir(path)) > 0)): if ignore_metadata_caches: try: found = False for x in os.listdir(path): if (x.lower() in {'.ds_store', 'thumbs.db'}): found = True x = os.path.join(path, x) if os.path.isdir(x): import shutil shutil.rmtree(x) else: os.remove(x) except Exception: found = False if found: remove_dir_if_empty(path) return raise
Remove a directory if it is empty or contains only the folder metadata caches from different OSes. To delete the folder if it contains only metadata caches, set ignore_metadata_caches to True.
remove a directory if it is empty or contains only the folder metadata caches from different oses .
Question: What does this function do? Code: def remove_dir_if_empty(path, ignore_metadata_caches=False): try: os.rmdir(path) except OSError as e: if ((e.errno == errno.ENOTEMPTY) or (len(os.listdir(path)) > 0)): if ignore_metadata_caches: try: found = False for x in os.listdir(path): if (x.lower() in {'.ds_store', 'thumbs.db'}): found = True x = os.path.join(path, x) if os.path.isdir(x): import shutil shutil.rmtree(x) else: os.remove(x) except Exception: found = False if found: remove_dir_if_empty(path) return raise
null
null
null
What does this function do?
def python_int_bitwidth(): return (struct.calcsize('l') * 8)
null
null
null
Return the bit width of Python int (C long int). Note that it can be different from the size of a memory pointer.
pcsd
def python int bitwidth return struct calcsize 'l' * 8
6361
def python_int_bitwidth(): return (struct.calcsize('l') * 8)
Return the bit width of Python int (C long int). Note that it can be different from the size of a memory pointer.
return the bit width of python int .
Question: What does this function do? Code: def python_int_bitwidth(): return (struct.calcsize('l') * 8)
null
null
null
What does this function do?
def start(): global __SCHED if __SCHED: logging.debug('Starting scheduler') __SCHED.start()
null
null
null
Start the scheduler
pcsd
def start global SCHED if SCHED logging debug 'Starting scheduler' SCHED start
6364
def start(): global __SCHED if __SCHED: logging.debug('Starting scheduler') __SCHED.start()
Start the scheduler
start the scheduler
Question: What does this function do? Code: def start(): global __SCHED if __SCHED: logging.debug('Starting scheduler') __SCHED.start()
null
null
null
What does this function do?
@pytest.fixture def temporary_topic(): pubsub_client = pubsub.Client() topic = pubsub_client.topic(TOPIC_NAME) if topic.exists(): topic.delete() (yield) if topic.exists(): topic.delete()
null
null
null
Fixture that ensures the test dataset does not exist before or after a test.
pcsd
@pytest fixture def temporary topic pubsub client = pubsub Client topic = pubsub client topic TOPIC NAME if topic exists topic delete yield if topic exists topic delete
6370
@pytest.fixture def temporary_topic(): pubsub_client = pubsub.Client() topic = pubsub_client.topic(TOPIC_NAME) if topic.exists(): topic.delete() (yield) if topic.exists(): topic.delete()
Fixture that ensures the test dataset does not exist before or after a test.
fixture that ensures the test dataset does not exist before or after a test .
Question: What does this function do? Code: @pytest.fixture def temporary_topic(): pubsub_client = pubsub.Client() topic = pubsub_client.topic(TOPIC_NAME) if topic.exists(): topic.delete() (yield) if topic.exists(): topic.delete()
null
null
null
What does this function do?
@require_role('user') def asset_list(request): (header_title, path1, path2) = (u'\u67e5\u770b\u8d44\u4ea7', u'\u8d44\u4ea7\u7ba1\u7406', u'\u67e5\u770b\u8d44\u4ea7') username = request.user.username user_perm = request.session['role_id'] idc_all = IDC.objects.filter() asset_group_all = AssetGroup.objects.all() asset_types = ASSET_TYPE asset_status = ASSET_STATUS idc_name = request.GET.get('idc', '') group_name = request.GET.get('group', '') asset_type = request.GET.get('asset_type', '') status = request.GET.get('status', '') keyword = request.GET.get('keyword', '') export = request.GET.get('export', False) group_id = request.GET.get('group_id', '') idc_id = request.GET.get('idc_id', '') asset_id_all = request.GET.getlist('id', '') if group_id: group = get_object(AssetGroup, id=group_id) if group: asset_find = Asset.objects.filter(group=group) elif idc_id: idc = get_object(IDC, id=idc_id) if idc: asset_find = Asset.objects.filter(idc=idc) elif (user_perm != 0): asset_find = Asset.objects.all() else: asset_id_all = [] user = get_object(User, username=username) asset_perm = (get_group_user_perm(user) if user else {'asset': ''}) user_asset_perm = asset_perm['asset'].keys() for asset in user_asset_perm: asset_id_all.append(asset.id) asset_find = Asset.objects.filter(pk__in=asset_id_all) asset_group_all = list(asset_perm['asset_group']) if idc_name: asset_find = asset_find.filter(idc__name__contains=idc_name) if group_name: asset_find = asset_find.filter(group__name__contains=group_name) if asset_type: asset_find = asset_find.filter(asset_type__contains=asset_type) if status: asset_find = asset_find.filter(status__contains=status) if keyword: asset_find = asset_find.filter(((((((((((((((Q(hostname__contains=keyword) | Q(other_ip__contains=keyword)) | Q(ip__contains=keyword)) | Q(remote_ip__contains=keyword)) | Q(comment__contains=keyword)) | Q(username__contains=keyword)) | Q(group__name__contains=keyword)) | Q(cpu__contains=keyword)) | Q(memory__contains=keyword)) | Q(disk__contains=keyword)) | Q(brand__contains=keyword)) | Q(cabinet__contains=keyword)) | Q(sn__contains=keyword)) | Q(system_type__contains=keyword)) | Q(system_version__contains=keyword))) if export: if asset_id_all: asset_find = [] for asset_id in asset_id_all: asset = get_object(Asset, id=asset_id) if asset: asset_find.append(asset) s = write_excel(asset_find) if s[0]: file_name = s[1] smg = u'excel\u6587\u4ef6\u5df2\u751f\u6210\uff0c\u8bf7\u70b9\u51fb\u4e0b\u8f7d!' return my_render('jasset/asset_excel_download.html', locals(), request) (assets_list, p, assets, page_range, current_page, show_first, show_end) = pages(asset_find, request) if (user_perm != 0): return my_render('jasset/asset_list.html', locals(), request) else: return my_render('jasset/asset_cu_list.html', locals(), request)
null
null
null
asset list view
pcsd
@require role 'user' def asset list request header title path1 path2 = u'\u67e5\u770b\u8d44\u4ea7' u'\u8d44\u4ea7\u7ba1\u7406' u'\u67e5\u770b\u8d44\u4ea7' username = request user username user perm = request session['role id'] idc all = IDC objects filter asset group all = Asset Group objects all asset types = ASSET TYPE asset status = ASSET STATUS idc name = request GET get 'idc' '' group name = request GET get 'group' '' asset type = request GET get 'asset type' '' status = request GET get 'status' '' keyword = request GET get 'keyword' '' export = request GET get 'export' False group id = request GET get 'group id' '' idc id = request GET get 'idc id' '' asset id all = request GET getlist 'id' '' if group id group = get object Asset Group id=group id if group asset find = Asset objects filter group=group elif idc id idc = get object IDC id=idc id if idc asset find = Asset objects filter idc=idc elif user perm != 0 asset find = Asset objects all else asset id all = [] user = get object User username=username asset perm = get group user perm user if user else {'asset' ''} user asset perm = asset perm['asset'] keys for asset in user asset perm asset id all append asset id asset find = Asset objects filter pk in=asset id all asset group all = list asset perm['asset group'] if idc name asset find = asset find filter idc name contains=idc name if group name asset find = asset find filter group name contains=group name if asset type asset find = asset find filter asset type contains=asset type if status asset find = asset find filter status contains=status if keyword asset find = asset find filter Q hostname contains=keyword | Q other ip contains=keyword | Q ip contains=keyword | Q remote ip contains=keyword | Q comment contains=keyword | Q username contains=keyword | Q group name contains=keyword | Q cpu contains=keyword | Q memory contains=keyword | Q disk contains=keyword | Q brand contains=keyword | Q cabinet contains=keyword | Q sn contains=keyword | Q system type contains=keyword | Q system version contains=keyword if export if asset id all asset find = [] for asset id in asset id all asset = get object Asset id=asset id if asset asset find append asset s = write excel asset find if s[0] file name = s[1] smg = u'excel\u6587\u4ef6\u5df2\u751f\u6210\uff0c\u8bf7\u70b9\u51fb\u4e0b\u8f7d!' return my render 'jasset/asset excel download html' locals request assets list p assets page range current page show first show end = pages asset find request if user perm != 0 return my render 'jasset/asset list html' locals request else return my render 'jasset/asset cu list html' locals request
6373
@require_role('user') def asset_list(request): (header_title, path1, path2) = (u'\u67e5\u770b\u8d44\u4ea7', u'\u8d44\u4ea7\u7ba1\u7406', u'\u67e5\u770b\u8d44\u4ea7') username = request.user.username user_perm = request.session['role_id'] idc_all = IDC.objects.filter() asset_group_all = AssetGroup.objects.all() asset_types = ASSET_TYPE asset_status = ASSET_STATUS idc_name = request.GET.get('idc', '') group_name = request.GET.get('group', '') asset_type = request.GET.get('asset_type', '') status = request.GET.get('status', '') keyword = request.GET.get('keyword', '') export = request.GET.get('export', False) group_id = request.GET.get('group_id', '') idc_id = request.GET.get('idc_id', '') asset_id_all = request.GET.getlist('id', '') if group_id: group = get_object(AssetGroup, id=group_id) if group: asset_find = Asset.objects.filter(group=group) elif idc_id: idc = get_object(IDC, id=idc_id) if idc: asset_find = Asset.objects.filter(idc=idc) elif (user_perm != 0): asset_find = Asset.objects.all() else: asset_id_all = [] user = get_object(User, username=username) asset_perm = (get_group_user_perm(user) if user else {'asset': ''}) user_asset_perm = asset_perm['asset'].keys() for asset in user_asset_perm: asset_id_all.append(asset.id) asset_find = Asset.objects.filter(pk__in=asset_id_all) asset_group_all = list(asset_perm['asset_group']) if idc_name: asset_find = asset_find.filter(idc__name__contains=idc_name) if group_name: asset_find = asset_find.filter(group__name__contains=group_name) if asset_type: asset_find = asset_find.filter(asset_type__contains=asset_type) if status: asset_find = asset_find.filter(status__contains=status) if keyword: asset_find = asset_find.filter(((((((((((((((Q(hostname__contains=keyword) | Q(other_ip__contains=keyword)) | Q(ip__contains=keyword)) | Q(remote_ip__contains=keyword)) | Q(comment__contains=keyword)) | Q(username__contains=keyword)) | Q(group__name__contains=keyword)) | Q(cpu__contains=keyword)) | Q(memory__contains=keyword)) | Q(disk__contains=keyword)) | Q(brand__contains=keyword)) | Q(cabinet__contains=keyword)) | Q(sn__contains=keyword)) | Q(system_type__contains=keyword)) | Q(system_version__contains=keyword))) if export: if asset_id_all: asset_find = [] for asset_id in asset_id_all: asset = get_object(Asset, id=asset_id) if asset: asset_find.append(asset) s = write_excel(asset_find) if s[0]: file_name = s[1] smg = u'excel\u6587\u4ef6\u5df2\u751f\u6210\uff0c\u8bf7\u70b9\u51fb\u4e0b\u8f7d!' return my_render('jasset/asset_excel_download.html', locals(), request) (assets_list, p, assets, page_range, current_page, show_first, show_end) = pages(asset_find, request) if (user_perm != 0): return my_render('jasset/asset_list.html', locals(), request) else: return my_render('jasset/asset_cu_list.html', locals(), request)
asset list view
asset list view
Question: What does this function do? Code: @require_role('user') def asset_list(request): (header_title, path1, path2) = (u'\u67e5\u770b\u8d44\u4ea7', u'\u8d44\u4ea7\u7ba1\u7406', u'\u67e5\u770b\u8d44\u4ea7') username = request.user.username user_perm = request.session['role_id'] idc_all = IDC.objects.filter() asset_group_all = AssetGroup.objects.all() asset_types = ASSET_TYPE asset_status = ASSET_STATUS idc_name = request.GET.get('idc', '') group_name = request.GET.get('group', '') asset_type = request.GET.get('asset_type', '') status = request.GET.get('status', '') keyword = request.GET.get('keyword', '') export = request.GET.get('export', False) group_id = request.GET.get('group_id', '') idc_id = request.GET.get('idc_id', '') asset_id_all = request.GET.getlist('id', '') if group_id: group = get_object(AssetGroup, id=group_id) if group: asset_find = Asset.objects.filter(group=group) elif idc_id: idc = get_object(IDC, id=idc_id) if idc: asset_find = Asset.objects.filter(idc=idc) elif (user_perm != 0): asset_find = Asset.objects.all() else: asset_id_all = [] user = get_object(User, username=username) asset_perm = (get_group_user_perm(user) if user else {'asset': ''}) user_asset_perm = asset_perm['asset'].keys() for asset in user_asset_perm: asset_id_all.append(asset.id) asset_find = Asset.objects.filter(pk__in=asset_id_all) asset_group_all = list(asset_perm['asset_group']) if idc_name: asset_find = asset_find.filter(idc__name__contains=idc_name) if group_name: asset_find = asset_find.filter(group__name__contains=group_name) if asset_type: asset_find = asset_find.filter(asset_type__contains=asset_type) if status: asset_find = asset_find.filter(status__contains=status) if keyword: asset_find = asset_find.filter(((((((((((((((Q(hostname__contains=keyword) | Q(other_ip__contains=keyword)) | Q(ip__contains=keyword)) | Q(remote_ip__contains=keyword)) | Q(comment__contains=keyword)) | Q(username__contains=keyword)) | Q(group__name__contains=keyword)) | Q(cpu__contains=keyword)) | Q(memory__contains=keyword)) | Q(disk__contains=keyword)) | Q(brand__contains=keyword)) | Q(cabinet__contains=keyword)) | Q(sn__contains=keyword)) | Q(system_type__contains=keyword)) | Q(system_version__contains=keyword))) if export: if asset_id_all: asset_find = [] for asset_id in asset_id_all: asset = get_object(Asset, id=asset_id) if asset: asset_find.append(asset) s = write_excel(asset_find) if s[0]: file_name = s[1] smg = u'excel\u6587\u4ef6\u5df2\u751f\u6210\uff0c\u8bf7\u70b9\u51fb\u4e0b\u8f7d!' return my_render('jasset/asset_excel_download.html', locals(), request) (assets_list, p, assets, page_range, current_page, show_first, show_end) = pages(asset_find, request) if (user_perm != 0): return my_render('jasset/asset_list.html', locals(), request) else: return my_render('jasset/asset_cu_list.html', locals(), request)
null
null
null
What does this function do?
@frappe.whitelist() def get_opening_accounts(company): accounts = frappe.db.sql_list(u"select\n DCTB DCTB DCTB name from tabAccount\n DCTB DCTB where\n DCTB DCTB DCTB is_group=0 and\n DCTB DCTB DCTB report_type='Balance Sheet' and\n DCTB DCTB DCTB ifnull(warehouse, '') = '' and\n DCTB DCTB DCTB company=%s\n DCTB DCTB order by name asc", company) return [{u'account': a, u'balance': get_balance_on(a)} for a in accounts]
null
null
null
get all balance sheet accounts for opening entry
pcsd
@frappe whitelist def get opening accounts company accounts = frappe db sql list u"select DCTB DCTB DCTB name from tab Account DCTB DCTB where DCTB DCTB DCTB is group=0 and DCTB DCTB DCTB report type='Balance Sheet' and DCTB DCTB DCTB ifnull warehouse '' = '' and DCTB DCTB DCTB company=%s DCTB DCTB order by name asc" company return [{u'account' a u'balance' get balance on a } for a in accounts]
6397
@frappe.whitelist() def get_opening_accounts(company): accounts = frappe.db.sql_list(u"select\n DCTB DCTB DCTB name from tabAccount\n DCTB DCTB where\n DCTB DCTB DCTB is_group=0 and\n DCTB DCTB DCTB report_type='Balance Sheet' and\n DCTB DCTB DCTB ifnull(warehouse, '') = '' and\n DCTB DCTB DCTB company=%s\n DCTB DCTB order by name asc", company) return [{u'account': a, u'balance': get_balance_on(a)} for a in accounts]
get all balance sheet accounts for opening entry
get all balance sheet accounts for opening entry
Question: What does this function do? Code: @frappe.whitelist() def get_opening_accounts(company): accounts = frappe.db.sql_list(u"select\n DCTB DCTB DCTB name from tabAccount\n DCTB DCTB where\n DCTB DCTB DCTB is_group=0 and\n DCTB DCTB DCTB report_type='Balance Sheet' and\n DCTB DCTB DCTB ifnull(warehouse, '') = '' and\n DCTB DCTB DCTB company=%s\n DCTB DCTB order by name asc", company) return [{u'account': a, u'balance': get_balance_on(a)} for a in accounts]
null
null
null
What does this function do?
def index(): s3_redirect_default(URL(f='job', args=['datalist']))
null
null
null
Module\'s Home Page
pcsd
def index s3 redirect default URL f='job' args=['datalist']
6400
def index(): s3_redirect_default(URL(f='job', args=['datalist']))
Module\'s Home Page
modules home page
Question: What does this function do? Code: def index(): s3_redirect_default(URL(f='job', args=['datalist']))
null
null
null
What does this function do?
def _pretty_hex(hex_str): if ((len(hex_str) % 2) != 0): hex_str = ('0' + hex_str) return ':'.join([hex_str[i:(i + 2)] for i in range(0, len(hex_str), 2)]).upper()
null
null
null
Nicely formats hex strings
pcsd
def pretty hex hex str if len hex str % 2 != 0 hex str = '0' + hex str return ' ' join [hex str[i i + 2 ] for i in range 0 len hex str 2 ] upper
6419
def _pretty_hex(hex_str): if ((len(hex_str) % 2) != 0): hex_str = ('0' + hex_str) return ':'.join([hex_str[i:(i + 2)] for i in range(0, len(hex_str), 2)]).upper()
Nicely formats hex strings
nicely formats hex strings
Question: What does this function do? Code: def _pretty_hex(hex_str): if ((len(hex_str) % 2) != 0): hex_str = ('0' + hex_str) return ':'.join([hex_str[i:(i + 2)] for i in range(0, len(hex_str), 2)]).upper()
null
null
null
What does this function do?
def make_list(value): return list(value)
null
null
null
Returns the value turned into a list. For an integer, it\'s a list of digits. For a string, it\'s a list of characters.
pcsd
def make list value return list value
6422
def make_list(value): return list(value)
Returns the value turned into a list. For an integer, it\'s a list of digits. For a string, it\'s a list of characters.
returns the value turned into a list .
Question: What does this function do? Code: def make_list(value): return list(value)
null
null
null
What does this function do?
def probe(verbose=False): import platform from gsmmodem import GsmModem import serial baudrates = [115200, 9600, 19200] ports = [] if (platform.system() == 'Linux'): import scanlinux as portscanner if (platform.system() == 'Windows'): import scanwin32 as portscanner if (platform.system() == 'Darwin'): import scanmac as portscanner try: for port in portscanner.scan(): if verbose: print ('Attempting to connect to port %s' % port) try: for baudrate in baudrates: if verbose: GsmModem(port=port, timeout=10, baudrate=baudrate) else: GsmModem(port=port, timeout=10, logger=logger, baudrate=baudrate) ports.append((port, baudrate)) break except serial.serialutil.SerialException as e: if verbose: print e pass except NameError as e: if verbose: print e pass return ports
null
null
null
Searches for probable ports on the system
pcsd
def probe verbose=False import platform from gsmmodem import Gsm Modem import serial baudrates = [115200 9600 19200] ports = [] if platform system == 'Linux' import scanlinux as portscanner if platform system == 'Windows' import scanwin32 as portscanner if platform system == 'Darwin' import scanmac as portscanner try for port in portscanner scan if verbose print 'Attempting to connect to port %s' % port try for baudrate in baudrates if verbose Gsm Modem port=port timeout=10 baudrate=baudrate else Gsm Modem port=port timeout=10 logger=logger baudrate=baudrate ports append port baudrate break except serial serialutil Serial Exception as e if verbose print e pass except Name Error as e if verbose print e pass return ports
6428
def probe(verbose=False): import platform from gsmmodem import GsmModem import serial baudrates = [115200, 9600, 19200] ports = [] if (platform.system() == 'Linux'): import scanlinux as portscanner if (platform.system() == 'Windows'): import scanwin32 as portscanner if (platform.system() == 'Darwin'): import scanmac as portscanner try: for port in portscanner.scan(): if verbose: print ('Attempting to connect to port %s' % port) try: for baudrate in baudrates: if verbose: GsmModem(port=port, timeout=10, baudrate=baudrate) else: GsmModem(port=port, timeout=10, logger=logger, baudrate=baudrate) ports.append((port, baudrate)) break except serial.serialutil.SerialException as e: if verbose: print e pass except NameError as e: if verbose: print e pass return ports
Searches for probable ports on the system
searches for probable ports on the system
Question: What does this function do? Code: def probe(verbose=False): import platform from gsmmodem import GsmModem import serial baudrates = [115200, 9600, 19200] ports = [] if (platform.system() == 'Linux'): import scanlinux as portscanner if (platform.system() == 'Windows'): import scanwin32 as portscanner if (platform.system() == 'Darwin'): import scanmac as portscanner try: for port in portscanner.scan(): if verbose: print ('Attempting to connect to port %s' % port) try: for baudrate in baudrates: if verbose: GsmModem(port=port, timeout=10, baudrate=baudrate) else: GsmModem(port=port, timeout=10, logger=logger, baudrate=baudrate) ports.append((port, baudrate)) break except serial.serialutil.SerialException as e: if verbose: print e pass except NameError as e: if verbose: print e pass return ports
null
null
null
What does this function do?
def getSortedInjectionTests(): retVal = copy.deepcopy(conf.tests) def priorityFunction(test): retVal = SORT_ORDER.FIRST if (test.stype == PAYLOAD.TECHNIQUE.UNION): retVal = SORT_ORDER.LAST elif (('details' in test) and ('dbms' in test.details)): if intersect(test.details.dbms, Backend.getIdentifiedDbms()): retVal = SORT_ORDER.SECOND else: retVal = SORT_ORDER.THIRD return retVal if Backend.getIdentifiedDbms(): retVal = sorted(retVal, key=priorityFunction) return retVal
null
null
null
Returns prioritized test list by eventually detected DBMS from error messages
pcsd
def get Sorted Injection Tests ret Val = copy deepcopy conf tests def priority Function test ret Val = SORT ORDER FIRST if test stype == PAYLOAD TECHNIQUE UNION ret Val = SORT ORDER LAST elif 'details' in test and 'dbms' in test details if intersect test details dbms Backend get Identified Dbms ret Val = SORT ORDER SECOND else ret Val = SORT ORDER THIRD return ret Val if Backend get Identified Dbms ret Val = sorted ret Val key=priority Function return ret Val
6431
def getSortedInjectionTests(): retVal = copy.deepcopy(conf.tests) def priorityFunction(test): retVal = SORT_ORDER.FIRST if (test.stype == PAYLOAD.TECHNIQUE.UNION): retVal = SORT_ORDER.LAST elif (('details' in test) and ('dbms' in test.details)): if intersect(test.details.dbms, Backend.getIdentifiedDbms()): retVal = SORT_ORDER.SECOND else: retVal = SORT_ORDER.THIRD return retVal if Backend.getIdentifiedDbms(): retVal = sorted(retVal, key=priorityFunction) return retVal
Returns prioritized test list by eventually detected DBMS from error messages
returns prioritized test list by eventually detected dbms from error messages
Question: What does this function do? Code: def getSortedInjectionTests(): retVal = copy.deepcopy(conf.tests) def priorityFunction(test): retVal = SORT_ORDER.FIRST if (test.stype == PAYLOAD.TECHNIQUE.UNION): retVal = SORT_ORDER.LAST elif (('details' in test) and ('dbms' in test.details)): if intersect(test.details.dbms, Backend.getIdentifiedDbms()): retVal = SORT_ORDER.SECOND else: retVal = SORT_ORDER.THIRD return retVal if Backend.getIdentifiedDbms(): retVal = sorted(retVal, key=priorityFunction) return retVal
null
null
null
What does this function do?
def list_bundled_profiles(): path = os.path.join(get_ipython_package_dir(), u'core', u'profile') files = os.listdir(path) profiles = [] for profile in files: full_path = os.path.join(path, profile) if (os.path.isdir(full_path) and (profile != '__pycache__')): profiles.append(profile) return profiles
null
null
null
list profiles that are bundled with IPython.
pcsd
def list bundled profiles path = os path join get ipython package dir u'core' u'profile' files = os listdir path profiles = [] for profile in files full path = os path join path profile if os path isdir full path and profile != ' pycache ' profiles append profile return profiles
6438
def list_bundled_profiles(): path = os.path.join(get_ipython_package_dir(), u'core', u'profile') files = os.listdir(path) profiles = [] for profile in files: full_path = os.path.join(path, profile) if (os.path.isdir(full_path) and (profile != '__pycache__')): profiles.append(profile) return profiles
list profiles that are bundled with IPython.
list profiles that are bundled with ipython .
Question: What does this function do? Code: def list_bundled_profiles(): path = os.path.join(get_ipython_package_dir(), u'core', u'profile') files = os.listdir(path) profiles = [] for profile in files: full_path = os.path.join(path, profile) if (os.path.isdir(full_path) and (profile != '__pycache__')): profiles.append(profile) return profiles
null
null
null
What does this function do?
@utils.arg('--flavor', default=None, metavar='<flavor>', help=_("Name or ID of flavor (see 'nova flavor-list').")) @utils.arg('--image', default=None, metavar='<image>', help=_("Name or ID of image (see 'glance image-list'). ")) @utils.arg('--image-with', default=[], type=_key_value_pairing, action='append', metavar='<key=value>', help=_("Image metadata property (see 'glance image-show'). ")) @utils.arg('--boot-volume', default=None, metavar='<volume_id>', help=_('Volume ID to boot from.')) @utils.arg('--snapshot', default=None, metavar='<snapshot_id>', help=_('Snapshot ID to boot from (will create a volume).')) @utils.arg('--min-count', default=None, type=int, metavar='<number>', help=_('Boot at least <number> servers (limited by quota).')) @utils.arg('--max-count', default=None, type=int, metavar='<number>', help=_('Boot up to <number> servers (limited by quota).')) @utils.arg('--meta', metavar='<key=value>', action='append', default=[], help=_('Record arbitrary key/value metadata to /meta_data.json on the metadata server. Can be specified multiple times.')) @utils.arg('--file', metavar='<dst-path=src-path>', action='append', dest='files', default=[], help=_('Store arbitrary files from <src-path> locally to <dst-path> on the new server. Limited by the injected_files quota value.')) @utils.arg('--key-name', default=os.environ.get('NOVACLIENT_DEFAULT_KEY_NAME'), metavar='<key-name>', help=_('Key name of keypair that should be created earlier with the command keypair-add.')) @utils.arg('name', metavar='<name>', help=_('Name for the new server.')) @utils.arg('--user-data', default=None, metavar='<user-data>', help=_('user data file to pass to be exposed by the metadata server.')) @utils.arg('--availability-zone', default=None, metavar='<availability-zone>', help=_('The availability zone for server placement.')) @utils.arg('--security-groups', default=None, metavar='<security-groups>', help=_('Comma separated list of security group names.')) @utils.arg('--block-device-mapping', metavar='<dev-name=mapping>', action='append', default=[], help=_('Block device mapping in the format <dev-name>=<id>:<type>:<size(GB)>:<delete-on-terminate>.')) @utils.arg('--block-device', metavar='key1=value1[,key2=value2...]', action='append', default=[], start_version='2.0', end_version='2.31', help=_("Block device mapping with the keys: id=UUID (image_id, snapshot_id or volume_id only if using source image, snapshot or volume) source=source type (image, snapshot, volume or blank), dest=destination type of the block device (volume or local), bus=device's bus (e.g. uml, lxc, virtio, ...; if omitted, hypervisor driver chooses a suitable default, honoured only if device type is supplied) type=device type (e.g. disk, cdrom, ...; defaults to 'disk') device=name of the device (e.g. vda, xda, ...; if omitted, hypervisor driver chooses suitable device depending on selected bus; note the libvirt driver always uses default device names), size=size of the block device in MB(for swap) and in GB(for other formats) (if omitted, hypervisor driver calculates size), format=device will be formatted (e.g. swap, ntfs, ...; optional), bootindex=integer used for ordering the boot disks (for image backed instances it is equal to 0, for others need to be specified) and shutdown=shutdown behaviour (either preserve or remove, for local destination set to remove).")) @utils.arg('--block-device', metavar='key1=value1[,key2=value2...]', action='append', default=[], start_version='2.32', help=_("Block device mapping with the keys: id=UUID (image_id, snapshot_id or volume_id only if using source image, snapshot or volume) source=source type (image, snapshot, volume or blank), dest=destination type of the block device (volume or local), bus=device's bus (e.g. uml, lxc, virtio, ...; if omitted, hypervisor driver chooses a suitable default, honoured only if device type is supplied) type=device type (e.g. disk, cdrom, ...; defaults to 'disk') device=name of the device (e.g. vda, xda, ...; tag=device metadata tag (optional) if omitted, hypervisor driver chooses suitable device depending on selected bus; note the libvirt driver always uses default device names), size=size of the block device in MB(for swap) and in GB(for other formats) (if omitted, hypervisor driver calculates size), format=device will be formatted (e.g. swap, ntfs, ...; optional), bootindex=integer used for ordering the boot disks (for image backed instances it is equal to 0, for others need to be specified) and shutdown=shutdown behaviour (either preserve or remove, for local destination set to remove).")) @utils.arg('--swap', metavar='<swap_size>', default=None, help=_('Create and attach a local swap block device of <swap_size> MB.')) @utils.arg('--ephemeral', metavar='size=<size>[,format=<format>]', action='append', default=[], help=_('Create and attach a local ephemeral block device of <size> GB and format it to <format>.')) @utils.arg('--hint', action='append', dest='scheduler_hints', default=[], metavar='<key=value>', help=_('Send arbitrary key/value pairs to the scheduler for custom use.')) @utils.arg('--nic', metavar='<net-id=net-uuid,net-name=network-name,v4-fixed-ip=ip-addr,v6-fixed-ip=ip-addr,port-id=port-uuid>', action='append', dest='nics', default=[], start_version='2.0', end_version='2.31', help=_('Create a NIC on the server. Specify option multiple times to create multiple NICs. net-id: attach NIC to network with this UUID net-name: attach NIC to network with this name (either port-id or net-id or net-name must be provided), v4-fixed-ip: IPv4 fixed address for NIC (optional), v6-fixed-ip: IPv6 fixed address for NIC (optional), port-id: attach NIC to port with this UUID (either port-id or net-id must be provided).')) @utils.arg('--nic', metavar='<net-id=net-uuid,net-name=network-name,v4-fixed-ip=ip-addr,v6-fixed-ip=ip-addr,port-id=port-uuid>', action='append', dest='nics', default=[], start_version='2.32', end_version='2.36', help=_('Create a NIC on the server. Specify option multiple times to create multiple nics. net-id: attach NIC to network with this UUID net-name: attach NIC to network with this name (either port-id or net-id or net-name must be provided), v4-fixed-ip: IPv4 fixed address for NIC (optional), v6-fixed-ip: IPv6 fixed address for NIC (optional), port-id: attach NIC to port with this UUID tag: interface metadata tag (optional) (either port-id or net-id must be provided).')) @utils.arg('--nic', metavar='<auto,none,net-id=net-uuid,net-name=network-name,port-id=port-uuid,v4-fixed-ip=ip-addr,v6-fixed-ip=ip-addr,tag=tag>', action='append', dest='nics', default=[], start_version='2.37', help=_("Create a NIC on the server. Specify option multiple times to create multiple nics unless using the special 'auto' or 'none' values. auto: automatically allocate network resources if none are available. This cannot be specified with any other nic value and cannot be specified multiple times. none: do not attach a NIC at all. This cannot be specified with any other nic value and cannot be specified multiple times. net-id: attach NIC to network with a specific UUID. net-name: attach NIC to network with this name (either port-id or net-id or net-name must be provided), v4-fixed-ip: IPv4 fixed address for NIC (optional), v6-fixed-ip: IPv6 fixed address for NIC (optional), port-id: attach NIC to port with this UUID tag: interface metadata tag (optional) (either port-id or net-id must be provided).")) @utils.arg('--config-drive', metavar='<value>', dest='config_drive', default=False, help=_('Enable config drive.')) @utils.arg('--poll', dest='poll', action='store_true', default=False, help=_('Report the new server boot progress until it completes.')) @utils.arg('--admin-pass', dest='admin_pass', metavar='<value>', default=None, help=_('Admin password for the instance.')) @utils.arg('--access-ip-v4', dest='access_ip_v4', metavar='<value>', default=None, help=_('Alternative access IPv4 of the instance.')) @utils.arg('--access-ip-v6', dest='access_ip_v6', metavar='<value>', default=None, help=_('Alternative access IPv6 of the instance.')) @utils.arg('--description', metavar='<description>', dest='description', default=None, help=_('Description for the server.'), start_version='2.19') def do_boot(cs, args): (boot_args, boot_kwargs) = _boot(cs, args) extra_boot_kwargs = utils.get_resource_manager_extra_kwargs(do_boot, args) boot_kwargs.update(extra_boot_kwargs) server = cs.servers.create(*boot_args, **boot_kwargs) _print_server(cs, args, server) if args.poll: _poll_for_status(cs.servers.get, server.id, 'building', ['active'])
null
null
null
Boot a new server.
pcsd
@utils arg '--flavor' default=None metavar='<flavor>' help= "Name or ID of flavor see 'nova flavor-list' " @utils arg '--image' default=None metavar='<image>' help= "Name or ID of image see 'glance image-list' " @utils arg '--image-with' default=[] type= key value pairing action='append' metavar='<key=value>' help= "Image metadata property see 'glance image-show' " @utils arg '--boot-volume' default=None metavar='<volume id>' help= 'Volume ID to boot from ' @utils arg '--snapshot' default=None metavar='<snapshot id>' help= 'Snapshot ID to boot from will create a volume ' @utils arg '--min-count' default=None type=int metavar='<number>' help= 'Boot at least <number> servers limited by quota ' @utils arg '--max-count' default=None type=int metavar='<number>' help= 'Boot up to <number> servers limited by quota ' @utils arg '--meta' metavar='<key=value>' action='append' default=[] help= 'Record arbitrary key/value metadata to /meta data json on the metadata server Can be specified multiple times ' @utils arg '--file' metavar='<dst-path=src-path>' action='append' dest='files' default=[] help= 'Store arbitrary files from <src-path> locally to <dst-path> on the new server Limited by the injected files quota value ' @utils arg '--key-name' default=os environ get 'NOVACLIENT DEFAULT KEY NAME' metavar='<key-name>' help= 'Key name of keypair that should be created earlier with the command keypair-add ' @utils arg 'name' metavar='<name>' help= 'Name for the new server ' @utils arg '--user-data' default=None metavar='<user-data>' help= 'user data file to pass to be exposed by the metadata server ' @utils arg '--availability-zone' default=None metavar='<availability-zone>' help= 'The availability zone for server placement ' @utils arg '--security-groups' default=None metavar='<security-groups>' help= 'Comma separated list of security group names ' @utils arg '--block-device-mapping' metavar='<dev-name=mapping>' action='append' default=[] help= 'Block device mapping in the format <dev-name>=<id> <type> <size GB > <delete-on-terminate> ' @utils arg '--block-device' metavar='key1=value1[ key2=value2 ]' action='append' default=[] start version='2 0' end version='2 31' help= "Block device mapping with the keys id=UUID image id snapshot id or volume id only if using source image snapshot or volume source=source type image snapshot volume or blank dest=destination type of the block device volume or local bus=device's bus e g uml lxc virtio if omitted hypervisor driver chooses a suitable default honoured only if device type is supplied type=device type e g disk cdrom defaults to 'disk' device=name of the device e g vda xda if omitted hypervisor driver chooses suitable device depending on selected bus note the libvirt driver always uses default device names size=size of the block device in MB for swap and in GB for other formats if omitted hypervisor driver calculates size format=device will be formatted e g swap ntfs optional bootindex=integer used for ordering the boot disks for image backed instances it is equal to 0 for others need to be specified and shutdown=shutdown behaviour either preserve or remove for local destination set to remove " @utils arg '--block-device' metavar='key1=value1[ key2=value2 ]' action='append' default=[] start version='2 32' help= "Block device mapping with the keys id=UUID image id snapshot id or volume id only if using source image snapshot or volume source=source type image snapshot volume or blank dest=destination type of the block device volume or local bus=device's bus e g uml lxc virtio if omitted hypervisor driver chooses a suitable default honoured only if device type is supplied type=device type e g disk cdrom defaults to 'disk' device=name of the device e g vda xda tag=device metadata tag optional if omitted hypervisor driver chooses suitable device depending on selected bus note the libvirt driver always uses default device names size=size of the block device in MB for swap and in GB for other formats if omitted hypervisor driver calculates size format=device will be formatted e g swap ntfs optional bootindex=integer used for ordering the boot disks for image backed instances it is equal to 0 for others need to be specified and shutdown=shutdown behaviour either preserve or remove for local destination set to remove " @utils arg '--swap' metavar='<swap size>' default=None help= 'Create and attach a local swap block device of <swap size> MB ' @utils arg '--ephemeral' metavar='size=<size>[ format=<format>]' action='append' default=[] help= 'Create and attach a local ephemeral block device of <size> GB and format it to <format> ' @utils arg '--hint' action='append' dest='scheduler hints' default=[] metavar='<key=value>' help= 'Send arbitrary key/value pairs to the scheduler for custom use ' @utils arg '--nic' metavar='<net-id=net-uuid net-name=network-name v4-fixed-ip=ip-addr v6-fixed-ip=ip-addr port-id=port-uuid>' action='append' dest='nics' default=[] start version='2 0' end version='2 31' help= 'Create a NIC on the server Specify option multiple times to create multiple NI Cs net-id attach NIC to network with this UUID net-name attach NIC to network with this name either port-id or net-id or net-name must be provided v4-fixed-ip I Pv4 fixed address for NIC optional v6-fixed-ip I Pv6 fixed address for NIC optional port-id attach NIC to port with this UUID either port-id or net-id must be provided ' @utils arg '--nic' metavar='<net-id=net-uuid net-name=network-name v4-fixed-ip=ip-addr v6-fixed-ip=ip-addr port-id=port-uuid>' action='append' dest='nics' default=[] start version='2 32' end version='2 36' help= 'Create a NIC on the server Specify option multiple times to create multiple nics net-id attach NIC to network with this UUID net-name attach NIC to network with this name either port-id or net-id or net-name must be provided v4-fixed-ip I Pv4 fixed address for NIC optional v6-fixed-ip I Pv6 fixed address for NIC optional port-id attach NIC to port with this UUID tag interface metadata tag optional either port-id or net-id must be provided ' @utils arg '--nic' metavar='<auto none net-id=net-uuid net-name=network-name port-id=port-uuid v4-fixed-ip=ip-addr v6-fixed-ip=ip-addr tag=tag>' action='append' dest='nics' default=[] start version='2 37' help= "Create a NIC on the server Specify option multiple times to create multiple nics unless using the special 'auto' or 'none' values auto automatically allocate network resources if none are available This cannot be specified with any other nic value and cannot be specified multiple times none do not attach a NIC at all This cannot be specified with any other nic value and cannot be specified multiple times net-id attach NIC to network with a specific UUID net-name attach NIC to network with this name either port-id or net-id or net-name must be provided v4-fixed-ip I Pv4 fixed address for NIC optional v6-fixed-ip I Pv6 fixed address for NIC optional port-id attach NIC to port with this UUID tag interface metadata tag optional either port-id or net-id must be provided " @utils arg '--config-drive' metavar='<value>' dest='config drive' default=False help= 'Enable config drive ' @utils arg '--poll' dest='poll' action='store true' default=False help= 'Report the new server boot progress until it completes ' @utils arg '--admin-pass' dest='admin pass' metavar='<value>' default=None help= 'Admin password for the instance ' @utils arg '--access-ip-v4' dest='access ip v4' metavar='<value>' default=None help= 'Alternative access I Pv4 of the instance ' @utils arg '--access-ip-v6' dest='access ip v6' metavar='<value>' default=None help= 'Alternative access I Pv6 of the instance ' @utils arg '--description' metavar='<description>' dest='description' default=None help= 'Description for the server ' start version='2 19' def do boot cs args boot args boot kwargs = boot cs args extra boot kwargs = utils get resource manager extra kwargs do boot args boot kwargs update extra boot kwargs server = cs servers create *boot args **boot kwargs print server cs args server if args poll poll for status cs servers get server id 'building' ['active']
6448
@utils.arg('--flavor', default=None, metavar='<flavor>', help=_("Name or ID of flavor (see 'nova flavor-list').")) @utils.arg('--image', default=None, metavar='<image>', help=_("Name or ID of image (see 'glance image-list'). ")) @utils.arg('--image-with', default=[], type=_key_value_pairing, action='append', metavar='<key=value>', help=_("Image metadata property (see 'glance image-show'). ")) @utils.arg('--boot-volume', default=None, metavar='<volume_id>', help=_('Volume ID to boot from.')) @utils.arg('--snapshot', default=None, metavar='<snapshot_id>', help=_('Snapshot ID to boot from (will create a volume).')) @utils.arg('--min-count', default=None, type=int, metavar='<number>', help=_('Boot at least <number> servers (limited by quota).')) @utils.arg('--max-count', default=None, type=int, metavar='<number>', help=_('Boot up to <number> servers (limited by quota).')) @utils.arg('--meta', metavar='<key=value>', action='append', default=[], help=_('Record arbitrary key/value metadata to /meta_data.json on the metadata server. Can be specified multiple times.')) @utils.arg('--file', metavar='<dst-path=src-path>', action='append', dest='files', default=[], help=_('Store arbitrary files from <src-path> locally to <dst-path> on the new server. Limited by the injected_files quota value.')) @utils.arg('--key-name', default=os.environ.get('NOVACLIENT_DEFAULT_KEY_NAME'), metavar='<key-name>', help=_('Key name of keypair that should be created earlier with the command keypair-add.')) @utils.arg('name', metavar='<name>', help=_('Name for the new server.')) @utils.arg('--user-data', default=None, metavar='<user-data>', help=_('user data file to pass to be exposed by the metadata server.')) @utils.arg('--availability-zone', default=None, metavar='<availability-zone>', help=_('The availability zone for server placement.')) @utils.arg('--security-groups', default=None, metavar='<security-groups>', help=_('Comma separated list of security group names.')) @utils.arg('--block-device-mapping', metavar='<dev-name=mapping>', action='append', default=[], help=_('Block device mapping in the format <dev-name>=<id>:<type>:<size(GB)>:<delete-on-terminate>.')) @utils.arg('--block-device', metavar='key1=value1[,key2=value2...]', action='append', default=[], start_version='2.0', end_version='2.31', help=_("Block device mapping with the keys: id=UUID (image_id, snapshot_id or volume_id only if using source image, snapshot or volume) source=source type (image, snapshot, volume or blank), dest=destination type of the block device (volume or local), bus=device's bus (e.g. uml, lxc, virtio, ...; if omitted, hypervisor driver chooses a suitable default, honoured only if device type is supplied) type=device type (e.g. disk, cdrom, ...; defaults to 'disk') device=name of the device (e.g. vda, xda, ...; if omitted, hypervisor driver chooses suitable device depending on selected bus; note the libvirt driver always uses default device names), size=size of the block device in MB(for swap) and in GB(for other formats) (if omitted, hypervisor driver calculates size), format=device will be formatted (e.g. swap, ntfs, ...; optional), bootindex=integer used for ordering the boot disks (for image backed instances it is equal to 0, for others need to be specified) and shutdown=shutdown behaviour (either preserve or remove, for local destination set to remove).")) @utils.arg('--block-device', metavar='key1=value1[,key2=value2...]', action='append', default=[], start_version='2.32', help=_("Block device mapping with the keys: id=UUID (image_id, snapshot_id or volume_id only if using source image, snapshot or volume) source=source type (image, snapshot, volume or blank), dest=destination type of the block device (volume or local), bus=device's bus (e.g. uml, lxc, virtio, ...; if omitted, hypervisor driver chooses a suitable default, honoured only if device type is supplied) type=device type (e.g. disk, cdrom, ...; defaults to 'disk') device=name of the device (e.g. vda, xda, ...; tag=device metadata tag (optional) if omitted, hypervisor driver chooses suitable device depending on selected bus; note the libvirt driver always uses default device names), size=size of the block device in MB(for swap) and in GB(for other formats) (if omitted, hypervisor driver calculates size), format=device will be formatted (e.g. swap, ntfs, ...; optional), bootindex=integer used for ordering the boot disks (for image backed instances it is equal to 0, for others need to be specified) and shutdown=shutdown behaviour (either preserve or remove, for local destination set to remove).")) @utils.arg('--swap', metavar='<swap_size>', default=None, help=_('Create and attach a local swap block device of <swap_size> MB.')) @utils.arg('--ephemeral', metavar='size=<size>[,format=<format>]', action='append', default=[], help=_('Create and attach a local ephemeral block device of <size> GB and format it to <format>.')) @utils.arg('--hint', action='append', dest='scheduler_hints', default=[], metavar='<key=value>', help=_('Send arbitrary key/value pairs to the scheduler for custom use.')) @utils.arg('--nic', metavar='<net-id=net-uuid,net-name=network-name,v4-fixed-ip=ip-addr,v6-fixed-ip=ip-addr,port-id=port-uuid>', action='append', dest='nics', default=[], start_version='2.0', end_version='2.31', help=_('Create a NIC on the server. Specify option multiple times to create multiple NICs. net-id: attach NIC to network with this UUID net-name: attach NIC to network with this name (either port-id or net-id or net-name must be provided), v4-fixed-ip: IPv4 fixed address for NIC (optional), v6-fixed-ip: IPv6 fixed address for NIC (optional), port-id: attach NIC to port with this UUID (either port-id or net-id must be provided).')) @utils.arg('--nic', metavar='<net-id=net-uuid,net-name=network-name,v4-fixed-ip=ip-addr,v6-fixed-ip=ip-addr,port-id=port-uuid>', action='append', dest='nics', default=[], start_version='2.32', end_version='2.36', help=_('Create a NIC on the server. Specify option multiple times to create multiple nics. net-id: attach NIC to network with this UUID net-name: attach NIC to network with this name (either port-id or net-id or net-name must be provided), v4-fixed-ip: IPv4 fixed address for NIC (optional), v6-fixed-ip: IPv6 fixed address for NIC (optional), port-id: attach NIC to port with this UUID tag: interface metadata tag (optional) (either port-id or net-id must be provided).')) @utils.arg('--nic', metavar='<auto,none,net-id=net-uuid,net-name=network-name,port-id=port-uuid,v4-fixed-ip=ip-addr,v6-fixed-ip=ip-addr,tag=tag>', action='append', dest='nics', default=[], start_version='2.37', help=_("Create a NIC on the server. Specify option multiple times to create multiple nics unless using the special 'auto' or 'none' values. auto: automatically allocate network resources if none are available. This cannot be specified with any other nic value and cannot be specified multiple times. none: do not attach a NIC at all. This cannot be specified with any other nic value and cannot be specified multiple times. net-id: attach NIC to network with a specific UUID. net-name: attach NIC to network with this name (either port-id or net-id or net-name must be provided), v4-fixed-ip: IPv4 fixed address for NIC (optional), v6-fixed-ip: IPv6 fixed address for NIC (optional), port-id: attach NIC to port with this UUID tag: interface metadata tag (optional) (either port-id or net-id must be provided).")) @utils.arg('--config-drive', metavar='<value>', dest='config_drive', default=False, help=_('Enable config drive.')) @utils.arg('--poll', dest='poll', action='store_true', default=False, help=_('Report the new server boot progress until it completes.')) @utils.arg('--admin-pass', dest='admin_pass', metavar='<value>', default=None, help=_('Admin password for the instance.')) @utils.arg('--access-ip-v4', dest='access_ip_v4', metavar='<value>', default=None, help=_('Alternative access IPv4 of the instance.')) @utils.arg('--access-ip-v6', dest='access_ip_v6', metavar='<value>', default=None, help=_('Alternative access IPv6 of the instance.')) @utils.arg('--description', metavar='<description>', dest='description', default=None, help=_('Description for the server.'), start_version='2.19') def do_boot(cs, args): (boot_args, boot_kwargs) = _boot(cs, args) extra_boot_kwargs = utils.get_resource_manager_extra_kwargs(do_boot, args) boot_kwargs.update(extra_boot_kwargs) server = cs.servers.create(*boot_args, **boot_kwargs) _print_server(cs, args, server) if args.poll: _poll_for_status(cs.servers.get, server.id, 'building', ['active'])
Boot a new server.
boot a new server .
Question: What does this function do? Code: @utils.arg('--flavor', default=None, metavar='<flavor>', help=_("Name or ID of flavor (see 'nova flavor-list').")) @utils.arg('--image', default=None, metavar='<image>', help=_("Name or ID of image (see 'glance image-list'). ")) @utils.arg('--image-with', default=[], type=_key_value_pairing, action='append', metavar='<key=value>', help=_("Image metadata property (see 'glance image-show'). ")) @utils.arg('--boot-volume', default=None, metavar='<volume_id>', help=_('Volume ID to boot from.')) @utils.arg('--snapshot', default=None, metavar='<snapshot_id>', help=_('Snapshot ID to boot from (will create a volume).')) @utils.arg('--min-count', default=None, type=int, metavar='<number>', help=_('Boot at least <number> servers (limited by quota).')) @utils.arg('--max-count', default=None, type=int, metavar='<number>', help=_('Boot up to <number> servers (limited by quota).')) @utils.arg('--meta', metavar='<key=value>', action='append', default=[], help=_('Record arbitrary key/value metadata to /meta_data.json on the metadata server. Can be specified multiple times.')) @utils.arg('--file', metavar='<dst-path=src-path>', action='append', dest='files', default=[], help=_('Store arbitrary files from <src-path> locally to <dst-path> on the new server. Limited by the injected_files quota value.')) @utils.arg('--key-name', default=os.environ.get('NOVACLIENT_DEFAULT_KEY_NAME'), metavar='<key-name>', help=_('Key name of keypair that should be created earlier with the command keypair-add.')) @utils.arg('name', metavar='<name>', help=_('Name for the new server.')) @utils.arg('--user-data', default=None, metavar='<user-data>', help=_('user data file to pass to be exposed by the metadata server.')) @utils.arg('--availability-zone', default=None, metavar='<availability-zone>', help=_('The availability zone for server placement.')) @utils.arg('--security-groups', default=None, metavar='<security-groups>', help=_('Comma separated list of security group names.')) @utils.arg('--block-device-mapping', metavar='<dev-name=mapping>', action='append', default=[], help=_('Block device mapping in the format <dev-name>=<id>:<type>:<size(GB)>:<delete-on-terminate>.')) @utils.arg('--block-device', metavar='key1=value1[,key2=value2...]', action='append', default=[], start_version='2.0', end_version='2.31', help=_("Block device mapping with the keys: id=UUID (image_id, snapshot_id or volume_id only if using source image, snapshot or volume) source=source type (image, snapshot, volume or blank), dest=destination type of the block device (volume or local), bus=device's bus (e.g. uml, lxc, virtio, ...; if omitted, hypervisor driver chooses a suitable default, honoured only if device type is supplied) type=device type (e.g. disk, cdrom, ...; defaults to 'disk') device=name of the device (e.g. vda, xda, ...; if omitted, hypervisor driver chooses suitable device depending on selected bus; note the libvirt driver always uses default device names), size=size of the block device in MB(for swap) and in GB(for other formats) (if omitted, hypervisor driver calculates size), format=device will be formatted (e.g. swap, ntfs, ...; optional), bootindex=integer used for ordering the boot disks (for image backed instances it is equal to 0, for others need to be specified) and shutdown=shutdown behaviour (either preserve or remove, for local destination set to remove).")) @utils.arg('--block-device', metavar='key1=value1[,key2=value2...]', action='append', default=[], start_version='2.32', help=_("Block device mapping with the keys: id=UUID (image_id, snapshot_id or volume_id only if using source image, snapshot or volume) source=source type (image, snapshot, volume or blank), dest=destination type of the block device (volume or local), bus=device's bus (e.g. uml, lxc, virtio, ...; if omitted, hypervisor driver chooses a suitable default, honoured only if device type is supplied) type=device type (e.g. disk, cdrom, ...; defaults to 'disk') device=name of the device (e.g. vda, xda, ...; tag=device metadata tag (optional) if omitted, hypervisor driver chooses suitable device depending on selected bus; note the libvirt driver always uses default device names), size=size of the block device in MB(for swap) and in GB(for other formats) (if omitted, hypervisor driver calculates size), format=device will be formatted (e.g. swap, ntfs, ...; optional), bootindex=integer used for ordering the boot disks (for image backed instances it is equal to 0, for others need to be specified) and shutdown=shutdown behaviour (either preserve or remove, for local destination set to remove).")) @utils.arg('--swap', metavar='<swap_size>', default=None, help=_('Create and attach a local swap block device of <swap_size> MB.')) @utils.arg('--ephemeral', metavar='size=<size>[,format=<format>]', action='append', default=[], help=_('Create and attach a local ephemeral block device of <size> GB and format it to <format>.')) @utils.arg('--hint', action='append', dest='scheduler_hints', default=[], metavar='<key=value>', help=_('Send arbitrary key/value pairs to the scheduler for custom use.')) @utils.arg('--nic', metavar='<net-id=net-uuid,net-name=network-name,v4-fixed-ip=ip-addr,v6-fixed-ip=ip-addr,port-id=port-uuid>', action='append', dest='nics', default=[], start_version='2.0', end_version='2.31', help=_('Create a NIC on the server. Specify option multiple times to create multiple NICs. net-id: attach NIC to network with this UUID net-name: attach NIC to network with this name (either port-id or net-id or net-name must be provided), v4-fixed-ip: IPv4 fixed address for NIC (optional), v6-fixed-ip: IPv6 fixed address for NIC (optional), port-id: attach NIC to port with this UUID (either port-id or net-id must be provided).')) @utils.arg('--nic', metavar='<net-id=net-uuid,net-name=network-name,v4-fixed-ip=ip-addr,v6-fixed-ip=ip-addr,port-id=port-uuid>', action='append', dest='nics', default=[], start_version='2.32', end_version='2.36', help=_('Create a NIC on the server. Specify option multiple times to create multiple nics. net-id: attach NIC to network with this UUID net-name: attach NIC to network with this name (either port-id or net-id or net-name must be provided), v4-fixed-ip: IPv4 fixed address for NIC (optional), v6-fixed-ip: IPv6 fixed address for NIC (optional), port-id: attach NIC to port with this UUID tag: interface metadata tag (optional) (either port-id or net-id must be provided).')) @utils.arg('--nic', metavar='<auto,none,net-id=net-uuid,net-name=network-name,port-id=port-uuid,v4-fixed-ip=ip-addr,v6-fixed-ip=ip-addr,tag=tag>', action='append', dest='nics', default=[], start_version='2.37', help=_("Create a NIC on the server. Specify option multiple times to create multiple nics unless using the special 'auto' or 'none' values. auto: automatically allocate network resources if none are available. This cannot be specified with any other nic value and cannot be specified multiple times. none: do not attach a NIC at all. This cannot be specified with any other nic value and cannot be specified multiple times. net-id: attach NIC to network with a specific UUID. net-name: attach NIC to network with this name (either port-id or net-id or net-name must be provided), v4-fixed-ip: IPv4 fixed address for NIC (optional), v6-fixed-ip: IPv6 fixed address for NIC (optional), port-id: attach NIC to port with this UUID tag: interface metadata tag (optional) (either port-id or net-id must be provided).")) @utils.arg('--config-drive', metavar='<value>', dest='config_drive', default=False, help=_('Enable config drive.')) @utils.arg('--poll', dest='poll', action='store_true', default=False, help=_('Report the new server boot progress until it completes.')) @utils.arg('--admin-pass', dest='admin_pass', metavar='<value>', default=None, help=_('Admin password for the instance.')) @utils.arg('--access-ip-v4', dest='access_ip_v4', metavar='<value>', default=None, help=_('Alternative access IPv4 of the instance.')) @utils.arg('--access-ip-v6', dest='access_ip_v6', metavar='<value>', default=None, help=_('Alternative access IPv6 of the instance.')) @utils.arg('--description', metavar='<description>', dest='description', default=None, help=_('Description for the server.'), start_version='2.19') def do_boot(cs, args): (boot_args, boot_kwargs) = _boot(cs, args) extra_boot_kwargs = utils.get_resource_manager_extra_kwargs(do_boot, args) boot_kwargs.update(extra_boot_kwargs) server = cs.servers.create(*boot_args, **boot_kwargs) _print_server(cs, args, server) if args.poll: _poll_for_status(cs.servers.get, server.id, 'building', ['active'])
null
null
null
What does this function do?
def beneficiary_type(): return s3_rest_controller()
null
null
null
Beneficiary Types: RESTful CRUD Controller
pcsd
def beneficiary type return s3 rest controller
6453
def beneficiary_type(): return s3_rest_controller()
Beneficiary Types: RESTful CRUD Controller
beneficiary types : restful crud controller
Question: What does this function do? Code: def beneficiary_type(): return s3_rest_controller()
null
null
null
What does this function do?
def show_image(kwargs, call=None): if (call != 'function'): raise SaltCloudSystemExit('The show_image action must be called with -f or --function.') params = {'ImageId.1': kwargs['image'], 'Action': 'DescribeImages'} result = aws.query(params, setname='tagSet', location=get_location(), provider=get_provider(), opts=__opts__, sigver='4') log.info(result) return result
null
null
null
Show the details from EC2 concerning an AMI
pcsd
def show image kwargs call=None if call != 'function' raise Salt Cloud System Exit 'The show image action must be called with -f or --function ' params = {'Image Id 1' kwargs['image'] 'Action' 'Describe Images'} result = aws query params setname='tag Set' location=get location provider=get provider opts= opts sigver='4' log info result return result
6455
def show_image(kwargs, call=None): if (call != 'function'): raise SaltCloudSystemExit('The show_image action must be called with -f or --function.') params = {'ImageId.1': kwargs['image'], 'Action': 'DescribeImages'} result = aws.query(params, setname='tagSet', location=get_location(), provider=get_provider(), opts=__opts__, sigver='4') log.info(result) return result
Show the details from EC2 concerning an AMI
show the details from ec2 concerning an ami
Question: What does this function do? Code: def show_image(kwargs, call=None): if (call != 'function'): raise SaltCloudSystemExit('The show_image action must be called with -f or --function.') params = {'ImageId.1': kwargs['image'], 'Action': 'DescribeImages'} result = aws.query(params, setname='tagSet', location=get_location(), provider=get_provider(), opts=__opts__, sigver='4') log.info(result) return result
null
null
null
What does this function do?
def block_device_mapping_destroy_by_instance_and_volume(context, instance_uuid, volume_id): return IMPL.block_device_mapping_destroy_by_instance_and_volume(context, instance_uuid, volume_id)
null
null
null
Destroy the block device mapping.
pcsd
def block device mapping destroy by instance and volume context instance uuid volume id return IMPL block device mapping destroy by instance and volume context instance uuid volume id
6457
def block_device_mapping_destroy_by_instance_and_volume(context, instance_uuid, volume_id): return IMPL.block_device_mapping_destroy_by_instance_and_volume(context, instance_uuid, volume_id)
Destroy the block device mapping.
destroy the block device mapping .
Question: What does this function do? Code: def block_device_mapping_destroy_by_instance_and_volume(context, instance_uuid, volume_id): return IMPL.block_device_mapping_destroy_by_instance_and_volume(context, instance_uuid, volume_id)
null
null
null
What does this function do?
def reformat_dict_keys(keymap=None, inputdict=None): keymap = (keymap or {}) inputdict = (inputdict or {}) return dict([(outk, inputdict[ink]) for (ink, outk) in keymap.items() if (ink in inputdict)])
null
null
null
Utility function for mapping one dict format to another.
pcsd
def reformat dict keys keymap=None inputdict=None keymap = keymap or {} inputdict = inputdict or {} return dict [ outk inputdict[ink] for ink outk in keymap items if ink in inputdict ]
6461
def reformat_dict_keys(keymap=None, inputdict=None): keymap = (keymap or {}) inputdict = (inputdict or {}) return dict([(outk, inputdict[ink]) for (ink, outk) in keymap.items() if (ink in inputdict)])
Utility function for mapping one dict format to another.
utility function for mapping one dict format to another .
Question: What does this function do? Code: def reformat_dict_keys(keymap=None, inputdict=None): keymap = (keymap or {}) inputdict = (inputdict or {}) return dict([(outk, inputdict[ink]) for (ink, outk) in keymap.items() if (ink in inputdict)])
null
null
null
What does this function do?
def validate_boxes(boxes, width=0, height=0): x1 = boxes[:, 0] y1 = boxes[:, 1] x2 = boxes[:, 2] y2 = boxes[:, 3] assert (x1 >= 0).all() assert (y1 >= 0).all() assert (x2 >= x1).all() assert (y2 >= y1).all() assert (x2 < width).all() assert (y2 < height).all()
null
null
null
Check that a set of boxes are valid.
pcsd
def validate boxes boxes width=0 height=0 x1 = boxes[ 0] y1 = boxes[ 1] x2 = boxes[ 2] y2 = boxes[ 3] assert x1 >= 0 all assert y1 >= 0 all assert x2 >= x1 all assert y2 >= y1 all assert x2 < width all assert y2 < height all
6466
def validate_boxes(boxes, width=0, height=0): x1 = boxes[:, 0] y1 = boxes[:, 1] x2 = boxes[:, 2] y2 = boxes[:, 3] assert (x1 >= 0).all() assert (y1 >= 0).all() assert (x2 >= x1).all() assert (y2 >= y1).all() assert (x2 < width).all() assert (y2 < height).all()
Check that a set of boxes are valid.
check that a set of boxes are valid .
Question: What does this function do? Code: def validate_boxes(boxes, width=0, height=0): x1 = boxes[:, 0] y1 = boxes[:, 1] x2 = boxes[:, 2] y2 = boxes[:, 3] assert (x1 >= 0).all() assert (y1 >= 0).all() assert (x2 >= x1).all() assert (y2 >= y1).all() assert (x2 < width).all() assert (y2 < height).all()
null
null
null
What does this function do?
def rename_blob(bucket_name, blob_name, new_name): storage_client = storage.Client() bucket = storage_client.get_bucket(bucket_name) blob = bucket.blob(blob_name) new_blob = bucket.rename_blob(blob, new_name) print 'Blob {} has been renamed to {}'.format(blob.name, new_blob.name)
null
null
null
Renames a blob.
pcsd
def rename blob bucket name blob name new name storage client = storage Client bucket = storage client get bucket bucket name blob = bucket blob blob name new blob = bucket rename blob blob new name print 'Blob {} has been renamed to {}' format blob name new blob name
6468
def rename_blob(bucket_name, blob_name, new_name): storage_client = storage.Client() bucket = storage_client.get_bucket(bucket_name) blob = bucket.blob(blob_name) new_blob = bucket.rename_blob(blob, new_name) print 'Blob {} has been renamed to {}'.format(blob.name, new_blob.name)
Renames a blob.
renames a blob .
Question: What does this function do? Code: def rename_blob(bucket_name, blob_name, new_name): storage_client = storage.Client() bucket = storage_client.get_bucket(bucket_name) blob = bucket.blob(blob_name) new_blob = bucket.rename_blob(blob, new_name) print 'Blob {} has been renamed to {}'.format(blob.name, new_blob.name)
null
null
null
What does this function do?
def render_to_response(template_name, context=None, context_instance=None, response_format='html'): if (context is None): context = {} if (not response_format): response_format = 'html' if (response_format not in settings.HARDTREE_RESPONSE_FORMATS): response_format = 'html' content_type = settings.HARDTREE_RESPONSE_FORMATS[response_format] if ('pdf' in response_format): while True: hasher = hashlib.md5() hasher.update(str(random.random())) filepath = (u'pdfs/' + hasher.hexdigest()) output = (settings.MEDIA_ROOT + filepath) if (not os.path.exists((output + '.pdf'))): break while True: hasher = hashlib.md5() hasher.update(str(random.random())) filepath = (hasher.hexdigest() + '.html') source = (getattr(settings, 'WKCWD', './') + filepath) if (not os.path.exists(source)): break page_size = 'A4' orientation = 'portrait' rendered_string = render_to_string(template_name, context, context_instance, response_format) f = codecs.open(source, encoding='utf-8', mode='w') pdf_string = unicode(rendered_string) if (context_instance and context_instance['request']): pdf_string = pdf_string.replace('a href="/', (('a href="http://' + RequestSite(context_instance['request']).domain) + '/')) pdf_string.replace('href="/', 'href="') pattern = 'Content-Type: text/html|<td>\n\\W*<div class="content-list-tick">\n\\W.*\n.*</div></td>|<th scope="col">Select</th>' pdf_string = re.sub(pattern, '', pdf_string).replace('/static/', 'static/') f.write(pdf_string) f.close() wkpath = getattr(settings, 'WKPATH', './bin/wkhtmltopdf-i386') x = subprocess.Popen(('%s --print-media-type --orientation %s --page-size %s %s %s' % (wkpath, orientation, page_size, source, output)), shell=True, cwd=getattr(settings, 'WKCWD', './')) x.wait() f = open(output) response = HttpResponse(f.read(), content_type='application/pdf') f.close() os.remove(output) os.remove(source) return response if ('ajax' in response_format): rendered_string = render_to_ajax(template_name, context, context_instance) else: if ((response_format == 'html') and context_instance and (context_instance['request'].path[:3] == '/m/')): context['response_format'] = response_format = 'mobile' if getattr(settings, 'HARDTREE_FORCE_AJAX_RENDERING', False): context = preprocess_context_ajax(context) rendered_string = render_to_string(template_name, context, context_instance, response_format) response = HttpResponse(rendered_string, content_type=content_type) return response
null
null
null
Extended render_to_response to support different formats
pcsd
def render to response template name context=None context instance=None response format='html' if context is None context = {} if not response format response format = 'html' if response format not in settings HARDTREE RESPONSE FORMATS response format = 'html' content type = settings HARDTREE RESPONSE FORMATS[response format] if 'pdf' in response format while True hasher = hashlib md5 hasher update str random random filepath = u'pdfs/' + hasher hexdigest output = settings MEDIA ROOT + filepath if not os path exists output + ' pdf' break while True hasher = hashlib md5 hasher update str random random filepath = hasher hexdigest + ' html' source = getattr settings 'WKCWD' ' /' + filepath if not os path exists source break page size = 'A4' orientation = 'portrait' rendered string = render to string template name context context instance response format f = codecs open source encoding='utf-8' mode='w' pdf string = unicode rendered string if context instance and context instance['request'] pdf string = pdf string replace 'a href="/' 'a href="http //' + Request Site context instance['request'] domain + '/' pdf string replace 'href="/' 'href="' pattern = 'Content-Type text/html|<td> \\W*<div class="content-list-tick"> \\W * *</div></td>|<th scope="col">Select</th>' pdf string = re sub pattern '' pdf string replace '/static/' 'static/' f write pdf string f close wkpath = getattr settings 'WKPATH' ' /bin/wkhtmltopdf-i386' x = subprocess Popen '%s --print-media-type --orientation %s --page-size %s %s %s' % wkpath orientation page size source output shell=True cwd=getattr settings 'WKCWD' ' /' x wait f = open output response = Http Response f read content type='application/pdf' f close os remove output os remove source return response if 'ajax' in response format rendered string = render to ajax template name context context instance else if response format == 'html' and context instance and context instance['request'] path[ 3] == '/m/' context['response format'] = response format = 'mobile' if getattr settings 'HARDTREE FORCE AJAX RENDERING' False context = preprocess context ajax context rendered string = render to string template name context context instance response format response = Http Response rendered string content type=content type return response
6473
def render_to_response(template_name, context=None, context_instance=None, response_format='html'): if (context is None): context = {} if (not response_format): response_format = 'html' if (response_format not in settings.HARDTREE_RESPONSE_FORMATS): response_format = 'html' content_type = settings.HARDTREE_RESPONSE_FORMATS[response_format] if ('pdf' in response_format): while True: hasher = hashlib.md5() hasher.update(str(random.random())) filepath = (u'pdfs/' + hasher.hexdigest()) output = (settings.MEDIA_ROOT + filepath) if (not os.path.exists((output + '.pdf'))): break while True: hasher = hashlib.md5() hasher.update(str(random.random())) filepath = (hasher.hexdigest() + '.html') source = (getattr(settings, 'WKCWD', './') + filepath) if (not os.path.exists(source)): break page_size = 'A4' orientation = 'portrait' rendered_string = render_to_string(template_name, context, context_instance, response_format) f = codecs.open(source, encoding='utf-8', mode='w') pdf_string = unicode(rendered_string) if (context_instance and context_instance['request']): pdf_string = pdf_string.replace('a href="/', (('a href="http://' + RequestSite(context_instance['request']).domain) + '/')) pdf_string.replace('href="/', 'href="') pattern = 'Content-Type: text/html|<td>\n\\W*<div class="content-list-tick">\n\\W.*\n.*</div></td>|<th scope="col">Select</th>' pdf_string = re.sub(pattern, '', pdf_string).replace('/static/', 'static/') f.write(pdf_string) f.close() wkpath = getattr(settings, 'WKPATH', './bin/wkhtmltopdf-i386') x = subprocess.Popen(('%s --print-media-type --orientation %s --page-size %s %s %s' % (wkpath, orientation, page_size, source, output)), shell=True, cwd=getattr(settings, 'WKCWD', './')) x.wait() f = open(output) response = HttpResponse(f.read(), content_type='application/pdf') f.close() os.remove(output) os.remove(source) return response if ('ajax' in response_format): rendered_string = render_to_ajax(template_name, context, context_instance) else: if ((response_format == 'html') and context_instance and (context_instance['request'].path[:3] == '/m/')): context['response_format'] = response_format = 'mobile' if getattr(settings, 'HARDTREE_FORCE_AJAX_RENDERING', False): context = preprocess_context_ajax(context) rendered_string = render_to_string(template_name, context, context_instance, response_format) response = HttpResponse(rendered_string, content_type=content_type) return response
Extended render_to_response to support different formats
extended render _ to _ response to support different formats
Question: What does this function do? Code: def render_to_response(template_name, context=None, context_instance=None, response_format='html'): if (context is None): context = {} if (not response_format): response_format = 'html' if (response_format not in settings.HARDTREE_RESPONSE_FORMATS): response_format = 'html' content_type = settings.HARDTREE_RESPONSE_FORMATS[response_format] if ('pdf' in response_format): while True: hasher = hashlib.md5() hasher.update(str(random.random())) filepath = (u'pdfs/' + hasher.hexdigest()) output = (settings.MEDIA_ROOT + filepath) if (not os.path.exists((output + '.pdf'))): break while True: hasher = hashlib.md5() hasher.update(str(random.random())) filepath = (hasher.hexdigest() + '.html') source = (getattr(settings, 'WKCWD', './') + filepath) if (not os.path.exists(source)): break page_size = 'A4' orientation = 'portrait' rendered_string = render_to_string(template_name, context, context_instance, response_format) f = codecs.open(source, encoding='utf-8', mode='w') pdf_string = unicode(rendered_string) if (context_instance and context_instance['request']): pdf_string = pdf_string.replace('a href="/', (('a href="http://' + RequestSite(context_instance['request']).domain) + '/')) pdf_string.replace('href="/', 'href="') pattern = 'Content-Type: text/html|<td>\n\\W*<div class="content-list-tick">\n\\W.*\n.*</div></td>|<th scope="col">Select</th>' pdf_string = re.sub(pattern, '', pdf_string).replace('/static/', 'static/') f.write(pdf_string) f.close() wkpath = getattr(settings, 'WKPATH', './bin/wkhtmltopdf-i386') x = subprocess.Popen(('%s --print-media-type --orientation %s --page-size %s %s %s' % (wkpath, orientation, page_size, source, output)), shell=True, cwd=getattr(settings, 'WKCWD', './')) x.wait() f = open(output) response = HttpResponse(f.read(), content_type='application/pdf') f.close() os.remove(output) os.remove(source) return response if ('ajax' in response_format): rendered_string = render_to_ajax(template_name, context, context_instance) else: if ((response_format == 'html') and context_instance and (context_instance['request'].path[:3] == '/m/')): context['response_format'] = response_format = 'mobile' if getattr(settings, 'HARDTREE_FORCE_AJAX_RENDERING', False): context = preprocess_context_ajax(context) rendered_string = render_to_string(template_name, context, context_instance, response_format) response = HttpResponse(rendered_string, content_type=content_type) return response
null
null
null
What does this function do?
def PassphraseCallback(verify=False, prompt1='Enter passphrase:', prompt2='Verify passphrase:'): while 1: try: p1 = getpass.getpass(prompt1) if verify: p2 = getpass.getpass(prompt2) if (p1 == p2): break else: break except KeyboardInterrupt: return None return p1
null
null
null
A utility function to read a passphrase from stdin.
pcsd
def Passphrase Callback verify=False prompt1='Enter passphrase ' prompt2='Verify passphrase ' while 1 try p1 = getpass getpass prompt1 if verify p2 = getpass getpass prompt2 if p1 == p2 break else break except Keyboard Interrupt return None return p1
6477
def PassphraseCallback(verify=False, prompt1='Enter passphrase:', prompt2='Verify passphrase:'): while 1: try: p1 = getpass.getpass(prompt1) if verify: p2 = getpass.getpass(prompt2) if (p1 == p2): break else: break except KeyboardInterrupt: return None return p1
A utility function to read a passphrase from stdin.
a utility function to read a passphrase from stdin .
Question: What does this function do? Code: def PassphraseCallback(verify=False, prompt1='Enter passphrase:', prompt2='Verify passphrase:'): while 1: try: p1 = getpass.getpass(prompt1) if verify: p2 = getpass.getpass(prompt2) if (p1 == p2): break else: break except KeyboardInterrupt: return None return p1