sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def items(self) -> Tuple[Tuple[str, "Package"], ...]: # type: ignore """ Return an iterable containing package name and corresponding `Package` instance that are available. """ item_dict = { name: self.build_dependencies.get(name) for name in self.build_dependencies ...
Return an iterable containing package name and corresponding `Package` instance that are available.
entailment
def values(self) -> List["Package"]: # type: ignore """ Return an iterable of the available `Package` instances. """ values = [self.build_dependencies.get(name) for name in self.build_dependencies] return values
Return an iterable of the available `Package` instances.
entailment
def get_dependency_package( self, package_name: str ) -> "Package": # type: ignore # noqa: F821 """ Return the dependency Package for a given package name. """ self._validate_name(package_name) return self.build_dependencies.get(package_name)
Return the dependency Package for a given package name.
entailment
def add(app: web.Application, feature: Any, key: Hashable = None, exist_ok: bool = False ): """ Adds a new feature to the app. Features can either be registered as the default feature for the class, or be given an explicit name. Args: app (web.Application): ...
Adds a new feature to the app. Features can either be registered as the default feature for the class, or be given an explicit name. Args: app (web.Application): The current Aiohttp application. feature (Any): The new feature that should be registered. ...
entailment
def get(app: web.Application, feature_type: Type[Any] = None, key: Hashable = None ) -> Any: """ Finds declared feature. Identification is done based on feature type and key. Args: app (web.Application): The current Aiohttp application. feature_type ...
Finds declared feature. Identification is done based on feature type and key. Args: app (web.Application): The current Aiohttp application. feature_type (Type[Any]): The Python type of the desired feature. If specified, it will be checked against the found f...
entailment
def validate_minimal_contract_factory_data(contract_data: Dict[str, str]) -> None: """ Validate that contract data in a package contains at least an "abi" and "deployment_bytecode" necessary to generate a deployable contract factory. """ if not all(key in contract_data.keys() for key in ("abi", "dep...
Validate that contract data in a package contains at least an "abi" and "deployment_bytecode" necessary to generate a deployable contract factory.
entailment
def generate_contract_factory_kwargs( contract_data: Dict[str, Any] ) -> Generator[Tuple[str, Any], None, None]: """ Build a dictionary of kwargs to be passed into contract factory. """ if "abi" in contract_data: yield "abi", contract_data["abi"] if "deployment_bytecode" in contract_dat...
Build a dictionary of kwargs to be passed into contract factory.
entailment
async def post_publish(request): """ --- tags: - Events summary: Publish event. description: Publish a new event message to the event bus. operationId: events.publish produces: - text/plain parameters: - in: body name: body description: Event message ...
--- tags: - Events summary: Publish event. description: Publish a new event message to the event bus. operationId: events.publish produces: - text/plain parameters: - in: body name: body description: Event message required: true schema: ...
entailment
async def post_subscribe(request): """ --- tags: - Events summary: Subscribe to events. operationId: events.subscribe produces: - text/plain parameters: - in: body name: body description: Event message required: true schema: typ...
--- tags: - Events summary: Subscribe to events. operationId: events.subscribe produces: - text/plain parameters: - in: body name: body description: Event message required: true schema: type: object properties: ...
entailment
async def _relay(self, channel: aioamqp.channel.Channel, body: str, envelope: aioamqp.envelope.Envelope, properties: aioamqp.properties.Properties): """Relays incoming messages between the queue and the user callback""" ...
Relays incoming messages between the queue and the user callback
entailment
def _lazy_listen(self): """ Ensures that the listener task only runs when actually needed. This function is a no-op if any of the preconditions is not met. Preconditions are: * The application is running (self._loop is set) * The task is not already running * The...
Ensures that the listener task only runs when actually needed. This function is a no-op if any of the preconditions is not met. Preconditions are: * The application is running (self._loop is set) * The task is not already running * There are subscriptions: either pending, or act...
entailment
def subscribe(self, exchange_name: str, routing: str, exchange_type: ExchangeType_ = 'topic', on_message: EVENT_CALLBACK_ = None ) -> EventSubscription: """Adds a new event subscription to the listener. Actual que...
Adds a new event subscription to the listener. Actual queue declaration to the remote message server is done when connected. If the listener is not currently connected, it defers declaration. All existing subscriptions are redeclared on the remote if `EventListener` loses and recreates...
entailment
async def publish(self, exchange: str, routing: str, message: Union[str, dict], exchange_type: ExchangeType_ = 'topic'): """ Publish a new event message. Connections are created automatically when calling `p...
Publish a new event message. Connections are created automatically when calling `publish()`, and will attempt to reconnect if connection was lost. For more information on publishing AMQP messages, see https://www.rabbitmq.com/tutorials/tutorial-three-python.html Args: ...
entailment
def is_ens_domain(authority: str) -> bool: """ Return false if authority is not a valid ENS domain. """ # check that authority ends with the tld '.eth' # check that there are either 2 or 3 subdomains in the authority # i.e. zeppelinos.eth or packages.zeppelinos.eth if authority[-4:] != ".eth...
Return false if authority is not a valid ENS domain.
entailment
def splitPrefix(name): """ Split the name into a tuple (I{prefix}, I{name}). The first element in the tuple is I{None} when the name does't have a prefix. @param name: A node name containing an optional prefix. @type name: basestring @return: A tuple containing the (2) parts of I{name} @rty...
Split the name into a tuple (I{prefix}, I{name}). The first element in the tuple is I{None} when the name does't have a prefix. @param name: A node name containing an optional prefix. @type name: basestring @return: A tuple containing the (2) parts of I{name} @rtype: (I{prefix}, I{name})
entailment
def unwrap(self, d, item): """ translate (unwrap) using an optional wrapper function """ nopt = ( lambda x: x ) try: md = d.__metadata__ pmd = getattr(md, '__print__', None) if pmd is None: return item wrappers = getattr(pmd, 'wrapp...
translate (unwrap) using an optional wrapper function
entailment
def exclude(self, d, item): """ check metadata for excluded items """ try: md = d.__metadata__ pmd = getattr(md, '__print__', None) if pmd is None: return False excludes = getattr(pmd, 'excludes', []) return ( item[0] in exclude...
check metadata for excluded items
entailment
def mangle(self, name, x): """ Mangle the name by hashing the I{name} and appending I{x}. @return: the mangled name. """ h = abs(hash(name)) return '%s-%s' % (h, x)
Mangle the name by hashing the I{name} and appending I{x}. @return: the mangled name.
entailment
def find(self, name, resolved=True): """ Get the definition object for the schema object by name. @param name: The name of a schema object. @type name: basestring @param resolved: A flag indicating that the fully resolved type should be returned. @type resolve...
Get the definition object for the schema object by name. @param name: The name of a schema object. @type name: basestring @param resolved: A flag indicating that the fully resolved type should be returned. @type resolved: boolean @return: The found schema I{type} ...
entailment
def push(self, x): """ Push an I{object} onto the stack. @param x: An object to push. @type x: L{Frame} @return: The pushed frame. @rtype: L{Frame} """ if isinstance(x, Frame): frame = x else: frame = Frame(x) self.s...
Push an I{object} onto the stack. @param x: An object to push. @type x: L{Frame} @return: The pushed frame. @rtype: L{Frame}
entailment
def pop(self): """ Pop the frame at the top of the stack. @return: The popped frame, else None. @rtype: L{Frame} """ if len(self.stack): popped = self.stack.pop() #log.debug('pop: (%s)\n%s', Repr(popped), Repr(self.stack)) return ...
Pop the frame at the top of the stack. @return: The popped frame, else None. @rtype: L{Frame}
entailment
def getchild(self, name, parent): """ get a child by name """ #log.debug('searching parent (%s) for (%s)', Repr(parent), name) if name.startswith('@'): return parent.get_attribute(name[1:]) else: return parent.get_child(name)
get a child by name
entailment
def query(self, name, node): """ blindly query the schema by name """ #log.debug('searching schema for (%s)', name) qref = qualify(name, node, node.namespace()) query = BlindQuery(qref) result = query.execute(self.schema) return (result, [])
blindly query the schema by name
entailment
def query(self, name): """ blindly query the schema by name """ #log.debug('searching schema for (%s)', name) schema = self.schema wsdl = self.wsdl() if wsdl is None: qref = qualify(name, schema.root, schema.tns) else: qref = qualify(name, wsdl.roo...
blindly query the schema by name
entailment
def resolvesoapbody(self, definitions, op): """ Resolve soap body I{message} parts by cross-referencing with operation defined in port type. @param definitions: A definitions object. @type definitions: L{Definitions} @param op: An I{operation} object. @type op: I...
Resolve soap body I{message} parts by cross-referencing with operation defined in port type. @param definitions: A definitions object. @type definitions: L{Definitions} @param op: An I{operation} object. @type op: I{operation}
entailment
def resolveheaders(self, definitions, op): """ Resolve soap header I{message} references. @param definitions: A definitions object. @type definitions: L{Definitions} @param op: An I{operation} object. @type op: I{operation} """ soap = op.soap heade...
Resolve soap header I{message} references. @param definitions: A definitions object. @type definitions: L{Definitions} @param op: An I{operation} object. @type op: I{operation}
entailment
def resolvefaults(self, definitions, op): """ Resolve soap fault I{message} references by cross-referencing with operation defined in port type. @param definitions: A definitions object. @type definitions: L{Definitions} @param op: An I{operation} object. @type op...
Resolve soap fault I{message} references by cross-referencing with operation defined in port type. @param definitions: A definitions object. @type definitions: L{Definitions} @param op: An I{operation} object. @type op: I{operation}
entailment
def find(self, location): """ Find the specified location in the store. @param location: The I{location} part of a URL. @type location: str @return: An input stream to the document. @rtype: StringIO """ try: content = self.store[location] ...
Find the specified location in the store. @param location: The I{location} part of a URL. @type location: str @return: An input stream to the document. @rtype: StringIO
entailment
def publictypes(self): """ get all public types """ for t in self.wsdl.schema.types.values(): if t in self.params: continue if t in self.types: continue item = (t, t) self.types.append(item) tc = lambda x,y: cmp(x[0].name, y[0].name) self.t...
get all public types
entailment
def encode(self, s): """ Encode special characters found in string I{s}. @param s: A string to encode. @type s: str @return: The encoded string. @rtype: str """ if isinstance(s, basestring) and self.needsEncoding(s): for x in self.encodings: ...
Encode special characters found in string I{s}. @param s: A string to encode. @type s: str @return: The encoded string. @rtype: str
entailment
def decode(self, s): """ Decode special characters encodings found in string I{s}. @param s: A string to decode. @type s: str @return: The decoded string. @rtype: str """ if isinstance(s, basestring) and '&' in s: for x in self.decodings: ...
Decode special characters encodings found in string I{s}. @param s: A string to decode. @type s: str @return: The decoded string. @rtype: str
entailment
def parse(self, file=None, string=None): """ SAX parse XML text. @param file: Parse a python I{file-like} object. @type file: I{file-like} object. @param string: Parse string XML. @type string: str """ timer = metrics.Timer() timer.start() ...
SAX parse XML text. @param file: Parse a python I{file-like} object. @type file: I{file-like} object. @param string: Parse string XML. @type string: str
entailment
def get_message(self, method, args, kwargs, options=None): """ Get the soap message for the specified method, args and soapheaders. This is the entry point for creating the outbound soap message. @param method: The method being invoked. @type method: I{service.Method} @pa...
Get the soap message for the specified method, args and soapheaders. This is the entry point for creating the outbound soap message. @param method: The method being invoked. @type method: I{service.Method} @param args: A list of args for the method invoked. @type args: list ...
entailment
def invoke(self, args, kwargs): """ Send the required soap message to invoke the specified method @param args: A list of args for the method invoked. @type args: list @param kwargs: Named (keyword) args for the method invoked. @type kwargs: dict @return: The resul...
Send the required soap message to invoke the specified method @param args: A list of args for the method invoked. @type args: list @param kwargs: Named (keyword) args for the method invoked. @type kwargs: dict @return: The result of the method invocation. @rtype: I{builti...
entailment
def send(self, soapenv): """ Send soap message. @param soapenv: A soap envelope to send. @type soapenv: L{Document} @return: The reply to the sent message. @rtype: I{builtin} or I{subclass of} L{Object} """ result = None location = self.location() ...
Send soap message. @param soapenv: A soap envelope to send. @type soapenv: L{Document} @return: The reply to the sent message. @rtype: I{builtin} or I{subclass of} L{Object}
entailment
def headers(self): """ Get http headers or the http/https request. @return: A dictionary of header/values. @rtype: dict """ action = self.method.soap.action stock = { 'Content-Type' : 'text/xml; charset=utf-8', 'SOAPAction': action } result = dict(stock, *...
Get http headers or the http/https request. @return: A dictionary of header/values. @rtype: dict
entailment
def succeeded(self, binding, reply): """ Request succeeded, process the reply @param binding: The binding to be used to process the reply. @type binding: L{bindings.binding.Binding} @param reply: The raw reply text. @type reply: str @return: The method result. ...
Request succeeded, process the reply @param binding: The binding to be used to process the reply. @type binding: L{bindings.binding.Binding} @param reply: The raw reply text. @type reply: str @return: The method result. @rtype: I{builtin}, L{Object} @raise WebFaul...
entailment
def failed(self, binding, error): """ Request failed, process reply based on reason @param binding: The binding to be used to process the reply. @type binding: L{suds.bindings.binding.Binding} @param error: The http error message @type error: L{transport.TransportError} ...
Request failed, process reply based on reason @param binding: The binding to be used to process the reply. @type binding: L{suds.bindings.binding.Binding} @param error: The http error message @type error: L{transport.TransportError}
entailment
def _get_line_no_from_comments(py_line): """Return the line number parsed from the comment or 0.""" matched = LINECOL_COMMENT_RE.match(py_line) if matched: return int(matched.group(1)) else: return 0
Return the line number parsed from the comment or 0.
entailment
def _find_bounds(py_line_no, py_by_line_no, cheetah_by_line_no): """Searches before and after in the python source to find comments which denote cheetah line numbers. If a lower bound is not found, 0 is substituted. If an upper bound is not found, len(cheetah lines) is returned. The result is a lower...
Searches before and after in the python source to find comments which denote cheetah line numbers. If a lower bound is not found, 0 is substituted. If an upper bound is not found, len(cheetah lines) is returned. The result is a lower-inclusive upper-exclusive range: [..., ...)
entailment
def _find_fuzzy_line( py_line_no, py_by_line_no, cheetah_by_line_no, prefer_first ): """Attempt to fuzzily find matching lines.""" stripped_line = _fuzz_py_line(py_by_line_no[py_line_no]) cheetah_lower_bound, cheetah_upper_bound = _find_bounds( py_line_no, py_by_line_no, cheetah_by_line_no, ...
Attempt to fuzzily find matching lines.
entailment
def perform_step(file_contents, step): """Performs a step of the transformation. :param text file_contents: Contends of the cheetah template :param function step: Function taking xmldoc and returning new contents :returns: new contents of the file. """ assert type(file_contents) is not bytes ...
Performs a step of the transformation. :param text file_contents: Contends of the cheetah template :param function step: Function taking xmldoc and returning new contents :returns: new contents of the file.
entailment
def _get_sender(*sender_params, **kwargs): """ Utility function acting as a Sender factory - ensures senders don't get created twice of more for the same target server """ notify_func = kwargs['notify_func'] with _sender_instances_lock: existing_sender = _sender_instances.get(sender_para...
Utility function acting as a Sender factory - ensures senders don't get created twice of more for the same target server
entailment
def terminate(): """ Stops all the active Senders by flushing the buffers and closing the underlying sockets """ with _sender_instances_lock: for sender_key, sender in _sender_instances.items(): sender.close() _sender_instances.clear()
Stops all the active Senders by flushing the buffers and closing the underlying sockets
entailment
def _format_event(self, orig_event, external_metadata=None): """ Format the event to the expected Alooma format, packing it into a message field and adding metadata :param orig_event: The original event that was sent, should be dict, str or unic...
Format the event to the expected Alooma format, packing it into a message field and adding metadata :param orig_event: The original event that was sent, should be dict, str or unicode. :param external_metadata: (Optional) a dict containing metadata to ...
entailment
def report(self, event, metadata=None, block=None): """ Reports an event to Alooma by formatting it properly and placing it in the buffer to be sent by the Sender instance :param event: A dict / string representing an event :param metadata: (Optional) A dict with extra metadat...
Reports an event to Alooma by formatting it properly and placing it in the buffer to be sent by the Sender instance :param event: A dict / string representing an event :param metadata: (Optional) A dict with extra metadata to be attached to the event :param bl...
entailment
def report_many(self, event_list, metadata=None, block=None): """ Reports all the given events to Alooma by formatting them properly and placing them in the buffer to be sent by the Sender instance :param event_list: A list of dicts / strings representing events :param metadata: ...
Reports all the given events to Alooma by formatting them properly and placing them in the buffer to be sent by the Sender instance :param event_list: A list of dicts / strings representing events :param metadata: (Optional) A dict with extra metadata to be attached to t...
entailment
def _notify(self, log_level, message): """ Calls the callback function and logs messages using the PySDK logger :param log_level: An integer representing the log level, as specified in the Python `logging` library :param message: The actual message to be sent ...
Calls the callback function and logs messages using the PySDK logger :param log_level: An integer representing the log level, as specified in the Python `logging` library :param message: The actual message to be sent to the logger and the `callback` ...
entailment
def _choose_host(self): """ This method randomly chooses a server from the server list given as a parameter to the parent PythonSDK :return: The selected host to which the Sender will attempt to connect """ # If a host hasn't been chosen yet or there is o...
This method randomly chooses a server from the server list given as a parameter to the parent PythonSDK :return: The selected host to which the Sender will attempt to connect
entailment
def _verify_connection(self): """ Checks availability of the Alooma server :return: If the server is reachable, returns True :raises: If connection fails, raises exceptions.ConnectionFailed """ try: res = self._session.get(self._connection_validation_url, json...
Checks availability of the Alooma server :return: If the server is reachable, returns True :raises: If connection fails, raises exceptions.ConnectionFailed
entailment
def _verify_token(self): """ Verifies the validity of the token against the remote server :return: True if the token is valid, else raises exceptions.BadToken """ res = self._session.get(self._token_verification_url) if not res.ok: raise exceptions.BadToken(co...
Verifies the validity of the token against the remote server :return: True if the token is valid, else raises exceptions.BadToken
entailment
def _send_batch(self, batch): """ Sends a batch to the destination server via HTTP REST API """ try: json_batch = '[' + ','.join(batch) + ']' # Make JSON array string logger.debug(consts.LOG_MSG_SENDING_BATCH, len(batch), len(json_batch),...
Sends a batch to the destination server via HTTP REST API
entailment
def _sender_main(self): """ Runs on a pysdk_sender_thread and handles sending events to the Alooma server. Events are sent every <self._batch_interval> seconds or whenever batch size reaches <self._batch_size> """ if not self._http_host: self._choose_host() ...
Runs on a pysdk_sender_thread and handles sending events to the Alooma server. Events are sent every <self._batch_interval> seconds or whenever batch size reaches <self._batch_size>
entailment
def enqueue_event(self, event, block): """ Enqueues an event in the buffer to be sent to the Alooma server :param event: A dict representing a formatted event to be sent by the sender :param block: Whether or not we should block if the event buffer is full :...
Enqueues an event in the buffer to be sent to the Alooma server :param event: A dict representing a formatted event to be sent by the sender :param block: Whether or not we should block if the event buffer is full :return: True if the event was enqueued successfully, else F...
entailment
def __get_event(self, block=True, timeout=1): """ Retrieves an event. If self._exceeding_event is not None, it'll be returned. Otherwise, an event is dequeued from the event buffer. If The event which was retrieved is bigger than the permitted batch size, it'll be omitted, and th...
Retrieves an event. If self._exceeding_event is not None, it'll be returned. Otherwise, an event is dequeued from the event buffer. If The event which was retrieved is bigger than the permitted batch size, it'll be omitted, and the next event in the event buffer is returned
entailment
def get_links(self, request=None): """ Return a dictionary containing all the links that should be included in the API schema. """ links = LinkNode() # Generate (path, method, view) given (path, method, callback). paths = [] view_endpoints = [] fo...
Return a dictionary containing all the links that should be included in the API schema.
entailment
def get_path_fields(self, path, method, view): """ Return a list of `coreapi.Field` instances corresponding to any templated path variables. """ model = getattr(getattr(view, 'queryset', None), 'model', None) fields = [] for variable in uritemplate.variables(path...
Return a list of `coreapi.Field` instances corresponding to any templated path variables.
entailment
def get_serializer_class(self, view, method_func): """ Try to get the serializer class from view method. If view method don't have request serializer, fallback to serializer_class on view class """ if hasattr(method_func, 'request_serializer'): return getattr(method_f...
Try to get the serializer class from view method. If view method don't have request serializer, fallback to serializer_class on view class
entailment
def fallback_schema_from_field(self, field): """ Fallback schema for field that isn't inspected properly by DRF and probably won't land in upstream canon due to its hacky nature only for doc purposes """ title = force_text(field.label) if field.label else '' description = force_t...
Fallback schema for field that isn't inspected properly by DRF and probably won't land in upstream canon due to its hacky nature only for doc purposes
entailment
def get_serializer_fields(self, path, method, view, version=None, method_func=None): """ Return a list of `coreapi.Field` instances corresponding to any request body input, as determined by the serializer class. """ if method in ('PUT', 'PATCH', 'POST'): location = 'f...
Return a list of `coreapi.Field` instances corresponding to any request body input, as determined by the serializer class.
entailment
def update(self, instance, validated_data): """ Update and return an existing `Snippet` instance, given the validated data. """ instance.title = validated_data.get('title', instance.title) instance.code = validated_data.get('code', instance.code) instance.linenos = valida...
Update and return an existing `Snippet` instance, given the validated data.
entailment
def _generate_openapi_object(document): """ Generates root of the Swagger spec. """ parsed_url = urlparse.urlparse(document.url) swagger = OrderedDict() swagger['swagger'] = '2.0' swagger['info'] = OrderedDict() swagger['info']['title'] = document.title swagger['info']['description...
Generates root of the Swagger spec.
entailment
def _get_responses(link): """ Returns an OpenApi-compliant response """ template = link.response_schema template.update({'description': 'Success'}) res = {200: template} res.update(link.error_status_codes) return res
Returns an OpenApi-compliant response
entailment
def _get_parameters(link, encoding): """ Generates Swagger Parameter Item object. """ parameters = [] properties = {} required = [] for field in link.fields: parser = OpenApiFieldParser(link, field) if parser.location == 'form': if encoding in ('multipart/form-da...
Generates Swagger Parameter Item object.
entailment
def auth_uri(self, redirect_uri=None, scope=None, scope_delim=None, state=None, **kwargs): """ Builds the auth URI for the authorization endpoint :param scope: (optional) The `scope` parameter to pass for authorization. The format should match that expected by ...
Builds the auth URI for the authorization endpoint :param scope: (optional) The `scope` parameter to pass for authorization. The format should match that expected by the provider (i.e. Facebook expects comma-delimited, while Google expects space...
entailment
def request_token(self, parser=None, redirect_uri=None, **kwargs): """ Request an access token from the token endpoint. This is largely a helper method and expects the client code to understand what the server expects. Anything that's passed into ``**kwargs`` will be sent (``urlencode``d...
Request an access token from the token endpoint. This is largely a helper method and expects the client code to understand what the server expects. Anything that's passed into ``**kwargs`` will be sent (``urlencode``d) to the endpoint. Client secret and client ID are automatically includ...
entailment
def request(self, url, method=None, data=None, headers=None, parser=None): """ Request user data from the resource endpoint :param url: The path to the resource and querystring if required :param method: HTTP method. Defaults to ``GET`` unless data is not None in which ca...
Request user data from the resource endpoint :param url: The path to the resource and querystring if required :param method: HTTP method. Defaults to ``GET`` unless data is not None in which case it defaults to ``POST`` :param data: Data to be POSTed to the resource endpoi...
entailment
def build_srcdict(gta, prop): """Build a dictionary that maps from source name to the value of a source property Parameters ---------- gta : `fermipy.GTAnalysis` The analysis object prop : str The name of the property we are mapping Returns ------- odict : dict ...
Build a dictionary that maps from source name to the value of a source property Parameters ---------- gta : `fermipy.GTAnalysis` The analysis object prop : str The name of the property we are mapping Returns ------- odict : dict Dictionary that maps from source ...
entailment
def get_src_names(gta): """Build and return a list of source name Parameters ---------- gta : `fermipy.GTAnalysis` The analysis object Returns ------- l : list Names of the source """ o = [] for s in gta.roi.sources: o += [s.name] return sorted(o)
Build and return a list of source name Parameters ---------- gta : `fermipy.GTAnalysis` The analysis object Returns ------- l : list Names of the source
entailment
def set_wts_get_npred_wt(gta, maskname): """Set a weights file and get the weighted npred for all the sources Parameters ---------- gta : `fermipy.GTAnalysis` The analysis object maskname : str The path to the file with the mask Returns ------- odict : dict ...
Set a weights file and get the weighted npred for all the sources Parameters ---------- gta : `fermipy.GTAnalysis` The analysis object maskname : str The path to the file with the mask Returns ------- odict : dict Dictionary mapping from source name to weighted ...
entailment
def snapshot(gta, plotter, key, do_weighted=True, make_plots=True): """Take a snapshot of the ROI Parameters ---------- gta : `fermipy.GTAnalysis` The analysis object plotter : `fermipy.plotting.AnalysisPlotter` The object that makes the plots key : str Key for this s...
Take a snapshot of the ROI Parameters ---------- gta : `fermipy.GTAnalysis` The analysis object plotter : `fermipy.plotting.AnalysisPlotter` The object that makes the plots key : str Key for this snapshot, used to create filenames do_weighted : bool If True, ...
entailment
def get_unchanged(src_list, npred_dict_new, npred_dict_old, npred_threshold=1e4, frac_threshold=0.9): """Compare two dictionarys of npreds, and get the list of sources than have changed less that set thresholds Parameters ---------- src_list : ...
Compare two dictionarys of npreds, and get the list of sources than have changed less that set thresholds Parameters ---------- src_list : list List of sources to examine npred_dict_new : dict Dictionary mapping source name to npred for the current weights file npred_dict_old...
entailment
def run_analysis(self, argv): """Run this analysis""" args = self._parser.parse_args(argv) if not HAVE_ST: raise RuntimeError( "Trying to run fermipy analysis, but don't have ST") if args.load_baseline: gta = GTAnalysis.create(args.roi_baseline, ...
Run this analysis
entailment
def build_job_configs(self, args): """Hook to build job configurations """ job_configs = {} # Tweak the batch job args try: self._interface._lsf_args.update(dict(n=2)) self._interface._lsf_args.update(dict(R='\"select[rhel60&&!fell] -R span[hosts=1]\"')) ...
Hook to build job configurations
entailment
def main(): """ Main function for command line usage """ usage = "usage: %(prog)s [options] " description = "Merge a set of Fermi-LAT files." parser = argparse.ArgumentParser(usage=usage, description=description) parser.add_argument('-o', '--output', default=None, type=str, ...
Main function for command line usage
entailment
def get_native_default_args(): """ Get the correct set of batch jobs arguments. """ native_default_args = dict(max_jobs=500, time_per_cycle=15, jobs_per_cycle=20, max_job_age=90, no_ba...
Get the correct set of batch jobs arguments.
entailment
def dispatch_job_hook(self, link, key, job_config, logfile, stream=sys.stdout): """Send a single job to be executed Parameters ---------- link : `fermipy.jobs.chain.Link` The link used to invoke the command we are running key : str A string that identif...
Send a single job to be executed Parameters ---------- link : `fermipy.jobs.chain.Link` The link used to invoke the command we are running key : str A string that identifies this particular instance of the job job_config : dict A dictionrar...
entailment
def log_level(level): """This is a function that returns a python like level from a HEASOFT like level. """ levels_dict = {0: 50, 1: 40, 2: 30, 3: 20, 4: 10} if not isinstance(level, int): level = int(level) i...
This is a function that returns a python like level from a HEASOFT like level.
entailment
def setup(config=None, logfile=None): """This method sets up the default configuration of the logger. Once this method is called all subsequent instances Logger instances will inherit this configuration.""" if config is None: configpath = os.path.join(fermipy.PACKAGE_ROOT, ...
This method sets up the default configuration of the logger. Once this method is called all subsequent instances Logger instances will inherit this configuration.
entailment
def configure(name, logfile, loglevel=logging.DEBUG): """Create a python logger instance and configure it. Parameters ---------- name : str Logger name. logfile : str Path to the log file. loglevel : int Default log level for STDOUT....
Create a python logger instance and configure it. Parameters ---------- name : str Logger name. logfile : str Path to the log file. loglevel : int Default log level for STDOUT.
entailment
def extract_arguments(args, defaults): """Extract a set of arguments from a large dictionary Parameters ---------- args : dict Dictionary with the arguments values to use defaults : dict Dictionary with all the argument to extract, and default values for each Returns ----...
Extract a set of arguments from a large dictionary Parameters ---------- args : dict Dictionary with the arguments values to use defaults : dict Dictionary with all the argument to extract, and default values for each Returns ------- out_dict : dict A dictionary ...
entailment
def check_files(filelist, file_stage_manager=None, return_found=True, return_missing=True): """Check that all files in a list exist Parameters ---------- filelist : list The list of files we are checking for. file_stage_manager : `fermipy.jo...
Check that all files in a list exist Parameters ---------- filelist : list The list of files we are checking for. file_stage_manager : `fermipy.jobs.file_archive.FileStageManager` A object that maps files to scratch space if needed. return_found : list A list with the pat...
entailment
def add_argument(parser, dest, info): """ Add an argument to an `argparse.ArgumentParser` object Parameters ---------- parser : `argparse.ArgumentParser` The parser in question dest : str The destination for the argument info : `tuple` The information associated with t...
Add an argument to an `argparse.ArgumentParser` object Parameters ---------- parser : `argparse.ArgumentParser` The parser in question dest : str The destination for the argument info : `tuple` The information associated with the argument in question.
entailment
def convert_dict_to_option_dict(input_dict): """Convert a simple key-value dictionary to a dictionary of options tuples""" ret_dict = {} for key, value in input_dict.items(): ret_dict[key] = convert_value_to_option_tuple(value) return ret_dict
Convert a simple key-value dictionary to a dictionary of options tuples
entailment
def convert_option_dict_to_dict(option_dict): """Convert a dictionary of options tuples to a simple key-value dictionary""" ret_dict = {} for key, value in option_dict.items(): if is_null(value): ret_dict[key] = None elif isinstance(value, tuple): ret_dict[key] = valu...
Convert a dictionary of options tuples to a simple key-value dictionary
entailment
def reduce_by_keys(orig_dict, keys, default=None): """Reduce a dictionary by selecting a set of keys """ ret = {} for key in keys: ret[key] = orig_dict.get(key, default) return ret
Reduce a dictionary by selecting a set of keys
entailment
def construct_docstring(options): """Construct a docstring for a set of options""" s = "\nParameters\n" s += "----------\n\n" for key, opt in options.items(): s += "%s : %s\n %s [%s]\n" % (key, str(opt[2]), str(opt[1]), str(...
Construct a docstring for a set of options
entailment
def register_class(cls): """Regsiter this class in the `LinkFactory` """ if cls.appname in LinkFactory._class_dict: return LinkFactory.register(cls.appname, cls)
Regsiter this class in the `LinkFactory`
entailment
def _fill_argparser(self, parser): """Fill an `argparser.ArgumentParser` with the options from this chain """ for key, val in self._options.items(): add_argument(parser, key, val)
Fill an `argparser.ArgumentParser` with the options from this chain
entailment
def _run_argparser(self, argv): """Initialize a link with a set of arguments using an `argparser.ArgumentParser` """ if self._parser is None: raise ValueError('Link was not given a parser on initialization') args = self._parser.parse_args(argv) self.update_args(args._...
Initialize a link with a set of arguments using an `argparser.ArgumentParser`
entailment
def _latch_file_info(self): """Internal function to update the dictionaries keeping track of input and output files """ self.files.file_dict.clear() self.files.latch_file_info(self.args)
Internal function to update the dictionaries keeping track of input and output files
entailment
def _update_sub_file_dict(self, sub_files): """Update a file dict with information from self""" sub_files.file_dict.clear() for job_details in self.jobs.values(): if job_details.file_dict is not None: sub_files.update(job_details.file_dict) if job_details....
Update a file dict with information from self
entailment
def _pre_run_checks(self, stream=sys.stdout, dry_run=False): """Do some checks before running this link This checks if input and output files are present. If input files are missing this will raise `OSError` if dry_run is False If all output files are present this return False. ...
Do some checks before running this link This checks if input and output files are present. If input files are missing this will raise `OSError` if dry_run is False If all output files are present this return False. Parameters ----------- stream : `file` Str...
entailment
def _create_job_details(self, key, job_config, logfile, status): """Create a `JobDetails` for a single job Parameters ---------- key : str Key used to identify this particular job job_config : dict Dictionary with arguements passed to this particular jo...
Create a `JobDetails` for a single job Parameters ---------- key : str Key used to identify this particular job job_config : dict Dictionary with arguements passed to this particular job logfile : str Name of the associated log file ...
entailment
def _map_scratch_files(self, file_dict): """Build and return the mapping for copying files to and from scratch area""" if self._file_stage is None: return ({}, {}) input_files = file_dict.input_files_to_stage output_files = file_dict.output_files_to_stage input_file_m...
Build and return the mapping for copying files to and from scratch area
entailment
def _update_file_args(self, file_mapping): """Adjust the arguments to deal with staging files to the scratch area""" for key, value in self.args.items(): new_value = file_mapping.get(value, value) if new_value != value: self.args[key] = new_value
Adjust the arguments to deal with staging files to the scratch area
entailment
def _stage_input_files(self, file_mapping, dry_run=True): """Stage the input files to the scratch area and adjust the arguments accordingly""" # print ("Staging input ", file_mapping) if self._file_stage is None: return self._file_stage.copy_to_scratch(file_mapping, dry_run)
Stage the input files to the scratch area and adjust the arguments accordingly
entailment
def _stage_output_files(self, file_mapping, dry_run=True): """Stage the output files to the scratch area and adjust the arguments accordingly""" # print ("Staging output ", file_mapping) if self._file_stage is None: return self._file_stage.copy_from_scratch(file_mapping, dry_...
Stage the output files to the scratch area and adjust the arguments accordingly
entailment
def _run_link(self, stream=sys.stdout, dry_run=False, stage_files=True, resubmit_failed=False): """Internal function that actually runs this link. This checks if input and output files are present. If input files are missing this will raise `OSError` if dry_run is False ...
Internal function that actually runs this link. This checks if input and output files are present. If input files are missing this will raise `OSError` if dry_run is False If all output files are present this will skip execution. Parameters ----------- stream : `file` ...
entailment
def _register_job(self, key, job_config, logfile, status): """Create a `JobDetails` for this link and add it to the self.jobs dictionary. Parameters ---------- key : str Key used to identify this particular job job_config : dict Dictionary with ...
Create a `JobDetails` for this link and add it to the self.jobs dictionary. Parameters ---------- key : str Key used to identify this particular job job_config : dict Dictionary with arguments passed to this particular job logfile : str ...
entailment