code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
def extract_symbol_app(parser, _, args): # pragma: no cover
parser.add_argument('file', help='ELF file to extract a symbol from')
parser.add_argument('symbol', help='the symbol to extract')
args = parser.parse_args(args)
return ELF(args.file).get_symbol(args.symbol).content | Extract a symbol from an ELF file. | null | null | null | |
(magic, word_size, byte_order, version, osabi, abi_version, _), data = \
unpack('4sBBBBB7s', data[:16]), data[16:]
assert magic == self._ELF_MAGIC, 'Missing ELF magic'
assert word_size in (1, 2), 'Invalid word size'
assert byte_order in (1, 2), 'Invalid byte order'... | def _parse_header(self, data) | Parse the ELF header in ``data`` and populate the properties.
Args:
data(bytes): The ELF header. | 2.333077 | 2.304253 | 1.012509 |
if type(f) is str:
self.f = open(f, 'rb')
else:
self.f = f
self._parse_header(self.f.read(64)) | def parse_file(self, f) | Parse an ELF file and fill the class' properties.
Arguments:
f(file or str): The (path to) the ELF file to read. | 3.294678 | 3.237188 | 1.017759 |
self._ensure_section_headers_loaded()
if type(section) is int:
return self._section_headers_by_index[section]
else:
return self._section_headers_by_name[section] | def get_section_header(self, section) | Get a specific section header by index or name.
Args:
section(int or str): The index or name of the section header to return.
Returns:
:class:`~ELF.SectionHeader`: The section header.
Raises:
KeyError: The requested section header does not exist. | 3.226039 | 2.766642 | 1.166049 |
self._ensure_symbols_loaded()
if type(symbol) is int:
return self._symbols_by_index[symbol]
else:
return self._symbols_by_name[symbol] | def get_symbol(self, symbol) | Get a specific symbol by index or name.
Args:
symbol(int or str): The index or name of the symbol to return.
Returns:
ELF.Symbol: The symbol.
Raises:
KeyError: The requested symbol does not exist. | 3.47997 | 3.075106 | 1.131658 |
'''
Returns a list of tuples of connected table pairs.
:param tables: a list of table names
:param cols: a list of column names
:param find_connections: set this to True to detect relationships from column names.
:return: a tuple (connected, pkeys, fkeys... | def connected(self, tables, cols, find_connections=False) | Returns a list of tuples of connected table pairs.
:param tables: a list of table names
:param cols: a list of column names
:param find_connections: set this to True to detect relationships from column names.
:return: a tuple (connected, pkeys, fkeys, reverse_fkeys) | 2.728478 | 2.110085 | 1.293065 |
def serialize_array(items):
content = b''.join(
php_serialize(i) + php_serialize(v)
for i, v in items
)
return 'a:{0}:'.format(len(value)).encode('utf8') + b'{' + content + b'}'
def serialize_str(prefix, item):
return prefix + b':' + str(item).encod... | def php_serialize(value) | Serialize a value for use with PHP's deserialize() function. This function
can serialize bytes, strings, integers, floats, booleans, None, lists,
dicts and custom objects implementing __php__().
Args:
value: The value to serialize.
Returns:
bytes: The serialized form of `value` ready t... | 2.390138 | 2.242052 | 1.06605 |
magic_1 = U16(fp.read(2), target=MARSHAL_TARGET)
magic_2 = U16(fp.read(2), target=MARSHAL_TARGET)
internals = MAGIC_MAP.get(magic_1)
if internals is None:
raise ValueError('Invalid or unknown magic (%d).' % magic_1)
if magic_2 != 2573:
raise ValueError('Invalid secondary magi... | def pyc_load(fp) | Load a .pyc file from a file-like object.
Arguments:
fp(file): The file-like object to read.
Returns:
PycFile: The parsed representation of the .pyc file. | 3.457522 | 3.51098 | 0.984774 |
'''
Emits mode declarations in Aleph-like format.
:param predicate: predicate name
:param args: predicate arguments with input/output specification, e.g.:
>>> [('+', 'train'), ('-', 'car')]
:param recall: recall setting (see `Aleph manual <http://www.cs... | def mode(self, predicate, args, recall=1, head=False) | Emits mode declarations in Aleph-like format.
:param predicate: predicate name
:param args: predicate arguments with input/output specification, e.g.:
>>> [('+', 'train'), ('-', 'car')]
:param recall: recall setting (see `Aleph manual <http://www.cs.ox.ac.uk/activities... | 9.767351 | 2.23479 | 4.37059 |
'''
Emits all examples in prolog form for RSD.
:param pred_name: override for the emitted predicate name
'''
target = self.db.target_table
pred_name = pred_name if pred_name else target
examples = self.db.rows(target, [self.db.target_att, self.db.pkeys[target... | def all_examples(self, pred_name=None) | Emits all examples in prolog form for RSD.
:param pred_name: override for the emitted predicate name | 9.464113 | 5.40182 | 1.752023 |
'''
Emits the background knowledge in prolog form for RSD.
'''
modeslist, getters = [self.mode(self.db.target_table, [('+', self.db.target_table)], head=True)], []
for (table, ref_table) in self.db.connected.keys():
if ref_table == self.db.target_table:
... | def background_knowledge(self) | Emits the background knowledge in prolog form for RSD. | 4.920044 | 4.251318 | 1.157299 |
'''
Emits the background knowledge in prolog form for Aleph.
'''
modeslist, getters = [self.mode(self.__target_predicate(), [('+', self.db.target_table)], head=True)], []
determinations, types = [], []
for (table, ref_table) in self.db.connected.keys():
if ref... | def background_knowledge(self) | Emits the background knowledge in prolog form for Aleph. | 4.378768 | 3.962357 | 1.105092 |
'''
Returns the target table as an Orange example table.
:rtype: orange.ExampleTable
'''
table, cls_att = self.db.target_table, self.db.target_att
if not self.db.orng_tables:
return self.convert_table(table, cls_att=cls_att)
else:
retu... | def target_Orange_table(self) | Returns the target table as an Orange example table.
:rtype: orange.ExampleTable | 6.365393 | 4.030287 | 1.579389 |
'''
Returns the related tables as Orange example tables.
:rtype: list
'''
target_table = self.db.target_table
if not self.db.orng_tables:
return [self.convert_table(table, None) for table in self.db.tables if table != target_table]
else:
... | def other_Orange_tables(self) | Returns the related tables as Orange example tables.
:rtype: list | 4.871837 | 3.55376 | 1.370896 |
'''
Returns the specified table as an orange example table.
:param table_name: table name to convert
:cls_att: class attribute name
:rtype: orange.ExampleTable
'''
import Orange
cols = self.db.cols[table_name]
attributes, metas, class... | def convert_table(self, table_name, cls_att=None) | Returns the specified table as an orange example table.
:param table_name: table name to convert
:cls_att: class attribute name
:rtype: orange.ExampleTable | 3.107981 | 2.634538 | 1.179706 |
'''
Returns an Orange datatype for a given mysql column.
:param table_name: target table name
:param col: column to determine the Orange datatype
'''
mysql_type = self.types[table_name][col]
n_vals = len(self.db.col_vals[table_name][col])
if mysql... | def orng_type(self, table_name, col) | Returns an Orange datatype for a given mysql column.
:param table_name: target table name
:param col: column to determine the Orange datatype | 4.28235 | 3.029424 | 1.413585 |
'''
Returns the facts for the given entity with pk in `target`.
'''
facts = []
cols = self.db.cols[target]
if target != self.db.target_table:
# Skip the class attribute
if self.db.target_att in cols:
cols.remove(self.db.target_att)... | def _facts(self, pk, pk_att, target, visited=set(), parent_table='', parent_pk='') | Returns the facts for the given entity with pk in `target`. | 2.757779 | 2.662636 | 1.035732 |
'''
Replaces the value with an appropriate interval symbol, if available.
'''
label = "'%s'" % col
if table in self.discr_intervals and att in self.discr_intervals[table]:
intervals = self.discr_intervals[table][att]
n_intervals = len(intervals)
... | def _discretize_check(self, table, att, col) | Replaces the value with an appropriate interval symbol, if available. | 4.129484 | 3.333933 | 1.238622 |
'''
Returns the DBContext as a list of interpretations, i.e., a list of
facts true for each example in the format for TreeLiker.
'''
target = self.db.target_table
db_examples = self.db.rows(target, [self.db.target_att, self.db.pkeys[target]])
examples = []
... | def dataset(self) | Returns the DBContext as a list of interpretations, i.e., a list of
facts true for each example in the format for TreeLiker. | 8.598576 | 3.963485 | 2.169448 |
'''
Emits the background knowledge in prd format.
'''
prd_str = ''
prd_str += '--INDIVIDUAL\n'
prd_str += '%s 1 %s cwa\n' % (self.db.target_table, self.db.target_table)
prd_str += '--STRUCTURAL\n'
for ftable, ptable in self.db.reverse_fkeys.items():
... | def create_prd_file(self) | Emits the background knowledge in prd format. | 3.964191 | 3.456907 | 1.146745 |
'''
Emits examples in fct format.
'''
fct_str = ''
fct_str += self.fct_rec(self.db.target_table)
return fct_str | def create_fct_file(self) | Emits examples in fct format. | 11.204065 | 5.310108 | 2.109951 |
points = sorted([s.point() for s in features])
l = reduce(_keep_left, points, [])
u = reduce(_keep_left, reversed(points), [])
return l.extend(u[i] for i in xrange(1, len(u) - 1)) or l | def convex_hull(features) | Returns points on convex hull of an array of points in CCW order. | 5.528072 | 5.214082 | 1.06022 |
if inspect.isfunction(code):
code = six.get_function_code(code).co_code
origin = get_py_internals(origin)
opname = origin['opname']
hasjrel = origin['hasjrel']
hasjabs = origin['hasjabs']
hasjump = set(hasjrel) | set(hasjabs)
wordcode = origin['wordcode']
if not wordcode:... | def disassemble(code, origin=None) | Disassemble python bytecode into a series of :class:`Op` and
:class:`Label` instances.
Arguments:
code(bytes): The bytecode (a code object's ``co_code`` property). You
can also provide a function.
origin(dict): The opcode specification of the python version that
generate... | 3.244164 | 3.004493 | 1.079771 |
blocks = {}
current_block = blocks[None] = Block()
for op in ops:
if isinstance(op, Label):
next_block = blocks[op] = Block(op)
current_block.next = next_block
current_block = next_block
continue
current_block.ops.append(op)
return bl... | def blocks_from_ops(ops) | Group a list of :class:`Op` and :class:`Label` instances by label.
Everytime a label is found, a new :class:`Block` is created. The resulting
blocks are returned as a dictionary to easily access the target block of a
jump operation. The keys of this dictionary will be the labels, the values
will be the... | 2.846857 | 2.623291 | 1.085223 |
blocks = blocks_from_ops(ops)
target = get_py_internals(target)
block = blocks[None]
while block:
block.seen = False
block.startdepth = -1
block = block.next
stackeffect = target['stackeffect']
stackeffect_traits = target['stackeffect_traits']
def walk(block=... | def calculate_max_stack_depth(ops, target=None) | Calculate the maximum stack depth (and required stack size) from a series
of :class:`Op` and :class:`Label` instances. This is required when you
manipulate the opcodes in such a way that the stack layout might change
and you want to re-create a working function from it.
This is a fairly literal re-impl... | 2.831095 | 2.67742 | 1.057397 |
if six.PY2:
co_kwonlyargcount = co_kwonlyargcount if co_kwonlyargcount is not BORROW else 0
else:
co_kwonlyargcount = co_kwonlyargcount if co_kwonlyargcount is not BORROW else code.co_kwonlyargcount
return cls(
co_argcount if co_argcount is not BORR... | def from_code(cls, code, co_argcount=BORROW, co_kwonlyargcount=BORROW, co_nlocals=BORROW, co_stacksize=BORROW,
co_flags=BORROW, co_code=BORROW, co_consts=BORROW, co_names=BORROW, co_varnames=BORROW,
co_filename=BORROW, co_name=BORROW, co_firstlineno=BORROW, co_lnotab=BORROW, co_freev... | from_code(code, co_argcount=BORROW, co_kwonlyargcount=BORROW, co_nlocals=BORROW, co_stacksize=BORROW, co_flags=BORROW, co_code=BORROW, co_consts=BORROW, co_names=BORROW, co_varnames=BORROW, co_filename=BORROW, co_name=BORROW, co_firstlineno=BORROW, co_lnotab=BORROW, co_freevars=BORROW, co_cellvars=BORROW)
Crea... | 1.211651 | 1.263469 | 0.958987 |
return cls.from_code(six.get_function_code(f), *args, **kwargs) | def from_function(cls, f, *args, **kwargs) | Create a new instance from a function. Gets the code object from
the function and passes it and any other specified parameters to
:meth:`from_code`.
Arguments:
f(function): The function to get the code object from.
Returns:
CodeObject: A new :class:`CodeObject` ... | 6.240372 | 6.091339 | 1.024466 |
if isinstance(op, Label):
return op
else:
return AnnotatedOp(self, op.name, op.arg) | def annotate_op(self, op) | Takes a bytecode operation (:class:`Op`) and annotates it using the
data contained in this code object.
Arguments:
op(Op): An :class:`Op` instance.
Returns:
AnnotatedOp: An annotated bytecode operation. | 6.253196 | 5.866606 | 1.065897 |
ops = disassemble(self.co_code, self.internals)
if annotate:
ops = [self.annotate_op(op) for op in ops]
if blocks:
return blocks_from_ops(ops)
else:
return ops | def disassemble(self, annotate=False, blocks=False) | Disassemble the bytecode of this code object into a series of
opcodes and labels. Can also annotate the opcodes and group
the opcodes into blocks based on the labels.
Arguments:
annotate(bool): Whether to annotate the operations.
blocks(bool): Whether to group the operat... | 3.873084 | 3.944594 | 0.981871 |
self.internals = target = get_py_internals(target, self.internals)
self.co_code = assemble(ops, target)
self.co_stacksize = calculate_max_stack_depth(ops, target)
return self | def assemble(self, ops, target=None) | Assemble a series of operations and labels into bytecode, analyse its
stack usage and replace the bytecode and stack size of this code
object. Can also (optionally) change the target python version.
Arguments:
ops(list): The opcodes (and labels) to assemble into bytecode.
... | 8.458071 | 7.768907 | 1.088708 |
if self.internals is not get_py_internals():
raise ValueError('CodeObject is not compatible with the running python internals.')
if six.PY2:
return types.CodeType(
self.co_argcount, self.co_nlocals, self.co_stacksize, self.co_flags, self.co_code, self.c... | def to_code(self) | Convert this instance back into a native python code object. This
only works if the internals of the code object are compatible with
those of the running python version.
Returns:
types.CodeType: The native python code object. | 1.863818 | 1.573803 | 1.184277 |
translation.activate(settings.LANGUAGE_CODE)
if app:
unpack = app.split('.')
if len(unpack) == 2:
models = [get_model(unpack[0], unpack[1])]
elif len(unpack) == 1:
models = get_models(get_app(unpack[0]))
else:
... | def handle(self, targetdir, app=None, **options) | command execution | 3.54684 | 3.636709 | 0.975288 |
self.pages[page_nb].print_page_cb(print_op, print_context,
keep_refs=keep_refs) | def print_page_cb(self, print_op, print_context, page_nb, keep_refs={}) | Called for printing operation by Gtk | 3.121572 | 2.911995 | 1.07197 |
count = self.docsearch.index.start_examine_rootdir()
progress = 0
while True:
(status, doc) = self.docsearch.index.continue_examine_rootdir()
if status == 'end':
break
elif status == 'modified':
on_doc_modified(doc)
... | def examine_rootdir(self,
on_new_doc,
on_doc_modified,
on_doc_deleted,
on_doc_unchanged,
progress_cb=dummy_progress_cb) | Examine the rootdir.
Calls on_new_doc(doc), on_doc_modified(doc), on_doc_deleted(docid)
every time a new, modified, or deleted document is found | 2.544185 | 2.655966 | 0.957914 |
logger.info("Indexing new doc: %s" % doc)
doc = doc.clone() # make sure it can be serialized safely
self.docsearch.index.add_doc(doc, index_update=index_update,
label_guesser_update=label_guesser_update) | def add_doc(self, doc, index_update=True, label_guesser_update=True) | Add a document to the index | 4.515543 | 4.536999 | 0.995271 |
logger.info("Removing doc from the index: %s" % doc)
doc = doc.clone() # make sure it can be serialized safely
self.docsearch.index.del_doc(doc) | def del_doc(self, doc) | Delete a document | 9.9051 | 10.140411 | 0.976795 |
logger.info("Index: Commiting changes")
self.docsearch.index.commit(index_update=index_update,
label_guesser_update=label_guesser_update) | def commit(self, index_update=True, label_guesser_update=True) | Apply the changes to the index | 4.399474 | 4.217299 | 1.043197 |
doc = doc.clone() # make sure it can be serialized safely
return self.index.guess_labels(doc) | def guess_labels(self, doc) | return a prediction of label names | 12.676291 | 12.690226 | 0.998902 |
nb_results = self.index.start_reload_index()
progress = 0
while self.index.continue_reload_index():
progress_cb(progress, nb_results, self.INDEX_STEP_LOADING)
progress += 1
progress_cb(1, 1, self.INDEX_STEP_LOADING)
self.index.end_reload_index() | def reload_index(self, progress_cb=dummy_progress_cb) | Read the index, and load the document list from it
Arguments:
callback --- called during the indexation (may be called *often*).
step : DocSearch.INDEX_STEP_READING or
DocSearch.INDEX_STEP_SORTING
progression : how many elements done yet
... | 3.843873 | 3.872982 | 0.992484 |
if doc:
clone = doc.clone() # make sure it's serializable
r = self.index.create_label(label, doc=clone)
return r | def create_label(self, label, doc=None, callback=dummy_progress_cb) | Create a new label
Arguments:
doc --- first document on which the label must be added (required
for now) | 8.97944 | 10.141028 | 0.885457 |
doc = doc.clone() # make sure it's serializable
r = self.index.remove_label(doc, label, update_index=update_index)
return r | def remove_label(self, doc, label, update_index=True) | Remove a label from a doc. Takes care of updating the index | 5.06662 | 4.552415 | 1.112952 |
current = 0
total = self.index.get_nb_docs()
self.index.start_update_label(old_label, new_label)
while True:
(op, doc) = self.index.continue_update_label()
if op == 'end':
break
callback(current, total, self.LABEL_STEP_UPDATING... | def update_label(self, old_label, new_label, callback=dummy_progress_cb) | Replace 'old_label' by 'new_label' on all the documents. Takes care of
updating the index. | 3.73262 | 3.60429 | 1.035605 |
current = 0
total = self.index.get_nb_docs()
self.index.start_destroy_label(label)
while True:
(op, doc) = self.index.continue_destroy_label()
if op == 'end':
break
callback(current, total, self.LABEL_STEP_DESTROYING, doc)
... | def destroy_label(self, label, callback=dummy_progress_cb) | Remove the label 'label' from all the documents. Takes care of updating
the index. | 4.473229 | 4.28139 | 1.044808 |
'''
Updates the default selections with user's selections.
'''
listCheck = lambda el: el[0] if type(el) == list else el # For handling lists of size 1
widget_id = listCheck(postdata.get('widget_id'))
context.target_table = listCheck(postdata.get('target_table%s' % widget_id))
context.target... | def _update_context(context, postdata) | Updates the default selections with user's selections. | 3.475988 | 3.202085 | 1.085539 |
'''
Maps a new example to a set of features.
'''
# Context of the unseen example(s)
train_context = input_dict['train_ctx']
test_context = input_dict['test_ctx']
# Currently known examples & background knowledge
features = input_dict['features']
format = input_dict['output_format']
... | def do_map(input_dict, feature_format, positive_class=None) | Maps a new example to a set of features. | 6.215975 | 5.381913 | 1.154975 |
self.options = options
self.stream = options.get("stream", StringIO())
self.selected_fields = options.get("fields")
self.use_natural_keys = options.get("use_natural_keys", True)
self.xml = options.get("xml", None)
self.root = (self.xml == None)
... | def serialize(self, queryset, **options) | Serialize a queryset.
THE OUTPUT OF THIS SERIALIZER IS NOT MEANT TO BE SERIALIZED BACK
INTO THE DB. | 3.611559 | 3.452943 | 1.045937 |
self.start_object(obj)
for field in obj._meta.local_fields:
if field.serialize and getattr(field, 'include_in_xml', True):
if field.rel is None:
if self.selected_fields is None or field.attname in self.selected_fields:
self... | def serialize_object(self, obj) | Write one item to the object stream | 2.62506 | 2.634043 | 0.99659 |
if (self.root):
self.xml = XmlPrinter(self.stream, self.options.get("encoding", settings.DEFAULT_CHARSET))
self.xml.startDocument()
self.xml.startElement("django-objects", {"version" : "1.0"}) | def start_serialization(self) | Start serialization -- open the XML document and the root element. | 7.102168 | 5.817503 | 1.220827 |
if (self.root):
self.indent(0)
self.xml.endElement("django-objects")
self.xml.endDocument() | def end_serialization(self) | End serialization -- end the document. | 9.635951 | 7.711006 | 1.249636 |
self.indent(2)
field_attrs = {
"name" : field.name,
"type" : field.get_internal_type()
}
# handle fields with a extra_attrs set as speciul
if hasattr(field, 'extra_attrs'):
if field.extra_attrs:
for (key, value) in fie... | def handle_field(self, obj, field) | Called to handle each field on an object (except for ForeignKeys and
ManyToManyFields) | 4.068029 | 3.917727 | 1.038365 |
self._start_relational_field(field)
related = getattr(obj, field.name)
if related is not None:
if self.use_natural_keys and hasattr(related, 'natural_key'):
# If related object has a natural key, use it
related = related.natural_key()
... | def handle_fk_field(self, obj, field) | Called to handle a ForeignKey (we need to treat them slightly
differently from regular fields). | 3.227788 | 3.202516 | 1.007891 |
if field.rel.through._meta.auto_created:# and obj.__class__ is not field.rel.to:
# keep approximate recursion level
with recursion_depth('handle_m2m_field') as recursion_level:
# a stack trace is better than python crashing.
... | def handle_m2m_field(self, obj, field) | while easymode follows inverse relations for foreign keys,
for manytomayfields it follows the forward relation.
While easymode excludes all relations to "self" you could
still create a loop if you add one extra level of indirection. | 6.964187 | 6.824046 | 1.020536 |
if not HAVE_CAPSTONE:
raise NotImplementedError('pwnypack requires capstone to disassemble to AT&T and Intel syntax')
if target is None:
target = pwnypack.target.target
if target.arch == pwnypack.target.Target.Arch.x86:
if target.bits is pwnypack.target.Target.Bits.bits_32:
... | def prepare_capstone(syntax=AsmSyntax.att, target=None) | Prepare a capstone disassembler instance for a given target and syntax.
Args:
syntax(AsmSyntax): The assembler syntax (Intel or AT&T).
target(~pwnypack.target.Target): The target to create a disassembler
instance for. The global target is used if this argument is
``None``.
... | 2.285169 | 2.146163 | 1.06477 |
if target is None:
target = pwnypack.target.target
if syntax is None:
if target.arch is pwnypack.target.Target.Arch.x86:
syntax = AsmSyntax.nasm
else:
syntax = AsmSyntax.att
if syntax is AsmSyntax.nasm:
if target.arch is not pwnypack.target.Tar... | def disasm(code, addr=0, syntax=None, target=None) | Disassemble machine readable code into human readable statements.
Args:
code(bytes): The machine code that is to be disassembled.
addr(int): The memory address of the code (used for relative
references).
syntax(AsmSyntax): The output assembler syntax. This defaults to
... | 2.812695 | 2.311245 | 1.216961 |
syntax = AsmSyntax.__members__[args.syntax]
else:
syntax = None
if args.source is None:
args.source = sys.stdin.read()
else:
args.source = args.source.replace(';', '\n')
return asm(
args.source,
syntax=syntax,
target=target,
addr=args.addr... | def asm_app(parser, cmd, args): # pragma: no cover
parser.add_argument('source', help='the code to assemble, read from stdin if omitted', nargs='?')
pwnypack.main.add_target_arguments(parser)
parser.add_argument(
'--syntax', '-s',
choices=AsmSyntax.__members__.keys(),
default=... | Assemble code from commandline or stdin.
Please not that all semi-colons are replaced with carriage returns
unless source is read from stdin. | 2.86991 | 2.588355 | 1.108777 |
syntax = AsmSyntax.__members__[args.syntax]
else:
syntax = None
if args.format is None:
if args.code is None:
args.format = 'bin'
else:
args.format = 'hex'
if args.format == 'hex':
code = pwnypack.codec.dehex(pwnypack.main.string_value_or_std... | def disasm_app(_parser, cmd, args): # pragma: no cover
parser = argparse.ArgumentParser(
prog=_parser.prog,
description=_parser.description,
)
parser.add_argument('code', help='the code to disassemble, read from stdin if omitted', nargs='?')
pwnypack.main.add_target_arguments(pars... | Disassemble code from commandline or stdin. | 2.491321 | 2.243955 | 1.110237 |
syntax = AsmSyntax.__members__[args.syntax]
else:
syntax = None
elf = ELF(args.file)
symbol = elf.get_symbol(args.symbol)
print('\n'.join(disasm(symbol.content, symbol.value, syntax=syntax, target=elf))) | def disasm_symbol_app(_parser, _, args): # pragma: no cover
parser = argparse.ArgumentParser(
prog=_parser.prog,
description=_parser.description,
)
parser.add_argument(
'--syntax', '-s',
choices=AsmSyntax.__members__.keys(),
default=None,
)
parser.add_a... | Disassemble a symbol from an ELF file. | 4.287607 | 3.503745 | 1.223721 |
try:
xslt_doc = libxml2.parseFile(xslt)
xslt_proc = libxslt.parseStylesheetDoc(xslt_doc)
xml_doc = libxml2.parseDoc(xml)
result = xslt_proc.applyStylesheet(xml_doc, params)
xml_string = str(result)
xml_unicode_string = xml_string.decode('utf-8')
... | def _transform_libxslt(xml, xslt, params=None) | Transform ``xslt`` using any of the 3 supported xslt engines:
- `lxml <http://codespeak.net/lxml/>`_
- `libxml <http://xmlsoft.org/python.html>`_
:param xml: The xml to be transformed.
:param xslt: The xslt to be used when transforming the ``xml``.
:param params: A dictionary containing xslt param... | 2.439885 | 2.536121 | 0.962054 |
# assuming params where created with prepare_string_param,
# they are encoded as unicode, which lxml does not like
xml_doc = etree.fromstring(xml)
xslt_doc = etree.parse(xslt_path)
xslt_proc = etree.XSLT(xslt_doc)
if params:
for (key, value) in params.iteritems():
... | def _transform_lxml(xml, xslt_path, params=None) | Transform ``xslt`` using any of the 2 supported xslt engines:
- `lxml <http://codespeak.net/lxml/>`_
- `libxml <http://xmlsoft.org/python.html>`_
:param xml: The xml to be transformed.
:param xslt: The xslt to be used when transforming the ``xml``.
:param params: A dictionary containing xslt param... | 3.42437 | 3.302573 | 1.036879 |
member_names = dir(module)
for member_name in member_names:
obj = getattr(module, member_name, None)
if isinstance(obj, ModelBase) \
and obj not in exclude \
and not obj._meta.abstract:
try:
if hasattr(obj, 'localized_fields'):
... | def register_all(module, exclude=[], AdminClass=admin.ModelAdmin) | Register all models in *module* with the admin
:param module: The module that contains the models
:param exclude: A list of models classes that should not be registered | 2.644442 | 2.962243 | 0.892716 |
pattern = re.compile('set\(([a-zA-Z0-9_]+),(\[a-zA-Z0-9_]+)\)')
pairs = pattern.findall(settings)
for name, val in pairs:
self.set(name, val) | def settingsAsFacts(self, settings) | Parses a string of settings.
:param setting: String of settings in the form:
``set(name1, val1), set(name2, val2)...`` | 3.671264 | 3.370268 | 1.089309 |
# Write the inputs
self.__prepare(filestem, b, examples=examples, pos=pos, neg=neg)
# Write scripts
self.__scripts(filestem)
dumpFile = None
if not printOutput:
dumpFile = tempfile.TemporaryFile()
# Run the script
logger.info("Runni... | def induce(self, b, filestem='default',
examples=None,
pos=None,
neg=None,
cn2sd=True,
printOutput=False) | Generate features and find subgroups.
:param filestem: The base name of this experiment.
:param examples: Classified examples; can be used instead of separate pos / neg files below.
:param pos: String of positive examples.
:param neg: String of negative examples.... | 5.181934 | 4.758056 | 1.089086 |
if examples:
examplesFile = open('%s/%s.pl' % (self.tmpdir, filestem), 'w')
examplesFile.write(examples)
examplesFile.close()
elif pos and neg:
posFile = open('%s/%s.f' % (self.tmpdir, filestem), 'w')
negFile = open('%s/%s.n' % (self.t... | def __prepare(self, filestem, b, examples=None, pos=None, neg=None) | Prepares the needed files. | 2.379894 | 2.315751 | 1.027699 |
script_construct = open('%s/%s' % (self.tmpdir, RSD.CONSTRUCT), 'w')
script_save = open('%s/%s' % (self.tmpdir, RSD.SAVE), 'w')
script_subgroups = open('%s/%s' % (self.tmpdir, RSD.SUBGROUPS), 'w')
# Permit the owner to execute and read this script
for fn in RSD.SCRIPTS:... | def __scripts(self, filestem) | Generates the required scripts. | 3.262114 | 3.223265 | 1.012053 |
a = [ 0 ] * (n + 1)
def gen(t, p):
if t > n:
for v in a[1:p + 1]:
yield v
else:
a[t] = a[t - p]
for v in gen(t + 1, p):
yield v
for j in range(a[t - p] + 1, k):
a[t] = j
... | def deBruijn(n, k) | An implementation of the FKM algorithm for generating the de Bruijn
sequence containing all k-ary strings of length n, as described in
"Combinatorial Generation" by Frank Ruskey. | 2.522413 | 2.587166 | 0.974972 |
iter = deBruijn(width, 26)
return ''.join([chr(ord('A') + next(iter)) for i in range(length)]) | def cycle(length, width=4) | Generate a de Bruijn sequence of a given length (and width). A de Bruijn
sequence is a set of varying repetitions where each sequence of *n*
characters is unique within the sequence. This type of sequence can be
used to easily find the offset to the return pointer when exploiting a
buffer overflow.
... | 8.587226 | 10.222705 | 0.840015 |
key_len = len(key)
buf = ''
it = deBruijn(width, 26)
for i in range(key_len):
buf += chr(ord('A') + next(it))
if buf == key:
return 0
for i, c in enumerate(it):
buf = buf[1:] + chr(ord('A') + c)
if buf == key:
return i + 1
return -1 | def cycle_find(key, width=4) | Given an element of a de Bruijn sequence, find its index in that sequence.
Args:
key(str): The piece of the de Bruijn sequence to find.
width(int): The width of each element in the sequence.
Returns:
int: The index of ``key`` in the de Bruijn sequence. | 3.282827 | 3.338735 | 0.983255 |
if not reghex_check.match(pattern):
raise SyntaxError('Invalid reghex pattern.')
b_pattern = b''
for match in reghex_regex.finditer(pattern):
_, match_hex, _, match_char, match_char_len, match_star_plus = match.groups()
if match_hex:
b_pattern += re.escape(pwnypac... | def reghex(pattern) | Compile a regular hexpression (a short form regular expression subset
specifically designed for searching for binary strings).
A regular hexpression consists of hex tuples interspaced with control
characters. The available control characters are:
- ``?``: Any byte (optional).
- ``.``: Any byte (re... | 2.925529 | 2.82994 | 1.033778 |
def cycle_app(parser, cmd, args): # pragma: no cover
parser.add_argument('-w', '--width', type=int, default=4, help='the length of the cycled value')
parser.add_argument('length', type=int, help='the cycle length to generate')
args = parser.parse_args(args)
return cycle(args.length, args.width) | Generate a de Bruijn sequence of a given length. | null | null | null | |
print('Not found.')
sys.exit(1)
else:
print('Found at position: %d' % index) | def cycle_find_app(_parser, cmd, args): # pragma: no cover
parser = argparse.ArgumentParser(
prog=_parser.prog,
description=_parser.description,
)
parser.add_argument('-w', '--width', type=int, default=4, help='the length of the cycled value')
parser.add_argument('value', help='th... | Find the first position of a value in a de Bruijn sequence. | 7.30705 | 4.193948 | 1.742284 |
def escape_single(matchobj):
return _unicode_for_entity_with_name(matchobj.group(1))
return entities.sub(escape_single, string) | def unescape_all(string) | Resolve all html entities to their corresponding unicode character | 6.224402 | 6.184453 | 1.00646 |
xml_file = StringIO.StringIO(xml_string.encode('utf-8'))
parser = XmlScanner()
parser.setContentHandler(ContentHandler())
try:
parser.parse(xml_file)
except SAXParseException:
return False
return True | def is_valid(xml_string) | validates a unicode string containing xml | 3.389548 | 3.268237 | 1.037118 |
global template_source_loaders
if template_source_loaders is None:
loaders = []
for loader_name in settings.TEMPLATE_LOADERS:
loader = find_template_loader(loader_name)
if loader is not None:
loaders.append(loader)
template_source_loaders = tu... | def find_template_path(name) | Same as :func:`django.template.loader.find_template`, but it only returns the path
to the template file. | 2.293552 | 2.244889 | 1.021678 |
doc = None
docpath = self.fs.join(self.rootdir, docid)
if not self.fs.exists(docpath):
return None
if doc_type_name is not None:
# if we already know the doc type name
for (is_doc_type, doc_type_name_b, doc_type) in DOC_TYPE_LIST:
... | def __inst_doc(self, docid, doc_type_name=None) | Instantiate a document based on its document id.
The information are taken from the whoosh index. | 2.585124 | 2.565445 | 1.007671 |
assert(docid is not None)
if docid in self._docs_by_id:
return self._docs_by_id[docid]
if not inst:
return None
doc = self.__inst_doc(docid, doc_type_name)
if doc is None:
return None
self._docs_by_id[docid] = doc
retur... | def get_doc_from_docid(self, docid, doc_type_name=None, inst=True) | Try to find a document based on its document id. if inst=True, if it
hasn't been instantiated yet, it will be. | 2.036979 | 1.946812 | 1.046315 |
all_labels = set(self.label_list)
doc_labels = set(doc.labels)
new_labels = doc_labels.difference(all_labels)
# can happen when we recreate the index from scratch
for label in new_labels:
self.create_label(label)
last_mod = datetime.datetime.fromtim... | def _update_doc_in_index(self, index_writer, doc) | Add/Update a document in the index | 3.832047 | 3.75894 | 1.019449 |
query = whoosh.query.Term("docid", docid)
index_writer.delete_by_query(query) | def _delete_doc_from_index(index_writer, docid) | Remove a document from the index | 3.927937 | 3.606317 | 1.089182 |
if not self.index_writer and index_update:
self.index_writer = self.index.writer()
if not self.label_guesser_updater and label_guesser_update:
self.label_guesser_updater = self.label_guesser.get_updater()
logger.info("Indexing new doc: %s" % doc)
if index... | def add_doc(self, doc, index_update=True, label_guesser_update=True) | Add a document to the index | 2.163399 | 2.162874 | 1.000243 |
if not self.index_writer and index_update:
self.index_writer = self.index.writer()
if not self.label_guesser_updater and label_guesser_update:
self.label_guesser_updater = self.label_guesser.get_updater()
logger.info("Updating modified doc: %s" % doc)
if ... | def upd_doc(self, doc, index_update=True, label_guesser_update=True) | Update a document in the index | 2.42027 | 2.389998 | 1.012666 |
if not self.index_writer:
self.index_writer = self.index.writer()
if not self.label_guesser_updater:
self.label_guesser_updater = self.label_guesser.get_updater()
logger.info("Removing doc from the index: %s" % doc)
if doc.docid in self._docs_by_id:
... | def del_doc(self, doc) | Delete a document | 3.986231 | 4.054655 | 0.983125 |
logger.info("Index: Commiting changes")
if self.index_writer:
if index_update:
self.index_writer.commit()
else:
self.index_writer.cancel()
del self.index_writer
self.index_writer = None
self.index.refresh()
... | def commit(self, index_update=True, label_guesser_update=True) | Apply the changes to the index | 3.200868 | 3.147099 | 1.017085 |
logger.info("Index: Index update cancelled")
if self.index_writer:
self.index_writer.cancel()
del self.index_writer
self.index_writer = None
if self.label_guesser_updater:
self.label_guesser_updater.cancel()
self.label_guesser_updater ... | def cancel(self) | Forget about the changes | 4.653568 | 4.480587 | 1.038607 |
if doc.nb_pages <= 0:
return set()
self.label_guesser.total_nb_documents = len(self._docs_by_id.keys())
label_names = self.label_guesser.guess(doc)
labels = set()
for label_name in label_names:
label = self.labels[label_name]
labels.ad... | def guess_labels(self, doc) | return a prediction of label names | 3.659526 | 3.772948 | 0.969938 |
if BasicPage.PAGE_ID_SEPARATOR in obj_id:
(docid, page_nb) = obj_id.split(BasicPage.PAGE_ID_SEPARATOR)
page_nb = int(page_nb)
return self._docs_by_id[docid].pages[page_nb]
return self._docs_by_id[obj_id] | def get(self, obj_id) | Get a document or a page using its ID
Won't instantiate them if they are not yet available | 3.303063 | 3.019449 | 1.093929 |
sentence = sentence.strip()
sentence = strip_accents(sentence)
if sentence == u"":
return self.get_all_docs()
result_list_list = []
total_results = 0
for query_parser in self.search_param_list[search_type]:
query = query_parser["query_p... | def find_documents(self, sentence, limit=None, must_sort=True,
search_type='fuzzy') | Returns all the documents matching the given keywords
Arguments:
sentence --- a sentenced query
Returns:
An array of document (doc objects) | 2.957742 | 3.018975 | 0.979717 |
if not isinstance(sentence, str):
sentence = str(sentence)
keywords = sentence.split(" ")
query_parser = self.search_param_list['strict'][0]['query_parser']
base_search = u" ".join(keywords).strip()
final_suggestions = []
corrector = self.__searche... | def find_suggestions(self, sentence) | Search all possible suggestions. Suggestions returned always have at
least one document matching.
Arguments:
sentence --- keywords (single strings) for which we want
suggestions
Return:
An array of sets of keywords. Each set of keywords (-> one string)
... | 3.591408 | 3.638037 | 0.987183 |
label = copy.copy(label)
assert(label not in self.labels.values())
self.labels[label.name] = label
self.label_guesser.load(label.name)
# TODO(Jflesch): Should train with previous documents
if doc:
doc.add_label(label)
self.upd_doc(doc)
... | def create_label(self, label, doc=None) | Create a new label
Arguments:
doc --- first document on which the label must be added (required
for now) | 8.182115 | 8.68321 | 0.942291 |
label = copy.copy(label)
assert(label in self.labels.values())
doc.add_label(label)
if update_index:
self.upd_doc(doc)
self.commit() | def add_label(self, doc, label, update_index=True) | Add a label on a document.
Arguments:
label --- The new label (see labels.Label)
doc --- The first document on which this label has been added | 4.637424 | 5.653374 | 0.820293 |
doc.remove_label(label)
if update_index:
self.upd_doc(doc)
self.commit() | def remove_label(self, doc, label, update_index=True) | Remove a label from a doc. Takes care of updating the index | 4.105773 | 4.289376 | 0.957196 |
self.close()
logger.info("Destroying the index ...")
rm_rf(self.indexdir)
rm_rf(self.label_guesser_dir)
logger.info("Done") | def destroy_index(self) | Destroy the index. Don't use this Index object anymore after this
call. Index will have to be rebuilt from scratch | 8.577459 | 8.916582 | 0.961967 |
filehash = (u"%X" % filehash)
results = self.__searcher.search(
whoosh.query.Term('docfilehash', filehash))
return bool(results) | def is_hash_in_index(self, filehash) | Check if there is a document using this file hash | 8.64465 | 6.786101 | 1.273876 |
try:
content_type = ContentType.objects.get(pk=content_type_id)
obj = content_type.get_object_for_this_type(pk=object_id)
except ObjectDoesNotExist:
raise http.Http404("Content type %s object %s doesn't exist" % (content_type_id, object_id))
try:
absolute_url = obj.... | def preview(request, content_type_id, object_id) | This is an override for django.views.default.shortcut.
It assumes that get_absolute_url returns an absolute url, so
it does not do any of the very elaborate link checking that shortcut does.
This version adds the language code to the url. (/en/blaat/). | 2.148501 | 2.074358 | 1.035743 |
tessdata_files = glob.glob("/app/share/locale/*/*.traineddata")
if len(tessdata_files) <= 0:
return os.path.exists("/app")
localdir = os.path.expanduser("~/.local")
base_data_dir = os.getenv(
"XDG_DATA_HOME",
os.path.join(localdir, "share")
)
tessdatadir = os.path.j... | def init_flatpak() | If we are in Flatpak, we must build a tessdata/ directory using the
.traineddata files from each locale directory | 2.423504 | 2.269172 | 1.068013 |
lang = translation.get_language()
fallback_list = settings.FALLBACK_LANGUAGES.get(lang, None)
if fallback_list:
return fallback_list
return settings.FALLBACK_LANGUAGES.get(lang[:2], []) | def get_fallback_languages() | Retrieve the fallback languages from the settings.py | 2.870535 | 2.675683 | 1.072823 |
'''
When accessing to the name of the field itself, the value
in the current language will be returned. Unless it's set,
the value in the default language will be returned.
'''
if language:
return getattr(context, get_real_fieldname(field, language))
if hasattr(settings, 'FALLBA... | def get_localized_property(context, field=None, language=None) | When accessing to the name of the field itself, the value
in the current language will be returned. Unless it's set,
the value in the default language will be returned. | 5.048685 | 3.395077 | 1.48706 |
attrs = [
translation.get_language(),
translation.get_language()[:2],
settings.LANGUAGE_CODE
]
def predicate(x):
field_name = get_real_fieldname(field, x)
if hasattr(context, field_name):
return field_name
... | def get_localized_field_name(context, field) | Get the name of the localized field | 6.647229 | 6.873178 | 0.967126 |
return first_match(lambda x: x if x.name == field_name else None, model_class._meta.fields) | def get_field_from_model_by_name(model_class, field_name) | Get a field by name from a model class without messing with the app cache. | 5.263349 | 5.083139 | 1.035453 |
module_names = args
if len(module_names) <= 0:
error("No module specified")
return
distribution = get_distribution()
for module_name in module_names:
_chkdeps(module_name, distribution) | def chkdeps(*args) | Arguments: <component1> [<component2> [...]]]
Look for missing dependencies and tries to suggest a command to install
them all using the local distribution package manager (APT, DNF, etc).
Examples:
paperwork-shell chkdeps paperwork_backend
paperwork-shell chkdeps paperwork
paperwo... | 4.217148 | 5.353386 | 0.787753 |
if len(args) == 0:
print("Possible commands are:")
print("")
for cmd_name in sorted(COMMANDS.keys()):
cmd_func = COMMANDS[cmd_name]
print("{}:".format(cmd_name))
print("=" * (len(cmd_name) + 1))
print(" {}".format(cmd_func.__doc__.strip... | def cmd_help(*args) | Arguments: [<command>]
List available commands | 1.883288 | 1.877631 | 1.003013 |
# train the network
self._som.train(data, **kwargs)
# retrieve first and second bmus and distances
bmus, q_error, t_error = self.bmus_with_errors(data)
# set errors measures of training data
self.quant_error = q_error
self.topog_error = t_error
# ... | def fit(self, data, labels, **kwargs) | \
Training the SOM on the the data and calibrate itself.
After the training, `self.quant_error` and `self.topog_error` are
respectively set.
:param data: sparse input matrix (ideal dtype is `numpy.float32`)
:type data: :class:`scipy.sparse.csr_matrix`
:param labels: th... | 8.705623 | 5.836547 | 1.491571 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.