uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e599c992ee9e56d7658fef2 | train | function | def exec_with_trap(the_question, the_dict, old_variable=None):
try:
exec(the_question.compute, the_dict)
the_question.post_exec(the_dict)
except (NameError, UndefinedError, CommandError, ResponseError, BackgroundResponseError, BackgroundResponseActionError, QuestionError, AttributeError, Mandato... | def exec_with_trap(the_question, the_dict, old_variable=None):
| try:
exec(the_question.compute, the_dict)
the_question.post_exec(the_dict)
except (NameError, UndefinedError, CommandError, ResponseError, BackgroundResponseError, BackgroundResponseActionError, QuestionError, AttributeError, MandatoryQuestion, CodeExecute, SyntaxException, CompileException):
... |
if re.search(r'[\n\r\(\)\{\}\*\^\#]', varname):
return True
varname = re.sub(r'[\.\[].*', '', varname)
if not valid_variable_match.match(varname):
return True
return False
def exec_with_trap(the_question, the_dict, old_variable=None):
| 76 | 76 | 254 | 15 | 60 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | exec_with_trap | exec_with_trap | 8,832 | 8,855 | 8,832 | 8,832 | c1846b991f52412c8e4a0710923fd5315585482a | bigcode/the-stack | train |
0064e3bcb518a1d7eb75398b | train | function | def url_sanitize(url):
return re.sub(r'\s', ' ', url)
| def url_sanitize(url):
| return re.sub(r'\s', ' ', url)
| return output
def docx_variable_fix(variable):
variable = re.sub(r'\\', '', variable)
variable = re.sub(r'^([A-Za-z\_][A-Za-z\_0-9]*).*', r'\1', variable)
return variable
def url_sanitize(url):
| 64 | 64 | 18 | 6 | 57 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | url_sanitize | url_sanitize | 1,650 | 1,651 | 1,650 | 1,650 | 721c1c745fef40aff44bc0ed1a12516053893eec | bigcode/the-stack | train |
cd9662485d05ae4b413ca273 | train | class | class InterviewStatus:
def __init__(self, current_info=dict(), **kwargs):
self.current_info = current_info
self.attributions = set()
self.seeking = list()
self.tracker = kwargs.get('tracker', -1)
self.maps = list()
self.extra_scripts = list()
self.extra_css = ... | class InterviewStatus:
| def __init__(self, current_info=dict(), **kwargs):
self.current_info = current_info
self.attributions = set()
self.seeking = list()
self.tracker = kwargs.get('tracker', -1)
self.maps = list()
self.extra_scripts = list()
self.extra_css = list()
self.usi... | **kwargs):
self.set_path(kwargs.get('path', None))
return super().__init__(**kwargs)
def set_path(self, path):
self.path = path
if self.path is None:
self.directory = None
else:
self.directory = re.sub('/[^/]*$', '', re.sub('\?.*', '', self.path))
... | 256 | 256 | 14,270 | 4 | 251 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | InterviewStatus | InterviewStatus | 357 | 1,312 | 357 | 357 | f4907263e542ff7a51cf091f66765688b23376b3 | bigcode/the-stack | train |
8bdea26c9c81c6e1ea3d9705 | train | function | def strip_tags(html):
s = MLStripper()
s.feed(html)
return s.get_data()
| def strip_tags(html):
| s = MLStripper()
s.feed(html)
return s.get_data()
| self):
super().__init__()
self.reset()
self.strict = False
self.convert_charrefs= True
self.text = StringIO()
def handle_data(self, d):
self.text.write(d)
def get_data(self):
return self.text.getvalue()
def strip_tags(html):
| 64 | 64 | 23 | 5 | 59 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | strip_tags | strip_tags | 9,334 | 9,337 | 9,334 | 9,334 | 4b01f40e9db728cb9b65759e3e373aaff29ff3b1 | bigcode/the-stack | train |
d998b856b842d1441ba6840f | train | function | def dummy_embed_input(status, variable):
return variable
| def dummy_embed_input(status, variable):
| return variable
| os.access(new_file, os.R_OK):
new_source = InterviewSourceFile()
new_source.path = path
new_source.directory = self.directory
new_source.filepath = new_file
if new_source.update():
return(new_source)
return None
def dummy_embed_input(s... | 64 | 64 | 12 | 8 | 55 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | dummy_embed_input | dummy_embed_input | 354 | 355 | 354 | 354 | 2da4c25888acb281409e14a6f02f062c7d5db1b1 | bigcode/the-stack | train |
3fd69ea3b4581495e8f4fece | train | class | class DAExtension(Extension):
def filter_stream(self, stream):
in_var = False
met_pipe = False
for token in stream:
if token.type == 'variable_begin':
in_var = True
met_pipe = False
if token.type == 'variable_end':
in_va... | class DAExtension(Extension):
| def filter_stream(self, stream):
in_var = False
met_pipe = False
for token in stream:
if token.type == 'variable_begin':
in_var = True
met_pipe = False
if token.type == 'variable_end':
in_var = False
if n... | if final_cut > 0:
final_parts = (var[0:final_cut], var[final_cut:])
else:
final_parts = (var, '')
return dict(valid=True, objects=objects, bracket_objects=bracket_objects, final_parts=final_parts)
class DAExtension(Extension):
| 64 | 64 | 126 | 6 | 58 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | DAExtension | DAExtension | 8,938 | 8,953 | 8,938 | 8,938 | 900f87eb54099130575d21ad7eeb68986fac35fd | bigcode/the-stack | train |
f233f01c3780366fee183b5c | train | function | def substitute_vars_action(action, is_generic, the_x, iterators):
if isinstance(action, str):
return substitute_vars(action, is_generic, the_x, iterators)
elif isinstance(action, dict):
new_dict = dict()
for key, val in action.items():
if key == 'action' and not key.startswit... | def substitute_vars_action(action, is_generic, the_x, iterators):
| if isinstance(action, str):
return substitute_vars(action, is_generic, the_x, iterators)
elif isinstance(action, dict):
new_dict = dict()
for key, val in action.items():
if key == 'action' and not key.startswith('_da_'):
new_dict[key] = substitute_vars_action(... | list_of_indices[indexno] + r'\]', '[' + repr(the_iterator) + ']', var)
var = re.sub(r'\[' + list_of_indices[indexno] + r'\]', '[' + str(iterators[indexno]) + ']', var)
return var
def substitute_vars_action(action, is_generic, the_x, iterators):
| 72 | 72 | 240 | 15 | 56 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | substitute_vars_action | substitute_vars_action | 8,567 | 8,588 | 8,567 | 8,567 | 8f5e56fd32ac828322cf68a273d6d0f3454869b3 | bigcode/the-stack | train |
e4effd50439e93f96f30dac1 | train | class | class DAEnvironment(Environment):
def from_string(self, source, **kwargs):
source = re.sub(r'({[\%\{].*?[\%\}]})', fix_quotes, source)
return super().from_string(source, **kwargs)
def getitem(self, obj, argument):
try:
return obj[argument]
except (AttributeError, Type... | class DAEnvironment(Environment):
| def from_string(self, source, **kwargs):
source = re.sub(r'({[\%\{].*?[\%\}]})', fix_quotes, source)
return super().from_string(source, **kwargs)
def getitem(self, obj, argument):
try:
return obj[argument]
except (AttributeError, TypeError, LookupError):
r... |
if not met_pipe:
yield Token(token.lineno, 'pipe', None)
yield Token(token.lineno, 'name', 'ampersand_filter')
# if in_var and token.type == 'pipe':
# met_pipe = True
yield token
class DAEnvironment(Environment):
| 64 | 64 | 141 | 5 | 58 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | DAEnvironment | DAEnvironment | 8,955 | 8,970 | 8,955 | 8,955 | 152d1455cf5fda28bff50ee624dff384531b3972 | bigcode/the-stack | train |
afec074721a2a8b5a9da4eee | train | class | class InterviewSource:
def __init__(self, **kwargs):
if not hasattr(self, 'package'):
self.package = kwargs.get('package', None)
self.language = kwargs.get('language', '*')
self.dialect = kwargs.get('dialect', None)
self.testing = kwargs.get('testing', False)
self... | class InterviewSource:
| def __init__(self, **kwargs):
if not hasattr(self, 'package'):
self.package = kwargs.get('package', None)
self.language = kwargs.get('language', '*')
self.dialect = kwargs.get('dialect', None)
self.testing = kwargs.get('testing', False)
self.translating = kwargs.g... | =None, modtime=None, accesstime=dict(), tasks=dict(), gather=list(), event_stack=dict(), misc=dict()), url_args=dict(), nav=docassemble.base.functions.DANav())
def set_initial_dict(the_dict):
global initial_dict
initial_dict = the_dict
return
def get_initial_dict():
return copy.deepcopy(initial_dict);... | 207 | 207 | 690 | 4 | 203 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | InterviewSource | InterviewSource | 145 | 226 | 145 | 145 | 172ac87b660879be39606bfbd98b5939233858c4 | bigcode/the-stack | train |
b63dd40aff75565d9f7ebb12 | train | function | def custom_jinja_env():
env = DAEnvironment(undefined=DAStrictUndefined, extensions=[DAExtension])
env.filters['ampersand_filter'] = ampersand_filter
env.filters['markdown'] = markdown_filter
env.filters['add_separators'] = docassemble.base.functions.add_separators
env.filters['inline_markdown'] = i... | def custom_jinja_env():
| env = DAEnvironment(undefined=DAStrictUndefined, extensions=[DAExtension])
env.filters['ampersand_filter'] = ampersand_filter
env.filters['markdown'] = markdown_filter
env.filters['add_separators'] = docassemble.base.functions.add_separators
env.filters['inline_markdown'] = inline_markdown_filter
... | add__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \
__truediv__ = __rtruediv__ = __floordiv__ = __rfloordiv__ = \
__mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \
__getitem__ = __lt__ = __le__ = __gt__ = __ge__ = __int__ = \
__float__ = __complex__ = __pow__ = __rpow__ = __sub__ = \... | 176 | 176 | 587 | 6 | 169 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | custom_jinja_env | custom_jinja_env | 9,049 | 9,091 | 9,049 | 9,049 | 9535bdf9a4ea08ce3c96a4d5698ce1458aec0e6d | bigcode/the-stack | train |
677f49d88c69234fd278021a | train | function | def recursive_textobject(target, question):
if isinstance(target, dict) or (hasattr(target, 'elements') and isinstance(target.elements, dict)):
new_dict = dict()
for key, val in target.items():
new_dict[key] = recursive_textobject(val, question)
return new_dict
if isinstance(... | def recursive_textobject(target, question):
| if isinstance(target, dict) or (hasattr(target, 'elements') and isinstance(target.elements, dict)):
new_dict = dict()
for key, val in target.items():
new_dict[key] = recursive_textobject(val, question)
return new_dict
if isinstance(target, list) or (hasattr(target, 'elements'... | new_set = set()
for val in target:
new_set.add(recursive_eval_data_from_code(val, the_user_dict))
return new_set
if isinstance(target, CodeType):
return eval(target, the_user_dict)
else:
return target
def recursive_textobject(target, question):
| 64 | 64 | 185 | 8 | 55 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | recursive_textobject | recursive_textobject | 1,536 | 1,552 | 1,536 | 1,536 | 55e70178da7e9efe1f32494dd0dc5de0392a5e22 | bigcode/the-stack | train |
cc96f1be91bccd2200497919 | train | function | def recurse_indices(expression_array, variable_list, pre_part, final_list, var_subs_dict, var_subs, generic_dict, generic):
if len(expression_array) == 0:
return
the_expr = "".join(pre_part) + "".join(expression_array)
if the_expr not in final_list and the_expr != 'x':
final_list.append(the_... | def recurse_indices(expression_array, variable_list, pre_part, final_list, var_subs_dict, var_subs, generic_dict, generic):
| if len(expression_array) == 0:
return
the_expr = "".join(pre_part) + "".join(expression_array)
if the_expr not in final_list and the_expr != 'x':
final_list.append(the_expr)
var_subs_dict[the_expr] = var_subs
generic_dict[the_expr] = "".join(generic)
first_part = expressi... | mimetype, encoding = mimetypes.guess_type(filename)
extension = filename.lower()
extension = re.sub('.*\.', '', extension)
if extension == '3gpp':
mimetype = 'audio/3gpp'
if mimetype is None:
mimetype = 'text/plain'
return mimetype
def interpret_label(text):
if text is None:
... | 122 | 122 | 407 | 29 | 93 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | recurse_indices | recurse_indices | 8,738 | 8,760 | 8,738 | 8,738 | a0d1a067fe448192d0968a2e0e75516b910b4f13 | bigcode/the-stack | train |
a57c754a1564358df867e9f6 | train | function | def ensure_object_exists(saveas, datatype, the_user_dict, commands=None):
# logmessage("ensure object exists: " + str(saveas))
if commands is None:
execute = True
commands = list()
else:
execute = False
already_there = False
try:
eval(saveas, the_user_dict)
al... | def ensure_object_exists(saveas, datatype, the_user_dict, commands=None):
# logmessage("ensure object exists: " + str(saveas))
| if commands is None:
execute = True
commands = list()
else:
execute = False
already_there = False
try:
eval(saveas, the_user_dict)
already_there = True
except:
pass
if already_there:
#logmessage("ensure object exists: already there")
... | len(new_var_subs) == 0 and len(generic) == 0:
recurse_indices(copy.copy(expression_array), new_list_of_indices, ['x', '[' + var_to_use + ']'], final_list, var_subs_dict, new_var_subs, generic_dict, copy.copy(pre_part))
pre_part.append(first_part)
recurse_indices(copy.copy(expression_array), variabl... | 190 | 190 | 635 | 31 | 159 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | ensure_object_exists | ensure_object_exists | 8,762 | 8,820 | 8,762 | 8,763 | 1e043c2dffe9b4bf1c6fabcf61d452f599b3f093 | bigcode/the-stack | train |
38ea05a75447541463afdc43 | train | class | class FileOnServer:
def __init__(self, fileref, question):
self.fileref = fileref
self.question = question
def path(self):
info = docassemble.base.functions.server.file_finder(self.fileref, question=self.question)
if 'fullpath' in info and info['fullpath']:
return inf... | class FileOnServer:
| def __init__(self, fileref, question):
self.fileref = fileref
self.question = question
def path(self):
info = docassemble.base.functions.server.file_finder(self.fileref, question=self.question)
if 'fullpath' in info and info['fullpath']:
return info['fullpath']
... | final_result = []
for the_file_ref in result:
if not str(the_file_ref).startswith('/'):
final_result.append(docassemble.base.functions.package_template_filename(str(the_file_ref), package=self.package))
else:
final_result.append(the_fi... | 64 | 64 | 96 | 5 | 58 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | FileOnServer | FileOnServer | 1,729 | 1,737 | 1,729 | 1,729 | 38b096b1937ccf9bc4e4830b0f98a471927287fc | bigcode/the-stack | train |
930c9827f437b97b85e30ecc | train | class | class DAStrictUndefined(StrictUndefined):
__slots__ = ('_undefined_type')
def __init__(self, hint=None, obj=missing, name=None, exc=UndefinedError, accesstype=None):
self._undefined_hint = hint
self._undefined_obj = obj
self._undefined_name = name
self._undefined_exception = exc
... | class DAStrictUndefined(StrictUndefined):
| __slots__ = ('_undefined_type')
def __init__(self, hint=None, obj=missing, name=None, exc=UndefinedError, accesstype=None):
self._undefined_hint = hint
self._undefined_obj = obj
self._undefined_name = name
self._undefined_exception = exc
self._undefined_type = accesstype
... | .__class__.__name__ in ('DAFile', 'DALink', 'DAStaticFile', 'DAFileCollection', 'DAFileList'):
return value
if value.__class__.__name__ in ('InlineImage', 'RichText', 'Listing', 'Document', 'Subdoc', 'DALazyTemplate'):
return str(value)
if isinstance(value, (int, bool, float, NoneType)):
... | 192 | 192 | 643 | 9 | 183 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | DAStrictUndefined | DAStrictUndefined | 8,985 | 9,047 | 8,985 | 8,985 | cd17c032dc6f79a980e883cf29a23184fa24ca40 | bigcode/the-stack | train |
2739afe8d073f4d1ee8101bf | train | class | class FileInPackage:
def __init__(self, fileref, area, package):
if area == 'template' and not isinstance(fileref, dict):
docassemble.base.functions.package_template_filename(fileref, package=package)
self.fileref = fileref
if isinstance(self.fileref, dict):
self.is_c... | class FileInPackage:
| def __init__(self, fileref, area, package):
if area == 'template' and not isinstance(fileref, dict):
docassemble.base.functions.package_template_filename(fileref, package=package)
self.fileref = fileref
if isinstance(self.fileref, dict):
self.is_code = True
... | raise DAError("recursive_eval_textobject_or_primitive: expected a TextObject, but found a " + str(type(target)))
def fix_quotes(match):
instring = match.group(1)
n = len(instring)
output = ''
i = 0
while i < n:
if instring[i] == '\u201c' or instring[i] == '\u201d':
output += '"... | 256 | 256 | 872 | 5 | 251 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | FileInPackage | FileInPackage | 1,653 | 1,727 | 1,653 | 1,653 | 86c73d8c187ad665a82ebf8ff308f6d6e308a27c | bigcode/the-stack | train |
474efdf7e3ea74150b1852c4 | train | function | def get_docx_variables(the_path):
import docassemble.base.legal
names = set()
if not os.path.isfile(the_path):
raise DAError("Missing docx template file " + os.path.basename(the_path))
try:
docx_template = docassemble.base.file_docx.DocxTemplate(the_path)
the_env = custom_jinja_e... | def get_docx_variables(the_path):
| import docassemble.base.legal
names = set()
if not os.path.isfile(the_path):
raise DAError("Missing docx template file " + os.path.basename(the_path))
try:
docx_template = docassemble.base.file_docx.DocxTemplate(the_path)
the_env = custom_jinja_env()
the_xml = docx_templa... | _thread.current_question, docassemble.base.functions.this_thread.misc.get('docx_template', None))
def inline_markdown_filter(text):
return docassemble.base.file_docx.inline_markdown_to_docx(str(text), docassemble.base.functions.this_thread.current_question, docassemble.base.functions.this_thread.misc.get('docx_tem... | 75 | 75 | 251 | 8 | 67 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | get_docx_variables | get_docx_variables | 9,273 | 9,294 | 9,273 | 9,273 | d9f8b29291ea01946673289df81b60fea83593fb | bigcode/the-stack | train |
6947ab19e09b6a00f16e760c | train | function | def dictsort_filter(dictionary, case_sensitive=False, by='key', reverse=False):
if by == 'value':
return sorted(dictionary.items(), key=lambda y: str_or_original(y[1], case_sensitive), reverse=reverse)
else:
return sorted(dictionary.items(), key=lambda y: str_or_original(y[0], case_sensitive), r... | def dictsort_filter(dictionary, case_sensitive=False, by='key', reverse=False):
| if by == 'value':
return sorted(dictionary.items(), key=lambda y: str_or_original(y[1], case_sensitive), reverse=reverse)
else:
return sorted(dictionary.items(), key=lambda y: str_or_original(y[0], case_sensitive), reverse=reverse)
| 'instanceName'):
if y.__class__.__name__ in ('Value', 'PeriodicValue'):
return y.amount()
return str(y).lower()
try:
return y.lower()
except:
return y
def dictsort_filter(dictionary, case_sensitive=False, by='key', reverse=False):
| 64 | 64 | 75 | 17 | 46 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | dictsort_filter | dictsort_filter | 9,114 | 9,118 | 9,114 | 9,114 | 1c76fae91c09d203d3149c997fe3935b6a5a2e11 | bigcode/the-stack | train |
a3fafbf9d4d6204c1f38ee80 | train | function | def recursive_eval_textobject_or_primitive(target, the_user_dict):
if isinstance(target, dict) or (hasattr(target, 'elements') and isinstance(target.elements, dict)):
new_dict = dict()
for key, val in target.items():
new_dict[key] = recursive_eval_textobject_or_primitive(val, the_user_di... | def recursive_eval_textobject_or_primitive(target, the_user_dict):
| if isinstance(target, dict) or (hasattr(target, 'elements') and isinstance(target.elements, dict)):
new_dict = dict()
for key, val in target.items():
new_dict[key] = recursive_eval_textobject_or_primitive(val, the_user_dict)
return new_dict
if isinstance(target, list) or (has... | new_set = set()
for val in target.__iter__():
new_set.add(recursive_textobject_or_primitive(val, question))
return new_set
if isinstance(target, (int, bool, float, NoneType)):
return target
return TextObject(str(target), question=question)
def recursive_eval_textobject_or_pr... | 78 | 78 | 263 | 14 | 64 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | recursive_eval_textobject_or_primitive | recursive_eval_textobject_or_primitive | 1,604 | 1,625 | 1,604 | 1,604 | 65e32bc0ceb744bceb21d1b1373af2eeebdb6788 | bigcode/the-stack | train |
e5ea5be6549b97b525b85a32 | train | function | def sum_filter(array, attribute=None, start=0):
if attribute is not None:
array = [mygetattr(y, attribute) for y in array]
return sum(array, start)
| def sum_filter(array, attribute=None, start=0):
| if attribute is not None:
array = [mygetattr(y, attribute) for y in array]
return sum(array, start)
| str_or_original(mygetattr(y, attribute), case_sensitive=case_sensitive)
else:
def key_func(y):
return str_or_original(y, case_sensitive=case_sensitive)
return min(chain([first], it), key=key_func)
def sum_filter(array, attribute=None, start=0):
| 64 | 64 | 42 | 12 | 52 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | sum_filter | sum_filter | 9,173 | 9,176 | 9,173 | 9,173 | 55555bc518080575675b171b232ded4103fefbe3 | bigcode/the-stack | train |
39f56bb58591d81c3c7379f1 | train | function | def process_selections(data, manual=False, exclude=None):
if exclude is None:
to_exclude = list()
else:
to_exclude = unpack_list(exclude)
result = []
if (isinstance(data, abc.Iterable) and not isinstance(data, (str, dict)) and not (hasattr(data, 'elements') and isinstance(data.elements, ... | def process_selections(data, manual=False, exclude=None):
| if exclude is None:
to_exclude = list()
else:
to_exclude = unpack_list(exclude)
result = []
if (isinstance(data, abc.Iterable) and not isinstance(data, (str, dict)) and not (hasattr(data, 'elements') and isinstance(data.elements, dict))) or (hasattr(data, 'elements') and isinstance(data.... | , iterators)
elif key == 'arguments' and isinstance(val, dict) and 'variables' in val and len(val) == 1:
new_dict[key] = substitute_vars_action(val, is_generic, the_x, iterators)
elif key == 'variables' and isinstance(val, list):
new_dict[key] = substitute_vars_ac... | 256 | 256 | 977 | 12 | 243 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | process_selections | process_selections | 8,604 | 8,679 | 8,604 | 8,604 | d4425c8211996116937359be365b314e3e86b85f | bigcode/the-stack | train |
02a3d823ed0f27cbb5dd37e2 | train | function | def safeid(text):
return re.sub(r'[\n=]', '', codecs.encode(text.encode('utf8'), 'base64').decode())
| def safeid(text):
| return re.sub(r'[\n=]', '', codecs.encode(text.encode('utf8'), 'base64').decode())
| _mako:
return(self.template.render(**the_user_dict))
else:
return(self.original_text)
def myb64quote(text):
return "'" + re.sub(r'[\n=]', '', codecs.encode(text.encode('utf8'), 'base64').decode()) + "'"
def safeid(text):
| 64 | 64 | 30 | 5 | 58 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | safeid | safeid | 1,375 | 1,376 | 1,375 | 1,375 | c7d621efbc6de45165e8cbc8dce43b17f1f6ce80 | bigcode/the-stack | train |
9f1068fc6773a849b867071b | train | function | def repad(text):
return text + (equals_byte * ((4 - len(text) % 4) % 4))
| def repad(text):
| return text + (equals_byte * ((4 - len(text) % 4) % 4))
| (text):
return re.sub(r'[\n=]', '', codecs.encode(text.encode('utf8'), 'base64').decode())
def from_safeid(text):
return(codecs.decode(repad(bytearray(text, encoding='utf-8')), 'base64').decode('utf8'))
def repad(text):
| 64 | 64 | 27 | 5 | 59 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | repad | repad | 1,381 | 1,382 | 1,381 | 1,381 | c819f8cc2914b173818a3b5f4509f25be40e2c72 | bigcode/the-stack | train |
e3d998ffdaa19a3bcef1c551 | train | function | def process_audio_video_list(the_list, the_user_dict):
output = list()
for the_item in the_list:
output.append({'text': the_item['text'].text(the_user_dict), 'package': the_item['package'], 'type': the_item['type']})
return output
| def process_audio_video_list(the_list, the_user_dict):
| output = list()
for the_item in the_list:
output.append({'text': the_item['text'].text(the_user_dict), 'package': the_item['package'], 'type': the_item['type']})
return output
| x', 'rtf': 'rtf', 'rtf to docx': 'docx', 'tex': 'tex', 'html': 'html'}
do_not_translate = """<%doc>
do not translate
</%doc>
"""
def process_audio_video_list(the_list, the_user_dict):
| 64 | 64 | 62 | 12 | 52 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | process_audio_video_list | process_audio_video_list | 86 | 90 | 86 | 86 | 2cdb285bf6ea59126db1a6c8c4d6870ab5f2f1ba | bigcode/the-stack | train |
3c54a418139961405fc37581 | train | function | def docx_variable_fix(variable):
variable = re.sub(r'\\', '', variable)
variable = re.sub(r'^([A-Za-z\_][A-Za-z\_0-9]*).*', r'\1', variable)
return variable
| def docx_variable_fix(variable):
| variable = re.sub(r'\\', '', variable)
variable = re.sub(r'^([A-Za-z\_][A-Za-z\_0-9]*).*', r'\1', variable)
return variable
| string[i] == '&' and i + 4 < n and instring[i:i+5] == '&':
output += '&'
i += 4
else:
output += instring[i]
i += 1
return output
def docx_variable_fix(variable):
| 64 | 64 | 54 | 7 | 56 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | docx_variable_fix | docx_variable_fix | 1,645 | 1,648 | 1,645 | 1,645 | daf777d34a93484762684b0ae8193f95d9a4b3b1 | bigcode/the-stack | train |
8fa274927d10abc485cf24cc | train | class | class InterviewSourceURL(InterviewSource):
def __init__(self, **kwargs):
self.set_path(kwargs.get('path', None))
return super().__init__(**kwargs)
def set_path(self, path):
self.path = path
if self.path is None:
self.directory = None
else:
self.dir... | class InterviewSourceURL(InterviewSource):
| def __init__(self, **kwargs):
self.set_path(kwargs.get('path', None))
return super().__init__(**kwargs)
def set_path(self, path):
self.path = path
if self.path is None:
self.directory = None
else:
self.directory = re.sub('/[^/]*$', '', re.sub('\?.*... | = path
new_source.directory = self.directory
new_source.basename = path
new_source.filepath = new_file
new_source.playground = self.playground
if hasattr(self, 'package'):
new_source.package = self.package
if new_source.update():
... | 76 | 76 | 255 | 8 | 68 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | InterviewSourceURL | InterviewSourceURL | 321 | 352 | 321 | 321 | 0023895200f2e1796cad0f3e95b1e76c6af6da18 | bigcode/the-stack | train |
1df77290ae23e3e275834a30 | train | class | class PackageImage:
def __init__(self, **kwargs):
self.filename = kwargs.get('filename', None)
self.attribution = kwargs.get('attribution', None)
self.setname = kwargs.get('setname', None)
self.package = kwargs.get('package', 'docassemble.base')
def get_filename(self):
re... | class PackageImage:
| def __init__(self, **kwargs):
self.filename = kwargs.get('filename', None)
self.attribution = kwargs.get('attribution', None)
self.setname = kwargs.get('setname', None)
self.package = kwargs.get('package', 'docassemble.base')
def get_filename(self):
return(docassemble.bas... | =dict(), gather=list(), event_stack=dict(), misc=dict()), url_args=dict(), nav=docassemble.base.functions.DANav())
def set_initial_dict(the_dict):
global initial_dict
initial_dict = the_dict
return
def get_initial_dict():
return copy.deepcopy(initial_dict);
class PackageImage:
| 64 | 64 | 132 | 4 | 60 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | PackageImage | PackageImage | 133 | 143 | 133 | 133 | 08f0eeafd2d46a53810f59936f3acf8471ee56fc | bigcode/the-stack | train |
fcb7ea86a62bc3664bc48535 | train | function | def selectattr_filter(*pargs, **kwargs):
if len(pargs) > 2:
array = pargs[0]
attr_name = pargs[1]
func_name = pargs[2]
env = custom_jinja_env()
func = lambda item: env.call_test(func_name, item, pargs[3:], kwargs)
for item in array:
if func(mygetattr(item,... | def selectattr_filter(*pargs, **kwargs):
| if len(pargs) > 2:
array = pargs[0]
attr_name = pargs[1]
func_name = pargs[2]
env = custom_jinja_env()
func = lambda item: env.call_test(func_name, item, pargs[3:], kwargs)
for item in array:
if func(mygetattr(item, attr_name)):
yield item
... | is not None:
return d.join([str(mygetattr(y, attribute)) for y in array])
return d.join([str(y) for y in array])
def attr_filter(var, attr_name):
return mygetattr(var, attr_name)
def selectattr_filter(*pargs, **kwargs):
| 64 | 64 | 125 | 11 | 53 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | selectattr_filter | selectattr_filter | 9,201 | 9,214 | 9,201 | 9,201 | c8ad5af33052c918c1c3f27f7cb4b0aa5fd2f9d7 | bigcode/the-stack | train |
265fe6d134f1041b3cb57a86 | train | function | def recursive_eval_dataobject(target, the_user_dict):
if isinstance(target, dict) or (hasattr(target, 'elements') and isinstance(target.elements, dict)):
new_dict = dict()
for key, val in target.items():
new_dict[key] = recursive_eval_dataobject(val, the_user_dict)
return new_dic... | def recursive_eval_dataobject(target, the_user_dict):
| if isinstance(target, dict) or (hasattr(target, 'elements') and isinstance(target.elements, dict)):
new_dict = dict()
for key, val in target.items():
new_dict[key] = recursive_eval_dataobject(val, the_user_dict)
return new_dict
if isinstance(target, list) or (hasattr(target, ... | status.question.interview.default_validation_messages[status.question.language][validation_type]
if message is None:
message = default_message
if parameters is not None and len(parameters) > 0:
try:
message = message % parameters
except TypeError:
... | 74 | 74 | 248 | 11 | 62 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | recursive_eval_dataobject | recursive_eval_dataobject | 1,492 | 1,513 | 1,492 | 1,492 | 80e4c93065a8aef22ae0e5c1f36cd4948fe57bd8 | bigcode/the-stack | train |
4ae1fbb63daa088b7313ad41 | train | function | def emoji_matcher_insert(obj):
return (lambda x: docassemble.base.filter.emoji_insert(x.group(1), images=obj.interview.images))
| def emoji_matcher_insert(obj):
| return (lambda x: docassemble.base.filter.emoji_insert(x.group(1), images=obj.interview.images))
| (1)):
result.append(dict(key=TextObject(value, question=self), label=TextObject(key, question=self)))
else:
raise DAError("Unknown data type in manual choices selection: " + re.sub(r'[<>]', '', repr(data)))
return(result)
def emoji_matcher_insert(obj):
| 64 | 64 | 31 | 7 | 57 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | emoji_matcher_insert | emoji_matcher_insert | 6,675 | 6,676 | 6,675 | 6,675 | 54ad774224867d40e1900d4aa7d30a5f46fe1e50 | bigcode/the-stack | train |
f61b301beb4d45d838887773 | train | function | def mygetattr(y, attr):
for attribute in attr.split('.'):
y = getattr(y, attribute)
return y
| def mygetattr(y, attr):
| for attribute in attr.split('.'):
y = getattr(y, attribute)
return y
| _punctuation'] = docassemble.base.functions.fix_punctuation
env.filters['redact'] = docassemble.base.functions.redact
env.filters['verbatim'] = docassemble.base.functions.verbatim
env.filters['map'] = map_filter
return env
def mygetattr(y, attr):
| 64 | 64 | 28 | 8 | 55 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | mygetattr | mygetattr | 9,093 | 9,096 | 9,093 | 9,093 | 9c48279568d45cbd7f11fefa963656532aa7ecb0 | bigcode/the-stack | train |
5d9dca75249f69ff2be4317a | train | function | def auto_determine_type(field_info, the_value=None):
types = dict()
if 'selections' in field_info:
for item in field_info['selections']:
the_type = type(item[0]).__name__
if the_type not in types:
types[the_type] = 0
types[the_type] += 1
if the_val... | def auto_determine_type(field_info, the_value=None):
| types = dict()
if 'selections' in field_info:
for item in field_info['selections']:
the_type = type(item[0]).__name__
if the_type not in types:
types[the_type] = 0
types[the_type] += 1
if the_value is not None:
the_type = type(the_value).__... | '[<>]', '', repr(data)))
return(result)
def extract_missing_name(the_error):
#logmessage("extract_missing_name: string was " + str(string))
m = nameerror_match.search(str(the_error))
if m:
return m.group(1)
else:
raise the_error
def auto_determine_type(field_info, the_value=None):
| 76 | 76 | 254 | 12 | 63 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | auto_determine_type | auto_determine_type | 8,689 | 8,719 | 8,689 | 8,689 | fb091d4fb0e9c8c005fdf6aa0ea520e90afc50aa | bigcode/the-stack | train |
e9525c683fa4ecc9d6e78f1a | train | function | def map_filter(*pargs, **kwargs):
if len(pargs) >= 2:
array = pargs[0]
the_filter = pargs[1]
env = custom_jinja_env()
if the_filter not in env.filters:
raise DAError('filter passed to map() does not exist')
for item in array:
yield env.call_filter(the_... | def map_filter(*pargs, **kwargs):
| if len(pargs) >= 2:
array = pargs[0]
the_filter = pargs[1]
env = custom_jinja_env()
if the_filter not in env.filters:
raise DAError('filter passed to map() does not exist')
for item in array:
yield env.call_filter(the_filter, item, pargs[2:], kwargs)
... | gs[1]
func_name = pargs[2]
env = custom_jinja_env()
func = lambda item: env.call_test(func_name, item, pargs[3:], kwargs)
for item in array:
if not func(mygetattr(item, attr_name)):
yield item
else:
for item in pargs[0]:
if not mygetatt... | 103 | 103 | 346 | 10 | 92 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | map_filter | map_filter | 9,231 | 9,265 | 9,231 | 9,231 | bec8bdfcec5475b9102b92908161d0f3aec054fb | bigcode/the-stack | train |
c9092bcb450c71a020dc04b6 | train | function | def substitute_vars(var, is_generic, the_x, iterators, last_only=False):
if is_generic:
if the_x != 'None':
var = re.sub(r'^x\b', the_x, var)
if len(iterators):
if last_only:
indexno = len(iterators) - 1
var = re.sub(r'\[' + list_of_indices[indexno] + r'\]', '... | def substitute_vars(var, is_generic, the_x, iterators, last_only=False):
| if is_generic:
if the_x != 'None':
var = re.sub(r'^x\b', the_x, var)
if len(iterators):
if last_only:
indexno = len(iterators) - 1
var = re.sub(r'\[' + list_of_indices[indexno] + r'\]', '[' + str(iterators[indexno]) + ']', var)
else:
for in... | to a variable '" + origMissingVariable + "' that could not be found in the question file (for language '" + str(language) + "') or in any of the files incorporated by reference into the question file.", variable=origMissingVariable)
def substitute_vars(var, is_generic, the_x, iterators, last_only=False):
| 67 | 67 | 225 | 18 | 49 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | substitute_vars | substitute_vars | 8,550 | 8,565 | 8,550 | 8,550 | 7775daca8cd98e841dd765b078c4bb304d5cb6c8 | bigcode/the-stack | train |
124f4ff8c47d01ab397e9163 | train | function | def groupby_filter(array, attr_name):
def func(y):
return mygetattr(y, attr_name)
return [_GroupTuple(key, list(values)) for key, values in groupby(sorted(array, key=func), func)]
| def groupby_filter(array, attr_name):
| def func(y):
return mygetattr(y, attr_name)
return [_GroupTuple(key, list(values)) for key, values in groupby(sorted(array, key=func), func)]
| attribute in attributes]
return sorted(array, key=key_func, reverse=reverse)
_GroupTuple = namedtuple('_GroupTuple', ['grouper', 'list'])
_GroupTuple.__repr__ = tuple.__repr__
_GroupTuple.__str__ = tuple.__str__
def groupby_filter(array, attr_name):
| 64 | 64 | 50 | 9 | 55 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | groupby_filter | groupby_filter | 9,140 | 9,143 | 9,140 | 9,140 | 8f8ef881c6bdfd9b87b60cd7a0bc210644191ed2 | bigcode/the-stack | train |
dc798584a57c95a8f867c237 | train | function | def recursive_textobject_or_primitive(target, question):
if isinstance(target, dict) or (hasattr(target, 'elements') and isinstance(target.elements, dict)):
new_dict = dict()
for key, val in target.items():
new_dict[key] = recursive_textobject_or_primitive(val, question)
return n... | def recursive_textobject_or_primitive(target, question):
| if isinstance(target, dict) or (hasattr(target, 'elements') and isinstance(target.elements, dict)):
new_dict = dict()
for key, val in target.items():
new_dict[key] = recursive_textobject_or_primitive(val, question)
return new_dict
if isinstance(target, list) or (hasattr(targe... | text = target.text(the_user_dict)
return docassemble.base.file_docx.transform_for_docx(text, question, tpl)
else:
raise DAError("recursive_eval_textobject: expected a TextObject, but found a " + str(type(target)))
def recursive_textobject_or_primitive(target, question):
| 64 | 64 | 216 | 11 | 53 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | recursive_textobject_or_primitive | recursive_textobject_or_primitive | 1,584 | 1,602 | 1,584 | 1,584 | 96a5c3a4a2332e74f90070a43dba282ccab25450 | bigcode/the-stack | train |
d63ac83c2e974e153cd25eba | train | function | def attr_filter(var, attr_name):
return mygetattr(var, attr_name)
| def attr_filter(var, attr_name):
| return mygetattr(var, attr_name)
| yield mygetattr(item, attribute)
def join_filter(array, d="", attribute=None):
if attribute is not None:
return d.join([str(mygetattr(y, attribute)) for y in array])
return d.join([str(y) for y in array])
def attr_filter(var, attr_name):
| 64 | 64 | 18 | 8 | 56 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | attr_filter | attr_filter | 9,198 | 9,199 | 9,198 | 9,198 | 37d87d00b2ba3348b59138ef0fe435b994561bde | bigcode/the-stack | train |
d7ead097db626e043ba32d6a | train | function | def allow_privileges_list(obj):
if not (isinstance(obj, list) or (hasattr(obj, 'instanceName') and hasattr(obj, 'elements') and isinstance(obj.elements, list))):
obj = [obj]
new_list = list()
for item in obj:
if isinstance(item, str):
new_list.append(item)
return new_list
| def allow_privileges_list(obj):
| if not (isinstance(obj, list) or (hasattr(obj, 'instanceName') and hasattr(obj, 'elements') and isinstance(obj.elements, list))):
obj = [obj]
new_list = list()
for item in obj:
if isinstance(item, str):
new_list.append(item)
return new_list
| (int, str)):
new_list.append(item)
else:
email_address_method = getattr(item, 'email_address', None)
if callable(email_address_method):
new_list.append(item.email)
else:
new_list.append(str(item))
return new_list
def allow_priv... | 64 | 64 | 78 | 7 | 56 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | allow_privileges_list | allow_privileges_list | 9,313 | 9,320 | 9,313 | 9,313 | db25e3df5d032ab3bc5e250141d0fd3b1db27b19 | bigcode/the-stack | train |
852574c07c0a048ca07f5d7b | train | function | def min_filter(array, case_sensitive=False, attribute=None):
it = iter(array)
try:
first = next(it)
except StopIteration:
raise DAError("min: list was empty")
if attribute:
def key_func(y):
return str_or_original(mygetattr(y, attribute), case_sensitive=case_sensitive)... | def min_filter(array, case_sensitive=False, attribute=None):
| it = iter(array)
try:
first = next(it)
except StopIteration:
raise DAError("min: list was empty")
if attribute:
def key_func(y):
return str_or_original(mygetattr(y, attribute), case_sensitive=case_sensitive)
else:
def key_func(y):
return str_or... | str_or_original(mygetattr(y, attribute), case_sensitive=case_sensitive)
else:
def key_func(y):
return str_or_original(y, case_sensitive=case_sensitive)
return max(chain([first], it), key=key_func)
def min_filter(array, case_sensitive=False, attribute=None):
| 64 | 64 | 107 | 12 | 52 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | min_filter | min_filter | 9,159 | 9,171 | 9,159 | 9,159 | 465b9983ca8031135bfbd6567f75e4f28cc2e312 | bigcode/the-stack | train |
38f90af5a6dbf75699c0c3d5 | train | function | def parse_var_name(var):
var_len = len(var)
cur_pos = 0
in_bracket = 0
in_quote = 0
the_quote = None
dots = list()
brackets = list()
while cur_pos < var_len:
char = var[cur_pos]
if char == '[':
if cur_pos == 0:
return dict(valid=False, reason='... | def parse_var_name(var):
| var_len = len(var)
cur_pos = 0
in_bracket = 0
in_quote = 0
the_quote = None
dots = list()
brackets = list()
while cur_pos < var_len:
char = var[cur_pos]
if char == '[':
if cur_pos == 0:
return dict(valid=False, reason='bracket at start')
... | (str(old_variable) + " = __oldvariable__", the_dict)
exec("del __oldvariable__", the_dict)
except:
pass
raise
except Exception as e:
cl, exc, tb = sys.exc_info()
exc.user_dict = docassemble.base.functions.serializable_dict(the_dict)
if len(... | 207 | 207 | 691 | 6 | 201 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | parse_var_name | parse_var_name | 8,860 | 8,936 | 8,860 | 8,860 | 1963c2659e5061b3acde291a6a10cabd8ed6595d | bigcode/the-stack | train |
f0af41c8bb726f269b77a96f | train | class | class Question:
def idebug(self, data):
if hasattr(self, 'from_source') and hasattr(self, 'package'):
return "\nIn file " + str(self.from_source.path) + " from package " + str(self.package) + ":\n\n" + yaml.dump(data)
else:
return yaml.dump(data)
def __init__(self, orig_d... | class Question:
| def idebug(self, data):
if hasattr(self, 'from_source') and hasattr(self, 'package'):
return "\nIn file " + str(self.from_source.path) + " from package " + str(self.package) + ":\n\n" + yaml.dump(data)
else:
return yaml.dump(data)
def __init__(self, orig_data, caller, **k... | mode="wb", delete=False)
try:
urlretrieve(url_sanitize(str(the_file_ref)), temp_template_file.name)
except Exception as err:
raise DAError("FileInPackage: error downloading " + str(the_file_ref) + ": " + str(err))
... | 256 | 256 | 64,710 | 3 | 253 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | Question | Question | 1,739 | 6,673 | 1,739 | 1,739 | 50a15e69c85862fe62394bcc1356686742d3a532 | bigcode/the-stack | train |
c874b0c97e82ac5069f6c75f | train | function | def recursive_eval_textobject(target, the_user_dict, question, tpl, skip_undefined):
if isinstance(target, dict) or (hasattr(target, 'elements') and isinstance(target.elements, dict)):
new_dict = dict()
for key, val in target.items():
new_dict[key] = recursive_eval_textobject(val, the_us... | def recursive_eval_textobject(target, the_user_dict, question, tpl, skip_undefined):
| if isinstance(target, dict) or (hasattr(target, 'elements') and isinstance(target.elements, dict)):
new_dict = dict()
for key, val in target.items():
new_dict[key] = recursive_eval_textobject(val, the_user_dict, question, tpl, skip_undefined)
return new_dict
if isinstance(tar... | _textobject(val, question))
return new_list
if isinstance(target, set) or (hasattr(target, 'elements') and isinstance(target.elements, set)):
new_set = set()
for val in target.__iter__():
new_set.add(recursive_textobject(val, question))
return new_set
return TextObjec... | 96 | 96 | 323 | 19 | 77 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | recursive_eval_textobject | recursive_eval_textobject | 1,554 | 1,582 | 1,554 | 1,554 | f2ee9b06be2232343a4f5cd6de0a161dab10008a | bigcode/the-stack | train |
97a8c0532b80c5939999af48 | train | function | def unpack_list(item, target_list=None):
if target_list is None:
target_list = list()
if not isinstance(item, (list, dict)):
target_list.append(item)
else:
for subitem in item:
unpack_list(subitem, target_list)
return target_list
| def unpack_list(item, target_list=None):
| if target_list is None:
target_list = list()
if not isinstance(item, (list, dict)):
target_list.append(item)
else:
for subitem in item:
unpack_list(subitem, target_list)
return target_list
| _action(item, is_generic, the_x, iterators))
return new_list
else:
return action
def reproduce_basics(interview, new_interview):
new_interview.metadata = interview.metadata
new_interview.external_files = interview.external_files
def unpack_list(item, target_list=None):
| 64 | 64 | 63 | 9 | 54 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | unpack_list | unpack_list | 8,594 | 8,602 | 8,594 | 8,594 | dcc2d213e005270bb76cd679f963aa8f4ce7b4da | bigcode/the-stack | train |
e8c14922f52f036cfe175d37 | train | class | class TableInfo:
pass
| class TableInfo:
| pass
| ' in entry:
if isinstance(entry['key'], TextObject):
if not isinstance(entry['key'].original_text, (bool, NoneType)):
return False
else:
if not isinstance(entry['key'], (bool, NoneType)):
return False
return True
class T... | 64 | 64 | 7 | 4 | 59 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | TableInfo | TableInfo | 6,727 | 6,728 | 6,727 | 6,727 | 612577f6f376ceb847e34650ccc561fbee17b536 | bigcode/the-stack | train |
8ef0804e5358846f49f9644c | train | function | def str_or_original(y, case_sensitive):
if case_sensitive:
if hasattr(y, 'instanceName'):
if y.__class__.__name__ in ('Value', 'PeriodicValue'):
return y.amount()
return str(y)
return y
if hasattr(y, 'instanceName'):
if y.__class__.__name__ in ('Va... | def str_or_original(y, case_sensitive):
| if case_sensitive:
if hasattr(y, 'instanceName'):
if y.__class__.__name__ in ('Value', 'PeriodicValue'):
return y.amount()
return str(y)
return y
if hasattr(y, 'instanceName'):
if y.__class__.__name__ in ('Value', 'PeriodicValue'):
retu... | .filters['verbatim'] = docassemble.base.functions.verbatim
env.filters['map'] = map_filter
return env
def mygetattr(y, attr):
for attribute in attr.split('.'):
y = getattr(y, attribute)
return y
def str_or_original(y, case_sensitive):
| 64 | 64 | 105 | 9 | 54 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | str_or_original | str_or_original | 9,098 | 9,112 | 9,098 | 9,098 | a4f53c047b1d9555663cfa3a7e1add12e274b839 | bigcode/the-stack | train |
a88382242a4e6b91bd753fad | train | function | def get_mimetype(filename):
if filename is None:
return 'text/plain; charset=utf-8'
mimetype, encoding = mimetypes.guess_type(filename)
extension = filename.lower()
extension = re.sub('.*\.', '', extension)
if extension == '3gpp':
mimetype = 'audio/3gpp'
if mimetype is None:
... | def get_mimetype(filename):
| if filename is None:
return 'text/plain; charset=utf-8'
mimetype, encoding = mimetypes.guess_type(filename)
extension = filename.lower()
extension = re.sub('.*\.', '', extension)
if extension == '3gpp':
mimetype = 'audio/3gpp'
if mimetype is None:
mimetype = 'text/plain'
... | field_info['type'] = 'boolean'
return
if 'int' in types:
field_info['type'] = 'integer'
return
if 'float' in types:
field_info['type'] = 'float'
return
return
def get_mimetype(filename):
| 64 | 64 | 95 | 6 | 57 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | get_mimetype | get_mimetype | 8,721 | 8,731 | 8,721 | 8,721 | 5d9ea18b56bdfbf56a0d5ec0f4b2173ab895340f | bigcode/the-stack | train |
7976dc04e8e97c1e9a855502 | train | function | def myb64quote(text):
return "'" + re.sub(r'[\n=]', '', codecs.encode(text.encode('utf8'), 'base64').decode()) + "'"
| def myb64quote(text):
| return "'" + re.sub(r'[\n=]', '', codecs.encode(text.encode('utf8'), 'base64').decode()) + "'"
| :
return(self.other_lang[target_lang][1].render(**the_user_dict))
else:
return(self.other_lang[target_lang][0])
if self.uses_mako:
return(self.template.render(**the_user_dict))
else:
return(self.original_text)
def myb64quote... | 64 | 64 | 37 | 7 | 57 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | myb64quote | myb64quote | 1,372 | 1,373 | 1,372 | 1,372 | 230a821ab793e0ccbdb31d631e999ef5b5f5c19e | bigcode/the-stack | train |
74a0514d68d313d9dcc2a060 | train | function | def is_boolean(field_data):
if 'choices' not in field_data:
return False
if 'has_code' in field_data:
return False
for entry in field_data['choices']:
if 'key' in entry and 'label' in entry:
if isinstance(entry['key'], TextObject):
if not isinstance(entry[... | def is_boolean(field_data):
| if 'choices' not in field_data:
return False
if 'has_code' in field_data:
return False
for entry in field_data['choices']:
if 'key' in entry and 'label' in entry:
if isinstance(entry['key'], TextObject):
if not isinstance(entry['key'].original_text, bool):... | str(path) + "\n")
if the_filename is not None:
new_source = InterviewSourceFile(filepath=the_filename, path=path)
if new_source.update():
return(new_source)
raise DAError("Interview " + str(path) + " not found")
def is_boolean(field_data):
| 64 | 64 | 105 | 6 | 58 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | is_boolean | is_boolean | 6,697 | 6,710 | 6,697 | 6,697 | c8498d09771e197c88d7d66472edfe9f4bcc6dc2 | bigcode/the-stack | train |
e1af0802380788e024cd6dc3 | train | function | def from_safeid(text):
return(codecs.decode(repad(bytearray(text, encoding='utf-8')), 'base64').decode('utf8'))
| def from_safeid(text):
| return(codecs.decode(repad(bytearray(text, encoding='utf-8')), 'base64').decode('utf8'))
| "'" + re.sub(r'[\n=]', '', codecs.encode(text.encode('utf8'), 'base64').decode()) + "'"
def safeid(text):
return re.sub(r'[\n=]', '', codecs.encode(text.encode('utf8'), 'base64').decode())
def from_safeid(text):
| 64 | 64 | 32 | 6 | 58 | provistechnologies/docassemble | docassemble_base/docassemble/base/parse.py | Python | from_safeid | from_safeid | 1,378 | 1,379 | 1,378 | 1,378 | b4a214ed652f8942fb548d3d73c29eb418f93a55 | bigcode/the-stack | train |
26efe815c7580cb20aef8d50 | train | class | class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('order', '0002_wishlist_product'),
('product', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='wishlist',
... | class Migration(migrations.Migration):
| initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('order', '0002_wishlist_product'),
('product', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='wishlist',
name='user',
fiel... | # Generated by Django 3.2.7 on 2021-11-23 16:39
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| 51 | 136 | 455 | 7 | 43 | rialrustamov/SuperB-E-Commerce-RR | SuperB/order/migrations/0003_initial.py | Python | Migration | Migration | 8 | 54 | 8 | 9 | 506d57f504e080615aa236506bb009d6274c9fa2 | bigcode/the-stack | train |
1f5ed90e7ee4f2b429710383 | train | class | class TargetRestoreInfo(Model):
"""Details about target workload during restore operation.
:param overwrite_option: Can Overwrite if Target DataBase already exists.
Possible values include: 'Invalid', 'FailOnConflict', 'Overwrite'
:type overwrite_option: str or
~azure.mgmt.recoveryservicesbackup.... | class TargetRestoreInfo(Model):
| """Details about target workload during restore operation.
:param overwrite_option: Can Overwrite if Target DataBase already exists.
Possible values include: 'Invalid', 'FailOnConflict', 'Overwrite'
:type overwrite_option: str or
~azure.mgmt.recoveryservicesbackup.models.OverwriteOptions
:par... | Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# -----------------------------... | 75 | 75 | 250 | 6 | 68 | AlexanderYukhanov/azure-sdk-for-python | azure-mgmt-recoveryservicesbackup/azure/mgmt/recoveryservicesbackup/models/target_restore_info.py | Python | TargetRestoreInfo | TargetRestoreInfo | 15 | 39 | 15 | 15 | 79646822430f0f7a602f65b195762394623e783a | bigcode/the-stack | train |
ec827c25b7621b368f540eaa | train | class | class Permiso(db.Model):
id = db.Column(db.Integer, primary_key = True)
nombre = db.Column(db.String(80), unique=True, nullable=False)
# db = None
__tablename__ = 'permiso'
def __init__(self, nombre):
self.nombre = nombre
@classmethod
def all(cls):
sql = 'SELECT * F... | class Permiso(db.Model):
| id = db.Column(db.Integer, primary_key = True)
nombre = db.Column(db.String(80), unique=True, nullable=False)
# db = None
__tablename__ = 'permiso'
def __init__(self, nombre):
self.nombre = nombre
@classmethod
def all(cls):
sql = 'SELECT * FROM permiso'
curs... | from flaskps.models.shared import db
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import and_
class Permiso(db.Model):
| 27 | 64 | 202 | 6 | 21 | ramirezlp/proyecto2019 | flaskps/models/permiso.py | Python | Permiso | Permiso | 5 | 39 | 5 | 5 | d38659a1d76e196a9c42820db6661661f09c468d | bigcode/the-stack | train |
c71487b7f22755a7db5f3fd7 | train | function | def main():
if len(sys.argv) != 2:
print("usage: %s address" % sys.argv[0])
sys.exit(-1)
# validate the address
address = sys.argv[1]
assert network.parse.address(address) is not None
print("creating coinbase transaction to %s" % address)
tx_in = network.tx.TxIn.coinbase_tx_in... | def main():
| if len(sys.argv) != 2:
print("usage: %s address" % sys.argv[0])
sys.exit(-1)
# validate the address
address = sys.argv[1]
assert network.parse.address(address) is not None
print("creating coinbase transaction to %s" % address)
tx_in = network.tx.TxIn.coinbase_tx_in(script=b'')... | #!/usr/bin/env python
# This script creates a fake coinbase transaction to an address of your
# choosing so you can test code that spends this output.
import sys
from pycoin.symbols.btc import network
def main():
| 49 | 64 | 144 | 3 | 45 | jaschadub/pycoin | recipes/multisig/2_create_coinbase_tx.py | Python | main | main | 11 | 25 | 11 | 11 | 44abe0c0ae9ea2b36313850194a818a0ab9ae5bf | bigcode/the-stack | train |
02ca2794b3ec04fd8a347038 | train | class | @rfm.simple_test
class IBCardCheck(rfm.RunOnlyRegressionTest):
descr = 'Check the number of IB cards'
valid_systems = ['*']
valid_prog_environs = ['*']
executable = 'lspci'
@sanity_function
def validate_results(self):
# Get node_data
vm_info = self.current_system.node_data
... | @rfm.simple_test
class IBCardCheck(rfm.RunOnlyRegressionTest):
| descr = 'Check the number of IB cards'
valid_systems = ['*']
valid_prog_environs = ['*']
executable = 'lspci'
@sanity_function
def validate_results(self):
# Get node_data
vm_info = self.current_system.node_data
# Ideas for refactoring:
# - get each name from ib... | # Copyright 2016-2021 Swiss National Supercomputing Centre (CSCS/ETH Zurich)
# ReFrame Project Developers. See the top-level LICENSE file for details.
#
# SPDX-License-Identifier: BSD-3-Clause
# rfmdocstart: streamtest4
import reframe as rfm
import reframe.utility.sanity as sn
import inspect
import reframe.core.config... | 104 | 226 | 754 | 17 | 86 | arstgr/reframe | azure_nhc/pcie/device_count.py | Python | IBCardCheck | IBCardCheck | 13 | 78 | 13 | 14 | efad49c77552ab92d25434179113e6da91bd9dd7 | bigcode/the-stack | train |
77b8499dcd0858e2bd5fae40 | train | function | @pytest.mark.uncollect_if(func=uncollect_if_test_explainer)
@pytest.mark.parametrize('n_explainer_runs', [5], ids='n_exp_runs={}'.format)
@pytest.mark.parametrize('at_defaults', [0.9, 0.95], ids='threshold={}'.format, indirect=True)
@pytest.mark.parametrize('rf_classifier',
[lazy_fixture('iris_... | @pytest.mark.uncollect_if(func=uncollect_if_test_explainer)
@pytest.mark.parametrize('n_explainer_runs', [5], ids='n_exp_runs={}'.format)
@pytest.mark.parametrize('at_defaults', [0.9, 0.95], ids='threshold={}'.format, indirect=True)
@pytest.mark.parametrize('rf_classifier',
[lazy_fixture('iris_... | """
Convergence test on Adult and Iris datasets.
"""
# fixture returns a fitted AnchorTabular explainer
X_test, explainer, predict_fn, predict_type = explainer
if predict_type == 'proba':
instance_label = np.argmax(predict_fn(X_test[test_instance_idx, :].reshape(1, -1)), axis=1)
els... | @pytest.mark.uncollect_if(func=uncollect_if_test_explainer)
@pytest.mark.parametrize('n_explainer_runs', [5], ids='n_exp_runs={}'.format)
@pytest.mark.parametrize('at_defaults', [0.9, 0.95], ids='threshold={}'.format, indirect=True)
@pytest.mark.parametrize('rf_classifier',
[lazy_fixture('iris_... | 193 | 163 | 546 | 193 | 0 | RobertSamoilescu/alibi | alibi/explainers/tests/test_anchor_tabular.py | Python | test_explainer | test_explainer | 43 | 91 | 43 | 56 | 62d2dbc32283f458935e245f9248fb7910adaffd | bigcode/the-stack | train |
794b18e0eea0f622e526d1f7 | train | function | def test_anchor_tabular_fails_bad_predictor_return_type():
"""
In this test `feature_names` is specified correctly, but the predictor returns the wrong type.
"""
with pytest.raises(AlibiPredictorReturnTypeError):
explainer = AnchorTabular(bad_predictor, feature_names=['f1', 'f2', 'f3']) # noqa:... | def test_anchor_tabular_fails_bad_predictor_return_type():
| """
In this test `feature_names` is specified correctly, but the predictor returns the wrong type.
"""
with pytest.raises(AlibiPredictorReturnTypeError):
explainer = AnchorTabular(bad_predictor, feature_names=['f1', 'f2', 'f3']) # noqa: F841
| an exception calling the `predictor`.
"""
with pytest.raises(AlibiPredictorCallException):
explainer = AnchorTabular(bad_predictor, feature_names=['f1', 'f2']) # noqa: F841
def test_anchor_tabular_fails_bad_predictor_return_type():
| 64 | 64 | 83 | 13 | 50 | RobertSamoilescu/alibi | alibi/explainers/tests/test_anchor_tabular.py | Python | test_anchor_tabular_fails_bad_predictor_return_type | test_anchor_tabular_fails_bad_predictor_return_type | 327 | 332 | 327 | 327 | 54311918f6b73d5e57c5a239a846b8b7c3da1dc6 | bigcode/the-stack | train |
a2224d047e4dff0bac6aae75 | train | function | def uncollect_if_test_sampler(**kwargs):
"""
Make sure only tests operating on the same dataset are run.
"""
clf_dataset_name = kwargs['rf_classifier'].name.split("_")[0] # "adult_data" -> "adult"
exp_dataset_name = kwargs['explainer'].name.split("_")[1] # "at_adult_explainer" -> "adult"
datas... | def uncollect_if_test_sampler(**kwargs):
| """
Make sure only tests operating on the same dataset are run.
"""
clf_dataset_name = kwargs['rf_classifier'].name.split("_")[0] # "adult_data" -> "adult"
exp_dataset_name = kwargs['explainer'].name.split("_")[1] # "at_adult_explainer" -> "adult"
dataset_name = kwargs['dataset'].name.split("_... | am.state['t_nsamples'][anchor] == current_state['t_nsamples'][anchor] + t
assert distrib_anchor_beam.state['t_positives'][anchor] == current_state['t_positives'][anchor] + p
ray.shutdown()
def uncollect_if_test_sampler(**kwargs):
| 64 | 64 | 136 | 9 | 55 | RobertSamoilescu/alibi | alibi/explainers/tests/test_anchor_tabular.py | Python | uncollect_if_test_sampler | uncollect_if_test_sampler | 179 | 191 | 179 | 179 | 59bb9e11fae4217a85a7bb79238e8e84b5fd08a0 | bigcode/the-stack | train |
38758b0ef6d3e4253927d8dd | train | function | def uncollect_if_test_explainer(**kwargs):
"""
This function is used to skip combinations of explainers
and classifiers that do not make sense. This is achieved
by using the hooks in conftest.py. Such functions should
be passed to the @pytest.mark.uncollect_if decorator as
the func argument. The... | def uncollect_if_test_explainer(**kwargs):
| """
This function is used to skip combinations of explainers
and classifiers that do not make sense. This is achieved
by using the hooks in conftest.py. Such functions should
be passed to the @pytest.mark.uncollect_if decorator as
the func argument. They should take the same inputs as the
te... | PredictorCallException, AlibiPredictorReturnTypeError
from alibi.explainers import AnchorTabular, DistributedAnchorTabular
from alibi.explainers.tests.utils import predict_fcn
from alibi.utils.distributed import RAY_INSTALLED
# TODO: Test DistributedAnchorBaseBeam separately
def uncollect_if_test_explainer(**kwargs):... | 75 | 75 | 253 | 11 | 63 | RobertSamoilescu/alibi | alibi/explainers/tests/test_anchor_tabular.py | Python | uncollect_if_test_explainer | uncollect_if_test_explainer | 18 | 40 | 18 | 18 | 7a18902e87669f659e2fb7b7afc82d4a6987d4a8 | bigcode/the-stack | train |
027bdbe82146a3da0e3953cf | train | function | def test_anchor_tabular_fails_init_bad_feature_names_predictor_call():
"""
In this test `feature_names` is misspecified leading to an exception calling the `predictor`.
"""
with pytest.raises(AlibiPredictorCallException):
explainer = AnchorTabular(bad_predictor, feature_names=['f1', 'f2']) # no... | def test_anchor_tabular_fails_init_bad_feature_names_predictor_call():
| """
In this test `feature_names` is misspecified leading to an exception calling the `predictor`.
"""
with pytest.raises(AlibiPredictorCallException):
explainer = AnchorTabular(bad_predictor, feature_names=['f1', 'f2']) # noqa: F841
| Expecting an array of certain dimension
- Returning an incorrect type
This is used below to test custom exception functionality.
"""
if x.shape[1] != 3:
raise ValueError
return list(x)
def test_anchor_tabular_fails_init_bad_feature_names_predictor_call():
| 64 | 64 | 81 | 15 | 49 | RobertSamoilescu/alibi | alibi/explainers/tests/test_anchor_tabular.py | Python | test_anchor_tabular_fails_init_bad_feature_names_predictor_call | test_anchor_tabular_fails_init_bad_feature_names_predictor_call | 319 | 324 | 319 | 319 | 2e5fed2b72bfe0abe23dcecc9909b8166da6585c | bigcode/the-stack | train |
f6b6823c6b35ed16d5b112f7 | train | function | def bad_predictor(x: np.ndarray) -> list:
"""
A dummy predictor emulating the following:
- Expecting an array of certain dimension
- Returning an incorrect type
This is used below to test custom exception functionality.
"""
if x.shape[1] != 3:
raise ValueError
return list(x)
| def bad_predictor(x: np.ndarray) -> list:
| """
A dummy predictor emulating the following:
- Expecting an array of certain dimension
- Returning an incorrect type
This is used below to test custom exception functionality.
"""
if x.shape[1] != 3:
raise ValueError
return list(x)
| in a sensible range for numerical features
assert (train_data_mean + train_data_3std - raw_data_mean > 0).all()
assert (train_data_mean - train_data_3std - raw_data_mean < 0).all()
def bad_predictor(x: np.ndarray) -> list:
| 64 | 64 | 74 | 12 | 52 | RobertSamoilescu/alibi | alibi/explainers/tests/test_anchor_tabular.py | Python | bad_predictor | bad_predictor | 307 | 316 | 307 | 307 | 022e80dd865dbfb19c2447e91299e5834e1bf933 | bigcode/the-stack | train |
ccc65bb6c6dfde4d9f1c0f73 | train | function | @pytest.mark.skip(reason='Not testing as performance of distributed anchors (within an instance) not clear.'
'Also, these tests fail intermittently with precision treshold not achieved.')
@pytest.mark.parametrize('ncpu', [2], ids='ncpu={}'.format)
@pytest.mark.parametrize('predict_type', ('prob... | @pytest.mark.skip(reason='Not testing as performance of distributed anchors (within an instance) not clear.'
'Also, these tests fail intermittently with precision treshold not achieved.')
@pytest.mark.parametrize('ncpu', [2], ids='ncpu={}'.format)
@pytest.mark.parametrize('predict_type', ('prob... | if RAY_INSTALLED:
import ray
# inputs
params = at_defaults
threshold = params['desired_confidence']
n_covered_ex = params['n_covered_ex'] # number of covered examples to return when anchor applies
batch_size = params['batch_size'] # number of samples to draw during... | # removed as the algorithm is too stochastic to pass for the fixed instance
# assert ((np.asarray(run_precisions) > threshold).sum()) / n_explainer_runs >= 0.80
sampler = explainer.samplers[0]
assert sampler.instance_label == instance_label
assert sampler.n_covered_ex == n_covered_ex
@pytest.mark.skip... | 256 | 256 | 867 | 182 | 73 | RobertSamoilescu/alibi | alibi/explainers/tests/test_anchor_tabular.py | Python | test_distributed_anchor_tabular | test_distributed_anchor_tabular | 94 | 176 | 94 | 111 | 90662101ab12cf823f4aea81210603d5647d73bc | bigcode/the-stack | train |
711f9283ea9eca0534994d3e | train | function | @pytest.mark.uncollect_if(func=uncollect_if_test_sampler)
@pytest.mark.parametrize('test_instance_idx', [0], ids='test_instance_idx={}'.format)
@pytest.mark.parametrize('nb_samples', [100], ids='nb_samples={}'.format)
@pytest.mark.parametrize('anchors', [((2,), (10,), (11,), (7, 10, 11), (3, 11))], ids='anchors={}'.for... | @pytest.mark.uncollect_if(func=uncollect_if_test_sampler)
@pytest.mark.parametrize('test_instance_idx', [0], ids='test_instance_idx={}'.format)
@pytest.mark.parametrize('nb_samples', [100], ids='nb_samples={}'.format)
@pytest.mark.parametrize('anchors', [((2,), (10,), (11,), (7, 10, 11), (3, 11))], ids='anchors={}'.for... | """
Test sampler for datasets that contain continuos only or continuous and categorical variables.
"""
# fixture returns a fitted AnchorTabular explainer
X_test, explainer, predict_fn, predict_type = explainer
test_dataset = dataset
test_dataset_name = test_dataset['metadata']['name']
... | # "adult_data" -> "adult"
conditions = [
len({clf_dataset_name, exp_dataset_name, dataset_name}) != 1,
]
return any(conditions)
@pytest.mark.uncollect_if(func=uncollect_if_test_sampler)
@pytest.mark.parametrize('test_instance_idx', [0], ids='test_instance_idx={}'.format)
@pytest.mark.parametrize... | 256 | 256 | 1,261 | 216 | 40 | RobertSamoilescu/alibi | alibi/explainers/tests/test_anchor_tabular.py | Python | test_sampler | test_sampler | 194 | 304 | 194 | 211 | a1de116370a563ad7a024753d8562e9ec3af3d56 | bigcode/the-stack | train |
f80e2f00d18261e5cc97bfb4 | train | class | class AcceptBlockTest(NuwaCoinTestFramework):
def add_options(self, parser):
parser.add_option("--testbinary", dest="testbinary",
default=os.getenv("BITCOIND", "nuwacoind"),
help="nuwacoind binary to test")
def set_test_params(self):
self.setu... | class AcceptBlockTest(NuwaCoinTestFramework):
| def add_options(self, parser):
parser.add_option("--testbinary", dest="testbinary",
default=os.getenv("BITCOIND", "nuwacoind"),
help="nuwacoind binary to test")
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = ... | too far ahead in height).
5. Send a duplicate of the block in #3 to Node0.
Node0 should not process the block because it is unrequested, and stay on
the shorter chain.
6. Send Node0 an inv for the height 3 block produced in #4 above.
Node0 should figure out that Node0 has the missing height 2 block and send ... | 256 | 256 | 2,829 | 10 | 245 | martin-braun/Nuwa | test/functional/p2p_unrequested_blocks.py | Python | AcceptBlockTest | AcceptBlockTest | 60 | 320 | 60 | 60 | e2b1adcbd8088c45390c1a7998a490e725fac821 | bigcode/the-stack | train |
2967d738a75d234840810d65 | train | class | class projector_read:
def __init__(self, data=None, step=None, index=None):
self.data = data
self.step = step
self.index = index
def get_meta_data(self):
if self.data:
_data = self.data
else:
return None
result = []
for items in _d... | class projector_read:
| def __init__(self, data=None, step=None, index=None):
self.data = data
self.step = step
self.index = index
def get_meta_data(self):
if self.data:
_data = self.data
else:
return None
result = []
for items in _data:
resul... | .0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
====... | 66 | 66 | 220 | 4 | 62 | Gouzhong1223/Dubhe | dubhe-visual-server/backend/backend/component/Projector/projector_read.py | Python | projector_read | projector_read | 20 | 50 | 20 | 20 | 9199b79dfdb51530ec2ab5fb2826684d2b0bc80f | bigcode/the-stack | train |
eeb17330ed9d4f81c41ff44e | train | class | class TaErradoError(Exception): # por convenção, uma classe que trata de um erro sempre deve terminar com 'ERROR'
pass
| class TaErradoError(Exception): # por convenção, uma classe que trata de um erro sempre deve terminar com 'ERROR'
| pass
| class TaErradoError(Exception): # por convenção, uma classe que trata de um erro sempre deve terminar com 'ERROR'
| 27 | 64 | 30 | 27 | 0 | AdrianaViabL/Curso-Python-udemy | 3 - python POO/107 - criando excecoes/excecoes.py | Python | TaErradoError | TaErradoError | 1 | 2 | 1 | 1 | e10182b07a8e625ef13e064decd9d64be4871ad6 | bigcode/the-stack | train |
d6e6047b7c24e0a9a6c5703b | train | function | def testar():
raise TaErradoError('esta errado')
| def testar():
| raise TaErradoError('esta errado')
| class TaErradoError(Exception): # por convenção, uma classe que trata de um erro sempre deve terminar com 'ERROR'
pass
def testar():
| 33 | 64 | 13 | 3 | 29 | AdrianaViabL/Curso-Python-udemy | 3 - python POO/107 - criando excecoes/excecoes.py | Python | testar | testar | 5 | 6 | 5 | 5 | 53a50185b29601fe84e5c68c8367d47f39ffedf2 | bigcode/the-stack | train |
84cbec625e34a1f2f31e534e | train | class | class ChangelogView(TemplateView):
"""Show a simple changelog page"""
def get(self, request, *args, **kwargs):
template_name = "viperweb/changelog.html"
_changelog = {"foo": "bar"}
return render(request, template_name, {'changelog': _changelog,
... | class ChangelogView(TemplateView):
| """Show a simple changelog page"""
def get(self, request, *args, **kwargs):
template_name = "viperweb/changelog.html"
_changelog = {"foo": "bar"}
return render(request, template_name, {'changelog': _changelog,
'projects': get_project_list()... | get(self, request, *args, **kwargs):
template_name = "viperweb/about.html"
return render(request, template_name, {'version': __version__,
'extractors': Extractor().extractors,
'projects': get_project_list()})... | 64 | 64 | 78 | 8 | 56 | CLEAR-seclab/viper | viper/web/viperweb/views.py | Python | ChangelogView | ChangelogView | 616 | 623 | 616 | 616 | 90f7a501512906bfc429d438f6eb1dbda63408db | bigcode/the-stack | train |
fc37cd69e41ac47a404af193 | train | function | def open_db(project):
# Check for valid project
if project == 'default':
__project__.open(project)
return Database()
else:
try:
__project__.open(project)
return Database()
except Exception:
return False
| def open_db(project):
# Check for valid project
| if project == 'default':
__project__.open(project)
return Database()
else:
try:
__project__.open(project)
return Database()
except Exception:
return False
| -a -t',
'rules': 'rules'}
}
# context manager for file uploader
@contextlib.contextmanager
def upload_temp():
temp_dir = tempfile.mkdtemp()
yield temp_dir
shutil.rmtree(temp_dir)
def open_db(project):
# Check for valid project
| 64 | 64 | 55 | 12 | 52 | CLEAR-seclab/viper | viper/web/viperweb/views.py | Python | open_db | open_db | 145 | 155 | 145 | 146 | f9c86630d222196181f8ecf80226fb15da817f86 | bigcode/the-stack | train |
505e589938a778e9b1567f95 | train | class | class AboutView(TemplateView):
"""Show a simple about page"""
def get(self, request, *args, **kwargs):
template_name = "viperweb/about.html"
return render(request, template_name, {'version': __version__,
'extractors': Extractor().extractors,
... | class AboutView(TemplateView):
| """Show a simple about page"""
def get(self, request, *args, **kwargs):
template_name = "viperweb/about.html"
return render(request, template_name, {'version': __version__,
'extractors': Extractor().extractors,
... | The File Name did not match the style 'name.yar'"
return render(request, template_name, {'rule_list': self.yara_rule_list,
'rule_name': rule_name,
'rule_text': rule_text,
... | 64 | 64 | 73 | 7 | 57 | CLEAR-seclab/viper | viper/web/viperweb/views.py | Python | AboutView | AboutView | 606 | 613 | 606 | 606 | 9e1e04cb000c93a4a33e4a2efc2b483072d7a06c | bigcode/the-stack | train |
d3c1a5b7dfd5c46ec57651fb | train | class | class YaraRulesView(LoginRequiredMixin, TemplateView):
"""Manage Yara Rules"""
# TODO(frennkie) this depends on - not yet merged - #649
yara_rule_path = os.path.join(__project__.base_path, 'yara')
def yara_rule_list(self):
# TODO(frennkie) clean this up when merging #649
if not os.path... | class YaraRulesView(LoginRequiredMixin, TemplateView):
| """Manage Yara Rules"""
# TODO(frennkie) this depends on - not yet merged - #649
yara_rule_path = os.path.join(__project__.base_path, 'yara')
def yara_rule_list(self):
# TODO(frennkie) clean this up when merging #649
if not os.path.isdir(self.yara_rule_path):
os.makedirs(se... | -s {0} -l {1} {2}'.format(hex_offset, hex_length, hex_path)
# get the output
hex_string = getoutput(hex_cmd)
# Format the data
html_string = ''
hex_rows = hex_string.split('\n')
for row in hex_rows:
if len(row) > 9:
off_str = row[0:8]
... | 231 | 231 | 773 | 12 | 219 | CLEAR-seclab/viper | viper/web/viperweb/views.py | Python | YaraRulesView | YaraRulesView | 521 | 603 | 521 | 521 | a1353c2e7543fcc7ed9eb90d91d71abb63958dc4 | bigcode/the-stack | train |
781d869369d54acd6274dc9d | train | function | @contextlib.contextmanager
def upload_temp():
temp_dir = tempfile.mkdtemp()
yield temp_dir
shutil.rmtree(temp_dir)
| @contextlib.contextmanager
def upload_temp():
| temp_dir = tempfile.mkdtemp()
yield temp_dir
shutil.rmtree(temp_dir)
| 'all': '-a',
'export': '-o'},
'yara': {'scan': 'scan -t',
'all': 'scan -a -t',
'rules': 'rules'}
}
# context manager for file uploader
@contextlib.contextmanager
def upload_temp():
| 64 | 64 | 31 | 10 | 53 | CLEAR-seclab/viper | viper/web/viperweb/views.py | Python | upload_temp | upload_temp | 138 | 142 | 138 | 139 | d0cefe0365f3004f0f2d56a121af51ae3c2d56e4 | bigcode/the-stack | train |
4b2fa216c74402a20f8c0136 | train | function | def module_cmdline(project=None, cmd_line=None, file_hash=None):
html = ""
cmd = Commands()
split_commands = cmd_line.split(';')
for split_command in split_commands:
split_command = split_command.strip()
if not split_command:
continue
root, args = parse(split_command)... | def module_cmdline(project=None, cmd_line=None, file_hash=None):
| html = ""
cmd = Commands()
split_commands = cmd_line.split(';')
for split_command in split_commands:
split_command = split_command.strip()
if not split_command:
continue
root, args = parse(split_command)
try:
if root in cmd.commands:
... | line.replace(r'\x1b', ''))
# Ignore the line that says we opened a session
if 'Session opened on' in line:
continue
# add text the string
set_text += '{0}\n'.format(line)
return set_text
# this will allow complex command line parameters to be passed in via the web gui
... | 91 | 91 | 306 | 15 | 75 | CLEAR-seclab/viper | viper/web/viperweb/views.py | Python | module_cmdline | module_cmdline | 226 | 261 | 226 | 226 | a3c802ae44c2fb374e12034149ab60dc00d44cd7 | bigcode/the-stack | train |
ccb4c6abc3da9be34ffa6e58 | train | class | class ConfigView(LoginRequiredMixin, TemplateView):
"""Show a simple page listing the settings from the config file"""
def get(self, request, *args, **kwargs):
template_name = "viperweb/config.html"
sections = list(cfg.__dict__)
config_values = {}
for section in sections:
... | class ConfigView(LoginRequiredMixin, TemplateView):
| """Show a simple page listing the settings from the config file"""
def get(self, request, *args, **kwargs):
template_name = "viperweb/config.html"
sections = list(cfg.__dict__)
config_values = {}
for section in sections:
config_values[section] = cfg.get(section)
... | if project not in get_project_list():
raise Http404("unknown project: {}".format(project))
template_name = "viperweb/cli.html"
return render(request, template_name, {'project': project,
'projects': get_project_list()})
class ConfigView(LoginRe... | 64 | 64 | 102 | 10 | 54 | CLEAR-seclab/viper | viper/web/viperweb/views.py | Python | ConfigView | ConfigView | 638 | 648 | 638 | 638 | 5f78df87c96d7676f35395aa8f269d48ca2d1dd0 | bigcode/the-stack | train |
3dad4572317065d6d80cdf90 | train | class | class VtDownloadView(LoginRequiredMixin, TemplateView):
"""Download a file from Virustotal and add to project"""
def get(self, request, *args, **kwargs):
return HttpResponse('This is a POST only view')
# VirusTotal Download
# TODO(frennkie) this most likely doesn't work
# virustotal -d do... | class VtDownloadView(LoginRequiredMixin, TemplateView):
| """Download a file from Virustotal and add to project"""
def get(self, request, *args, **kwargs):
return HttpResponse('This is a POST only view')
# VirusTotal Download
# TODO(frennkie) this most likely doesn't work
# virustotal -d does not take a parameter - so providing a vt_hash will fa... | .split('/')[-1], tags=tags)
if sha_256:
messages.success(request, "stored file in database: {}".format(tf.name))
return redirect(reverse('main-page-project', kwargs={'project': project}))
else:
messages.error(request, "Unable to Store The File, already in database")
... | 92 | 93 | 311 | 12 | 80 | CLEAR-seclab/viper | viper/web/viperweb/views.py | Python | VtDownloadView | VtDownloadView | 353 | 381 | 353 | 353 | b67d6f21e74d20ab57828f9fbbae7fb9df983f1c | bigcode/the-stack | train |
947e6fca4f96d113d6c5485e | train | class | class FileView(LoginRequiredMixin, TemplateView):
"""Show details for a file/sample"""
def get(self, request, *args, **kwargs):
template_name = "viperweb/file.html"
# default to "default" project if none given
project = kwargs.get('project', 'default')
db = open_db(project)
... | class FileView(LoginRequiredMixin, TemplateView):
| """Show details for a file/sample"""
def get(self, request, *args, **kwargs):
template_name = "viperweb/file.html"
# default to "default" project if none given
project = kwargs.get('project', 'default')
db = open_db(project)
sha256 = kwargs.get('sha256')
if not ... | )
if len(tags) > 0:
cmd_line += '; tags -a {0}'.format(tags)
module_results = module_cmdline(project=project, file_hash=False, cmd_line=cmd_line)
if 'Stored' in module_results:
return redirect(reverse("main-page-project", kwargs={"project": project}))
else:
... | 119 | 119 | 399 | 10 | 108 | CLEAR-seclab/viper | viper/web/viperweb/views.py | Python | FileView | FileView | 385 | 436 | 385 | 385 | a7dc2ee86188d7ad0370ed05317ffc6cdcd0b6d8 | bigcode/the-stack | train |
47d7fe2606a1b1ed89b69116 | train | class | class CliView(LoginRequiredMixin, TemplateView):
"""Show GUI that implement the command line interface (CLI)"""
def get(self, request, *args, **kwargs):
project = kwargs.get("project", "default")
if project not in get_project_list():
raise Http404("unknown project: {}".format(project... | class CliView(LoginRequiredMixin, TemplateView):
| """Show GUI that implement the command line interface (CLI)"""
def get(self, request, *args, **kwargs):
project = kwargs.get("project", "default")
if project not in get_project_list():
raise Http404("unknown project: {}".format(project))
template_name = "viperweb/cli.html"
... | *args, **kwargs):
template_name = "viperweb/changelog.html"
_changelog = {"foo": "bar"}
return render(request, template_name, {'changelog': _changelog,
'projects': get_project_list()})
class CliView(LoginRequiredMixin, TemplateView):
| 64 | 64 | 103 | 10 | 54 | CLEAR-seclab/viper | viper/web/viperweb/views.py | Python | CliView | CliView | 626 | 635 | 626 | 626 | aa6d3b45b290d6c8271ae2cb6cee110d260c3fd2 | bigcode/the-stack | train |
feed4501da15141a37fa279c | train | class | class MainPageView(LoginRequiredMixin, TemplateView):
"""Main Page"""
def get(self, request, *args, **kwargs):
template_name = "viperweb/index.html"
# default to "default" project if none given
project = kwargs.get('project', 'default')
db = open_db(project)
# Get all S... | class MainPageView(LoginRequiredMixin, TemplateView):
| """Main Page"""
def get(self, request, *args, **kwargs):
template_name = "viperweb/index.html"
# default to "default" project if none given
project = kwargs.get('project', 'default')
db = open_db(project)
# Get all Samples
sample_list = db.find('all')
r... | open session to keep the session table clean
__sessions__.close()
return obj.sha256
else:
# ToDo Remove the stored file if we cant write to DB
return
##
# Class Based Views
##
# Main Page
class MainPageView(LoginRequiredMixin, TemplateView):
| 64 | 64 | 126 | 11 | 52 | CLEAR-seclab/viper | viper/web/viperweb/views.py | Python | MainPageView | MainPageView | 295 | 310 | 295 | 295 | 721a7c43d8d9a90ad7169169bfc96e3530ccb8a8 | bigcode/the-stack | train |
97f3eca01d2d2b1b34af5d62 | train | function | def print_output(output):
if not output:
return '<p class="text-danger">! The command Generated no Output</p>'
return_html = ''
for entry in output:
# Skip lines that say seesion opened
if 'Session opened on' in entry['data']:
continue
if entry['type'] == 'info':
... | def print_output(output):
| if not output:
return '<p class="text-danger">! The command Generated no Output</p>'
return_html = ''
for entry in output:
# Skip lines that say seesion opened
if 'Session opened on' in entry['data']:
continue
if entry['type'] == 'info':
return_html +=... | 'scan -a -t',
'rules': 'rules'}
}
# context manager for file uploader
@contextlib.contextmanager
def upload_temp():
temp_dir = tempfile.mkdtemp()
yield temp_dir
shutil.rmtree(temp_dir)
def open_db(project):
# Check for valid project
if project == 'default':
... | 114 | 114 | 380 | 5 | 108 | CLEAR-seclab/viper | viper/web/viperweb/views.py | Python | print_output | print_output | 158 | 195 | 158 | 158 | 397fcd03f383a031ce5054b381a9e61d0c454e95 | bigcode/the-stack | train |
1bd2796a7007eef3bc917658 | train | function | def add_file(file_path, name=None, tags=None, parent=None):
obj = File(file_path)
new_path = store_sample(obj)
print(new_path)
if not name:
name = os.path.basename(file_path)
# success = True
if new_path:
# Add file to the database.
db = Database()
db.add(obj=ob... | def add_file(file_path, name=None, tags=None, parent=None):
| obj = File(file_path)
new_path = store_sample(obj)
print(new_path)
if not name:
name = os.path.basename(file_path)
# success = True
if new_path:
# Add file to the database.
db = Database()
db.add(obj=obj, name=name, tags=tags, parent_sha=parent)
# AutoR... | valid command</p>'.format(cmd_line)
except Exception:
html += '<p class="text-danger">We were unable to complete the command {0}</p>'.format(cmd_line)
__sessions__.close()
return html
def add_file(file_path, name=None, tags=None, parent=None):
| 64 | 64 | 159 | 15 | 48 | CLEAR-seclab/viper | viper/web/viperweb/views.py | Python | add_file | add_file | 264 | 287 | 264 | 264 | c1d9611bd367ec3e42e7b475dd5d20d92222e49a | bigcode/the-stack | train |
2ebfb0587f35ba417367d4db | train | function | def parse_text(module_text):
# String to hold the new text
set_text = ''
# Split in to lines.
for line in module_text.split('\n'):
# Remove the colour codes
line = re.sub(r'\[(\d)+m', '', line.replace(r'\x1b', ''))
# Ignore the line that says we opened a session
if 'Sessi... | def parse_text(module_text):
# String to hold the new text
| set_text = ''
# Split in to lines.
for line in module_text.split('\n'):
# Remove the colour codes
line = re.sub(r'\[(\d)+m', '', line.replace(r'\x1b', ''))
# Ignore the line that says we opened a session
if 'Session opened on' in line:
continue
# add text ... | First word is the root command.
root = words[0]
# If there are more words, populate the arguments list.
if len(words) > 1:
args = words[1:]
return root, args
def parse_text(module_text):
# String to hold the new text
| 64 | 64 | 117 | 15 | 48 | CLEAR-seclab/viper | viper/web/viperweb/views.py | Python | parse_text | parse_text | 210 | 222 | 210 | 211 | 3c42cf0cc493423b72f1e6b323ed80d1eda4ec5a | bigcode/the-stack | train |
d83d11d8bd3c44d6ad0b7d35 | train | class | class CuckooCheckOrSubmitView(LoginRequiredMixin, TemplateView):
"""Check if report for file exists on Cuckoo - if not submit"""
def get(self, request, *args, **kwargs):
project = kwargs.get("project", "default")
if project not in get_project_list():
raise Http404("unknown project: {... | class CuckooCheckOrSubmitView(LoginRequiredMixin, TemplateView):
| """Check if report for file exists on Cuckoo - if not submit"""
def get(self, request, *args, **kwargs):
project = kwargs.get("project", "default")
if project not in get_project_list():
raise Http404("unknown project: {}".format(project))
sha256 = kwargs.get("sha256")
... | return render(request, template_name, {'config_values': config_values,
'projects': get_project_list()})
class CreateProjectView(LoginRequiredMixin, TemplateView):
"""Create project (if not existing) and switch (redirect) to it"""
def get(self, request, *a... | 180 | 181 | 605 | 15 | 165 | CLEAR-seclab/viper | viper/web/viperweb/views.py | Python | CuckooCheckOrSubmitView | CuckooCheckOrSubmitView | 666 | 717 | 666 | 666 | 65347976fc9ff76df73fc8a3a6772eadbac767db | bigcode/the-stack | train |
633640407d2d7dc123b33adc | train | function | def parse(data):
args = []
# Split words by white space.
words = data.split()
# First word is the root command.
root = words[0]
# If there are more words, populate the arguments list.
if len(words) > 1:
args = words[1:]
return root, args
| def parse(data):
| args = []
# Split words by white space.
words = data.split()
# First word is the root command.
root = words[0]
# If there are more words, populate the arguments list.
if len(words) > 1:
args = words[1:]
return root, args
| in row:
return_html += '<td>{0}</td>'.format(cell)
return_html += '</tr>'
# Close table
return_html += '</table>'
else:
return_html += '<p>{0}</p>'.format(entry['data'])
return return_html
def parse(data):
| 64 | 64 | 73 | 4 | 59 | CLEAR-seclab/viper | viper/web/viperweb/views.py | Python | parse | parse | 198 | 207 | 198 | 198 | 2f3d08567a21ae58fa2a66d65900edf00a00edfd | bigcode/the-stack | train |
edc4b5f2354e591a6411e4c0 | train | class | class HexView(LoginRequiredMixin, TemplateView):
"""Read file a return as Hex"""
def get(self, request, *args, **kwargs):
return HttpResponse('This is a POST only view')
def post(self, request, *args, **kwargs):
# Get the project and hash of the file
project = kwargs.get('project', ... | class HexView(LoginRequiredMixin, TemplateView):
| """Read file a return as Hex"""
def get(self, request, *args, **kwargs):
return HttpResponse('This is a POST only view')
def post(self, request, *args, **kwargs):
# Get the project and hash of the file
project = kwargs.get('project', 'default')
file_hash = request.POST.get('... | {1}</p>'.format(result.cmd_line, result.stored_at)
html += str(parse_text(module_results))
return HttpResponse('<pre>{0}</pre>'.format(html))
if cmd_line:
cmd_string = cmd_line
elif module_args:
cmd_string = '{0} {1}'.format(module_name, mod_dict[module_n... | 127 | 128 | 427 | 10 | 117 | CLEAR-seclab/viper | viper/web/viperweb/views.py | Python | HexView | HexView | 477 | 518 | 477 | 477 | 4946d7617d851ecf2abe215d88d2ff0238d47890 | bigcode/the-stack | train |
6d13170d6557c1b9a4bc1344 | train | class | class CreateProjectView(LoginRequiredMixin, TemplateView):
"""Create project (if not existing) and switch (redirect) to it"""
def get(self, request, *args, **kwargs):
return HttpResponse('This is a POST only view')
def post(self, request, *args, **kwargs):
project_name = request.POST['proje... | class CreateProjectView(LoginRequiredMixin, TemplateView):
| """Create project (if not existing) and switch (redirect) to it"""
def get(self, request, *args, **kwargs):
return HttpResponse('This is a POST only view')
def post(self, request, *args, **kwargs):
project_name = request.POST['project'].replace(' ', '_')
if project_name not in get_p... | sections = list(cfg.__dict__)
config_values = {}
for section in sections:
config_values[section] = cfg.get(section)
return render(request, template_name, {'config_values': config_values,
'projects': get_project_list()})
class CreateProj... | 64 | 64 | 141 | 11 | 53 | CLEAR-seclab/viper | viper/web/viperweb/views.py | Python | CreateProjectView | CreateProjectView | 651 | 663 | 651 | 651 | 57c1747098fc9884693dbd58ab423d1dcdef1b16 | bigcode/the-stack | train |
af285bfd604365ee3c3ca38e | train | class | class UrlDownloadView(LoginRequiredMixin, TemplateView):
"""Download a file from URL and add to project"""
def get(self, request, *args, **kwargs):
return HttpResponse('This is a POST only view')
def post(self, request, *args, **kwargs):
# Set Project
project = request.POST.get('pro... | class UrlDownloadView(LoginRequiredMixin, TemplateView):
| """Download a file from URL and add to project"""
def get(self, request, *args, **kwargs):
return HttpResponse('This is a POST only view')
def post(self, request, *args, **kwargs):
# Set Project
project = request.POST.get('project', 'default')
open_db(project)
url =... | # default to "default" project if none given
project = kwargs.get('project', 'default')
db = open_db(project)
# Get all Samples
sample_list = db.find('all')
return render(request, template_name, {'sample_list': sample_list,
'extra... | 96 | 96 | 321 | 11 | 85 | CLEAR-seclab/viper | viper/web/viperweb/views.py | Python | UrlDownloadView | UrlDownloadView | 313 | 350 | 313 | 313 | c1ebdc52786c8f07cb1ddbd09615c0c40d64e108 | bigcode/the-stack | train |
dfd102dd51e0a683b6b09d99 | train | class | class SearchFileView(LoginRequiredMixin, TemplateView):
""" Search file"""
def get(self, request, *args, **kwargs):
return HttpResponse('This is a POST only view')
def post(self, request, *args, **kwargs):
template_name = "viperweb/search_result.html"
key = request.POST.get('key')
... | class SearchFileView(LoginRequiredMixin, TemplateView):
| """ Search file"""
def get(self, request, *args, **kwargs):
return HttpResponse('This is a POST only view')
def post(self, request, *args, **kwargs):
template_name = "viperweb/search_result.html"
key = request.POST.get('key')
value = request.POST.get('term').lower()
... | , files=options)
if cuckoo_response.status_code == 200:
cuckoo_id = dict(cuckoo_response.json())['task_id']
return HttpResponse('<a href="{0}/analysis/pending/" target="_blank"> Link To Cuckoo (pending tasks)</a>'.format(cfg.cuckoo.cuckoo_web, str(cuckoo_id)))
els... | 129 | 130 | 435 | 11 | 119 | CLEAR-seclab/viper | viper/web/viperweb/views.py | Python | SearchFileView | SearchFileView | 720 | 778 | 720 | 720 | 7259ad87979e84abbd64a0cd4888229f5d0b1868 | bigcode/the-stack | train |
4a6a7122b74414f87bc4c866 | train | class | class RunModuleView(LoginRequiredMixin, TemplateView):
"""Run a module and return output"""
def get(self, request, *args, **kwargs):
return HttpResponse('This is a POST only view')
def post(self, request, *args, **kwargs):
# Get the project and hash of the file we want to run a command agai... | class RunModuleView(LoginRequiredMixin, TemplateView):
| """Run a module and return output"""
def get(self, request, *args, **kwargs):
return HttpResponse('This is a POST only view')
def post(self, request, *args, **kwargs):
# Get the project and hash of the file we want to run a command against
project = kwargs.get('project', 'default')
... | tag_list = db.list_tags_for_malware(sha256)
children = db.list_children(malware_obj.id)
parent = db.get_parent(malware_obj.id)
return render(request, template_name, {'malware': malware_obj,
'note_list': note_list,
... | 116 | 116 | 388 | 11 | 105 | CLEAR-seclab/viper | viper/web/viperweb/views.py | Python | RunModuleView | RunModuleView | 439 | 474 | 439 | 439 | dffa6e083f1caab7d0ef31fa20904881a4775c8a | bigcode/the-stack | train |
f74df8fce996b9377e4477ec | train | class | class Buffer(object):
def __init__(self, maxlen=100000):
self.buffer_size = maxlen
self.buffer = []
self.position = 0
def insert(self, transition):
""" Saves a transition """
if len(self.buffer) < self.buffer_size: # case buffer not full
self.buffer.appen... | class Buffer(object):
| def __init__(self, maxlen=100000):
self.buffer_size = maxlen
self.buffer = []
self.position = 0
def insert(self, transition):
""" Saves a transition """
if len(self.buffer) < self.buffer_size: # case buffer not full
self.buffer.append(transition)
e... |
# Imports
import random
import numpy as np
from collections import namedtuple
Transition = namedtuple("Transition", ["state", "action", "reward", "next_state", "done"])
class Buffer(object):
| 45 | 149 | 498 | 4 | 41 | orenpeer12/randomized_value_functions | RL_HW/memory.py | Python | Buffer | Buffer | 11 | 66 | 11 | 12 | bcbe67a5399172eb7685bab7e22e9a1a4015e33b | bigcode/the-stack | train |
2e246fc74116ad691a76d16e | train | class | class MeanVFE(VFETemplate):
def __init__(self, model_cfg, num_point_features, **kwargs):
super().__init__(model_cfg=model_cfg)
self.num_point_features = num_point_features
def get_output_feature_dim(self):
return self.num_point_features
def forward(self, batch_dict, **kwargs):
... | class MeanVFE(VFETemplate):
| def __init__(self, model_cfg, num_point_features, **kwargs):
super().__init__(model_cfg=model_cfg)
self.num_point_features = num_point_features
def get_output_feature_dim(self):
return self.num_point_features
def forward(self, batch_dict, **kwargs):
"""
Args:
... | import torch
from .vfe_template import VFETemplate
class MeanVFE(VFETemplate):
| 22 | 79 | 265 | 9 | 12 | Yamin05114/OpenPCDet | pcdet/models/backbones_3d/vfe/mean_vfe.py | Python | MeanVFE | MeanVFE | 5 | 32 | 5 | 5 | 1264eb4d4ce5ade1cbc9a386ca8976474fa88ae9 | bigcode/the-stack | train |
a7f7eb469c68374fc57c8fe8 | train | function | def block_size_exceed_max_position_embeddings(config, block_size):
# This will cause position ids automatically create from model
# to go beyond embedding size of position id embedding.
# And return not so useful error.
# This sound like a bug in transformers library.
# If we got this error the work... | def block_size_exceed_max_position_embeddings(config, block_size):
# This will cause position ids automatically create from model
# to go beyond embedding size of position id embedding.
# And return not so useful error.
# This sound like a bug in transformers library.
# If we got this error the work... | if(block_size > config.max_position_embeddings + config.pad_token_id + 1):
recommend_block_size = config.max_position_embeddings + config.pad_token_id + 1
raise ValueError(f'This block size will cause error due to max_position_embeddings. '
f'Use this block_size={recommend_b... | def block_size_exceed_max_position_embeddings(config, block_size):
# This will cause position ids automatically create from model
# to go beyond embedding size of position id embedding.
# And return not so useful error.
# This sound like a bug in transformers library.
# If we got this error the work... | 112 | 64 | 189 | 112 | 0 | modem888/thai2transformers | scripts/sanity.py | Python | block_size_exceed_max_position_embeddings | block_size_exceed_max_position_embeddings | 31 | 43 | 31 | 38 | 54465136c297af62a7a42a8b36465546f2e27038 | bigcode/the-stack | train |
417e1f3e78d243ba185bfccc | train | function | def tokenizer_and_model_config_mismatch(config, tokenizer):
"""
Check for tokenizer and model config miss match.
Args:
config:
model config.
tokenizer:
tokenizer.
Raises:
ValueError: A special token id in config is different from tokenizer.
"""
i... | def tokenizer_and_model_config_mismatch(config, tokenizer):
| """
Check for tokenizer and model config miss match.
Args:
config:
model config.
tokenizer:
tokenizer.
Raises:
ValueError: A special token id in config is different from tokenizer.
"""
id_check_list = ['bos_token_id', 'eos_token_id', 'pad_token_i... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 3 14:39:32 2020
@author: zo
"""
def tokenizer_and_model_config_mismatch(config, tokenizer):
| 49 | 64 | 142 | 11 | 38 | modem888/thai2transformers | scripts/sanity.py | Python | tokenizer_and_model_config_mismatch | tokenizer_and_model_config_mismatch | 10 | 28 | 10 | 10 | cd6ae067e9bea3a16be2ca39a8f86fee32aededb | bigcode/the-stack | train |
e61d7c90c0d7e0090373a9df | train | class | @gin.configurable
@six.add_metaclass(abc.ABCMeta)
class CriticModel(abstract_model.AbstractT2RModel):
"""Critic model with continuous actions trained using MC returns."""
def __init__(
self,
loss_function = tf.losses.mean_squared_error,
action_batch_size = None,
**kwargs):
"""Constructo... | @gin.configurable
@six.add_metaclass(abc.ABCMeta)
class CriticModel(abstract_model.AbstractT2RModel):
| """Critic model with continuous actions trained using MC returns."""
def __init__(
self,
loss_function = tf.losses.mean_squared_error,
action_batch_size = None,
**kwargs):
"""Constructor for ContinuousMCModel.
Args:
loss_function: Python function taking in (labels, prediction... | distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python2, python3
"""TFModel abstract subclasses."""
from __fut... | 256 | 256 | 1,467 | 29 | 226 | ZachT1711/tensor2robot | models/critic_model.py | Python | CriticModel | CriticModel | 46 | 243 | 46 | 48 | e0c66bba69ce33c9d7424b40bb9e0d5aa7b4a1eb | bigcode/the-stack | train |
359055d589233d916df58ac7 | train | class | class MLP(torch.nn.Module):
def __init__(
self,
in_channels: int,
hidden_channels: int,
out_channels: int,
num_layers: int,
dropout: float = 0.0,
batch_norm: bool = True,
relu_last: bool = False,
):
super(MLP, self).__init__()
self... | class MLP(torch.nn.Module):
| def __init__(
self,
in_channels: int,
hidden_channels: int,
out_channels: int,
num_layers: int,
dropout: float = 0.0,
batch_norm: bool = True,
relu_last: bool = False,
):
super(MLP, self).__init__()
self.lins = ModuleList()
... | import time
import argparse
import torch
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torch.nn import ModuleList, Linear, BatchNorm1d, Identity
from ogb.lsc import MAG240MDataset, MAG240MEvaluator
from root import ROOT
class MLP(torch.nn.Module):
| 68 | 96 | 320 | 7 | 60 | rryoung98/ogb | examples/lsc/mag240m/mlp.py | Python | MLP | MLP | 13 | 55 | 13 | 13 | 5288336faf2feab7d2bdc0e912683855e0e9adad | bigcode/the-stack | train |
a95b08c9a90dc6005f303181 | train | function | def train(model, x_train, y_train, batch_size, optimizer):
model.train()
total_loss = 0
for idx in DataLoader(range(y_train.size(0)), batch_size, shuffle=True):
optimizer.zero_grad()
loss = F.cross_entropy(model(x_train[idx]), y_train[idx])
loss.backward()
optimizer.step()
... | def train(model, x_train, y_train, batch_size, optimizer):
| model.train()
total_loss = 0
for idx in DataLoader(range(y_train.size(0)), batch_size, shuffle=True):
optimizer.zero_grad()
loss = F.cross_entropy(model(x_train[idx]), y_train[idx])
loss.backward()
optimizer.step()
total_loss += float(loss) * idx.numel()
return... | batch_norm(x).relu_()
else:
x = batch_norm(x.relu_())
x = F.dropout(x, p=self.dropout, training=self.training)
x = self.lins[-1](x)
return x
def train(model, x_train, y_train, batch_size, optimizer):
| 64 | 64 | 96 | 15 | 48 | rryoung98/ogb | examples/lsc/mag240m/mlp.py | Python | train | train | 58 | 70 | 58 | 58 | fc6405db7bdc8f2c5974233e87539b1f696a74cc | bigcode/the-stack | train |
4ce7e04ccc2291993415b2d8 | train | function | @torch.no_grad()
def test(model, x_eval, y_eval, evaluator):
model.eval()
y_pred = model(x_eval).argmax(dim=-1)
return evaluator.eval({"y_true": y_eval, "y_pred": y_pred})["acc"]
| @torch.no_grad()
def test(model, x_eval, y_eval, evaluator):
| model.eval()
y_pred = model(x_eval).argmax(dim=-1)
return evaluator.eval({"y_true": y_eval, "y_pred": y_pred})["acc"]
| ()
loss = F.cross_entropy(model(x_train[idx]), y_train[idx])
loss.backward()
optimizer.step()
total_loss += float(loss) * idx.numel()
return total_loss / y_train.size(0)
@torch.no_grad()
def test(model, x_eval, y_eval, evaluator):
| 64 | 64 | 56 | 17 | 47 | rryoung98/ogb | examples/lsc/mag240m/mlp.py | Python | test | test | 73 | 77 | 73 | 74 | 3c75a595e1bbe4502aefc527553fb4307a1c9712 | bigcode/the-stack | train |
91a732657d3cb05c2339ed0b | train | class | class OperationTests(OperationTestBase):
"""
Tests running the operations and making sure they do what they say they do.
Each test looks at their state changing, and then their database operation -
both forwards and backwards.
"""
def test_create_model(self):
"""
Tests the Creat... | class OperationTests(OperationTestBase):
| """
Tests running the operations and making sure they do what they say they do.
Each test looks at their state changing, and then their database operation -
both forwards and backwards.
"""
def test_create_model(self):
"""
Tests the CreateModel operation.
Most other test... | Key("self", models.CASCADE))
],
))
if mti_model:
operations.append(migrations.CreateModel(
"ShetlandPony",
fields=[
('pony_ptr', models.OneToOneField(
'Pony',
models.CASCAD... | 256 | 256 | 20,777 | 7 | 249 | MikeAmy/django | tests/migrations/test_operations.py | Python | OperationTests | OperationTests | 157 | 2,073 | 157 | 157 | 903117df1a2de2292b8dd3043f2ff2f57a595751 | bigcode/the-stack | train |
471daf433b6ce8026218a2d0 | train | class | class SwappableOperationTests(OperationTestBase):
"""
Tests that key operations ignore swappable models
(we don't want to replicate all of them here, as the functionality
is in a common base class anyway)
"""
available_apps = [
"migrations",
"django.contrib.auth",
"djang... | class SwappableOperationTests(OperationTestBase):
| """
Tests that key operations ignore swappable models
(we don't want to replicate all of them here, as the functionality
is in a common base class anyway)
"""
available_apps = [
"migrations",
"django.contrib.auth",
"django.contrib.contenttypes",
]
@override_sett... | .models)
self.assertNotIn((app_label, "iloveevenmoreponies"), new_state.models)
self.assertTableNotExists("somethingelse")
self.assertTableNotExists("somethingcompletelydifferent")
self.assertTableNotExists("ilovemoreponies")
if after_db:
self.... | 224 | 224 | 747 | 9 | 215 | MikeAmy/django | tests/migrations/test_operations.py | Python | SwappableOperationTests | SwappableOperationTests | 2,076 | 2,157 | 2,076 | 2,076 | 75c84d077cd5591fb22f84b4c6475cccbf21959c | bigcode/the-stack | train |
bf6b157663cbd8803e22d3c1 | train | class | class OperationTestBase(MigrationTestBase):
"""
Common functions to help test operations.
"""
def apply_operations(self, app_label, project_state, operations):
migration = Migration('name', app_label)
migration.operations = operations
with connection.schema_editor() as editor:
... | class OperationTestBase(MigrationTestBase):
| """
Common functions to help test operations.
"""
def apply_operations(self, app_label, project_state, operations):
migration = Migration('name', app_label)
migration.operations = operations
with connection.schema_editor() as editor:
return migration.apply(project_st... | from __future__ import unicode_literals
import unittest
from django.db import connection, migrations, models, transaction
from django.db.migrations.migration import Migration
from django.db.migrations.state import ProjectState
from django.db.models.fields import NOT_PROVIDED
from django.db.transaction import atomic
f... | 132 | 256 | 952 | 8 | 123 | MikeAmy/django | tests/migrations/test_operations.py | Python | OperationTestBase | OperationTestBase | 23 | 154 | 23 | 23 | 7e342bd6e87f1cc40876564c17886b9907a2e99a | bigcode/the-stack | train |
4a0162102ed55f5cad735f6d | train | function | def build_oracle(n: int, f) -> QuantumCircuit:
# implement the oracle O_f
# NOTE: use multi_control_toffoli_gate ('noancilla' mode)
# https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html
# https://quantumcomputing.stackexchange.com/questions/3943/how-do-yo... | def build_oracle(n: int, f) -> QuantumCircuit:
# implement the oracle O_f
# NOTE: use multi_control_toffoli_gate ('noancilla' mode)
# https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html
# https://quantumcomputing.stackexchange.com/questions/3943/how-do-yo... | controls = QuantumRegister(n, "ofc")
target = QuantumRegister(1, "oft")
oracle = QuantumCircuit(controls, target, name="Of")
for i in range(2 ** n):
rep = np.binary_repr(i, n)
if f(rep) == "1":
for j in range(n):
if rep[j] == "0":
oracle.x(... | def build_oracle(n: int, f) -> QuantumCircuit:
# implement the oracle O_f
# NOTE: use multi_control_toffoli_gate ('noancilla' mode)
# https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html
# https://quantumcomputing.stackexchange.com/questions/3943/how-do-yo... | 138 | 83 | 278 | 138 | 0 | UCLA-SEAL/QDiff | benchmark/startQiskit_noisy3330.py | Python | build_oracle | build_oracle | 31 | 51 | 31 | 36 | b7a8ed7a88aaeae13a59b1564c24bee83d544220 | bigcode/the-stack | train |
914f5328ef2a15216df5463b | train | function | def bitwise_xor(s: str, t: str) -> str:
length = len(s)
res = []
for i in range(length):
res.append(str(int(s[i]) ^ int(t[i])))
return ''.join(res[::-1])
| def bitwise_xor(s: str, t: str) -> str:
| length = len(s)
res = []
for i in range(length):
res.append(str(int(s[i]) ^ int(t[i])))
return ''.join(res[::-1])
| Register
from qiskit import BasicAer, execute, transpile
from pprint import pprint
from qiskit.test.mock import FakeVigo
from math import log2
import numpy as np
import networkx as nx
def bitwise_xor(s: str, t: str) -> str:
| 64 | 64 | 54 | 16 | 47 | UCLA-SEAL/QDiff | benchmark/startQiskit_noisy3330.py | Python | bitwise_xor | bitwise_xor | 16 | 21 | 16 | 16 | 643dca80c9054c8a7c10bfe226d5dd994f1f8215 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.