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 signed(content, private_key_name='signing.key'):
command = ['openssl', 'dgst', '-sha256', '-sign', join(tests_dir(), private_key_name)]
(out, err) = out_and_err(command, input=content)
return out
| null | null | null | Return the signed SHA-256 hash of ``content``, using the given key file. | pcsd | def signed content private key name='signing key' command = ['openssl' 'dgst' '-sha256' '-sign' join tests dir private key name ] out err = out and err command input=content return out | 13658 | def signed(content, private_key_name='signing.key'):
command = ['openssl', 'dgst', '-sha256', '-sign', join(tests_dir(), private_key_name)]
(out, err) = out_and_err(command, input=content)
return out
| Return the signed SHA-256 hash of ``content``, using the given key file. | return the signed sha - 256 hash of content , using the given key file . | Question:
What does this function do?
Code:
def signed(content, private_key_name='signing.key'):
command = ['openssl', 'dgst', '-sha256', '-sign', join(tests_dir(), private_key_name)]
(out, err) = out_and_err(command, input=content)
return out
|
null | null | null | What does this function do? | def _safe_log(log_func, msg, msg_data):
SANITIZE = {'set_admin_password': [('args', 'new_pass')], 'run_instance': [('args', 'admin_password')], 'route_message': [('args', 'message', 'args', 'method_info', 'method_kwargs', 'password'), ('args', 'message', 'args', 'method_info', 'method_kwargs', 'admin_password')]}
has_method = (('method' in msg_data) and (msg_data['method'] in SANITIZE))
has_context_token = ('_context_auth_token' in msg_data)
has_token = ('auth_token' in msg_data)
if (not any([has_method, has_context_token, has_token])):
return log_func(msg, msg_data)
msg_data = copy.deepcopy(msg_data)
if has_method:
for arg in SANITIZE.get(msg_data['method'], []):
try:
d = msg_data
for elem in arg[:(-1)]:
d = d[elem]
d[arg[(-1)]] = '<SANITIZED>'
except KeyError as e:
LOG.info(_('Failed to sanitize %(item)s. Key error %(err)s'), {'item': arg, 'err': e})
if has_context_token:
msg_data['_context_auth_token'] = '<SANITIZED>'
if has_token:
msg_data['auth_token'] = '<SANITIZED>'
return log_func(msg, msg_data)
| null | null | null | Sanitizes the msg_data field before logging. | pcsd | def safe log log func msg msg data SANITIZE = {'set admin password' [ 'args' 'new pass' ] 'run instance' [ 'args' 'admin password' ] 'route message' [ 'args' 'message' 'args' 'method info' 'method kwargs' 'password' 'args' 'message' 'args' 'method info' 'method kwargs' 'admin password' ]} has method = 'method' in msg data and msg data['method'] in SANITIZE has context token = ' context auth token' in msg data has token = 'auth token' in msg data if not any [has method has context token has token] return log func msg msg data msg data = copy deepcopy msg data if has method for arg in SANITIZE get msg data['method'] [] try d = msg data for elem in arg[ -1 ] d = d[elem] d[arg[ -1 ]] = '<SANITIZED>' except Key Error as e LOG info 'Failed to sanitize % item s Key error % err s' {'item' arg 'err' e} if has context token msg data[' context auth token'] = '<SANITIZED>' if has token msg data['auth token'] = '<SANITIZED>' return log func msg msg data | 13666 | def _safe_log(log_func, msg, msg_data):
SANITIZE = {'set_admin_password': [('args', 'new_pass')], 'run_instance': [('args', 'admin_password')], 'route_message': [('args', 'message', 'args', 'method_info', 'method_kwargs', 'password'), ('args', 'message', 'args', 'method_info', 'method_kwargs', 'admin_password')]}
has_method = (('method' in msg_data) and (msg_data['method'] in SANITIZE))
has_context_token = ('_context_auth_token' in msg_data)
has_token = ('auth_token' in msg_data)
if (not any([has_method, has_context_token, has_token])):
return log_func(msg, msg_data)
msg_data = copy.deepcopy(msg_data)
if has_method:
for arg in SANITIZE.get(msg_data['method'], []):
try:
d = msg_data
for elem in arg[:(-1)]:
d = d[elem]
d[arg[(-1)]] = '<SANITIZED>'
except KeyError as e:
LOG.info(_('Failed to sanitize %(item)s. Key error %(err)s'), {'item': arg, 'err': e})
if has_context_token:
msg_data['_context_auth_token'] = '<SANITIZED>'
if has_token:
msg_data['auth_token'] = '<SANITIZED>'
return log_func(msg, msg_data)
| Sanitizes the msg_data field before logging. | sanitizes the msg _ data field before logging . | Question:
What does this function do?
Code:
def _safe_log(log_func, msg, msg_data):
SANITIZE = {'set_admin_password': [('args', 'new_pass')], 'run_instance': [('args', 'admin_password')], 'route_message': [('args', 'message', 'args', 'method_info', 'method_kwargs', 'password'), ('args', 'message', 'args', 'method_info', 'method_kwargs', 'admin_password')]}
has_method = (('method' in msg_data) and (msg_data['method'] in SANITIZE))
has_context_token = ('_context_auth_token' in msg_data)
has_token = ('auth_token' in msg_data)
if (not any([has_method, has_context_token, has_token])):
return log_func(msg, msg_data)
msg_data = copy.deepcopy(msg_data)
if has_method:
for arg in SANITIZE.get(msg_data['method'], []):
try:
d = msg_data
for elem in arg[:(-1)]:
d = d[elem]
d[arg[(-1)]] = '<SANITIZED>'
except KeyError as e:
LOG.info(_('Failed to sanitize %(item)s. Key error %(err)s'), {'item': arg, 'err': e})
if has_context_token:
msg_data['_context_auth_token'] = '<SANITIZED>'
if has_token:
msg_data['auth_token'] = '<SANITIZED>'
return log_func(msg, msg_data)
|
null | null | null | What does this function do? | @with_setup(prepare_stdout)
def test_output_when_could_not_find_features():
path = fs.relpath(join(abspath(dirname(__file__)), 'no_features', 'unexistent-folder'))
runner = Runner(path, verbosity=3, no_color=False)
runner.run()
assert_stdout_lines(('\x1b[1;31mOops!\x1b[0m\n\x1b[1;37mcould not find features at \x1b[1;33m./%s\x1b[0m\n' % path))
| null | null | null | Testing the colorful output of many successful features | pcsd | @with setup prepare stdout def test output when could not find features path = fs relpath join abspath dirname file 'no features' 'unexistent-folder' runner = Runner path verbosity=3 no color=False runner run assert stdout lines '\x1b[1 31m Oops!\x1b[0m \x1b[1 37mcould not find features at \x1b[1 33m /%s\x1b[0m ' % path | 13668 | @with_setup(prepare_stdout)
def test_output_when_could_not_find_features():
path = fs.relpath(join(abspath(dirname(__file__)), 'no_features', 'unexistent-folder'))
runner = Runner(path, verbosity=3, no_color=False)
runner.run()
assert_stdout_lines(('\x1b[1;31mOops!\x1b[0m\n\x1b[1;37mcould not find features at \x1b[1;33m./%s\x1b[0m\n' % path))
| Testing the colorful output of many successful features | testing the colorful output of many successful features | Question:
What does this function do?
Code:
@with_setup(prepare_stdout)
def test_output_when_could_not_find_features():
path = fs.relpath(join(abspath(dirname(__file__)), 'no_features', 'unexistent-folder'))
runner = Runner(path, verbosity=3, no_color=False)
runner.run()
assert_stdout_lines(('\x1b[1;31mOops!\x1b[0m\n\x1b[1;37mcould not find features at \x1b[1;33m./%s\x1b[0m\n' % path))
|
null | null | null | What does this function do? | def dot(inp, matrix):
if (('int' in inp.dtype) and (inp.ndim == 2)):
return matrix[inp.flatten()]
elif ('int' in inp.dtype):
return matrix[inp]
elif (('float' in inp.dtype) and (inp.ndim == 3)):
shape0 = inp.shape[0]
shape1 = inp.shape[1]
shape2 = inp.shape[2]
return TT.dot(inp.reshape(((shape0 * shape1), shape2)), matrix)
else:
return TT.dot(inp, matrix)
| null | null | null | Decide the right type of dot product depending on the input
arguments | pcsd | def dot inp matrix if 'int' in inp dtype and inp ndim == 2 return matrix[inp flatten ] elif 'int' in inp dtype return matrix[inp] elif 'float' in inp dtype and inp ndim == 3 shape0 = inp shape[0] shape1 = inp shape[1] shape2 = inp shape[2] return TT dot inp reshape shape0 * shape1 shape2 matrix else return TT dot inp matrix | 13670 | def dot(inp, matrix):
if (('int' in inp.dtype) and (inp.ndim == 2)):
return matrix[inp.flatten()]
elif ('int' in inp.dtype):
return matrix[inp]
elif (('float' in inp.dtype) and (inp.ndim == 3)):
shape0 = inp.shape[0]
shape1 = inp.shape[1]
shape2 = inp.shape[2]
return TT.dot(inp.reshape(((shape0 * shape1), shape2)), matrix)
else:
return TT.dot(inp, matrix)
| Decide the right type of dot product depending on the input
arguments | decide the right type of dot product depending on the input arguments | Question:
What does this function do?
Code:
def dot(inp, matrix):
if (('int' in inp.dtype) and (inp.ndim == 2)):
return matrix[inp.flatten()]
elif ('int' in inp.dtype):
return matrix[inp]
elif (('float' in inp.dtype) and (inp.ndim == 3)):
shape0 = inp.shape[0]
shape1 = inp.shape[1]
shape2 = inp.shape[2]
return TT.dot(inp.reshape(((shape0 * shape1), shape2)), matrix)
else:
return TT.dot(inp, matrix)
|
null | null | null | What does this function do? | def _insert_object_resp(bucket=None, name=None, data=None):
assert (type(data) is bytes)
hasher = hashlib.md5()
hasher.update(data)
md5_hex_hash = hasher.hexdigest()
return {u'bucket': bucket, u'name': name, u'md5Hash': _hex_to_base64(md5_hex_hash), u'timeCreated': _datetime_to_gcptime(), u'size': str(len(data)), u'_data': data}
| null | null | null | Fake GCS object metadata | pcsd | def insert object resp bucket=None name=None data=None assert type data is bytes hasher = hashlib md5 hasher update data md5 hex hash = hasher hexdigest return {u'bucket' bucket u'name' name u'md5Hash' hex to base64 md5 hex hash u'time Created' datetime to gcptime u'size' str len data u' data' data} | 13676 | def _insert_object_resp(bucket=None, name=None, data=None):
assert (type(data) is bytes)
hasher = hashlib.md5()
hasher.update(data)
md5_hex_hash = hasher.hexdigest()
return {u'bucket': bucket, u'name': name, u'md5Hash': _hex_to_base64(md5_hex_hash), u'timeCreated': _datetime_to_gcptime(), u'size': str(len(data)), u'_data': data}
| Fake GCS object metadata | fake gcs object metadata | Question:
What does this function do?
Code:
def _insert_object_resp(bucket=None, name=None, data=None):
assert (type(data) is bytes)
hasher = hashlib.md5()
hasher.update(data)
md5_hex_hash = hasher.hexdigest()
return {u'bucket': bucket, u'name': name, u'md5Hash': _hex_to_base64(md5_hex_hash), u'timeCreated': _datetime_to_gcptime(), u'size': str(len(data)), u'_data': data}
|
null | null | null | What does this function do? | def create_xml_attributes(module, xml):
xml_attrs = {}
for (attr, val) in xml.attrib.iteritems():
if (attr not in module.fields):
if (attr == 'parent_sequential_url'):
attr = 'parent_url'
xml_attrs[attr] = val
module.xml_attributes = xml_attrs
| null | null | null | Make up for modules which don\'t define xml_attributes by creating them here and populating | pcsd | def create xml attributes module xml xml attrs = {} for attr val in xml attrib iteritems if attr not in module fields if attr == 'parent sequential url' attr = 'parent url' xml attrs[attr] = val module xml attributes = xml attrs | 13677 | def create_xml_attributes(module, xml):
xml_attrs = {}
for (attr, val) in xml.attrib.iteritems():
if (attr not in module.fields):
if (attr == 'parent_sequential_url'):
attr = 'parent_url'
xml_attrs[attr] = val
module.xml_attributes = xml_attrs
| Make up for modules which don\'t define xml_attributes by creating them here and populating | make up for modules which dont define xml _ attributes by creating them here and populating | Question:
What does this function do?
Code:
def create_xml_attributes(module, xml):
xml_attrs = {}
for (attr, val) in xml.attrib.iteritems():
if (attr not in module.fields):
if (attr == 'parent_sequential_url'):
attr = 'parent_url'
xml_attrs[attr] = val
module.xml_attributes = xml_attrs
|
null | null | null | What does this function do? | @commands(u'tld')
@example(u'.tld ru')
def gettld(bot, trigger):
page = web.get(uri)
tld = trigger.group(2)
if (tld[0] == u'.'):
tld = tld[1:]
search = u'(?i)<td><a href="\\S+" title="\\S+">\\.{0}</a></td>\\n(<td><a href=".*</a></td>\\n)?<td>([A-Za-z0-9].*?)</td>\\n<td>(.*)</td>\\n<td[^>]*>(.*?)</td>\\n<td[^>]*>(.*?)</td>\\n'
search = search.format(tld)
re_country = re.compile(search)
matches = re_country.findall(page)
if (not matches):
search = u'(?i)<td><a href="\\S+" title="(\\S+)">\\.{0}</a></td>\\n<td><a href=".*">(.*)</a></td>\\n<td>([A-Za-z0-9].*?)</td>\\n<td[^>]*>(.*?)</td>\\n<td[^>]*>(.*?)</td>\\n'
search = search.format(tld)
re_country = re.compile(search)
matches = re_country.findall(page)
if matches:
matches = list(matches[0])
i = 0
while (i < len(matches)):
matches[i] = r_tag.sub(u'', matches[i])
i += 1
desc = matches[2]
if (len(desc) > 400):
desc = (desc[:400] + u'...')
reply = (u'%s -- %s. IDN: %s, DNSSEC: %s' % (matches[1], desc, matches[3], matches[4]))
bot.reply(reply)
else:
search = u'<td><a href="\\S+" title="\\S+">.{0}</a></td>\\n<td><span class="flagicon"><img.*?\\">(.*?)</a></td>\\n<td[^>]*>(.*?)</td>\\n<td[^>]*>(.*?)</td>\\n<td[^>]*>(.*?)</td>\\n<td[^>]*>(.*?)</td>\\n<td[^>]*>(.*?)</td>\\n'
search = search.format(unicode(tld))
re_country = re.compile(search)
matches = re_country.findall(page)
if matches:
matches = matches[0]
dict_val = dict()
(dict_val[u'country'], dict_val[u'expl'], dict_val[u'notes'], dict_val[u'idn'], dict_val[u'dnssec'], dict_val[u'sld']) = matches
for key in dict_val:
if (dict_val[key] == u' '):
dict_val[key] = u'N/A'
dict_val[key] = r_tag.sub(u'', dict_val[key])
if (len(dict_val[u'notes']) > 400):
dict_val[u'notes'] = (dict_val[u'notes'][:400] + u'...')
reply = (u'%s (%s, %s). IDN: %s, DNSSEC: %s, SLD: %s' % (dict_val[u'country'], dict_val[u'expl'], dict_val[u'notes'], dict_val[u'idn'], dict_val[u'dnssec'], dict_val[u'sld']))
else:
reply = u'No matches found for TLD: {0}'.format(unicode(tld))
bot.reply(reply)
| null | null | null | Show information about the given Top Level Domain. | pcsd | @commands u'tld' @example u' tld ru' def gettld bot trigger page = web get uri tld = trigger group 2 if tld[0] == u' ' tld = tld[1 ] search = u' ?i <td><a href="\\S+" title="\\S+">\\ {0}</a></td>\ <td><a href=" *</a></td>\ ?<td> [A-Za-z0-9] *? </td>\ <td> * </td>\ <td[^>]*> *? </td>\ <td[^>]*> *? </td>\ ' search = search format tld re country = re compile search matches = re country findall page if not matches search = u' ?i <td><a href="\\S+" title=" \\S+ ">\\ {0}</a></td>\ <td><a href=" *"> * </a></td>\ <td> [A-Za-z0-9] *? </td>\ <td[^>]*> *? </td>\ <td[^>]*> *? </td>\ ' search = search format tld re country = re compile search matches = re country findall page if matches matches = list matches[0] i = 0 while i < len matches matches[i] = r tag sub u'' matches[i] i += 1 desc = matches[2] if len desc > 400 desc = desc[ 400] + u' ' reply = u'%s -- %s IDN %s DNSSEC %s' % matches[1] desc matches[3] matches[4] bot reply reply else search = u'<td><a href="\\S+" title="\\S+"> {0}</a></td>\ <td><span class="flagicon"><img *?\\"> *? </a></td>\ <td[^>]*> *? </td>\ <td[^>]*> *? </td>\ <td[^>]*> *? </td>\ <td[^>]*> *? </td>\ <td[^>]*> *? </td>\ ' search = search format unicode tld re country = re compile search matches = re country findall page if matches matches = matches[0] dict val = dict dict val[u'country'] dict val[u'expl'] dict val[u'notes'] dict val[u'idn'] dict val[u'dnssec'] dict val[u'sld'] = matches for key in dict val if dict val[key] == u'  ' dict val[key] = u'N/A' dict val[key] = r tag sub u'' dict val[key] if len dict val[u'notes'] > 400 dict val[u'notes'] = dict val[u'notes'][ 400] + u' ' reply = u'%s %s %s IDN %s DNSSEC %s SLD %s' % dict val[u'country'] dict val[u'expl'] dict val[u'notes'] dict val[u'idn'] dict val[u'dnssec'] dict val[u'sld'] else reply = u'No matches found for TLD {0}' format unicode tld bot reply reply | 13681 | @commands(u'tld')
@example(u'.tld ru')
def gettld(bot, trigger):
page = web.get(uri)
tld = trigger.group(2)
if (tld[0] == u'.'):
tld = tld[1:]
search = u'(?i)<td><a href="\\S+" title="\\S+">\\.{0}</a></td>\\n(<td><a href=".*</a></td>\\n)?<td>([A-Za-z0-9].*?)</td>\\n<td>(.*)</td>\\n<td[^>]*>(.*?)</td>\\n<td[^>]*>(.*?)</td>\\n'
search = search.format(tld)
re_country = re.compile(search)
matches = re_country.findall(page)
if (not matches):
search = u'(?i)<td><a href="\\S+" title="(\\S+)">\\.{0}</a></td>\\n<td><a href=".*">(.*)</a></td>\\n<td>([A-Za-z0-9].*?)</td>\\n<td[^>]*>(.*?)</td>\\n<td[^>]*>(.*?)</td>\\n'
search = search.format(tld)
re_country = re.compile(search)
matches = re_country.findall(page)
if matches:
matches = list(matches[0])
i = 0
while (i < len(matches)):
matches[i] = r_tag.sub(u'', matches[i])
i += 1
desc = matches[2]
if (len(desc) > 400):
desc = (desc[:400] + u'...')
reply = (u'%s -- %s. IDN: %s, DNSSEC: %s' % (matches[1], desc, matches[3], matches[4]))
bot.reply(reply)
else:
search = u'<td><a href="\\S+" title="\\S+">.{0}</a></td>\\n<td><span class="flagicon"><img.*?\\">(.*?)</a></td>\\n<td[^>]*>(.*?)</td>\\n<td[^>]*>(.*?)</td>\\n<td[^>]*>(.*?)</td>\\n<td[^>]*>(.*?)</td>\\n<td[^>]*>(.*?)</td>\\n'
search = search.format(unicode(tld))
re_country = re.compile(search)
matches = re_country.findall(page)
if matches:
matches = matches[0]
dict_val = dict()
(dict_val[u'country'], dict_val[u'expl'], dict_val[u'notes'], dict_val[u'idn'], dict_val[u'dnssec'], dict_val[u'sld']) = matches
for key in dict_val:
if (dict_val[key] == u' '):
dict_val[key] = u'N/A'
dict_val[key] = r_tag.sub(u'', dict_val[key])
if (len(dict_val[u'notes']) > 400):
dict_val[u'notes'] = (dict_val[u'notes'][:400] + u'...')
reply = (u'%s (%s, %s). IDN: %s, DNSSEC: %s, SLD: %s' % (dict_val[u'country'], dict_val[u'expl'], dict_val[u'notes'], dict_val[u'idn'], dict_val[u'dnssec'], dict_val[u'sld']))
else:
reply = u'No matches found for TLD: {0}'.format(unicode(tld))
bot.reply(reply)
| Show information about the given Top Level Domain. | show information about the given top level domain . | Question:
What does this function do?
Code:
@commands(u'tld')
@example(u'.tld ru')
def gettld(bot, trigger):
page = web.get(uri)
tld = trigger.group(2)
if (tld[0] == u'.'):
tld = tld[1:]
search = u'(?i)<td><a href="\\S+" title="\\S+">\\.{0}</a></td>\\n(<td><a href=".*</a></td>\\n)?<td>([A-Za-z0-9].*?)</td>\\n<td>(.*)</td>\\n<td[^>]*>(.*?)</td>\\n<td[^>]*>(.*?)</td>\\n'
search = search.format(tld)
re_country = re.compile(search)
matches = re_country.findall(page)
if (not matches):
search = u'(?i)<td><a href="\\S+" title="(\\S+)">\\.{0}</a></td>\\n<td><a href=".*">(.*)</a></td>\\n<td>([A-Za-z0-9].*?)</td>\\n<td[^>]*>(.*?)</td>\\n<td[^>]*>(.*?)</td>\\n'
search = search.format(tld)
re_country = re.compile(search)
matches = re_country.findall(page)
if matches:
matches = list(matches[0])
i = 0
while (i < len(matches)):
matches[i] = r_tag.sub(u'', matches[i])
i += 1
desc = matches[2]
if (len(desc) > 400):
desc = (desc[:400] + u'...')
reply = (u'%s -- %s. IDN: %s, DNSSEC: %s' % (matches[1], desc, matches[3], matches[4]))
bot.reply(reply)
else:
search = u'<td><a href="\\S+" title="\\S+">.{0}</a></td>\\n<td><span class="flagicon"><img.*?\\">(.*?)</a></td>\\n<td[^>]*>(.*?)</td>\\n<td[^>]*>(.*?)</td>\\n<td[^>]*>(.*?)</td>\\n<td[^>]*>(.*?)</td>\\n<td[^>]*>(.*?)</td>\\n'
search = search.format(unicode(tld))
re_country = re.compile(search)
matches = re_country.findall(page)
if matches:
matches = matches[0]
dict_val = dict()
(dict_val[u'country'], dict_val[u'expl'], dict_val[u'notes'], dict_val[u'idn'], dict_val[u'dnssec'], dict_val[u'sld']) = matches
for key in dict_val:
if (dict_val[key] == u' '):
dict_val[key] = u'N/A'
dict_val[key] = r_tag.sub(u'', dict_val[key])
if (len(dict_val[u'notes']) > 400):
dict_val[u'notes'] = (dict_val[u'notes'][:400] + u'...')
reply = (u'%s (%s, %s). IDN: %s, DNSSEC: %s, SLD: %s' % (dict_val[u'country'], dict_val[u'expl'], dict_val[u'notes'], dict_val[u'idn'], dict_val[u'dnssec'], dict_val[u'sld']))
else:
reply = u'No matches found for TLD: {0}'.format(unicode(tld))
bot.reply(reply)
|
null | null | null | What does this function do? | def disabled(name='allprofiles'):
ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''}
action = False
check_name = None
if (name != 'allprofiles'):
check_name = True
current_config = __salt__['firewall.get_config']()
if (check_name and (name not in current_config)):
ret['result'] = False
ret['comment'] = 'Profile {0} does not exist in firewall.get_config'.format(name)
return ret
for key in current_config:
if current_config[key]:
if (check_name and (key != name)):
continue
action = True
ret['changes'] = {'fw': 'disabled'}
break
if __opts__['test']:
ret['result'] = ((not action) or None)
return ret
if action:
ret['result'] = __salt__['firewall.disable'](name)
if (not ret['result']):
ret['comment'] = 'Could not disable the FW'
if check_name:
msg = 'Firewall profile {0} could not be disabled'.format(name)
else:
msg = 'Could not disable the FW'
ret['comment'] = msg
else:
if check_name:
msg = 'Firewall profile {0} is disabled'.format(name)
else:
msg = 'All the firewall profiles are disabled'
ret['comment'] = msg
return ret
| null | null | null | Disable all the firewall profiles (Windows only) | pcsd | def disabled name='allprofiles' ret = {'name' name 'result' True 'changes' {} 'comment' ''} action = False check name = None if name != 'allprofiles' check name = True current config = salt ['firewall get config'] if check name and name not in current config ret['result'] = False ret['comment'] = 'Profile {0} does not exist in firewall get config' format name return ret for key in current config if current config[key] if check name and key != name continue action = True ret['changes'] = {'fw' 'disabled'} break if opts ['test'] ret['result'] = not action or None return ret if action ret['result'] = salt ['firewall disable'] name if not ret['result'] ret['comment'] = 'Could not disable the FW' if check name msg = 'Firewall profile {0} could not be disabled' format name else msg = 'Could not disable the FW' ret['comment'] = msg else if check name msg = 'Firewall profile {0} is disabled' format name else msg = 'All the firewall profiles are disabled' ret['comment'] = msg return ret | 13698 | def disabled(name='allprofiles'):
ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''}
action = False
check_name = None
if (name != 'allprofiles'):
check_name = True
current_config = __salt__['firewall.get_config']()
if (check_name and (name not in current_config)):
ret['result'] = False
ret['comment'] = 'Profile {0} does not exist in firewall.get_config'.format(name)
return ret
for key in current_config:
if current_config[key]:
if (check_name and (key != name)):
continue
action = True
ret['changes'] = {'fw': 'disabled'}
break
if __opts__['test']:
ret['result'] = ((not action) or None)
return ret
if action:
ret['result'] = __salt__['firewall.disable'](name)
if (not ret['result']):
ret['comment'] = 'Could not disable the FW'
if check_name:
msg = 'Firewall profile {0} could not be disabled'.format(name)
else:
msg = 'Could not disable the FW'
ret['comment'] = msg
else:
if check_name:
msg = 'Firewall profile {0} is disabled'.format(name)
else:
msg = 'All the firewall profiles are disabled'
ret['comment'] = msg
return ret
| Disable all the firewall profiles (Windows only) | disable all the firewall profiles | Question:
What does this function do?
Code:
def disabled(name='allprofiles'):
ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''}
action = False
check_name = None
if (name != 'allprofiles'):
check_name = True
current_config = __salt__['firewall.get_config']()
if (check_name and (name not in current_config)):
ret['result'] = False
ret['comment'] = 'Profile {0} does not exist in firewall.get_config'.format(name)
return ret
for key in current_config:
if current_config[key]:
if (check_name and (key != name)):
continue
action = True
ret['changes'] = {'fw': 'disabled'}
break
if __opts__['test']:
ret['result'] = ((not action) or None)
return ret
if action:
ret['result'] = __salt__['firewall.disable'](name)
if (not ret['result']):
ret['comment'] = 'Could not disable the FW'
if check_name:
msg = 'Firewall profile {0} could not be disabled'.format(name)
else:
msg = 'Could not disable the FW'
ret['comment'] = msg
else:
if check_name:
msg = 'Firewall profile {0} is disabled'.format(name)
else:
msg = 'All the firewall profiles are disabled'
ret['comment'] = msg
return ret
|
null | null | null | What does this function do? | @utils.arg('server', metavar='<server>', help=_('Name or ID of server.'))
@utils.arg('address', metavar='<address>', help=_('IP Address.'))
def do_floating_ip_disassociate(cs, args):
_disassociate_floating_ip(cs, args)
| null | null | null | Disassociate a floating IP address from a server. | pcsd | @utils arg 'server' metavar='<server>' help= 'Name or ID of server ' @utils arg 'address' metavar='<address>' help= 'IP Address ' def do floating ip disassociate cs args disassociate floating ip cs args | 13699 | @utils.arg('server', metavar='<server>', help=_('Name or ID of server.'))
@utils.arg('address', metavar='<address>', help=_('IP Address.'))
def do_floating_ip_disassociate(cs, args):
_disassociate_floating_ip(cs, args)
| Disassociate a floating IP address from a server. | disassociate a floating ip address from a server . | Question:
What does this function do?
Code:
@utils.arg('server', metavar='<server>', help=_('Name or ID of server.'))
@utils.arg('address', metavar='<address>', help=_('IP Address.'))
def do_floating_ip_disassociate(cs, args):
_disassociate_floating_ip(cs, args)
|
null | null | null | What does this function do? | @register.filter
def format_name(user, format='first_last'):
last_name = (getattr(user, 'last_name', None) or user.get('last_name', None))
first_name = (getattr(user, 'first_name', None) or user.get('first_name', None))
username = (getattr(user, 'username', None) or user.get('username', None))
if (format == 'first_last'):
if (last_name and first_name):
return ('%s %s' % (first_name, last_name))
else:
return (first_name or last_name or username)
elif (format == 'last_first'):
if (last_name and first_name):
return ('%s, %s' % (last_name, first_name))
else:
return (last_name or first_name or username)
else:
raise NotImplementedError(('Unrecognized format string: %s' % format))
| null | null | null | Can be used for objects or dictionaries. | pcsd | @register filter def format name user format='first last' last name = getattr user 'last name' None or user get 'last name' None first name = getattr user 'first name' None or user get 'first name' None username = getattr user 'username' None or user get 'username' None if format == 'first last' if last name and first name return '%s %s' % first name last name else return first name or last name or username elif format == 'last first' if last name and first name return '%s %s' % last name first name else return last name or first name or username else raise Not Implemented Error 'Unrecognized format string %s' % format | 13700 | @register.filter
def format_name(user, format='first_last'):
last_name = (getattr(user, 'last_name', None) or user.get('last_name', None))
first_name = (getattr(user, 'first_name', None) or user.get('first_name', None))
username = (getattr(user, 'username', None) or user.get('username', None))
if (format == 'first_last'):
if (last_name and first_name):
return ('%s %s' % (first_name, last_name))
else:
return (first_name or last_name or username)
elif (format == 'last_first'):
if (last_name and first_name):
return ('%s, %s' % (last_name, first_name))
else:
return (last_name or first_name or username)
else:
raise NotImplementedError(('Unrecognized format string: %s' % format))
| Can be used for objects or dictionaries. | can be used for objects or dictionaries . | Question:
What does this function do?
Code:
@register.filter
def format_name(user, format='first_last'):
last_name = (getattr(user, 'last_name', None) or user.get('last_name', None))
first_name = (getattr(user, 'first_name', None) or user.get('first_name', None))
username = (getattr(user, 'username', None) or user.get('username', None))
if (format == 'first_last'):
if (last_name and first_name):
return ('%s %s' % (first_name, last_name))
else:
return (first_name or last_name or username)
elif (format == 'last_first'):
if (last_name and first_name):
return ('%s, %s' % (last_name, first_name))
else:
return (last_name or first_name or username)
else:
raise NotImplementedError(('Unrecognized format string: %s' % format))
|
null | null | null | What does this function do? | def _finish_auth_url(params):
return u'{}?{}'.format(reverse('finish_auth'), urllib.urlencode(params))
| null | null | null | Construct the URL that follows login/registration if we are doing auto-enrollment | pcsd | def finish auth url params return u'{}?{}' format reverse 'finish auth' urllib urlencode params | 13713 | def _finish_auth_url(params):
return u'{}?{}'.format(reverse('finish_auth'), urllib.urlencode(params))
| Construct the URL that follows login/registration if we are doing auto-enrollment | construct the url that follows login / registration if we are doing auto - enrollment | Question:
What does this function do?
Code:
def _finish_auth_url(params):
return u'{}?{}'.format(reverse('finish_auth'), urllib.urlencode(params))
|
null | null | null | What does this function do? | def get_parent_theme_name(theme_name, themes_dirs=None):
parent_path = os.path.join(theme_name, u'parent')
if os.path.isfile(parent_path):
with open(parent_path) as fd:
parent = fd.readlines()[0].strip()
if themes_dirs:
return get_theme_path_real(parent, themes_dirs)
return parent
return None
| null | null | null | Get name of parent theme. | pcsd | def get parent theme name theme name themes dirs=None parent path = os path join theme name u'parent' if os path isfile parent path with open parent path as fd parent = fd readlines [0] strip if themes dirs return get theme path real parent themes dirs return parent return None | 13723 | def get_parent_theme_name(theme_name, themes_dirs=None):
parent_path = os.path.join(theme_name, u'parent')
if os.path.isfile(parent_path):
with open(parent_path) as fd:
parent = fd.readlines()[0].strip()
if themes_dirs:
return get_theme_path_real(parent, themes_dirs)
return parent
return None
| Get name of parent theme. | get name of parent theme . | Question:
What does this function do?
Code:
def get_parent_theme_name(theme_name, themes_dirs=None):
parent_path = os.path.join(theme_name, u'parent')
if os.path.isfile(parent_path):
with open(parent_path) as fd:
parent = fd.readlines()[0].strip()
if themes_dirs:
return get_theme_path_real(parent, themes_dirs)
return parent
return None
|
null | null | null | What does this function do? | def getToothProfileAnnulus(derivation, pitchRadius, teeth):
toothProfileHalf = []
toothProfileHalfCylinder = getToothProfileHalfCylinder(derivation, pitchRadius)
pitchRadius = (- pitchRadius)
innerRadius = (pitchRadius - derivation.addendum)
for point in getWidthMultipliedPath(toothProfileHalfCylinder, (1.02 / derivation.toothWidthMultiplier)):
if (abs(point) >= innerRadius):
toothProfileHalf.append(point)
profileFirst = toothProfileHalf[0]
profileSecond = toothProfileHalf[1]
firstMinusSecond = (profileFirst - profileSecond)
remainingAddendum = (abs(profileFirst) - innerRadius)
firstMinusSecond *= (remainingAddendum / abs(firstMinusSecond))
extensionPoint = (profileFirst + firstMinusSecond)
if (derivation.tipBevel > 0.0):
unitPolar = euclidean.getWiddershinsUnitPolar(((2.0 / float(teeth)) * math.pi))
mirrorPoint = (complex((- extensionPoint.real), extensionPoint.imag) * unitPolar)
bevelPath = getBevelPath(profileFirst, derivation.tipBevel, extensionPoint, mirrorPoint)
toothProfileHalf = (bevelPath + toothProfileHalf)
else:
toothProfileHalf.insert(0, extensionPoint)
profileLast = toothProfileHalf[(-1)]
profilePenultimate = toothProfileHalf[(-2)]
lastMinusPenultimate = (profileLast - profilePenultimate)
remainingDedendum = ((pitchRadius - abs(profileLast)) + derivation.dedendum)
lastMinusPenultimate *= (remainingDedendum / abs(lastMinusPenultimate))
extensionPoint = (profileLast + lastMinusPenultimate)
if (derivation.rootBevel > 0.0):
mirrorPoint = complex((- extensionPoint.real), extensionPoint.imag)
bevelPath = getBevelPath(profileLast, derivation.rootBevel, extensionPoint, mirrorPoint)
bevelPath.reverse()
toothProfileHalf += bevelPath
else:
toothProfileHalf.append(extensionPoint)
toothProfileAnnulus = euclidean.getMirrorPath(toothProfileHalf)
toothProfileAnnulus.reverse()
return toothProfileAnnulus
| null | null | null | Get profile for one tooth of an annulus. | pcsd | def get Tooth Profile Annulus derivation pitch Radius teeth tooth Profile Half = [] tooth Profile Half Cylinder = get Tooth Profile Half Cylinder derivation pitch Radius pitch Radius = - pitch Radius inner Radius = pitch Radius - derivation addendum for point in get Width Multiplied Path tooth Profile Half Cylinder 1 02 / derivation tooth Width Multiplier if abs point >= inner Radius tooth Profile Half append point profile First = tooth Profile Half[0] profile Second = tooth Profile Half[1] first Minus Second = profile First - profile Second remaining Addendum = abs profile First - inner Radius first Minus Second *= remaining Addendum / abs first Minus Second extension Point = profile First + first Minus Second if derivation tip Bevel > 0 0 unit Polar = euclidean get Widdershins Unit Polar 2 0 / float teeth * math pi mirror Point = complex - extension Point real extension Point imag * unit Polar bevel Path = get Bevel Path profile First derivation tip Bevel extension Point mirror Point tooth Profile Half = bevel Path + tooth Profile Half else tooth Profile Half insert 0 extension Point profile Last = tooth Profile Half[ -1 ] profile Penultimate = tooth Profile Half[ -2 ] last Minus Penultimate = profile Last - profile Penultimate remaining Dedendum = pitch Radius - abs profile Last + derivation dedendum last Minus Penultimate *= remaining Dedendum / abs last Minus Penultimate extension Point = profile Last + last Minus Penultimate if derivation root Bevel > 0 0 mirror Point = complex - extension Point real extension Point imag bevel Path = get Bevel Path profile Last derivation root Bevel extension Point mirror Point bevel Path reverse tooth Profile Half += bevel Path else tooth Profile Half append extension Point tooth Profile Annulus = euclidean get Mirror Path tooth Profile Half tooth Profile Annulus reverse return tooth Profile Annulus | 13724 | def getToothProfileAnnulus(derivation, pitchRadius, teeth):
toothProfileHalf = []
toothProfileHalfCylinder = getToothProfileHalfCylinder(derivation, pitchRadius)
pitchRadius = (- pitchRadius)
innerRadius = (pitchRadius - derivation.addendum)
for point in getWidthMultipliedPath(toothProfileHalfCylinder, (1.02 / derivation.toothWidthMultiplier)):
if (abs(point) >= innerRadius):
toothProfileHalf.append(point)
profileFirst = toothProfileHalf[0]
profileSecond = toothProfileHalf[1]
firstMinusSecond = (profileFirst - profileSecond)
remainingAddendum = (abs(profileFirst) - innerRadius)
firstMinusSecond *= (remainingAddendum / abs(firstMinusSecond))
extensionPoint = (profileFirst + firstMinusSecond)
if (derivation.tipBevel > 0.0):
unitPolar = euclidean.getWiddershinsUnitPolar(((2.0 / float(teeth)) * math.pi))
mirrorPoint = (complex((- extensionPoint.real), extensionPoint.imag) * unitPolar)
bevelPath = getBevelPath(profileFirst, derivation.tipBevel, extensionPoint, mirrorPoint)
toothProfileHalf = (bevelPath + toothProfileHalf)
else:
toothProfileHalf.insert(0, extensionPoint)
profileLast = toothProfileHalf[(-1)]
profilePenultimate = toothProfileHalf[(-2)]
lastMinusPenultimate = (profileLast - profilePenultimate)
remainingDedendum = ((pitchRadius - abs(profileLast)) + derivation.dedendum)
lastMinusPenultimate *= (remainingDedendum / abs(lastMinusPenultimate))
extensionPoint = (profileLast + lastMinusPenultimate)
if (derivation.rootBevel > 0.0):
mirrorPoint = complex((- extensionPoint.real), extensionPoint.imag)
bevelPath = getBevelPath(profileLast, derivation.rootBevel, extensionPoint, mirrorPoint)
bevelPath.reverse()
toothProfileHalf += bevelPath
else:
toothProfileHalf.append(extensionPoint)
toothProfileAnnulus = euclidean.getMirrorPath(toothProfileHalf)
toothProfileAnnulus.reverse()
return toothProfileAnnulus
| Get profile for one tooth of an annulus. | get profile for one tooth of an annulus . | Question:
What does this function do?
Code:
def getToothProfileAnnulus(derivation, pitchRadius, teeth):
toothProfileHalf = []
toothProfileHalfCylinder = getToothProfileHalfCylinder(derivation, pitchRadius)
pitchRadius = (- pitchRadius)
innerRadius = (pitchRadius - derivation.addendum)
for point in getWidthMultipliedPath(toothProfileHalfCylinder, (1.02 / derivation.toothWidthMultiplier)):
if (abs(point) >= innerRadius):
toothProfileHalf.append(point)
profileFirst = toothProfileHalf[0]
profileSecond = toothProfileHalf[1]
firstMinusSecond = (profileFirst - profileSecond)
remainingAddendum = (abs(profileFirst) - innerRadius)
firstMinusSecond *= (remainingAddendum / abs(firstMinusSecond))
extensionPoint = (profileFirst + firstMinusSecond)
if (derivation.tipBevel > 0.0):
unitPolar = euclidean.getWiddershinsUnitPolar(((2.0 / float(teeth)) * math.pi))
mirrorPoint = (complex((- extensionPoint.real), extensionPoint.imag) * unitPolar)
bevelPath = getBevelPath(profileFirst, derivation.tipBevel, extensionPoint, mirrorPoint)
toothProfileHalf = (bevelPath + toothProfileHalf)
else:
toothProfileHalf.insert(0, extensionPoint)
profileLast = toothProfileHalf[(-1)]
profilePenultimate = toothProfileHalf[(-2)]
lastMinusPenultimate = (profileLast - profilePenultimate)
remainingDedendum = ((pitchRadius - abs(profileLast)) + derivation.dedendum)
lastMinusPenultimate *= (remainingDedendum / abs(lastMinusPenultimate))
extensionPoint = (profileLast + lastMinusPenultimate)
if (derivation.rootBevel > 0.0):
mirrorPoint = complex((- extensionPoint.real), extensionPoint.imag)
bevelPath = getBevelPath(profileLast, derivation.rootBevel, extensionPoint, mirrorPoint)
bevelPath.reverse()
toothProfileHalf += bevelPath
else:
toothProfileHalf.append(extensionPoint)
toothProfileAnnulus = euclidean.getMirrorPath(toothProfileHalf)
toothProfileAnnulus.reverse()
return toothProfileAnnulus
|
null | null | null | What does this function do? | def resolve_environment(service_dict, environment=None):
env = {}
for env_file in service_dict.get(u'env_file', []):
env.update(env_vars_from_file(env_file))
env.update(parse_environment(service_dict.get(u'environment')))
return dict((resolve_env_var(k, v, environment) for (k, v) in six.iteritems(env)))
| null | null | null | Unpack any environment variables from an env_file, if set.
Interpolate environment values if set. | pcsd | def resolve environment service dict environment=None env = {} for env file in service dict get u'env file' [] env update env vars from file env file env update parse environment service dict get u'environment' return dict resolve env var k v environment for k v in six iteritems env | 13727 | def resolve_environment(service_dict, environment=None):
env = {}
for env_file in service_dict.get(u'env_file', []):
env.update(env_vars_from_file(env_file))
env.update(parse_environment(service_dict.get(u'environment')))
return dict((resolve_env_var(k, v, environment) for (k, v) in six.iteritems(env)))
| Unpack any environment variables from an env_file, if set.
Interpolate environment values if set. | unpack any environment variables from an env _ file , if set . | Question:
What does this function do?
Code:
def resolve_environment(service_dict, environment=None):
env = {}
for env_file in service_dict.get(u'env_file', []):
env.update(env_vars_from_file(env_file))
env.update(parse_environment(service_dict.get(u'environment')))
return dict((resolve_env_var(k, v, environment) for (k, v) in six.iteritems(env)))
|
null | null | null | What does this function do? | @_get_client
def image_location_update(client, image_id, location, session=None):
client.image_location_update(image_id=image_id, location=location)
| null | null | null | Update image location. | pcsd | @ get client def image location update client image id location session=None client image location update image id=image id location=location | 13733 | @_get_client
def image_location_update(client, image_id, location, session=None):
client.image_location_update(image_id=image_id, location=location)
| Update image location. | update image location . | Question:
What does this function do?
Code:
@_get_client
def image_location_update(client, image_id, location, session=None):
client.image_location_update(image_id=image_id, location=location)
|
null | null | null | What does this function do? | def getFunctionLists(fileName):
fileText = archive.getFileText(fileName)
functionList = []
functionLists = [functionList]
lines = archive.getTextLines(fileText)
for line in lines:
lineStripped = line.strip()
if lineStripped.startswith('def '):
bracketIndex = lineStripped.find('(')
if (bracketIndex > (-1)):
lineStripped = lineStripped[:bracketIndex]
functionList.append(lineStripped)
elif line.startswith('class'):
functionList = []
functionLists.append(functionList)
return functionLists
| null | null | null | Get the function lists in the file. | pcsd | def get Function Lists file Name file Text = archive get File Text file Name function List = [] function Lists = [function List] lines = archive get Text Lines file Text for line in lines line Stripped = line strip if line Stripped startswith 'def ' bracket Index = line Stripped find ' ' if bracket Index > -1 line Stripped = line Stripped[ bracket Index] function List append line Stripped elif line startswith 'class' function List = [] function Lists append function List return function Lists | 13739 | def getFunctionLists(fileName):
fileText = archive.getFileText(fileName)
functionList = []
functionLists = [functionList]
lines = archive.getTextLines(fileText)
for line in lines:
lineStripped = line.strip()
if lineStripped.startswith('def '):
bracketIndex = lineStripped.find('(')
if (bracketIndex > (-1)):
lineStripped = lineStripped[:bracketIndex]
functionList.append(lineStripped)
elif line.startswith('class'):
functionList = []
functionLists.append(functionList)
return functionLists
| Get the function lists in the file. | get the function lists in the file . | Question:
What does this function do?
Code:
def getFunctionLists(fileName):
fileText = archive.getFileText(fileName)
functionList = []
functionLists = [functionList]
lines = archive.getTextLines(fileText)
for line in lines:
lineStripped = line.strip()
if lineStripped.startswith('def '):
bracketIndex = lineStripped.find('(')
if (bracketIndex > (-1)):
lineStripped = lineStripped[:bracketIndex]
functionList.append(lineStripped)
elif line.startswith('class'):
functionList = []
functionLists.append(functionList)
return functionLists
|
null | null | null | What does this function do? | def getLargestCenterOutsetLoopFromLoopRegardless(loop, radius):
global globalDecreasingRadiusMultipliers
for decreasingRadiusMultiplier in globalDecreasingRadiusMultipliers:
decreasingRadius = (radius * decreasingRadiusMultiplier)
largestCenterOutsetLoop = getLargestCenterOutsetLoopFromLoop(loop, decreasingRadius)
if (largestCenterOutsetLoop != None):
return largestCenterOutsetLoop
print 'Warning, there should always be a largestOutsetLoop in getLargestCenterOutsetLoopFromLoopRegardless in intercircle.'
print loop
return CenterOutset(loop, loop)
| null | null | null | Get the largest circle outset loop from the loop, even if the radius has to be shrunk and even if there is still no outset loop. | pcsd | def get Largest Center Outset Loop From Loop Regardless loop radius global global Decreasing Radius Multipliers for decreasing Radius Multiplier in global Decreasing Radius Multipliers decreasing Radius = radius * decreasing Radius Multiplier largest Center Outset Loop = get Largest Center Outset Loop From Loop loop decreasing Radius if largest Center Outset Loop != None return largest Center Outset Loop print 'Warning there should always be a largest Outset Loop in get Largest Center Outset Loop From Loop Regardless in intercircle ' print loop return Center Outset loop loop | 13742 | def getLargestCenterOutsetLoopFromLoopRegardless(loop, radius):
global globalDecreasingRadiusMultipliers
for decreasingRadiusMultiplier in globalDecreasingRadiusMultipliers:
decreasingRadius = (radius * decreasingRadiusMultiplier)
largestCenterOutsetLoop = getLargestCenterOutsetLoopFromLoop(loop, decreasingRadius)
if (largestCenterOutsetLoop != None):
return largestCenterOutsetLoop
print 'Warning, there should always be a largestOutsetLoop in getLargestCenterOutsetLoopFromLoopRegardless in intercircle.'
print loop
return CenterOutset(loop, loop)
| Get the largest circle outset loop from the loop, even if the radius has to be shrunk and even if there is still no outset loop. | get the largest circle outset loop from the loop , even if the radius has to be shrunk and even if there is still no outset loop . | Question:
What does this function do?
Code:
def getLargestCenterOutsetLoopFromLoopRegardless(loop, radius):
global globalDecreasingRadiusMultipliers
for decreasingRadiusMultiplier in globalDecreasingRadiusMultipliers:
decreasingRadius = (radius * decreasingRadiusMultiplier)
largestCenterOutsetLoop = getLargestCenterOutsetLoopFromLoop(loop, decreasingRadius)
if (largestCenterOutsetLoop != None):
return largestCenterOutsetLoop
print 'Warning, there should always be a largestOutsetLoop in getLargestCenterOutsetLoopFromLoopRegardless in intercircle.'
print loop
return CenterOutset(loop, loop)
|
null | null | null | What does this function do? | def layer_kml():
tablename = ('%s_%s' % (module, resourcename))
s3db.table(tablename)
type = 'KML'
LAYERS = T((TYPE_LAYERS_FMT % type))
ADD_NEW_LAYER = T((ADD_NEW_TYPE_LAYER_FMT % type))
EDIT_LAYER = T((EDIT_TYPE_LAYER_FMT % type))
LIST_LAYERS = T((LIST_TYPE_LAYERS_FMT % type))
NO_LAYERS = T((NO_TYPE_LAYERS_FMT % type))
s3.crud_strings[tablename] = Storage(label_create=ADD_LAYER, title_display=LAYER_DETAILS, title_list=LAYERS, title_update=EDIT_LAYER, label_list_button=LIST_LAYERS, label_delete_button=DELETE_LAYER, msg_record_created=LAYER_ADDED, msg_record_modified=LAYER_UPDATED, msg_record_deleted=LAYER_DELETED, msg_list_empty=NO_LAYERS)
def prep(r):
if r.interactive:
if (r.component_name == 'config'):
ltable = s3db.gis_layer_config
ltable.base.writable = ltable.base.readable = False
if (r.method != 'update'):
table = r.table
query = ((ltable.layer_id == table.layer_id) & (table.id == r.id))
rows = db(query).select(ltable.config_id)
ltable.config_id.requires = IS_ONE_OF(db, 'gis_config.id', '%(name)s', not_filterby='config_id', not_filter_opts=[row.config_id for row in rows])
return True
s3.prep = prep
def postp(r, output):
if (r.interactive and (r.method != 'import')):
if (not r.component):
s3_action_buttons(r, copyable=True)
inject_enable(output)
return output
s3.postp = postp
output = s3_rest_controller(rheader=s3db.gis_rheader)
return output
| null | null | null | RESTful CRUD controller | pcsd | def layer kml tablename = '%s %s' % module resourcename s3db table tablename type = 'KML' LAYERS = T TYPE LAYERS FMT % type ADD NEW LAYER = T ADD NEW TYPE LAYER FMT % type EDIT LAYER = T EDIT TYPE LAYER FMT % type LIST LAYERS = T LIST TYPE LAYERS FMT % type NO LAYERS = T NO TYPE LAYERS FMT % type s3 crud strings[tablename] = Storage label create=ADD LAYER title display=LAYER DETAILS title list=LAYERS title update=EDIT LAYER label list button=LIST LAYERS label delete button=DELETE LAYER msg record created=LAYER ADDED msg record modified=LAYER UPDATED msg record deleted=LAYER DELETED msg list empty=NO LAYERS def prep r if r interactive if r component name == 'config' ltable = s3db gis layer config ltable base writable = ltable base readable = False if r method != 'update' table = r table query = ltable layer id == table layer id & table id == r id rows = db query select ltable config id ltable config id requires = IS ONE OF db 'gis config id' '% name s' not filterby='config id' not filter opts=[row config id for row in rows] return True s3 prep = prep def postp r output if r interactive and r method != 'import' if not r component s3 action buttons r copyable=True inject enable output return output s3 postp = postp output = s3 rest controller rheader=s3db gis rheader return output | 13746 | def layer_kml():
tablename = ('%s_%s' % (module, resourcename))
s3db.table(tablename)
type = 'KML'
LAYERS = T((TYPE_LAYERS_FMT % type))
ADD_NEW_LAYER = T((ADD_NEW_TYPE_LAYER_FMT % type))
EDIT_LAYER = T((EDIT_TYPE_LAYER_FMT % type))
LIST_LAYERS = T((LIST_TYPE_LAYERS_FMT % type))
NO_LAYERS = T((NO_TYPE_LAYERS_FMT % type))
s3.crud_strings[tablename] = Storage(label_create=ADD_LAYER, title_display=LAYER_DETAILS, title_list=LAYERS, title_update=EDIT_LAYER, label_list_button=LIST_LAYERS, label_delete_button=DELETE_LAYER, msg_record_created=LAYER_ADDED, msg_record_modified=LAYER_UPDATED, msg_record_deleted=LAYER_DELETED, msg_list_empty=NO_LAYERS)
def prep(r):
if r.interactive:
if (r.component_name == 'config'):
ltable = s3db.gis_layer_config
ltable.base.writable = ltable.base.readable = False
if (r.method != 'update'):
table = r.table
query = ((ltable.layer_id == table.layer_id) & (table.id == r.id))
rows = db(query).select(ltable.config_id)
ltable.config_id.requires = IS_ONE_OF(db, 'gis_config.id', '%(name)s', not_filterby='config_id', not_filter_opts=[row.config_id for row in rows])
return True
s3.prep = prep
def postp(r, output):
if (r.interactive and (r.method != 'import')):
if (not r.component):
s3_action_buttons(r, copyable=True)
inject_enable(output)
return output
s3.postp = postp
output = s3_rest_controller(rheader=s3db.gis_rheader)
return output
| RESTful CRUD controller | restful crud controller | Question:
What does this function do?
Code:
def layer_kml():
tablename = ('%s_%s' % (module, resourcename))
s3db.table(tablename)
type = 'KML'
LAYERS = T((TYPE_LAYERS_FMT % type))
ADD_NEW_LAYER = T((ADD_NEW_TYPE_LAYER_FMT % type))
EDIT_LAYER = T((EDIT_TYPE_LAYER_FMT % type))
LIST_LAYERS = T((LIST_TYPE_LAYERS_FMT % type))
NO_LAYERS = T((NO_TYPE_LAYERS_FMT % type))
s3.crud_strings[tablename] = Storage(label_create=ADD_LAYER, title_display=LAYER_DETAILS, title_list=LAYERS, title_update=EDIT_LAYER, label_list_button=LIST_LAYERS, label_delete_button=DELETE_LAYER, msg_record_created=LAYER_ADDED, msg_record_modified=LAYER_UPDATED, msg_record_deleted=LAYER_DELETED, msg_list_empty=NO_LAYERS)
def prep(r):
if r.interactive:
if (r.component_name == 'config'):
ltable = s3db.gis_layer_config
ltable.base.writable = ltable.base.readable = False
if (r.method != 'update'):
table = r.table
query = ((ltable.layer_id == table.layer_id) & (table.id == r.id))
rows = db(query).select(ltable.config_id)
ltable.config_id.requires = IS_ONE_OF(db, 'gis_config.id', '%(name)s', not_filterby='config_id', not_filter_opts=[row.config_id for row in rows])
return True
s3.prep = prep
def postp(r, output):
if (r.interactive and (r.method != 'import')):
if (not r.component):
s3_action_buttons(r, copyable=True)
inject_enable(output)
return output
s3.postp = postp
output = s3_rest_controller(rheader=s3db.gis_rheader)
return output
|
null | null | null | What does this function do? | @pytest.mark.git
def test_freeze_git_clone(script, tmpdir):
pkg_version = _create_test_package(script)
result = script.run('git', 'clone', pkg_version, 'pip-test-package', expect_stderr=True)
repo_dir = (script.scratch_path / 'pip-test-package')
result = script.run('python', 'setup.py', 'develop', cwd=repo_dir, expect_stderr=True)
result = script.pip('freeze', expect_stderr=True)
expected = textwrap.dedent('\n ...-e git+...#egg=version_pkg\n ...\n ').strip()
_check_output(result.stdout, expected)
result = script.pip('freeze', '-f', ('%s#egg=pip_test_package' % repo_dir), expect_stderr=True)
expected = textwrap.dedent(('\n -f %(repo)s#egg=pip_test_package...\n -e git+...#egg=version_pkg\n ...\n ' % {'repo': repo_dir})).strip()
_check_output(result.stdout, expected)
script.run('git', 'checkout', '-b', 'branch/name/with/slash', cwd=repo_dir, expect_stderr=True)
script.run('touch', 'newfile', cwd=repo_dir)
script.run('git', 'add', 'newfile', cwd=repo_dir)
script.run('git', 'commit', '-m', '...', cwd=repo_dir)
result = script.pip('freeze', expect_stderr=True)
expected = textwrap.dedent('\n ...-e ...@...#egg=version_pkg\n ...\n ').strip()
_check_output(result.stdout, expected)
| null | null | null | Test freezing a Git clone. | pcsd | @pytest mark git def test freeze git clone script tmpdir pkg version = create test package script result = script run 'git' 'clone' pkg version 'pip-test-package' expect stderr=True repo dir = script scratch path / 'pip-test-package' result = script run 'python' 'setup py' 'develop' cwd=repo dir expect stderr=True result = script pip 'freeze' expect stderr=True expected = textwrap dedent ' -e git+ #egg=version pkg ' strip check output result stdout expected result = script pip 'freeze' '-f' '%s#egg=pip test package' % repo dir expect stderr=True expected = textwrap dedent ' -f % repo s#egg=pip test package -e git+ #egg=version pkg ' % {'repo' repo dir} strip check output result stdout expected script run 'git' 'checkout' '-b' 'branch/name/with/slash' cwd=repo dir expect stderr=True script run 'touch' 'newfile' cwd=repo dir script run 'git' 'add' 'newfile' cwd=repo dir script run 'git' 'commit' '-m' ' ' cwd=repo dir result = script pip 'freeze' expect stderr=True expected = textwrap dedent ' -e @ #egg=version pkg ' strip check output result stdout expected | 13752 | @pytest.mark.git
def test_freeze_git_clone(script, tmpdir):
pkg_version = _create_test_package(script)
result = script.run('git', 'clone', pkg_version, 'pip-test-package', expect_stderr=True)
repo_dir = (script.scratch_path / 'pip-test-package')
result = script.run('python', 'setup.py', 'develop', cwd=repo_dir, expect_stderr=True)
result = script.pip('freeze', expect_stderr=True)
expected = textwrap.dedent('\n ...-e git+...#egg=version_pkg\n ...\n ').strip()
_check_output(result.stdout, expected)
result = script.pip('freeze', '-f', ('%s#egg=pip_test_package' % repo_dir), expect_stderr=True)
expected = textwrap.dedent(('\n -f %(repo)s#egg=pip_test_package...\n -e git+...#egg=version_pkg\n ...\n ' % {'repo': repo_dir})).strip()
_check_output(result.stdout, expected)
script.run('git', 'checkout', '-b', 'branch/name/with/slash', cwd=repo_dir, expect_stderr=True)
script.run('touch', 'newfile', cwd=repo_dir)
script.run('git', 'add', 'newfile', cwd=repo_dir)
script.run('git', 'commit', '-m', '...', cwd=repo_dir)
result = script.pip('freeze', expect_stderr=True)
expected = textwrap.dedent('\n ...-e ...@...#egg=version_pkg\n ...\n ').strip()
_check_output(result.stdout, expected)
| Test freezing a Git clone. | test freezing a git clone . | Question:
What does this function do?
Code:
@pytest.mark.git
def test_freeze_git_clone(script, tmpdir):
pkg_version = _create_test_package(script)
result = script.run('git', 'clone', pkg_version, 'pip-test-package', expect_stderr=True)
repo_dir = (script.scratch_path / 'pip-test-package')
result = script.run('python', 'setup.py', 'develop', cwd=repo_dir, expect_stderr=True)
result = script.pip('freeze', expect_stderr=True)
expected = textwrap.dedent('\n ...-e git+...#egg=version_pkg\n ...\n ').strip()
_check_output(result.stdout, expected)
result = script.pip('freeze', '-f', ('%s#egg=pip_test_package' % repo_dir), expect_stderr=True)
expected = textwrap.dedent(('\n -f %(repo)s#egg=pip_test_package...\n -e git+...#egg=version_pkg\n ...\n ' % {'repo': repo_dir})).strip()
_check_output(result.stdout, expected)
script.run('git', 'checkout', '-b', 'branch/name/with/slash', cwd=repo_dir, expect_stderr=True)
script.run('touch', 'newfile', cwd=repo_dir)
script.run('git', 'add', 'newfile', cwd=repo_dir)
script.run('git', 'commit', '-m', '...', cwd=repo_dir)
result = script.pip('freeze', expect_stderr=True)
expected = textwrap.dedent('\n ...-e ...@...#egg=version_pkg\n ...\n ').strip()
_check_output(result.stdout, expected)
|
null | null | null | What does this function do? | def application_start(context, view):
context.app.set_view(view)
view.show()
view.raise_()
runtask = qtutils.RunTask(parent=view)
init_update_task(view, runtask, context.model)
fsmonitor.current().start()
msg_timer = QtCore.QTimer()
msg_timer.setSingleShot(True)
msg_timer.timeout.connect(_send_msg)
msg_timer.start(0)
result = context.app.exec_()
fsmonitor.current().stop()
QtCore.QThreadPool.globalInstance().waitForDone()
return result
| null | null | null | Show the GUI and start the main event loop | pcsd | def application start context view context app set view view view show view raise runtask = qtutils Run Task parent=view init update task view runtask context model fsmonitor current start msg timer = Qt Core Q Timer msg timer set Single Shot True msg timer timeout connect send msg msg timer start 0 result = context app exec fsmonitor current stop Qt Core Q Thread Pool global Instance wait For Done return result | 13755 | def application_start(context, view):
context.app.set_view(view)
view.show()
view.raise_()
runtask = qtutils.RunTask(parent=view)
init_update_task(view, runtask, context.model)
fsmonitor.current().start()
msg_timer = QtCore.QTimer()
msg_timer.setSingleShot(True)
msg_timer.timeout.connect(_send_msg)
msg_timer.start(0)
result = context.app.exec_()
fsmonitor.current().stop()
QtCore.QThreadPool.globalInstance().waitForDone()
return result
| Show the GUI and start the main event loop | show the gui and start the main event loop | Question:
What does this function do?
Code:
def application_start(context, view):
context.app.set_view(view)
view.show()
view.raise_()
runtask = qtutils.RunTask(parent=view)
init_update_task(view, runtask, context.model)
fsmonitor.current().start()
msg_timer = QtCore.QTimer()
msg_timer.setSingleShot(True)
msg_timer.timeout.connect(_send_msg)
msg_timer.start(0)
result = context.app.exec_()
fsmonitor.current().stop()
QtCore.QThreadPool.globalInstance().waitForDone()
return result
|
null | null | null | What does this function do? | @click.command(u'add-system-manager')
@click.argument(u'email')
@click.option(u'--first-name')
@click.option(u'--last-name')
@click.option(u'--send-welcome-email', default=False, is_flag=True)
@pass_context
def add_system_manager(context, email, first_name, last_name, send_welcome_email):
import frappe.utils.user
for site in context.sites:
frappe.connect(site=site)
try:
frappe.utils.user.add_system_manager(email, first_name, last_name, send_welcome_email)
frappe.db.commit()
finally:
frappe.destroy()
| null | null | null | Add a new system manager to a site | pcsd | @click command u'add-system-manager' @click argument u'email' @click option u'--first-name' @click option u'--last-name' @click option u'--send-welcome-email' default=False is flag=True @pass context def add system manager context email first name last name send welcome email import frappe utils user for site in context sites frappe connect site=site try frappe utils user add system manager email first name last name send welcome email frappe db commit finally frappe destroy | 13756 | @click.command(u'add-system-manager')
@click.argument(u'email')
@click.option(u'--first-name')
@click.option(u'--last-name')
@click.option(u'--send-welcome-email', default=False, is_flag=True)
@pass_context
def add_system_manager(context, email, first_name, last_name, send_welcome_email):
import frappe.utils.user
for site in context.sites:
frappe.connect(site=site)
try:
frappe.utils.user.add_system_manager(email, first_name, last_name, send_welcome_email)
frappe.db.commit()
finally:
frappe.destroy()
| Add a new system manager to a site | add a new system manager to a site | Question:
What does this function do?
Code:
@click.command(u'add-system-manager')
@click.argument(u'email')
@click.option(u'--first-name')
@click.option(u'--last-name')
@click.option(u'--send-welcome-email', default=False, is_flag=True)
@pass_context
def add_system_manager(context, email, first_name, last_name, send_welcome_email):
import frappe.utils.user
for site in context.sites:
frappe.connect(site=site)
try:
frappe.utils.user.add_system_manager(email, first_name, last_name, send_welcome_email)
frappe.db.commit()
finally:
frappe.destroy()
|
null | null | null | What does this function do? | def _extract_jdk_version(java_version_out):
match = re.search('Runtime Environment \\(build (.*?)\\)', java_version_out)
if (match is None):
return None
(version, build) = match.group(1).split('-')
release = version.split('_')[0].split('.')[1]
update = str(int(version.split('_')[1]))
return ('%(release)su%(update)s-%(build)s' % locals())
| null | null | null | Extracts JDK version in format like \'7u13-b20\'
from \'java -version\' command output. | pcsd | def extract jdk version java version out match = re search 'Runtime Environment \\ build *? \\ ' java version out if match is None return None version build = match group 1 split '-' release = version split ' ' [0] split ' ' [1] update = str int version split ' ' [1] return '% release su% update s-% build s' % locals | 13759 | def _extract_jdk_version(java_version_out):
match = re.search('Runtime Environment \\(build (.*?)\\)', java_version_out)
if (match is None):
return None
(version, build) = match.group(1).split('-')
release = version.split('_')[0].split('.')[1]
update = str(int(version.split('_')[1]))
return ('%(release)su%(update)s-%(build)s' % locals())
| Extracts JDK version in format like \'7u13-b20\'
from \'java -version\' command output. | extracts jdk version in format like 7u13 - b20 from java - version command output . | Question:
What does this function do?
Code:
def _extract_jdk_version(java_version_out):
match = re.search('Runtime Environment \\(build (.*?)\\)', java_version_out)
if (match is None):
return None
(version, build) = match.group(1).split('-')
release = version.split('_')[0].split('.')[1]
update = str(int(version.split('_')[1]))
return ('%(release)su%(update)s-%(build)s' % locals())
|
null | null | null | What does this function do? | def merge(a):
count = 0
if (len(a) > 1):
midpoint = (len(a) // 2)
b = a[:midpoint]
c = a[midpoint:]
count_b = merge(b)
count_c = merge(c)
(result, count_a) = _merge_lists(b, c)
a[:] = result
count = ((count_a + count_b) + count_c)
return count
| null | null | null | Merge Sort: split the list in half, and sort each half, then
combine the sorted halves. | pcsd | def merge a count = 0 if len a > 1 midpoint = len a // 2 b = a[ midpoint] c = a[midpoint ] count b = merge b count c = merge c result count a = merge lists b c a[ ] = result count = count a + count b + count c return count | 13761 | def merge(a):
count = 0
if (len(a) > 1):
midpoint = (len(a) // 2)
b = a[:midpoint]
c = a[midpoint:]
count_b = merge(b)
count_c = merge(c)
(result, count_a) = _merge_lists(b, c)
a[:] = result
count = ((count_a + count_b) + count_c)
return count
| Merge Sort: split the list in half, and sort each half, then
combine the sorted halves. | merge sort : split the list in half , and sort each half , then combine the sorted halves . | Question:
What does this function do?
Code:
def merge(a):
count = 0
if (len(a) > 1):
midpoint = (len(a) // 2)
b = a[:midpoint]
c = a[midpoint:]
count_b = merge(b)
count_c = merge(c)
(result, count_a) = _merge_lists(b, c)
a[:] = result
count = ((count_a + count_b) + count_c)
return count
|
null | null | null | What does this function do? | def get_config_value(node, value_index):
try:
for value in node.values.values():
if ((value.command_class == 112) and (value.index == value_index)):
return value.data
except RuntimeError:
return get_config_value(node, value_index)
| null | null | null | Return the current configuration value for a specific index. | pcsd | def get config value node value index try for value in node values values if value command class == 112 and value index == value index return value data except Runtime Error return get config value node value index | 13773 | def get_config_value(node, value_index):
try:
for value in node.values.values():
if ((value.command_class == 112) and (value.index == value_index)):
return value.data
except RuntimeError:
return get_config_value(node, value_index)
| Return the current configuration value for a specific index. | return the current configuration value for a specific index . | Question:
What does this function do?
Code:
def get_config_value(node, value_index):
try:
for value in node.values.values():
if ((value.command_class == 112) and (value.index == value_index)):
return value.data
except RuntimeError:
return get_config_value(node, value_index)
|
null | null | null | What does this function do? | def make_dirs(path):
sickrage.srCore.srLogger.debug(u'Checking if the path [{}] already exists'.format(path))
if (not os.path.isdir(path)):
if ((os.name == u'nt') or (os.name == u'ce')):
try:
sickrage.srCore.srLogger.debug((u"Folder %s didn't exist, creating it" % path))
os.makedirs(path)
except (OSError, IOError) as e:
sickrage.srCore.srLogger.error((u'Failed creating %s : %r' % (path, e)))
return False
else:
sofar = u''
folder_list = path.split(os.path.sep)
for cur_folder in folder_list:
sofar += (cur_folder + os.path.sep)
if os.path.isdir(sofar):
continue
try:
sickrage.srCore.srLogger.debug((u"Folder %s didn't exist, creating it" % sofar))
os.mkdir(sofar)
chmodAsParent(os.path.normpath(sofar))
sickrage.srCore.notifiersDict.synoindex_notifier.addFolder(sofar)
except (OSError, IOError) as e:
sickrage.srCore.srLogger.error((u'Failed creating %s : %r' % (sofar, e)))
return False
return True
| null | null | null | Creates any folders that are missing and assigns them the permissions of their
parents | pcsd | def make dirs path sickrage sr Core sr Logger debug u'Checking if the path [{}] already exists' format path if not os path isdir path if os name == u'nt' or os name == u'ce' try sickrage sr Core sr Logger debug u"Folder %s didn't exist creating it" % path os makedirs path except OS Error IO Error as e sickrage sr Core sr Logger error u'Failed creating %s %r' % path e return False else sofar = u'' folder list = path split os path sep for cur folder in folder list sofar += cur folder + os path sep if os path isdir sofar continue try sickrage sr Core sr Logger debug u"Folder %s didn't exist creating it" % sofar os mkdir sofar chmod As Parent os path normpath sofar sickrage sr Core notifiers Dict synoindex notifier add Folder sofar except OS Error IO Error as e sickrage sr Core sr Logger error u'Failed creating %s %r' % sofar e return False return True | 13776 | def make_dirs(path):
sickrage.srCore.srLogger.debug(u'Checking if the path [{}] already exists'.format(path))
if (not os.path.isdir(path)):
if ((os.name == u'nt') or (os.name == u'ce')):
try:
sickrage.srCore.srLogger.debug((u"Folder %s didn't exist, creating it" % path))
os.makedirs(path)
except (OSError, IOError) as e:
sickrage.srCore.srLogger.error((u'Failed creating %s : %r' % (path, e)))
return False
else:
sofar = u''
folder_list = path.split(os.path.sep)
for cur_folder in folder_list:
sofar += (cur_folder + os.path.sep)
if os.path.isdir(sofar):
continue
try:
sickrage.srCore.srLogger.debug((u"Folder %s didn't exist, creating it" % sofar))
os.mkdir(sofar)
chmodAsParent(os.path.normpath(sofar))
sickrage.srCore.notifiersDict.synoindex_notifier.addFolder(sofar)
except (OSError, IOError) as e:
sickrage.srCore.srLogger.error((u'Failed creating %s : %r' % (sofar, e)))
return False
return True
| Creates any folders that are missing and assigns them the permissions of their
parents | creates any folders that are missing and assigns them the permissions of their parents | Question:
What does this function do?
Code:
def make_dirs(path):
sickrage.srCore.srLogger.debug(u'Checking if the path [{}] already exists'.format(path))
if (not os.path.isdir(path)):
if ((os.name == u'nt') or (os.name == u'ce')):
try:
sickrage.srCore.srLogger.debug((u"Folder %s didn't exist, creating it" % path))
os.makedirs(path)
except (OSError, IOError) as e:
sickrage.srCore.srLogger.error((u'Failed creating %s : %r' % (path, e)))
return False
else:
sofar = u''
folder_list = path.split(os.path.sep)
for cur_folder in folder_list:
sofar += (cur_folder + os.path.sep)
if os.path.isdir(sofar):
continue
try:
sickrage.srCore.srLogger.debug((u"Folder %s didn't exist, creating it" % sofar))
os.mkdir(sofar)
chmodAsParent(os.path.normpath(sofar))
sickrage.srCore.notifiersDict.synoindex_notifier.addFolder(sofar)
except (OSError, IOError) as e:
sickrage.srCore.srLogger.error((u'Failed creating %s : %r' % (sofar, e)))
return False
return True
|
null | null | null | What does this function do? | def get_default_compiler(is_post, compilers, post_pages):
filtered = [entry for entry in post_pages if (entry[3] == is_post)]
for entry in filtered:
extension = os.path.splitext(entry[0])[(-1)]
for (compiler, extensions) in compilers.items():
if (extension in extensions):
return compiler
return u'rest'
| null | null | null | Given compilers and post_pages, return a reasonable default compiler for this kind of post/page. | pcsd | def get default compiler is post compilers post pages filtered = [entry for entry in post pages if entry[3] == is post ] for entry in filtered extension = os path splitext entry[0] [ -1 ] for compiler extensions in compilers items if extension in extensions return compiler return u'rest' | 13777 | def get_default_compiler(is_post, compilers, post_pages):
filtered = [entry for entry in post_pages if (entry[3] == is_post)]
for entry in filtered:
extension = os.path.splitext(entry[0])[(-1)]
for (compiler, extensions) in compilers.items():
if (extension in extensions):
return compiler
return u'rest'
| Given compilers and post_pages, return a reasonable default compiler for this kind of post/page. | given compilers and post _ pages , return a reasonable default compiler for this kind of post / page . | Question:
What does this function do?
Code:
def get_default_compiler(is_post, compilers, post_pages):
filtered = [entry for entry in post_pages if (entry[3] == is_post)]
for entry in filtered:
extension = os.path.splitext(entry[0])[(-1)]
for (compiler, extensions) in compilers.items():
if (extension in extensions):
return compiler
return u'rest'
|
null | null | null | What does this function do? | def _object_reducer(o, names=('id', 'name', 'path', 'httpMethod', 'statusCode', 'Created', 'Deleted', 'Updated', 'Flushed', 'Associated', 'Disassociated')):
result = {}
if isinstance(o, dict):
for (k, v) in six.iteritems(o):
if isinstance(v, dict):
reduced = (v if (k == 'variables') else _object_reducer(v, names))
if (reduced or _name_matches(k, names)):
result[k] = reduced
elif isinstance(v, list):
newlist = []
for val in v:
reduced = _object_reducer(val, names)
if (reduced or _name_matches(k, names)):
newlist.append(reduced)
if newlist:
result[k] = newlist
elif _name_matches(k, names):
result[k] = v
return result
| null | null | null | Helper function to reduce the amount of information that will be kept in the change log
for API GW related return values | pcsd | def object reducer o names= 'id' 'name' 'path' 'http Method' 'status Code' 'Created' 'Deleted' 'Updated' 'Flushed' 'Associated' 'Disassociated' result = {} if isinstance o dict for k v in six iteritems o if isinstance v dict reduced = v if k == 'variables' else object reducer v names if reduced or name matches k names result[k] = reduced elif isinstance v list newlist = [] for val in v reduced = object reducer val names if reduced or name matches k names newlist append reduced if newlist result[k] = newlist elif name matches k names result[k] = v return result | 13785 | def _object_reducer(o, names=('id', 'name', 'path', 'httpMethod', 'statusCode', 'Created', 'Deleted', 'Updated', 'Flushed', 'Associated', 'Disassociated')):
result = {}
if isinstance(o, dict):
for (k, v) in six.iteritems(o):
if isinstance(v, dict):
reduced = (v if (k == 'variables') else _object_reducer(v, names))
if (reduced or _name_matches(k, names)):
result[k] = reduced
elif isinstance(v, list):
newlist = []
for val in v:
reduced = _object_reducer(val, names)
if (reduced or _name_matches(k, names)):
newlist.append(reduced)
if newlist:
result[k] = newlist
elif _name_matches(k, names):
result[k] = v
return result
| Helper function to reduce the amount of information that will be kept in the change log
for API GW related return values | helper function to reduce the amount of information that will be kept in the change log for api gw related return values | Question:
What does this function do?
Code:
def _object_reducer(o, names=('id', 'name', 'path', 'httpMethod', 'statusCode', 'Created', 'Deleted', 'Updated', 'Flushed', 'Associated', 'Disassociated')):
result = {}
if isinstance(o, dict):
for (k, v) in six.iteritems(o):
if isinstance(v, dict):
reduced = (v if (k == 'variables') else _object_reducer(v, names))
if (reduced or _name_matches(k, names)):
result[k] = reduced
elif isinstance(v, list):
newlist = []
for val in v:
reduced = _object_reducer(val, names)
if (reduced or _name_matches(k, names)):
newlist.append(reduced)
if newlist:
result[k] = newlist
elif _name_matches(k, names):
result[k] = v
return result
|
null | null | null | What does this function do? | @contextlib.contextmanager
def autonested_transaction(sess):
if sess.is_active:
session_context = sess.begin(nested=True)
else:
session_context = sess.begin(subtransactions=True)
with session_context as tx:
(yield tx)
| null | null | null | This is a convenience method to not bother with \'nested\' parameter. | pcsd | @contextlib contextmanager def autonested transaction sess if sess is active session context = sess begin nested=True else session context = sess begin subtransactions=True with session context as tx yield tx | 13804 | @contextlib.contextmanager
def autonested_transaction(sess):
if sess.is_active:
session_context = sess.begin(nested=True)
else:
session_context = sess.begin(subtransactions=True)
with session_context as tx:
(yield tx)
| This is a convenience method to not bother with \'nested\' parameter. | this is a convenience method to not bother with nested parameter . | Question:
What does this function do?
Code:
@contextlib.contextmanager
def autonested_transaction(sess):
if sess.is_active:
session_context = sess.begin(nested=True)
else:
session_context = sess.begin(subtransactions=True)
with session_context as tx:
(yield tx)
|
null | null | null | What does this function do? | def search_list(list_provided):
for i in range((len(list_provided) - 1)):
if ((not (list_provided[i] in list_provided[(i + 1):])) and (not (list_provided[i] in list_provided[:i]))):
'If the same number is not present before or after in the list then\n return the number'
return str(list_provided[i])
break
| null | null | null | Search list provided for characters that are represented only once. | pcsd | def search list list provided for i in range len list provided - 1 if not list provided[i] in list provided[ i + 1 ] and not list provided[i] in list provided[ i] 'If the same number is not present before or after in the list then return the number' return str list provided[i] break | 13811 | def search_list(list_provided):
for i in range((len(list_provided) - 1)):
if ((not (list_provided[i] in list_provided[(i + 1):])) and (not (list_provided[i] in list_provided[:i]))):
'If the same number is not present before or after in the list then\n return the number'
return str(list_provided[i])
break
| Search list provided for characters that are represented only once. | search list provided for characters that are represented only once . | Question:
What does this function do?
Code:
def search_list(list_provided):
for i in range((len(list_provided) - 1)):
if ((not (list_provided[i] in list_provided[(i + 1):])) and (not (list_provided[i] in list_provided[:i]))):
'If the same number is not present before or after in the list then\n return the number'
return str(list_provided[i])
break
|
null | null | null | What does this function do? | def count_special_lines(word, filename, invert=False):
try:
cmd = ['grep', '-c', '-E']
if invert:
cmd.append('-v')
cmd.extend([word, filename])
out = subprocess.Popen(cmd, stdout=subprocess.PIPE)
return int(out.communicate()[0].split()[0])
except:
pass
return 0
| null | null | null | searching for special \'words\' using the grep tool
grep is used to speed up the searching and counting
The number of hits is returned. | pcsd | def count special lines word filename invert=False try cmd = ['grep' '-c' '-E'] if invert cmd append '-v' cmd extend [word filename] out = subprocess Popen cmd stdout=subprocess PIPE return int out communicate [0] split [0] except pass return 0 | 13816 | def count_special_lines(word, filename, invert=False):
try:
cmd = ['grep', '-c', '-E']
if invert:
cmd.append('-v')
cmd.extend([word, filename])
out = subprocess.Popen(cmd, stdout=subprocess.PIPE)
return int(out.communicate()[0].split()[0])
except:
pass
return 0
| searching for special \'words\' using the grep tool
grep is used to speed up the searching and counting
The number of hits is returned. | searching for special words using the grep tool grep is used to speed up the searching and counting | Question:
What does this function do?
Code:
def count_special_lines(word, filename, invert=False):
try:
cmd = ['grep', '-c', '-E']
if invert:
cmd.append('-v')
cmd.extend([word, filename])
out = subprocess.Popen(cmd, stdout=subprocess.PIPE)
return int(out.communicate()[0].split()[0])
except:
pass
return 0
|
null | null | null | What does this function do? | def _compute_regularization(alpha, l1_ratio, regularization):
alpha_H = 0.0
alpha_W = 0.0
if (regularization in ('both', 'components')):
alpha_H = float(alpha)
if (regularization in ('both', 'transformation')):
alpha_W = float(alpha)
l1_reg_W = (alpha_W * l1_ratio)
l1_reg_H = (alpha_H * l1_ratio)
l2_reg_W = (alpha_W * (1.0 - l1_ratio))
l2_reg_H = (alpha_H * (1.0 - l1_ratio))
return (l1_reg_W, l1_reg_H, l2_reg_W, l2_reg_H)
| null | null | null | Compute L1 and L2 regularization coefficients for W and H | pcsd | def compute regularization alpha l1 ratio regularization alpha H = 0 0 alpha W = 0 0 if regularization in 'both' 'components' alpha H = float alpha if regularization in 'both' 'transformation' alpha W = float alpha l1 reg W = alpha W * l1 ratio l1 reg H = alpha H * l1 ratio l2 reg W = alpha W * 1 0 - l1 ratio l2 reg H = alpha H * 1 0 - l1 ratio return l1 reg W l1 reg H l2 reg W l2 reg H | 13818 | def _compute_regularization(alpha, l1_ratio, regularization):
alpha_H = 0.0
alpha_W = 0.0
if (regularization in ('both', 'components')):
alpha_H = float(alpha)
if (regularization in ('both', 'transformation')):
alpha_W = float(alpha)
l1_reg_W = (alpha_W * l1_ratio)
l1_reg_H = (alpha_H * l1_ratio)
l2_reg_W = (alpha_W * (1.0 - l1_ratio))
l2_reg_H = (alpha_H * (1.0 - l1_ratio))
return (l1_reg_W, l1_reg_H, l2_reg_W, l2_reg_H)
| Compute L1 and L2 regularization coefficients for W and H | compute l1 and l2 regularization coefficients for w and h | Question:
What does this function do?
Code:
def _compute_regularization(alpha, l1_ratio, regularization):
alpha_H = 0.0
alpha_W = 0.0
if (regularization in ('both', 'components')):
alpha_H = float(alpha)
if (regularization in ('both', 'transformation')):
alpha_W = float(alpha)
l1_reg_W = (alpha_W * l1_ratio)
l1_reg_H = (alpha_H * l1_ratio)
l2_reg_W = (alpha_W * (1.0 - l1_ratio))
l2_reg_H = (alpha_H * (1.0 - l1_ratio))
return (l1_reg_W, l1_reg_H, l2_reg_W, l2_reg_H)
|
null | null | null | What does this function do? | def follow_redirects(link, sites=None):
def follow(url):
return ((sites == None) or (urlparse.urlparse(url).hostname in sites))
class RedirectHandler(urllib2.HTTPRedirectHandler, ):
def __init__(self):
self.last_url = None
def redirect_request(self, req, fp, code, msg, hdrs, newurl):
self.last_url = newurl
if (not follow(newurl)):
return None
r = urllib2.HTTPRedirectHandler.redirect_request(self, req, fp, code, msg, hdrs, newurl)
r.get_method = (lambda : 'HEAD')
return r
if (not follow(link)):
return link
redirect_handler = RedirectHandler()
opener = urllib2.build_opener(redirect_handler)
req = urllib2.Request(link)
req.get_method = (lambda : 'HEAD')
try:
with contextlib.closing(opener.open(req, timeout=1)) as site:
return site.url
except:
return (redirect_handler.last_url if redirect_handler.last_url else link)
| null | null | null | Follow directs for the link as long as the redirects are on the given
sites and return the resolved link. | pcsd | def follow redirects link sites=None def follow url return sites == None or urlparse urlparse url hostname in sites class Redirect Handler urllib2 HTTP Redirect Handler def init self self last url = None def redirect request self req fp code msg hdrs newurl self last url = newurl if not follow newurl return None r = urllib2 HTTP Redirect Handler redirect request self req fp code msg hdrs newurl r get method = lambda 'HEAD' return r if not follow link return link redirect handler = Redirect Handler opener = urllib2 build opener redirect handler req = urllib2 Request link req get method = lambda 'HEAD' try with contextlib closing opener open req timeout=1 as site return site url except return redirect handler last url if redirect handler last url else link | 13833 | def follow_redirects(link, sites=None):
def follow(url):
return ((sites == None) or (urlparse.urlparse(url).hostname in sites))
class RedirectHandler(urllib2.HTTPRedirectHandler, ):
def __init__(self):
self.last_url = None
def redirect_request(self, req, fp, code, msg, hdrs, newurl):
self.last_url = newurl
if (not follow(newurl)):
return None
r = urllib2.HTTPRedirectHandler.redirect_request(self, req, fp, code, msg, hdrs, newurl)
r.get_method = (lambda : 'HEAD')
return r
if (not follow(link)):
return link
redirect_handler = RedirectHandler()
opener = urllib2.build_opener(redirect_handler)
req = urllib2.Request(link)
req.get_method = (lambda : 'HEAD')
try:
with contextlib.closing(opener.open(req, timeout=1)) as site:
return site.url
except:
return (redirect_handler.last_url if redirect_handler.last_url else link)
| Follow directs for the link as long as the redirects are on the given
sites and return the resolved link. | follow directs for the link as long as the redirects are on the given sites and return the resolved link . | Question:
What does this function do?
Code:
def follow_redirects(link, sites=None):
def follow(url):
return ((sites == None) or (urlparse.urlparse(url).hostname in sites))
class RedirectHandler(urllib2.HTTPRedirectHandler, ):
def __init__(self):
self.last_url = None
def redirect_request(self, req, fp, code, msg, hdrs, newurl):
self.last_url = newurl
if (not follow(newurl)):
return None
r = urllib2.HTTPRedirectHandler.redirect_request(self, req, fp, code, msg, hdrs, newurl)
r.get_method = (lambda : 'HEAD')
return r
if (not follow(link)):
return link
redirect_handler = RedirectHandler()
opener = urllib2.build_opener(redirect_handler)
req = urllib2.Request(link)
req.get_method = (lambda : 'HEAD')
try:
with contextlib.closing(opener.open(req, timeout=1)) as site:
return site.url
except:
return (redirect_handler.last_url if redirect_handler.last_url else link)
|
null | null | null | What does this function do? | def getFileTextInFileDirectory(fileInDirectory, fileName, readMode='r'):
absoluteFilePathInFileDirectory = os.path.join(os.path.dirname(fileInDirectory), fileName)
return getFileText(absoluteFilePathInFileDirectory, True, readMode)
| null | null | null | Get the entire text of a file in the directory of the file in directory. | pcsd | def get File Text In File Directory file In Directory file Name read Mode='r' absolute File Path In File Directory = os path join os path dirname file In Directory file Name return get File Text absolute File Path In File Directory True read Mode | 13839 | def getFileTextInFileDirectory(fileInDirectory, fileName, readMode='r'):
absoluteFilePathInFileDirectory = os.path.join(os.path.dirname(fileInDirectory), fileName)
return getFileText(absoluteFilePathInFileDirectory, True, readMode)
| Get the entire text of a file in the directory of the file in directory. | get the entire text of a file in the directory of the file in directory . | Question:
What does this function do?
Code:
def getFileTextInFileDirectory(fileInDirectory, fileName, readMode='r'):
absoluteFilePathInFileDirectory = os.path.join(os.path.dirname(fileInDirectory), fileName)
return getFileText(absoluteFilePathInFileDirectory, True, readMode)
|
null | null | null | What does this function do? | def main():
password = getpass()
for a_dict in (pynet1, pynet2, juniper_srx):
a_dict['password'] = password
a_dict['verbose'] = False
for a_device in (pynet1, pynet2):
net_connect = ConnectHandler(**a_device)
net_connect.send_config_from_file(config_file='config_file.txt')
output = net_connect.send_command('show run | inc logging')
print
print ('#' * 80)
print 'Device: {}:{}'.format(net_connect.ip, net_connect.port)
print
print output
print ('#' * 80)
print
| null | null | null | Use Netmiko to change the logging buffer size and to disable console logging
from a file for both pynet-rtr1 and pynet-rtr2 | pcsd | def main password = getpass for a dict in pynet1 pynet2 juniper srx a dict['password'] = password a dict['verbose'] = False for a device in pynet1 pynet2 net connect = Connect Handler **a device net connect send config from file config file='config file txt' output = net connect send command 'show run | inc logging' print print '#' * 80 print 'Device {} {}' format net connect ip net connect port print print output print '#' * 80 print | 13848 | def main():
password = getpass()
for a_dict in (pynet1, pynet2, juniper_srx):
a_dict['password'] = password
a_dict['verbose'] = False
for a_device in (pynet1, pynet2):
net_connect = ConnectHandler(**a_device)
net_connect.send_config_from_file(config_file='config_file.txt')
output = net_connect.send_command('show run | inc logging')
print
print ('#' * 80)
print 'Device: {}:{}'.format(net_connect.ip, net_connect.port)
print
print output
print ('#' * 80)
print
| Use Netmiko to change the logging buffer size and to disable console logging
from a file for both pynet-rtr1 and pynet-rtr2 | use netmiko to change the logging buffer size and to disable console logging from a file for both pynet - rtr1 and pynet - rtr2 | Question:
What does this function do?
Code:
def main():
password = getpass()
for a_dict in (pynet1, pynet2, juniper_srx):
a_dict['password'] = password
a_dict['verbose'] = False
for a_device in (pynet1, pynet2):
net_connect = ConnectHandler(**a_device)
net_connect.send_config_from_file(config_file='config_file.txt')
output = net_connect.send_command('show run | inc logging')
print
print ('#' * 80)
print 'Device: {}:{}'.format(net_connect.ip, net_connect.port)
print
print output
print ('#' * 80)
print
|
null | null | null | What does this function do? | def extract_live_config(config, plugins):
live_config = config._sections['live_config'].copy()
del live_config['__name__']
parsed = ConfigValueParser(live_config)
parsed.add_spec(Globals.live_config_spec)
for plugin in plugins:
parsed.add_spec(plugin.live_config)
return parsed
| null | null | null | Gets live config out of INI file and validates it according to spec. | pcsd | def extract live config config plugins live config = config sections['live config'] copy del live config[' name '] parsed = Config Value Parser live config parsed add spec Globals live config spec for plugin in plugins parsed add spec plugin live config return parsed | 13863 | def extract_live_config(config, plugins):
live_config = config._sections['live_config'].copy()
del live_config['__name__']
parsed = ConfigValueParser(live_config)
parsed.add_spec(Globals.live_config_spec)
for plugin in plugins:
parsed.add_spec(plugin.live_config)
return parsed
| Gets live config out of INI file and validates it according to spec. | gets live config out of ini file and validates it according to spec . | Question:
What does this function do?
Code:
def extract_live_config(config, plugins):
live_config = config._sections['live_config'].copy()
del live_config['__name__']
parsed = ConfigValueParser(live_config)
parsed.add_spec(Globals.live_config_spec)
for plugin in plugins:
parsed.add_spec(plugin.live_config)
return parsed
|
null | null | null | What does this function do? | def get_cluster_addr_for_job_submission():
if is_yarn():
if get_yarn().LOGICAL_NAME.get():
return get_yarn().LOGICAL_NAME.get()
conf = get_cluster_conf_for_job_submission()
if (conf is None):
return None
return ('%s:%s' % (conf.HOST.get(), conf.PORT.get()))
| null | null | null | Check the \'submit_to\' for each MR/Yarn cluster, and return the logical name or host:port of first one that enables submission. | pcsd | def get cluster addr for job submission if is yarn if get yarn LOGICAL NAME get return get yarn LOGICAL NAME get conf = get cluster conf for job submission if conf is None return None return '%s %s' % conf HOST get conf PORT get | 13864 | def get_cluster_addr_for_job_submission():
if is_yarn():
if get_yarn().LOGICAL_NAME.get():
return get_yarn().LOGICAL_NAME.get()
conf = get_cluster_conf_for_job_submission()
if (conf is None):
return None
return ('%s:%s' % (conf.HOST.get(), conf.PORT.get()))
| Check the \'submit_to\' for each MR/Yarn cluster, and return the logical name or host:port of first one that enables submission. | check the submit _ to for each mr / yarn cluster , and return the logical name or host : port of first one that enables submission . | Question:
What does this function do?
Code:
def get_cluster_addr_for_job_submission():
if is_yarn():
if get_yarn().LOGICAL_NAME.get():
return get_yarn().LOGICAL_NAME.get()
conf = get_cluster_conf_for_job_submission()
if (conf is None):
return None
return ('%s:%s' % (conf.HOST.get(), conf.PORT.get()))
|
null | null | null | What does this function do? | @before.all
def start_video_server():
video_source_dir = '{}/data/video'.format(settings.TEST_ROOT)
video_server = VideoSourceHttpService(port_num=settings.VIDEO_SOURCE_PORT)
video_server.config['root_dir'] = video_source_dir
world.video_source = video_server
| null | null | null | Serve the HTML5 Video Sources from a local port | pcsd | @before all def start video server video source dir = '{}/data/video' format settings TEST ROOT video server = Video Source Http Service port num=settings VIDEO SOURCE PORT video server config['root dir'] = video source dir world video source = video server | 13867 | @before.all
def start_video_server():
video_source_dir = '{}/data/video'.format(settings.TEST_ROOT)
video_server = VideoSourceHttpService(port_num=settings.VIDEO_SOURCE_PORT)
video_server.config['root_dir'] = video_source_dir
world.video_source = video_server
| Serve the HTML5 Video Sources from a local port | serve the html5 video sources from a local port | Question:
What does this function do?
Code:
@before.all
def start_video_server():
video_source_dir = '{}/data/video'.format(settings.TEST_ROOT)
video_server = VideoSourceHttpService(port_num=settings.VIDEO_SOURCE_PORT)
video_server.config['root_dir'] = video_source_dir
world.video_source = video_server
|
null | null | null | What does this function do? | def reverse_order(order):
items = []
for item in order.split(','):
item = item.lower().split()
direction = ('asc' if (item[1:] == ['desc']) else 'desc')
items.append(('%s %s' % (item[0], direction)))
return ', '.join(items)
| null | null | null | Reverse an ORDER BY clause | pcsd | def reverse order order items = [] for item in order split ' ' item = item lower split direction = 'asc' if item[1 ] == ['desc'] else 'desc' items append '%s %s' % item[0] direction return ' ' join items | 13880 | def reverse_order(order):
items = []
for item in order.split(','):
item = item.lower().split()
direction = ('asc' if (item[1:] == ['desc']) else 'desc')
items.append(('%s %s' % (item[0], direction)))
return ', '.join(items)
| Reverse an ORDER BY clause | reverse an order by clause | Question:
What does this function do?
Code:
def reverse_order(order):
items = []
for item in order.split(','):
item = item.lower().split()
direction = ('asc' if (item[1:] == ['desc']) else 'desc')
items.append(('%s %s' % (item[0], direction)))
return ', '.join(items)
|
null | null | null | What does this function do? | def _pdfjs_version():
try:
(pdfjs_file, file_path) = pdfjs.get_pdfjs_res_and_path('build/pdf.js')
except pdfjs.PDFJSNotFound:
return 'no'
else:
pdfjs_file = pdfjs_file.decode('utf-8')
version_re = re.compile("^(PDFJS\\.version|var pdfjsVersion) = '([^']+)';$", re.MULTILINE)
match = version_re.search(pdfjs_file)
if (not match):
pdfjs_version = 'unknown'
else:
pdfjs_version = match.group(2)
if (file_path is None):
file_path = 'bundled'
return '{} ({})'.format(pdfjs_version, file_path)
| null | null | null | Get the pdf.js version.
Return:
A string with the version number. | pcsd | def pdfjs version try pdfjs file file path = pdfjs get pdfjs res and path 'build/pdf js' except pdfjs PDFJS Not Found return 'no' else pdfjs file = pdfjs file decode 'utf-8' version re = re compile "^ PDFJS\\ version|var pdfjs Version = ' [^']+ ' $" re MULTILINE match = version re search pdfjs file if not match pdfjs version = 'unknown' else pdfjs version = match group 2 if file path is None file path = 'bundled' return '{} {} ' format pdfjs version file path | 13883 | def _pdfjs_version():
try:
(pdfjs_file, file_path) = pdfjs.get_pdfjs_res_and_path('build/pdf.js')
except pdfjs.PDFJSNotFound:
return 'no'
else:
pdfjs_file = pdfjs_file.decode('utf-8')
version_re = re.compile("^(PDFJS\\.version|var pdfjsVersion) = '([^']+)';$", re.MULTILINE)
match = version_re.search(pdfjs_file)
if (not match):
pdfjs_version = 'unknown'
else:
pdfjs_version = match.group(2)
if (file_path is None):
file_path = 'bundled'
return '{} ({})'.format(pdfjs_version, file_path)
| Get the pdf.js version.
Return:
A string with the version number. | get the pdf . js version . | Question:
What does this function do?
Code:
def _pdfjs_version():
try:
(pdfjs_file, file_path) = pdfjs.get_pdfjs_res_and_path('build/pdf.js')
except pdfjs.PDFJSNotFound:
return 'no'
else:
pdfjs_file = pdfjs_file.decode('utf-8')
version_re = re.compile("^(PDFJS\\.version|var pdfjsVersion) = '([^']+)';$", re.MULTILINE)
match = version_re.search(pdfjs_file)
if (not match):
pdfjs_version = 'unknown'
else:
pdfjs_version = match.group(2)
if (file_path is None):
file_path = 'bundled'
return '{} ({})'.format(pdfjs_version, file_path)
|
null | null | null | What does this function do? | def init():
proxy_factory = ProxyFactory()
objreg.register('proxy-factory', proxy_factory)
QNetworkProxyFactory.setApplicationProxyFactory(proxy_factory)
| null | null | null | Set the application wide proxy factory. | pcsd | def init proxy factory = Proxy Factory objreg register 'proxy-factory' proxy factory Q Network Proxy Factory set Application Proxy Factory proxy factory | 13890 | def init():
proxy_factory = ProxyFactory()
objreg.register('proxy-factory', proxy_factory)
QNetworkProxyFactory.setApplicationProxyFactory(proxy_factory)
| Set the application wide proxy factory. | set the application wide proxy factory . | Question:
What does this function do?
Code:
def init():
proxy_factory = ProxyFactory()
objreg.register('proxy-factory', proxy_factory)
QNetworkProxyFactory.setApplicationProxyFactory(proxy_factory)
|
null | null | null | What does this function do? | def CORREL(ds1, ds2, count, timeperiod=(- (2 ** 31))):
data1 = value_ds_to_numpy(ds1, count)
if (data1 is None):
return None
data2 = value_ds_to_numpy(ds2, count)
if (data2 is None):
return None
return talib.CORREL(data1, data2, timeperiod)
| null | null | null | Pearson\'s Correlation Coefficient (r) | pcsd | def CORREL ds1 ds2 count timeperiod= - 2 ** 31 data1 = value ds to numpy ds1 count if data1 is None return None data2 = value ds to numpy ds2 count if data2 is None return None return talib CORREL data1 data2 timeperiod | 13893 | def CORREL(ds1, ds2, count, timeperiod=(- (2 ** 31))):
data1 = value_ds_to_numpy(ds1, count)
if (data1 is None):
return None
data2 = value_ds_to_numpy(ds2, count)
if (data2 is None):
return None
return talib.CORREL(data1, data2, timeperiod)
| Pearson\'s Correlation Coefficient (r) | pearsons correlation coefficient ( r ) | Question:
What does this function do?
Code:
def CORREL(ds1, ds2, count, timeperiod=(- (2 ** 31))):
data1 = value_ds_to_numpy(ds1, count)
if (data1 is None):
return None
data2 = value_ds_to_numpy(ds2, count)
if (data2 is None):
return None
return talib.CORREL(data1, data2, timeperiod)
|
null | null | null | What does this function do? | def log_to_stderr(level=None):
global _log_to_stderr
import logging
logger = get_logger()
formatter = logging.Formatter(DEFAULT_LOGGING_FORMAT)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)
if level:
logger.setLevel(level)
_log_to_stderr = True
return _logger
| null | null | null | Turn on logging and add a handler which prints to stderr | pcsd | def log to stderr level=None global log to stderr import logging logger = get logger formatter = logging Formatter DEFAULT LOGGING FORMAT handler = logging Stream Handler handler set Formatter formatter logger add Handler handler if level logger set Level level log to stderr = True return logger | 13895 | def log_to_stderr(level=None):
global _log_to_stderr
import logging
logger = get_logger()
formatter = logging.Formatter(DEFAULT_LOGGING_FORMAT)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)
if level:
logger.setLevel(level)
_log_to_stderr = True
return _logger
| Turn on logging and add a handler which prints to stderr | turn on logging and add a handler which prints to stderr | Question:
What does this function do?
Code:
def log_to_stderr(level=None):
global _log_to_stderr
import logging
logger = get_logger()
formatter = logging.Formatter(DEFAULT_LOGGING_FORMAT)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)
if level:
logger.setLevel(level)
_log_to_stderr = True
return _logger
|
null | null | null | What does this function do? | def save_minions(jid, minions, syndic_id=None):
pass
| null | null | null | Included for API consistency | pcsd | def save minions jid minions syndic id=None pass | 13897 | def save_minions(jid, minions, syndic_id=None):
pass
| Included for API consistency | included for api consistency | Question:
What does this function do?
Code:
def save_minions(jid, minions, syndic_id=None):
pass
|
null | null | null | What does this function do? | @ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@coach_dashboard
def set_grading_policy(request, course, ccx=None):
if (not ccx):
raise Http404
override_field_for_ccx(ccx, course, 'grading_policy', json.loads(request.POST['policy']))
responses = SignalHandler.course_published.send(sender=ccx, course_key=CCXLocator.from_course_locator(course.id, unicode(ccx.id)))
for (rec, response) in responses:
log.info('Signal fired when course is published. Receiver: %s. Response: %s', rec, response)
url = reverse('ccx_coach_dashboard', kwargs={'course_id': CCXLocator.from_course_locator(course.id, unicode(ccx.id))})
return redirect(url)
| null | null | null | Set grading policy for the CCX. | pcsd | @ensure csrf cookie @cache control no cache=True no store=True must revalidate=True @coach dashboard def set grading policy request course ccx=None if not ccx raise Http404 override field for ccx ccx course 'grading policy' json loads request POST['policy'] responses = Signal Handler course published send sender=ccx course key=CCX Locator from course locator course id unicode ccx id for rec response in responses log info 'Signal fired when course is published Receiver %s Response %s' rec response url = reverse 'ccx coach dashboard' kwargs={'course id' CCX Locator from course locator course id unicode ccx id } return redirect url | 13898 | @ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@coach_dashboard
def set_grading_policy(request, course, ccx=None):
if (not ccx):
raise Http404
override_field_for_ccx(ccx, course, 'grading_policy', json.loads(request.POST['policy']))
responses = SignalHandler.course_published.send(sender=ccx, course_key=CCXLocator.from_course_locator(course.id, unicode(ccx.id)))
for (rec, response) in responses:
log.info('Signal fired when course is published. Receiver: %s. Response: %s', rec, response)
url = reverse('ccx_coach_dashboard', kwargs={'course_id': CCXLocator.from_course_locator(course.id, unicode(ccx.id))})
return redirect(url)
| Set grading policy for the CCX. | set grading policy for the ccx . | Question:
What does this function do?
Code:
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@coach_dashboard
def set_grading_policy(request, course, ccx=None):
if (not ccx):
raise Http404
override_field_for_ccx(ccx, course, 'grading_policy', json.loads(request.POST['policy']))
responses = SignalHandler.course_published.send(sender=ccx, course_key=CCXLocator.from_course_locator(course.id, unicode(ccx.id)))
for (rec, response) in responses:
log.info('Signal fired when course is published. Receiver: %s. Response: %s', rec, response)
url = reverse('ccx_coach_dashboard', kwargs={'course_id': CCXLocator.from_course_locator(course.id, unicode(ccx.id))})
return redirect(url)
|
null | null | null | What does this function do? | def getNewDerivation(elementNode, prefix, sideLength):
return RotateDerivation(elementNode, prefix)
| null | null | null | Get new derivation. | pcsd | def get New Derivation element Node prefix side Length return Rotate Derivation element Node prefix | 13908 | def getNewDerivation(elementNode, prefix, sideLength):
return RotateDerivation(elementNode, prefix)
| Get new derivation. | get new derivation . | Question:
What does this function do?
Code:
def getNewDerivation(elementNode, prefix, sideLength):
return RotateDerivation(elementNode, prefix)
|
null | null | null | What does this function do? | def _CompileFilters(config):
filters = []
for filter_type in iterkeys(config):
compiler = FILTER_COMPILERS.get(filter_type)
if (compiler is not None):
for filter_config in _ListOf(config[filter_type]):
compiledFilter = compiler(filter_config)
filters.append(compiledFilter)
return filters
| null | null | null | Given a filter config dictionary, return a list of compiled filters | pcsd | def Compile Filters config filters = [] for filter type in iterkeys config compiler = FILTER COMPILERS get filter type if compiler is not None for filter config in List Of config[filter type] compiled Filter = compiler filter config filters append compiled Filter return filters | 13910 | def _CompileFilters(config):
filters = []
for filter_type in iterkeys(config):
compiler = FILTER_COMPILERS.get(filter_type)
if (compiler is not None):
for filter_config in _ListOf(config[filter_type]):
compiledFilter = compiler(filter_config)
filters.append(compiledFilter)
return filters
| Given a filter config dictionary, return a list of compiled filters | given a filter config dictionary , return a list of compiled filters | Question:
What does this function do?
Code:
def _CompileFilters(config):
filters = []
for filter_type in iterkeys(config):
compiler = FILTER_COMPILERS.get(filter_type)
if (compiler is not None):
for filter_config in _ListOf(config[filter_type]):
compiledFilter = compiler(filter_config)
filters.append(compiledFilter)
return filters
|
null | null | null | What does this function do? | def import_set(dset, in_stream, headers=True):
return import_set_wrapper(dset, in_stream, headers=headers, delimiter=DELIMITER)
| null | null | null | Returns dataset from TSV stream. | pcsd | def import set dset in stream headers=True return import set wrapper dset in stream headers=headers delimiter=DELIMITER | 13916 | def import_set(dset, in_stream, headers=True):
return import_set_wrapper(dset, in_stream, headers=headers, delimiter=DELIMITER)
| Returns dataset from TSV stream. | returns dataset from tsv stream . | Question:
What does this function do?
Code:
def import_set(dset, in_stream, headers=True):
return import_set_wrapper(dset, in_stream, headers=headers, delimiter=DELIMITER)
|
null | null | null | What does this function do? | def list_url_unsafe_chars(name):
reserved_chars = ''
for i in name:
if (i in URL_RESERVED_CHARS):
reserved_chars += i
return reserved_chars
| null | null | null | Return a list of the reserved characters. | pcsd | def list url unsafe chars name reserved chars = '' for i in name if i in URL RESERVED CHARS reserved chars += i return reserved chars | 13917 | def list_url_unsafe_chars(name):
reserved_chars = ''
for i in name:
if (i in URL_RESERVED_CHARS):
reserved_chars += i
return reserved_chars
| Return a list of the reserved characters. | return a list of the reserved characters . | Question:
What does this function do?
Code:
def list_url_unsafe_chars(name):
reserved_chars = ''
for i in name:
if (i in URL_RESERVED_CHARS):
reserved_chars += i
return reserved_chars
|
null | null | null | What does this function do? | def getRadialPath(begin, end, path, segmentCenter):
beginComplex = begin.dropAxis()
endComplex = end.dropAxis()
segmentCenterComplex = segmentCenter.dropAxis()
beginMinusCenterComplex = (beginComplex - segmentCenterComplex)
endMinusCenterComplex = (endComplex - segmentCenterComplex)
beginMinusCenterComplexRadius = abs(beginMinusCenterComplex)
endMinusCenterComplexRadius = abs(endMinusCenterComplex)
if ((beginMinusCenterComplexRadius == 0.0) or (endMinusCenterComplexRadius == 0.0)):
return [begin]
beginMinusCenterComplex /= beginMinusCenterComplexRadius
endMinusCenterComplex /= endMinusCenterComplexRadius
angleDifference = euclidean.getAngleDifferenceByComplex(endMinusCenterComplex, beginMinusCenterComplex)
radialPath = []
for point in path:
weightEnd = point.x
weightBegin = (1.0 - weightEnd)
weightedRadius = ((beginMinusCenterComplexRadius * weightBegin) + ((endMinusCenterComplexRadius * weightEnd) * (1.0 + point.y)))
radialComplex = ((weightedRadius * euclidean.getWiddershinsUnitPolar((angleDifference * point.x))) * beginMinusCenterComplex)
polygonPoint = (segmentCenter + Vector3(radialComplex.real, radialComplex.imag, point.z))
radialPath.append(polygonPoint)
return radialPath
| null | null | null | Get radial path. | pcsd | def get Radial Path begin end path segment Center begin Complex = begin drop Axis end Complex = end drop Axis segment Center Complex = segment Center drop Axis begin Minus Center Complex = begin Complex - segment Center Complex end Minus Center Complex = end Complex - segment Center Complex begin Minus Center Complex Radius = abs begin Minus Center Complex end Minus Center Complex Radius = abs end Minus Center Complex if begin Minus Center Complex Radius == 0 0 or end Minus Center Complex Radius == 0 0 return [begin] begin Minus Center Complex /= begin Minus Center Complex Radius end Minus Center Complex /= end Minus Center Complex Radius angle Difference = euclidean get Angle Difference By Complex end Minus Center Complex begin Minus Center Complex radial Path = [] for point in path weight End = point x weight Begin = 1 0 - weight End weighted Radius = begin Minus Center Complex Radius * weight Begin + end Minus Center Complex Radius * weight End * 1 0 + point y radial Complex = weighted Radius * euclidean get Widdershins Unit Polar angle Difference * point x * begin Minus Center Complex polygon Point = segment Center + Vector3 radial Complex real radial Complex imag point z radial Path append polygon Point return radial Path | 13919 | def getRadialPath(begin, end, path, segmentCenter):
beginComplex = begin.dropAxis()
endComplex = end.dropAxis()
segmentCenterComplex = segmentCenter.dropAxis()
beginMinusCenterComplex = (beginComplex - segmentCenterComplex)
endMinusCenterComplex = (endComplex - segmentCenterComplex)
beginMinusCenterComplexRadius = abs(beginMinusCenterComplex)
endMinusCenterComplexRadius = abs(endMinusCenterComplex)
if ((beginMinusCenterComplexRadius == 0.0) or (endMinusCenterComplexRadius == 0.0)):
return [begin]
beginMinusCenterComplex /= beginMinusCenterComplexRadius
endMinusCenterComplex /= endMinusCenterComplexRadius
angleDifference = euclidean.getAngleDifferenceByComplex(endMinusCenterComplex, beginMinusCenterComplex)
radialPath = []
for point in path:
weightEnd = point.x
weightBegin = (1.0 - weightEnd)
weightedRadius = ((beginMinusCenterComplexRadius * weightBegin) + ((endMinusCenterComplexRadius * weightEnd) * (1.0 + point.y)))
radialComplex = ((weightedRadius * euclidean.getWiddershinsUnitPolar((angleDifference * point.x))) * beginMinusCenterComplex)
polygonPoint = (segmentCenter + Vector3(radialComplex.real, radialComplex.imag, point.z))
radialPath.append(polygonPoint)
return radialPath
| Get radial path. | get radial path . | Question:
What does this function do?
Code:
def getRadialPath(begin, end, path, segmentCenter):
beginComplex = begin.dropAxis()
endComplex = end.dropAxis()
segmentCenterComplex = segmentCenter.dropAxis()
beginMinusCenterComplex = (beginComplex - segmentCenterComplex)
endMinusCenterComplex = (endComplex - segmentCenterComplex)
beginMinusCenterComplexRadius = abs(beginMinusCenterComplex)
endMinusCenterComplexRadius = abs(endMinusCenterComplex)
if ((beginMinusCenterComplexRadius == 0.0) or (endMinusCenterComplexRadius == 0.0)):
return [begin]
beginMinusCenterComplex /= beginMinusCenterComplexRadius
endMinusCenterComplex /= endMinusCenterComplexRadius
angleDifference = euclidean.getAngleDifferenceByComplex(endMinusCenterComplex, beginMinusCenterComplex)
radialPath = []
for point in path:
weightEnd = point.x
weightBegin = (1.0 - weightEnd)
weightedRadius = ((beginMinusCenterComplexRadius * weightBegin) + ((endMinusCenterComplexRadius * weightEnd) * (1.0 + point.y)))
radialComplex = ((weightedRadius * euclidean.getWiddershinsUnitPolar((angleDifference * point.x))) * beginMinusCenterComplex)
polygonPoint = (segmentCenter + Vector3(radialComplex.real, radialComplex.imag, point.z))
radialPath.append(polygonPoint)
return radialPath
|
null | null | null | What does this function do? | def _get_context(keyspaces, connections):
if keyspaces:
if (not isinstance(keyspaces, (list, tuple))):
raise ValueError('keyspaces must be a list or a tuple.')
if connections:
if (not isinstance(connections, (list, tuple))):
raise ValueError('connections must be a list or a tuple.')
keyspaces = (keyspaces if keyspaces else [None])
connections = (connections if connections else [None])
return product(connections, keyspaces)
| null | null | null | Return all the execution contexts | pcsd | def get context keyspaces connections if keyspaces if not isinstance keyspaces list tuple raise Value Error 'keyspaces must be a list or a tuple ' if connections if not isinstance connections list tuple raise Value Error 'connections must be a list or a tuple ' keyspaces = keyspaces if keyspaces else [None] connections = connections if connections else [None] return product connections keyspaces | 13922 | def _get_context(keyspaces, connections):
if keyspaces:
if (not isinstance(keyspaces, (list, tuple))):
raise ValueError('keyspaces must be a list or a tuple.')
if connections:
if (not isinstance(connections, (list, tuple))):
raise ValueError('connections must be a list or a tuple.')
keyspaces = (keyspaces if keyspaces else [None])
connections = (connections if connections else [None])
return product(connections, keyspaces)
| Return all the execution contexts | return all the execution contexts | Question:
What does this function do?
Code:
def _get_context(keyspaces, connections):
if keyspaces:
if (not isinstance(keyspaces, (list, tuple))):
raise ValueError('keyspaces must be a list or a tuple.')
if connections:
if (not isinstance(connections, (list, tuple))):
raise ValueError('connections must be a list or a tuple.')
keyspaces = (keyspaces if keyspaces else [None])
connections = (connections if connections else [None])
return product(connections, keyspaces)
|
null | null | null | What does this function do? | def sort_thing_ids_by_data_value(type_id, thing_ids, value_name, limit=None, desc=False):
(thing_table, data_table) = get_thing_table(type_id)
join = thing_table.join(data_table, (data_table.c.thing_id == thing_table.c.thing_id))
query = sa.select([thing_table.c.thing_id], sa.and_(thing_table.c.thing_id.in_(thing_ids), (thing_table.c.deleted == False), (thing_table.c.spam == False), (data_table.c.key == value_name))).select_from(join)
sort_column = data_table.c.value
if desc:
sort_column = sa.desc(sort_column)
query = query.order_by(sort_column)
if limit:
query = query.limit(limit)
rows = query.execute()
return Results(rows, (lambda row: row.thing_id))
| null | null | null | Order thing_ids by the value of a data column. | pcsd | def sort thing ids by data value type id thing ids value name limit=None desc=False thing table data table = get thing table type id join = thing table join data table data table c thing id == thing table c thing id query = sa select [thing table c thing id] sa and thing table c thing id in thing ids thing table c deleted == False thing table c spam == False data table c key == value name select from join sort column = data table c value if desc sort column = sa desc sort column query = query order by sort column if limit query = query limit limit rows = query execute return Results rows lambda row row thing id | 13932 | def sort_thing_ids_by_data_value(type_id, thing_ids, value_name, limit=None, desc=False):
(thing_table, data_table) = get_thing_table(type_id)
join = thing_table.join(data_table, (data_table.c.thing_id == thing_table.c.thing_id))
query = sa.select([thing_table.c.thing_id], sa.and_(thing_table.c.thing_id.in_(thing_ids), (thing_table.c.deleted == False), (thing_table.c.spam == False), (data_table.c.key == value_name))).select_from(join)
sort_column = data_table.c.value
if desc:
sort_column = sa.desc(sort_column)
query = query.order_by(sort_column)
if limit:
query = query.limit(limit)
rows = query.execute()
return Results(rows, (lambda row: row.thing_id))
| Order thing_ids by the value of a data column. | order thing _ ids by the value of a data column . | Question:
What does this function do?
Code:
def sort_thing_ids_by_data_value(type_id, thing_ids, value_name, limit=None, desc=False):
(thing_table, data_table) = get_thing_table(type_id)
join = thing_table.join(data_table, (data_table.c.thing_id == thing_table.c.thing_id))
query = sa.select([thing_table.c.thing_id], sa.and_(thing_table.c.thing_id.in_(thing_ids), (thing_table.c.deleted == False), (thing_table.c.spam == False), (data_table.c.key == value_name))).select_from(join)
sort_column = data_table.c.value
if desc:
sort_column = sa.desc(sort_column)
query = query.order_by(sort_column)
if limit:
query = query.limit(limit)
rows = query.execute()
return Results(rows, (lambda row: row.thing_id))
|
null | null | null | What does this function do? | @login_required
@require_http_methods(['GET', 'POST'])
def delete_avatar(request):
try:
user_profile = Profile.objects.get(user=request.user)
except Profile.DoesNotExist:
user_profile = Profile.objects.create(user=request.user)
if (request.method == 'POST'):
if user_profile.avatar:
user_profile.avatar.delete()
return HttpResponseRedirect(reverse('users.edit_my_profile'))
return render(request, 'users/confirm_avatar_delete.html', {'profile': user_profile})
| null | null | null | Delete user avatar. | pcsd | @login required @require http methods ['GET' 'POST'] def delete avatar request try user profile = Profile objects get user=request user except Profile Does Not Exist user profile = Profile objects create user=request user if request method == 'POST' if user profile avatar user profile avatar delete return Http Response Redirect reverse 'users edit my profile' return render request 'users/confirm avatar delete html' {'profile' user profile} | 13934 | @login_required
@require_http_methods(['GET', 'POST'])
def delete_avatar(request):
try:
user_profile = Profile.objects.get(user=request.user)
except Profile.DoesNotExist:
user_profile = Profile.objects.create(user=request.user)
if (request.method == 'POST'):
if user_profile.avatar:
user_profile.avatar.delete()
return HttpResponseRedirect(reverse('users.edit_my_profile'))
return render(request, 'users/confirm_avatar_delete.html', {'profile': user_profile})
| Delete user avatar. | delete user avatar . | Question:
What does this function do?
Code:
@login_required
@require_http_methods(['GET', 'POST'])
def delete_avatar(request):
try:
user_profile = Profile.objects.get(user=request.user)
except Profile.DoesNotExist:
user_profile = Profile.objects.create(user=request.user)
if (request.method == 'POST'):
if user_profile.avatar:
user_profile.avatar.delete()
return HttpResponseRedirect(reverse('users.edit_my_profile'))
return render(request, 'users/confirm_avatar_delete.html', {'profile': user_profile})
|
null | null | null | What does this function do? | def register_models(app_label, *models):
for model in models:
model_name = model._meta.object_name.lower()
model_dict = _app_models.setdefault(app_label, {})
if model_dict.has_key(model_name):
fname1 = os.path.abspath(sys.modules[model.__module__].__file__)
fname2 = os.path.abspath(sys.modules[model_dict[model_name].__module__].__file__)
if (os.path.splitext(fname1)[0] == os.path.splitext(fname2)[0]):
continue
model_dict[model_name] = model
| null | null | null | Register a set of models as belonging to an app. | pcsd | def register models app label *models for model in models model name = model meta object name lower model dict = app models setdefault app label {} if model dict has key model name fname1 = os path abspath sys modules[model module ] file fname2 = os path abspath sys modules[model dict[model name] module ] file if os path splitext fname1 [0] == os path splitext fname2 [0] continue model dict[model name] = model | 13949 | def register_models(app_label, *models):
for model in models:
model_name = model._meta.object_name.lower()
model_dict = _app_models.setdefault(app_label, {})
if model_dict.has_key(model_name):
fname1 = os.path.abspath(sys.modules[model.__module__].__file__)
fname2 = os.path.abspath(sys.modules[model_dict[model_name].__module__].__file__)
if (os.path.splitext(fname1)[0] == os.path.splitext(fname2)[0]):
continue
model_dict[model_name] = model
| Register a set of models as belonging to an app. | register a set of models as belonging to an app . | Question:
What does this function do?
Code:
def register_models(app_label, *models):
for model in models:
model_name = model._meta.object_name.lower()
model_dict = _app_models.setdefault(app_label, {})
if model_dict.has_key(model_name):
fname1 = os.path.abspath(sys.modules[model.__module__].__file__)
fname2 = os.path.abspath(sys.modules[model_dict[model_name].__module__].__file__)
if (os.path.splitext(fname1)[0] == os.path.splitext(fname2)[0]):
continue
model_dict[model_name] = model
|
null | null | null | What does this function do? | def backends(request, user):
storage = module_member(get_helper('STORAGE'))
return {'backends': user_backends_data(user, get_helper('AUTHENTICATION_BACKENDS'), storage)}
| null | null | null | Load Social Auth current user data to context under the key \'backends\'.
Will return the output of social.backends.utils.user_backends_data. | pcsd | def backends request user storage = module member get helper 'STORAGE' return {'backends' user backends data user get helper 'AUTHENTICATION BACKENDS' storage } | 13953 | def backends(request, user):
storage = module_member(get_helper('STORAGE'))
return {'backends': user_backends_data(user, get_helper('AUTHENTICATION_BACKENDS'), storage)}
| Load Social Auth current user data to context under the key \'backends\'.
Will return the output of social.backends.utils.user_backends_data. | load social auth current user data to context under the key backends . | Question:
What does this function do?
Code:
def backends(request, user):
storage = module_member(get_helper('STORAGE'))
return {'backends': user_backends_data(user, get_helper('AUTHENTICATION_BACKENDS'), storage)}
|
null | null | null | What does this function do? | def GetFieldInDocument(document, field_name):
for f in document.field_list():
if (f.name() == field_name):
return f
return None
| null | null | null | Find and return the first field with the provided name in the document. | pcsd | def Get Field In Document document field name for f in document field list if f name == field name return f return None | 13959 | def GetFieldInDocument(document, field_name):
for f in document.field_list():
if (f.name() == field_name):
return f
return None
| Find and return the first field with the provided name in the document. | find and return the first field with the provided name in the document . | Question:
What does this function do?
Code:
def GetFieldInDocument(document, field_name):
for f in document.field_list():
if (f.name() == field_name):
return f
return None
|
null | null | null | What does this function do? | def md5sum_is_current(src_file):
src_md5 = get_md5sum(src_file)
src_md5_file = (src_file + '.md5')
if os.path.exists(src_md5_file):
with open(src_md5_file, 'r') as file_checksum:
ref_md5 = file_checksum.read()
return (src_md5 == ref_md5)
return False
| null | null | null | Checks whether src_file has the same md5 hash as the one on disk | pcsd | def md5sum is current src file src md5 = get md5sum src file src md5 file = src file + ' md5' if os path exists src md5 file with open src md5 file 'r' as file checksum ref md5 = file checksum read return src md5 == ref md5 return False | 13961 | def md5sum_is_current(src_file):
src_md5 = get_md5sum(src_file)
src_md5_file = (src_file + '.md5')
if os.path.exists(src_md5_file):
with open(src_md5_file, 'r') as file_checksum:
ref_md5 = file_checksum.read()
return (src_md5 == ref_md5)
return False
| Checks whether src_file has the same md5 hash as the one on disk | checks whether src _ file has the same md5 hash as the one on disk | Question:
What does this function do?
Code:
def md5sum_is_current(src_file):
src_md5 = get_md5sum(src_file)
src_md5_file = (src_file + '.md5')
if os.path.exists(src_md5_file):
with open(src_md5_file, 'r') as file_checksum:
ref_md5 = file_checksum.read()
return (src_md5 == ref_md5)
return False
|
null | null | null | What does this function do? | def running(name, sig=None):
return status(name).get(name, False)
| null | null | null | Return whether this service is running. | pcsd | def running name sig=None return status name get name False | 13965 | def running(name, sig=None):
return status(name).get(name, False)
| Return whether this service is running. | return whether this service is running . | Question:
What does this function do?
Code:
def running(name, sig=None):
return status(name).get(name, False)
|
null | null | null | What does this function do? | def enabled(name, **kwargs):
ret = {'name': name, 'result': True, 'changes': {}, 'comment': []}
current_beacons = __salt__['beacons.list'](show_all=True, return_yaml=False)
if (name in current_beacons):
if (('test' in __opts__) and __opts__['test']):
kwargs['test'] = True
result = __salt__['beacons.enable_beacon'](name, **kwargs)
ret['comment'].append(result['comment'])
else:
result = __salt__['beacons.enable_job'](name, **kwargs)
if (not result['result']):
ret['result'] = result['result']
ret['comment'] = result['comment']
return ret
else:
ret['comment'].append('Enabled {0} from beacons'.format(name))
else:
ret['comment'].append('{0} not a configured beacon'.format(name))
ret['comment'] = '\n'.join(ret['comment'])
return ret
| null | null | null | Enable a beacon.
name
The name of the beacon to enable. | pcsd | def enabled name **kwargs ret = {'name' name 'result' True 'changes' {} 'comment' []} current beacons = salt ['beacons list'] show all=True return yaml=False if name in current beacons if 'test' in opts and opts ['test'] kwargs['test'] = True result = salt ['beacons enable beacon'] name **kwargs ret['comment'] append result['comment'] else result = salt ['beacons enable job'] name **kwargs if not result['result'] ret['result'] = result['result'] ret['comment'] = result['comment'] return ret else ret['comment'] append 'Enabled {0} from beacons' format name else ret['comment'] append '{0} not a configured beacon' format name ret['comment'] = ' ' join ret['comment'] return ret | 13974 | def enabled(name, **kwargs):
ret = {'name': name, 'result': True, 'changes': {}, 'comment': []}
current_beacons = __salt__['beacons.list'](show_all=True, return_yaml=False)
if (name in current_beacons):
if (('test' in __opts__) and __opts__['test']):
kwargs['test'] = True
result = __salt__['beacons.enable_beacon'](name, **kwargs)
ret['comment'].append(result['comment'])
else:
result = __salt__['beacons.enable_job'](name, **kwargs)
if (not result['result']):
ret['result'] = result['result']
ret['comment'] = result['comment']
return ret
else:
ret['comment'].append('Enabled {0} from beacons'.format(name))
else:
ret['comment'].append('{0} not a configured beacon'.format(name))
ret['comment'] = '\n'.join(ret['comment'])
return ret
| Enable a beacon.
name
The name of the beacon to enable. | enable a beacon . | Question:
What does this function do?
Code:
def enabled(name, **kwargs):
ret = {'name': name, 'result': True, 'changes': {}, 'comment': []}
current_beacons = __salt__['beacons.list'](show_all=True, return_yaml=False)
if (name in current_beacons):
if (('test' in __opts__) and __opts__['test']):
kwargs['test'] = True
result = __salt__['beacons.enable_beacon'](name, **kwargs)
ret['comment'].append(result['comment'])
else:
result = __salt__['beacons.enable_job'](name, **kwargs)
if (not result['result']):
ret['result'] = result['result']
ret['comment'] = result['comment']
return ret
else:
ret['comment'].append('Enabled {0} from beacons'.format(name))
else:
ret['comment'].append('{0} not a configured beacon'.format(name))
ret['comment'] = '\n'.join(ret['comment'])
return ret
|
null | null | null | What does this function do? | def whitespace_normalize_name(name):
return ' '.join(name.split())
| null | null | null | Return a whitespace-normalized name. | pcsd | def whitespace normalize name name return ' ' join name split | 13976 | def whitespace_normalize_name(name):
return ' '.join(name.split())
| Return a whitespace-normalized name. | return a whitespace - normalized name . | Question:
What does this function do?
Code:
def whitespace_normalize_name(name):
return ' '.join(name.split())
|
null | null | null | What does this function do? | def merge_includes(code):
pattern = '\\#\\s*include\\s*"(?P<filename>[a-zA-Z0-9\\_\\-\\.\\/]+)"'
regex = re.compile(pattern)
includes = []
def replace(match):
filename = match.group('filename')
if (filename not in includes):
includes.append(filename)
path = glsl.find(filename)
if (not path):
logger.critical(('"%s" not found' % filename))
raise RuntimeError('File not found', filename)
text = ('\n// --- start of "%s" ---\n' % filename)
with open(path) as fh:
text += fh.read()
text += ('// --- end of "%s" ---\n' % filename)
return text
return ''
for i in range(10):
if re.search(regex, code):
code = re.sub(regex, replace, code)
else:
break
return code
| null | null | null | Merge all includes recursively. | pcsd | def merge includes code pattern = '\\#\\s*include\\s*" ?P<filename>[a-z A-Z0-9\\ \\-\\ \\/]+ "' regex = re compile pattern includes = [] def replace match filename = match group 'filename' if filename not in includes includes append filename path = glsl find filename if not path logger critical '"%s" not found' % filename raise Runtime Error 'File not found' filename text = ' // --- start of "%s" --- ' % filename with open path as fh text += fh read text += '// --- end of "%s" --- ' % filename return text return '' for i in range 10 if re search regex code code = re sub regex replace code else break return code | 13981 | def merge_includes(code):
pattern = '\\#\\s*include\\s*"(?P<filename>[a-zA-Z0-9\\_\\-\\.\\/]+)"'
regex = re.compile(pattern)
includes = []
def replace(match):
filename = match.group('filename')
if (filename not in includes):
includes.append(filename)
path = glsl.find(filename)
if (not path):
logger.critical(('"%s" not found' % filename))
raise RuntimeError('File not found', filename)
text = ('\n// --- start of "%s" ---\n' % filename)
with open(path) as fh:
text += fh.read()
text += ('// --- end of "%s" ---\n' % filename)
return text
return ''
for i in range(10):
if re.search(regex, code):
code = re.sub(regex, replace, code)
else:
break
return code
| Merge all includes recursively. | merge all includes recursively . | Question:
What does this function do?
Code:
def merge_includes(code):
pattern = '\\#\\s*include\\s*"(?P<filename>[a-zA-Z0-9\\_\\-\\.\\/]+)"'
regex = re.compile(pattern)
includes = []
def replace(match):
filename = match.group('filename')
if (filename not in includes):
includes.append(filename)
path = glsl.find(filename)
if (not path):
logger.critical(('"%s" not found' % filename))
raise RuntimeError('File not found', filename)
text = ('\n// --- start of "%s" ---\n' % filename)
with open(path) as fh:
text += fh.read()
text += ('// --- end of "%s" ---\n' % filename)
return text
return ''
for i in range(10):
if re.search(regex, code):
code = re.sub(regex, replace, code)
else:
break
return code
|
null | null | null | What does this function do? | def mail_admins(subject, message, fail_silently=False, connection=None, html_message=None):
if (not settings.ADMINS):
return
mail = EmailMultiAlternatives((u'%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject)), message, settings.SERVER_EMAIL, [a[1] for a in settings.ADMINS], connection=connection)
if html_message:
mail.attach_alternative(html_message, 'text/html')
mail.send(fail_silently=fail_silently)
| null | null | null | Sends a message to the admins, as defined by the ADMINS setting. | pcsd | def mail admins subject message fail silently=False connection=None html message=None if not settings ADMINS return mail = Email Multi Alternatives u'%s%s' % settings EMAIL SUBJECT PREFIX subject message settings SERVER EMAIL [a[1] for a in settings ADMINS] connection=connection if html message mail attach alternative html message 'text/html' mail send fail silently=fail silently | 13983 | def mail_admins(subject, message, fail_silently=False, connection=None, html_message=None):
if (not settings.ADMINS):
return
mail = EmailMultiAlternatives((u'%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject)), message, settings.SERVER_EMAIL, [a[1] for a in settings.ADMINS], connection=connection)
if html_message:
mail.attach_alternative(html_message, 'text/html')
mail.send(fail_silently=fail_silently)
| Sends a message to the admins, as defined by the ADMINS setting. | sends a message to the admins , as defined by the admins setting . | Question:
What does this function do?
Code:
def mail_admins(subject, message, fail_silently=False, connection=None, html_message=None):
if (not settings.ADMINS):
return
mail = EmailMultiAlternatives((u'%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject)), message, settings.SERVER_EMAIL, [a[1] for a in settings.ADMINS], connection=connection)
if html_message:
mail.attach_alternative(html_message, 'text/html')
mail.send(fail_silently=fail_silently)
|
null | null | null | What does this function do? | def assert_element_text(output, path, verify_assertions_function, children):
text = xml_find_text(output, path)
verify_assertions_function(text, children)
| null | null | null | Recursively checks the specified assertions against the text of
the first element matching the specified path. | pcsd | def assert element text output path verify assertions function children text = xml find text output path verify assertions function text children | 14000 | def assert_element_text(output, path, verify_assertions_function, children):
text = xml_find_text(output, path)
verify_assertions_function(text, children)
| Recursively checks the specified assertions against the text of
the first element matching the specified path. | recursively checks the specified assertions against the text of the first element matching the specified path . | Question:
What does this function do?
Code:
def assert_element_text(output, path, verify_assertions_function, children):
text = xml_find_text(output, path)
verify_assertions_function(text, children)
|
null | null | null | What does this function do? | def sorter(default_sort_id, kwd):
SortSpec = namedtuple('SortSpec', ['sort_id', 'order', 'arrow', 'exc_order'])
sort_id = kwd.get('sort_id')
order = kwd.get('order')
if (sort_id == 'default'):
sort_id = default_sort_id
if (order == 'asc'):
_order = sa.asc(sort_id)
elif (order == 'desc'):
_order = sa.desc(sort_id)
else:
order = 'desc'
_order = sa.desc(sort_id)
up_arrow = '↑'
down_arrow = '↓'
arrow = ' '
if (order == 'asc'):
arrow += down_arrow
else:
arrow += up_arrow
return SortSpec(sort_id, order, arrow, _order)
| null | null | null | Initialize sorting variables | pcsd | def sorter default sort id kwd Sort Spec = namedtuple 'Sort Spec' ['sort id' 'order' 'arrow' 'exc order'] sort id = kwd get 'sort id' order = kwd get 'order' if sort id == 'default' sort id = default sort id if order == 'asc' order = sa asc sort id elif order == 'desc' order = sa desc sort id else order = 'desc' order = sa desc sort id up arrow = '↑ ' down arrow = '↓ ' arrow = ' ' if order == 'asc' arrow += down arrow else arrow += up arrow return Sort Spec sort id order arrow order | 14005 | def sorter(default_sort_id, kwd):
SortSpec = namedtuple('SortSpec', ['sort_id', 'order', 'arrow', 'exc_order'])
sort_id = kwd.get('sort_id')
order = kwd.get('order')
if (sort_id == 'default'):
sort_id = default_sort_id
if (order == 'asc'):
_order = sa.asc(sort_id)
elif (order == 'desc'):
_order = sa.desc(sort_id)
else:
order = 'desc'
_order = sa.desc(sort_id)
up_arrow = '↑'
down_arrow = '↓'
arrow = ' '
if (order == 'asc'):
arrow += down_arrow
else:
arrow += up_arrow
return SortSpec(sort_id, order, arrow, _order)
| Initialize sorting variables | initialize sorting variables | Question:
What does this function do?
Code:
def sorter(default_sort_id, kwd):
SortSpec = namedtuple('SortSpec', ['sort_id', 'order', 'arrow', 'exc_order'])
sort_id = kwd.get('sort_id')
order = kwd.get('order')
if (sort_id == 'default'):
sort_id = default_sort_id
if (order == 'asc'):
_order = sa.asc(sort_id)
elif (order == 'desc'):
_order = sa.desc(sort_id)
else:
order = 'desc'
_order = sa.desc(sort_id)
up_arrow = '↑'
down_arrow = '↓'
arrow = ' '
if (order == 'asc'):
arrow += down_arrow
else:
arrow += up_arrow
return SortSpec(sort_id, order, arrow, _order)
|
null | null | null | What does this function do? | @testing.requires_testing_data
def test_with_statement():
for preload in [True, False]:
with read_raw_fif(fif_fname, preload=preload) as raw_:
print raw_
| null | null | null | Test with statement. | pcsd | @testing requires testing data def test with statement for preload in [True False] with read raw fif fif fname preload=preload as raw print raw | 14024 | @testing.requires_testing_data
def test_with_statement():
for preload in [True, False]:
with read_raw_fif(fif_fname, preload=preload) as raw_:
print raw_
| Test with statement. | test with statement . | Question:
What does this function do?
Code:
@testing.requires_testing_data
def test_with_statement():
for preload in [True, False]:
with read_raw_fif(fif_fname, preload=preload) as raw_:
print raw_
|
null | null | null | What does this function do? | def _ensure_trans(trans, fro='mri', to='head'):
if isinstance(fro, string_types):
from_str = fro
from_const = _str_to_frame[fro]
else:
from_str = _frame_to_str[fro]
from_const = fro
del fro
if isinstance(to, string_types):
to_str = to
to_const = _str_to_frame[to]
else:
to_str = _frame_to_str[to]
to_const = to
del to
err_str = ('trans must go %s<->%s, provided' % (from_str, to_str))
if (trans is None):
raise ValueError(('%s None' % err_str))
if (set([trans['from'], trans['to']]) != set([from_const, to_const])):
raise ValueError(('%s trans is %s->%s' % (err_str, _frame_to_str[trans['from']], _frame_to_str[trans['to']])))
if (trans['from'] != from_const):
trans = invert_transform(trans)
return trans
| null | null | null | Ensure we have the proper transform. | pcsd | def ensure trans trans fro='mri' to='head' if isinstance fro string types from str = fro from const = str to frame[fro] else from str = frame to str[fro] from const = fro del fro if isinstance to string types to str = to to const = str to frame[to] else to str = frame to str[to] to const = to del to err str = 'trans must go %s<->%s provided' % from str to str if trans is None raise Value Error '%s None' % err str if set [trans['from'] trans['to']] != set [from const to const] raise Value Error '%s trans is %s->%s' % err str frame to str[trans['from']] frame to str[trans['to']] if trans['from'] != from const trans = invert transform trans return trans | 14032 | def _ensure_trans(trans, fro='mri', to='head'):
if isinstance(fro, string_types):
from_str = fro
from_const = _str_to_frame[fro]
else:
from_str = _frame_to_str[fro]
from_const = fro
del fro
if isinstance(to, string_types):
to_str = to
to_const = _str_to_frame[to]
else:
to_str = _frame_to_str[to]
to_const = to
del to
err_str = ('trans must go %s<->%s, provided' % (from_str, to_str))
if (trans is None):
raise ValueError(('%s None' % err_str))
if (set([trans['from'], trans['to']]) != set([from_const, to_const])):
raise ValueError(('%s trans is %s->%s' % (err_str, _frame_to_str[trans['from']], _frame_to_str[trans['to']])))
if (trans['from'] != from_const):
trans = invert_transform(trans)
return trans
| Ensure we have the proper transform. | ensure we have the proper transform . | Question:
What does this function do?
Code:
def _ensure_trans(trans, fro='mri', to='head'):
if isinstance(fro, string_types):
from_str = fro
from_const = _str_to_frame[fro]
else:
from_str = _frame_to_str[fro]
from_const = fro
del fro
if isinstance(to, string_types):
to_str = to
to_const = _str_to_frame[to]
else:
to_str = _frame_to_str[to]
to_const = to
del to
err_str = ('trans must go %s<->%s, provided' % (from_str, to_str))
if (trans is None):
raise ValueError(('%s None' % err_str))
if (set([trans['from'], trans['to']]) != set([from_const, to_const])):
raise ValueError(('%s trans is %s->%s' % (err_str, _frame_to_str[trans['from']], _frame_to_str[trans['to']])))
if (trans['from'] != from_const):
trans = invert_transform(trans)
return trans
|
null | null | null | What does this function do? | def abspath(*relpath, **base):
path = os.path.join(*relpath)
gluon = base.get('gluon', False)
if os.path.isabs(path):
return path
if gluon:
return os.path.join(global_settings.gluon_parent, path)
return os.path.join(global_settings.applications_parent, path)
| null | null | null | Converts relative path to absolute path based (by default) on
applications_parent | pcsd | def abspath *relpath **base path = os path join *relpath gluon = base get 'gluon' False if os path isabs path return path if gluon return os path join global settings gluon parent path return os path join global settings applications parent path | 14056 | def abspath(*relpath, **base):
path = os.path.join(*relpath)
gluon = base.get('gluon', False)
if os.path.isabs(path):
return path
if gluon:
return os.path.join(global_settings.gluon_parent, path)
return os.path.join(global_settings.applications_parent, path)
| Converts relative path to absolute path based (by default) on
applications_parent | converts relative path to absolute path based on applications _ parent | Question:
What does this function do?
Code:
def abspath(*relpath, **base):
path = os.path.join(*relpath)
gluon = base.get('gluon', False)
if os.path.isabs(path):
return path
if gluon:
return os.path.join(global_settings.gluon_parent, path)
return os.path.join(global_settings.applications_parent, path)
|
null | null | null | What does this function do? | def handle_opts(module):
options = module.config
Setting = ['', 'Option', 'Value', 'Type', 'Required']
table = display_options(options, Setting)
while True:
try:
choice = raw_input(('%s > ' % ((color.B_WHITE + module.which) + color.END)))
tmp = check_opts(choice)
if (tmp == (-1)):
continue
if (choice is '0'):
return False
elif (choice == 'info'):
if (module.info is None):
Msg('Module has no information available')
continue
print ('%s%s%s' % (color.GREEN, ('-' * len(module.info.split('\n')[1].strip())), color.END)),
print dedent(module.info.rstrip())
print ('%s%s%s' % (color.GREEN, ('-' * len(module.info.split('\n')[1].strip())), color.END))
elif (choice == 'ops'):
display_options(options, Setting)
continue
elif (len(choice.split(' ')) > 1):
choice = choice.split(' ')
try:
if (int(choice[0]) > len(table)):
continue
elif (int(choice[0]) is 0):
return False
key = options.keys()[(int(choice[0]) - 1)]
if ((choice[1] == 'o') and (module.config[key].opts is not None)):
Msg(('Options: %s' % module.config[key].opts))
continue
elif ((choice[1] == 'o') and (module.config[key].type == 'list')):
Msg(('%s' % module.config[key].value))
continue
tmp = copy(module.config[key])
tmp.value = ' '.join(choice[1::None])
if (not tmp.validate()):
Error(('Wrong type assigned. Expected value of type "%s"' % options[key].type))
else:
module.config[key] = tmp
except Exception as e:
Error(('%s' % e))
continue
elif (('r' in choice.lower()) or ('run' in choice.lower())):
for opt in options.keys():
if (options[opt].required and (options[opt].value is None)):
Error(("Option '%s' is required." % opt))
raise FailedCheck
return True
except KeyboardInterrupt:
return False
except FailedCheck:
continue
except Exception as e:
Error(('%s' % e))
| null | null | null | The user has selected a module, so we should parse out all the
options for this particular module, set the config, and when
requested, run it. This is kinda messy, but works for now. | pcsd | def handle opts module options = module config Setting = ['' 'Option' 'Value' 'Type' 'Required'] table = display options options Setting while True try choice = raw input '%s > ' % color B WHITE + module which + color END tmp = check opts choice if tmp == -1 continue if choice is '0' return False elif choice == 'info' if module info is None Msg 'Module has no information available' continue print '%s%s%s' % color GREEN '-' * len module info split ' ' [1] strip color END print dedent module info rstrip print '%s%s%s' % color GREEN '-' * len module info split ' ' [1] strip color END elif choice == 'ops' display options options Setting continue elif len choice split ' ' > 1 choice = choice split ' ' try if int choice[0] > len table continue elif int choice[0] is 0 return False key = options keys [ int choice[0] - 1 ] if choice[1] == 'o' and module config[key] opts is not None Msg 'Options %s' % module config[key] opts continue elif choice[1] == 'o' and module config[key] type == 'list' Msg '%s' % module config[key] value continue tmp = copy module config[key] tmp value = ' ' join choice[1 None] if not tmp validate Error 'Wrong type assigned Expected value of type "%s"' % options[key] type else module config[key] = tmp except Exception as e Error '%s' % e continue elif 'r' in choice lower or 'run' in choice lower for opt in options keys if options[opt] required and options[opt] value is None Error "Option '%s' is required " % opt raise Failed Check return True except Keyboard Interrupt return False except Failed Check continue except Exception as e Error '%s' % e | 14058 | def handle_opts(module):
options = module.config
Setting = ['', 'Option', 'Value', 'Type', 'Required']
table = display_options(options, Setting)
while True:
try:
choice = raw_input(('%s > ' % ((color.B_WHITE + module.which) + color.END)))
tmp = check_opts(choice)
if (tmp == (-1)):
continue
if (choice is '0'):
return False
elif (choice == 'info'):
if (module.info is None):
Msg('Module has no information available')
continue
print ('%s%s%s' % (color.GREEN, ('-' * len(module.info.split('\n')[1].strip())), color.END)),
print dedent(module.info.rstrip())
print ('%s%s%s' % (color.GREEN, ('-' * len(module.info.split('\n')[1].strip())), color.END))
elif (choice == 'ops'):
display_options(options, Setting)
continue
elif (len(choice.split(' ')) > 1):
choice = choice.split(' ')
try:
if (int(choice[0]) > len(table)):
continue
elif (int(choice[0]) is 0):
return False
key = options.keys()[(int(choice[0]) - 1)]
if ((choice[1] == 'o') and (module.config[key].opts is not None)):
Msg(('Options: %s' % module.config[key].opts))
continue
elif ((choice[1] == 'o') and (module.config[key].type == 'list')):
Msg(('%s' % module.config[key].value))
continue
tmp = copy(module.config[key])
tmp.value = ' '.join(choice[1::None])
if (not tmp.validate()):
Error(('Wrong type assigned. Expected value of type "%s"' % options[key].type))
else:
module.config[key] = tmp
except Exception as e:
Error(('%s' % e))
continue
elif (('r' in choice.lower()) or ('run' in choice.lower())):
for opt in options.keys():
if (options[opt].required and (options[opt].value is None)):
Error(("Option '%s' is required." % opt))
raise FailedCheck
return True
except KeyboardInterrupt:
return False
except FailedCheck:
continue
except Exception as e:
Error(('%s' % e))
| The user has selected a module, so we should parse out all the
options for this particular module, set the config, and when
requested, run it. This is kinda messy, but works for now. | the user has selected a module , so we should parse out all the options for this particular module , set the config , and when requested , run it . | Question:
What does this function do?
Code:
def handle_opts(module):
options = module.config
Setting = ['', 'Option', 'Value', 'Type', 'Required']
table = display_options(options, Setting)
while True:
try:
choice = raw_input(('%s > ' % ((color.B_WHITE + module.which) + color.END)))
tmp = check_opts(choice)
if (tmp == (-1)):
continue
if (choice is '0'):
return False
elif (choice == 'info'):
if (module.info is None):
Msg('Module has no information available')
continue
print ('%s%s%s' % (color.GREEN, ('-' * len(module.info.split('\n')[1].strip())), color.END)),
print dedent(module.info.rstrip())
print ('%s%s%s' % (color.GREEN, ('-' * len(module.info.split('\n')[1].strip())), color.END))
elif (choice == 'ops'):
display_options(options, Setting)
continue
elif (len(choice.split(' ')) > 1):
choice = choice.split(' ')
try:
if (int(choice[0]) > len(table)):
continue
elif (int(choice[0]) is 0):
return False
key = options.keys()[(int(choice[0]) - 1)]
if ((choice[1] == 'o') and (module.config[key].opts is not None)):
Msg(('Options: %s' % module.config[key].opts))
continue
elif ((choice[1] == 'o') and (module.config[key].type == 'list')):
Msg(('%s' % module.config[key].value))
continue
tmp = copy(module.config[key])
tmp.value = ' '.join(choice[1::None])
if (not tmp.validate()):
Error(('Wrong type assigned. Expected value of type "%s"' % options[key].type))
else:
module.config[key] = tmp
except Exception as e:
Error(('%s' % e))
continue
elif (('r' in choice.lower()) or ('run' in choice.lower())):
for opt in options.keys():
if (options[opt].required and (options[opt].value is None)):
Error(("Option '%s' is required." % opt))
raise FailedCheck
return True
except KeyboardInterrupt:
return False
except FailedCheck:
continue
except Exception as e:
Error(('%s' % e))
|
null | null | null | What does this function do? | def serve_500_error(request, *args, **kwargs):
try:
exc_info = sys.exc_info()
if exc_info:
if (desktop.conf.HTTP_500_DEBUG_MODE.get() and exc_info[0] and exc_info[1]):
return django.views.debug.technical_500_response(request, *exc_info)
else:
return render('500.mako', request, {'traceback': traceback.extract_tb(exc_info[2])})
else:
return render('500.mako', request, {})
finally:
pass
| null | null | null | Registered handler for 500. We use the debug view to make debugging easier. | pcsd | def serve 500 error request *args **kwargs try exc info = sys exc info if exc info if desktop conf HTTP 500 DEBUG MODE get and exc info[0] and exc info[1] return django views debug technical 500 response request *exc info else return render '500 mako' request {'traceback' traceback extract tb exc info[2] } else return render '500 mako' request {} finally pass | 14083 | def serve_500_error(request, *args, **kwargs):
try:
exc_info = sys.exc_info()
if exc_info:
if (desktop.conf.HTTP_500_DEBUG_MODE.get() and exc_info[0] and exc_info[1]):
return django.views.debug.technical_500_response(request, *exc_info)
else:
return render('500.mako', request, {'traceback': traceback.extract_tb(exc_info[2])})
else:
return render('500.mako', request, {})
finally:
pass
| Registered handler for 500. We use the debug view to make debugging easier. | registered handler for 500 . | Question:
What does this function do?
Code:
def serve_500_error(request, *args, **kwargs):
try:
exc_info = sys.exc_info()
if exc_info:
if (desktop.conf.HTTP_500_DEBUG_MODE.get() and exc_info[0] and exc_info[1]):
return django.views.debug.technical_500_response(request, *exc_info)
else:
return render('500.mako', request, {'traceback': traceback.extract_tb(exc_info[2])})
else:
return render('500.mako', request, {})
finally:
pass
|
null | null | null | What does this function do? | def layer_openstreetmap():
tablename = ('%s_%s' % (module, resourcename))
s3db.table(tablename)
type = 'OpenStreetMap'
LIST_LAYERS = T((LIST_TYPE_LAYERS_FMT % type))
EDIT_LAYER = T((EDIT_TYPE_LAYER_FMT % type))
NO_LAYERS = T((NO_TYPE_LAYERS_FMT % type))
s3.crud_strings[tablename] = Storage(label_create=ADD_LAYER, title_display=LAYER_DETAILS, title_list=LAYERS, title_update=EDIT_LAYER, label_list_button=LIST_LAYERS, label_delete_button=DELETE_LAYER, msg_record_created=LAYER_ADDED, msg_record_modified=LAYER_UPDATED, msg_record_deleted=LAYER_DELETED, msg_list_empty=NO_LAYERS)
def prep(r):
if r.interactive:
if (r.component_name == 'config'):
ltable = s3db.gis_layer_config
if (r.method != 'update'):
table = r.table
query = ((ltable.layer_id == table.layer_id) & (table.id == r.id))
rows = db(query).select(ltable.config_id)
ltable.config_id.requires = IS_ONE_OF(db, 'gis_config.id', '%(name)s', not_filterby='config_id', not_filter_opts=[row.config_id for row in rows])
return True
s3.prep = prep
def postp(r, output):
if (r.interactive and (r.method != 'import')):
if (not r.component):
inject_enable(output)
return output
s3.postp = postp
output = s3_rest_controller(rheader=s3db.gis_rheader)
return output
| null | null | null | RESTful CRUD controller | pcsd | def layer openstreetmap tablename = '%s %s' % module resourcename s3db table tablename type = 'Open Street Map' LIST LAYERS = T LIST TYPE LAYERS FMT % type EDIT LAYER = T EDIT TYPE LAYER FMT % type NO LAYERS = T NO TYPE LAYERS FMT % type s3 crud strings[tablename] = Storage label create=ADD LAYER title display=LAYER DETAILS title list=LAYERS title update=EDIT LAYER label list button=LIST LAYERS label delete button=DELETE LAYER msg record created=LAYER ADDED msg record modified=LAYER UPDATED msg record deleted=LAYER DELETED msg list empty=NO LAYERS def prep r if r interactive if r component name == 'config' ltable = s3db gis layer config if r method != 'update' table = r table query = ltable layer id == table layer id & table id == r id rows = db query select ltable config id ltable config id requires = IS ONE OF db 'gis config id' '% name s' not filterby='config id' not filter opts=[row config id for row in rows] return True s3 prep = prep def postp r output if r interactive and r method != 'import' if not r component inject enable output return output s3 postp = postp output = s3 rest controller rheader=s3db gis rheader return output | 14086 | def layer_openstreetmap():
tablename = ('%s_%s' % (module, resourcename))
s3db.table(tablename)
type = 'OpenStreetMap'
LIST_LAYERS = T((LIST_TYPE_LAYERS_FMT % type))
EDIT_LAYER = T((EDIT_TYPE_LAYER_FMT % type))
NO_LAYERS = T((NO_TYPE_LAYERS_FMT % type))
s3.crud_strings[tablename] = Storage(label_create=ADD_LAYER, title_display=LAYER_DETAILS, title_list=LAYERS, title_update=EDIT_LAYER, label_list_button=LIST_LAYERS, label_delete_button=DELETE_LAYER, msg_record_created=LAYER_ADDED, msg_record_modified=LAYER_UPDATED, msg_record_deleted=LAYER_DELETED, msg_list_empty=NO_LAYERS)
def prep(r):
if r.interactive:
if (r.component_name == 'config'):
ltable = s3db.gis_layer_config
if (r.method != 'update'):
table = r.table
query = ((ltable.layer_id == table.layer_id) & (table.id == r.id))
rows = db(query).select(ltable.config_id)
ltable.config_id.requires = IS_ONE_OF(db, 'gis_config.id', '%(name)s', not_filterby='config_id', not_filter_opts=[row.config_id for row in rows])
return True
s3.prep = prep
def postp(r, output):
if (r.interactive and (r.method != 'import')):
if (not r.component):
inject_enable(output)
return output
s3.postp = postp
output = s3_rest_controller(rheader=s3db.gis_rheader)
return output
| RESTful CRUD controller | restful crud controller | Question:
What does this function do?
Code:
def layer_openstreetmap():
tablename = ('%s_%s' % (module, resourcename))
s3db.table(tablename)
type = 'OpenStreetMap'
LIST_LAYERS = T((LIST_TYPE_LAYERS_FMT % type))
EDIT_LAYER = T((EDIT_TYPE_LAYER_FMT % type))
NO_LAYERS = T((NO_TYPE_LAYERS_FMT % type))
s3.crud_strings[tablename] = Storage(label_create=ADD_LAYER, title_display=LAYER_DETAILS, title_list=LAYERS, title_update=EDIT_LAYER, label_list_button=LIST_LAYERS, label_delete_button=DELETE_LAYER, msg_record_created=LAYER_ADDED, msg_record_modified=LAYER_UPDATED, msg_record_deleted=LAYER_DELETED, msg_list_empty=NO_LAYERS)
def prep(r):
if r.interactive:
if (r.component_name == 'config'):
ltable = s3db.gis_layer_config
if (r.method != 'update'):
table = r.table
query = ((ltable.layer_id == table.layer_id) & (table.id == r.id))
rows = db(query).select(ltable.config_id)
ltable.config_id.requires = IS_ONE_OF(db, 'gis_config.id', '%(name)s', not_filterby='config_id', not_filter_opts=[row.config_id for row in rows])
return True
s3.prep = prep
def postp(r, output):
if (r.interactive and (r.method != 'import')):
if (not r.component):
inject_enable(output)
return output
s3.postp = postp
output = s3_rest_controller(rheader=s3db.gis_rheader)
return output
|
null | null | null | What does this function do? | def addFacesByConvexReversed(faces, indexedLoop):
addFacesByConvex(faces, indexedLoop[::(-1)])
| null | null | null | Add faces from a reversed convex polygon. | pcsd | def add Faces By Convex Reversed faces indexed Loop add Faces By Convex faces indexed Loop[ -1 ] | 14092 | def addFacesByConvexReversed(faces, indexedLoop):
addFacesByConvex(faces, indexedLoop[::(-1)])
| Add faces from a reversed convex polygon. | add faces from a reversed convex polygon . | Question:
What does this function do?
Code:
def addFacesByConvexReversed(faces, indexedLoop):
addFacesByConvex(faces, indexedLoop[::(-1)])
|
null | null | null | What does this function do? | def get_first_import(node, context, name, base, level):
fullname = (('%s.%s' % (base, name)) if base else name)
first = None
found = False
for first in context.body:
if (first is node):
continue
if ((first.scope() is node.scope()) and (first.fromlineno > node.fromlineno)):
continue
if isinstance(first, astroid.Import):
if any(((fullname == iname[0]) for iname in first.names)):
found = True
break
elif isinstance(first, astroid.From):
if ((level == first.level) and any(((fullname == ('%s.%s' % (first.modname, iname[0]))) for iname in first.names))):
found = True
break
if (found and (not are_exclusive(first, node))):
return first
| null | null | null | return the node where [base.]<name> is imported or None if not found | pcsd | def get first import node context name base level fullname = '%s %s' % base name if base else name first = None found = False for first in context body if first is node continue if first scope is node scope and first fromlineno > node fromlineno continue if isinstance first astroid Import if any fullname == iname[0] for iname in first names found = True break elif isinstance first astroid From if level == first level and any fullname == '%s %s' % first modname iname[0] for iname in first names found = True break if found and not are exclusive first node return first | 14093 | def get_first_import(node, context, name, base, level):
fullname = (('%s.%s' % (base, name)) if base else name)
first = None
found = False
for first in context.body:
if (first is node):
continue
if ((first.scope() is node.scope()) and (first.fromlineno > node.fromlineno)):
continue
if isinstance(first, astroid.Import):
if any(((fullname == iname[0]) for iname in first.names)):
found = True
break
elif isinstance(first, astroid.From):
if ((level == first.level) and any(((fullname == ('%s.%s' % (first.modname, iname[0]))) for iname in first.names))):
found = True
break
if (found and (not are_exclusive(first, node))):
return first
| return the node where [base.]<name> is imported or None if not found | return the node where [ base . ] is imported or none if not found | Question:
What does this function do?
Code:
def get_first_import(node, context, name, base, level):
fullname = (('%s.%s' % (base, name)) if base else name)
first = None
found = False
for first in context.body:
if (first is node):
continue
if ((first.scope() is node.scope()) and (first.fromlineno > node.fromlineno)):
continue
if isinstance(first, astroid.Import):
if any(((fullname == iname[0]) for iname in first.names)):
found = True
break
elif isinstance(first, astroid.From):
if ((level == first.level) and any(((fullname == ('%s.%s' % (first.modname, iname[0]))) for iname in first.names))):
found = True
break
if (found and (not are_exclusive(first, node))):
return first
|
null | null | null | What does this function do? | def _autoregister(admin, model, follow=None):
if model._meta.proxy:
raise RegistrationError('Proxy models cannot be used with django-reversion, register the parent class instead')
if (not is_registered(model)):
follow = (follow or [])
for (parent_cls, field) in model._meta.parents.items():
follow.append(field.name)
_autoregister(admin, parent_cls)
register(model, follow=follow, format=admin.reversion_format)
| null | null | null | Registers a model with reversion, if required. | pcsd | def autoregister admin model follow=None if model meta proxy raise Registration Error 'Proxy models cannot be used with django-reversion register the parent class instead' if not is registered model follow = follow or [] for parent cls field in model meta parents items follow append field name autoregister admin parent cls register model follow=follow format=admin reversion format | 14095 | def _autoregister(admin, model, follow=None):
if model._meta.proxy:
raise RegistrationError('Proxy models cannot be used with django-reversion, register the parent class instead')
if (not is_registered(model)):
follow = (follow or [])
for (parent_cls, field) in model._meta.parents.items():
follow.append(field.name)
_autoregister(admin, parent_cls)
register(model, follow=follow, format=admin.reversion_format)
| Registers a model with reversion, if required. | registers a model with reversion , if required . | Question:
What does this function do?
Code:
def _autoregister(admin, model, follow=None):
if model._meta.proxy:
raise RegistrationError('Proxy models cannot be used with django-reversion, register the parent class instead')
if (not is_registered(model)):
follow = (follow or [])
for (parent_cls, field) in model._meta.parents.items():
follow.append(field.name)
_autoregister(admin, parent_cls)
register(model, follow=follow, format=admin.reversion_format)
|
null | null | null | What does this function do? | def notify(context, message):
if (not context):
context = req_context.get_admin_context()
priority = message.get('priority', CONF.default_notification_level)
priority = priority.lower()
for topic in CONF.notification_topics:
topic = ('%s.%s' % (topic, priority))
try:
rpc.notify(context, topic, message)
except Exception:
LOG.exception(_('Could not send notification to %(topic)s. Payload=%(message)s'), locals())
| null | null | null | Sends a notification via RPC. | pcsd | def notify context message if not context context = req context get admin context priority = message get 'priority' CONF default notification level priority = priority lower for topic in CONF notification topics topic = '%s %s' % topic priority try rpc notify context topic message except Exception LOG exception 'Could not send notification to % topic s Payload=% message s' locals | 14102 | def notify(context, message):
if (not context):
context = req_context.get_admin_context()
priority = message.get('priority', CONF.default_notification_level)
priority = priority.lower()
for topic in CONF.notification_topics:
topic = ('%s.%s' % (topic, priority))
try:
rpc.notify(context, topic, message)
except Exception:
LOG.exception(_('Could not send notification to %(topic)s. Payload=%(message)s'), locals())
| Sends a notification via RPC. | sends a notification via rpc . | Question:
What does this function do?
Code:
def notify(context, message):
if (not context):
context = req_context.get_admin_context()
priority = message.get('priority', CONF.default_notification_level)
priority = priority.lower()
for topic in CONF.notification_topics:
topic = ('%s.%s' % (topic, priority))
try:
rpc.notify(context, topic, message)
except Exception:
LOG.exception(_('Could not send notification to %(topic)s. Payload=%(message)s'), locals())
|
null | null | null | What does this function do? | def _raw_input_contains_national_prefix(raw_input, national_prefix, region_code):
nnn = normalize_digits_only(raw_input)
if nnn.startswith(national_prefix):
try:
return is_valid_number(parse(nnn[len(national_prefix):], region_code))
except NumberParseException:
return False
return False
| null | null | null | Check if raw_input, which is assumed to be in the national format, has a
national prefix. The national prefix is assumed to be in digits-only
form. | pcsd | def raw input contains national prefix raw input national prefix region code nnn = normalize digits only raw input if nnn startswith national prefix try return is valid number parse nnn[len national prefix ] region code except Number Parse Exception return False return False | 14120 | def _raw_input_contains_national_prefix(raw_input, national_prefix, region_code):
nnn = normalize_digits_only(raw_input)
if nnn.startswith(national_prefix):
try:
return is_valid_number(parse(nnn[len(national_prefix):], region_code))
except NumberParseException:
return False
return False
| Check if raw_input, which is assumed to be in the national format, has a
national prefix. The national prefix is assumed to be in digits-only
form. | check if raw _ input , which is assumed to be in the national format , has a national prefix . | Question:
What does this function do?
Code:
def _raw_input_contains_national_prefix(raw_input, national_prefix, region_code):
nnn = normalize_digits_only(raw_input)
if nnn.startswith(national_prefix):
try:
return is_valid_number(parse(nnn[len(national_prefix):], region_code))
except NumberParseException:
return False
return False
|
null | null | null | What does this function do? | def verbose_print(arg):
if test_support.verbose:
with _print_mutex:
print arg
| null | null | null | Helper function for printing out debugging output. | pcsd | def verbose print arg if test support verbose with print mutex print arg | 14123 | def verbose_print(arg):
if test_support.verbose:
with _print_mutex:
print arg
| Helper function for printing out debugging output. | helper function for printing out debugging output . | Question:
What does this function do?
Code:
def verbose_print(arg):
if test_support.verbose:
with _print_mutex:
print arg
|
null | null | null | What does this function do? | def fold_arg_vars(typevars, args, vararg, kws):
n_pos_args = len(args)
kwds = [kw for (kw, var) in kws]
argtypes = [typevars[a.name] for a in args]
argtypes += [typevars[var.name] for (kw, var) in kws]
if (vararg is not None):
argtypes.append(typevars[vararg.name])
if (not all((a.defined for a in argtypes))):
return
args = tuple((a.getone() for a in argtypes))
pos_args = args[:n_pos_args]
if (vararg is not None):
if (not isinstance(args[(-1)], types.BaseTuple)):
raise TypeError(('*args in function call should be a tuple, got %s' % (args[(-1)],)))
pos_args += args[(-1)].types
args = args[:(-1)]
kw_args = dict(zip(kwds, args[n_pos_args:]))
return (pos_args, kw_args)
| null | null | null | Fold and resolve the argument variables of a function call. | pcsd | def fold arg vars typevars args vararg kws n pos args = len args kwds = [kw for kw var in kws] argtypes = [typevars[a name] for a in args] argtypes += [typevars[var name] for kw var in kws] if vararg is not None argtypes append typevars[vararg name] if not all a defined for a in argtypes return args = tuple a getone for a in argtypes pos args = args[ n pos args] if vararg is not None if not isinstance args[ -1 ] types Base Tuple raise Type Error '*args in function call should be a tuple got %s' % args[ -1 ] pos args += args[ -1 ] types args = args[ -1 ] kw args = dict zip kwds args[n pos args ] return pos args kw args | 14124 | def fold_arg_vars(typevars, args, vararg, kws):
n_pos_args = len(args)
kwds = [kw for (kw, var) in kws]
argtypes = [typevars[a.name] for a in args]
argtypes += [typevars[var.name] for (kw, var) in kws]
if (vararg is not None):
argtypes.append(typevars[vararg.name])
if (not all((a.defined for a in argtypes))):
return
args = tuple((a.getone() for a in argtypes))
pos_args = args[:n_pos_args]
if (vararg is not None):
if (not isinstance(args[(-1)], types.BaseTuple)):
raise TypeError(('*args in function call should be a tuple, got %s' % (args[(-1)],)))
pos_args += args[(-1)].types
args = args[:(-1)]
kw_args = dict(zip(kwds, args[n_pos_args:]))
return (pos_args, kw_args)
| Fold and resolve the argument variables of a function call. | fold and resolve the argument variables of a function call . | Question:
What does this function do?
Code:
def fold_arg_vars(typevars, args, vararg, kws):
n_pos_args = len(args)
kwds = [kw for (kw, var) in kws]
argtypes = [typevars[a.name] for a in args]
argtypes += [typevars[var.name] for (kw, var) in kws]
if (vararg is not None):
argtypes.append(typevars[vararg.name])
if (not all((a.defined for a in argtypes))):
return
args = tuple((a.getone() for a in argtypes))
pos_args = args[:n_pos_args]
if (vararg is not None):
if (not isinstance(args[(-1)], types.BaseTuple)):
raise TypeError(('*args in function call should be a tuple, got %s' % (args[(-1)],)))
pos_args += args[(-1)].types
args = args[:(-1)]
kw_args = dict(zip(kwds, args[n_pos_args:]))
return (pos_args, kw_args)
|
null | null | null | What does this function do? | def create_local_pifs():
for host_ref in _db_content['host'].keys():
_create_local_pif(host_ref)
| null | null | null | Adds a PIF for each to the local database with VLAN=-1.
Do this one per host. | pcsd | def create local pifs for host ref in db content['host'] keys create local pif host ref | 14125 | def create_local_pifs():
for host_ref in _db_content['host'].keys():
_create_local_pif(host_ref)
| Adds a PIF for each to the local database with VLAN=-1.
Do this one per host. | adds a pif for each to the local database with vlan = - 1 . | Question:
What does this function do?
Code:
def create_local_pifs():
for host_ref in _db_content['host'].keys():
_create_local_pif(host_ref)
|
null | null | null | What does this function do? | def run_func_until_ret_arg(fun, kwargs, fun_call=None, argument_being_watched=None, required_argument_response=None):
status = None
while (status != required_argument_response):
f_result = fun(kwargs, call=fun_call)
r_set = {}
for d in f_result:
if isinstance(d, list):
d0 = d[0]
if isinstance(d0, dict):
for (k, v) in six.iteritems(d0):
r_set[k] = v
status = _unwrap_dict(r_set, argument_being_watched)
log.debug('Function: {0}, Watched arg: {1}, Response: {2}'.format(str(fun).split(' ')[1], argument_being_watched, status))
time.sleep(5)
return True
| null | null | null | Waits until the function retrieves some required argument.
NOTE: Tested with ec2 describe_volumes and describe_snapshots only. | pcsd | def run func until ret arg fun kwargs fun call=None argument being watched=None required argument response=None status = None while status != required argument response f result = fun kwargs call=fun call r set = {} for d in f result if isinstance d list d0 = d[0] if isinstance d0 dict for k v in six iteritems d0 r set[k] = v status = unwrap dict r set argument being watched log debug 'Function {0} Watched arg {1} Response {2}' format str fun split ' ' [1] argument being watched status time sleep 5 return True | 14127 | def run_func_until_ret_arg(fun, kwargs, fun_call=None, argument_being_watched=None, required_argument_response=None):
status = None
while (status != required_argument_response):
f_result = fun(kwargs, call=fun_call)
r_set = {}
for d in f_result:
if isinstance(d, list):
d0 = d[0]
if isinstance(d0, dict):
for (k, v) in six.iteritems(d0):
r_set[k] = v
status = _unwrap_dict(r_set, argument_being_watched)
log.debug('Function: {0}, Watched arg: {1}, Response: {2}'.format(str(fun).split(' ')[1], argument_being_watched, status))
time.sleep(5)
return True
| Waits until the function retrieves some required argument.
NOTE: Tested with ec2 describe_volumes and describe_snapshots only. | waits until the function retrieves some required argument . | Question:
What does this function do?
Code:
def run_func_until_ret_arg(fun, kwargs, fun_call=None, argument_being_watched=None, required_argument_response=None):
status = None
while (status != required_argument_response):
f_result = fun(kwargs, call=fun_call)
r_set = {}
for d in f_result:
if isinstance(d, list):
d0 = d[0]
if isinstance(d0, dict):
for (k, v) in six.iteritems(d0):
r_set[k] = v
status = _unwrap_dict(r_set, argument_being_watched)
log.debug('Function: {0}, Watched arg: {1}, Response: {2}'.format(str(fun).split(' ')[1], argument_being_watched, status))
time.sleep(5)
return True
|
null | null | null | What does this function do? | def _execute2(*args, **kargs):
cmd = (args[1:(-3)] if (args[0] == 'raidcom') else args)
result = EXECUTE_TABLE2.get(cmd, CMD_SUCCEED)
return result
| null | null | null | Return predefined results based on EXECUTE_TABLE2. | pcsd | def execute2 *args **kargs cmd = args[1 -3 ] if args[0] == 'raidcom' else args result = EXECUTE TABLE2 get cmd CMD SUCCEED return result | 14144 | def _execute2(*args, **kargs):
cmd = (args[1:(-3)] if (args[0] == 'raidcom') else args)
result = EXECUTE_TABLE2.get(cmd, CMD_SUCCEED)
return result
| Return predefined results based on EXECUTE_TABLE2. | return predefined results based on execute _ table2 . | Question:
What does this function do?
Code:
def _execute2(*args, **kargs):
cmd = (args[1:(-3)] if (args[0] == 'raidcom') else args)
result = EXECUTE_TABLE2.get(cmd, CMD_SUCCEED)
return result
|
null | null | null | What does this function do? | def index():
if mode_task:
s3_redirect_default(URL(f='project', vars={'tasks': 1}))
else:
s3_redirect_default(URL(f='project'))
| null | null | null | Module\'s Home Page | pcsd | def index if mode task s3 redirect default URL f='project' vars={'tasks' 1} else s3 redirect default URL f='project' | 14145 | def index():
if mode_task:
s3_redirect_default(URL(f='project', vars={'tasks': 1}))
else:
s3_redirect_default(URL(f='project'))
| Module\'s Home Page | modules home page | Question:
What does this function do?
Code:
def index():
if mode_task:
s3_redirect_default(URL(f='project', vars={'tasks': 1}))
else:
s3_redirect_default(URL(f='project'))
|
null | null | null | What does this function do? | def send_export_mail(event_id, result):
job = DataGetter.get_export_jobs(event_id)
if (not job):
return
event = EventModel.query.get(event_id)
if (not event):
event_name = '(Undefined)'
else:
event_name = event.name
send_email_after_export(job.user_email, event_name, result)
user = DataGetter.get_user_by_email(job.user_email)
send_notif_after_export(user, event_name, result)
| null | null | null | send export event mail after the process is complete | pcsd | def send export mail event id result job = Data Getter get export jobs event id if not job return event = Event Model query get event id if not event event name = ' Undefined ' else event name = event name send email after export job user email event name result user = Data Getter get user by email job user email send notif after export user event name result | 14148 | def send_export_mail(event_id, result):
job = DataGetter.get_export_jobs(event_id)
if (not job):
return
event = EventModel.query.get(event_id)
if (not event):
event_name = '(Undefined)'
else:
event_name = event.name
send_email_after_export(job.user_email, event_name, result)
user = DataGetter.get_user_by_email(job.user_email)
send_notif_after_export(user, event_name, result)
| send export event mail after the process is complete | send export event mail after the process is complete | Question:
What does this function do?
Code:
def send_export_mail(event_id, result):
job = DataGetter.get_export_jobs(event_id)
if (not job):
return
event = EventModel.query.get(event_id)
if (not event):
event_name = '(Undefined)'
else:
event_name = event.name
send_email_after_export(job.user_email, event_name, result)
user = DataGetter.get_user_by_email(job.user_email)
send_notif_after_export(user, event_name, result)
|
null | null | null | What does this function do? | def assertRequestTransmissionFailed(self, deferred, reasonTypes):
return assertWrapperExceptionTypes(self, deferred, RequestTransmissionFailed, reasonTypes)
| null | null | null | A simple helper to invoke L{assertWrapperExceptionTypes} with a C{mainType}
of L{RequestTransmissionFailed}. | pcsd | def assert Request Transmission Failed self deferred reason Types return assert Wrapper Exception Types self deferred Request Transmission Failed reason Types | 14150 | def assertRequestTransmissionFailed(self, deferred, reasonTypes):
return assertWrapperExceptionTypes(self, deferred, RequestTransmissionFailed, reasonTypes)
| A simple helper to invoke L{assertWrapperExceptionTypes} with a C{mainType}
of L{RequestTransmissionFailed}. | a simple helper to invoke l { assertwrapperexceptiontypes } with a c { maintype } of l { requesttransmissionfailed } . | Question:
What does this function do?
Code:
def assertRequestTransmissionFailed(self, deferred, reasonTypes):
return assertWrapperExceptionTypes(self, deferred, RequestTransmissionFailed, reasonTypes)
|
null | null | null | What does this function do? | def tally(zcontext, url):
zsock = zcontext.socket(zmq.PULL)
zsock.bind(url)
p = q = 0
while True:
decision = zsock.recv_string()
q += 1
if (decision == 'Y'):
p += 4
print (decision, (p / q))
| null | null | null | Tally how many points fall within the unit circle, and print pi. | pcsd | def tally zcontext url zsock = zcontext socket zmq PULL zsock bind url p = q = 0 while True decision = zsock recv string q += 1 if decision == 'Y' p += 4 print decision p / q | 14152 | def tally(zcontext, url):
zsock = zcontext.socket(zmq.PULL)
zsock.bind(url)
p = q = 0
while True:
decision = zsock.recv_string()
q += 1
if (decision == 'Y'):
p += 4
print (decision, (p / q))
| Tally how many points fall within the unit circle, and print pi. | tally how many points fall within the unit circle , and print pi . | Question:
What does this function do?
Code:
def tally(zcontext, url):
zsock = zcontext.socket(zmq.PULL)
zsock.bind(url)
p = q = 0
while True:
decision = zsock.recv_string()
q += 1
if (decision == 'Y'):
p += 4
print (decision, (p / q))
|
null | null | null | What does this function do? | def notify_new_comment(unit, comment, user, report_source_bugs):
mails = []
subscriptions = Profile.objects.subscribed_new_comment(unit.translation.subproject.project, comment.language, user)
for subscription in subscriptions:
mails.append(subscription.notify_new_comment(unit, comment, user))
if ((comment.language is None) and (report_source_bugs != u'')):
send_notification_email(u'en', report_source_bugs, u'new_comment', unit.translation, {u'unit': unit, u'comment': comment, u'subproject': unit.translation.subproject}, user=user)
send_mails(mails)
| null | null | null | Notify about new comment. | pcsd | def notify new comment unit comment user report source bugs mails = [] subscriptions = Profile objects subscribed new comment unit translation subproject project comment language user for subscription in subscriptions mails append subscription notify new comment unit comment user if comment language is None and report source bugs != u'' send notification email u'en' report source bugs u'new comment' unit translation {u'unit' unit u'comment' comment u'subproject' unit translation subproject} user=user send mails mails | 14158 | def notify_new_comment(unit, comment, user, report_source_bugs):
mails = []
subscriptions = Profile.objects.subscribed_new_comment(unit.translation.subproject.project, comment.language, user)
for subscription in subscriptions:
mails.append(subscription.notify_new_comment(unit, comment, user))
if ((comment.language is None) and (report_source_bugs != u'')):
send_notification_email(u'en', report_source_bugs, u'new_comment', unit.translation, {u'unit': unit, u'comment': comment, u'subproject': unit.translation.subproject}, user=user)
send_mails(mails)
| Notify about new comment. | notify about new comment . | Question:
What does this function do?
Code:
def notify_new_comment(unit, comment, user, report_source_bugs):
mails = []
subscriptions = Profile.objects.subscribed_new_comment(unit.translation.subproject.project, comment.language, user)
for subscription in subscriptions:
mails.append(subscription.notify_new_comment(unit, comment, user))
if ((comment.language is None) and (report_source_bugs != u'')):
send_notification_email(u'en', report_source_bugs, u'new_comment', unit.translation, {u'unit': unit, u'comment': comment, u'subproject': unit.translation.subproject}, user=user)
send_mails(mails)
|
null | null | null | What does this function do? | @RegisterWithArgChecks(name='prefix.add_local', req_args=[ROUTE_DISTINGUISHER, PREFIX, NEXT_HOP], opt_args=[VRF_RF])
def add_local(route_dist, prefix, next_hop, route_family=VRF_RF_IPV4):
try:
tm = CORE_MANAGER.get_core_service().table_manager
label = tm.update_vrf_table(route_dist, prefix, next_hop, route_family)
if label:
label = label[0]
return [{ROUTE_DISTINGUISHER: route_dist, PREFIX: prefix, VRF_RF: route_family, VPN_LABEL: label}]
except BgpCoreError as e:
raise PrefixError(desc=e)
| null | null | null | Adds *prefix* from VRF identified by *route_dist* and sets the source as
network controller. | pcsd | @Register With Arg Checks name='prefix add local' req args=[ROUTE DISTINGUISHER PREFIX NEXT HOP] opt args=[VRF RF] def add local route dist prefix next hop route family=VRF RF IPV4 try tm = CORE MANAGER get core service table manager label = tm update vrf table route dist prefix next hop route family if label label = label[0] return [{ROUTE DISTINGUISHER route dist PREFIX prefix VRF RF route family VPN LABEL label}] except Bgp Core Error as e raise Prefix Error desc=e | 14159 | @RegisterWithArgChecks(name='prefix.add_local', req_args=[ROUTE_DISTINGUISHER, PREFIX, NEXT_HOP], opt_args=[VRF_RF])
def add_local(route_dist, prefix, next_hop, route_family=VRF_RF_IPV4):
try:
tm = CORE_MANAGER.get_core_service().table_manager
label = tm.update_vrf_table(route_dist, prefix, next_hop, route_family)
if label:
label = label[0]
return [{ROUTE_DISTINGUISHER: route_dist, PREFIX: prefix, VRF_RF: route_family, VPN_LABEL: label}]
except BgpCoreError as e:
raise PrefixError(desc=e)
| Adds *prefix* from VRF identified by *route_dist* and sets the source as
network controller. | adds * prefix * from vrf identified by * route _ dist * and sets the source as network controller . | Question:
What does this function do?
Code:
@RegisterWithArgChecks(name='prefix.add_local', req_args=[ROUTE_DISTINGUISHER, PREFIX, NEXT_HOP], opt_args=[VRF_RF])
def add_local(route_dist, prefix, next_hop, route_family=VRF_RF_IPV4):
try:
tm = CORE_MANAGER.get_core_service().table_manager
label = tm.update_vrf_table(route_dist, prefix, next_hop, route_family)
if label:
label = label[0]
return [{ROUTE_DISTINGUISHER: route_dist, PREFIX: prefix, VRF_RF: route_family, VPN_LABEL: label}]
except BgpCoreError as e:
raise PrefixError(desc=e)
|
null | null | null | What does this function do? | def add_extension(module, name, code):
code = int(code)
if (not (1 <= code <= 2147483647)):
raise ValueError, 'code out of range'
key = (module, name)
if (_extension_registry.get(key) == code):
if (_inverted_registry.get(code) == key):
return
if (key in _extension_registry):
raise ValueError(('key %s is already registered with code %s' % (key, _extension_registry[key])))
if (code in _inverted_registry):
raise ValueError(('code %s is already in use for key %s' % (code, _inverted_registry[code])))
_extension_registry[key] = code
_inverted_registry[code] = key
| null | null | null | Register an extension code. | pcsd | def add extension module name code code = int code if not 1 <= code <= 2147483647 raise Value Error 'code out of range' key = module name if extension registry get key == code if inverted registry get code == key return if key in extension registry raise Value Error 'key %s is already registered with code %s' % key extension registry[key] if code in inverted registry raise Value Error 'code %s is already in use for key %s' % code inverted registry[code] extension registry[key] = code inverted registry[code] = key | 14160 | def add_extension(module, name, code):
code = int(code)
if (not (1 <= code <= 2147483647)):
raise ValueError, 'code out of range'
key = (module, name)
if (_extension_registry.get(key) == code):
if (_inverted_registry.get(code) == key):
return
if (key in _extension_registry):
raise ValueError(('key %s is already registered with code %s' % (key, _extension_registry[key])))
if (code in _inverted_registry):
raise ValueError(('code %s is already in use for key %s' % (code, _inverted_registry[code])))
_extension_registry[key] = code
_inverted_registry[code] = key
| Register an extension code. | register an extension code . | Question:
What does this function do?
Code:
def add_extension(module, name, code):
code = int(code)
if (not (1 <= code <= 2147483647)):
raise ValueError, 'code out of range'
key = (module, name)
if (_extension_registry.get(key) == code):
if (_inverted_registry.get(code) == key):
return
if (key in _extension_registry):
raise ValueError(('key %s is already registered with code %s' % (key, _extension_registry[key])))
if (code in _inverted_registry):
raise ValueError(('code %s is already in use for key %s' % (code, _inverted_registry[code])))
_extension_registry[key] = code
_inverted_registry[code] = key
|
null | null | null | What does this function do? | @core_helper
def format_resource_items(items):
blacklist = ['name', 'description', 'url', 'tracking_summary']
output = []
reg_ex_datetime = '^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d{6})?$'
reg_ex_int = '^-?\\d{1,}$'
reg_ex_float = '^-?\\d{1,}\\.\\d{1,}$'
for (key, value) in items:
if ((not value) or (key in blacklist)):
continue
if (key == 'size'):
try:
value = formatters.localised_filesize(int(value))
except ValueError:
pass
elif isinstance(value, basestring):
if re.search(reg_ex_datetime, value):
datetime_ = date_str_to_datetime(value)
value = formatters.localised_nice_date(datetime_)
elif re.search(reg_ex_float, value):
value = formatters.localised_number(float(value))
elif re.search(reg_ex_int, value):
value = formatters.localised_number(int(value))
elif ((isinstance(value, int) or isinstance(value, float)) and (value not in (True, False))):
value = formatters.localised_number(value)
key = key.replace('_', ' ')
output.append((key, value))
return sorted(output, key=(lambda x: x[0]))
| null | null | null | Take a resource item list and format nicely with blacklisting etc. | pcsd | @core helper def format resource items items blacklist = ['name' 'description' 'url' 'tracking summary'] output = [] reg ex datetime = '^\\d{4}-\\d{2}-\\d{2}T\\d{2} \\d{2} \\d{2} \\ \\d{6} ?$' reg ex int = '^-?\\d{1 }$' reg ex float = '^-?\\d{1 }\\ \\d{1 }$' for key value in items if not value or key in blacklist continue if key == 'size' try value = formatters localised filesize int value except Value Error pass elif isinstance value basestring if re search reg ex datetime value datetime = date str to datetime value value = formatters localised nice date datetime elif re search reg ex float value value = formatters localised number float value elif re search reg ex int value value = formatters localised number int value elif isinstance value int or isinstance value float and value not in True False value = formatters localised number value key = key replace ' ' ' ' output append key value return sorted output key= lambda x x[0] | 14161 | @core_helper
def format_resource_items(items):
blacklist = ['name', 'description', 'url', 'tracking_summary']
output = []
reg_ex_datetime = '^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d{6})?$'
reg_ex_int = '^-?\\d{1,}$'
reg_ex_float = '^-?\\d{1,}\\.\\d{1,}$'
for (key, value) in items:
if ((not value) or (key in blacklist)):
continue
if (key == 'size'):
try:
value = formatters.localised_filesize(int(value))
except ValueError:
pass
elif isinstance(value, basestring):
if re.search(reg_ex_datetime, value):
datetime_ = date_str_to_datetime(value)
value = formatters.localised_nice_date(datetime_)
elif re.search(reg_ex_float, value):
value = formatters.localised_number(float(value))
elif re.search(reg_ex_int, value):
value = formatters.localised_number(int(value))
elif ((isinstance(value, int) or isinstance(value, float)) and (value not in (True, False))):
value = formatters.localised_number(value)
key = key.replace('_', ' ')
output.append((key, value))
return sorted(output, key=(lambda x: x[0]))
| Take a resource item list and format nicely with blacklisting etc. | take a resource item list and format nicely with blacklisting etc . | Question:
What does this function do?
Code:
@core_helper
def format_resource_items(items):
blacklist = ['name', 'description', 'url', 'tracking_summary']
output = []
reg_ex_datetime = '^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d{6})?$'
reg_ex_int = '^-?\\d{1,}$'
reg_ex_float = '^-?\\d{1,}\\.\\d{1,}$'
for (key, value) in items:
if ((not value) or (key in blacklist)):
continue
if (key == 'size'):
try:
value = formatters.localised_filesize(int(value))
except ValueError:
pass
elif isinstance(value, basestring):
if re.search(reg_ex_datetime, value):
datetime_ = date_str_to_datetime(value)
value = formatters.localised_nice_date(datetime_)
elif re.search(reg_ex_float, value):
value = formatters.localised_number(float(value))
elif re.search(reg_ex_int, value):
value = formatters.localised_number(int(value))
elif ((isinstance(value, int) or isinstance(value, float)) and (value not in (True, False))):
value = formatters.localised_number(value)
key = key.replace('_', ' ')
output.append((key, value))
return sorted(output, key=(lambda x: x[0]))
|
null | null | null | What does this function do? | def eye(size, dtype=None, name=None):
if (dtype is None):
dtype = floatx()
return variable(np.eye(size), dtype, name)
| null | null | null | Instantiates an identity matrix. | pcsd | def eye size dtype=None name=None if dtype is None dtype = floatx return variable np eye size dtype name | 14163 | def eye(size, dtype=None, name=None):
if (dtype is None):
dtype = floatx()
return variable(np.eye(size), dtype, name)
| Instantiates an identity matrix. | instantiates an identity matrix . | Question:
What does this function do?
Code:
def eye(size, dtype=None, name=None):
if (dtype is None):
dtype = floatx()
return variable(np.eye(size), dtype, name)
|
null | null | null | What does this function do? | def _ppoly3d_eval(c, xs, xnew, ynew, znew, nu=None):
if (nu is None):
nu = (0, 0, 0)
out = np.empty((len(xnew),), dtype=c.dtype)
(nx, ny, nz) = c.shape[:3]
for (jout, (x, y, z)) in enumerate(zip(xnew, ynew, znew)):
if (not ((xs[0][0] <= x <= xs[0][(-1)]) and (xs[1][0] <= y <= xs[1][(-1)]) and (xs[2][0] <= z <= xs[2][(-1)]))):
out[jout] = np.nan
continue
j1 = (np.searchsorted(xs[0], x) - 1)
j2 = (np.searchsorted(xs[1], y) - 1)
j3 = (np.searchsorted(xs[2], z) - 1)
s1 = (x - xs[0][j1])
s2 = (y - xs[1][j2])
s3 = (z - xs[2][j3])
val = 0
for k1 in range(c.shape[0]):
for k2 in range(c.shape[1]):
for k3 in range(c.shape[2]):
val += (((c[(((nx - k1) - 1), ((ny - k2) - 1), ((nz - k3) - 1), j1, j2, j3)] * _dpow(s1, k1, nu[0])) * _dpow(s2, k2, nu[1])) * _dpow(s3, k3, nu[2]))
out[jout] = val
return out
| null | null | null | Straightforward evaluation of 3D piecewise polynomial | pcsd | def ppoly3d eval c xs xnew ynew znew nu=None if nu is None nu = 0 0 0 out = np empty len xnew dtype=c dtype nx ny nz = c shape[ 3] for jout x y z in enumerate zip xnew ynew znew if not xs[0][0] <= x <= xs[0][ -1 ] and xs[1][0] <= y <= xs[1][ -1 ] and xs[2][0] <= z <= xs[2][ -1 ] out[jout] = np nan continue j1 = np searchsorted xs[0] x - 1 j2 = np searchsorted xs[1] y - 1 j3 = np searchsorted xs[2] z - 1 s1 = x - xs[0][j1] s2 = y - xs[1][j2] s3 = z - xs[2][j3] val = 0 for k1 in range c shape[0] for k2 in range c shape[1] for k3 in range c shape[2] val += c[ nx - k1 - 1 ny - k2 - 1 nz - k3 - 1 j1 j2 j3 ] * dpow s1 k1 nu[0] * dpow s2 k2 nu[1] * dpow s3 k3 nu[2] out[jout] = val return out | 14169 | def _ppoly3d_eval(c, xs, xnew, ynew, znew, nu=None):
if (nu is None):
nu = (0, 0, 0)
out = np.empty((len(xnew),), dtype=c.dtype)
(nx, ny, nz) = c.shape[:3]
for (jout, (x, y, z)) in enumerate(zip(xnew, ynew, znew)):
if (not ((xs[0][0] <= x <= xs[0][(-1)]) and (xs[1][0] <= y <= xs[1][(-1)]) and (xs[2][0] <= z <= xs[2][(-1)]))):
out[jout] = np.nan
continue
j1 = (np.searchsorted(xs[0], x) - 1)
j2 = (np.searchsorted(xs[1], y) - 1)
j3 = (np.searchsorted(xs[2], z) - 1)
s1 = (x - xs[0][j1])
s2 = (y - xs[1][j2])
s3 = (z - xs[2][j3])
val = 0
for k1 in range(c.shape[0]):
for k2 in range(c.shape[1]):
for k3 in range(c.shape[2]):
val += (((c[(((nx - k1) - 1), ((ny - k2) - 1), ((nz - k3) - 1), j1, j2, j3)] * _dpow(s1, k1, nu[0])) * _dpow(s2, k2, nu[1])) * _dpow(s3, k3, nu[2]))
out[jout] = val
return out
| Straightforward evaluation of 3D piecewise polynomial | straightforward evaluation of 3d piecewise polynomial | Question:
What does this function do?
Code:
def _ppoly3d_eval(c, xs, xnew, ynew, znew, nu=None):
if (nu is None):
nu = (0, 0, 0)
out = np.empty((len(xnew),), dtype=c.dtype)
(nx, ny, nz) = c.shape[:3]
for (jout, (x, y, z)) in enumerate(zip(xnew, ynew, znew)):
if (not ((xs[0][0] <= x <= xs[0][(-1)]) and (xs[1][0] <= y <= xs[1][(-1)]) and (xs[2][0] <= z <= xs[2][(-1)]))):
out[jout] = np.nan
continue
j1 = (np.searchsorted(xs[0], x) - 1)
j2 = (np.searchsorted(xs[1], y) - 1)
j3 = (np.searchsorted(xs[2], z) - 1)
s1 = (x - xs[0][j1])
s2 = (y - xs[1][j2])
s3 = (z - xs[2][j3])
val = 0
for k1 in range(c.shape[0]):
for k2 in range(c.shape[1]):
for k3 in range(c.shape[2]):
val += (((c[(((nx - k1) - 1), ((ny - k2) - 1), ((nz - k3) - 1), j1, j2, j3)] * _dpow(s1, k1, nu[0])) * _dpow(s2, k2, nu[1])) * _dpow(s3, k3, nu[2]))
out[jout] = val
return out
|
null | null | null | What does this function do? | def repo_refresh(m):
retvals = {'rc': 0, 'stdout': '', 'stderr': ''}
cmd = get_cmd(m, 'refresh')
retvals['cmd'] = cmd
(result, retvals['rc'], retvals['stdout'], retvals['stderr']) = parse_zypper_xml(m, cmd)
return retvals
| null | null | null | update the repositories | pcsd | def repo refresh m retvals = {'rc' 0 'stdout' '' 'stderr' ''} cmd = get cmd m 'refresh' retvals['cmd'] = cmd result retvals['rc'] retvals['stdout'] retvals['stderr'] = parse zypper xml m cmd return retvals | 14172 | def repo_refresh(m):
retvals = {'rc': 0, 'stdout': '', 'stderr': ''}
cmd = get_cmd(m, 'refresh')
retvals['cmd'] = cmd
(result, retvals['rc'], retvals['stdout'], retvals['stderr']) = parse_zypper_xml(m, cmd)
return retvals
| update the repositories | update the repositories | Question:
What does this function do?
Code:
def repo_refresh(m):
retvals = {'rc': 0, 'stdout': '', 'stderr': ''}
cmd = get_cmd(m, 'refresh')
retvals['cmd'] = cmd
(result, retvals['rc'], retvals['stdout'], retvals['stderr']) = parse_zypper_xml(m, cmd)
return retvals
|
null | null | null | What does this function do? | def check_migration_histories(histories, delete_ghosts=False, ignore_ghosts=False):
exists = SortedSet()
ghosts = []
for h in histories:
try:
m = h.get_migration()
m.migration()
except exceptions.UnknownMigration:
ghosts.append(h)
except ImproperlyConfigured:
pass
else:
exists.add(m)
if ghosts:
if delete_ghosts:
for h in ghosts:
h.delete()
elif (not ignore_ghosts):
raise exceptions.GhostMigrations(ghosts)
return exists
| null | null | null | Checks that there\'s no \'ghost\' migrations in the database. | pcsd | def check migration histories histories delete ghosts=False ignore ghosts=False exists = Sorted Set ghosts = [] for h in histories try m = h get migration m migration except exceptions Unknown Migration ghosts append h except Improperly Configured pass else exists add m if ghosts if delete ghosts for h in ghosts h delete elif not ignore ghosts raise exceptions Ghost Migrations ghosts return exists | 14174 | def check_migration_histories(histories, delete_ghosts=False, ignore_ghosts=False):
exists = SortedSet()
ghosts = []
for h in histories:
try:
m = h.get_migration()
m.migration()
except exceptions.UnknownMigration:
ghosts.append(h)
except ImproperlyConfigured:
pass
else:
exists.add(m)
if ghosts:
if delete_ghosts:
for h in ghosts:
h.delete()
elif (not ignore_ghosts):
raise exceptions.GhostMigrations(ghosts)
return exists
| Checks that there\'s no \'ghost\' migrations in the database. | checks that theres no ghost migrations in the database . | Question:
What does this function do?
Code:
def check_migration_histories(histories, delete_ghosts=False, ignore_ghosts=False):
exists = SortedSet()
ghosts = []
for h in histories:
try:
m = h.get_migration()
m.migration()
except exceptions.UnknownMigration:
ghosts.append(h)
except ImproperlyConfigured:
pass
else:
exists.add(m)
if ghosts:
if delete_ghosts:
for h in ghosts:
h.delete()
elif (not ignore_ghosts):
raise exceptions.GhostMigrations(ghosts)
return exists
|
null | null | null | What does this function do? | def is_hv_pool(metadata):
return (POOL_FLAG in metadata.keys())
| null | null | null | Checks if aggregate is a hypervisor_pool. | pcsd | def is hv pool metadata return POOL FLAG in metadata keys | 14194 | def is_hv_pool(metadata):
return (POOL_FLAG in metadata.keys())
| Checks if aggregate is a hypervisor_pool. | checks if aggregate is a hypervisor _ pool . | Question:
What does this function do?
Code:
def is_hv_pool(metadata):
return (POOL_FLAG in metadata.keys())
|
null | null | null | What does this function do? | def rename_regkey(skey, ssubkey, dsubkey):
res_handle = HANDLE()
options = DWORD(0)
res = RegOpenKeyExW(skey, ssubkey, options, _winreg.KEY_ALL_ACCESS, byref(res_handle))
if (not res):
bsize = c_ushort((len(dsubkey) * 2))
us = UNICODE_STRING()
us.Buffer = c_wchar_p(dsubkey)
us.Length = bsize
us.MaximumLength = bsize
res = NtRenameKey(res_handle, pointer(us))
if res:
log.warning('Error renaming %s\\%s to %s (0x%x)', skey, ssubkey, dsubkey, (res % (2 ** 32)))
if res_handle:
RegCloseKey(res_handle)
| null | null | null | Rename an entire tree of values in the registry.
Function by Thorsten Sick. | pcsd | def rename regkey skey ssubkey dsubkey res handle = HANDLE options = DWORD 0 res = Reg Open Key Ex W skey ssubkey options winreg KEY ALL ACCESS byref res handle if not res bsize = c ushort len dsubkey * 2 us = UNICODE STRING us Buffer = c wchar p dsubkey us Length = bsize us Maximum Length = bsize res = Nt Rename Key res handle pointer us if res log warning 'Error renaming %s\\%s to %s 0x%x ' skey ssubkey dsubkey res % 2 ** 32 if res handle Reg Close Key res handle | 14196 | def rename_regkey(skey, ssubkey, dsubkey):
res_handle = HANDLE()
options = DWORD(0)
res = RegOpenKeyExW(skey, ssubkey, options, _winreg.KEY_ALL_ACCESS, byref(res_handle))
if (not res):
bsize = c_ushort((len(dsubkey) * 2))
us = UNICODE_STRING()
us.Buffer = c_wchar_p(dsubkey)
us.Length = bsize
us.MaximumLength = bsize
res = NtRenameKey(res_handle, pointer(us))
if res:
log.warning('Error renaming %s\\%s to %s (0x%x)', skey, ssubkey, dsubkey, (res % (2 ** 32)))
if res_handle:
RegCloseKey(res_handle)
| Rename an entire tree of values in the registry.
Function by Thorsten Sick. | rename an entire tree of values in the registry . | Question:
What does this function do?
Code:
def rename_regkey(skey, ssubkey, dsubkey):
res_handle = HANDLE()
options = DWORD(0)
res = RegOpenKeyExW(skey, ssubkey, options, _winreg.KEY_ALL_ACCESS, byref(res_handle))
if (not res):
bsize = c_ushort((len(dsubkey) * 2))
us = UNICODE_STRING()
us.Buffer = c_wchar_p(dsubkey)
us.Length = bsize
us.MaximumLength = bsize
res = NtRenameKey(res_handle, pointer(us))
if res:
log.warning('Error renaming %s\\%s to %s (0x%x)', skey, ssubkey, dsubkey, (res % (2 ** 32)))
if res_handle:
RegCloseKey(res_handle)
|
null | null | null | What does this function do? | @utils.arg('network', metavar='<network>', help=_('UUID of network.'))
@utils.arg('host', metavar='<host>', help=_('Name of host'))
@deprecated_network
def do_network_associate_host(cs, args):
cs.networks.associate_host(args.network, args.host)
| null | null | null | Associate host with network. | pcsd | @utils arg 'network' metavar='<network>' help= 'UUID of network ' @utils arg 'host' metavar='<host>' help= 'Name of host' @deprecated network def do network associate host cs args cs networks associate host args network args host | 14204 | @utils.arg('network', metavar='<network>', help=_('UUID of network.'))
@utils.arg('host', metavar='<host>', help=_('Name of host'))
@deprecated_network
def do_network_associate_host(cs, args):
cs.networks.associate_host(args.network, args.host)
| Associate host with network. | associate host with network . | Question:
What does this function do?
Code:
@utils.arg('network', metavar='<network>', help=_('UUID of network.'))
@utils.arg('host', metavar='<host>', help=_('Name of host'))
@deprecated_network
def do_network_associate_host(cs, args):
cs.networks.associate_host(args.network, args.host)
|
null | null | null | What does this function do? | def random_normal():
return inverse_normal_cdf(random.random())
| null | null | null | returns a random draw from a standard normal distribution | pcsd | def random normal return inverse normal cdf random random | 14212 | def random_normal():
return inverse_normal_cdf(random.random())
| returns a random draw from a standard normal distribution | returns a random draw from a standard normal distribution | Question:
What does this function do?
Code:
def random_normal():
return inverse_normal_cdf(random.random())
|
null | null | null | What does this function do? | def get_response(options, address):
remap_addr = {'libc.0': 134522405L, 'libc.1': 715879804}
method = 'GET'
if (address['stack'] in remap_addr):
real_addr = remap_addr[address['stack']]
(cookie, body) = build_payload(options, real_addr, libc=True)
else:
(cookie, body) = build_payload(options, address['stack'], libc=False)
conn = httplib.HTTPSConnection(options.target_ip, options.port)
if (logging.getLogger().level <= logging.DEBUG):
if ((len(body) + len(cookie)) > 10240):
logging.debug((('WARNING: debug mode selected, but the amount of ' + 'data being sent to the server is large (> 10kb). ') + 'Temporarily disabling debug output.'))
else:
conn.set_debuglevel(3)
logging.info(('Sending %s request (%d-byte cookie) to https://%s:%s%s' % (method, len(cookie), options.target_ip, options.port, address['action'])))
try:
conn.request(method, address['action'], body=body, headers={'Cookie': cookie})
except socket.error as e:
print ('Connection error %d: %s' % tuple(e))
sys.exit(1)
return conn.getresponse()
| null | null | null | Send an exploit to the target and get its response. | pcsd | def get response options address remap addr = {'libc 0' 134522405L 'libc 1' 715879804} method = 'GET' if address['stack'] in remap addr real addr = remap addr[address['stack']] cookie body = build payload options real addr libc=True else cookie body = build payload options address['stack'] libc=False conn = httplib HTTPS Connection options target ip options port if logging get Logger level <= logging DEBUG if len body + len cookie > 10240 logging debug 'WARNING debug mode selected but the amount of ' + 'data being sent to the server is large > 10kb ' + 'Temporarily disabling debug output ' else conn set debuglevel 3 logging info 'Sending %s request %d-byte cookie to https //%s %s%s' % method len cookie options target ip options port address['action'] try conn request method address['action'] body=body headers={'Cookie' cookie} except socket error as e print 'Connection error %d %s' % tuple e sys exit 1 return conn getresponse | 14225 | def get_response(options, address):
remap_addr = {'libc.0': 134522405L, 'libc.1': 715879804}
method = 'GET'
if (address['stack'] in remap_addr):
real_addr = remap_addr[address['stack']]
(cookie, body) = build_payload(options, real_addr, libc=True)
else:
(cookie, body) = build_payload(options, address['stack'], libc=False)
conn = httplib.HTTPSConnection(options.target_ip, options.port)
if (logging.getLogger().level <= logging.DEBUG):
if ((len(body) + len(cookie)) > 10240):
logging.debug((('WARNING: debug mode selected, but the amount of ' + 'data being sent to the server is large (> 10kb). ') + 'Temporarily disabling debug output.'))
else:
conn.set_debuglevel(3)
logging.info(('Sending %s request (%d-byte cookie) to https://%s:%s%s' % (method, len(cookie), options.target_ip, options.port, address['action'])))
try:
conn.request(method, address['action'], body=body, headers={'Cookie': cookie})
except socket.error as e:
print ('Connection error %d: %s' % tuple(e))
sys.exit(1)
return conn.getresponse()
| Send an exploit to the target and get its response. | send an exploit to the target and get its response . | Question:
What does this function do?
Code:
def get_response(options, address):
remap_addr = {'libc.0': 134522405L, 'libc.1': 715879804}
method = 'GET'
if (address['stack'] in remap_addr):
real_addr = remap_addr[address['stack']]
(cookie, body) = build_payload(options, real_addr, libc=True)
else:
(cookie, body) = build_payload(options, address['stack'], libc=False)
conn = httplib.HTTPSConnection(options.target_ip, options.port)
if (logging.getLogger().level <= logging.DEBUG):
if ((len(body) + len(cookie)) > 10240):
logging.debug((('WARNING: debug mode selected, but the amount of ' + 'data being sent to the server is large (> 10kb). ') + 'Temporarily disabling debug output.'))
else:
conn.set_debuglevel(3)
logging.info(('Sending %s request (%d-byte cookie) to https://%s:%s%s' % (method, len(cookie), options.target_ip, options.port, address['action'])))
try:
conn.request(method, address['action'], body=body, headers={'Cookie': cookie})
except socket.error as e:
print ('Connection error %d: %s' % tuple(e))
sys.exit(1)
return conn.getresponse()
|
null | null | null | What does this function do? | def is_file_into_dir(filename, dirname):
try:
res = (not os.path.relpath(filename, dirname).startswith(u'.'))
except ValueError:
res = False
return res
| null | null | null | Check if a file is in directory. | pcsd | def is file into dir filename dirname try res = not os path relpath filename dirname startswith u' ' except Value Error res = False return res | 14231 | def is_file_into_dir(filename, dirname):
try:
res = (not os.path.relpath(filename, dirname).startswith(u'.'))
except ValueError:
res = False
return res
| Check if a file is in directory. | check if a file is in directory . | Question:
What does this function do?
Code:
def is_file_into_dir(filename, dirname):
try:
res = (not os.path.relpath(filename, dirname).startswith(u'.'))
except ValueError:
res = False
return res
|
null | null | null | What does this function do? | def deg2pix(degrees, monitor, correctFlat=False):
scrWidthCm = monitor.getWidth()
scrSizePix = monitor.getSizePix()
if (scrSizePix is None):
msg = 'Monitor %s has no known size in pixels (SEE MONITOR CENTER)'
raise ValueError((msg % monitor.name))
if (scrWidthCm is None):
msg = 'Monitor %s has no known width in cm (SEE MONITOR CENTER)'
raise ValueError((msg % monitor.name))
cmSize = deg2cm(degrees, monitor, correctFlat)
return ((cmSize * scrSizePix[0]) / float(scrWidthCm))
| null | null | null | Convert size in degrees to size in pixels for a given Monitor object | pcsd | def deg2pix degrees monitor correct Flat=False scr Width Cm = monitor get Width scr Size Pix = monitor get Size Pix if scr Size Pix is None msg = 'Monitor %s has no known size in pixels SEE MONITOR CENTER ' raise Value Error msg % monitor name if scr Width Cm is None msg = 'Monitor %s has no known width in cm SEE MONITOR CENTER ' raise Value Error msg % monitor name cm Size = deg2cm degrees monitor correct Flat return cm Size * scr Size Pix[0] / float scr Width Cm | 14234 | def deg2pix(degrees, monitor, correctFlat=False):
scrWidthCm = monitor.getWidth()
scrSizePix = monitor.getSizePix()
if (scrSizePix is None):
msg = 'Monitor %s has no known size in pixels (SEE MONITOR CENTER)'
raise ValueError((msg % monitor.name))
if (scrWidthCm is None):
msg = 'Monitor %s has no known width in cm (SEE MONITOR CENTER)'
raise ValueError((msg % monitor.name))
cmSize = deg2cm(degrees, monitor, correctFlat)
return ((cmSize * scrSizePix[0]) / float(scrWidthCm))
| Convert size in degrees to size in pixels for a given Monitor object | convert size in degrees to size in pixels for a given monitor object | Question:
What does this function do?
Code:
def deg2pix(degrees, monitor, correctFlat=False):
scrWidthCm = monitor.getWidth()
scrSizePix = monitor.getSizePix()
if (scrSizePix is None):
msg = 'Monitor %s has no known size in pixels (SEE MONITOR CENTER)'
raise ValueError((msg % monitor.name))
if (scrWidthCm is None):
msg = 'Monitor %s has no known width in cm (SEE MONITOR CENTER)'
raise ValueError((msg % monitor.name))
cmSize = deg2cm(degrees, monitor, correctFlat)
return ((cmSize * scrSizePix[0]) / float(scrWidthCm))
|
null | null | null | What does this function do? | def main():
defaults = {'TEST_APP': ('gcpfront50test' + GoogleFront50TestScenario.DEFAULT_TEST_ID)}
return citest.base.TestRunner.main(parser_inits=[GoogleFront50TestScenario.initArgumentParser], default_binding_overrides=defaults, test_case_list=[GoogleFront50Test])
| null | null | null | Implements the main method running this smoke test. | pcsd | def main defaults = {'TEST APP' 'gcpfront50test' + Google Front50Test Scenario DEFAULT TEST ID } return citest base Test Runner main parser inits=[Google Front50Test Scenario init Argument Parser] default binding overrides=defaults test case list=[Google Front50Test] | 14238 | def main():
defaults = {'TEST_APP': ('gcpfront50test' + GoogleFront50TestScenario.DEFAULT_TEST_ID)}
return citest.base.TestRunner.main(parser_inits=[GoogleFront50TestScenario.initArgumentParser], default_binding_overrides=defaults, test_case_list=[GoogleFront50Test])
| Implements the main method running this smoke test. | implements the main method running this smoke test . | Question:
What does this function do?
Code:
def main():
defaults = {'TEST_APP': ('gcpfront50test' + GoogleFront50TestScenario.DEFAULT_TEST_ID)}
return citest.base.TestRunner.main(parser_inits=[GoogleFront50TestScenario.initArgumentParser], default_binding_overrides=defaults, test_case_list=[GoogleFront50Test])
|
null | null | null | What does this function do? | @handle_response_format
@treeio_login_required
@_process_mass_form
def index_owned(request, response_format='html'):
query = Q(parent__isnull=True, caller__related_user=request.user.profile)
if request.GET:
if (('status' in request.GET) and request.GET['status']):
query = (query & _get_filter_query(request.GET))
else:
query = ((query & Q(status__hidden=False)) & _get_filter_query(request.GET))
else:
query = (query & Q(status__hidden=False))
tasks = Object.filter_by_request(request, Task.objects.filter(query))
milestones = Object.filter_by_request(request, Milestone.objects.filter(status__hidden=False))
filters = FilterForm(request.user.profile, 'status', request.GET)
context = _get_default_context(request)
context.update({'milestones': milestones, 'tasks': tasks, 'filters': filters})
return render_to_response('projects/index_owned', context, context_instance=RequestContext(request), response_format=response_format)
| null | null | null | Tasks owned by current user | pcsd | @handle response format @treeio login required @ process mass form def index owned request response format='html' query = Q parent isnull=True caller related user=request user profile if request GET if 'status' in request GET and request GET['status'] query = query & get filter query request GET else query = query & Q status hidden=False & get filter query request GET else query = query & Q status hidden=False tasks = Object filter by request request Task objects filter query milestones = Object filter by request request Milestone objects filter status hidden=False filters = Filter Form request user profile 'status' request GET context = get default context request context update {'milestones' milestones 'tasks' tasks 'filters' filters} return render to response 'projects/index owned' context context instance=Request Context request response format=response format | 14252 | @handle_response_format
@treeio_login_required
@_process_mass_form
def index_owned(request, response_format='html'):
query = Q(parent__isnull=True, caller__related_user=request.user.profile)
if request.GET:
if (('status' in request.GET) and request.GET['status']):
query = (query & _get_filter_query(request.GET))
else:
query = ((query & Q(status__hidden=False)) & _get_filter_query(request.GET))
else:
query = (query & Q(status__hidden=False))
tasks = Object.filter_by_request(request, Task.objects.filter(query))
milestones = Object.filter_by_request(request, Milestone.objects.filter(status__hidden=False))
filters = FilterForm(request.user.profile, 'status', request.GET)
context = _get_default_context(request)
context.update({'milestones': milestones, 'tasks': tasks, 'filters': filters})
return render_to_response('projects/index_owned', context, context_instance=RequestContext(request), response_format=response_format)
| Tasks owned by current user | tasks owned by current user | Question:
What does this function do?
Code:
@handle_response_format
@treeio_login_required
@_process_mass_form
def index_owned(request, response_format='html'):
query = Q(parent__isnull=True, caller__related_user=request.user.profile)
if request.GET:
if (('status' in request.GET) and request.GET['status']):
query = (query & _get_filter_query(request.GET))
else:
query = ((query & Q(status__hidden=False)) & _get_filter_query(request.GET))
else:
query = (query & Q(status__hidden=False))
tasks = Object.filter_by_request(request, Task.objects.filter(query))
milestones = Object.filter_by_request(request, Milestone.objects.filter(status__hidden=False))
filters = FilterForm(request.user.profile, 'status', request.GET)
context = _get_default_context(request)
context.update({'milestones': milestones, 'tasks': tasks, 'filters': filters})
return render_to_response('projects/index_owned', context, context_instance=RequestContext(request), response_format=response_format)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.