_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q233000 | TargetRunLengthEncoder._rle | train | def _rle(self, a):
'''
rle implementation credit to Thomas Browne from his SOF post Sept 2015
Parameters
----------
a : array, shape[n,]
input vector
Returns
-------
z : array, shape[nt,]
run lengths
p : array, shape[nt,]
... | python | {
"resource": ""
} |
q233001 | TargetRunLengthEncoder._transform | train | def _transform(self, X, y):
'''
Transforms single series
'''
z, p, y_rle = self._rle(y)
p = np.append(p, len(y))
big_enough = p[1:] - p[:-1] >= self.min_length
Xt = []
for i in range(len(y_rle)):
if (big_enough[i]):
Xt.append(X... | python | {
"resource": ""
} |
q233002 | get_ts_data_parts | train | def get_ts_data_parts(X):
'''
Separates time series data object into time series variables and contextual variables
Parameters
----------
X : array-like, shape [n_series, ...]
Time series data and (optionally) contextual data
Returns
-------
Xt : array-like, shape [n_series, ]
... | python | {
"resource": ""
} |
q233003 | check_ts_data_with_ts_target | train | def check_ts_data_with_ts_target(X, y=None):
'''
Checks time series data with time series target is good. If not raises value error.
Parameters
----------
X : array-like, shape [n_series, ...]
Time series data and (optionally) contextual data
y : array-like, shape [n_series, ...]
... | python | {
"resource": ""
} |
q233004 | ts_stats | train | def ts_stats(Xt, y, fs=1.0, class_labels=None):
'''
Generates some helpful statistics about the data X
Parameters
----------
X : array-like, shape [n_series, ...]
Time series data and (optionally) contextual data
y : array-like, shape [n_series]
target data
fs : float
... | python | {
"resource": ""
} |
q233005 | load_watch | train | def load_watch():
'''
Loads some of the 6-axis inertial sensor data from my smartwatch project. The sensor data was
recorded as study subjects performed sets of 20 shoulder exercise repetitions while wearing a
smartwatch. It is a multivariate time series.
The study can be found here: https://arxiv.... | python | {
"resource": ""
} |
q233006 | shuffle_data | train | def shuffle_data(X, y=None, sample_weight=None):
''' Shuffles indices X, y, and sample_weight together'''
if len(X) > 1:
ind = np.arange(len(X), dtype=np.int)
np.random.shuffle(ind)
Xt = X[ind]
yt = y
swt = sample_weight
if yt is not None:
yt = yt[ind... | python | {
"resource": ""
} |
q233007 | expand_variables_to_segments | train | def expand_variables_to_segments(v, Nt):
''' expands contextual variables v, by repeating each instance as specified in Nt '''
N_v = len(np.atleast_1d(v[0]))
return np.concatenate([np.full((Nt[i], N_v), v[i]) for i in np.arange(len(v))]) | python | {
"resource": ""
} |
q233008 | sliding_window | train | def sliding_window(time_series, width, step, order='F'):
'''
Segments univariate time series with sliding window
Parameters
----------
time_series : array like shape [n_samples]
time series or sequence
width : int > 0
segment width in samples
step : int > 0
stepsize ... | python | {
"resource": ""
} |
q233009 | sliding_tensor | train | def sliding_tensor(mv_time_series, width, step, order='F'):
'''
segments multivariate time series with sliding window
Parameters
----------
mv_time_series : array like shape [n_samples, n_variables]
multivariate time series or sequence
width : int > 0
segment width in samples
... | python | {
"resource": ""
} |
q233010 | SegmentXY.transform | train | def transform(self, X, y=None, sample_weight=None):
'''
Transforms the time series data into segments
Note this transformation changes the number of samples in the data
If y is provided, it is segmented and transformed to align to the new samples as per
``y_func``
Current... | python | {
"resource": ""
} |
q233011 | PadTrunc.transform | train | def transform(self, X, y=None, sample_weight=None):
'''
Transforms the time series data into fixed length segments using padding and or truncation
If y is a time series and passed, it will be transformed as well
Parameters
----------
X : array-like, shape [n_series, ...]... | python | {
"resource": ""
} |
q233012 | InterpLongToWide._check_data | train | def _check_data(self, X):
'''
Checks that unique identifiers vaf_types are consistent between time series.
Parameters
----------
X : array-like, shape [n_series, ...]
Time series data and (optionally) contextual data
'''
if len(X) > 1:
sv... | python | {
"resource": ""
} |
q233013 | FeatureRep._check_features | train | def _check_features(self, features, Xti):
'''
tests output of each feature against a segmented time series X
Parameters
----------
features : dict
feature function dictionary
Xti : array-like, shape [n_samples, segment_width, n_variables]
segmente... | python | {
"resource": ""
} |
q233014 | FeatureRep._generate_feature_labels | train | def _generate_feature_labels(self, X):
'''
Generates string feature labels
'''
Xt, Xc = get_ts_data_parts(X)
ftr_sizes = self._check_features(self.features, Xt[0:3])
f_labels = []
# calculated features
for key in ftr_sizes:
for i in range(ftr... | python | {
"resource": ""
} |
q233015 | FeatureRepMix._retrieve_indices | train | def _retrieve_indices(cols):
'''
Retrieve a list of indices corresponding to the provided column specification.
'''
if isinstance(cols, int):
return [cols]
elif isinstance(cols, slice):
start = cols.start if cols.start else 0
stop = cols.stop
... | python | {
"resource": ""
} |
q233016 | FeatureRepMix._validate | train | def _validate(self):
'''
Internal function to validate the transformer before applying all internal transformers.
'''
if self.f_labels is None:
raise NotFittedError('FeatureRepMix')
if not self.transformers:
return
names, transformers, _ = zip(*s... | python | {
"resource": ""
} |
q233017 | FunctionTransformer.transform | train | def transform(self, X):
'''
Transforms the time series data based on the provided function. Note this transformation
must not change the number of samples in the data.
Parameters
----------
X : array-like, shape [n_samples, ...]
time series data and (optional... | python | {
"resource": ""
} |
q233018 | RequestSegment.build_payload | train | def build_payload(self, payload):
"""Build payload of all parts and write them into the payload buffer"""
remaining_size = self.MAX_SEGMENT_PAYLOAD_SIZE
for part in self.parts:
part_payload = part.pack(remaining_size)
payload.write(part_payload)
remaining_siz... | python | {
"resource": ""
} |
q233019 | escape | train | def escape(value):
"""
Escape a single value.
"""
if isinstance(value, (tuple, list)):
return "(" + ", ".join([escape(arg) for arg in value]) + ")"
else:
typ = by_python_type.get(value.__class__)
if typ is None:
raise InterfaceError(
"Unsupported ... | python | {
"resource": ""
} |
q233020 | escape_values | train | def escape_values(values):
"""
Escape multiple values from a list, tuple or dict.
"""
if isinstance(values, (tuple, list)):
return tuple([escape(value) for value in values])
elif isinstance(values, dict):
return dict([
(key, escape(value)) for (key, value) in values.items... | python | {
"resource": ""
} |
q233021 | Date.prepare | train | def prepare(cls, value):
"""Pack datetime value into proper binary format"""
pfield = struct.pack('b', cls.type_code)
if isinstance(value, string_types):
value = datetime.datetime.strptime(value, "%Y-%m-%d")
year = value.year | 0x8000 # for some unknown reasons year has to b... | python | {
"resource": ""
} |
q233022 | Time.prepare | train | def prepare(cls, value):
"""Pack time value into proper binary format"""
pfield = struct.pack('b', cls.type_code)
if isinstance(value, string_types):
if "." in value:
value = datetime.datetime.strptime(value, "%H:%M:%S.%f")
else:
value = da... | python | {
"resource": ""
} |
q233023 | MixinLobType.prepare | train | def prepare(cls, value, length=0, position=0, is_last_data=True):
"""Prepare Lob header.
Note that the actual lob data is NOT written here but appended after the parameter block for each row!
"""
hstruct = WriteLobHeader.header_struct
lob_option_dataincluded = WriteLobHeader.LOB_... | python | {
"resource": ""
} |
q233024 | Lob.seek | train | def seek(self, offset, whence=SEEK_SET):
"""Seek pointer in lob data buffer to requested position.
Might trigger further loading of data from the database if the pointer is beyond currently read data.
"""
# A nice trick is to (ab)use BytesIO.seek() to go to the desired position for easie... | python | {
"resource": ""
} |
q233025 | Lob._read_missing_lob_data_from_db | train | def _read_missing_lob_data_from_db(self, readoffset, readlength):
"""Read LOB request part from database"""
logger.debug('Reading missing lob data from db. Offset: %d, readlength: %d' % (readoffset, readlength))
lob_data = self._make_read_lob_request(readoffset, readlength)
# make sure ... | python | {
"resource": ""
} |
q233026 | Clob._init_io_container | train | def _init_io_container(self, init_value):
"""Initialize container to hold lob data.
Here either a cStringIO or a io.StringIO class is used depending on the Python version.
For CLobs ensure that an initial unicode value only contains valid ascii chars.
"""
if isinstance(init_value... | python | {
"resource": ""
} |
q233027 | Cursor._handle_upsert | train | def _handle_upsert(self, parts, unwritten_lobs=()):
"""Handle reply messages from INSERT or UPDATE statements"""
self.description = None
self._received_last_resultset_part = True # set to 'True' so that cursor.fetch*() returns just empty list
for part in parts:
if part.kind... | python | {
"resource": ""
} |
q233028 | Cursor._handle_select | train | def _handle_select(self, parts, result_metadata=None):
"""Handle reply messages from SELECT statements"""
self.rowcount = -1
if result_metadata is not None:
# Select was prepared and we can use the already received metadata
self.description, self._column_types = self._han... | python | {
"resource": ""
} |
q233029 | Cursor._handle_dbproc_call | train | def _handle_dbproc_call(self, parts, parameters_metadata):
"""Handle reply messages from STORED PROCEDURE statements"""
for part in parts:
if part.kind == part_kinds.ROWSAFFECTED:
self.rowcount = part.values[0]
elif part.kind == part_kinds.TRANSACTIONFLAGS:
... | python | {
"resource": ""
} |
q233030 | allhexlify | train | def allhexlify(data):
"""Hexlify given data into a string representation with hex values for all chars
Input like
'ab\x04ce'
becomes
'\x61\x62\x04\x63\x65'
"""
hx = binascii.hexlify(data)
return b''.join([b'\\x' + o for o in re.findall(b'..', hx)]) | python | {
"resource": ""
} |
q233031 | Part.pack | train | def pack(self, remaining_size):
"""Pack data of part into binary format"""
arguments_count, payload = self.pack_data(remaining_size - self.header_size)
payload_length = len(payload)
# align payload length to multiple of 8
if payload_length % 8 != 0:
payload += b"\x00... | python | {
"resource": ""
} |
q233032 | Part.unpack_from | train | def unpack_from(cls, payload, expected_parts):
"""Unpack parts from payload"""
for num_part in iter_range(expected_parts):
hdr = payload.read(cls.header_size)
try:
part_header = PartHeader(*cls.header_struct.unpack(hdr))
except struct.error:
... | python | {
"resource": ""
} |
q233033 | ReadLobRequest.pack_data | train | def pack_data(self, remaining_size):
"""Pack data. readoffset has to be increased by one, seems like HANA starts from 1, not zero."""
payload = self.part_struct.pack(self.locator_id, self.readoffset + 1, self.readlength, b' ')
return 4, payload | python | {
"resource": ""
} |
q233034 | RequestMessage.build_payload | train | def build_payload(self, payload):
""" Build payload of message. """
for segment in self.segments:
segment.pack(payload, commit=self.autocommit) | python | {
"resource": ""
} |
q233035 | RequestMessage.pack | train | def pack(self):
""" Pack message to binary stream. """
payload = io.BytesIO()
# Advance num bytes equal to header size - the header is written later
# after the payload of all segments and parts has been written:
payload.seek(self.header_size, io.SEEK_CUR)
# Write out pa... | python | {
"resource": ""
} |
q233036 | check_specs | train | def check_specs(specs, renamings, types):
'''
Does nothing but raising PythranSyntaxError if specs
are incompatible with the actual code
'''
from pythran.types.tog import unify, clone, tr
from pythran.types.tog import Function, TypeVariable, InferenceError
functions = {renamings.get(k, k): ... | python | {
"resource": ""
} |
q233037 | check_exports | train | def check_exports(mod, specs, renamings):
'''
Does nothing but raising PythranSyntaxError if specs
references an undefined global
'''
functions = {renamings.get(k, k): v for k, v in specs.functions.items()}
mod_functions = {node.name: node for node in mod.body
if isinstance... | python | {
"resource": ""
} |
q233038 | SyntaxChecker.visit_Import | train | def visit_Import(self, node):
""" Check if imported module exists in MODULES. """
for alias in node.names:
current_module = MODULES
# Recursive check for submodules
for path in alias.name.split('.'):
if path not in current_module:
r... | python | {
"resource": ""
} |
q233039 | SyntaxChecker.visit_ImportFrom | train | def visit_ImportFrom(self, node):
"""
Check validity of imported functions.
Check:
- no level specific value are provided.
- a module is provided
- module/submodule exists in MODULES
- imported function exists in the given ... | python | {
"resource": ""
} |
q233040 | uncamel | train | def uncamel(name):
"""Transform CamelCase naming convention into C-ish convention."""
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() | python | {
"resource": ""
} |
q233041 | ContextManager.verify_dependencies | train | def verify_dependencies(self):
"""
Checks no analysis are called before a transformation,
as the transformation could invalidate the analysis.
"""
for i in range(1, len(self.deps)):
assert(not (isinstance(self.deps[i], Transformation) and
isinstanc... | python | {
"resource": ""
} |
q233042 | ContextManager.prepare | train | def prepare(self, node):
'''Gather analysis result required by this analysis'''
if isinstance(node, ast.Module):
self.ctx.module = node
elif isinstance(node, ast.FunctionDef):
self.ctx.function = node
for D in self.deps:
d = D()
d.attach(s... | python | {
"resource": ""
} |
q233043 | Transformation.run | train | def run(self, node):
""" Apply transformation and dependencies and fix new node location."""
n = super(Transformation, self).run(node)
if self.update:
ast.fix_missing_locations(n)
self.passmanager._cache.clear()
return n | python | {
"resource": ""
} |
q233044 | Transformation.apply | train | def apply(self, node):
""" Apply transformation and return if an update happened. """
new_node = self.run(node)
return self.update, new_node | python | {
"resource": ""
} |
q233045 | PassManager.gather | train | def gather(self, analysis, node):
"High-level function to call an `analysis' on a `node'"
assert issubclass(analysis, Analysis)
a = analysis()
a.attach(self)
return a.run(node) | python | {
"resource": ""
} |
q233046 | PassManager.dump | train | def dump(self, backend, node):
'''High-level function to call a `backend' on a `node' to generate
code for module `module_name'.'''
assert issubclass(backend, Backend)
b = backend()
b.attach(self)
return b.run(node) | python | {
"resource": ""
} |
q233047 | PassManager.apply | train | def apply(self, transformation, node):
'''
High-level function to call a `transformation' on a `node'.
If the transformation is an analysis, the result of the analysis
is displayed.
'''
assert issubclass(transformation, (Transformation, Analysis))
a = transformati... | python | {
"resource": ""
} |
q233048 | pytype_to_ctype | train | def pytype_to_ctype(t):
""" Python -> pythonic type binding. """
if isinstance(t, List):
return 'pythonic::types::list<{0}>'.format(
pytype_to_ctype(t.__args__[0])
)
elif isinstance(t, Set):
return 'pythonic::types::set<{0}>'.format(
pytype_to_ctype(t.__args__... | python | {
"resource": ""
} |
q233049 | pytype_to_pretty_type | train | def pytype_to_pretty_type(t):
""" Python -> docstring type. """
if isinstance(t, List):
return '{0} list'.format(pytype_to_pretty_type(t.__args__[0]))
elif isinstance(t, Set):
return '{0} set'.format(pytype_to_pretty_type(t.__args__[0]))
elif isinstance(t, Dict):
tkey, tvalue = t... | python | {
"resource": ""
} |
q233050 | get_type | train | def get_type(name, env, non_generic):
"""Get the type of identifier name from the type environment env.
Args:
name: The identifier name
env: The type environment mapping from identifier names to types
non_generic: A set of non-generic TypeVariables
Raises:
ParseError: Raise... | python | {
"resource": ""
} |
q233051 | fresh | train | def fresh(t, non_generic):
"""Makes a copy of a type expression.
The type t is copied. The generic variables are duplicated and the
non_generic variables are shared.
Args:
t: A type to be copied.
non_generic: A set of non-generic TypeVariables
"""
mappings = {} # A mapping of... | python | {
"resource": ""
} |
q233052 | prune | train | def prune(t):
"""Returns the currently defining instance of t.
As a side effect, collapses the list of type instances. The function Prune
is used whenever a type expression has to be inspected: it will always
return a type expression which is either an uninstantiated type variable or
a type operato... | python | {
"resource": ""
} |
q233053 | occurs_in_type | train | def occurs_in_type(v, type2):
"""Checks whether a type variable occurs in a type expression.
Note: Must be called with v pre-pruned
Args:
v: The TypeVariable to be tested for
type2: The type in which to search
Returns:
True if v occurs in type2, otherwise False
"""
pr... | python | {
"resource": ""
} |
q233054 | ExpandImports.visit_Module | train | def visit_Module(self, node):
"""
Visit the whole module and add all import at the top level.
>> import numpy.linalg
Becomes
>> import numpy
"""
node.body = [k for k in (self.visit(n) for n in node.body) if k]
imports = [ast.Import([ast.alias(i, mangle... | python | {
"resource": ""
} |
q233055 | ExpandImports.visit_Name | train | def visit_Name(self, node):
"""
Replace name with full expanded name.
Examples
--------
>> from numpy.linalg import det
>> det(a)
Becomes
>> numpy.linalg.det(a)
"""
if node.id in self.symbols:
symbol = path_to_node(self.symb... | python | {
"resource": ""
} |
q233056 | save_function_effect | train | def save_function_effect(module):
""" Recursively save function effect for pythonic functions. """
for intr in module.values():
if isinstance(intr, dict): # Submodule case
save_function_effect(intr)
else:
fe = FunctionEffects(intr)
IntrinsicArgumentEffects[in... | python | {
"resource": ""
} |
q233057 | ArgumentEffects.prepare | train | def prepare(self, node):
"""
Initialise arguments effects as this analyse is inter-procedural.
Initialisation done for Pythonic functions and default value set for
user defined functions.
"""
super(ArgumentEffects, self).prepare(node)
for n in self.global_declara... | python | {
"resource": ""
} |
q233058 | CxxFunction.process_locals | train | def process_locals(self, node, node_visited, *skipped):
"""
Declare variable local to node and insert declaration before.
Not possible for function yielding values.
"""
local_vars = self.scope[node].difference(skipped)
local_vars = local_vars.difference(self.openmp_deps)... | python | {
"resource": ""
} |
q233059 | CxxFunction.process_omp_attachements | train | def process_omp_attachements(self, node, stmt, index=None):
"""
Add OpenMP pragma on the correct stmt in the correct order.
stmt may be a list. On this case, index have to be specify to add
OpenMP on the correct statement.
"""
omp_directives = metadata.get(node, OMPDirec... | python | {
"resource": ""
} |
q233060 | CxxFunction.visit_Assign | train | def visit_Assign(self, node):
"""
Create Assign node for final Cxx representation.
It tries to handle multi assignment like:
>> a = b = c = 2
If only one local variable is assigned, typing is added:
>> int a = 2;
TODO: Handle case of multi-assignement for som... | python | {
"resource": ""
} |
q233061 | CxxFunction.gen_for | train | def gen_for(self, node, target, local_iter, local_iter_decl, loop_body):
"""
Create For representation on iterator for Cxx generation.
Examples
--------
>> "omp parallel for"
>> for i in xrange(10):
>> ... do things ...
Becomes
>> "omp paral... | python | {
"resource": ""
} |
q233062 | CxxFunction.handle_real_loop_comparison | train | def handle_real_loop_comparison(self, args, target, upper_bound):
"""
Handle comparison for real loops.
Add the correct comparison operator if possible.
"""
# order is 1 for increasing loop, -1 for decreasing loop and 0 if it is
# not known at compile time
if len... | python | {
"resource": ""
} |
q233063 | CxxFunction.gen_c_for | train | def gen_c_for(self, node, local_iter, loop_body):
"""
Create C For representation for Cxx generation.
Examples
--------
>> for i in xrange(10):
>> ... do things ...
Becomes
>> for(long i = 0, __targetX = 10; i < __targetX; i += 1)
>> ...... | python | {
"resource": ""
} |
q233064 | CxxFunction.handle_omp_for | train | def handle_omp_for(self, node, local_iter):
"""
Fix OpenMP directives on For loops.
Add the target as private variable as a new variable may have been
introduce to handle cxx iterator.
Also, add the iterator as shared variable as all 'parallel for chunck'
have to use th... | python | {
"resource": ""
} |
q233065 | CxxFunction.can_use_autofor | train | def can_use_autofor(self, node):
"""
Check if given for Node can use autoFor syntax.
To use auto_for:
- iterator should have local scope
- yield should not be use
- OpenMP pragma should not be use
TODO : Yield should block only if it is use in the fo... | python | {
"resource": ""
} |
q233066 | CxxFunction.can_use_c_for | train | def can_use_c_for(self, node):
"""
Check if a for loop can use classic C syntax.
To use C syntax:
- target should not be assign in the loop
- xrange should be use as iterator
- order have to be known at compile time
"""
assert isinstance(node.... | python | {
"resource": ""
} |
q233067 | CxxFunction.visit_For | train | def visit_For(self, node):
"""
Create For representation for Cxx generation.
Examples
--------
>> for i in xrange(10):
>> ... work ...
Becomes
>> typename returnable<decltype(__builtin__.xrange(10))>::type __iterX
= __builtin__.xrange(10)... | python | {
"resource": ""
} |
q233068 | CxxFunction.visit_While | train | def visit_While(self, node):
"""
Create While node for Cxx generation.
It is a cxx_loop to handle else clause.
"""
test = self.visit(node.test)
body = [self.visit(n) for n in node.body]
stmt = While(test, Block(body))
return self.process_omp_attachements(... | python | {
"resource": ""
} |
q233069 | CxxFunction.visit_Break | train | def visit_Break(self, _):
"""
Generate break statement in most case and goto for orelse clause.
See Also : cxx_loop
"""
if self.break_handlers and self.break_handlers[-1]:
return Statement("goto {0}".format(self.break_handlers[-1]))
else:
return S... | python | {
"resource": ""
} |
q233070 | Cxx.visit_Module | train | def visit_Module(self, node):
""" Build a compilation unit. """
# build all types
deps = sorted(self.dependencies)
headers = [Include(os.path.join("pythonic", "include", *t) + ".hpp")
for t in deps]
headers += [Include(os.path.join("pythonic", *t) + ".hpp")
... | python | {
"resource": ""
} |
q233071 | refine | train | def refine(pm, node, optimizations):
""" Refine node in place until it matches pythran's expectations. """
# Sanitize input
pm.apply(ExpandGlobals, node)
pm.apply(ExpandImportAll, node)
pm.apply(NormalizeTuples, node)
pm.apply(ExpandBuiltins, node)
pm.apply(ExpandImports, node)
pm.apply(... | python | {
"resource": ""
} |
q233072 | GlobalEffects.prepare | train | def prepare(self, node):
"""
Initialise globals effects as this analyse is inter-procedural.
Initialisation done for Pythonic functions and default value set for
user defined functions.
"""
super(GlobalEffects, self).prepare(node)
def register_node(module):
... | python | {
"resource": ""
} |
q233073 | Types.prepare | train | def prepare(self, node):
"""
Initialise values to prepare typing computation.
Reorder functions to avoid dependencies issues and prepare typing
computation setting typing values for Pythonic functions.
"""
def register(name, module):
""" Recursively save fun... | python | {
"resource": ""
} |
q233074 | Types.register | train | def register(self, ptype):
"""register ptype as a local typedef"""
# Too many of them leads to memory burst
if len(self.typedefs) < cfg.getint('typing', 'max_combiner'):
self.typedefs.append(ptype)
return True
return False | python | {
"resource": ""
} |
q233075 | Types.isargument | train | def isargument(self, node):
""" checks whether node aliases to a parameter."""
try:
node_id, _ = self.node_to_id(node)
return (node_id in self.name_to_nodes and
any([isinstance(n, ast.Name) and
isinstance(n.ctx, ast.Param)
... | python | {
"resource": ""
} |
q233076 | Types.combine | train | def combine(self, node, othernode, op=None, unary_op=None, register=False,
aliasing_type=False):
"""
Change `node` typing with combination of `node` and `othernode`.
Parameters
----------
aliasing_type : bool
All node aliasing to `node` have to be upd... | python | {
"resource": ""
} |
q233077 | Types.visit_Return | train | def visit_Return(self, node):
""" Compute return type and merges with others possible return type."""
self.generic_visit(node)
# No merge are done if the function is a generator.
if not self.yield_points:
assert node.value, "Values were added in each return statement."
... | python | {
"resource": ""
} |
q233078 | Types.visit_Yield | train | def visit_Yield(self, node):
""" Compute yield type and merges it with others yield type. """
self.generic_visit(node)
self.combine(self.current, node.value) | python | {
"resource": ""
} |
q233079 | Types.visit_BoolOp | train | def visit_BoolOp(self, node):
"""
Merge BoolOp operand type.
BoolOp are "and" and "or" and may return any of these results so all
operands should have the combinable type.
"""
# Visit subnodes
self.generic_visit(node)
# Merge all operands types.
[... | python | {
"resource": ""
} |
q233080 | Types.visit_Num | train | def visit_Num(self, node):
"""
Set type for number.
It could be int, long or float so we use the default python to pythonic
type converter.
"""
ty = type(node.n)
sty = pytype_to_ctype(ty)
if node in self.immediates:
sty = "std::integral_consta... | python | {
"resource": ""
} |
q233081 | Types.visit_Str | train | def visit_Str(self, node):
""" Set the pythonic string type. """
self.result[node] = self.builder.NamedType(pytype_to_ctype(str)) | python | {
"resource": ""
} |
q233082 | Types.visit_Attribute | train | def visit_Attribute(self, node):
""" Compute typing for an attribute node. """
obj, path = attr_to_path(node)
# If no type is given, use a decltype
if obj.isliteral():
typename = pytype_to_ctype(obj.signature)
self.result[node] = self.builder.NamedType(typename)
... | python | {
"resource": ""
} |
q233083 | Types.visit_Slice | train | def visit_Slice(self, node):
"""
Set slicing type using continuous information if provided.
Also visit subnodes as they may contains relevant typing information.
"""
self.generic_visit(node)
if node.step is None or (isinstance(node.step, ast.Num) and
... | python | {
"resource": ""
} |
q233084 | OpenMP.init_not_msvc | train | def init_not_msvc(self):
""" Find OpenMP library and try to load if using ctype interface. """
# find_library() does not search automatically LD_LIBRARY_PATH
paths = os.environ.get('LD_LIBRARY_PATH', '').split(':')
for gomp in ('libgomp.so', 'libgomp.dylib'):
if cxx is None:
... | python | {
"resource": ""
} |
q233085 | Inlinable.visit_FunctionDef | train | def visit_FunctionDef(self, node):
""" Determine this function definition can be inlined. """
if (len(node.body) == 1 and
isinstance(node.body[0], (ast.Call, ast.Return))):
ids = self.gather(Identifiers, node.body[0])
# FIXME : It mark "not inlinable" def foo(foo)... | python | {
"resource": ""
} |
q233086 | pytype_to_deps_hpp | train | def pytype_to_deps_hpp(t):
"""python -> pythonic type hpp filename."""
if isinstance(t, List):
return {'list.hpp'}.union(pytype_to_deps_hpp(t.__args__[0]))
elif isinstance(t, Set):
return {'set.hpp'}.union(pytype_to_deps_hpp(t.__args__[0]))
elif isinstance(t, Dict):
tkey, tvalue ... | python | {
"resource": ""
} |
q233087 | pytype_to_deps | train | def pytype_to_deps(t):
""" python -> pythonic type header full path. """
res = set()
for hpp_dep in pytype_to_deps_hpp(t):
res.add(os.path.join('pythonic', 'types', hpp_dep))
res.add(os.path.join('pythonic', 'include', 'types', hpp_dep))
return res | python | {
"resource": ""
} |
q233088 | TypeDependencies.prepare | train | def prepare(self, node):
"""
Add nodes for each global declarations in the result graph.
No edges are added as there are no type builtin type dependencies.
"""
super(TypeDependencies, self).prepare(node)
for v in self.global_declarations.values():
self.result... | python | {
"resource": ""
} |
q233089 | TypeDependencies.visit_any_conditionnal | train | def visit_any_conditionnal(self, node1, node2):
"""
Set and restore the in_cond variable before visiting subnode.
Compute correct dependencies on a value as both branch are possible
path.
"""
true_naming = false_naming = None
try:
tmp = self.naming.... | python | {
"resource": ""
} |
q233090 | TypeDependencies.visit_FunctionDef | train | def visit_FunctionDef(self, node):
"""
Initialize variable for the current function to add edges from calls.
We compute variable to call dependencies and add edges when returns
are reach.
"""
# Ensure there are no nested functions.
assert self.current_function is... | python | {
"resource": ""
} |
q233091 | TypeDependencies.visit_Return | train | def visit_Return(self, node):
"""
Add edge from all possible callee to current function.
Gather all the function call that led to the creation of the
returned expression and add an edge to each of this function.
When visiting an expression, one returns a list of frozensets. Eac... | python | {
"resource": ""
} |
q233092 | TypeDependencies.visit_Assign | train | def visit_Assign(self, node):
"""
In case of assignment assign value depend on r-value type dependencies.
It is valid for subscript, `a[i] = foo()` means `a` type depend on
`foo` return type.
"""
value_deps = self.visit(node.value)
for target in node.targets:
... | python | {
"resource": ""
} |
q233093 | TypeDependencies.visit_AugAssign | train | def visit_AugAssign(self, node):
"""
AugAssigned value depend on r-value type dependencies.
It is valid for subscript, `a[i] += foo()` means `a` type depend on
`foo` return type and previous a types too.
"""
args = (self.naming[get_variable(node.target).id],
... | python | {
"resource": ""
} |
q233094 | TypeDependencies.visit_For | train | def visit_For(self, node):
"""
Handle iterator variable in for loops.
Iterate variable may be the correct one at the end of the loop.
"""
body = node.body
if node.target.id in self.naming:
body = [ast.Assign(targets=[node.target], value=node.iter)] + body
... | python | {
"resource": ""
} |
q233095 | TypeDependencies.visit_BoolOp | train | def visit_BoolOp(self, node):
""" Return type may come from any boolop operand. """
return sum((self.visit(value) for value in node.values), []) | python | {
"resource": ""
} |
q233096 | TypeDependencies.visit_BinOp | train | def visit_BinOp(self, node):
""" Return type depend from both operand of the binary operation. """
args = [self.visit(arg) for arg in (node.left, node.right)]
return list({frozenset.union(*x) for x in itertools.product(*args)}) | python | {
"resource": ""
} |
q233097 | TypeDependencies.visit_Call | train | def visit_Call(self, node):
"""
Function call depend on all function use in the call.
>> a = foo(bar(c) or foobar(d))
Return type depend on [foo, bar] or [foo, foobar]
"""
args = [self.visit(arg) for arg in node.args]
func = self.visit(node.func)
params ... | python | {
"resource": ""
} |
q233098 | TypeDependencies.visit_Name | train | def visit_Name(self, node):
"""
Return dependencies for given variable.
It have to be register first.
"""
if node.id in self.naming:
return self.naming[node.id]
elif node.id in self.global_declarations:
return [frozenset([self.global_declarations[... | python | {
"resource": ""
} |
q233099 | TypeDependencies.visit_List | train | def visit_List(self, node):
""" List construction depend on each elements type dependency. """
if node.elts:
return list(set(sum([self.visit(elt) for elt in node.elts], [])))
else:
return [frozenset()] | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.