_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 31
13.1k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q2000
|
FlatTerm._combined_wildcards_iter
|
train
|
def _combined_wildcards_iter(flatterm: Iterator[TermAtom]) -> Iterator[TermAtom]:
"""Combine consecutive wildcards in a flatterm into a single one."""
last_wildcard = None # type: Optional[Wildcard]
for term in flatterm:
if isinstance(term, Wildcard) and not isinstance(term, SymbolWildcard):
if last_wildcard is not None:
new_min_count = last_wildcard.min_count + term.min_count
new_fixed_size = last_wildcard.fixed_size and term.fixed_size
last_wildcard = Wildcard(new_min_count, new_fixed_size)
|
python
|
{
"resource": ""
}
|
q2001
|
_StateQueueItem.labels
|
train
|
def labels(self) -> Set[TransitionLabel]:
"""Return the set of transition labels to examine for this queue state.
This is the union of the transition label sets for both states.
However, if one of the states is fixed, it is excluded from this union and a wildcard transition is included
instead. Also, when already in a failed state (one of the states is ``None``), the :const:`OPERATION_END` is
also included.
"""
labels = set() # type: Set[TransitionLabel]
if self.state1 is not None and self.fixed != 1:
labels.update(self.state1.keys())
|
python
|
{
"resource": ""
}
|
q2002
|
DiscriminationNet.add
|
train
|
def add(self, pattern: Union[Pattern, FlatTerm], final_label: T=None) -> int:
"""Add a pattern to the discrimination net.
Args:
pattern:
The pattern which is added to the DiscriminationNet. If an expression is given, it will be converted to
a `FlatTerm` for internal processing. You can also pass a `FlatTerm` directly.
final_label:
A label that is returned if the pattern matches when using :meth:`match`. This will default to the
pattern itself.
Returns:
The index of the newly added pattern. This is used internally to later to get the pattern and its final
|
python
|
{
"resource": ""
}
|
q2003
|
DiscriminationNet._generate_net
|
train
|
def _generate_net(cls, flatterm: FlatTerm, final_label: T) -> _State[T]:
"""Generates a DFA matching the given pattern."""
# Capture the last sequence wildcard for every level of operation nesting on a stack
# Used to add backtracking edges in case the "match" fails later
last_wildcards = [None]
# Generate a fail state for every level of nesting to backtrack to a sequence wildcard in a parent Expression
# in case no match can be found
fail_states = [None]
operand_counts = [0]
root = state = _State()
states = {root.id: root}
for term in flatterm:
if operand_counts[-1] >= 0:
operand_counts[-1] += 1
# For wildcards, generate a chain of #min_count Wildcard edges
# If the wildcard is unbounded (fixed_size = False),
# add a wildcard self loop at the end
if isinstance(term, Wildcard):
# Generate a chain of #min_count Wildcard edges
for _ in range(term.min_count):
state = cls._create_child_state(state, Wildcard)
states[state.id] = state
# If it is a sequence wildcard, add a self loop
if not term.fixed_size:
state[Wildcard] = state
last_wildcards[-1] = state
operand_counts[-1] = -1
else:
state = cls._create_child_state(state, term)
states[state.id] = state
if is_operation(term):
|
python
|
{
"resource": ""
}
|
q2004
|
DiscriminationNet.match
|
train
|
def match(self, subject: Union[Expression, FlatTerm]) -> Iterator[Tuple[T, Substitution]]:
"""Match the given subject against all patterns in the net.
Args:
subject:
The subject that is matched. Must be constant.
Yields:
A tuple :code:`(final label, substitution)`, where the first component is the final label associated with
the pattern as given when using :meth:`add()` and the second one is the match substitution.
"""
for index in self._match(subject):
pattern, label = self._patterns[index]
|
python
|
{
"resource": ""
}
|
q2005
|
DiscriminationNet.is_match
|
train
|
def is_match(self, subject: Union[Expression, FlatTerm]) -> bool:
"""Check if the given subject matches any pattern in the net.
Args:
subject:
The subject that is matched. Must be constant.
Returns:
|
python
|
{
"resource": ""
}
|
q2006
|
DiscriminationNet.as_graph
|
train
|
def as_graph(self) -> Digraph: # pragma: no cover
"""Renders the discrimination net as graphviz digraph."""
if Digraph is None:
raise ImportError('The graphviz package is required to draw the graph.')
dot = Digraph()
nodes = set()
queue = [self._root]
while queue:
state = queue.pop(0)
if not state.payload:
dot.node('n{!s}'.format(state.id), '', {'shape': ('circle' if state else 'doublecircle')})
else:
dot.node('n{!s}'.format(state.id), '\n'.join(map(str, state.payload)), {'shape': 'box'})
for next_state in state.values():
if next_state.id not in nodes:
queue.append(next_state)
nodes.add(state.id)
nodes = set()
queue = [self._root]
while
|
python
|
{
"resource": ""
}
|
q2007
|
SequenceMatcher.add
|
train
|
def add(self, pattern: Pattern) -> int:
"""Add a pattern that will be recognized by the matcher.
Args:
pattern:
The pattern to add.
Returns:
An internal index for the pattern.
Raises:
ValueError:
If the pattern does not have the correct form.
TypeError:
If the pattern is not a non-commutative operation.
"""
inner = pattern.expression
if self.operation is None:
if not isinstance(inner, Operation) or isinstance(inner, CommutativeOperation):
|
python
|
{
"resource": ""
}
|
q2008
|
SequenceMatcher.match
|
train
|
def match(self, subject: Expression) -> Iterator[Tuple[Pattern, Substitution]]:
"""Match the given subject against all patterns in the sequence matcher.
Args:
subject:
The subject that is matched. Must be constant.
Yields:
A tuple :code:`(pattern, substitution)` for every matching pattern.
"""
if not isinstance(subject, self.operation):
return
subjects = list(op_iter(subject))
flatterms = [FlatTerm(o) for o in subjects]
for i in range(len(flatterms)):
flatterm = FlatTerm.merged(*flatterms[i:])
for index in self._net._match(flatterm, collect=True):
match_index = self._net._patterns[index][1]
pattern, first_name, last_name = self._patterns[match_index]
operand_count = op_len(pattern.expression) - 2
expr_operands = subjects[i:i + operand_count]
patt_operands = list(op_iter(pattern.expression))[1:-1]
substitution = Substitution()
if not all(itertools.starmap(substitution.extract_substitution, zip(expr_operands, patt_operands))):
continue
|
python
|
{
"resource": ""
}
|
q2009
|
_build_full_partition
|
train
|
def _build_full_partition(
optional_parts, sequence_var_partition: Sequence[int], subjects: Sequence[Expression], operation: Operation
) -> List[Sequence[Expression]]:
"""Distribute subject operands among pattern operands.
Given a partitoning for the variable part of the operands (i.e. a list of how many extra operands each sequence
variable gets assigned).
"""
i = 0
var_index = 0
opt_index = 0
result = []
for operand in op_iter(operation):
wrap_associative = False
if isinstance(operand, Wildcard):
count = operand.min_count if operand.optional is None else 0
if not operand.fixed_size or isinstance(operation, AssociativeOperation):
count += sequence_var_partition[var_index]
var_index += 1
wrap_associative = operand.fixed_size and operand.min_count
elif operand.optional is not None:
count = optional_parts[opt_index]
opt_index += 1
|
python
|
{
"resource": ""
}
|
q2010
|
_MatchIter.grouped
|
train
|
def grouped(self):
"""
Yield the matches grouped by their final state in the automaton, i.e. structurally identical patterns
only differing in constraints will be yielded together. Each group is yielded as a list of tuples consisting of
a pattern and a match substitution.
|
python
|
{
"resource": ""
}
|
q2011
|
ManyToOneMatcher.match
|
train
|
def match(self, subject: Expression) -> Iterator[Tuple[Expression, Substitution]]:
"""Match the subject against all the matcher's patterns.
Args:
subject: The subject to match.
|
python
|
{
"resource": ""
}
|
q2012
|
ManyToOneMatcher._collect_variable_renaming
|
train
|
def _collect_variable_renaming(
cls, expression: Expression, position: List[int]=None, variables: Dict[str, str]=None
) -> Dict[str, str]:
"""Return renaming for the variables in the expression.
The variable names are generated according to the position of the variable in the expression. The goal is to
rename variables in structurally identical patterns so that the automaton contains less redundant states.
"""
if position is None:
position = [0]
if variables is None:
variables = {}
if getattr(expression, 'variable_name', False):
if expression.variable_name not in variables:
variables[expression.variable_name] = cls._get_name_for_position(position, variables.values())
|
python
|
{
"resource": ""
}
|
q2013
|
ManyToOneReplacer.add
|
train
|
def add(self, rule: 'functions.ReplacementRule') -> None:
"""Add a new rule to the replacer.
Args:
rule:
|
python
|
{
"resource": ""
}
|
q2014
|
Expression.collect_variables
|
train
|
def collect_variables(self, variables: MultisetOfVariables) -> None:
"""Recursively adds all variables occuring in the expression to the given multiset.
This is used internally by `variables`. Needs to be overwritten by inheriting container expression classes.
This
|
python
|
{
"resource": ""
}
|
q2015
|
Operation.new
|
train
|
def new(
name: str,
arity: Arity,
class_name: str=None,
*,
associative: bool=False,
commutative: bool=False,
one_identity: bool=False,
infix: bool=False
) -> Type['Operation']:
"""Utility method to create a new operation type.
Example:
>>> Times = Operation.new('*', Arity.polyadic, 'Times', associative=True, commutative=True, one_identity=True)
>>> Times
Times['*', Arity(min_count=2, fixed_size=False), associative, commutative, one_identity]
>>> str(Times(Symbol('a'), Symbol('b')))
'*(a, b)'
Args:
name:
Name or symbol for the operator. Will be used as name for the new class if
`class_name` is not specified.
arity:
The arity of the operator as explained in the documentation of `Operation`.
class_name:
Name for the new operation class to be used instead of name. This argument
is required if `name` is not a valid python identifier.
Keyword Args:
associative:
|
python
|
{
"resource": ""
}
|
q2016
|
Wildcard.optional
|
train
|
def optional(name, default) -> 'Wildcard':
"""Create a `Wildcard` that matches a single argument with a default value.
If the wildcard does not match, the substitution will contain the
default value instead.
Args:
name:
The name for the wildcard.
default:
|
python
|
{
"resource": ""
}
|
q2017
|
Wildcard.symbol
|
train
|
def symbol(name: str=None, symbol_type: Type[Symbol]=Symbol) -> 'SymbolWildcard':
"""Create a `SymbolWildcard` that matches a single `Symbol` argument.
Args:
name:
Optional variable name for the wildcard.
symbol_type:
An optional subclass of `Symbol` to further limit which kind of symbols are
matched by the wildcard.
Returns:
A `SymbolWildcard` that matches the
|
python
|
{
"resource": ""
}
|
q2018
|
Client.request
|
train
|
def request(self, method, url_parts, headers=None, data=None):
""" Method for making requests to the Optimizely API
"""
if method in self.ALLOWED_REQUESTS:
# add request token header
headers = headers or {}
# test if Oauth token
if self.token_type == 'legacy':
headers.update(
{'Token': self.api_key,
'User-Agent': 'optimizely-client-python/0.1.1'})
elif self.token_type == 'oauth':
headers.update(
{'Authorization': 'Bearer ' + self.api_key,
'User-Agent': 'optimizely-client-python/0.1.1'})
else:
raise ValueError(
'{} is not a valid token type.'.format(self.token_type))
# make request and return parsed response
|
python
|
{
"resource": ""
}
|
q2019
|
Client.parse_response
|
train
|
def parse_response(resp):
""" Method to parse response from the Optimizely API and
return results as JSON. Errors are thrown for various
errors that the API can throw.
"""
if resp.status_code in [200, 201, 202]:
return resp.json()
elif resp.status_code == 204:
return None
elif resp.status_code == 400:
raise error.BadRequestError(resp.text)
elif resp.status_code == 401:
raise error.UnauthorizedError(resp.text)
elif resp.status_code == 403:
raise error.ForbiddenError(resp.text)
|
python
|
{
"resource": ""
}
|
q2020
|
_to_r
|
train
|
def _to_r(o, as_data=False, level=0):
"""Helper function to convert python data structures to R equivalents
TODO: a single model for transforming to r to handle
* function args
* lists as function args
"""
if o is None:
return "NA"
if isinstance(o, basestring):
return o
if hasattr(o, "r"):
# bridge to @property r on GGStatement(s)
|
python
|
{
"resource": ""
}
|
q2021
|
data_py
|
train
|
def data_py(o, *args, **kwargs):
"""converts python object into R Dataframe definition
converts following data structures:
row oriented list of dictionaries:
[ { 'x': 0, 'y': 1, ...}, ... ]
col oriented dictionary of lists
{ 'x': [0,1,2...], 'y': [...], ... }
@param o python object to convert
@param args argument list to pass to read.csv
@param kwargs keyword args to pass to read.csv
@return a tuple of the file containing the data and an
expression to define data.frame object and set it to variable "data"
data = read.csv(tmpfile, *args, **kwargs)
"""
if isinstance(o, basestring):
fname = o
else:
|
python
|
{
"resource": ""
}
|
q2022
|
ggsave
|
train
|
def ggsave(name, plot, data=None, *args, **kwargs):
"""Save a GGStatements object to destination name
@param name output file name. if None, don't run R command
@param kwargs keyword args to pass to ggsave. The following are special
keywords for the python save method
data: a python data object (list, dict, DataFrame) used to populate
the `data` variable in R
libs: list of library names to load in addition to ggplot2
prefix: string containing R code to run before any ggplot commands (including data loading)
postfix: string containing R code to run after data is loaded (e.g., if you want to rename variable names)
quiet: if Truthy, don't print out R program string
"""
# constants
kwdefaults = {
'width': 10,
'height': 8,
'scale': 1
}
keys_to_rm = ["prefix", "quiet", "postfix", 'libs']
varname = 'p'
# process arguments
prefix = kwargs.get('prefix', '')
postfix = kwargs.get('postfix', '')
libs = kwargs.get('libs', [])
libs = '\n'.join(["library(%s)" % lib for lib in libs])
quiet = kwargs.get("quiet", False)
kwargs = {k: v for k, v in kwargs.iteritems()
if v is not None and k not in keys_to_rm}
kwdefaults.update(kwargs)
kwargs = kwdefaults
# figure out how to load data in the R environment
if data is None: data = plot.data
if data is None:
# Don't load anything, the data source is
|
python
|
{
"resource": ""
}
|
q2023
|
gg_ipython
|
train
|
def gg_ipython(plot, data, width=IPYTHON_IMAGE_SIZE, height=None,
*args, **kwargs):
"""Render pygg in an IPython notebook
Allows one to say things like:
import pygg
p = pygg.ggplot('diamonds', pygg.aes(x='carat', y='price', color='clarity'))
p += pygg.geom_point(alpha=0.5, size = 2)
p += pygg.scale_x_log10(limits=[1, 2])
pygg.gg_ipython(p, data=None, quiet=True)
directly in an IPython notebook and see the resulting ggplot2 image
displayed inline. This function is print a warning if the IPython library
cannot be imported. The ggplot2 image is rendered as a PNG and not
as a vectorized graphics object right now.
Note that by default gg_ipython sets the output height and width to
|
python
|
{
"resource": ""
}
|
q2024
|
size_r_img_inches
|
train
|
def size_r_img_inches(width, height):
"""Compute the width and height for an R image for display in IPython
Neight width nor height can be null but should be integer pixel values > 0.
Returns a tuple of (width, height) that
|
python
|
{
"resource": ""
}
|
q2025
|
execute_r
|
train
|
def execute_r(prog, quiet):
"""Run the R code prog an R subprocess
@raises ValueError if the subprocess exits with non-zero status
"""
FNULL = open(os.devnull, 'w') if quiet else None
try:
input_proc = subprocess.Popen(["echo", prog], stdout=subprocess.PIPE)
status = subprocess.call("R --no-save --quiet",
|
python
|
{
"resource": ""
}
|
q2026
|
GGStatement.r
|
train
|
def r(self):
"""Convert this GGStatement into its R equivalent expression"""
r_args = [_to_r(self.args), _to_r(self.kwargs)]
# remove empty strings from the call args
|
python
|
{
"resource": ""
}
|
q2027
|
encode
|
train
|
def encode(precision, with_z):
"""Given GeoJSON on stdin, writes a geobuf file to stdout."""
logger = logging.getLogger('geobuf')
stdin = click.get_text_stream('stdin')
sink = click.get_binary_stream('stdout')
|
python
|
{
"resource": ""
}
|
q2028
|
decode
|
train
|
def decode():
"""Given a Geobuf byte string on stdin, write a GeoJSON feature
collection to stdout."""
logger = logging.getLogger('geobuf')
stdin = click.get_binary_stream('stdin')
sink = click.get_text_stream('stdout')
try:
pbf = stdin.read()
data = geobuf.decode(pbf)
|
python
|
{
"resource": ""
}
|
q2029
|
encode_int
|
train
|
def encode_int(code, bits_per_char=6):
"""Encode int into a string preserving order
It is using 2, 4 or 6 bits per coding character (default 6).
Parameters:
code: int Positive integer.
bits_per_char: int The number of bits per coding character.
|
python
|
{
"resource": ""
}
|
q2030
|
_coord2int
|
train
|
def _coord2int(lng, lat, dim):
"""Convert lon, lat values into a dim x dim-grid coordinate system.
Parameters:
lng: float Longitude value of coordinate (-180.0, 180.0); corresponds to X axis
lat: float Latitude value of coordinate (-90.0, 90.0); corresponds to Y axis
dim: int Number of coding points each x, y value can take.
Corresponds to 2^level of the hilbert curve.
Returns:
Tuple[int, int]:
Lower left corner of corresponding dim x dim-grid box
|
python
|
{
"resource": ""
}
|
q2031
|
_int2coord
|
train
|
def _int2coord(x, y, dim):
"""Convert x, y values in dim x dim-grid coordinate system into lng, lat values.
Parameters:
x: int x value of point [0, dim); corresponds to longitude
y: int y value of point [0, dim); corresponds to latitude
dim: int Number of coding points each x, y value can take.
Corresponds to 2^level of the hilbert curve.
Returns:
Tuple[float, float]: (lng, lat)
lng longitude value of coordinate
|
python
|
{
"resource": ""
}
|
q2032
|
_rotate
|
train
|
def _rotate(n, x, y, rx, ry):
"""Rotate and flip a quadrant appropriately
Based on the implementation here:
https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503
"""
if ry == 0:
|
python
|
{
"resource": ""
}
|
q2033
|
neighbours
|
train
|
def neighbours(code, bits_per_char=6):
"""Get the neighbouring geohashes for `code`.
Look for the north, north-east, east, south-east, south, south-west, west,
north-west neighbours. If you are at the east/west edge of the grid
(lng ∈ (-180, 180)), then it wraps around the globe and gets the corresponding
neighbor.
Parameters:
code: str The geohash at the center.
bits_per_char: int The number of bits per coding character.
Returns:
dict: geohashes in the neighborhood of `code`. Possible keys are 'north',
'north-east', 'east', 'south-east', 'south', 'south-west',
'west', 'north-west'. If the input code covers the north pole, then
keys 'north', 'north-east', and 'north-west' are not present, and if
the input code covers the south pole then keys 'south', 'south-west',
and 'south-east' are not present.
"""
lng, lat, lng_err, lat_err = decode_exactly(code, bits_per_char)
precision = len(code)
north = lat + 2 * lat_err
south = lat - 2 * lat_err
east = lng + 2 * lng_err
if east > 180:
east -= 360
west = lng - 2 * lng_err
if west < -180:
west += 360
neighbours_dict = {
'east': encode(east, lat,
|
python
|
{
"resource": ""
}
|
q2034
|
isSignatureValid
|
train
|
def isSignatureValid(expected, received):
"""
Verifies that the received signature matches the expected value
"""
if expected:
if not received or expected != received:
|
python
|
{
"resource": ""
}
|
q2035
|
RemoteDBusObject.notifyOnDisconnect
|
train
|
def notifyOnDisconnect(self, callback):
"""
Registers a callback that will be called when the DBus connection
underlying the remote object is lost
@type callback: Callable object accepting a L{RemoteDBusObject} and
L{twisted.python.failure.Failure}
@param callback: Function that will be called when the connection to
the DBus session is lost. Arguments are the
L{RemoteDBusObject} instance and reason for
|
python
|
{
"resource": ""
}
|
q2036
|
RemoteDBusObject.notifyOnSignal
|
train
|
def notifyOnSignal(self, signalName, callback, interface=None):
"""
Informs the DBus daemon of the process's interest in the specified
signal and registers the callback function to be called when the
signal arrives. Multiple callbacks may be registered.
@type signalName: C{string}
@param signalName: Name of the signal to register the callback for
@type callback: Callable object
@param callback: Callback to be called on signal arrival. The callback
will be passed signals arguments as positional function arguments.
@type interface: C{string}
@param interface: Optional DBus interface emitting the signal. This is
only needed if more than one interface shares a signal with the
same name
@rtype: L{twisted.internet.defer.Deferred}
@returns: a Deferred to an integer rule_id that may be passed to
|
python
|
{
"resource": ""
}
|
q2037
|
RemoteDBusObject.cancelSignalNotification
|
train
|
def cancelSignalNotification(self, rule_id):
"""
Cancels a callback previously registered with notifyOnSignal
"""
if
|
python
|
{
"resource": ""
}
|
q2038
|
RemoteDBusObject.callRemote
|
train
|
def callRemote(self, methodName, *args, **kwargs):
"""
Calls the remote method and returns a Deferred instance to the result.
DBus does not support passing keyword arguments over the wire. The
keyword arguments accepted by this method alter the behavior of the
remote call as described in the kwargs prameter description.
@type methodName: C{string}
@param methodName: Name of the method to call
@param args: Positional arguments to be passed to the remote method
@param kwargs: Three keyword parameters may be passed to alter the
behavior of the remote method call. If \"expectReply=False\" is
supplied, the returned Deferred will be immediately called back
with the value None. If \"autoStart=False\" is supplied the DBus
daemon will not attempt to auto-start a service to fulfill the call
if the service is not yet running (defaults to True). If
\"timeout=VALUE\" is supplied, the returned Deferred will be
errbacked with a L{error.TimeOut} instance if the remote call does
not return before the timeout elapses. If \"interface\" is
specified, the remote call use the method of the named interface.
@rtype: L{twisted.internet.defer.Deferred}
@returns: a Deferred to the result of the remote call
"""
expectReply = kwargs.get('expectReply', True)
autoStart = kwargs.get('autoStart', True)
timeout = kwargs.get('timeout', None)
|
python
|
{
"resource": ""
}
|
q2039
|
DBusObjectHandler.connectionLost
|
train
|
def connectionLost(self, reason):
"""
Called by the DBus Connection object when the connection is lost.
@type reason: L{twistd.python.failure.Failure}
@param reason: The value passed to the associated connection's
|
python
|
{
"resource": ""
}
|
q2040
|
DBusObjectHandler.exportObject
|
train
|
def exportObject(self, dbusObject):
"""
Makes the specified object available over DBus
@type dbusObject: an object implementing the L{IDBusObject} interface
@param dbusObject: The object to export over DBus
"""
o = IDBusObject(dbusObject)
self.exports[o.getObjectPath()] = o
|
python
|
{
"resource": ""
}
|
q2041
|
DBusObjectHandler.getManagedObjects
|
train
|
def getManagedObjects(self, objectPath):
"""
Returns a Python dictionary containing the reply content for
org.freedesktop.DBus.ObjectManager.GetManagedObjects
"""
d = {}
for p in sorted(self.exports.keys()):
if not p.startswith(objectPath) or p == objectPath:
|
python
|
{
"resource": ""
}
|
q2042
|
DBusObjectHandler._send_err
|
train
|
def _send_err(self, msg, errName, errMsg):
"""
Helper method for sending error messages
"""
r = message.ErrorMessage(
errName,
msg.serial,
|
python
|
{
"resource": ""
}
|
q2043
|
DBusClientConnection._cbGotHello
|
train
|
def _cbGotHello(self, busName):
"""
Called in reply to the initial Hello remote method invocation
|
python
|
{
"resource": ""
}
|
q2044
|
DBusClientConnection.connectionLost
|
train
|
def connectionLost(self, reason):
"""
Called when the transport loses connection to the bus
"""
if self.busName is None:
return
for cb in self._dcCallbacks:
cb(self, reason)
for d, timeout in self._pendingCalls.values():
|
python
|
{
"resource": ""
}
|
q2045
|
DBusClientConnection.delMatch
|
train
|
def delMatch(self, rule_id):
"""
Removes a message matching rule previously registered with addMatch
"""
rule = self.match_rules[rule_id]
d = self.callRemote(
'/org/freedesktop/DBus',
|
python
|
{
"resource": ""
}
|
q2046
|
DBusClientConnection.addMatch
|
train
|
def addMatch(self, callback, mtype=None, sender=None, interface=None,
member=None, path=None, path_namespace=None, destination=None,
arg=None, arg_path=None, arg0namespace=None):
"""
Creates a message matching rule, associates it with the specified
callback function, and sends the match rule to the DBus daemon.
The arguments to this function are exactly follow the DBus
specification. Refer to the \"Message Bus Message Routing\" section of
the DBus specification for details.
@rtype: C{int}
@returns: a L{Deferred} to an integer id that may be used to unregister
the match rule
"""
l = []
def add(k, v):
if v is not None:
l.append("%s='%s'" % (k, v))
add('type', mtype)
add('sender', sender)
add('interface', interface)
add('member', member)
add('path', path)
add('path_namespace', path_namespace)
add('destination', destination)
if arg:
for idx, v in arg:
add('arg%d' % (idx,), v)
if arg_path:
for idx, v in
|
python
|
{
"resource": ""
}
|
q2047
|
DBusClientConnection.getNameOwner
|
train
|
def getNameOwner(self, busName):
"""
Calls org.freedesktop.DBus.GetNameOwner
@rtype: L{twisted.internet.defer.Deferred}
@returns: a Deferred to the unique connection name owning the bus name
"""
d = self.callRemote(
|
python
|
{
"resource": ""
}
|
q2048
|
DBusClientConnection.requestBusName
|
train
|
def requestBusName(self, newName,
allowReplacement=False,
replaceExisting=False,
doNotQueue=True,
errbackUnlessAcquired=True):
"""
Calls org.freedesktop.DBus.RequestName to request that the specified
bus name be associated with the connection.
@type newName: C{string}
@param newName: Bus name to acquire
@type allowReplacement: C{bool}
@param allowReplacement: If True (defaults to False) and another
application later requests this same name, the new requester will
be given the name and this connection will lose ownership.
@type replaceExisting: C{bool}
@param replaceExisting: If True (defaults to False) and another
application owns the name but specified allowReplacement at the
time of the name acquisition, this connection will assume ownership
of the bus name.
@type doNotQueue: C{bool}
@param doNotQueue: If True (defaults to True) the name request will
fail if the name is currently in use. If False, the request will
cause this connection to be queued for ownership of the requested
name
@type errbackUnlessAcquired: C{bool}
@param errbackUnlessAcquired: If True (defaults to True) an
|
python
|
{
"resource": ""
}
|
q2049
|
DBusClientConnection.introspectRemoteObject
|
train
|
def introspectRemoteObject(self, busName, objectPath,
replaceKnownInterfaces=False):
"""
Calls org.freedesktop.DBus.Introspectable.Introspect
@type busName: C{string}
@param busName: Name of the bus containing the object
@type objectPath: C{string}
@param objectPath: Object Path to introspect
@type replaceKnownInterfaces: C{bool}
@param replaceKnownInterfaces: If True (defaults to False), the content
of the introspected XML will override any pre-existing definitions
|
python
|
{
"resource": ""
}
|
q2050
|
DBusClientConnection._cbCvtReply
|
train
|
def _cbCvtReply(self, msg, returnSignature):
"""
Converts a remote method call reply message into an appropriate
callback
value.
"""
if msg is None:
return None
if returnSignature != _NO_CHECK_RETURN:
if not returnSignature:
if msg.signature:
raise error.RemoteError(
'Unexpected return value signature')
else:
if not msg.signature or msg.signature != returnSignature:
msg = 'Expected "%s". Received "%s"' % (
str(returnSignature), str(msg.signature))
raise error.RemoteError(
'Unexpected return value signature: %s' %
(msg,))
if msg.body
|
python
|
{
"resource": ""
}
|
q2051
|
DBusClientConnection.callRemote
|
train
|
def callRemote(self, objectPath, methodName,
interface=None,
destination=None,
signature=None,
body=None,
expectReply=True,
autoStart=True,
timeout=None,
returnSignature=_NO_CHECK_RETURN):
"""
Calls a method on a remote DBus object and returns a deferred to the
result.
@type objectPath: C{string}
@param objectPath: Path of the remote object
@type methodName: C{string}
@param methodName: Name of the method to call
@type interface: None or C{string}
@param interface: If specified, this specifies the interface containing
the desired method
@type destination: None or C{string}
@param destination: If specified, this specifies the bus name
containing the remote object
@type signature: None or C{string}
@param signature: If specified, this specifies the DBus signature of
the body of the DBus MethodCall message. This string must be a
valid Signature string as defined by the DBus specification. If
arguments are supplied to the method call, this parameter must be
provided.
@type body: C{list}
@param body: A C{list} of Python objects to encode. The list content
must match the content of the signature parameter
@type expectReply: C{bool}
@param expectReply: If True (defaults to True) the returned deferred
will be called back with the eventual result of the remote call. If
False, the deferred will be immediately called back with None.
@type autoStart: C{bool}
@param autoStart: If True (defaults to True) DBus will attempt to
automatically start a service to handle the method call if a
service matching the target object is registered but not yet
started.
@type timeout: None or C{float}
@param timeout: If specified and the remote call does not return a
value before the timeout expires, the returned Deferred will be
errbacked with a L{error.TimeOut} instance.
@type returnSignature: C{string}
@param returnSignature:
|
python
|
{
"resource": ""
}
|
q2052
|
DBusClientConnection._onMethodTimeout
|
train
|
def _onMethodTimeout(self, serial, d):
"""
Called when a remote method invocation timeout occurs
"""
|
python
|
{
"resource": ""
}
|
q2053
|
DBusClientConnection.methodReturnReceived
|
train
|
def methodReturnReceived(self, mret):
"""
Called when a method return message is received
"""
d, timeout = self._pendingCalls.get(mret.reply_serial, (None, None))
if timeout:
|
python
|
{
"resource": ""
}
|
q2054
|
DBusClientConnection.errorReceived
|
train
|
def errorReceived(self, merr):
"""
Called when an error message is received
"""
d, timeout = self._pendingCalls.get(merr.reply_serial, (None, None))
if timeout:
timeout.cancel()
if d:
del self._pendingCalls[merr.reply_serial]
e = error.RemoteError(merr.error_name)
e.message = ''
e.values = []
if
|
python
|
{
"resource": ""
}
|
q2055
|
getDBusEnvEndpoints
|
train
|
def getDBusEnvEndpoints(reactor, client=True):
"""
Creates endpoints from the DBUS_SESSION_BUS_ADDRESS environment variable
@rtype: C{list} of L{twisted.internet.interfaces.IStreamServerEndpoint}
@returns: A list of endpoint instances
"""
|
python
|
{
"resource": ""
}
|
q2056
|
getDBusEndpoints
|
train
|
def getDBusEndpoints(reactor, busAddress, client=True):
"""
Creates DBus endpoints.
@param busAddress: 'session', 'system', or a valid bus address as defined
by the DBus specification. If 'session' (the default) or 'system' is
supplied, the contents of the DBUS_SESSION_BUS_ADDRESS or
DBUS_SYSTEM_BUS_ADDRESS environment variables will be used for the bus
address, respectively. If DBUS_SYSTEM_BUS_ADDRESS is not set, the
well-known address unix:path=/var/run/dbus/system_bus_socket will be
used.
@type busAddress: C{string}
@rtype: C{list} of L{twisted.internet.interfaces.IStreamServerEndpoint}
@returns: A list of endpoint instances
"""
if busAddress == 'session':
addrString = os.environ.get('DBUS_SESSION_BUS_ADDRESS', None)
if addrString is None:
raise Exception('DBus Session environment variable not set')
elif busAddress == 'system':
addrString = os.environ.get(
'DBUS_SYSTEM_BUS_ADDRESS',
'unix:path=/var/run/dbus/system_bus_socket',
)
else:
addrString = busAddress
# XXX Add documentation about extra key=value parameters in address string
# such as nonce-tcp vs tcp which use same endpoint class
epl = []
for ep_addr in addrString.split(';'):
d = {}
kind = None
ep = None
for c in ep_addr.split(','):
if c.startswith('unix:'):
kind = 'unix'
c = c[5:]
elif c.startswith('tcp:'):
kind = 'tcp'
c = c[4:]
elif c.startswith('nonce-tcp:'):
kind = 'tcp'
c = c[10:]
|
python
|
{
"resource": ""
}
|
q2057
|
FDObject.dbus_lenFD
|
train
|
def dbus_lenFD(self, fd):
"""
Returns the byte count after reading till EOF.
|
python
|
{
"resource": ""
}
|
q2058
|
FDObject.dbus_readBytesFD
|
train
|
def dbus_readBytesFD(self, fd, byte_count):
"""
Reads byte_count bytes from fd and returns them.
|
python
|
{
"resource": ""
}
|
q2059
|
FDObject.dbus_readBytesTwoFDs
|
train
|
def dbus_readBytesTwoFDs(self, fd1, fd2, byte_count):
"""
Reads byte_count from fd1 and fd2. Returns concatenation.
"""
result = bytearray()
for fd in (fd1, fd2):
|
python
|
{
"resource": ""
}
|
q2060
|
generateIntrospectionXML
|
train
|
def generateIntrospectionXML(objectPath, exportedObjects):
"""
Generates the introspection XML for an object path or partial object path
that matches exported objects.
This allows for browsing the exported objects with tools such as d-feet.
@rtype: C{string}
"""
l = [_dtd_decl]
l.append('<node name="%s">' % (objectPath,))
obj = exportedObjects.get(objectPath, None)
if obj is not None:
for i in obj.getInterfaces():
l.append(i.introspectionXml)
l.append(_intro)
# make sure objectPath ends with '/' to only get partial matches based on
# the full path, not a part of a subpath
if not objectPath.endswith('/'):
objectPath += '/'
|
python
|
{
"resource": ""
}
|
q2061
|
Bus.clientConnected
|
train
|
def clientConnected(self, proto):
"""
Called when a client connects to the bus. This method assigns the
|
python
|
{
"resource": ""
}
|
q2062
|
Bus.clientDisconnected
|
train
|
def clientDisconnected(self, proto):
"""
Called when a client disconnects from the bus
"""
for rule_id in proto.matchRules:
self.router.delMatch(rule_id)
for busName in proto.busNames.keys():
|
python
|
{
"resource": ""
}
|
q2063
|
Bus.sendMessage
|
train
|
def sendMessage(self, msg):
"""
Sends the supplied message to the correct destination. The
@type msg: L{message.DBusMessage}
@param msg: The 'destination' field of the message must be set for
method calls and returns
"""
if msg._messageType in (1, 2):
assert msg.destination, 'Failed to specify a message destination'
if msg.destination is not None:
|
python
|
{
"resource": ""
}
|
q2064
|
Bus.sendSignal
|
train
|
def sendSignal(self, p, member, signature=None, body=None,
path='/org/freedesktop/DBus',
interface='org.freedesktop.DBus'):
"""
Sends a signal to a specific connection
@type p: L{BusProtocol}
@param p: L{BusProtocol} instance to send a signal to
@type member: C{string}
@param member: Name of the signal to send
@type path: C{string}
@param path: Path of the object emitting the signal. Defaults to
'org/freedesktop/DBus'
@type interface: C{string}
@param interface: If specified, this specifies the interface containing
the desired method. Defaults to 'org.freedesktop.DBus'
@type body: None or C{list}
@param body: If supplied, this is a list of signal arguments. The
contents
|
python
|
{
"resource": ""
}
|
q2065
|
Bus.broadcastSignal
|
train
|
def broadcastSignal(self, member, signature=None, body=None,
path='/org/freedesktop/DBus',
interface='org.freedesktop.DBus'):
"""
Sends a signal to all connections with registered interest
@type member: C{string}
@param member: Name of the signal to send
@type path: C{string}
@param path: Path of the object emitting the signal. Defaults to
'org/freedesktop/DBus'
@type interface: C{string}
@param interface: If specified, this specifies the interface containing
the desired method. Defaults to 'org.freedesktop.DBus'
@type body: None or C{list}
@param body: If supplied, this is a list of signal arguments. The
contents of the list must match
|
python
|
{
"resource": ""
}
|
q2066
|
OPE.encrypt
|
train
|
def encrypt(self, plaintext):
"""Encrypt the given plaintext value"""
if not isinstance(plaintext, int):
raise ValueError('Plaintext must be an integer value')
if not self.in_range.contains(plaintext):
|
python
|
{
"resource": ""
}
|
q2067
|
OPE.decrypt
|
train
|
def decrypt(self, ciphertext):
"""Decrypt the given ciphertext value"""
if not isinstance(ciphertext, int):
raise ValueError('Ciphertext must be an integer value')
if not self.out_range.contains(ciphertext):
|
python
|
{
"resource": ""
}
|
q2068
|
OPE.tape_gen
|
train
|
def tape_gen(self, data):
"""Return a bit string, generated from the given data string"""
# FIXME
data = str(data).encode()
# Derive a key from data
hmac_obj = hmac.HMAC(self.key, digestmod=hashlib.sha256)
hmac_obj.update(data)
assert hmac_obj.digest_size == 32
digest = hmac_obj.digest()
# Use AES in the CTR mode to generate a pseudo-random bit string
aes_algo = algorithms.AES(digest)
|
python
|
{
"resource": ""
}
|
q2069
|
OPE.generate_key
|
train
|
def generate_key(block_size=32):
"""Generate random key for ope cipher.
Parameters
----------
block_size : int, optional
Length of random bytes.
Returns
|
python
|
{
"resource": ""
}
|
q2070
|
byte_to_bitstring
|
train
|
def byte_to_bitstring(byte):
"""Convert one byte to a list of bits"""
|
python
|
{
"resource": ""
}
|
q2071
|
str_to_bitstring
|
train
|
def str_to_bitstring(data):
"""Convert a string to a list of bits"""
assert isinstance(data, bytes), "Data must be an instance of bytes"
byte_list = data_to_byte_list(data)
bit_list =
|
python
|
{
"resource": ""
}
|
q2072
|
sample_hgd
|
train
|
def sample_hgd(in_range, out_range, nsample, seed_coins):
"""Get a sample from the hypergeometric distribution, using the provided bit list as a source of randomness"""
in_size = in_range.size()
out_size = out_range.size()
assert in_size > 0 and out_size > 0
assert in_size <= out_size
assert out_range.contains(nsample)
|
python
|
{
"resource": ""
}
|
q2073
|
sample_uniform
|
train
|
def sample_uniform(in_range, seed_coins):
"""Uniformly select a number from the range using the bit list as a source of randomness"""
if isinstance(seed_coins, list):
seed_coins.append(None)
seed_coins = iter(seed_coins)
cur_range = in_range.copy()
assert cur_range.size() != 0
while cur_range.size() > 1:
mid = (cur_range.start + cur_range.end) // 2
bit = next(seed_coins)
if bit == 0:
cur_range.end = mid
elif
|
python
|
{
"resource": ""
}
|
q2074
|
__downloadPage
|
train
|
def __downloadPage(factory, *args, **kwargs):
"""Start a HTTP download, returning a HTTPDownloader object"""
# The Twisted API is weird:
# 1) web.client.downloadPage() doesn't give us the HTTP headers
# 2) there is no method that simply accepts a URL and gives you back
# a HTTPDownloader object
#TODO: convert getPage() usage to something similar, too
downloader = factory(*args, **kwargs)
if downloader.scheme == 'https':
|
python
|
{
"resource": ""
}
|
q2075
|
Twitter.__clientDefer
|
train
|
def __clientDefer(self, c):
"""Return a deferred for a HTTP client, after handling incoming headers"""
def handle_headers(r):
|
python
|
{
"resource": ""
}
|
q2076
|
Twitter.verify_credentials
|
train
|
def verify_credentials(self, delegate=None):
"Verify a user's credentials."
parser = txml.Users(delegate)
|
python
|
{
"resource": ""
}
|
q2077
|
Twitter.update
|
train
|
def update(self, status, source=None, params={}):
"Update your status. Returns the ID of the new post."
params = params.copy()
params['status'] = status
if source:
params['source'] = source
|
python
|
{
"resource": ""
}
|
q2078
|
Twitter.retweet
|
train
|
def retweet(self, id, delegate):
"""Retweet a post
Returns the retweet status info back to the given delegate
"""
|
python
|
{
"resource": ""
}
|
q2079
|
Twitter.user_timeline
|
train
|
def user_timeline(self, delegate, user=None, params={}, extra_args=None):
"""Get the most recent updates for a user.
If no user is specified, the statuses for the authenticating user are
returned.
See search for example of how results are returned."""
|
python
|
{
"resource": ""
}
|
q2080
|
Twitter.public_timeline
|
train
|
def public_timeline(self, delegate, params={}, extra_args=None):
"Get the most recent public timeline."
|
python
|
{
"resource": ""
}
|
q2081
|
Twitter.direct_messages
|
train
|
def direct_messages(self, delegate, params={}, extra_args=None):
"""Get direct messages for the authenticating user.
Search results are returned one message at a time a DirectMessage
|
python
|
{
"resource": ""
}
|
q2082
|
Twitter.send_direct_message
|
train
|
def send_direct_message(self, text, user=None, delegate=None, screen_name=None, user_id=None, params={}):
"""Send a direct message
"""
params = params.copy()
if user is not None:
params['user'] = user
if user_id is not None:
params['user_id'] = user_id
|
python
|
{
"resource": ""
}
|
q2083
|
Twitter.replies
|
train
|
def replies(self, delegate, params={}, extra_args=None):
"""Get the most recent replies for the authenticating user.
See search for example of how results are returned."""
|
python
|
{
"resource": ""
}
|
q2084
|
Twitter.follow_user
|
train
|
def follow_user(self, user, delegate):
"""Follow the given user.
Returns the user info back to the given delegate
"""
|
python
|
{
"resource": ""
}
|
q2085
|
Twitter.unfollow_user
|
train
|
def unfollow_user(self, user, delegate):
"""Unfollow the given user.
Returns the user info back to the given delegate
"""
|
python
|
{
"resource": ""
}
|
q2086
|
Twitter.list_friends
|
train
|
def list_friends(self, delegate, user=None, params={}, extra_args=None, page_delegate=None):
"""Get the list of friends for a user.
Calls the delegate with each user object found."""
if user:
url = '/statuses/friends/' + user + '.xml'
|
python
|
{
"resource": ""
}
|
q2087
|
Twitter.show_user
|
train
|
def show_user(self, user):
"""Get the info for a specific user.
Returns a delegate that will receive the user in a callback."""
|
python
|
{
"resource": ""
}
|
q2088
|
Twitter.search
|
train
|
def search(self, query, delegate, args=None, extra_args=None):
"""Perform a search query.
Results are given one at a time to the delegate. An example delegate
may look like this:
|
python
|
{
"resource": ""
}
|
q2089
|
TwitterMonitor.startService
|
train
|
def startService(self):
"""
Start the service.
This causes a transition to the C{'idle'} state, and then calls
L{connect} to attempt
|
python
|
{
"resource": ""
}
|
q2090
|
TwitterMonitor.connect
|
train
|
def connect(self, forceReconnect=False):
"""
Check current conditions and initiate connection if possible.
This is called to check preconditions for starting a new connection,
and initating the connection itself.
If the service is not running, this will do nothing.
@param forceReconnect: Drop an existing connection to reconnnect.
@type forceReconnect: C{False}
@raises L{ConnectError}: When a connection (attempt) is already in
progress, unless C{forceReconnect} is set.
@raises L{NoConsumerError}: When there is no consumer for incoming
tweets. No further connection attempts will be made, unless L{connect}
is called again.
"""
if self._state == 'stopped':
raise Error("This service is not running. Not connecting.")
if self._state == 'connected':
if forceReconnect:
self._toState('disconnecting')
return True
else:
raise ConnectError("Already connected.")
elif self._state == 'aborting':
raise ConnectError("Aborting connection in progress.")
|
python
|
{
"resource": ""
}
|
q2091
|
TwitterMonitor.makeConnection
|
train
|
def makeConnection(self, protocol):
"""
Called when the connection has been established.
This method is called when an HTTP 200 response has been received,
with the protocol that decodes the individual Twitter stream elements.
That protocol will call the consumer for all Twitter entries received.
The protocol, stored in L{protocol}, has a deferred that fires when
the connection is closed, causing a transition to the
C{'disconnected'} state.
@param protocol: The Twitter stream protocol.
@type protocol: L{TwitterStream}
"""
self._errorState = None
def cb(result):
|
python
|
{
"resource": ""
}
|
q2092
|
TwitterMonitor._reconnect
|
train
|
def _reconnect(self, errorState):
"""
Attempt to reconnect.
If the current back-off delay is 0, L{connect} is called. Otherwise,
it will cause a transition to the C{'waiting'} state, ultimately
causing a call to L{connect} when the delay expires.
"""
def connect():
if self.noisy:
log.msg("Reconnecting now.")
self.connect()
backOff = self.backOffs[errorState]
if self._errorState != errorState or self._delay is None:
self._errorState = errorState
self._delay = backOff['initial']
|
python
|
{
"resource": ""
}
|
q2093
|
TwitterMonitor._toState
|
train
|
def _toState(self, state, *args, **kwargs):
"""
Transition to the next state.
@param state: Name of the next state.
"""
try:
method
|
python
|
{
"resource": ""
}
|
q2094
|
TwitterMonitor._state_stopped
|
train
|
def _state_stopped(self):
"""
The service is not running.
This is the initial state, and the state after L{stopService} was
called. To get out of this state, call L{startService}. If there is a
current connection, we disconnect.
"""
|
python
|
{
"resource": ""
}
|
q2095
|
TwitterMonitor._state_connecting
|
train
|
def _state_connecting(self):
"""
A connection is being started.
A succesful attempt results in the state C{'connected'} when the
first response from Twitter has been received. Transitioning
to the state C{'aborting'} will cause an immediate disconnect instead,
by transitioning to C{'disconnecting'}.
Errors will cause a transition to the C{'error'} state.
"""
def responseReceived(protocol):
self.makeConnection(protocol)
if self._state == 'aborting':
self._toState('disconnecting')
else:
|
python
|
{
"resource": ""
}
|
q2096
|
TwitterMonitor._state_error
|
train
|
def _state_error(self, reason):
"""
The connection attempt resulted in an error.
Attempt a reconnect with a back-off algorithm.
"""
log.err(reason)
def matchException(failure):
for errorState, backOff in self.backOffs.iteritems():
if 'errorTypes' not in backOff:
continue
if
|
python
|
{
"resource": ""
}
|
q2097
|
LengthDelimitedStream.lineReceived
|
train
|
def lineReceived(self, line):
"""
Called when a line is received.
We expect a length in bytes or an empty line for keep-alive. If
we got a length, switch to raw mode to receive that amount of bytes.
"""
if line and line.isdigit():
|
python
|
{
"resource": ""
}
|
q2098
|
LengthDelimitedStream.rawDataReceived
|
train
|
def rawDataReceived(self, data):
"""
Called when raw data is received.
Fill the raw buffer C{_rawBuffer} until we have received at least
C{_expectedLength} bytes. Call C{datagramReceived} with the received
byte string of the expected size. Then switch back to line mode with
the remainder of the buffer.
|
python
|
{
"resource": ""
}
|
q2099
|
TwitterObject.fromDict
|
train
|
def fromDict(cls, data):
"""
Fill this objects attributes from a dict for known properties.
"""
obj = cls()
obj.raw = data
for name, value in data.iteritems():
if cls.SIMPLE_PROPS and name in cls.SIMPLE_PROPS:
setattr(obj, name, value)
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.