docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
UMA RP function to get the claims gathering URL.
Parameters:
* **ticket (str):** ticket to pass to the auth server. for 90% of the cases, this will be obtained from 'need_info' error of get_rpt
Returns:
**string** specifying the claims gathering url | def uma_rp_get_claims_gathering_url(self, ticket):
params = {
'oxd_id': self.oxd_id,
'claims_redirect_uri': self.config.get('client',
'claims_redirect_uri'),
'ticket': ticket
}
logger.debug("Sending c... | 649,360 |
Constructor for SocketMessenger
Parameters:
* **host (str):** the host to connect for oxd-server, default localhost
* **port (integer):** the port number to bind to the host, default is 8099 | def __init__(self, host='localhost', port=8099):
Messenger.__init__(self)
self.host = host
self.port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
logger.debug("Creating a AF_INET, SOCK_STREAM socket.")
self.firstDone = False | 649,397 |
send function sends the command to the oxd server and recieves the
response.
Parameters:
* **command (dict):** Dict representation of the JSON command string
Returns:
**response (dict):** The JSON response from the oxd Server as a dict | def send(self, command):
cmd = json.dumps(command)
cmd = "{:04d}".format(len(cmd)) + cmd
msg_length = len(cmd)
# make the first time connection
if not self.firstDone:
logger.info('Initiating first time socket connection.')
self.__connect()
... | 649,399 |
Function that builds the request and returns the response from
oxd-server
Parameters:
* **command (str):** The command that has to be sent to the oxd-server
* ** **kwargs:** The parameters that should accompany the request
Returns:
**dict:** the returned res... | def request(self, command, **kwargs):
payload = {
"command": command,
"params": dict()
}
for item in kwargs.keys():
payload["params"][item] = kwargs.get(item)
if self.access_token:
payload["params"]["protection_access_token"] = se... | 649,400 |
Function that builds the request and returns the response
Parameters:
* **command (str):** The command that has to be sent to the oxd-server
* ** **kwargs:** The parameters that should accompany the request
Returns:
**dict:** the returned response from oxd-server as... | def request(self, command, **kwargs):
url = self.base + command.replace("_", "-")
req = urllib2.Request(url, json.dumps(kwargs))
req.add_header("User-Agent", "oxdpython/%s" % __version__)
req.add_header("Content-type", "application/json; charset=UTF-8")
# add the prot... | 649,403 |
Set a scope condition for the resource for a http_method
Parameters:
* **http_method (str):** HTTP method like GET, POST, PUT, DELETE
* **scope (str, list):** the scope of access control as str if single, or as a list of strings if multiple scopes are to be set | def set_scope(self, http_method, scope):
for con in self.conditions:
if http_method in con['httpMethods']:
if isinstance(scope, list):
con['scopes'] = scope
elif isinstance(scope, str) or isinstance(scope, unicode):
co... | 649,441 |
Adds a new resource with the given path to the resource set.
Parameters:
* **path (str, unicode):** path of the resource to be protected
Raises:
TypeError when the path is not a string or a unicode string | def add(self, path):
if not isinstance(path, str) and not isinstance(path, unicode):
raise TypeError('The value passed for parameter path is not a str'
' or unicode')
resource = Resource(path)
self.resources[path] = resource
return resour... | 649,442 |
Sets up a new project from a template
Note that the `temple.constants.TEMPLE_ENV_VAR` is set to 'setup' during the duration
of this function.
Args:
template (str): The git SSH path to a template
version (str, optional): The version of the template to use when updating. Defaults
... | def setup(template, version=None):
temple.check.is_git_ssh_path(template)
temple.check.not_in_git_repo()
repo_path = temple.utils.get_repo_path(template)
msg = (
'You will be prompted for the parameters of your new project.'
' Please read the docs at https://github.com/{} before en... | 650,436 |
Performs a Github API code search
Args:
query (str): The query sent to Github's code search
github_user (str, optional): The Github user being searched in the query string
Returns:
dict: A dictionary of repository information keyed on the git SSH url
Raises:
`InvalidGithub... | def _code_search(query, github_user=None):
github_client = temple.utils.GithubClient()
headers = {'Accept': 'application/vnd.github.v3.text-match+json'}
resp = github_client.get('/search/code',
params={'q': query, 'per_page': 100},
headers=head... | 650,438 |
Given an old version and new version, check if the cookiecutter.json files have changed
When the cookiecutter.json files change, it means the user will need to be prompted for
new context
Args:
template (str): The git SSH path to the template
old_version (str): The git SHA of the old versi... | def _cookiecutter_configs_have_changed(template, old_version, new_version):
temple.check.is_git_ssh_path(template)
repo_path = temple.utils.get_repo_path(template)
github_client = temple.utils.GithubClient()
api = '/repos/{}/contents/cookiecutter.json'.format(repo_path)
old_config_resp = githu... | 650,451 |
Obtains the configuration used for cookiecutter templating
Args:
template: Path to the template
default_config (dict, optional): The default configuration
version (str, optional): The git SHA or branch to use when
checking out template. Defaults to latest version
Returns:
... | def get_cookiecutter_config(template, default_config=None, version=None):
default_config = default_config or {}
config_dict = cc_config.get_user_config()
repo_dir, _ = cc_repository.determine_repo_dir(
template=template,
abbreviations=config_dict['abbreviations'],
clone_to_dir=c... | 650,462 |
Perform a github API call
Args:
verb (str): Can be "post", "put", or "get"
url (str): The base URL with a leading slash for Github API (v3)
auth (str or HTTPBasicAuth): A Github API token or a HTTPBasicAuth object | def _call_api(self, verb, url, **request_kwargs):
api = 'https://api.github.com{}'.format(url)
auth_headers = {'Authorization': 'token {}'.format(self.api_token)}
headers = {**auth_headers, **request_kwargs.pop('headers', {})}
return getattr(requests, verb)(api, headers=headers,... | 650,465 |
Factory function for penaltymodel_maxgap.
Args:
specification (penaltymodel.Specification): The specification
for the desired penalty model.
Returns:
:class:`penaltymodel.PenaltyModel`: Penalty model with the given specification.
Raises:
:class:`penaltymodel.Impossible... | def get_penalty_model(specification):
# check that the feasible_configurations are spin
feasible_configurations = specification.feasible_configurations
if specification.vartype is dimod.BINARY:
feasible_configurations = {tuple(2 * v - 1 for v in config): en
f... | 650,467 |
Iterate over all of the sets of feasible configurations in the cache.
Args:
cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function
is meant to be run within a :obj:`with` statement.
Yields:
dict[tuple(int): number]: The feasible_configurations. | def iter_feasible_configurations(cur):
select = \
for num_variables, feasible_configurations, energies in cur.execute(select):
configs = json.loads(feasible_configurations)
energies = json.loads(energies)
yield {_decode_config(config, num_variables): energy
... | 650,469 |
Iterate through all penalty models in the cache matching the
given specification.
Args:
cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function
is meant to be run within a :obj:`with` statement.
specification (:class:`penaltymodel.Specification`): A specification
... | def iter_penalty_model_from_specification(cur, specification):
encoded_data = {}
nodelist = sorted(specification.graph)
edgelist = sorted(sorted(edge) for edge in specification.graph.edges)
encoded_data['num_nodes'] = len(nodelist)
encoded_data['num_edges'] = len(edgelist)
encoded_data['ed... | 650,478 |
Caching function for penaltymodel_cache.
Args:
penalty_model (:class:`penaltymodel.PenaltyModel`): Penalty model to
be cached.
database (str, optional): The path to the desired sqlite database
file. If None, will use the default. | def cache_penalty_model(penalty_model, database=None):
# only handles index-labelled nodes
if not _is_index_labelled(penalty_model.graph):
mapping, __ = _graph_canonicalization(penalty_model.graph)
penalty_model = penalty_model.relabel_variables(mapping, inplace=False)
# connect to th... | 650,484 |
Factory function for penaltymodel-lp.
Args:
specification (penaltymodel.Specification): The specification
for the desired penalty model.
Returns:
:class:`penaltymodel.PenaltyModel`: Penalty model with the given specification.
Raises:
:class:`penaltymodel.ImpossiblePena... | def get_penalty_model(specification):
# check that the feasible_configurations are spin
feasible_configurations = specification.feasible_configurations
if specification.vartype is dimod.BINARY:
feasible_configurations = {tuple(2 * v - 1 for v in config): en
fo... | 650,490 |
Grab values from a dictionary using an unordered tuple as a key.
Dictionary should not contain None, 0, or False as dictionary values.
Args:
dictionary: Dictionary that uses two-element tuple as keys
tuple_key: Unordered tuple of two elements
default_value: Value that is returned when ... | def get_item(dictionary, tuple_key, default_value):
u, v = tuple_key
# Grab tuple-values from dictionary
tuple1 = dictionary.get((u, v), None)
tuple2 = dictionary.get((v, u), None)
# Return the first value that is not {None, 0, False}
return tuple1 or tuple2 or default_value | 650,498 |
Creates an linear programming matrix based on the spin states, graph, and scalars provided.
LP matrix:
[spin_states, corresponding states of edges, offset_weight, gap_weight]
Args:
spin_states: Numpy array of spin states
nodes: Iterable
edges: Iterable of tuples
offset_w... | def _get_lp_matrix(spin_states, nodes, edges, offset_weight, gap_weight):
if len(spin_states) == 0:
return None
# Set up an empty matrix
n_states = len(spin_states)
m_linear = len(nodes)
m_quadratic = len(edges)
matrix = np.empty((n_states, m_linear + m_quadratic + 2)) # +2 colum... | 650,499 |
Creates an pysmt Real constant from x.
Args:
x (number): A number to be cast to a pysmt constant.
max_denominator (int, optional): The maximum size of the denominator.
Default 1000000.
Returns:
A Real constant with the given value and the denominator limited. | def limitReal(x, max_denominator=1000000):
f = Fraction(x).limit_denominator(max_denominator)
return Real((f.numerator, f.denominator)) | 650,502 |
Given a pysmt model, return a bqm.
Adds the values of the biases as determined by the SMT solver to a bqm.
Args:
model: A pysmt model.
Returns:
:obj:`dimod.BinaryQuadraticModel` | def to_bqm(self, model):
linear = ((v, float(model.get_py_value(bias)))
for v, bias in self.linear.items())
quadratic = ((u, v, float(model.get_py_value(bias)))
for (u, v), bias in self.quadratic.items())
offset = float(model.get_py_value(self.offs... | 650,505 |
Define our own multiplication for bias times spins. This allows for
cleaner log code as well as value checking.
Args:
spin (int): -1 or 1
bias (:class:`pysmt.shortcuts.Symbol`): The bias
Returns:
spins * bias | def SpinTimes(spin, bias):
if not isinstance(spin, int):
raise TypeError('spin must be an int')
if spin == -1:
return Times(Real((-1, 1)), bias) # -1 / 1
elif spin == 1:
# identity
return bias
else:
raise ValueError('expected spins to be -1., or 1.') | 650,506 |
A formula for an upper bound on the energy of Theta with spins fixed.
Args:
spins (dict): Spin values for a subset of the variables in Theta.
Returns:
Formula that upper bounds the energy with spins fixed. | def energy_upperbound(self, spins):
subtheta = self.theta.copy()
subtheta.fix_variables(spins)
# ok, let's start eliminating variables
trees = self._trees
if not trees:
# if there are no variables to eliminate, then the offset of
# subtheta is t... | 650,509 |
Determine the energy of the elimination tree.
Args:
tree (dict): The current elimination tree
spins (dict): The current fixed spins
subtheta (dict): Theta with spins fixed.
auxvars (dict): The auxiliary variables for the given spins.
Returns:
... | def message(self, tree, spins, subtheta, auxvars):
energy_sources = set()
for v, children in tree.items():
aux = auxvars[v]
assert all(u in spins for u in self._ancestors[v])
# build an iterable over all of the energies contributions
# that we c... | 650,511 |
Determine an upper bound on the energy of the elimination tree.
Args:
tree (dict): The current elimination tree
spins (dict): The current fixed spins
subtheta (dict): Theta with spins fixed.
Returns:
The formula for the energy of the tree. | def message_upperbound(self, tree, spins, subtheta):
energy_sources = set()
for v, subtree in tree.items():
assert all(u in spins for u in self._ancestors[v])
# build an iterable over all of the energies contributions
# that we can exactly determine given v... | 650,512 |
Set the energy of Theta with spins fixed to target_energy.
Args:
spins (dict): Spin values for a subset of the variables in Theta.
target_energy (float): The desired energy for Theta with spins fixed.
Notes:
Add equality constraint to assertions. | def set_energy(self, spins, target_energy):
spin_energy = self.energy(spins)
self.assertions.add(Equals(spin_energy, limitReal(target_energy))) | 650,513 |
Upper bound the energy of Theta with spins fixed to be greater than (gap + offset).
Args:
spins (dict): Spin values for a subset of the variables in Theta.
offset (float): A value that is added to the upper bound. Default value is 0.
Notes:
Add equality constraint t... | def set_energy_upperbound(self, spins, offset=0):
spin_energy = self.energy_upperbound(spins)
self.assertions.add(GE(spin_energy, self.gap + offset)) | 650,514 |
Takes a camelCaseFieldName and returns an Title Case Field Name
Args:
name (str): E.g. camelCaseFieldName
Returns:
str: Title Case converted name. E.g. Camel Case Field Name | def camel_to_title(name):
split = re.findall(r"[A-Z]?[a-z0-9]+|[A-Z]+(?=[A-Z]|$)", name)
ret = " ".join(split)
ret = ret[0].upper() + ret[1:]
return ret | 650,540 |
Takes a snake_field_name and returns a camelCaseFieldName
Args:
name (str): E.g. snake_field_name or SNAKE_FIELD_NAME
Returns:
str: camelCase converted name. E.g. capsFieldName | def snake_to_camel(name):
ret = "".join(x.title() for x in name.split("_"))
ret = ret[0].lower() + ret[1:]
return ret | 650,541 |
Create an instance from a serialized version of cls
Args:
d(dict): Endpoints of cls to set
ignore(tuple): Keys to ignore
Returns:
Instance of this class | def from_dict(cls, d, ignore=()):
filtered = {}
for k, v in d.items():
if k == "typeid":
assert v == cls.typeid, \
"Dict has typeid %s but %s has typeid %s" % \
(v, cls, cls.typeid)
elif k not in ignore:
... | 650,545 |
Register a subclass so from_dict() works
Args:
typeid (str): Type identifier for subclass | def register_subclass(cls, typeid):
def decorator(subclass):
cls._subcls_lookup[typeid] = subclass
subclass.typeid = typeid
return subclass
return decorator | 650,546 |
Look up a class based on a serialized dictionary containing a typeid
Args:
d (dict): Dictionary with key "typeid"
Returns:
Serializable subclass | def lookup_subclass(cls, d):
try:
typeid = d["typeid"]
except KeyError:
raise FieldError("typeid not present in keys %s" % list(d))
subclass = cls._subcls_lookup.get(typeid, None)
if not subclass:
raise FieldError("'%s' not a valid typeid" % ... | 650,547 |
Start the process going
Args:
timeout (float): Maximum amount of time to wait for each spawned
process. None means forever | def start(self, timeout=None):
assert self.state == STOPPED, "Process already started"
self.state = STARTING
should_publish = self._start_controllers(
self._controllers.values(), timeout)
if should_publish:
self._publish_controllers(timeout)
self.... | 650,564 |
Stop the process and wait for it to finish
Args:
timeout (float): Maximum amount of time to wait for each spawned
object. None means forever | def stop(self, timeout=None):
assert self.state == STARTED, "Process not started"
self.state = STOPPING
# Allow every controller a chance to clean up
self._run_hook(ProcessStopHook, timeout=timeout)
for s in self._spawned:
if not s.ready():
se... | 650,568 |
Runs the function in a worker thread, returning a Result object
Args:
function: Function to run
args: Positional arguments to run the function with
kwargs: Keyword arguments to run the function with
Returns:
Spawned: Something you can call wait(timeout) ... | def spawn(self, function, *args, **kwargs):
# type: (Callable[..., Any], *Any, **Any) -> Spawned
assert self.state != STOPPED, "Can't spawn when process stopped"
spawned = Spawned(function, args, kwargs)
self._spawned.append(spawned)
self._spawn_count += 1
# Filt... | 650,569 |
Add a controller to be hosted by this process
Args:
controller (Controller): Its controller
timeout (float): Maximum amount of time to wait for each spawned
object. None means forever | def add_controller(self, controller, timeout=None):
# type: (Controller, float) -> None
assert controller.mri not in self._controllers, \
"Controller already exists for %s" % controller.mri
self._controllers[controller.mri] = controller
controller.setup(self)
... | 650,571 |
Create the relevant parts for this field
Args:
field_name (str): Short field name, e.g. VAL
field_data (FieldData): Field data object | def make_parts_for(self, field_name, field_data):
typ = field_data.field_type
subtyp = field_data.field_subtype
if typ in ("read", "xadc"):
writeable = False
else:
writeable = True
if typ == "time" or typ in ("param", "read") and subtyp == "time... | 650,597 |
Get a view of a block
Args:
mri: The mri of the controller hosting the block
Returns:
Block: The block we control | def block_view(self, mri):
# type: (str) -> Block
controller = self.get_controller(mri)
block = controller.block_view(weakref.proxy(self))
return block | 650,625 |
Set function to call just before requests are dispatched
Args:
notify_dispatch_request (callable): function will be called
with request as single arg just before request is dispatched | def set_notify_dispatch_request(self, notify_dispatch_request, *args):
self._notify_dispatch_request = notify_dispatch_request
self._notify_args = args | 650,627 |
Puts a value to a path and returns when it completes
Args:
path (list): The path to put to
value (object): The value to set
timeout (float): time in seconds to wait for responses, wait forever
if None
event_timeout: maximum time in seconds to wait... | def put(self, path, value, timeout=None, event_timeout=None):
future = self.put_async(path, value)
self.wait_all_futures(
future, timeout=timeout, event_timeout=event_timeout)
return future.result() | 650,630 |
Puts a value to a path and returns immediately
Args:
path (list): The path to put to
value (object): The value to set
Returns:
Future: A single Future which will resolve to the result | def put_async(self, path, value):
request = Put(self._get_next_id(), path, value)
request.set_callback(self._q.put)
future = self._dispatch_request(request)
return future | 650,631 |
Synchronously calls a method
Args:
path (list): The path to post to
params (dict): parameters for the call
timeout (float): time in seconds to wait for responses, wait
forever if None
event_timeout: maximum time in seconds to wait between each res... | def post(self, path, params=None, timeout=None, event_timeout=None):
future = self.post_async(path, params)
self.wait_all_futures(
future, timeout=timeout, event_timeout=event_timeout)
return future.result() | 650,632 |
Asynchronously calls a function on a child block
Args:
path (list): The path to post to
params (dict): parameters for the call
Returns:
Future: as single Future that will resolve to the result | def post_async(self, path, params=None):
request = Post(self._get_next_id(), path, params)
request.set_callback(self._q.put)
future = self._dispatch_request(request)
return future | 650,633 |
Terminates the subscription given by a future
Args:
future (Future): The future of the original subscription | def unsubscribe(self, future):
assert future not in self._pending_unsubscribes, \
"%r has already been unsubscribed from" % \
self._pending_unsubscribes[future]
subscribe = self._requests[future]
self._pending_unsubscribes[future] = subscribe
# Clear out ... | 650,635 |
Resolve when an path value equals value
Args:
path (list): The path to wait to
good_value (object): the value to wait for
bad_values (list): values to raise an error on
timeout (float): time in seconds to wait for responses, wait
forever if None
... | def when_matches(self, path, good_value, bad_values=None, timeout=None,
event_timeout=None):
future = self.when_matches_async(path, good_value, bad_values)
self.wait_all_futures(
future, timeout=timeout, event_timeout=event_timeout) | 650,637 |
Services all futures while waiting
Args:
seconds (float): Time to wait | def sleep(self, seconds):
until = time.time() + seconds
try:
while True:
self._service_futures([], until)
except TimeoutError:
return | 650,640 |
Register func to be run when any of the hooks are run by parent
Args:
hooks: A Hook class or list of Hook classes of interest
func: The callable that should be run on that Hook
args_gen: Optionally specify the argument names that should be
passed to func. If ... | def register_hooked(self,
hooks, # type: Union[Type[Hook], Sequence[Type[Hook]]]
func, # type: Hooked
args_gen=None # type: Optional[ArgsGen]
):
# type: (Type[Hook], Callable, Optional[Callable]) -> None
... | 650,679 |
Pass response from server to process receive queue
Args:
message(str): Received message | def on_message(self, message):
# Called in tornado loop
try:
self.log.debug("Got message %s", message)
d = json_decode(message)
response = deserialize_object(d, Response)
if isinstance(response, (Return, Error)):
request = self._re... | 650,715 |
Abstract method telling the ClientComms to sync this proxy Block
with its remote counterpart. Should wait until it is connected
Args:
mri (str): The mri for the remote block
block (BlockModel): The local proxy Block to keep in sync | def sync_proxy(self, mri, block):
# Send a root Subscribe to the server
subscribe = Subscribe(path=[mri], delta=True)
done_queue = Queue()
def handle_response(response):
# Called from tornado
if not isinstance(response, Delta):
# Return o... | 650,719 |
Abstract method to dispatch a Put to the server
Args:
mri (str): The mri of the Block
attribute_name (str): The name of the Attribute within the Block
value: The value to put | def send_put(self, mri, attribute_name, value):
q = Queue()
request = Put(
path=[mri, attribute_name, "value"],
value=value)
request.set_callback(q.put)
IOLoopHelper.call(self._send_request, request)
response = q.get()
if isinstance(respon... | 650,723 |
Abstract method to dispatch a Post to the server
Args:
mri (str): The mri of the Block
method_name (str): The name of the Method within the Block
params: The parameters to send
Returns:
The return results from the server | def send_post(self, mri, method_name, **params):
q = Queue()
request = Post(
path=[mri, method_name],
parameters=params)
request.set_callback(q.put)
IOLoopHelper.call(self._send_request, request)
response = q.get()
if isinstance(response, ... | 650,724 |
Filter the part_info dict looking for instances of our class
Args:
part_info (dict): {part_name: [Info] or None} as returned from
Controller.run_hook()
Returns:
dict: {part_name: [info]} where info is a subclass of cls | def filter_parts(cls, part_info):
# type: (Type[T], PartInfo) -> Dict[str, List[T]]
filtered = OrderedDict()
for part_name, info_list in part_info.items():
if info_list is None or isinstance(info_list, Exception):
continue
info_list = [i for i in ... | 650,727 |
Filter the part_info dict list looking for instances of our class
Args:
part_info (dict): {part_name: [Info] or None} as returned from
Controller.run_hook()
Returns:
list: [info] where info is a subclass of cls | def filter_values(cls, part_info):
# type: (Type[T], PartInfo) -> List[T]
filtered = []
for info_list in cls.filter_parts(part_info).values():
filtered += info_list
return filtered | 650,728 |
Filter the part_info dict list looking for a single instance of our
class
Args:
part_info (dict): {part_name: [Info] or None} as returned from
Controller.run_hook()
error_msg (str, optional): Specific error message to show if
there isn't a single ... | def filter_single_value(cls, part_info, error_msg=None):
# type: (Type[T], PartInfo, str) -> T
filtered = cls.filter_values(part_info)
if len(filtered) != 1:
if error_msg is None:
error_msg = "Expected a single %s, got %s of them" % \
... | 650,729 |
Search tags for port info, returning it
Args:
tags: A list of tags to check
Returns:
None or (is_source, port, connected_value|disconnected_value)
where port is one of the Enum entries of Port | def port_tag_details(cls, tags):
# type: (Sequence[str]) -> Union[Tuple[bool, Port, str], None]
for tag in tags:
match = port_tag_re.match(tag)
if match:
source_sink, port, extra = match.groups()
return source_sink == "source", cls(port), ... | 650,756 |
Change to a new state if the transition is allowed
Args:
state (str): State to transition to
message (str): Message if the transition is to a fault state | def transition(self, state, message=""):
with self.changes_squashed:
initial_state = self.state.value
if self.state_set.transition_allowed(
initial_state=initial_state, target_state=state):
self.log.debug(
"%s: Transitionin... | 650,769 |
Abstract method telling the ClientComms to sync this proxy Block
with its remote counterpart. Should wait until it is connected
Args:
mri (str): The mri for the remote block
block (BlockModel): The local proxy Block to keep in sync | def sync_proxy(self, mri, block):
done_queue = Queue()
self._queues[mri] = done_queue
update_fields = set()
def callback(value=None):
if isinstance(value, Exception):
# Disconnect or Cancelled or RemoteError
if isinstance(value, Disco... | 650,798 |
Abstract method to dispatch a Put to the server
Args:
mri (str): The mri of the Block
attribute_name (str): The name of the Attribute within the Block
value: The value to put | def send_put(self, mri, attribute_name, value):
path = attribute_name + ".value"
typ, value = convert_to_type_tuple_value(serialize_object(value))
if isinstance(typ, tuple):
# Structure, make into a Value
_, typeid, fields = typ
value = Value(Type(fie... | 650,801 |
Abstract method to dispatch a Post to the server
Args:
mri (str): The mri of the Block
method_name (str): The name of the Method within the Block
params: The parameters to send
Returns:
The return results from the server | def send_post(self, mri, method_name, **params):
typ, parameters = convert_to_type_tuple_value(serialize_object(params))
uri = NTURI(typ[2])
uri = uri.wrap(
path="%s.%s" % (mri, method_name),
kws=parameters,
scheme="pva"
)
value = sel... | 650,802 |
Wait until a Block backed by a StatefulController has initialized
Args:
context (Context): The context to use to make the child block
mri (str): The mri of the child block
timeout (float): The maximum time to wait | def wait_for_stateful_block_init(context, mri, timeout=DEFAULT_TIMEOUT):
context.when_matches(
[mri, "state", "value"], StatefulStates.READY,
bad_values=[StatefulStates.FAULT, StatefulStates.DISABLED],
timeout=timeout) | 650,827 |
Change the name of the logger that log.* should call
Args:
**fields: Extra fields to be logged. Logger name will be:
".".join([<module_name>, <cls_name>] + fields_sorted_on_key) | def set_logger(self, **fields):
names = [self.__module__, self.__class__.__name__]
for field, value in sorted(fields.items()):
names.append(value)
# names should be something like this for one field:
# ["malcolm.modules.scanning.controllers.runnablecontroller",
... | 650,862 |
Make a View subclass containing properties specific for given data
Args:
controller (Controller): The child controller that hosts the data
context (Context): The context the parent has made that the View should
use for manipulating the data
data (Model): The actual data that con... | def make_view(controller, context, data):
# type: (Controller, Context, Any) -> Any
if isinstance(data, BlockModel):
# Make an Block View
view = _make_view_subclass(Block, controller, context, data)
elif isinstance(data, AttributeModel):
# Make an Attribute View
view = A... | 650,873 |
Sets the notifier, and the path from the path from block root
Args:
notifier (Notifier): The Notifier to tell when endpoint data changes
path (list): The absolute path to get to this object | def set_notifier_path(self, notifier, path):
# type: (Union[Notifier, DummyNotifier], List[str]) -> None
# This function should either change from the DummyNotifier or to
# the DummyNotifier, never between two valid notifiers
assert self.notifier is Model.notifier or notifier is... | 650,899 |
Make an AttributeModel instance of the correct type for this Meta
Args:
initial_value: The initial value the Attribute should take
Returns:
AttributeModel: The created attribute model instance | def create_attribute_model(self, initial_value=None):
# type: (Any) -> AttributeModel
attr = self.attribute_class(meta=self, value=initial_value)
return attr | 650,903 |
Send a message to a PandABox and wait for the response
Args:
message (str): The message to send
timeout (float): How long to wait before raising queue.Empty
Returns:
str: The response | def send_recv(self, message, timeout=10.0):
response_queue = self.send(message)
response = self.recv(response_queue, timeout)
return response | 650,952 |
Send batched requests for a list of parameters
Args:
request (str): Request to send, like "%s.*?\n"
parameter_list (list): parameters to format with, like
["TTLIN", "TTLOUT"]
Returns:
dict: {parameter: response_queue} | def parameterized_send(self, request, parameter_list):
response_queues = OrderedDict()
for parameter in parameter_list:
response_queues[parameter] = self.send(request % parameter)
return response_queues | 650,958 |
Conditionally sever Sink Ports of the child. If connected_to
is then None then sever all, otherwise restrict to connected_to's
Source Ports
Args:
context (Context): The context to use
ports (dict): {part_name: [PortInfo]}
connected_to (str): Restrict severing... | def sever_sink_ports(self, context, ports, connected_to=None):
# type: (AContext, APortMap, str) -> None
# Find the Source Ports to connect to
if connected_to:
# Calculate a lookup of the Source Port "name" to type
source_port_lookup = self._source_port_lookup(
... | 650,990 |
Calculate what is connected to what
Args:
ports: {part_name: [PortInfo]} from other ports | def calculate_part_visibility(self, ports):
# type: (APortMap) -> None
# Calculate a lookup of Source Port connected_value to part_name
source_port_lookup = {}
for part_name, port_infos in SourcePortInfo.filter_parts(ports).items():
for port_info in port_infos:
... | 650,991 |
Register a squashed change to a particular path
Args:
path (list): The path of what has changed, relative from Block
data (object): The new data | def add_squashed_change(self, path, data):
# type: (List[str], Any) -> None
assert self._squashed_count, "Called while not squashing changes"
self._squashed_changes.append([path[1:], data]) | 651,007 |
Set our data and notify anyone listening
Args:
changes (list): [[path, optional data]] where path is the path to
what has changed, and data is the unserialized object that has
changed
Returns:
list: [(callback, Response)] that need to be called | def notify_changes(self, changes):
# type: (List[List]) -> CallbackResponses
ret = []
child_changes = {}
for change in changes:
# Add any changes that our children need to know about
self._add_child_change(change, child_changes)
# If we have upda... | 651,011 |
Set our data and notify any subscribers of children what has changed
Args:
data (object): The new data
Returns:
dict: {child_name: [path_list, optional child_data]} of the change
that needs to be passed to a child as a result of this | def _update_data(self, data):
# type: (Any) -> Dict[str, List]
self.data = data
child_change_dict = {}
# Reflect change of data to children
for name in self.children:
child_data = getattr(data, name, None)
if child_data is None:
# ... | 651,013 |
Add to the list of request to notify, and notify the initial value of
the data held
Args:
request (Subscribe): The subscribe request
path (list): The relative path from ourself
Returns:
list: [(callback, Response)] that need to be called | def handle_subscribe(self, request, path):
# type: (Subscribe, List[str]) -> CallbackResponses
ret = []
if path:
# Recurse down
name = path[0]
if name not in self.children:
self.children[name] = NotifierNode(
getatt... | 651,014 |
Remove from the notifier list and send a return
Args:
request (Subscribe): The original subscribe request
path (list): The relative path from ourself
Returns:
list: [(callback, Response)] that need to be called | def handle_unsubscribe(self, request, path):
# type: (Subscribe, List[str]) -> CallbackResponses
ret = []
if path:
# Recurse down
name = path[0]
child = self.children[name]
ret += child.handle_unsubscribe(request, path[1:])
if ... | 651,015 |
Keep recursing down from base using dotted name, then call it with
self.params and args
Args:
substitutions (dict): Substitutions to make to self.param_dict
Returns:
The found object called with (*args, map_from_d)
E.g. if ob is malcolm.parts, and name is "ca.C... | def instantiate(self, substitutions):
param_dict = self.substitute_params(substitutions)
pkg, ident = self.name.rsplit(".", 1)
pkg = "malcolm.modules.%s" % pkg
try:
ob = importlib.import_module(pkg)
except ImportError as e:
raise_with_traceback(
... | 651,035 |
Split a dictionary into parameters controllers parts blocks defines
Args:
yaml_path (str): File path to YAML file, or a file in the same dir
filename (str): If give, use this filename as the last element in
the yaml_path (so yaml_path can be __file__)
Returns:
... | def from_yaml(cls, yaml_path, filename=None):
if filename:
# different filename to support passing __file__
yaml_path = os.path.join(os.path.dirname(yaml_path), filename)
assert yaml_path.endswith(".yaml"), \
"Expected a/path/to/<yamlname>.yaml, got %r" % yam... | 651,036 |
Substitute param values in our param_dict from params
Args:
substitutions (Map or dict): Values to substitute. E.g. Map of
{"name": "me"}
E.g. if self.param_dict is:
{"name": "$(name):pos", "exposure": 1.0}
And substitutions is:
{"name": "me"... | def substitute_params(self, substitutions):
param_dict = {}
# TODO: this should be yaml.add_implicit_resolver()
for k, v in self.param_dict.items():
param_dict[k] = replace_substitutions(v, substitutions)
return param_dict | 651,037 |
Make config dir and return full file path and extension
Args:
name (str): Filename without dir or extension
Returns:
str: Full path including extension | def _validated_config_filename(self, name):
dir_name = self._make_config_dir()
filename = os.path.join(dir_name, name.split(".json")[0] + ".json")
return filename | 651,064 |
Load a design name, running the child LoadHooks.
Args:
design: Name of the design json file, without extension
init: Passed to the LoadHook to tell the children if this is being
run at Init or not | def do_load(self, design, init=False):
# type: (str, bool) -> None
if design:
filename = self._validated_config_filename(design)
with open(filename, "r") as f:
text = f.read()
structure = json_decode(text)
else:
structure =... | 651,067 |
Record a purchase in Sailthru
Arguments:
sailthru_client (object): SailthruClient
email (str): user's email address
item (dict): Sailthru required information about the course
purchase_incomplete (boolean): True if adding item to shopping cart
message_id (str): Cookie used t... | def _record_purchase(sailthru_client, email, item, purchase_incomplete, message_id, options):
try:
sailthru_response = sailthru_client.purchase(email, [item],
incomplete=purchase_incomplete, message_id=message_id,
... | 651,082 |
Get course information using the Sailthru content api or from cache.
If there is an error, just return with an empty response.
Arguments:
course_id (str): course key of the course
course_url (str): LMS url for course info page.
sailthru_client (object): SailthruClient
site_code... | def _get_course_content(course_id, course_url, sailthru_client, site_code, config):
# check cache first
cache_key = "{}:{}".format(site_code, course_url)
response = cache.get(cache_key)
if not response:
try:
sailthru_response = sailthru_client.api_get("content", {"id": course_ur... | 651,083 |
Get course information using the Ecommerce course api.
In case of error returns empty response.
Arguments:
course_id (str): course key of the course
site_code (str): site code
Returns:
course information from Ecommerce | def _get_course_content_from_ecommerce(course_id, site_code=None):
api = get_ecommerce_client(site_code=site_code)
try:
api_response = api.courses(course_id).get()
except Exception: # pylint: disable=broad-except
logger.exception(
'An error occurred while retrieving data fo... | 651,084 |
Maintain a list of courses the user has unenrolled from in the Sailthru user record
Arguments:
sailthru_client (object): SailthruClient
email (str): user's email address
course_url (str): LMS url for course info page.
unenroll (boolean): True if unenrolling, False if enrolling
... | def _update_unenrolled_list(sailthru_client, email, course_url, unenroll):
try:
# get the user 'vars' values from sailthru
sailthru_response = sailthru_client.api_get("user", {"id": email, "fields": {"vars": 1}})
if not sailthru_response.is_ok():
error = sailthru_response.ge... | 651,085 |
Sends the offer assignment email.
Args:
self: Ignore.
user_email (str): Recipient's email address.
offer_assignment_id (str): Key of the entry in the offer_assignment model.
subject (str): Email subject.
email_body (str): The body of the email.
site_code (str): Identi... | def send_offer_assignment_email(self, user_email, offer_assignment_id, subject, email_body, site_code=None):
config = get_sailthru_configuration(site_code)
response = _send_offer_assignment_notification_email(config, user_email, subject, email_body, site_code, self)
if response and response.is_ok():
... | 651,088 |
Update the offer_assignment and offer_assignment_email model using the Ecommerce assignmentemail api.
Arguments:
offer_assignment_id (str): Key of the entry in the offer_assignment model.
send_id (str): Unique message id from Sailthru
status (str): status to be sent to the api
site_c... | def _update_assignment_email_status(offer_assignment_id, send_id, status, site_code=None):
api = get_ecommerce_client(url_postfix='assignment-email/', site_code=site_code)
post_data = {
'offer_assignment_id': offer_assignment_id,
'send_id': send_id,
'status': status,
}
try:
... | 651,090 |
Sends the offer emails after assignment, either for revoking or reminding.
Args:
self: Ignore.
user_email (str): Recipient's email address.
subject (str): Email subject.
email_body (str): The body of the email.
site_code (str): Identifier of the site sending the email. | def send_offer_update_email(self, user_email, subject, email_body, site_code=None):
config = get_sailthru_configuration(site_code)
_send_offer_assignment_notification_email(config, user_email, subject, email_body, site_code, self) | 651,091 |
Fulfills an order.
Arguments:
order_number (str): Order number indicating which order to fulfill.
Returns:
None | def fulfill_order(self, order_number, site_code=None, email_opt_in=False):
max_fulfillment_retries = get_configuration('MAX_FULFILLMENT_RETRIES', site_code=site_code)
api = get_ecommerce_client(site_code=site_code)
try:
logger.info('Requesting fulfillment of order [%s].', order_number)
... | 651,094 |
Returns a Sailthru client for the specified site.
Args:
site_code (str): Site for which the client should be configured.
Returns:
SailthruClient
Raises:
SailthruNotEnabled: If Sailthru is not enabled for the specified site.
ConfigurationError: If either the Sailthru API ke... | def get_sailthru_client(site_code):
# Get configuration
config = get_sailthru_configuration(site_code)
# Return if Sailthru integration disabled
if not config.get('SAILTHRU_ENABLE'):
msg = 'Sailthru is not enabled for site {}'.format(site_code)
log.debug(msg)
raise Sailthru... | 651,095 |
Get an object from the cache
Arguments:
key (str): Cache key
Returns:
Cached object | def get(self, key):
lock.acquire()
try:
if key not in self:
return None
current_time = time.time()
if self[key].expire > current_time:
return self[key].value
# expired key, clean out all expired keys
d... | 651,097 |
Save an object in the cache
Arguments:
key (str): Cache key
value (object): object to cache
duration (int): time in seconds to keep object in cache | def set(self, key, value, duration):
lock.acquire()
try:
self[key] = CacheObject(value, duration)
finally:
lock.release() | 651,098 |
Get client for fetching data from ecommerce API.
Arguments:
site_code (str): (Optional) The SITE_OVERRIDES key to inspect for site-specific values
url_postfix (str): (Optional) The URL postfix value to append to the ECOMMERCE_API_ROOT value.
Returns:
EdxRestApiClient object | def get_ecommerce_client(url_postfix='', site_code=None):
ecommerce_api_root = get_configuration('ECOMMERCE_API_ROOT', site_code=site_code)
signing_key = get_configuration('JWT_SECRET_KEY', site_code=site_code)
issuer = get_configuration('JWT_ISSUER', site_code=site_code)
service_username = get_con... | 651,100 |
Class constructor.
Args:
issues (list): List of `Issue` instances | def __init__(self, issues = None):
self._issues = []
self._config = {}
self._project = None
self.issues = issues | 651,734 |
Setter for 'path' property
Args:
value (str): Absolute path to scan | def path(self, value):
if not value.endswith('/'):
self._path = '{v}/'.format(v=value)
else:
self._path = value | 651,739 |
Parse the config values
Args:
value (dict): Dictionary which contains the checker config
Returns:
dict: The checker config with parsed values | def parseConfig(cls, value):
if 'enabled' in value:
value['enabled'] = bool(value['enabled'])
if 'exclude_paths' in value:
value['exclude_paths'] = [n.strip() for n in ast.literal_eval(value['exclude_paths'])]
return value | 651,740 |
Check if a software is installed into machine.
Args:
value (str): Software's name
Returns:
bool: True if the software is installed. False else | def isInstalled(value):
function =
command = .format(f = function, arg=value)
cmd = CommandHelper(command)
cmd.execute()
return "1" in cmd.output | 651,741 |
Class constructor.
Args:
command (str): Command to execute | def __init__(self, command = None):
self._output = None
self._errors = None
self._command = None
self.command = command | 651,743 |
Executes the command setted into class
Args:
shell (boolean): Set True if command is a shell command. Default: True | def execute(self, shell = True):
process = Popen(self.command, stdout=PIPE, stderr=PIPE, shell=shell)
self.output, self.errors = process.communicate() | 651,746 |
Print a message if the class attribute 'verbose' is enabled
Args:
message (str): Message to print | def _debug(message, color=None, attrs=None):
if attrs is None:
attrs = []
if color is not None:
print colored(message, color, attrs=attrs)
else:
if len(attrs) > 0:
print colored(message, "white", attrs=attrs)
else:
print message | 651,748 |
Writes a section for a plugin.
Args:
instance (object): Class instance for plugin
config (object): Object (ConfigParser) which the current config
parent_section (str): Parent section for plugin. Usually 'checkers' or 'reports' | def _addConfig(instance, config, parent_section):
try:
section_name = "{p}/{n}".format(p = parent_section, n=instance.NAME.lower())
config.add_section(section_name)
for k in instance.CONFIG.keys():
config.set(section_name, k, instance.CONFIG[k])
except Exception as e:
print "[!] %s" % e | 651,758 |
Returns a dictionary which contains the current config. If a section is setted,
only will returns the section config
Args:
section (str): (Optional) Section name.
Returns:
dict: Representation of current config | def getConfig(self, section = None):
data = {}
if section is None:
for s in self.config.sections():
if '/' in s:
# Subsection
parent, _s = s.split('/')
data[parent][_s] = dict(self.config.items(s))
else:
data[s] = dict(self.config.items(s))
else:
# Only one section will be ret... | 651,761 |
Returns a class instance from a .py file.
Args:
path (str): Absolute path to .py file
args (dict): Arguments passed via class constructor
Returns:
object: Class instance or None | def _getClassInstance(path, args=None):
if not path.endswith(".py"):
return None
if args is None:
args = {}
classname = AtomShieldsScanner._getClassName(path)
basename = os.path.basename(path).replace(".py", "")
sys.path.append(os.path.dirname(path))
try:
mod = __import__(basename, globals(), ... | 651,766 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.