code stringlengths 70 11.9k | docstring stringlengths 4 7.08k | text stringlengths 128 15k |
|---|---|---|
def requires(self):
reqs = OrderedDict()
reqs.update(self.task.workflow_requires())
return reqs | Returns the default workflow requirements in an ordered dictionary, which is updated with
the return value of the task's *workflow_requires* method. | ### Input:
Returns the default workflow requirements in an ordered dictionary, which is updated with
the return value of the task's *workflow_requires* method.
### Response:
def requires(self):
reqs = OrderedDict()
reqs.update(self.task.workflow_requires())
return reqs |
def get_fragment_language() -> ParserElement:
_fragment_value_inner = fragment_range | missing_fragment(FRAGMENT_MISSING)
_fragment_value = _fragment_value_inner | And([Suppress(), _fragment_value_inner, Suppress()])
parser_element = fragment_tag + nest(_fragment_value + Optional(WCW + quote(FRAGMENT_DESCRIPTION)))
return parser_element | Build a protein fragment parser. | ### Input:
Build a protein fragment parser.
### Response:
def get_fragment_language() -> ParserElement:
_fragment_value_inner = fragment_range | missing_fragment(FRAGMENT_MISSING)
_fragment_value = _fragment_value_inner | And([Suppress(), _fragment_value_inner, Suppress()])
parser_element = fragment_tag + nest(_fragment_value + Optional(WCW + quote(FRAGMENT_DESCRIPTION)))
return parser_element |
def export_instance(self, instance, body, project_id=None):
try:
response = self.get_conn().instances().export(
project=project_id,
instance=instance,
body=body
).execute(num_retries=self.num_retries)
operation_name = response["name"]
self._wait_for_operation_to_complete(project_id=project_id,
operation_name=operation_name)
except HttpError as ex:
raise AirflowException(
.format(instance, ex.content)
) | Exports data from a Cloud SQL instance to a Cloud Storage bucket as a SQL dump
or CSV file.
:param instance: Database instance ID of the Cloud SQL instance. This does not include the
project ID.
:type instance: str
:param body: The request body, as described in
https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/instances/export#request-body
:type body: dict
:param project_id: Project ID of the project that contains the instance. If set
to None or missing, the default project_id from the GCP connection is used.
:type project_id: str
:return: None | ### Input:
Exports data from a Cloud SQL instance to a Cloud Storage bucket as a SQL dump
or CSV file.
:param instance: Database instance ID of the Cloud SQL instance. This does not include the
project ID.
:type instance: str
:param body: The request body, as described in
https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/instances/export#request-body
:type body: dict
:param project_id: Project ID of the project that contains the instance. If set
to None or missing, the default project_id from the GCP connection is used.
:type project_id: str
:return: None
### Response:
def export_instance(self, instance, body, project_id=None):
try:
response = self.get_conn().instances().export(
project=project_id,
instance=instance,
body=body
).execute(num_retries=self.num_retries)
operation_name = response["name"]
self._wait_for_operation_to_complete(project_id=project_id,
operation_name=operation_name)
except HttpError as ex:
raise AirflowException(
.format(instance, ex.content)
) |
def update_sample_for_autocreated_cohorts(instance, created, **kwargs):
"Manages adding/removing samples from autocreated cohorts."
lookup = {: None, : None, : True,
: }
try:
world_cohort = Cohort.objects.get(**lookup)
except Cohort.DoesNotExist:
if getattr(settings, , True):
world_cohort = Cohort(**lookup)
world_cohort.save()
else:
log.info("World cohort was not found and was not created because "
"VARIFY_AUTO_CREATE_COHORT setting is False.")
return
project = instance.project
lookup = {: None, : project, : True}
try:
project_cohort = Cohort.objects.get(**lookup)
except Cohort.DoesNotExist:
project_cohort = Cohort(name=unicode(project), **lookup)
project_cohort.save()
if instance.published:
world_cohort.add(instance, added=False)
project_cohort.add(instance, added=False)
else:
world_cohort.remove(instance, delete=True)
project_cohort.remove(instance, delete=True) | Manages adding/removing samples from autocreated cohorts. | ### Input:
Manages adding/removing samples from autocreated cohorts.
### Response:
def update_sample_for_autocreated_cohorts(instance, created, **kwargs):
"Manages adding/removing samples from autocreated cohorts."
lookup = {: None, : None, : True,
: }
try:
world_cohort = Cohort.objects.get(**lookup)
except Cohort.DoesNotExist:
if getattr(settings, , True):
world_cohort = Cohort(**lookup)
world_cohort.save()
else:
log.info("World cohort was not found and was not created because "
"VARIFY_AUTO_CREATE_COHORT setting is False.")
return
project = instance.project
lookup = {: None, : project, : True}
try:
project_cohort = Cohort.objects.get(**lookup)
except Cohort.DoesNotExist:
project_cohort = Cohort(name=unicode(project), **lookup)
project_cohort.save()
if instance.published:
world_cohort.add(instance, added=False)
project_cohort.add(instance, added=False)
else:
world_cohort.remove(instance, delete=True)
project_cohort.remove(instance, delete=True) |
async def _connect(self):
logger.debug("connecting to the stream")
await self.client.setup
if self.session is None:
self.session = self.client._session
kwargs = await self.client.headers.prepare_request(**self.kwargs)
request = self.client.error_handler(self.session.request)
return await request(timeout=0, **kwargs) | Connect to the stream
Returns
-------
asyncio.coroutine
The streaming response | ### Input:
Connect to the stream
Returns
-------
asyncio.coroutine
The streaming response
### Response:
async def _connect(self):
logger.debug("connecting to the stream")
await self.client.setup
if self.session is None:
self.session = self.client._session
kwargs = await self.client.headers.prepare_request(**self.kwargs)
request = self.client.error_handler(self.session.request)
return await request(timeout=0, **kwargs) |
def discover_gateways(self):
_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
_socket.settimeout(5.0)
if self._interface != :
_socket.bind((self._interface, 0))
for gateway in self._gateways_config:
host = gateway.get()
port = gateway.get()
sid = gateway.get()
if not (host and port and sid):
continue
try:
ip_address = socket.gethostbyname(host)
if gateway.get():
_LOGGER.info(
, sid)
self.disabled_gateways.append(ip_address)
continue
_LOGGER.info(
,
sid, ip_address, port)
self.gateways[ip_address] = XiaomiGateway(
ip_address, port, sid,
gateway.get(), self._device_discovery_retries,
self._interface, gateway.get())
except OSError as error:
_LOGGER.error(
"Could not resolve %s: %s", host, error)
try:
_socket.sendto(.encode(),
(self.MULTICAST_ADDRESS, self.GATEWAY_DISCOVERY_PORT))
while True:
data, (ip_add, _) = _socket.recvfrom(1024)
if len(data) is None or ip_add in self.gateways:
continue
if ip_add in self.gateways.keys() or ip_add in self.disabled_gateways:
continue
resp = json.loads(data.decode())
if resp["cmd"] != :
_LOGGER.error("Response does not match return cmd")
continue
if resp["model"] not in GATEWAY_MODELS:
_LOGGER.error("Response must be gateway model")
continue
disabled = False
gateway_key = None
for gateway in self._gateways_config:
sid = gateway.get()
if sid is None or sid == resp["sid"]:
gateway_key = gateway.get()
if sid and sid == resp[] and gateway.get():
disabled = True
sid = resp["sid"]
if disabled:
_LOGGER.info("Xiaomi Gateway %s is disabled by configuration",
sid)
self.disabled_gateways.append(ip_add)
else:
_LOGGER.info(, sid, ip_add)
self.gateways[ip_add] = XiaomiGateway(
ip_add, resp["port"], sid, gateway_key,
self._device_discovery_retries, self._interface,
resp["proto_version"] if "proto_version" in resp else None)
except socket.timeout:
_LOGGER.info("Gateway discovery finished in 5 seconds")
_socket.close() | Discover gateways using multicast | ### Input:
Discover gateways using multicast
### Response:
def discover_gateways(self):
_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
_socket.settimeout(5.0)
if self._interface != :
_socket.bind((self._interface, 0))
for gateway in self._gateways_config:
host = gateway.get()
port = gateway.get()
sid = gateway.get()
if not (host and port and sid):
continue
try:
ip_address = socket.gethostbyname(host)
if gateway.get():
_LOGGER.info(
, sid)
self.disabled_gateways.append(ip_address)
continue
_LOGGER.info(
,
sid, ip_address, port)
self.gateways[ip_address] = XiaomiGateway(
ip_address, port, sid,
gateway.get(), self._device_discovery_retries,
self._interface, gateway.get())
except OSError as error:
_LOGGER.error(
"Could not resolve %s: %s", host, error)
try:
_socket.sendto(.encode(),
(self.MULTICAST_ADDRESS, self.GATEWAY_DISCOVERY_PORT))
while True:
data, (ip_add, _) = _socket.recvfrom(1024)
if len(data) is None or ip_add in self.gateways:
continue
if ip_add in self.gateways.keys() or ip_add in self.disabled_gateways:
continue
resp = json.loads(data.decode())
if resp["cmd"] != :
_LOGGER.error("Response does not match return cmd")
continue
if resp["model"] not in GATEWAY_MODELS:
_LOGGER.error("Response must be gateway model")
continue
disabled = False
gateway_key = None
for gateway in self._gateways_config:
sid = gateway.get()
if sid is None or sid == resp["sid"]:
gateway_key = gateway.get()
if sid and sid == resp[] and gateway.get():
disabled = True
sid = resp["sid"]
if disabled:
_LOGGER.info("Xiaomi Gateway %s is disabled by configuration",
sid)
self.disabled_gateways.append(ip_add)
else:
_LOGGER.info(, sid, ip_add)
self.gateways[ip_add] = XiaomiGateway(
ip_add, resp["port"], sid, gateway_key,
self._device_discovery_retries, self._interface,
resp["proto_version"] if "proto_version" in resp else None)
except socket.timeout:
_LOGGER.info("Gateway discovery finished in 5 seconds")
_socket.close() |
def get_model(app_label, model_name):
try:
from django.apps import apps
from django.core.exceptions import AppRegistryNotReady
except ImportError:
from django.db import models
return models.get_model(app_label, model_name)
try:
return apps.get_model(app_label, model_name)
except AppRegistryNotReady:
if apps.apps_ready and not apps.models_ready:
app_config = apps.get_app_config(app_label)
import_module("%s.%s" % (app_config.name, "models"))
return apps.get_registered_model(app_label, model_name)
else:
raise | Fetches a Django model using the app registry.
This doesn't require that an app with the given app label exists, which
makes it safe to call when the registry is being populated. All other
methods to access models might raise an exception about the registry not
being ready yet.
Raises LookupError if model isn't found. | ### Input:
Fetches a Django model using the app registry.
This doesn't require that an app with the given app label exists, which
makes it safe to call when the registry is being populated. All other
methods to access models might raise an exception about the registry not
being ready yet.
Raises LookupError if model isn't found.
### Response:
def get_model(app_label, model_name):
try:
from django.apps import apps
from django.core.exceptions import AppRegistryNotReady
except ImportError:
from django.db import models
return models.get_model(app_label, model_name)
try:
return apps.get_model(app_label, model_name)
except AppRegistryNotReady:
if apps.apps_ready and not apps.models_ready:
app_config = apps.get_app_config(app_label)
import_module("%s.%s" % (app_config.name, "models"))
return apps.get_registered_model(app_label, model_name)
else:
raise |
def delete_collection_namespaced_job(self, namespace, **kwargs):
kwargs[] = True
if kwargs.get():
return self.delete_collection_namespaced_job_with_http_info(namespace, **kwargs)
else:
(data) = self.delete_collection_namespaced_job_with_http_info(namespace, **kwargs)
return data | delete collection of Job
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_collection_namespaced_job(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:return: V1Status
If the method is called asynchronously,
returns the request thread. | ### Input:
delete collection of Job
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_collection_namespaced_job(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
### Response:
def delete_collection_namespaced_job(self, namespace, **kwargs):
kwargs[] = True
if kwargs.get():
return self.delete_collection_namespaced_job_with_http_info(namespace, **kwargs)
else:
(data) = self.delete_collection_namespaced_job_with_http_info(namespace, **kwargs)
return data |
def start(self):
if self.is_started:
raise ConnectionError("Client has already been started")
if self.BOT_TOKEN_RE.match(self.session_name):
self.is_bot = True
self.bot_token = self.session_name
self.session_name = self.session_name.split(":")[0]
log.warning(
)
self.load_config()
self.load_session()
self.load_plugins()
self.session = Session(
self,
self.dc_id,
self.auth_key
)
self.session.start()
self.is_started = True
try:
if self.user_id is None:
if self.bot_token is None:
self.is_bot = False
self.authorize_user()
else:
self.is_bot = True
self.authorize_bot()
self.save_session()
if not self.is_bot:
if self.takeout:
self.takeout_id = self.send(functions.account.InitTakeoutSession()).id
log.warning("Takeout session {} initiated".format(self.takeout_id))
now = time.time()
if abs(now - self.date) > Client.OFFLINE_SLEEP:
self.peers_by_username = {}
self.peers_by_phone = {}
self.get_initial_dialogs()
self.get_contacts()
else:
self.send(functions.messages.GetPinnedDialogs())
self.get_initial_dialogs_chunk()
else:
self.send(functions.updates.GetState())
except Exception as e:
self.is_started = False
self.session.stop()
raise e
for i in range(self.UPDATES_WORKERS):
self.updates_workers_list.append(
Thread(
target=self.updates_worker,
name="UpdatesWorker
)
)
self.updates_workers_list[-1].start()
for i in range(self.DOWNLOAD_WORKERS):
self.download_workers_list.append(
Thread(
target=self.download_worker,
name="DownloadWorker
)
)
self.download_workers_list[-1].start()
self.dispatcher.start()
mimetypes.init()
Syncer.add(self)
return self | Use this method to start the Client after creating it.
Requires no parameters.
Raises:
:class:`RPCError <pyrogram.RPCError>` in case of a Telegram RPC error.
``ConnectionError`` in case you try to start an already started Client. | ### Input:
Use this method to start the Client after creating it.
Requires no parameters.
Raises:
:class:`RPCError <pyrogram.RPCError>` in case of a Telegram RPC error.
``ConnectionError`` in case you try to start an already started Client.
### Response:
def start(self):
if self.is_started:
raise ConnectionError("Client has already been started")
if self.BOT_TOKEN_RE.match(self.session_name):
self.is_bot = True
self.bot_token = self.session_name
self.session_name = self.session_name.split(":")[0]
log.warning(
)
self.load_config()
self.load_session()
self.load_plugins()
self.session = Session(
self,
self.dc_id,
self.auth_key
)
self.session.start()
self.is_started = True
try:
if self.user_id is None:
if self.bot_token is None:
self.is_bot = False
self.authorize_user()
else:
self.is_bot = True
self.authorize_bot()
self.save_session()
if not self.is_bot:
if self.takeout:
self.takeout_id = self.send(functions.account.InitTakeoutSession()).id
log.warning("Takeout session {} initiated".format(self.takeout_id))
now = time.time()
if abs(now - self.date) > Client.OFFLINE_SLEEP:
self.peers_by_username = {}
self.peers_by_phone = {}
self.get_initial_dialogs()
self.get_contacts()
else:
self.send(functions.messages.GetPinnedDialogs())
self.get_initial_dialogs_chunk()
else:
self.send(functions.updates.GetState())
except Exception as e:
self.is_started = False
self.session.stop()
raise e
for i in range(self.UPDATES_WORKERS):
self.updates_workers_list.append(
Thread(
target=self.updates_worker,
name="UpdatesWorker
)
)
self.updates_workers_list[-1].start()
for i in range(self.DOWNLOAD_WORKERS):
self.download_workers_list.append(
Thread(
target=self.download_worker,
name="DownloadWorker
)
)
self.download_workers_list[-1].start()
self.dispatcher.start()
mimetypes.init()
Syncer.add(self)
return self |
def generateParams(rawfilepath, outputpath, isolationWindow, coElute):
output = str()
output = .join([output, .join([, rawfilepath])])
output = .join([output, .join([, outputpath])])
output = .join([output, .join([, outputpath])])
output = .join([output, .join([, str(coElute)])])
output = .join([output, .join([, ])])
output = .join([output, .join([,
str(isolationWindow)]
)])
output = .join([output, .join([, ])])
output = .join([output, .join([, ])])
output = .join([output, .join([, ])])
output = .join([output, .join([, ])])
output = .join([output, .join([, ])])
output = .join([output, .join([, ])])
output = .join([output, .join([, ])])
output = .join([output, .join([, ])])
output = .join([output, .join([, ])])
output = .join([output, .join([, ])])
output = .join([output, .join([, ])])
output = .join([output, .join([, ])])
output = .join([output, .join([, ])])
output = .join([output, .join([, ])])
output = .join([output, .join([, ])])
return output | Generates a string containing the parameters for a pParse parameter file
but doesn't write any file yet.
:param rawfilepath: location of the thermo ".raw" file
:param outputpath: path to the output directory of pParse
:param isolationWindow: MSn isolation window that was used for the
aquisition of the specified thermo raw file
:param coElute: 0 or 1, see "[Advanced Options]" below
:returns: string containing pParse parameters
.. note:
# pParse.para params template
# For help: mail to tuhuijun@ict.ac.cn
# Time: 2014.12.08
[Basic Options]
datapath = C:\filedirectory\filename
logfilepath = C:\filedirectory
outputpath = C:\filedirectory
[Advanced Options]
co-elute = 1
# 0, output single precursor for single scan;
# 1, output all co-eluted precursors.
input_format = raw
# raw / ms1
isolation_width = 1.6
# 2 / 2.5 / 3 / 4
mars_threshold = -0.5
ipv_file = .\IPV.txt
trainingset = EmptyPath
[Internal Switches]
output_mars_y = 0
delete_msn = 0
output_mgf = 1
output_pf = 1
debug_mode = 0
check_activationcenter = 1
output_all_mars_y = 0
rewrite_files = 0
export_unchecked_mono = 0
cut_similiar_mono = 1
mars_model = 4
output_trainingdata = 0 | ### Input:
Generates a string containing the parameters for a pParse parameter file
but doesn't write any file yet.
:param rawfilepath: location of the thermo ".raw" file
:param outputpath: path to the output directory of pParse
:param isolationWindow: MSn isolation window that was used for the
aquisition of the specified thermo raw file
:param coElute: 0 or 1, see "[Advanced Options]" below
:returns: string containing pParse parameters
.. note:
# pParse.para params template
# For help: mail to tuhuijun@ict.ac.cn
# Time: 2014.12.08
[Basic Options]
datapath = C:\filedirectory\filename
logfilepath = C:\filedirectory
outputpath = C:\filedirectory
[Advanced Options]
co-elute = 1
# 0, output single precursor for single scan;
# 1, output all co-eluted precursors.
input_format = raw
# raw / ms1
isolation_width = 1.6
# 2 / 2.5 / 3 / 4
mars_threshold = -0.5
ipv_file = .\IPV.txt
trainingset = EmptyPath
[Internal Switches]
output_mars_y = 0
delete_msn = 0
output_mgf = 1
output_pf = 1
debug_mode = 0
check_activationcenter = 1
output_all_mars_y = 0
rewrite_files = 0
export_unchecked_mono = 0
cut_similiar_mono = 1
mars_model = 4
output_trainingdata = 0
### Response:
def generateParams(rawfilepath, outputpath, isolationWindow, coElute):
output = str()
output = .join([output, .join([, rawfilepath])])
output = .join([output, .join([, outputpath])])
output = .join([output, .join([, outputpath])])
output = .join([output, .join([, str(coElute)])])
output = .join([output, .join([, ])])
output = .join([output, .join([,
str(isolationWindow)]
)])
output = .join([output, .join([, ])])
output = .join([output, .join([, ])])
output = .join([output, .join([, ])])
output = .join([output, .join([, ])])
output = .join([output, .join([, ])])
output = .join([output, .join([, ])])
output = .join([output, .join([, ])])
output = .join([output, .join([, ])])
output = .join([output, .join([, ])])
output = .join([output, .join([, ])])
output = .join([output, .join([, ])])
output = .join([output, .join([, ])])
output = .join([output, .join([, ])])
output = .join([output, .join([, ])])
output = .join([output, .join([, ])])
return output |
def ability(cls, id_, name, function_type, ability_id, general_id=0):
assert function_type in ABILITY_FUNCTIONS
return cls(id_, name, ability_id, general_id, function_type,
FUNCTION_TYPES[function_type], None) | Define a function represented as a game ability. | ### Input:
Define a function represented as a game ability.
### Response:
def ability(cls, id_, name, function_type, ability_id, general_id=0):
assert function_type in ABILITY_FUNCTIONS
return cls(id_, name, ability_id, general_id, function_type,
FUNCTION_TYPES[function_type], None) |
def hash_from_stream(n, hash_stream):
x = to_int64(0x345678)
multiplied = to_int64(1000003)
for i in range(n - 1, -1, -1):
h = next(hash_stream)
if h is -1:
return -1
x = (x ^ h) * multiplied
multiplied += to_int64(82520 + 2 * n)
x += 97531
if x == -1:
return -2
return x | >>> from Redy.Tools.Hash import hash_from_stream
>>> s = iter((1, 2, 3))
>>> assert hash_from_stream(3, iter(s)) == hash((1, 2, 3)) | ### Input:
>>> from Redy.Tools.Hash import hash_from_stream
>>> s = iter((1, 2, 3))
>>> assert hash_from_stream(3, iter(s)) == hash((1, 2, 3))
### Response:
def hash_from_stream(n, hash_stream):
x = to_int64(0x345678)
multiplied = to_int64(1000003)
for i in range(n - 1, -1, -1):
h = next(hash_stream)
if h is -1:
return -1
x = (x ^ h) * multiplied
multiplied += to_int64(82520 + 2 * n)
x += 97531
if x == -1:
return -2
return x |
def herz_me(val):
result = 0
if val.endswith("MHz"):
stripped = val.replace("MHz", "")
strip_fl = float(stripped)
result = strip_fl * 1000000
elif val.endswith("kHz"):
stripped = val.replace("kHz", "")
strip_fl = float(stripped)
result = strip_fl * 1000
elif val.endswith("Hz"):
stripped = val.replace("Hz", "")
result = float(stripped)
return(result) | Return integer value for Hz, translated from (MHz|kHz|Hz). | ### Input:
Return integer value for Hz, translated from (MHz|kHz|Hz).
### Response:
def herz_me(val):
result = 0
if val.endswith("MHz"):
stripped = val.replace("MHz", "")
strip_fl = float(stripped)
result = strip_fl * 1000000
elif val.endswith("kHz"):
stripped = val.replace("kHz", "")
strip_fl = float(stripped)
result = strip_fl * 1000
elif val.endswith("Hz"):
stripped = val.replace("Hz", "")
result = float(stripped)
return(result) |
def create(self):
if self.dirname and not os.path.exists(self.dirname):
os.makedirs(self.dirname) | Creates the directory and all its parent directories if it does not
exist yet | ### Input:
Creates the directory and all its parent directories if it does not
exist yet
### Response:
def create(self):
if self.dirname and not os.path.exists(self.dirname):
os.makedirs(self.dirname) |
def calculateDatasets(self, scene, axes, datasets):
items = self.calculateDatasetItems(scene, datasets)
if not items:
scene.clear()
return
rect = self.buildData()
for dataset, item in items.items():
first = True
pos = None
home = None
ellipses = []
path = QPainterPath()
for value in dataset.values():
pos = self.pointAt(axes, value)
ellipses.append(pos)
if first:
path.moveTo(pos)
first = False
else:
path.lineTo(pos)
item.setPath(path)
item.setBuildData(, ellipses) | Builds the datasets for this renderer. Each renderer will need to
subclass and implemenent this method, otherwise, no data will be
shown in the chart.
:param scene | <XChartScene>
axes | [<
datasets | [<XChartDataset>, ..] | ### Input:
Builds the datasets for this renderer. Each renderer will need to
subclass and implemenent this method, otherwise, no data will be
shown in the chart.
:param scene | <XChartScene>
axes | [<
datasets | [<XChartDataset>, ..]
### Response:
def calculateDatasets(self, scene, axes, datasets):
items = self.calculateDatasetItems(scene, datasets)
if not items:
scene.clear()
return
rect = self.buildData()
for dataset, item in items.items():
first = True
pos = None
home = None
ellipses = []
path = QPainterPath()
for value in dataset.values():
pos = self.pointAt(axes, value)
ellipses.append(pos)
if first:
path.moveTo(pos)
first = False
else:
path.lineTo(pos)
item.setPath(path)
item.setBuildData(, ellipses) |
def _get_config(self, host, port, unix_socket, auth, config_key):
client = self._client(host, port, unix_socket, auth)
if client is None:
return None
config_value = client.config_get(config_key)
del client
return config_value | Return config string from specified Redis instance and config key
:param str host: redis host
:param int port: redis port
:param str host: redis config_key
:rtype: str | ### Input:
Return config string from specified Redis instance and config key
:param str host: redis host
:param int port: redis port
:param str host: redis config_key
:rtype: str
### Response:
def _get_config(self, host, port, unix_socket, auth, config_key):
client = self._client(host, port, unix_socket, auth)
if client is None:
return None
config_value = client.config_get(config_key)
del client
return config_value |
def calc_entropy(phase_space_density_array):
entropy = -_scipy.constants.Boltzmann*_np.log(phase_space_density_array)
return entropy | Calculates the entropy of your system at each point in time
for your given phase space density evolution in time.
Parameters
----------
phase_space_density_array : array
array which represents the phase space density at every point in time
Returns:
-------
entropy : array
The entropy of the particle at every point in time via the phase space density method. | ### Input:
Calculates the entropy of your system at each point in time
for your given phase space density evolution in time.
Parameters
----------
phase_space_density_array : array
array which represents the phase space density at every point in time
Returns:
-------
entropy : array
The entropy of the particle at every point in time via the phase space density method.
### Response:
def calc_entropy(phase_space_density_array):
entropy = -_scipy.constants.Boltzmann*_np.log(phase_space_density_array)
return entropy |
def get_client_token():
if getattr(settings, , ):
return settings.NOMIS_API_CLIENT_TOKEN
global client_token
if not client_token or client_token[] and client_token[] - now() < datetime.timedelta(days=1):
session = None
try:
session = api_client.get_authenticated_api_session(settings.TOKEN_RETRIEVAL_USERNAME,
settings.TOKEN_RETRIEVAL_PASSWORD)
client_token = session.get().json()
except (requests.RequestException, HttpNotFoundError, ValueError, AttributeError):
logger.exception()
return None
finally:
if session and getattr(session, , None):
api_client.revoke_token(session.access_token)
if client_token.get():
client_token[] = parse_datetime(client_token[])
if client_token[] < now():
logger.error()
return None
return client_token[] | Requests and stores the NOMIS API client token from mtp-api | ### Input:
Requests and stores the NOMIS API client token from mtp-api
### Response:
def get_client_token():
if getattr(settings, , ):
return settings.NOMIS_API_CLIENT_TOKEN
global client_token
if not client_token or client_token[] and client_token[] - now() < datetime.timedelta(days=1):
session = None
try:
session = api_client.get_authenticated_api_session(settings.TOKEN_RETRIEVAL_USERNAME,
settings.TOKEN_RETRIEVAL_PASSWORD)
client_token = session.get().json()
except (requests.RequestException, HttpNotFoundError, ValueError, AttributeError):
logger.exception()
return None
finally:
if session and getattr(session, , None):
api_client.revoke_token(session.access_token)
if client_token.get():
client_token[] = parse_datetime(client_token[])
if client_token[] < now():
logger.error()
return None
return client_token[] |
def _proxy(self):
if self._context is None:
self._context = VerificationContext(
self._version,
service_sid=self._solution[],
sid=self._solution[],
)
return self._context | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: VerificationContext for this VerificationInstance
:rtype: twilio.rest.verify.v2.service.verification.VerificationContext | ### Input:
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: VerificationContext for this VerificationInstance
:rtype: twilio.rest.verify.v2.service.verification.VerificationContext
### Response:
def _proxy(self):
if self._context is None:
self._context = VerificationContext(
self._version,
service_sid=self._solution[],
sid=self._solution[],
)
return self._context |
def finetune_classification_cnn(config):
dataset = config[]
x_names = config[]
y_name = config[]
model_dir = config[]
debug = config[]
num_classes = None
if in config.keys():
num_classes = config[]
batch_size = config[][]
train_pct = config[][]
model_save_period = config[][]
data_aug_config = config[]
preproc_config = config[]
iterator_config = config[]
model_config = config[]
base_model_config = model_config[]
optimization_config = config[]
train_config = config[]
generator_image_shape = None
if in data_aug_config.keys():
generator_image_shape = data_aug_config[]
optimizer_name = optimization_config[]
model_params = {}
if in model_config.keys():
model_params = model_config[]
base_model_params = {}
if in base_model_config.keys():
base_model_params = base_model_config[]
if debug:
seed = 108
random.seed(seed)
np.random.seed(seed)
if not os.path.exists(model_dir):
os.mkdir(model_dir)
model_id = utils.gen_experiment_id()
model_dir = os.path.join(model_dir, %(model_id))
if not os.path.exists(model_dir):
os.mkdir(model_dir)
logging.info( %(model_dir))
latest_model_filename = os.path.join(model_dir, )
best_model_filename = os.path.join(model_dir, )
training_config_filename = os.path.join(model_dir, )
config.save(training_config_filename)
dataset = TensorDataset.open(dataset)
indices_filename = os.path.join(model_dir, )
if os.path.exists(indices_filename):
indices = np.load(indices_filename)[].tolist()
train_indices = indices[]
val_indices = indices[]
else:
train_indices, val_indices = dataset.split(train_pct)
indices = np.array({:train_indices,
:val_indices})
np.savez_compressed(indices_filename, indices)
num_train = train_indices.shape[0]
num_val = val_indices.shape[0]
val_steps = int(np.ceil(float(num_val) / batch_size))
train_generator_filename = os.path.join(model_dir, )
val_generator_filename = os.path.join(model_dir, )
if os.path.exists(train_generator_filename):
logging.info()
train_generator = pkl.load(open(train_generator_filename, ))
val_generator = pkl.load(open(val_generator_filename, ))
else:
logging.info()
train_generator = TensorDataGenerator(num_classes=num_classes,
**data_aug_config)
val_generator = TensorDataGenerator(featurewise_center=data_aug_config[],
featurewise_std_normalization=data_aug_config[],
image_shape=generator_image_shape,
num_classes=num_classes)
fit_start = time.time()
train_generator.fit(dataset, x_names, y_name, indices=train_indices, **preproc_config)
val_generator.mean = train_generator.mean
val_generator.std = train_generator.std
val_generator.min_output = train_generator.min_output
val_generator.max_output = train_generator.max_output
val_generator.num_classes = train_generator.num_classes
fit_stop = time.time()
logging.info( %(fit_stop - fit_start))
pkl.dump(train_generator, open(train_generator_filename, ))
pkl.dump(val_generator, open(val_generator_filename, ))
if num_classes is None:
num_classes = int(train_generator.num_classes)
train_iterator = train_generator.flow_from_dataset(dataset, x_names, y_name,
indices=train_indices,
batch_size=batch_size,
**iterator_config)
val_iterator = val_generator.flow_from_dataset(dataset, x_names, y_name,
indices=val_indices,
batch_size=batch_size,
**iterator_config)
base_cnn = ClassificationCNN.open(base_model_config[],
base_model_config[],
input_name=x_names[0],
**base_model_params)
cnn = FinetunedClassificationCNN(base_cnn=base_cnn,
name=,
num_classes=num_classes,
output_name=y_name,
im_preprocessor=val_generator,
**model_params)
cnn.freeze_base_cnn()
if optimizer_name == :
optimizer = SGD(lr=optimization_config[],
momentum=optimization_config[])
elif optimizer_name == :
optimizer = Adam(lr=optimization_config[])
else:
raise ValueError( %(optimizer_name))
model = cnn.model
model.compile(optimizer=optimizer,
loss=optimization_config[],
metrics=optimization_config[])
steps_per_epoch = int(np.ceil(float(num_train) / batch_size))
latest_model_ckpt = ModelCheckpoint(latest_model_filename, period=model_save_period)
best_model_ckpt = ModelCheckpoint(best_model_filename,
save_best_only=True,
period=model_save_period)
train_history_cb = TrainHistory(model_dir)
callbacks = [latest_model_ckpt, best_model_ckpt, train_history_cb]
history = model.fit_generator(train_iterator,
steps_per_epoch=steps_per_epoch,
epochs=train_config[],
callbacks=callbacks,
validation_data=val_iterator,
validation_steps=val_steps,
class_weight=train_config[],
use_multiprocessing=train_config[])
cnn.save(model_dir)
history_filename = os.path.join(model_dir, )
pkl.dump(history.history, open(history_filename, )) | Main function. | ### Input:
Main function.
### Response:
def finetune_classification_cnn(config):
dataset = config[]
x_names = config[]
y_name = config[]
model_dir = config[]
debug = config[]
num_classes = None
if in config.keys():
num_classes = config[]
batch_size = config[][]
train_pct = config[][]
model_save_period = config[][]
data_aug_config = config[]
preproc_config = config[]
iterator_config = config[]
model_config = config[]
base_model_config = model_config[]
optimization_config = config[]
train_config = config[]
generator_image_shape = None
if in data_aug_config.keys():
generator_image_shape = data_aug_config[]
optimizer_name = optimization_config[]
model_params = {}
if in model_config.keys():
model_params = model_config[]
base_model_params = {}
if in base_model_config.keys():
base_model_params = base_model_config[]
if debug:
seed = 108
random.seed(seed)
np.random.seed(seed)
if not os.path.exists(model_dir):
os.mkdir(model_dir)
model_id = utils.gen_experiment_id()
model_dir = os.path.join(model_dir, %(model_id))
if not os.path.exists(model_dir):
os.mkdir(model_dir)
logging.info( %(model_dir))
latest_model_filename = os.path.join(model_dir, )
best_model_filename = os.path.join(model_dir, )
training_config_filename = os.path.join(model_dir, )
config.save(training_config_filename)
dataset = TensorDataset.open(dataset)
indices_filename = os.path.join(model_dir, )
if os.path.exists(indices_filename):
indices = np.load(indices_filename)[].tolist()
train_indices = indices[]
val_indices = indices[]
else:
train_indices, val_indices = dataset.split(train_pct)
indices = np.array({:train_indices,
:val_indices})
np.savez_compressed(indices_filename, indices)
num_train = train_indices.shape[0]
num_val = val_indices.shape[0]
val_steps = int(np.ceil(float(num_val) / batch_size))
train_generator_filename = os.path.join(model_dir, )
val_generator_filename = os.path.join(model_dir, )
if os.path.exists(train_generator_filename):
logging.info()
train_generator = pkl.load(open(train_generator_filename, ))
val_generator = pkl.load(open(val_generator_filename, ))
else:
logging.info()
train_generator = TensorDataGenerator(num_classes=num_classes,
**data_aug_config)
val_generator = TensorDataGenerator(featurewise_center=data_aug_config[],
featurewise_std_normalization=data_aug_config[],
image_shape=generator_image_shape,
num_classes=num_classes)
fit_start = time.time()
train_generator.fit(dataset, x_names, y_name, indices=train_indices, **preproc_config)
val_generator.mean = train_generator.mean
val_generator.std = train_generator.std
val_generator.min_output = train_generator.min_output
val_generator.max_output = train_generator.max_output
val_generator.num_classes = train_generator.num_classes
fit_stop = time.time()
logging.info( %(fit_stop - fit_start))
pkl.dump(train_generator, open(train_generator_filename, ))
pkl.dump(val_generator, open(val_generator_filename, ))
if num_classes is None:
num_classes = int(train_generator.num_classes)
train_iterator = train_generator.flow_from_dataset(dataset, x_names, y_name,
indices=train_indices,
batch_size=batch_size,
**iterator_config)
val_iterator = val_generator.flow_from_dataset(dataset, x_names, y_name,
indices=val_indices,
batch_size=batch_size,
**iterator_config)
base_cnn = ClassificationCNN.open(base_model_config[],
base_model_config[],
input_name=x_names[0],
**base_model_params)
cnn = FinetunedClassificationCNN(base_cnn=base_cnn,
name=,
num_classes=num_classes,
output_name=y_name,
im_preprocessor=val_generator,
**model_params)
cnn.freeze_base_cnn()
if optimizer_name == :
optimizer = SGD(lr=optimization_config[],
momentum=optimization_config[])
elif optimizer_name == :
optimizer = Adam(lr=optimization_config[])
else:
raise ValueError( %(optimizer_name))
model = cnn.model
model.compile(optimizer=optimizer,
loss=optimization_config[],
metrics=optimization_config[])
steps_per_epoch = int(np.ceil(float(num_train) / batch_size))
latest_model_ckpt = ModelCheckpoint(latest_model_filename, period=model_save_period)
best_model_ckpt = ModelCheckpoint(best_model_filename,
save_best_only=True,
period=model_save_period)
train_history_cb = TrainHistory(model_dir)
callbacks = [latest_model_ckpt, best_model_ckpt, train_history_cb]
history = model.fit_generator(train_iterator,
steps_per_epoch=steps_per_epoch,
epochs=train_config[],
callbacks=callbacks,
validation_data=val_iterator,
validation_steps=val_steps,
class_weight=train_config[],
use_multiprocessing=train_config[])
cnn.save(model_dir)
history_filename = os.path.join(model_dir, )
pkl.dump(history.history, open(history_filename, )) |
def _pfp__watch(self, watcher):
if self._pfp__parent is not None and isinstance(self._pfp__parent, Union):
self._pfp__parent._pfp__watch(watcher)
else:
self._pfp__watchers.append(watcher) | Add the watcher to the list of fields that
are watching this field | ### Input:
Add the watcher to the list of fields that
are watching this field
### Response:
def _pfp__watch(self, watcher):
if self._pfp__parent is not None and isinstance(self._pfp__parent, Union):
self._pfp__parent._pfp__watch(watcher)
else:
self._pfp__watchers.append(watcher) |
def transaction(self, *, isolation=, readonly=False,
deferrable=False):
self._check_open()
return transaction.Transaction(self, isolation, readonly, deferrable) | Create a :class:`~transaction.Transaction` object.
Refer to `PostgreSQL documentation`_ on the meaning of transaction
parameters.
:param isolation: Transaction isolation mode, can be one of:
`'serializable'`, `'repeatable_read'`,
`'read_committed'`.
:param readonly: Specifies whether or not this transaction is
read-only.
:param deferrable: Specifies whether or not this transaction is
deferrable.
.. _`PostgreSQL documentation`:
https://www.postgresql.org/docs/
current/static/sql-set-transaction.html | ### Input:
Create a :class:`~transaction.Transaction` object.
Refer to `PostgreSQL documentation`_ on the meaning of transaction
parameters.
:param isolation: Transaction isolation mode, can be one of:
`'serializable'`, `'repeatable_read'`,
`'read_committed'`.
:param readonly: Specifies whether or not this transaction is
read-only.
:param deferrable: Specifies whether or not this transaction is
deferrable.
.. _`PostgreSQL documentation`:
https://www.postgresql.org/docs/
current/static/sql-set-transaction.html
### Response:
def transaction(self, *, isolation=, readonly=False,
deferrable=False):
self._check_open()
return transaction.Transaction(self, isolation, readonly, deferrable) |
def from_signed_raw(cls: Type[CertificationType], signed_raw: str) -> CertificationType:
n = 0
lines = signed_raw.splitlines(True)
version = int(Identity.parse_field("Version", lines[n]))
n += 1
Certification.parse_field("Type", lines[n])
n += 1
currency = Certification.parse_field("Currency", lines[n])
n += 1
pubkey_from = Certification.parse_field("Issuer", lines[n])
n += 1
identity_pubkey = Certification.parse_field("IdtyIssuer", lines[n])
n += 1
identity_uid = Certification.parse_field("IdtyUniqueID", lines[n])
n += 1
identity_timestamp = BlockUID.from_str(Certification.parse_field("IdtyTimestamp", lines[n]))
n += 1
identity_signature = Certification.parse_field("IdtySignature", lines[n])
n += 1
timestamp = BlockUID.from_str(Certification.parse_field("CertTimestamp", lines[n]))
n += 1
signature = Certification.parse_field("Signature", lines[n])
identity = Identity(version, currency, identity_pubkey, identity_uid, identity_timestamp, identity_signature)
return cls(version, currency, pubkey_from, identity, timestamp, signature) | Return Certification instance from signed raw document
:param signed_raw: Signed raw document
:return: | ### Input:
Return Certification instance from signed raw document
:param signed_raw: Signed raw document
:return:
### Response:
def from_signed_raw(cls: Type[CertificationType], signed_raw: str) -> CertificationType:
n = 0
lines = signed_raw.splitlines(True)
version = int(Identity.parse_field("Version", lines[n]))
n += 1
Certification.parse_field("Type", lines[n])
n += 1
currency = Certification.parse_field("Currency", lines[n])
n += 1
pubkey_from = Certification.parse_field("Issuer", lines[n])
n += 1
identity_pubkey = Certification.parse_field("IdtyIssuer", lines[n])
n += 1
identity_uid = Certification.parse_field("IdtyUniqueID", lines[n])
n += 1
identity_timestamp = BlockUID.from_str(Certification.parse_field("IdtyTimestamp", lines[n]))
n += 1
identity_signature = Certification.parse_field("IdtySignature", lines[n])
n += 1
timestamp = BlockUID.from_str(Certification.parse_field("CertTimestamp", lines[n]))
n += 1
signature = Certification.parse_field("Signature", lines[n])
identity = Identity(version, currency, identity_pubkey, identity_uid, identity_timestamp, identity_signature)
return cls(version, currency, pubkey_from, identity, timestamp, signature) |
def _line_suppresses_error_code(line, code):
match = re.compile(r"suppress\((.*)\)").match(line)
if match:
codes = match.group(1).split(",")
return code in codes
return False | Check if line contains necessary content to suppress code.
A line suppresses code if it is in the format suppress(code1,code2) etc. | ### Input:
Check if line contains necessary content to suppress code.
A line suppresses code if it is in the format suppress(code1,code2) etc.
### Response:
def _line_suppresses_error_code(line, code):
match = re.compile(r"suppress\((.*)\)").match(line)
if match:
codes = match.group(1).split(",")
return code in codes
return False |
def generate_key(filtered_args):
if isinstance(filtered_args, Iterable):
return hash(tuple(filtered_args))
return hash((filtered_args,)) | Get a key from some input.
This function should be used whenever a key is needed, to keep keys
consistent. | ### Input:
Get a key from some input.
This function should be used whenever a key is needed, to keep keys
consistent.
### Response:
def generate_key(filtered_args):
if isinstance(filtered_args, Iterable):
return hash(tuple(filtered_args))
return hash((filtered_args,)) |
def clean_tuple(t0, clean_item_fn=None):
clean_item_fn = clean_item_fn if clean_item_fn else clean_item
l = list()
for index, item in enumerate(t0):
cleaned_item = clean_item_fn(item)
l.append(cleaned_item)
return tuple(l) | Return a json-clean tuple. Will log info message for failures. | ### Input:
Return a json-clean tuple. Will log info message for failures.
### Response:
def clean_tuple(t0, clean_item_fn=None):
clean_item_fn = clean_item_fn if clean_item_fn else clean_item
l = list()
for index, item in enumerate(t0):
cleaned_item = clean_item_fn(item)
l.append(cleaned_item)
return tuple(l) |
def parse_application_name(setup_filename):
with open(setup_filename, ) as setup_file:
fst = RedBaron(setup_file.read())
for node in fst:
if (
node.type == and
str(node.name) ==
):
for call in node.call:
if str(call.name) == :
value = call.value
if hasattr(value, ):
value = value.to_python()
name = str(value)
break
if name:
break
return name | Parse a setup.py file for the name.
Returns:
name, or None | ### Input:
Parse a setup.py file for the name.
Returns:
name, or None
### Response:
def parse_application_name(setup_filename):
with open(setup_filename, ) as setup_file:
fst = RedBaron(setup_file.read())
for node in fst:
if (
node.type == and
str(node.name) ==
):
for call in node.call:
if str(call.name) == :
value = call.value
if hasattr(value, ):
value = value.to_python()
name = str(value)
break
if name:
break
return name |
def commit(*args):
parser = argparse.ArgumentParser(prog="%s %s" % (__package__, commit.__name__), description=commit.__doc__)
parser.add_argument(, help="file(s) to commit", nargs="*", default=[])
args = parser.parse_args(args)
config = FragmentsConfig()
for s, curr_path in _iterate_over_files(args.FILENAME, config, statuses=):
key = os.path.relpath(curr_path, config.root)
if key not in config[]:
yield "Could not commit because it is not being followed" % os.path.relpath(curr_path)
continue
if s in :
repo_path = os.path.join(config.directory, config[][key])
with _smart_open(repo_path, ) as repo_file:
with _smart_open(curr_path, ) as curr_file:
repo_file.write(curr_file.read())
os.utime(repo_path, os.stat(curr_path)[7:9])
yield " committed" % os.path.relpath(curr_path)
elif s == :
yield "Could not commit because it has been removed, instead revert or forget it" % os.path.relpath(curr_path)
elif s == :
yield "Could not commit because it has not been changed" % os.path.relpath(curr_path) | Commit changes to the fragments repository, limited to FILENAME(s) if specified. | ### Input:
Commit changes to the fragments repository, limited to FILENAME(s) if specified.
### Response:
def commit(*args):
parser = argparse.ArgumentParser(prog="%s %s" % (__package__, commit.__name__), description=commit.__doc__)
parser.add_argument(, help="file(s) to commit", nargs="*", default=[])
args = parser.parse_args(args)
config = FragmentsConfig()
for s, curr_path in _iterate_over_files(args.FILENAME, config, statuses=):
key = os.path.relpath(curr_path, config.root)
if key not in config[]:
yield "Could not commit because it is not being followed" % os.path.relpath(curr_path)
continue
if s in :
repo_path = os.path.join(config.directory, config[][key])
with _smart_open(repo_path, ) as repo_file:
with _smart_open(curr_path, ) as curr_file:
repo_file.write(curr_file.read())
os.utime(repo_path, os.stat(curr_path)[7:9])
yield " committed" % os.path.relpath(curr_path)
elif s == :
yield "Could not commit because it has been removed, instead revert or forget it" % os.path.relpath(curr_path)
elif s == :
yield "Could not commit because it has not been changed" % os.path.relpath(curr_path) |
def cumulative_returns(returns, period, freq=None):
if not isinstance(period, pd.Timedelta):
period = pd.Timedelta(period)
if freq is None:
freq = returns.index.freq
if freq is None:
freq = BDay()
warnings.warn(" not set, using business day calendar",
UserWarning)
trades_idx = returns.index.copy()
returns_idx = utils.add_custom_calendar_timedelta(trades_idx, period, freq)
full_idx = trades_idx.union(returns_idx)
for slice_idx in slice:
sub_period = utils.diff_custom_calendar_timedeltas(
pret_idx, slice_idx, freq)
subret[slice_idx] = rate_of_returns(pret, period / sub_period)
subret[pret_idx] = np.nan
subret[slice[1:]] = (subret[slice] + 1).pct_change()[slice[1:]]
sub_returns.append(subret)
trades_idx = trades_idx.difference(sub_index)
sub_portfolios = pd.concat(sub_returns, axis=1)
portfolio = pd.Series(index=sub_portfolios.index)
for i, (index, row) in enumerate(sub_portfolios.iterrows()):
active_subfolios = row.count()
portfolio.iloc[i] = portfolio.iloc[i - 1] if i > 0 else 1.
if active_subfolios <= 0:
continue
portfolio.iloc[i] *= (row + 1).mean(skipna=True)
return portfolio | Builds cumulative returns from 'period' returns. This function simulates
the cumulative effect that a series of gains or losses (the 'returns')
have on an original amount of capital over a period of time.
if F is the frequency at which returns are computed (e.g. 1 day if
'returns' contains daily values) and N is the period for which the retuns
are computed (e.g. returns after 1 day, 5 hours or 3 days) then:
- if N <= F the cumulative retuns are trivially computed as Compound Return
- if N > F (e.g. F 1 day, and N is 3 days) then the returns overlap and the
cumulative returns are computed building and averaging N interleaved sub
portfolios (started at subsequent periods 1,2,..,N) each one rebalancing
every N periods. This correspond to an algorithm which trades the factor
every single time it is computed, which is statistically more robust and
with a lower volatity compared to an algorithm that trades the factor
every N periods and whose returns depend on the specific starting day of
trading.
Also note that when the factor is not computed at a specific frequency, for
exaple a factor representing a random event, it is not efficient to create
multiples sub-portfolios as it is not certain when the factor will be
traded and this would result in an underleveraged portfolio. In this case
the simulated portfolio is fully invested whenever an event happens and if
a subsequent event occur while the portfolio is still invested in a
previous event then the portfolio is rebalanced and split equally among the
active events.
Parameters
----------
returns: pd.Series
pd.Series containing factor 'period' forward returns, the index
contains timestamps at which the trades are computed and the values
correspond to returns after 'period' time
period: pandas.Timedelta or string
Length of period for which the returns are computed (1 day, 2 mins,
3 hours etc). It can be a Timedelta or a string in the format accepted
by Timedelta constructor ('1 days', '1D', '30m', '3h', '1D1h', etc)
freq : pandas DateOffset, optional
Used to specify a particular trading calendar. If not present
returns.index.freq will be used
Returns
-------
Cumulative returns series : pd.Series
Example:
2015-07-16 09:30:00 -0.012143
2015-07-16 12:30:00 0.012546
2015-07-17 09:30:00 0.045350
2015-07-17 12:30:00 0.065897
2015-07-20 09:30:00 0.030957 | ### Input:
Builds cumulative returns from 'period' returns. This function simulates
the cumulative effect that a series of gains or losses (the 'returns')
have on an original amount of capital over a period of time.
if F is the frequency at which returns are computed (e.g. 1 day if
'returns' contains daily values) and N is the period for which the retuns
are computed (e.g. returns after 1 day, 5 hours or 3 days) then:
- if N <= F the cumulative retuns are trivially computed as Compound Return
- if N > F (e.g. F 1 day, and N is 3 days) then the returns overlap and the
cumulative returns are computed building and averaging N interleaved sub
portfolios (started at subsequent periods 1,2,..,N) each one rebalancing
every N periods. This correspond to an algorithm which trades the factor
every single time it is computed, which is statistically more robust and
with a lower volatity compared to an algorithm that trades the factor
every N periods and whose returns depend on the specific starting day of
trading.
Also note that when the factor is not computed at a specific frequency, for
exaple a factor representing a random event, it is not efficient to create
multiples sub-portfolios as it is not certain when the factor will be
traded and this would result in an underleveraged portfolio. In this case
the simulated portfolio is fully invested whenever an event happens and if
a subsequent event occur while the portfolio is still invested in a
previous event then the portfolio is rebalanced and split equally among the
active events.
Parameters
----------
returns: pd.Series
pd.Series containing factor 'period' forward returns, the index
contains timestamps at which the trades are computed and the values
correspond to returns after 'period' time
period: pandas.Timedelta or string
Length of period for which the returns are computed (1 day, 2 mins,
3 hours etc). It can be a Timedelta or a string in the format accepted
by Timedelta constructor ('1 days', '1D', '30m', '3h', '1D1h', etc)
freq : pandas DateOffset, optional
Used to specify a particular trading calendar. If not present
returns.index.freq will be used
Returns
-------
Cumulative returns series : pd.Series
Example:
2015-07-16 09:30:00 -0.012143
2015-07-16 12:30:00 0.012546
2015-07-17 09:30:00 0.045350
2015-07-17 12:30:00 0.065897
2015-07-20 09:30:00 0.030957
### Response:
def cumulative_returns(returns, period, freq=None):
if not isinstance(period, pd.Timedelta):
period = pd.Timedelta(period)
if freq is None:
freq = returns.index.freq
if freq is None:
freq = BDay()
warnings.warn(" not set, using business day calendar",
UserWarning)
trades_idx = returns.index.copy()
returns_idx = utils.add_custom_calendar_timedelta(trades_idx, period, freq)
full_idx = trades_idx.union(returns_idx)
for slice_idx in slice:
sub_period = utils.diff_custom_calendar_timedeltas(
pret_idx, slice_idx, freq)
subret[slice_idx] = rate_of_returns(pret, period / sub_period)
subret[pret_idx] = np.nan
subret[slice[1:]] = (subret[slice] + 1).pct_change()[slice[1:]]
sub_returns.append(subret)
trades_idx = trades_idx.difference(sub_index)
sub_portfolios = pd.concat(sub_returns, axis=1)
portfolio = pd.Series(index=sub_portfolios.index)
for i, (index, row) in enumerate(sub_portfolios.iterrows()):
active_subfolios = row.count()
portfolio.iloc[i] = portfolio.iloc[i - 1] if i > 0 else 1.
if active_subfolios <= 0:
continue
portfolio.iloc[i] *= (row + 1).mean(skipna=True)
return portfolio |
def _collect_images(self, content: str, md_file_path: Path) -> str:
t deal with images outside the project
self.logger.debug(f)
def _sub(image):
image_caption = image.group()
image_path = (md_file_path.parent / Path(image.group())).resolve()
self.logger.debug(f)
if self.working_dir.resolve() not in image_path.parents:
self.logger.debug()
self._collected_imgs_path.mkdir(exist_ok=True)
collected_img_path = (
self._collected_imgs_path/f
).with_suffix(image_path.suffix)
copy(image_path, collected_img_path)
self.logger.debug(f)
rel_img_path = Path(relpath(collected_img_path, md_file_path.parent)).as_posix()
else:
self.logger.debug()
rel_img_path = Path(relpath(image_path, md_file_path.parent)).as_posix()
img_ref = f
self.logger.debug(f)
return img_ref
return self._image_pattern.sub(_sub, content) | Find images outside the source directory, copy them into the source directory,
and replace the paths in the source.
This is necessary because MkDocs can't deal with images outside the project's doc_dir.
:param content: Markdown content
:param md_file_path: Path to the Markdown file with content ``content``
:returns: Markdown content with image paths pointing within the source directory | ### Input:
Find images outside the source directory, copy them into the source directory,
and replace the paths in the source.
This is necessary because MkDocs can't deal with images outside the project's doc_dir.
:param content: Markdown content
:param md_file_path: Path to the Markdown file with content ``content``
:returns: Markdown content with image paths pointing within the source directory
### Response:
def _collect_images(self, content: str, md_file_path: Path) -> str:
t deal with images outside the project
self.logger.debug(f)
def _sub(image):
image_caption = image.group()
image_path = (md_file_path.parent / Path(image.group())).resolve()
self.logger.debug(f)
if self.working_dir.resolve() not in image_path.parents:
self.logger.debug()
self._collected_imgs_path.mkdir(exist_ok=True)
collected_img_path = (
self._collected_imgs_path/f
).with_suffix(image_path.suffix)
copy(image_path, collected_img_path)
self.logger.debug(f)
rel_img_path = Path(relpath(collected_img_path, md_file_path.parent)).as_posix()
else:
self.logger.debug()
rel_img_path = Path(relpath(image_path, md_file_path.parent)).as_posix()
img_ref = f
self.logger.debug(f)
return img_ref
return self._image_pattern.sub(_sub, content) |
def _OpenFileObject(self, path_spec):
if not path_spec.HasParent():
raise errors.PathSpecError(
)
resolver.Resolver.key_chain.ExtractCredentialsFromPathSpec(path_spec)
file_object = resolver.Resolver.OpenFileObject(
path_spec.parent, resolver_context=self._resolver_context)
bde_volume = pybde.volume()
bde.BDEVolumeOpen(
bde_volume, path_spec, file_object, resolver.Resolver.key_chain)
return bde_volume | Opens the file-like object defined by path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
pyvde.volume: BDE volume file-like object.
Raises:
PathSpecError: if the path specification is incorrect. | ### Input:
Opens the file-like object defined by path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
pyvde.volume: BDE volume file-like object.
Raises:
PathSpecError: if the path specification is incorrect.
### Response:
def _OpenFileObject(self, path_spec):
if not path_spec.HasParent():
raise errors.PathSpecError(
)
resolver.Resolver.key_chain.ExtractCredentialsFromPathSpec(path_spec)
file_object = resolver.Resolver.OpenFileObject(
path_spec.parent, resolver_context=self._resolver_context)
bde_volume = pybde.volume()
bde.BDEVolumeOpen(
bde_volume, path_spec, file_object, resolver.Resolver.key_chain)
return bde_volume |
async def _handle_telegram_response(self, response, ignore=None):
if ignore is None:
ignore = set()
ok = response.status == 200
try:
data = await response.json()
if not ok:
desc = data[]
if desc in ignore:
return
raise PlatformOperationError(
.format(desc)
)
except (ValueError, TypeError, KeyError):
raise PlatformOperationError()
return data | Parse a response from Telegram. If there's an error, an exception will
be raised with an explicative message.
:param response: Response to parse
:return: Data | ### Input:
Parse a response from Telegram. If there's an error, an exception will
be raised with an explicative message.
:param response: Response to parse
:return: Data
### Response:
async def _handle_telegram_response(self, response, ignore=None):
if ignore is None:
ignore = set()
ok = response.status == 200
try:
data = await response.json()
if not ok:
desc = data[]
if desc in ignore:
return
raise PlatformOperationError(
.format(desc)
)
except (ValueError, TypeError, KeyError):
raise PlatformOperationError()
return data |
def apply_caching(response):
for k, v in config.get().items():
response.headers[k] = v
return response | Applies the configuration's http headers to all responses | ### Input:
Applies the configuration's http headers to all responses
### Response:
def apply_caching(response):
for k, v in config.get().items():
response.headers[k] = v
return response |
def IsDir(directory):
s doc for performance issues information
ftp':
from ._exceptions import NotImplementedProtocol
raise NotImplementedProtocol(target_url.scheme)
else:
from ._exceptions import NotImplementedProtocol
raise NotImplementedProtocol(directory_url.scheme) | :param unicode directory:
A path
:rtype: bool
:returns:
Returns whether the given path points to an existent directory.
:raises NotImplementedProtocol:
If the path protocol is not local or ftp
.. seealso:: FTP LIMITATIONS at this module's doc for performance issues information | ### Input:
:param unicode directory:
A path
:rtype: bool
:returns:
Returns whether the given path points to an existent directory.
:raises NotImplementedProtocol:
If the path protocol is not local or ftp
.. seealso:: FTP LIMITATIONS at this module's doc for performance issues information
### Response:
def IsDir(directory):
s doc for performance issues information
ftp':
from ._exceptions import NotImplementedProtocol
raise NotImplementedProtocol(target_url.scheme)
else:
from ._exceptions import NotImplementedProtocol
raise NotImplementedProtocol(directory_url.scheme) |
def main(search_engine, search_option, list_engines, query):
engine_data = {}
if list_engines:
for name in engines:
conf = get_config(name)
optionals = filter(lambda e: e != , conf.keys())
if optionals:
click.echo(.format(
command=name.replace(, ),
options=.join(optionals)))
else:
click.echo(name.replace(, ))
sys.exit(0)
for name in engines:
if name.find(search_engine) == 0:
engine_data = get_config(name)
break
if not sys.stdin.isatty():
query = sys.stdin.read()
if not query:
exit_with_error()
if not engine_data:
exit_with_error(.format(search_engine))
if search_option not in engine_data:
exit_with_error(.\
format(search_option, search_engine))
query = u.join(query) if isinstance(query, tuple) else query
engine_url = engine_data.get(search_option)
url = engine_url.format(query).encode()
launch.open(url) | Quick search command tool for your terminal | ### Input:
Quick search command tool for your terminal
### Response:
def main(search_engine, search_option, list_engines, query):
engine_data = {}
if list_engines:
for name in engines:
conf = get_config(name)
optionals = filter(lambda e: e != , conf.keys())
if optionals:
click.echo(.format(
command=name.replace(, ),
options=.join(optionals)))
else:
click.echo(name.replace(, ))
sys.exit(0)
for name in engines:
if name.find(search_engine) == 0:
engine_data = get_config(name)
break
if not sys.stdin.isatty():
query = sys.stdin.read()
if not query:
exit_with_error()
if not engine_data:
exit_with_error(.format(search_engine))
if search_option not in engine_data:
exit_with_error(.\
format(search_option, search_engine))
query = u.join(query) if isinstance(query, tuple) else query
engine_url = engine_data.get(search_option)
url = engine_url.format(query).encode()
launch.open(url) |
def send_to_kinesis_stream(events, stream_name, partition_key=None,
packer=None, serializer=json.dumps):
if not events:
logger.info("No events provided: nothing delivered to Firehose")
return
records = []
for event in events:
if not partition_key:
partition_key_value = str(uuid.uuid4())
elif hasattr(partition_key, "__call__"):
partition_key_value = partition_key(event)
else:
partition_key_value = partition_key
if not isinstance(event, str):
event = serializer(event)
if packer:
event = packer(event)
record = {"Data": event,
"PartitionKey": partition_key_value}
records.append(record)
kinesis = boto3.client("kinesis")
resp = kinesis.put_records(StreamName=stream_name, Records=records)
return resp | Sends events to a Kinesis stream. | ### Input:
Sends events to a Kinesis stream.
### Response:
def send_to_kinesis_stream(events, stream_name, partition_key=None,
packer=None, serializer=json.dumps):
if not events:
logger.info("No events provided: nothing delivered to Firehose")
return
records = []
for event in events:
if not partition_key:
partition_key_value = str(uuid.uuid4())
elif hasattr(partition_key, "__call__"):
partition_key_value = partition_key(event)
else:
partition_key_value = partition_key
if not isinstance(event, str):
event = serializer(event)
if packer:
event = packer(event)
record = {"Data": event,
"PartitionKey": partition_key_value}
records.append(record)
kinesis = boto3.client("kinesis")
resp = kinesis.put_records(StreamName=stream_name, Records=records)
return resp |
def rouge_l_summary_level(evaluated_sentences, reference_sentences):
if len(evaluated_sentences) <= 0 or len(reference_sentences) <= 0:
raise ValueError("Collections must contain at least 1 sentence.")
m = len(set(_split_into_words(reference_sentences)))
n = len(set(_split_into_words(evaluated_sentences)))
union_lcs_sum_across_all_references = 0
union = set()
for ref_s in reference_sentences:
lcs_count, union = _union_lcs(evaluated_sentences,
ref_s,
prev_union=union)
union_lcs_sum_across_all_references += lcs_count
llcs = union_lcs_sum_across_all_references
r_lcs = llcs / m
p_lcs = llcs / n
beta = p_lcs / (r_lcs + 1e-12)
num = (1 + (beta**2)) * r_lcs * p_lcs
denom = r_lcs + ((beta**2) * p_lcs)
f_lcs = num / (denom + 1e-12)
return {"f": f_lcs, "p": p_lcs, "r": r_lcs} | Computes ROUGE-L (summary level) of two text collections of sentences.
http://research.microsoft.com/en-us/um/people/cyl/download/papers/
rouge-working-note-v1.3.1.pdf
Calculated according to:
R_lcs = SUM(1, u)[LCS<union>(r_i,C)]/m
P_lcs = SUM(1, u)[LCS<union>(r_i,C)]/n
F_lcs = ((1 + beta^2)*R_lcs*P_lcs) / (R_lcs + (beta^2) * P_lcs)
where:
SUM(i,u) = SUM from i through u
u = number of sentences in reference summary
C = Candidate summary made up of v sentences
m = number of words in reference summary
n = number of words in candidate summary
Args:
evaluated_sentences: The sentences that have been picked by the
summarizer
reference_sentence: One of the sentences in the reference summaries
Returns:
A float: F_lcs
Raises:
ValueError: raises exception if a param has len <= 0 | ### Input:
Computes ROUGE-L (summary level) of two text collections of sentences.
http://research.microsoft.com/en-us/um/people/cyl/download/papers/
rouge-working-note-v1.3.1.pdf
Calculated according to:
R_lcs = SUM(1, u)[LCS<union>(r_i,C)]/m
P_lcs = SUM(1, u)[LCS<union>(r_i,C)]/n
F_lcs = ((1 + beta^2)*R_lcs*P_lcs) / (R_lcs + (beta^2) * P_lcs)
where:
SUM(i,u) = SUM from i through u
u = number of sentences in reference summary
C = Candidate summary made up of v sentences
m = number of words in reference summary
n = number of words in candidate summary
Args:
evaluated_sentences: The sentences that have been picked by the
summarizer
reference_sentence: One of the sentences in the reference summaries
Returns:
A float: F_lcs
Raises:
ValueError: raises exception if a param has len <= 0
### Response:
def rouge_l_summary_level(evaluated_sentences, reference_sentences):
if len(evaluated_sentences) <= 0 or len(reference_sentences) <= 0:
raise ValueError("Collections must contain at least 1 sentence.")
m = len(set(_split_into_words(reference_sentences)))
n = len(set(_split_into_words(evaluated_sentences)))
union_lcs_sum_across_all_references = 0
union = set()
for ref_s in reference_sentences:
lcs_count, union = _union_lcs(evaluated_sentences,
ref_s,
prev_union=union)
union_lcs_sum_across_all_references += lcs_count
llcs = union_lcs_sum_across_all_references
r_lcs = llcs / m
p_lcs = llcs / n
beta = p_lcs / (r_lcs + 1e-12)
num = (1 + (beta**2)) * r_lcs * p_lcs
denom = r_lcs + ((beta**2) * p_lcs)
f_lcs = num / (denom + 1e-12)
return {"f": f_lcs, "p": p_lcs, "r": r_lcs} |
def parse_extlang(subtags):
index = 0
parsed = []
while index < len(subtags) and len(subtags[index]) == 3 and index < 3:
parsed.append((, subtags[index]))
index += 1
return parsed + parse_subtags(subtags[index:], SCRIPT) | Parse an 'extended language' tag, which consists of 1 to 3 three-letter
language codes.
Extended languages are used for distinguishing dialects/sublanguages
(depending on your view) of macrolanguages such as Arabic, Bahasa Malay,
and Chinese.
It's supposed to also be acceptable to just use the sublanguage as the
primary language code, and your code should know what's a macrolanguage of
what. For example, 'zh-yue' and 'yue' are the same language (Cantonese),
and differ only in whether they explicitly spell out that Cantonese is a
kind of Chinese. | ### Input:
Parse an 'extended language' tag, which consists of 1 to 3 three-letter
language codes.
Extended languages are used for distinguishing dialects/sublanguages
(depending on your view) of macrolanguages such as Arabic, Bahasa Malay,
and Chinese.
It's supposed to also be acceptable to just use the sublanguage as the
primary language code, and your code should know what's a macrolanguage of
what. For example, 'zh-yue' and 'yue' are the same language (Cantonese),
and differ only in whether they explicitly spell out that Cantonese is a
kind of Chinese.
### Response:
def parse_extlang(subtags):
index = 0
parsed = []
while index < len(subtags) and len(subtags[index]) == 3 and index < 3:
parsed.append((, subtags[index]))
index += 1
return parsed + parse_subtags(subtags[index:], SCRIPT) |
def simulate(model, dr, N=1, T=40, s0=None, i0=None, m0=None,
driving_process=None, seed=42, stochastic=True):
if isinstance(dr, AlgoResult):
dr = dr.dr
calib = model.calibration
parms = numpy.array(calib[])
if s0 is None:
s0 = calib[]
n_x = len(model.symbols["controls"])
n_s = len(model.symbols["states"])
s_simul = numpy.zeros((T, N, n_s))
x_simul = numpy.zeros((T, N, n_x))
s_simul[0, :, :] = s0[None, :]
if driving_process is not None:
m_simul = driving_process
sim_type =
m0 = m_simul[0,:,:]
x_simul[0,:,:] = dr.eval_ms(m0, s0)
else:
if isinstance(dr.exo_grid, UnstructuredGrid):
if i0 is None:
i0 = 0
dp = model.exogenous.discretize()
m_simul = dp.simulate(N, T, i0=i0, stochastic=stochastic)
i_simul = find_index(m_simul, dp.values)
sim_type =
m0 = dp.node(i0)
x0 = dr.eval_is(i0, s0)
else:
process = model.exogenous
m_simul = process.simulate(N, T, m0=m0, stochastic=stochastic)
sim_type =
if m0 is None:
m0 = model.calibration["exogenous"]
x0 = dr.eval_ms(m0, s0)
x_simul[0, :, :] = x0[None, :]
fun = model.functions
f = model.functions[]
g = model.functions[]
numpy.random.seed(seed)
from dolo.misc.dprint import dprint
mp = m0
for i in range(T):
m = m_simul[i,:,:]
s = s_simul[i,:,:]
if sim_type==:
i_m = i_simul[i,:]
xx = [dr.eval_is(i_m[ii], s[ii,:]) for ii in range(s.shape[0])]
x = np.row_stack(xx)
else:
x = dr.eval_ms(m, s)
x_simul[i,:,:] = x
ss = g(mp, s, x, m, parms)
if i < T-1:
s_simul[i + 1, :, :] = ss
mp = m
if not in fun:
l = [s_simul, x_simul]
varnames = model.symbols[] + model.symbols[]
else:
aux = fun[]
a_simul = aux(
m_simul.reshape((N * T, -1)),
s_simul.reshape((N * T, -1)),
x_simul.reshape((N * T, -1)), parms)
a_simul = a_simul.reshape(T, N, -1)
l = [m_simul, s_simul, x_simul, a_simul]
varnames = model.symbols[] + model.symbols[] + model.symbols[
] + model.symbols[]
simul = numpy.concatenate(l, axis=2)
import xarray as xr
data = xr.DataArray(
simul,
dims=[,,],
coords={: range(T), : range(N), : varnames}
)
return data | Simulate a model using the specified decision rule.
Parameters
----------
model: NumericModel
dr: decision rule
s0: ndarray
initial state where all simulations start
driving_process: ndarray
realization of exogenous driving process (drawn randomly if None)
N: int
number of simulations
T: int
horizon for the simulations
seed: int
used to initialize the random number generator. Use it to replicate
exact same results among simulations
discard: boolean (False)
if True, then all simulations containing at least one non finite value
are discarded
Returns
-------
xarray.DataArray:
returns a ``T x N x n_v`` array where ``n_v``
is the number of variables. | ### Input:
Simulate a model using the specified decision rule.
Parameters
----------
model: NumericModel
dr: decision rule
s0: ndarray
initial state where all simulations start
driving_process: ndarray
realization of exogenous driving process (drawn randomly if None)
N: int
number of simulations
T: int
horizon for the simulations
seed: int
used to initialize the random number generator. Use it to replicate
exact same results among simulations
discard: boolean (False)
if True, then all simulations containing at least one non finite value
are discarded
Returns
-------
xarray.DataArray:
returns a ``T x N x n_v`` array where ``n_v``
is the number of variables.
### Response:
def simulate(model, dr, N=1, T=40, s0=None, i0=None, m0=None,
driving_process=None, seed=42, stochastic=True):
if isinstance(dr, AlgoResult):
dr = dr.dr
calib = model.calibration
parms = numpy.array(calib[])
if s0 is None:
s0 = calib[]
n_x = len(model.symbols["controls"])
n_s = len(model.symbols["states"])
s_simul = numpy.zeros((T, N, n_s))
x_simul = numpy.zeros((T, N, n_x))
s_simul[0, :, :] = s0[None, :]
if driving_process is not None:
m_simul = driving_process
sim_type =
m0 = m_simul[0,:,:]
x_simul[0,:,:] = dr.eval_ms(m0, s0)
else:
if isinstance(dr.exo_grid, UnstructuredGrid):
if i0 is None:
i0 = 0
dp = model.exogenous.discretize()
m_simul = dp.simulate(N, T, i0=i0, stochastic=stochastic)
i_simul = find_index(m_simul, dp.values)
sim_type =
m0 = dp.node(i0)
x0 = dr.eval_is(i0, s0)
else:
process = model.exogenous
m_simul = process.simulate(N, T, m0=m0, stochastic=stochastic)
sim_type =
if m0 is None:
m0 = model.calibration["exogenous"]
x0 = dr.eval_ms(m0, s0)
x_simul[0, :, :] = x0[None, :]
fun = model.functions
f = model.functions[]
g = model.functions[]
numpy.random.seed(seed)
from dolo.misc.dprint import dprint
mp = m0
for i in range(T):
m = m_simul[i,:,:]
s = s_simul[i,:,:]
if sim_type==:
i_m = i_simul[i,:]
xx = [dr.eval_is(i_m[ii], s[ii,:]) for ii in range(s.shape[0])]
x = np.row_stack(xx)
else:
x = dr.eval_ms(m, s)
x_simul[i,:,:] = x
ss = g(mp, s, x, m, parms)
if i < T-1:
s_simul[i + 1, :, :] = ss
mp = m
if not in fun:
l = [s_simul, x_simul]
varnames = model.symbols[] + model.symbols[]
else:
aux = fun[]
a_simul = aux(
m_simul.reshape((N * T, -1)),
s_simul.reshape((N * T, -1)),
x_simul.reshape((N * T, -1)), parms)
a_simul = a_simul.reshape(T, N, -1)
l = [m_simul, s_simul, x_simul, a_simul]
varnames = model.symbols[] + model.symbols[] + model.symbols[
] + model.symbols[]
simul = numpy.concatenate(l, axis=2)
import xarray as xr
data = xr.DataArray(
simul,
dims=[,,],
coords={: range(T), : range(N), : varnames}
)
return data |
def _parse_neural_network_model(topology, parent_scope, model, inputs, outputs):
s (neither layers) inputs and outputs with proper variables created when
parsing sub-models.
4. Link local variables and the corresponding parent variables (only model
scope = topology.declare_scope(, [parent_scope] + parent_scope.parent_scopes)
network = None
network_type = model.WhichOneof()
if network_type == :
network = model.neuralNetworkClassifier
elif network_type == :
network = model.neuralNetworkRegressor
elif network_type == :
network = model.neuralNetwork
else:
raise ValueError(.format(network_type))
for op in network.preprocessing:
operator = scope.declare_local_operator(op.WhichOneof() + , op)
name = op.featureName if op.featureName != else model.description.input[0].name
original = scope.get_local_variable_or_declare_one(name)
original.type = FloatTensorType()
operator.inputs.append(original)
processed = scope.declare_local_variable(name)
processed.type = FloatTensorType()
operator.outputs.append(processed)
for op in network.layers:
operator = scope.declare_local_operator(op.WhichOneof(), op)
for name in op.input:
variable = scope.get_local_variable_or_declare_one(name)
for name in op.output:
variable = scope.declare_local_variable(name)
variable.type = FloatTensorType()
operator.outputs.append(variable)
sink_variables = scope.find_sink_variables()
special_variable_names = [model.description.predictedFeatureName, model.description.predictedProbabilitiesName]
if model.WhichOneof() == and var.name in special_variable_names:
continue
child_variable = scope.variables[scope.variable_name_mapping[var.name][-1]]
variable = scope.declare_local_variable(
var.name, _parse_coreml_feature(var, topology.target_opset, topology.default_batch_size))
operator = scope.declare_local_operator()
operator.inputs.append(child_variable)
operator.outputs.append(variable)
if model.WhichOneof() == and model.description.predictedFeatureName:
label_variable = None
for var in model.description.output:
if var.name == model.description.predictedFeatureName:
label_type = _parse_coreml_feature(var, topology.target_opset, topology.default_batch_size)
label_variable = scope.declare_local_variable(var.name, label_type)
break
operator = scope.declare_local_operator(, model)
probability_name = model.description.predictedProbabilitiesName
if probability_name in scope.variable_name_mapping:
operator.inputs.append(scope.variables[scope.variable_name_mapping[probability_name][-1]])
else:
operator.inputs.append(sink_variables[0])
operator.outputs.append(label_variable)
if model.WhichOneof() == and model.description.predictedProbabilitiesName:
operator = scope.declare_local_operator(, model)
probability_name = model.description.predictedProbabilitiesName
if probability_name in scope.variable_name_mapping:
operator.inputs.append(scope.variables[scope.variable_name_mapping[probability_name][-1]])
else:
operator.inputs.append(sink_variables[0])
for var in model.description.output:
if var.name == model.description.predictedProbabilitiesName:
probability_type = _parse_coreml_feature(var, topology.target_opset,
topology.default_batch_size)
probability_variable = scope.declare_local_variable(var.name, probability_type)
operator.outputs.append(probability_variable)
break
for parent_variable in outputs:
raw_name = parent_variable.raw_name
child_variable = scope.variables[scope.variable_name_mapping[raw_name][-1]]
operator = scope.declare_local_operator()
operator.inputs.append(child_variable)
operator.outputs.append(parent_variable) | Parse a neural network model.
Steps:
1. Create local scope for allocating local variables and operators
2. Sequentially parse the preprocessors and layers
3. Connect model's (neither layers' nor preprocessors') inputs and outputs with proper variables created when
parsing sub-models.
4. Link local variables and the corresponding parent variables (only model's inputs and outputs are considered)
Note:
1. A CoreML preprocessor/layer can use the same variable for its input and output.
2. Two CoreML variables may have the same name but different types.
3. Preprocessor sometime may not include any information about its input | ### Input:
Parse a neural network model.
Steps:
1. Create local scope for allocating local variables and operators
2. Sequentially parse the preprocessors and layers
3. Connect model's (neither layers' nor preprocessors') inputs and outputs with proper variables created when
parsing sub-models.
4. Link local variables and the corresponding parent variables (only model's inputs and outputs are considered)
Note:
1. A CoreML preprocessor/layer can use the same variable for its input and output.
2. Two CoreML variables may have the same name but different types.
3. Preprocessor sometime may not include any information about its input
### Response:
def _parse_neural_network_model(topology, parent_scope, model, inputs, outputs):
s (neither layers) inputs and outputs with proper variables created when
parsing sub-models.
4. Link local variables and the corresponding parent variables (only model
scope = topology.declare_scope(, [parent_scope] + parent_scope.parent_scopes)
network = None
network_type = model.WhichOneof()
if network_type == :
network = model.neuralNetworkClassifier
elif network_type == :
network = model.neuralNetworkRegressor
elif network_type == :
network = model.neuralNetwork
else:
raise ValueError(.format(network_type))
for op in network.preprocessing:
operator = scope.declare_local_operator(op.WhichOneof() + , op)
name = op.featureName if op.featureName != else model.description.input[0].name
original = scope.get_local_variable_or_declare_one(name)
original.type = FloatTensorType()
operator.inputs.append(original)
processed = scope.declare_local_variable(name)
processed.type = FloatTensorType()
operator.outputs.append(processed)
for op in network.layers:
operator = scope.declare_local_operator(op.WhichOneof(), op)
for name in op.input:
variable = scope.get_local_variable_or_declare_one(name)
for name in op.output:
variable = scope.declare_local_variable(name)
variable.type = FloatTensorType()
operator.outputs.append(variable)
sink_variables = scope.find_sink_variables()
special_variable_names = [model.description.predictedFeatureName, model.description.predictedProbabilitiesName]
if model.WhichOneof() == and var.name in special_variable_names:
continue
child_variable = scope.variables[scope.variable_name_mapping[var.name][-1]]
variable = scope.declare_local_variable(
var.name, _parse_coreml_feature(var, topology.target_opset, topology.default_batch_size))
operator = scope.declare_local_operator()
operator.inputs.append(child_variable)
operator.outputs.append(variable)
if model.WhichOneof() == and model.description.predictedFeatureName:
label_variable = None
for var in model.description.output:
if var.name == model.description.predictedFeatureName:
label_type = _parse_coreml_feature(var, topology.target_opset, topology.default_batch_size)
label_variable = scope.declare_local_variable(var.name, label_type)
break
operator = scope.declare_local_operator(, model)
probability_name = model.description.predictedProbabilitiesName
if probability_name in scope.variable_name_mapping:
operator.inputs.append(scope.variables[scope.variable_name_mapping[probability_name][-1]])
else:
operator.inputs.append(sink_variables[0])
operator.outputs.append(label_variable)
if model.WhichOneof() == and model.description.predictedProbabilitiesName:
operator = scope.declare_local_operator(, model)
probability_name = model.description.predictedProbabilitiesName
if probability_name in scope.variable_name_mapping:
operator.inputs.append(scope.variables[scope.variable_name_mapping[probability_name][-1]])
else:
operator.inputs.append(sink_variables[0])
for var in model.description.output:
if var.name == model.description.predictedProbabilitiesName:
probability_type = _parse_coreml_feature(var, topology.target_opset,
topology.default_batch_size)
probability_variable = scope.declare_local_variable(var.name, probability_type)
operator.outputs.append(probability_variable)
break
for parent_variable in outputs:
raw_name = parent_variable.raw_name
child_variable = scope.variables[scope.variable_name_mapping[raw_name][-1]]
operator = scope.declare_local_operator()
operator.inputs.append(child_variable)
operator.outputs.append(parent_variable) |
def extract_along_line(self, pid, xy0, xy1, N=10):
assert N >= 2
xy0 = np.array(xy0).squeeze()
xy1 = np.array(xy1).squeeze()
assert xy0.size == 2
assert xy1.size == 2
points = [(x, y) for x, y in zip(
np.linspace(xy0[0], xy1[0], N), np.linspace(xy0[1], xy1[1], N)
)]
result = self.extract_points(pid, points)
results_xyv = np.hstack((
points,
result[:, np.newaxis]
))
return results_xyv | Extract parameter values along a given line.
Parameters
----------
pid: int
The parameter id to extract values from
xy0: tuple
A tupe with (x,y) start point coordinates
xy1: tuple
A tupe with (x,y) end point coordinates
N: integer, optional
The number of values to extract along the line (including start and
end point)
Returns
-------
values: numpy.ndarray (n x 1)
data values for extracted data points | ### Input:
Extract parameter values along a given line.
Parameters
----------
pid: int
The parameter id to extract values from
xy0: tuple
A tupe with (x,y) start point coordinates
xy1: tuple
A tupe with (x,y) end point coordinates
N: integer, optional
The number of values to extract along the line (including start and
end point)
Returns
-------
values: numpy.ndarray (n x 1)
data values for extracted data points
### Response:
def extract_along_line(self, pid, xy0, xy1, N=10):
assert N >= 2
xy0 = np.array(xy0).squeeze()
xy1 = np.array(xy1).squeeze()
assert xy0.size == 2
assert xy1.size == 2
points = [(x, y) for x, y in zip(
np.linspace(xy0[0], xy1[0], N), np.linspace(xy0[1], xy1[1], N)
)]
result = self.extract_points(pid, points)
results_xyv = np.hstack((
points,
result[:, np.newaxis]
))
return results_xyv |
def tag_and_stem(self, text, cache=None):
analysis = self.analyze(text)
triples = []
for record in analysis:
root = self.get_record_root(record)
token = self.get_record_token(record)
if token:
if unicode_is_punctuation(token):
triples.append((token, , token))
else:
pos = self.get_record_pos(record)
triples.append((root, pos, token))
return triples | Given some text, return a sequence of (stem, pos, text) triples as
appropriate for the reader. `pos` can be as general or specific as
necessary (for example, it might label all parts of speech, or it might
only distinguish function words from others).
Twitter-style hashtags and at-mentions have the stem and pos they would
have without the leading # or @. For instance, if the reader's triple
for "thing" is ('thing', 'NN', 'things'), then "#things" would come out
as ('thing', 'NN', '#things'). | ### Input:
Given some text, return a sequence of (stem, pos, text) triples as
appropriate for the reader. `pos` can be as general or specific as
necessary (for example, it might label all parts of speech, or it might
only distinguish function words from others).
Twitter-style hashtags and at-mentions have the stem and pos they would
have without the leading # or @. For instance, if the reader's triple
for "thing" is ('thing', 'NN', 'things'), then "#things" would come out
as ('thing', 'NN', '#things').
### Response:
def tag_and_stem(self, text, cache=None):
analysis = self.analyze(text)
triples = []
for record in analysis:
root = self.get_record_root(record)
token = self.get_record_token(record)
if token:
if unicode_is_punctuation(token):
triples.append((token, , token))
else:
pos = self.get_record_pos(record)
triples.append((root, pos, token))
return triples |
def visit_Block(self, node, frame):
level = 0
if frame.toplevel:
if self.has_known_extends:
return
if self.extends_so_far > 0:
self.writeline()
self.indent()
level += 1
if node.scoped:
context = self.derive_context(frame)
else:
context = self.get_context_ref()
if supports_yield_from and not self.environment.is_async and \
frame.buffer is None:
self.writeline( % (
node.name, context), node)
else:
loop = self.environment.is_async and or
self.writeline( % (
loop, node.name, context), node)
self.indent()
self.simple_write(, frame)
self.outdent()
self.outdent(level) | Call a block and register it for the template. | ### Input:
Call a block and register it for the template.
### Response:
def visit_Block(self, node, frame):
level = 0
if frame.toplevel:
if self.has_known_extends:
return
if self.extends_so_far > 0:
self.writeline()
self.indent()
level += 1
if node.scoped:
context = self.derive_context(frame)
else:
context = self.get_context_ref()
if supports_yield_from and not self.environment.is_async and \
frame.buffer is None:
self.writeline( % (
node.name, context), node)
else:
loop = self.environment.is_async and or
self.writeline( % (
loop, node.name, context), node)
self.indent()
self.simple_write(, frame)
self.outdent()
self.outdent(level) |
def add_peer(self, peer):
if type(peer) == list:
for i in peer:
check_url(i)
self.PEERS.extend(peer)
elif type(peer) == str:
check_url(peer)
self.PEERS.append(peer) | Add a peer or multiple peers to the PEERS variable, takes a single string or a list.
:param peer(list or string) | ### Input:
Add a peer or multiple peers to the PEERS variable, takes a single string or a list.
:param peer(list or string)
### Response:
def add_peer(self, peer):
if type(peer) == list:
for i in peer:
check_url(i)
self.PEERS.extend(peer)
elif type(peer) == str:
check_url(peer)
self.PEERS.append(peer) |
def mpl_palette(name, n_colors=6):
brewer_qual_pals = {"Accent": 8, "Dark2": 8, "Paired": 12,
"Pastel1": 9, "Pastel2": 8,
"Set1": 9, "Set2": 8, "Set3": 12}
if name.endswith("_d"):
pal = ["
pal.extend(color_palette(name.replace("_d", "_r"), 2))
cmap = blend_palette(pal, n_colors, as_cmap=True)
else:
cmap = getattr(mpl.cm, name)
if name in brewer_qual_pals:
bins = np.linspace(0, 1, brewer_qual_pals[name])[:n_colors]
else:
bins = np.linspace(0, 1, n_colors + 2)[1:-1]
palette = list(map(tuple, cmap(bins)[:, :3]))
return palette | Return discrete colors from a matplotlib palette.
Note that this handles the qualitative colorbrewer palettes
properly, although if you ask for more colors than a particular
qualitative palette can provide you will fewer than you are
expecting.
Parameters
----------
name : string
name of the palette
n_colors : int
number of colors in the palette
Returns
-------
palette : list of tuples
palette colors in r, g, b format | ### Input:
Return discrete colors from a matplotlib palette.
Note that this handles the qualitative colorbrewer palettes
properly, although if you ask for more colors than a particular
qualitative palette can provide you will fewer than you are
expecting.
Parameters
----------
name : string
name of the palette
n_colors : int
number of colors in the palette
Returns
-------
palette : list of tuples
palette colors in r, g, b format
### Response:
def mpl_palette(name, n_colors=6):
brewer_qual_pals = {"Accent": 8, "Dark2": 8, "Paired": 12,
"Pastel1": 9, "Pastel2": 8,
"Set1": 9, "Set2": 8, "Set3": 12}
if name.endswith("_d"):
pal = ["
pal.extend(color_palette(name.replace("_d", "_r"), 2))
cmap = blend_palette(pal, n_colors, as_cmap=True)
else:
cmap = getattr(mpl.cm, name)
if name in brewer_qual_pals:
bins = np.linspace(0, 1, brewer_qual_pals[name])[:n_colors]
else:
bins = np.linspace(0, 1, n_colors + 2)[1:-1]
palette = list(map(tuple, cmap(bins)[:, :3]))
return palette |
def Progress(text=, percentage=0, auto_close=False, pulsate=False, **kwargs):
args = []
if text:
args.append( % text)
if percentage:
args.append( % percentage)
if auto_close:
args.append( % auto_close)
if pulsate:
args.append( % pulsate)
for generic_args in kwargs_helper(kwargs):
args.append( % generic_args)
p = Popen([zen_exec, ] + args, stdin=PIPE, stdout=PIPE)
def update(percent, message=):
if type(percent) == float:
percent = int(percent * 100)
p.stdin.write(str(percent) + )
if message:
p.stdin.write( % message)
return p.returncode
return update | Show a progress dialog to the user.
This will raise a Zenity Progress Dialog. It returns a callback that
accepts two arguments. The first is a numeric value of the percent
complete. The second is a message about the progress.
NOTE: This function sends the SIGHUP signal if the user hits the cancel
button. You must connect to this signal if you do not want your
application to exit.
text - The initial message about the progress.
percentage - The initial percentage to set the progress bar to.
auto_close - True if the dialog should close automatically if it reaches
100%.
pulsate - True is the status should pulsate instead of progress.
kwargs - Optional command line parameters for Zenity such as height,
width, etc. | ### Input:
Show a progress dialog to the user.
This will raise a Zenity Progress Dialog. It returns a callback that
accepts two arguments. The first is a numeric value of the percent
complete. The second is a message about the progress.
NOTE: This function sends the SIGHUP signal if the user hits the cancel
button. You must connect to this signal if you do not want your
application to exit.
text - The initial message about the progress.
percentage - The initial percentage to set the progress bar to.
auto_close - True if the dialog should close automatically if it reaches
100%.
pulsate - True is the status should pulsate instead of progress.
kwargs - Optional command line parameters for Zenity such as height,
width, etc.
### Response:
def Progress(text=, percentage=0, auto_close=False, pulsate=False, **kwargs):
args = []
if text:
args.append( % text)
if percentage:
args.append( % percentage)
if auto_close:
args.append( % auto_close)
if pulsate:
args.append( % pulsate)
for generic_args in kwargs_helper(kwargs):
args.append( % generic_args)
p = Popen([zen_exec, ] + args, stdin=PIPE, stdout=PIPE)
def update(percent, message=):
if type(percent) == float:
percent = int(percent * 100)
p.stdin.write(str(percent) + )
if message:
p.stdin.write( % message)
return p.returncode
return update |
def reverse(self):
"reverse *IN PLACE*"
leftblock = self.left
rightblock = self.right
leftindex = self.leftndx
rightindex = self.rightndx
for i in range(self.length // 2):
assert leftblock != rightblock or leftindex < rightindex
(rightblock[rightindex], leftblock[leftindex]) = (
leftblock[leftindex], rightblock[rightindex])
leftindex += 1
if leftindex == n:
leftblock = leftblock[RGTLNK]
assert leftblock is not None
leftindex = 0
rightindex -= 1
if rightindex == -1:
rightblock = rightblock[LFTLNK]
assert rightblock is not None
rightindex = n - 1 | reverse *IN PLACE* | ### Input:
reverse *IN PLACE*
### Response:
def reverse(self):
"reverse *IN PLACE*"
leftblock = self.left
rightblock = self.right
leftindex = self.leftndx
rightindex = self.rightndx
for i in range(self.length // 2):
assert leftblock != rightblock or leftindex < rightindex
(rightblock[rightindex], leftblock[leftindex]) = (
leftblock[leftindex], rightblock[rightindex])
leftindex += 1
if leftindex == n:
leftblock = leftblock[RGTLNK]
assert leftblock is not None
leftindex = 0
rightindex -= 1
if rightindex == -1:
rightblock = rightblock[LFTLNK]
assert rightblock is not None
rightindex = n - 1 |
def lookup_asset_types(self, sids):
found = {}
missing = set()
for sid in sids:
try:
found[sid] = self._asset_type_cache[sid]
except KeyError:
missing.add(sid)
if not missing:
return found
router_cols = self.asset_router.c
for assets in group_into_chunks(missing):
query = sa.select((router_cols.sid, router_cols.asset_type)).where(
self.asset_router.c.sid.in_(map(int, assets))
)
for sid, type_ in query.execute().fetchall():
missing.remove(sid)
found[sid] = self._asset_type_cache[sid] = type_
for sid in missing:
found[sid] = self._asset_type_cache[sid] = None
return found | Retrieve asset types for a list of sids.
Parameters
----------
sids : list[int]
Returns
-------
types : dict[sid -> str or None]
Asset types for the provided sids. | ### Input:
Retrieve asset types for a list of sids.
Parameters
----------
sids : list[int]
Returns
-------
types : dict[sid -> str or None]
Asset types for the provided sids.
### Response:
def lookup_asset_types(self, sids):
found = {}
missing = set()
for sid in sids:
try:
found[sid] = self._asset_type_cache[sid]
except KeyError:
missing.add(sid)
if not missing:
return found
router_cols = self.asset_router.c
for assets in group_into_chunks(missing):
query = sa.select((router_cols.sid, router_cols.asset_type)).where(
self.asset_router.c.sid.in_(map(int, assets))
)
for sid, type_ in query.execute().fetchall():
missing.remove(sid)
found[sid] = self._asset_type_cache[sid] = type_
for sid in missing:
found[sid] = self._asset_type_cache[sid] = None
return found |
def _annotate_params(self, word):
annotation = {}
annotation[] = word
annotation[] = + self.entity_map[word]
annotation[] = self.entity_map[word].replace(, )
annotation[] = True
self.data.append(annotation) | Annotates a given word for the UserSays data field of an Intent object.
Annotations are created using the entity map within the user_says.yaml template. | ### Input:
Annotates a given word for the UserSays data field of an Intent object.
Annotations are created using the entity map within the user_says.yaml template.
### Response:
def _annotate_params(self, word):
annotation = {}
annotation[] = word
annotation[] = + self.entity_map[word]
annotation[] = self.entity_map[word].replace(, )
annotation[] = True
self.data.append(annotation) |
def NewFromContent(cls,
content,
urn,
chunk_size=1024,
token=None,
private_key=None,
public_key=None):
aff4.FACTORY.Delete(urn, token=token)
with data_store.DB.GetMutationPool() as pool:
with aff4.FACTORY.Create(
urn, cls, mode="w", mutation_pool=pool, token=token) as fd:
for start_of_chunk in range(0, len(content), chunk_size):
chunk = content[start_of_chunk:start_of_chunk + chunk_size]
blob_rdf = rdf_crypto.SignedBlob()
blob_rdf.Sign(chunk, private_key, public_key)
fd.Add(blob_rdf, mutation_pool=pool)
return urn | Alternate constructor for GRRSignedBlob.
Creates a GRRSignedBlob from a content string by chunking it and signing
each chunk.
Args:
content: The data to stored in the GRRSignedBlob.
urn: The AFF4 URN to create.
chunk_size: Data will be chunked into this size (each chunk is
individually signed.
token: The ACL Token.
private_key: An rdf_crypto.RSAPrivateKey() instance.
public_key: An rdf_crypto.RSAPublicKey() instance.
Returns:
the URN of the new object written. | ### Input:
Alternate constructor for GRRSignedBlob.
Creates a GRRSignedBlob from a content string by chunking it and signing
each chunk.
Args:
content: The data to stored in the GRRSignedBlob.
urn: The AFF4 URN to create.
chunk_size: Data will be chunked into this size (each chunk is
individually signed.
token: The ACL Token.
private_key: An rdf_crypto.RSAPrivateKey() instance.
public_key: An rdf_crypto.RSAPublicKey() instance.
Returns:
the URN of the new object written.
### Response:
def NewFromContent(cls,
content,
urn,
chunk_size=1024,
token=None,
private_key=None,
public_key=None):
aff4.FACTORY.Delete(urn, token=token)
with data_store.DB.GetMutationPool() as pool:
with aff4.FACTORY.Create(
urn, cls, mode="w", mutation_pool=pool, token=token) as fd:
for start_of_chunk in range(0, len(content), chunk_size):
chunk = content[start_of_chunk:start_of_chunk + chunk_size]
blob_rdf = rdf_crypto.SignedBlob()
blob_rdf.Sign(chunk, private_key, public_key)
fd.Add(blob_rdf, mutation_pool=pool)
return urn |
def request(self, rpc_command, source=None, filter=None):
if etree.iselement(rpc_command):
node = rpc_command
else:
node = new_ele(rpc_command)
if source is not None:
node.append(util.datastore_or_url("source", source, self._assert))
if filter is not None:
node.append(util.build_filter(filter))
return self._request(node) | *rpc_command* specifies rpc command to be dispatched either in plain text or in xml element format (depending on command)
*source* name of the configuration datastore being queried
*filter* specifies the portion of the configuration to retrieve (by default entire configuration is retrieved)
:seealso: :ref:`filter_params`
Examples of usage::
dispatch('clear-arp-table')
or dispatch element like ::
xsd_fetch = new_ele('get-xnm-information')
sub_ele(xsd_fetch, 'type').text="xml-schema"
sub_ele(xsd_fetch, 'namespace').text="junos-configuration"
dispatch(xsd_fetch) | ### Input:
*rpc_command* specifies rpc command to be dispatched either in plain text or in xml element format (depending on command)
*source* name of the configuration datastore being queried
*filter* specifies the portion of the configuration to retrieve (by default entire configuration is retrieved)
:seealso: :ref:`filter_params`
Examples of usage::
dispatch('clear-arp-table')
or dispatch element like ::
xsd_fetch = new_ele('get-xnm-information')
sub_ele(xsd_fetch, 'type').text="xml-schema"
sub_ele(xsd_fetch, 'namespace').text="junos-configuration"
dispatch(xsd_fetch)
### Response:
def request(self, rpc_command, source=None, filter=None):
if etree.iselement(rpc_command):
node = rpc_command
else:
node = new_ele(rpc_command)
if source is not None:
node.append(util.datastore_or_url("source", source, self._assert))
if filter is not None:
node.append(util.build_filter(filter))
return self._request(node) |
def offset_to_sky(skydir, offset_lon, offset_lat,
coordsys=, projection=):
offset_lon = np.array(offset_lon, ndmin=1)
offset_lat = np.array(offset_lat, ndmin=1)
w = create_wcs(skydir, coordsys, projection)
pixcrd = np.vstack((offset_lon, offset_lat)).T
return w.wcs_pix2world(pixcrd, 0) | Convert a cartesian offset (X,Y) in the given projection into
a pair of spherical coordinates. | ### Input:
Convert a cartesian offset (X,Y) in the given projection into
a pair of spherical coordinates.
### Response:
def offset_to_sky(skydir, offset_lon, offset_lat,
coordsys=, projection=):
offset_lon = np.array(offset_lon, ndmin=1)
offset_lat = np.array(offset_lat, ndmin=1)
w = create_wcs(skydir, coordsys, projection)
pixcrd = np.vstack((offset_lon, offset_lat)).T
return w.wcs_pix2world(pixcrd, 0) |
def dropIndex(cls, fields) :
"removes an index created with ensureIndex "
con = RabaConnection(cls._raba_namespace)
rlf, ff = cls._parseIndex(fields)
for name in rlf :
con.dropIndex(name, )
con.dropIndex(cls.__name__, ff)
con.commit() | removes an index created with ensureIndex | ### Input:
removes an index created with ensureIndex
### Response:
def dropIndex(cls, fields) :
"removes an index created with ensureIndex "
con = RabaConnection(cls._raba_namespace)
rlf, ff = cls._parseIndex(fields)
for name in rlf :
con.dropIndex(name, )
con.dropIndex(cls.__name__, ff)
con.commit() |
def monitor(self, name, ip, port, quorum):
fut = self.execute(b, name, ip, port, quorum)
return wait_ok(fut) | Add a new master to Sentinel to be monitored. | ### Input:
Add a new master to Sentinel to be monitored.
### Response:
def monitor(self, name, ip, port, quorum):
fut = self.execute(b, name, ip, port, quorum)
return wait_ok(fut) |
def get_profile(self, ann_el_demand_per_sector):
return self.slp_frame.multiply(pd.Series(
ann_el_demand_per_sector), axis=1).dropna(how=, axis=1) * 4 | Get the profiles for the given annual demand
Parameters
----------
ann_el_demand_per_sector : dictionary
Key: sector, value: annual value
Returns
-------
pandas.DataFrame : Table with all profiles | ### Input:
Get the profiles for the given annual demand
Parameters
----------
ann_el_demand_per_sector : dictionary
Key: sector, value: annual value
Returns
-------
pandas.DataFrame : Table with all profiles
### Response:
def get_profile(self, ann_el_demand_per_sector):
return self.slp_frame.multiply(pd.Series(
ann_el_demand_per_sector), axis=1).dropna(how=, axis=1) * 4 |
def _pruned(self, path):
if path[0] == :
path = path[1:]
for rule in reversed(self.pruneRules):
if isinstance(rule, six.string_types):
if fnmatch(path, rule):
return True
elif rule(path):
return True
return False | Is a stat tree node pruned? Goes through the list of prune rules
to find one that applies. Chronologically newer rules are
higher-precedence than older ones. If no rule applies, the stat is
not pruned by default. | ### Input:
Is a stat tree node pruned? Goes through the list of prune rules
to find one that applies. Chronologically newer rules are
higher-precedence than older ones. If no rule applies, the stat is
not pruned by default.
### Response:
def _pruned(self, path):
if path[0] == :
path = path[1:]
for rule in reversed(self.pruneRules):
if isinstance(rule, six.string_types):
if fnmatch(path, rule):
return True
elif rule(path):
return True
return False |
def right_click_specimen_equalarea(self, event):
if event.LeftIsDown() or event.ButtonDClick():
return
elif self.specimen_EA_setting == "Zoom":
self.specimen_EA_setting = "Pan"
try:
self.toolbar2.pan()
except TypeError:
pass
elif self.specimen_EA_setting == "Pan":
self.specimen_EA_setting = "Zoom"
try:
self.toolbar2.zoom()
except TypeError:
pass | toggles between zoom and pan effects for the specimen equal area on
right click
Parameters
----------
event : the wx.MouseEvent that triggered the call of this function
Alters
------
specimen_EA_setting, toolbar2 setting | ### Input:
toggles between zoom and pan effects for the specimen equal area on
right click
Parameters
----------
event : the wx.MouseEvent that triggered the call of this function
Alters
------
specimen_EA_setting, toolbar2 setting
### Response:
def right_click_specimen_equalarea(self, event):
if event.LeftIsDown() or event.ButtonDClick():
return
elif self.specimen_EA_setting == "Zoom":
self.specimen_EA_setting = "Pan"
try:
self.toolbar2.pan()
except TypeError:
pass
elif self.specimen_EA_setting == "Pan":
self.specimen_EA_setting = "Zoom"
try:
self.toolbar2.zoom()
except TypeError:
pass |
def remove(group_id, user_id):
group = Group.query.get_or_404(group_id)
user = User.query.get_or_404(user_id)
if group.can_edit(current_user):
try:
group.remove_member(user)
except Exception as e:
flash(str(e), "error")
return redirect(urlparse(request.referrer).path)
flash(_(,
user_email=user.email, group_name=group.name), )
return redirect(urlparse(request.referrer).path)
flash(
_(
,
group_name=group.name
),
)
return redirect(url_for()) | Remove user from a group. | ### Input:
Remove user from a group.
### Response:
def remove(group_id, user_id):
group = Group.query.get_or_404(group_id)
user = User.query.get_or_404(user_id)
if group.can_edit(current_user):
try:
group.remove_member(user)
except Exception as e:
flash(str(e), "error")
return redirect(urlparse(request.referrer).path)
flash(_(,
user_email=user.email, group_name=group.name), )
return redirect(urlparse(request.referrer).path)
flash(
_(
,
group_name=group.name
),
)
return redirect(url_for()) |
def post_generate_identifier(request):
d1_gmn.app.views.assert_db.post_has_mime_parts(request, ((, ),))
if request.POST[] != :
raise d1_common.types.exceptions.InvalidRequest(
0,
)
fragment = request.POST.get(, None)
while True:
pid = (fragment if fragment else ) + uuid.uuid4().hex
if not d1_gmn.app.models.ScienceObject.objects.filter(pid__did=pid).exists():
return pid | MNStorage.generateIdentifier(session, scheme[, fragment]) → Identifier. | ### Input:
MNStorage.generateIdentifier(session, scheme[, fragment]) → Identifier.
### Response:
def post_generate_identifier(request):
d1_gmn.app.views.assert_db.post_has_mime_parts(request, ((, ),))
if request.POST[] != :
raise d1_common.types.exceptions.InvalidRequest(
0,
)
fragment = request.POST.get(, None)
while True:
pid = (fragment if fragment else ) + uuid.uuid4().hex
if not d1_gmn.app.models.ScienceObject.objects.filter(pid__did=pid).exists():
return pid |
def sha1(self):
if self._sha1 is None:
self._sha1 = hashlib.sha1(self.dump()).digest()
return self._sha1 | :return:
The SHA1 hash of the DER-encoded bytes of this name | ### Input:
:return:
The SHA1 hash of the DER-encoded bytes of this name
### Response:
def sha1(self):
if self._sha1 is None:
self._sha1 = hashlib.sha1(self.dump()).digest()
return self._sha1 |
def items_for_result(cl, result, form):
first = True
pk = cl.lookup_opts.pk.attname
for field_name in cl.list_display:
result_repr, row_class = get_result_and_row_class(cl, field_name,
result)
if (first and not cl.list_display_links) or \
field_name in cl.list_display_links:
table_tag = {True: , False: }[first]
spacer = get_spacer(first, result)
collapse = get_collapse(result)
drag_handler = get_drag_handler(first)
first = False
url = cl.url_for_result(result)
if cl.to_field:
attr = str(cl.to_field)
else:
attr = pk
value = result.serializable_value(attr)
result_id = "" % force_str(value)
onclickstr = (
)
yield mark_safe(
u() % (
drag_handler, table_tag, row_class, spacer, collapse, url,
(cl.is_popup and onclickstr % result_id or ),
conditional_escape(result_repr), table_tag))
else:
if (
form and
field_name in form.fields and
not (
field_name == cl.model._meta.pk.name and
form[cl.model._meta.pk.name].is_hidden
)
):
bf = form[field_name]
result_repr = mark_safe(force_str(bf.errors) + force_str(bf))
yield format_html(u(), row_class, result_repr)
if form and not form[cl.model._meta.pk.name].is_hidden:
yield format_html(u(),
force_str(form[cl.model._meta.pk.name])) | Generates the actual list of data.
@jjdelc:
This has been shamelessly copied from original
django.contrib.admin.templatetags.admin_list.items_for_result
in order to alter the dispay for the first element | ### Input:
Generates the actual list of data.
@jjdelc:
This has been shamelessly copied from original
django.contrib.admin.templatetags.admin_list.items_for_result
in order to alter the dispay for the first element
### Response:
def items_for_result(cl, result, form):
first = True
pk = cl.lookup_opts.pk.attname
for field_name in cl.list_display:
result_repr, row_class = get_result_and_row_class(cl, field_name,
result)
if (first and not cl.list_display_links) or \
field_name in cl.list_display_links:
table_tag = {True: , False: }[first]
spacer = get_spacer(first, result)
collapse = get_collapse(result)
drag_handler = get_drag_handler(first)
first = False
url = cl.url_for_result(result)
if cl.to_field:
attr = str(cl.to_field)
else:
attr = pk
value = result.serializable_value(attr)
result_id = "" % force_str(value)
onclickstr = (
)
yield mark_safe(
u() % (
drag_handler, table_tag, row_class, spacer, collapse, url,
(cl.is_popup and onclickstr % result_id or ),
conditional_escape(result_repr), table_tag))
else:
if (
form and
field_name in form.fields and
not (
field_name == cl.model._meta.pk.name and
form[cl.model._meta.pk.name].is_hidden
)
):
bf = form[field_name]
result_repr = mark_safe(force_str(bf.errors) + force_str(bf))
yield format_html(u(), row_class, result_repr)
if form and not form[cl.model._meta.pk.name].is_hidden:
yield format_html(u(),
force_str(form[cl.model._meta.pk.name])) |
def base(context, config, database, root, log_level):
coloredlogs.install(level=log_level)
context.obj = ruamel.yaml.safe_load(config) if config else {}
context.obj[] = database if database else context.obj[]
context.obj[] = root if root else context.obj[] | Housekeeper - Access your files! | ### Input:
Housekeeper - Access your files!
### Response:
def base(context, config, database, root, log_level):
coloredlogs.install(level=log_level)
context.obj = ruamel.yaml.safe_load(config) if config else {}
context.obj[] = database if database else context.obj[]
context.obj[] = root if root else context.obj[] |
def setOptimizedForIPTV(self, status, wifiInterfaceId=1, timeout=1):
namespace = Fritz.getServiceType("setOptimizedForIPTV") + str(wifiInterfaceId)
uri = self.getControlURL(namespace)
if status:
setStatus = 1
else:
setStatus = 0
arguments = {"timeout": timeout, "NewX_AVM-DE_IPTVoptimize": setStatus}
self.execute(uri, namespace, "X_AVM-DE_SetIPTVOptimized", **arguments) | Set if the Wifi interface is optimized for IP TV
:param bool status: set if Wifi interface should be optimized
:param int wifiInterfaceId: the id of the Wifi interface
:param float timeout: the timeout to wait for the action to be executed
.. seealso:: :meth:`~simpletr64.actions.Fritz.isOptimizedForIPTV` | ### Input:
Set if the Wifi interface is optimized for IP TV
:param bool status: set if Wifi interface should be optimized
:param int wifiInterfaceId: the id of the Wifi interface
:param float timeout: the timeout to wait for the action to be executed
.. seealso:: :meth:`~simpletr64.actions.Fritz.isOptimizedForIPTV`
### Response:
def setOptimizedForIPTV(self, status, wifiInterfaceId=1, timeout=1):
namespace = Fritz.getServiceType("setOptimizedForIPTV") + str(wifiInterfaceId)
uri = self.getControlURL(namespace)
if status:
setStatus = 1
else:
setStatus = 0
arguments = {"timeout": timeout, "NewX_AVM-DE_IPTVoptimize": setStatus}
self.execute(uri, namespace, "X_AVM-DE_SetIPTVOptimized", **arguments) |
def ipv6_acl_ipv6_access_list_standard_seq_action(self, **kwargs):
config = ET.Element("config")
ipv6_acl = ET.SubElement(config, "ipv6-acl", xmlns="urn:brocade.com:mgmt:brocade-ipv6-access-list")
ipv6 = ET.SubElement(ipv6_acl, "ipv6")
access_list = ET.SubElement(ipv6, "access-list")
standard = ET.SubElement(access_list, "standard")
name_key = ET.SubElement(standard, "name")
name_key.text = kwargs.pop()
seq = ET.SubElement(standard, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop()
action = ET.SubElement(seq, "action")
action.text = kwargs.pop()
callback = kwargs.pop(, self._callback)
return callback(config) | Auto Generated Code | ### Input:
Auto Generated Code
### Response:
def ipv6_acl_ipv6_access_list_standard_seq_action(self, **kwargs):
config = ET.Element("config")
ipv6_acl = ET.SubElement(config, "ipv6-acl", xmlns="urn:brocade.com:mgmt:brocade-ipv6-access-list")
ipv6 = ET.SubElement(ipv6_acl, "ipv6")
access_list = ET.SubElement(ipv6, "access-list")
standard = ET.SubElement(access_list, "standard")
name_key = ET.SubElement(standard, "name")
name_key.text = kwargs.pop()
seq = ET.SubElement(standard, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop()
action = ET.SubElement(seq, "action")
action.text = kwargs.pop()
callback = kwargs.pop(, self._callback)
return callback(config) |
def insert_df(self, table_name, df):
df.to_sql(table_name, con=self.own_connection) | Create a table and populate it with data from a dataframe. | ### Input:
Create a table and populate it with data from a dataframe.
### Response:
def insert_df(self, table_name, df):
df.to_sql(table_name, con=self.own_connection) |
def get_average_length_of_string(strings):
if not strings:
return 0
return sum(len(word) for word in strings) / len(strings) | Computes average length of words
:param strings: list of words
:return: Average length of word on list | ### Input:
Computes average length of words
:param strings: list of words
:return: Average length of word on list
### Response:
def get_average_length_of_string(strings):
if not strings:
return 0
return sum(len(word) for word in strings) / len(strings) |
def Hvap(self):
rwater
Hvamp = self.Hvapm
if Hvamp:
return property_molar_to_mass(Hvamp, self.MW)
return None | r'''Enthalpy of vaporization of the chemical at its current temperature,
in units of [J/kg].
This property uses the object-oriented interface
:obj:`thermo.phase_change.EnthalpyVaporization`, but converts its
results from molar to mass units.
Examples
--------
>>> Chemical('water', T=320).Hvap
2389540.219347256 | ### Input:
r'''Enthalpy of vaporization of the chemical at its current temperature,
in units of [J/kg].
This property uses the object-oriented interface
:obj:`thermo.phase_change.EnthalpyVaporization`, but converts its
results from molar to mass units.
Examples
--------
>>> Chemical('water', T=320).Hvap
2389540.219347256
### Response:
def Hvap(self):
rwater
Hvamp = self.Hvapm
if Hvamp:
return property_molar_to_mass(Hvamp, self.MW)
return None |
def stream(self):
if self._stream is None:
self._stream = tempfile.NamedTemporaryFile(delete=False)
try:
self._stream.write(self.client.open(self.filename, view=).read())
except:
pass
return self._stream | the stream to write the log content too.
@return: | ### Input:
the stream to write the log content too.
@return:
### Response:
def stream(self):
if self._stream is None:
self._stream = tempfile.NamedTemporaryFile(delete=False)
try:
self._stream.write(self.client.open(self.filename, view=).read())
except:
pass
return self._stream |
def create_directory(self, path=None):
if path is None:
path = self.get_path()
if not os.path.exists(path):
os.makedirs(path) | Create the directory for the given path. If path is None use the path of this instance
:param path: the path to create
:type path: str
:returns: None
:rtype: None
:raises: OSError | ### Input:
Create the directory for the given path. If path is None use the path of this instance
:param path: the path to create
:type path: str
:returns: None
:rtype: None
:raises: OSError
### Response:
def create_directory(self, path=None):
if path is None:
path = self.get_path()
if not os.path.exists(path):
os.makedirs(path) |
def split_sentences_spacy(text, language_model=):
r
doc = nlp(text)
sentences = []
if not hasattr(doc, ):
logger.warning("Using NLTK sentence tokenizer because SpaCy language model hasn'.join(doc[i].string for i in range(span.start, span.end)).strip()
if len(sent):
sentences.append(sent)
return sentences | r""" You must download a spacy language model with python -m download 'en'
The default English language model for spacy tends to be a lot more agressive than NLTK's punkt:
>>> split_sentences_nltk("Hi Ms. Lovelace.\nI'm a wanna-\nbe human @ I.B.M. ;) --Watson 2.0")
['Hi Ms. Lovelace.', "I'm a wanna-\nbe human @ I.B.M.", ';) --Watson 2.0']
>>> split_sentences_spacy("Hi Ms. Lovelace.\nI'm a wanna-\nbe human @ I.B.M. ;) --Watson 2.0")
['Hi Ms. Lovelace.', "I'm a wanna-", 'be human @', 'I.B.M. ;) --Watson 2.0']
>>> split_sentences_spacy("Hi Ms. Lovelace. I'm at I.B.M. --Watson 2.0")
['Hi Ms. Lovelace.', "I'm at I.B.M. --Watson 2.0"]
>>> split_sentences_nltk("Hi Ms. Lovelace. I'm at I.B.M. --Watson 2.0")
['Hi Ms. Lovelace.', "I'm at I.B.M.", '--Watson 2.0'] | ### Input:
r""" You must download a spacy language model with python -m download 'en'
The default English language model for spacy tends to be a lot more agressive than NLTK's punkt:
>>> split_sentences_nltk("Hi Ms. Lovelace.\nI'm a wanna-\nbe human @ I.B.M. ;) --Watson 2.0")
['Hi Ms. Lovelace.', "I'm a wanna-\nbe human @ I.B.M.", ';) --Watson 2.0']
>>> split_sentences_spacy("Hi Ms. Lovelace.\nI'm a wanna-\nbe human @ I.B.M. ;) --Watson 2.0")
['Hi Ms. Lovelace.', "I'm a wanna-", 'be human @', 'I.B.M. ;) --Watson 2.0']
>>> split_sentences_spacy("Hi Ms. Lovelace. I'm at I.B.M. --Watson 2.0")
['Hi Ms. Lovelace.', "I'm at I.B.M. --Watson 2.0"]
>>> split_sentences_nltk("Hi Ms. Lovelace. I'm at I.B.M. --Watson 2.0")
['Hi Ms. Lovelace.', "I'm at I.B.M.", '--Watson 2.0']
### Response:
def split_sentences_spacy(text, language_model=):
r
doc = nlp(text)
sentences = []
if not hasattr(doc, ):
logger.warning("Using NLTK sentence tokenizer because SpaCy language model hasn'.join(doc[i].string for i in range(span.start, span.end)).strip()
if len(sent):
sentences.append(sent)
return sentences |
def event(self, event):
if (event.type() == QEvent.KeyPress) and (event.key() == Qt.Key_Tab):
self.sig_tab_pressed.emit(True)
self.numpress += 1
if self.numpress == 1:
self.presstimer = QTimer.singleShot(400, self.handle_keypress)
return True
return QComboBox.event(self, event) | Qt Override.
Filter tab keys and process double tab keys. | ### Input:
Qt Override.
Filter tab keys and process double tab keys.
### Response:
def event(self, event):
if (event.type() == QEvent.KeyPress) and (event.key() == Qt.Key_Tab):
self.sig_tab_pressed.emit(True)
self.numpress += 1
if self.numpress == 1:
self.presstimer = QTimer.singleShot(400, self.handle_keypress)
return True
return QComboBox.event(self, event) |
def findHotspot( self, name ):
for hotspot in self._hotspots:
if ( hotspot.name() == name ):
return hotspot
return None | Finds the hotspot based on the inputed name.
:param name | <str>
:return <XNodeHotspot> || None | ### Input:
Finds the hotspot based on the inputed name.
:param name | <str>
:return <XNodeHotspot> || None
### Response:
def findHotspot( self, name ):
for hotspot in self._hotspots:
if ( hotspot.name() == name ):
return hotspot
return None |
def document_partition_url(self, partition_key):
return .join((
self._database.database_partition_url(partition_key),
,
url_quote_plus(self[][8:], safe=)
)) | Retrieve the design document partition URL.
:param str partition_key: Partition key.
:return: Design document partition URL.
:rtype: str | ### Input:
Retrieve the design document partition URL.
:param str partition_key: Partition key.
:return: Design document partition URL.
:rtype: str
### Response:
def document_partition_url(self, partition_key):
return .join((
self._database.database_partition_url(partition_key),
,
url_quote_plus(self[][8:], safe=)
)) |
def initialize(self, max_batch_size: int, max_input_length: int, get_max_output_length_function: Callable):
self.max_batch_size = max_batch_size
self.max_input_length = max_input_length
if self.max_input_length > self.training_max_seq_len_source:
logger.warning("Model was only trained with sentences up to a length of %d, "
"but a max_input_len of %d is used.",
self.training_max_seq_len_source, self.max_input_length)
self.get_max_output_length = get_max_output_length_function
if self.max_supported_seq_len_source is not None:
utils.check_condition(self.max_input_length <= self.max_supported_seq_len_source,
"Encoder only supports a maximum length of %d" % self.max_supported_seq_len_source)
if self.max_supported_seq_len_target is not None:
decoder_max_len = self.get_max_output_length(max_input_length)
utils.check_condition(decoder_max_len <= self.max_supported_seq_len_target,
"Decoder only supports a maximum length of %d, but %d was requested. Note that the "
"maximum output length depends on the input length and the source/target length "
"ratio observed during training." % (self.max_supported_seq_len_target,
decoder_max_len))
self.encoder_module, self.encoder_default_bucket_key = self._get_encoder_module()
self.decoder_module, self.decoder_default_bucket_key = self._get_decoder_module()
max_encoder_data_shapes = self._get_encoder_data_shapes(self.encoder_default_bucket_key,
self.max_batch_size)
max_decoder_data_shapes = self._get_decoder_data_shapes(self.decoder_default_bucket_key,
self.max_batch_size * self.beam_size)
self.encoder_module.bind(data_shapes=max_encoder_data_shapes, for_training=False, grad_req="null")
self.decoder_module.bind(data_shapes=max_decoder_data_shapes, for_training=False, grad_req="null")
self.load_params_from_file(self.params_fname)
self.encoder_module.init_params(arg_params=self.params, aux_params=self.aux_params, allow_missing=False)
self.decoder_module.init_params(arg_params=self.params, aux_params=self.aux_params, allow_missing=False)
if self.cache_output_layer_w_b:
if self.output_layer.weight_normalization:
assert self.output_layer.weight_norm is not None
weight = self.params[self.output_layer.weight_norm.weight.name].as_in_context(self.context)
scale = self.params[self.output_layer.weight_norm.scale.name].as_in_context(self.context)
self.output_layer_w = self.output_layer.weight_norm(weight, scale)
else:
self.output_layer_w = self.params[self.output_layer.w.name].as_in_context(self.context)
self.output_layer_b = self.params[self.output_layer.b.name].as_in_context(self.context) | Delayed construction of modules to ensure multiple Inference models can agree on computing a common
maximum output length.
:param max_batch_size: Maximum batch size.
:param max_input_length: Maximum input length.
:param get_max_output_length_function: Callable to compute maximum output length. | ### Input:
Delayed construction of modules to ensure multiple Inference models can agree on computing a common
maximum output length.
:param max_batch_size: Maximum batch size.
:param max_input_length: Maximum input length.
:param get_max_output_length_function: Callable to compute maximum output length.
### Response:
def initialize(self, max_batch_size: int, max_input_length: int, get_max_output_length_function: Callable):
self.max_batch_size = max_batch_size
self.max_input_length = max_input_length
if self.max_input_length > self.training_max_seq_len_source:
logger.warning("Model was only trained with sentences up to a length of %d, "
"but a max_input_len of %d is used.",
self.training_max_seq_len_source, self.max_input_length)
self.get_max_output_length = get_max_output_length_function
if self.max_supported_seq_len_source is not None:
utils.check_condition(self.max_input_length <= self.max_supported_seq_len_source,
"Encoder only supports a maximum length of %d" % self.max_supported_seq_len_source)
if self.max_supported_seq_len_target is not None:
decoder_max_len = self.get_max_output_length(max_input_length)
utils.check_condition(decoder_max_len <= self.max_supported_seq_len_target,
"Decoder only supports a maximum length of %d, but %d was requested. Note that the "
"maximum output length depends on the input length and the source/target length "
"ratio observed during training." % (self.max_supported_seq_len_target,
decoder_max_len))
self.encoder_module, self.encoder_default_bucket_key = self._get_encoder_module()
self.decoder_module, self.decoder_default_bucket_key = self._get_decoder_module()
max_encoder_data_shapes = self._get_encoder_data_shapes(self.encoder_default_bucket_key,
self.max_batch_size)
max_decoder_data_shapes = self._get_decoder_data_shapes(self.decoder_default_bucket_key,
self.max_batch_size * self.beam_size)
self.encoder_module.bind(data_shapes=max_encoder_data_shapes, for_training=False, grad_req="null")
self.decoder_module.bind(data_shapes=max_decoder_data_shapes, for_training=False, grad_req="null")
self.load_params_from_file(self.params_fname)
self.encoder_module.init_params(arg_params=self.params, aux_params=self.aux_params, allow_missing=False)
self.decoder_module.init_params(arg_params=self.params, aux_params=self.aux_params, allow_missing=False)
if self.cache_output_layer_w_b:
if self.output_layer.weight_normalization:
assert self.output_layer.weight_norm is not None
weight = self.params[self.output_layer.weight_norm.weight.name].as_in_context(self.context)
scale = self.params[self.output_layer.weight_norm.scale.name].as_in_context(self.context)
self.output_layer_w = self.output_layer.weight_norm(weight, scale)
else:
self.output_layer_w = self.params[self.output_layer.w.name].as_in_context(self.context)
self.output_layer_b = self.params[self.output_layer.b.name].as_in_context(self.context) |
def update_rho(self, k, r, s):
if self.opt[, ]:
tau = self.rho_tau
mu = self.rho_mu
xi = self.rho_xi
if k != 0 and np.mod(k + 1, self.opt[, ]) == 0:
if self.opt[, ]:
if s == 0.0 or r == 0.0:
rhomlt = tau
else:
rhomlt = np.sqrt(r / (s * xi) if r > s * xi else
(s * xi) / r)
if rhomlt > tau:
rhomlt = tau
else:
rhomlt = tau
rsf = 1.0
if r > xi * mu * s:
rsf = rhomlt
elif s > (mu / xi) * r:
rsf = 1.0 / rhomlt
self.rho *= self.dtype.type(rsf)
self.U /= rsf
if rsf != 1.0:
self.rhochange() | Automatic rho adjustment. | ### Input:
Automatic rho adjustment.
### Response:
def update_rho(self, k, r, s):
if self.opt[, ]:
tau = self.rho_tau
mu = self.rho_mu
xi = self.rho_xi
if k != 0 and np.mod(k + 1, self.opt[, ]) == 0:
if self.opt[, ]:
if s == 0.0 or r == 0.0:
rhomlt = tau
else:
rhomlt = np.sqrt(r / (s * xi) if r > s * xi else
(s * xi) / r)
if rhomlt > tau:
rhomlt = tau
else:
rhomlt = tau
rsf = 1.0
if r > xi * mu * s:
rsf = rhomlt
elif s > (mu / xi) * r:
rsf = 1.0 / rhomlt
self.rho *= self.dtype.type(rsf)
self.U /= rsf
if rsf != 1.0:
self.rhochange() |
def readMNIST(sc, output, format):
output_images = output + "/images"
output_labels = output + "/labels"
imageRDD = None
labelRDD = None
if format == "pickle":
imageRDD = sc.pickleFile(output_images)
labelRDD = sc.pickleFile(output_labels)
elif format == "csv":
imageRDD = sc.textFile(output_images).map(fromCSV)
labelRDD = sc.textFile(output_labels).map(fromCSV)
else:
tfRDD = sc.newAPIHadoopFile(output, "org.tensorflow.hadoop.io.TFRecordFileInputFormat",
keyClass="org.apache.hadoop.io.BytesWritable",
valueClass="org.apache.hadoop.io.NullWritable")
imageRDD = tfRDD.map(lambda x: fromTFExample(bytes(x[0])))
num_images = imageRDD.count()
num_labels = labelRDD.count() if labelRDD is not None else num_images
samples = imageRDD.take(10)
print("num_images: ", num_images)
print("num_labels: ", num_labels)
print("samples: ", samples) | Reads/verifies previously created output | ### Input:
Reads/verifies previously created output
### Response:
def readMNIST(sc, output, format):
output_images = output + "/images"
output_labels = output + "/labels"
imageRDD = None
labelRDD = None
if format == "pickle":
imageRDD = sc.pickleFile(output_images)
labelRDD = sc.pickleFile(output_labels)
elif format == "csv":
imageRDD = sc.textFile(output_images).map(fromCSV)
labelRDD = sc.textFile(output_labels).map(fromCSV)
else:
tfRDD = sc.newAPIHadoopFile(output, "org.tensorflow.hadoop.io.TFRecordFileInputFormat",
keyClass="org.apache.hadoop.io.BytesWritable",
valueClass="org.apache.hadoop.io.NullWritable")
imageRDD = tfRDD.map(lambda x: fromTFExample(bytes(x[0])))
num_images = imageRDD.count()
num_labels = labelRDD.count() if labelRDD is not None else num_images
samples = imageRDD.take(10)
print("num_images: ", num_images)
print("num_labels: ", num_labels)
print("samples: ", samples) |
def get_instance(self, payload):
return ParticipantInstance(
self._version,
payload,
account_sid=self._solution[],
conference_sid=self._solution[],
) | Build an instance of ParticipantInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.conference.participant.ParticipantInstance
:rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantInstance | ### Input:
Build an instance of ParticipantInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.conference.participant.ParticipantInstance
:rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantInstance
### Response:
def get_instance(self, payload):
return ParticipantInstance(
self._version,
payload,
account_sid=self._solution[],
conference_sid=self._solution[],
) |
def hpoterms():
query = request.args.get()
if query is None:
return abort(500)
terms = sorted(store.hpo_terms(query=query), key=itemgetter())
json_terms = [
{: .format(term[], term[]),
: term[]
} for term in terms[:7]]
return jsonify(json_terms) | Search for HPO terms. | ### Input:
Search for HPO terms.
### Response:
def hpoterms():
query = request.args.get()
if query is None:
return abort(500)
terms = sorted(store.hpo_terms(query=query), key=itemgetter())
json_terms = [
{: .format(term[], term[]),
: term[]
} for term in terms[:7]]
return jsonify(json_terms) |
def init(self):
import subprocess
import fcntl
width = str(self.image_dimensions[0])
height = str(self.image_dimensions[1])
comlist = self.executable.split() + [width, height, self.tmpfile]
try:
self.p = subprocess.Popen(comlist, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
except Exception as e:
print(self.pre, "Could not open external process. Failed with ")
return
self.reset() | Start the process | ### Input:
Start the process
### Response:
def init(self):
import subprocess
import fcntl
width = str(self.image_dimensions[0])
height = str(self.image_dimensions[1])
comlist = self.executable.split() + [width, height, self.tmpfile]
try:
self.p = subprocess.Popen(comlist, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
except Exception as e:
print(self.pre, "Could not open external process. Failed with ")
return
self.reset() |
def get_voms_proxy_user():
out = _voms_proxy_info(["--identity"])[1].strip()
try:
return re.match(r".*\/CN\=([^\/]+).*", out.strip()).group(1)
except:
raise Exception("no valid identity found in voms proxy: {}".format(out)) | Returns the owner of the voms proxy. | ### Input:
Returns the owner of the voms proxy.
### Response:
def get_voms_proxy_user():
out = _voms_proxy_info(["--identity"])[1].strip()
try:
return re.match(r".*\/CN\=([^\/]+).*", out.strip()).group(1)
except:
raise Exception("no valid identity found in voms proxy: {}".format(out)) |
def _run_toolkit_function(fnname, arguments, args, kwargs):
num_args_got = len(args) + len(kwargs)
num_args_required = len(arguments)
if num_args_got != num_args_required:
raise TypeError("Expecting " + str(num_args_required) + " arguments, got " + str(num_args_got))
argument_dict = {}
for i in range(len(args)):
argument_dict[arguments[i]] = args[i]
for k in kwargs.keys():
if k in argument_dict:
raise TypeError("Got multiple values for keyword argument ")
argument_dict[k] = kwargs[k]
with cython_context():
ret = _get_unity().run_toolkit(fnname, argument_dict)
if not ret[0]:
if len(ret[1]) > 0:
raise _ToolkitError(ret[1])
else:
raise _ToolkitError("Toolkit failed with unknown error")
ret = _wrap_function_return(ret[2])
if type(ret) is dict and in ret:
return ret[]
else:
return ret | Dispatches arguments to a toolkit function.
Parameters
----------
fnname : string
The toolkit function to run
arguments : list[string]
The list of all the arguments the function takes.
args : list
The arguments that were passed
kwargs : dictionary
The keyword arguments that were passed | ### Input:
Dispatches arguments to a toolkit function.
Parameters
----------
fnname : string
The toolkit function to run
arguments : list[string]
The list of all the arguments the function takes.
args : list
The arguments that were passed
kwargs : dictionary
The keyword arguments that were passed
### Response:
def _run_toolkit_function(fnname, arguments, args, kwargs):
num_args_got = len(args) + len(kwargs)
num_args_required = len(arguments)
if num_args_got != num_args_required:
raise TypeError("Expecting " + str(num_args_required) + " arguments, got " + str(num_args_got))
argument_dict = {}
for i in range(len(args)):
argument_dict[arguments[i]] = args[i]
for k in kwargs.keys():
if k in argument_dict:
raise TypeError("Got multiple values for keyword argument ")
argument_dict[k] = kwargs[k]
with cython_context():
ret = _get_unity().run_toolkit(fnname, argument_dict)
if not ret[0]:
if len(ret[1]) > 0:
raise _ToolkitError(ret[1])
else:
raise _ToolkitError("Toolkit failed with unknown error")
ret = _wrap_function_return(ret[2])
if type(ret) is dict and in ret:
return ret[]
else:
return ret |
def from_cli(cls, opts):
logging.info("Reading configuration file")
if opts.config_overrides is not None:
overrides = [override.split(":")
for override in opts.config_overrides]
else:
overrides = None
if opts.config_delete is not None:
deletes = [delete.split(":") for delete in opts.config_delete]
else:
deletes = None
return cls(opts.config_files, overrides, deleteTuples=deletes) | Loads a config file from the given options, with overrides and
deletes applied. | ### Input:
Loads a config file from the given options, with overrides and
deletes applied.
### Response:
def from_cli(cls, opts):
logging.info("Reading configuration file")
if opts.config_overrides is not None:
overrides = [override.split(":")
for override in opts.config_overrides]
else:
overrides = None
if opts.config_delete is not None:
deletes = [delete.split(":") for delete in opts.config_delete]
else:
deletes = None
return cls(opts.config_files, overrides, deleteTuples=deletes) |
def y_select_cb(self, w, index):
try:
self.y_col = self.cols[index]
except IndexError as e:
self.logger.error(str(e))
else:
self.plot_two_columns(reset_ylimits=True) | Callback to set Y-axis column. | ### Input:
Callback to set Y-axis column.
### Response:
def y_select_cb(self, w, index):
try:
self.y_col = self.cols[index]
except IndexError as e:
self.logger.error(str(e))
else:
self.plot_two_columns(reset_ylimits=True) |
def num_open_files(self):
return reduce(lambda x, y: x + y, (1 for rlist in self._fdict.values() if len(rlist) > 0), 0) | Amount of opened files in the system | ### Input:
Amount of opened files in the system
### Response:
def num_open_files(self):
return reduce(lambda x, y: x + y, (1 for rlist in self._fdict.values() if len(rlist) > 0), 0) |
def strip_output(nb):
nb.metadata.pop(, None)
nb.metadata.pop(, None)
for cell in _cells(nb):
if in cell:
cell[] = []
if in cell:
cell[] = None
return nb | strip the outputs from a notebook object | ### Input:
strip the outputs from a notebook object
### Response:
def strip_output(nb):
nb.metadata.pop(, None)
nb.metadata.pop(, None)
for cell in _cells(nb):
if in cell:
cell[] = []
if in cell:
cell[] = None
return nb |
def connect(self, name, func, sender=None, dispatch_uid=None):
try:
signal = self._registry[name]
except KeyError:
signal = self.register(name)
signal.connect(func, sender=sender, dispatch_uid=dispatch_uid) | Connects a function to a hook.\
Creates the hook (name) if it does not exists
:param str name: The hook name
:param callable func: A function reference used as a callback
:param class sender: Optional sender __class__ to which the\
func should respond. Default will match all
:param str dispatch_uid: Optional unique id,\
see :py:class:`django.dispatch.Signal` for more info | ### Input:
Connects a function to a hook.\
Creates the hook (name) if it does not exists
:param str name: The hook name
:param callable func: A function reference used as a callback
:param class sender: Optional sender __class__ to which the\
func should respond. Default will match all
:param str dispatch_uid: Optional unique id,\
see :py:class:`django.dispatch.Signal` for more info
### Response:
def connect(self, name, func, sender=None, dispatch_uid=None):
try:
signal = self._registry[name]
except KeyError:
signal = self.register(name)
signal.connect(func, sender=sender, dispatch_uid=dispatch_uid) |
def _filter_or_exclude_querysets(self, negate, **kwargs):
negate = bool(negate)
for kwarg, value in kwargs.items():
parts = kwarg.split(LOOKUP_SEP)
if parts[0] != :
raise ValueError("Keyword is not a valid keyword to filter over, "
"it must begin with ." % kwarg)
pass
if lookup in (, ):
value = six.text_type(value)
self._queryset_idxs = filter(lambda i: (value in six.text_type(i)) != negate, self._queryset_idxs)
elif lookup == :
self._queryset_idxs = filter(lambda i: (i in value) != negate, self._queryset_idxs)
elif lookup in (, ):
value = six.text_type(value)
self._queryset_idxs = filter(lambda i: six.text_type(i).startswith(value) != negate, self._queryset_idxs)
elif lookup in (, ):
value = six.text_type(value)
self._queryset_idxs = filter(lambda i: six.text_type(i).endswith(value) != negate, self._queryset_idxs)
elif lookup == :
start, end = value
self._queryset_idxs = filter(lambda i: (start <= i <= end) != negate, self._queryset_idxs)
else:
raise ValueError("Unsupported lookup " % lookup)
self._queryset_idxs = list(self._queryset_idxs)
self._querysets = [self._querysets[i] for i in self._queryset_idxs] | Similar to QuerySet._filter_or_exclude, but run over the QuerySets in
the QuerySetSequence instead of over each QuerySet's fields. | ### Input:
Similar to QuerySet._filter_or_exclude, but run over the QuerySets in
the QuerySetSequence instead of over each QuerySet's fields.
### Response:
def _filter_or_exclude_querysets(self, negate, **kwargs):
negate = bool(negate)
for kwarg, value in kwargs.items():
parts = kwarg.split(LOOKUP_SEP)
if parts[0] != :
raise ValueError("Keyword is not a valid keyword to filter over, "
"it must begin with ." % kwarg)
pass
if lookup in (, ):
value = six.text_type(value)
self._queryset_idxs = filter(lambda i: (value in six.text_type(i)) != negate, self._queryset_idxs)
elif lookup == :
self._queryset_idxs = filter(lambda i: (i in value) != negate, self._queryset_idxs)
elif lookup in (, ):
value = six.text_type(value)
self._queryset_idxs = filter(lambda i: six.text_type(i).startswith(value) != negate, self._queryset_idxs)
elif lookup in (, ):
value = six.text_type(value)
self._queryset_idxs = filter(lambda i: six.text_type(i).endswith(value) != negate, self._queryset_idxs)
elif lookup == :
start, end = value
self._queryset_idxs = filter(lambda i: (start <= i <= end) != negate, self._queryset_idxs)
else:
raise ValueError("Unsupported lookup " % lookup)
self._queryset_idxs = list(self._queryset_idxs)
self._querysets = [self._querysets[i] for i in self._queryset_idxs] |
def _get_override_lookup_session(self):
from ..utilities import OVERRIDE_VAULT_TYPE
try:
override_vaults = self._get_vault_lookup_session().get_vaults_by_genus_type(OVERRIDE_VAULT_TYPE)
except Unimplemented:
return None
if override_vaults.available():
vault = override_vaults.next()
else:
return None
session = self._get_authz_manager().get_authorization_lookup_session_for_vault(vault.get_id())
session.use_isolated_vault_view()
return session | Gets the AuthorizationLookupSession for the override typed Vault
Assumes only one | ### Input:
Gets the AuthorizationLookupSession for the override typed Vault
Assumes only one
### Response:
def _get_override_lookup_session(self):
from ..utilities import OVERRIDE_VAULT_TYPE
try:
override_vaults = self._get_vault_lookup_session().get_vaults_by_genus_type(OVERRIDE_VAULT_TYPE)
except Unimplemented:
return None
if override_vaults.available():
vault = override_vaults.next()
else:
return None
session = self._get_authz_manager().get_authorization_lookup_session_for_vault(vault.get_id())
session.use_isolated_vault_view()
return session |
def main(argv=None):
arguments = cli_common(__doc__, argv=argv)
es_export = ESExporter(arguments[], arguments[])
es_export.export()
if argv is not None:
return es_export | ben-elastic entry point | ### Input:
ben-elastic entry point
### Response:
def main(argv=None):
arguments = cli_common(__doc__, argv=argv)
es_export = ESExporter(arguments[], arguments[])
es_export.export()
if argv is not None:
return es_export |
def export(self, view_datas):
view_datas_copy = \
[self.copy_and_finalize_view_data(vd) for vd in view_datas]
if len(self.exporters) > 0:
for e in self.exporters:
try:
e.export(view_datas_copy)
except AttributeError:
pass | export view datas to registered exporters | ### Input:
export view datas to registered exporters
### Response:
def export(self, view_datas):
view_datas_copy = \
[self.copy_and_finalize_view_data(vd) for vd in view_datas]
if len(self.exporters) > 0:
for e in self.exporters:
try:
e.export(view_datas_copy)
except AttributeError:
pass |
def set_allowed(self, initial_state, *allowed_states):
allowed_states = list(allowed_states)
self._allowed.setdefault(initial_state, set()).update(allowed_states)
for state in allowed_states + [initial_state]:
if state not in self.possible_states:
self.possible_states.append(state) | Add an allowed transition from initial_state to allowed_states | ### Input:
Add an allowed transition from initial_state to allowed_states
### Response:
def set_allowed(self, initial_state, *allowed_states):
allowed_states = list(allowed_states)
self._allowed.setdefault(initial_state, set()).update(allowed_states)
for state in allowed_states + [initial_state]:
if state not in self.possible_states:
self.possible_states.append(state) |
def barmatch2(data, tups, cutters, longbar, matchdict, fnum):
waitchunk = int(1e6)
epid = os.getpid()
filestat = np.zeros(3, dtype=np.int)
samplehits = {}
dsort1 = {}
dsort2 = {}
dbars = {}
for sname in data.barcodes:
if "-technical-replicate-" in sname:
sname = sname.rsplit("-technical-replicate", 1)[0]
samplehits[sname] = 0
dsort1[sname] = []
dsort2[sname] = []
dbars[sname] = set()
barhits = {}
for barc in matchdict:
barhits[barc] = 0
misses = {}
misses[] = 0
getbarcode = get_barcode_func(data, longbar)
if tups[0].endswith(".gz"):
ofunc = gzip.open
else:
ofunc = open
ofile1 = ofunc(tups[0], )
fr1 = iter(ofile1)
quart1 = itertools.izip(fr1, fr1, fr1, fr1)
if tups[1]:
ofile2 = ofunc(tups[1], )
fr2 = iter(ofile2)
quart2 = itertools.izip(fr2, fr2, fr2, fr2)
quarts = itertools.izip(quart1, quart2)
else:
quarts = itertools.izip(quart1, iter(int, 1))
while 1:
try:
read1, read2 = quarts.next()
read1 = list(read1)
filestat[0] += 1
except StopIteration:
break
barcode = ""
if in data.paramsdict["datatype"]:
if not filestat[0] % waitchunk:
writetofile(data, dsort1, 1, epid)
if in data.paramsdict["datatype"]:
writetofile(data, dsort2, 2, epid)
for sample in data.barcodes:
if "-technical-replicate-" in sname:
sname = sname.rsplit("-technical-replicate", 1)[0]
dsort1[sname] = []
dsort2[sname] = []
ofile1.close()
if tups[1]:
ofile2.close()
writetofile(data, dsort1, 1, epid)
if in data.paramsdict["datatype"]:
writetofile(data, dsort2, 2, epid)
samplestats = [samplehits, barhits, misses, dbars]
outname = os.path.join(data.dirs.fastqs, "tmp_{}_{}.p".format(epid, fnum))
with open(outname, ) as wout:
pickle.dump([filestat, samplestats], wout)
return outname | cleaner barmatch func... | ### Input:
cleaner barmatch func...
### Response:
def barmatch2(data, tups, cutters, longbar, matchdict, fnum):
waitchunk = int(1e6)
epid = os.getpid()
filestat = np.zeros(3, dtype=np.int)
samplehits = {}
dsort1 = {}
dsort2 = {}
dbars = {}
for sname in data.barcodes:
if "-technical-replicate-" in sname:
sname = sname.rsplit("-technical-replicate", 1)[0]
samplehits[sname] = 0
dsort1[sname] = []
dsort2[sname] = []
dbars[sname] = set()
barhits = {}
for barc in matchdict:
barhits[barc] = 0
misses = {}
misses[] = 0
getbarcode = get_barcode_func(data, longbar)
if tups[0].endswith(".gz"):
ofunc = gzip.open
else:
ofunc = open
ofile1 = ofunc(tups[0], )
fr1 = iter(ofile1)
quart1 = itertools.izip(fr1, fr1, fr1, fr1)
if tups[1]:
ofile2 = ofunc(tups[1], )
fr2 = iter(ofile2)
quart2 = itertools.izip(fr2, fr2, fr2, fr2)
quarts = itertools.izip(quart1, quart2)
else:
quarts = itertools.izip(quart1, iter(int, 1))
while 1:
try:
read1, read2 = quarts.next()
read1 = list(read1)
filestat[0] += 1
except StopIteration:
break
barcode = ""
if in data.paramsdict["datatype"]:
if not filestat[0] % waitchunk:
writetofile(data, dsort1, 1, epid)
if in data.paramsdict["datatype"]:
writetofile(data, dsort2, 2, epid)
for sample in data.barcodes:
if "-technical-replicate-" in sname:
sname = sname.rsplit("-technical-replicate", 1)[0]
dsort1[sname] = []
dsort2[sname] = []
ofile1.close()
if tups[1]:
ofile2.close()
writetofile(data, dsort1, 1, epid)
if in data.paramsdict["datatype"]:
writetofile(data, dsort2, 2, epid)
samplestats = [samplehits, barhits, misses, dbars]
outname = os.path.join(data.dirs.fastqs, "tmp_{}_{}.p".format(epid, fnum))
with open(outname, ) as wout:
pickle.dump([filestat, samplestats], wout)
return outname |
def connect(self, path="", headers=None, query=None, timeout=0, **kwargs):
ret = None
ws_url = self.get_fetch_url(path, query)
ws_headers = self.get_fetch_headers("GET", headers)
ws_headers = [.format(h[0], h[1]) for h in ws_headers.items() if h[1]]
timeout = self.get_timeout(timeout=timeout, **kwargs)
self.set_trace(kwargs.pop("trace", False))
try:
logger.debug("{} connecting to {}".format(self.client_id, ws_url))
self.ws = websocket.create_connection(
ws_url,
header=ws_headers,
timeout=timeout,
sslopt={:ssl.CERT_NONE},
)
ret = self.recv_callback(callback=lambda r: r.uuid == "CONNECT")
if ret.code >= 400:
raise IOError("Failed to connect with code {}".format(ret.code))
except websocket.WebSocketTimeoutException:
raise IOError("Failed to connect within {} seconds".format(timeout))
except websocket.WebSocketException as e:
raise IOError("Failed to connect with error: {}".format(e))
except socket.error as e:
raise
return ret | make the actual connection to the websocket
:param headers: dict, key/val pairs of any headers to add to connection, if
you would like to override headers just pass in an empty value
:param query: dict, any query string params you want to send up with the connection
url
:returns: Payload, this will return the CONNECT response from the websocket | ### Input:
make the actual connection to the websocket
:param headers: dict, key/val pairs of any headers to add to connection, if
you would like to override headers just pass in an empty value
:param query: dict, any query string params you want to send up with the connection
url
:returns: Payload, this will return the CONNECT response from the websocket
### Response:
def connect(self, path="", headers=None, query=None, timeout=0, **kwargs):
ret = None
ws_url = self.get_fetch_url(path, query)
ws_headers = self.get_fetch_headers("GET", headers)
ws_headers = [.format(h[0], h[1]) for h in ws_headers.items() if h[1]]
timeout = self.get_timeout(timeout=timeout, **kwargs)
self.set_trace(kwargs.pop("trace", False))
try:
logger.debug("{} connecting to {}".format(self.client_id, ws_url))
self.ws = websocket.create_connection(
ws_url,
header=ws_headers,
timeout=timeout,
sslopt={:ssl.CERT_NONE},
)
ret = self.recv_callback(callback=lambda r: r.uuid == "CONNECT")
if ret.code >= 400:
raise IOError("Failed to connect with code {}".format(ret.code))
except websocket.WebSocketTimeoutException:
raise IOError("Failed to connect within {} seconds".format(timeout))
except websocket.WebSocketException as e:
raise IOError("Failed to connect with error: {}".format(e))
except socket.error as e:
raise
return ret |
def date(self):
try:
return datetime.date(self.creation_year, 1, 1) + datetime.timedelta(
self.creation_day_of_year - 1
)
except ValueError:
return None | Returns the creation date stored in the las file
Returns
-------
datetime.date | ### Input:
Returns the creation date stored in the las file
Returns
-------
datetime.date
### Response:
def date(self):
try:
return datetime.date(self.creation_year, 1, 1) + datetime.timedelta(
self.creation_day_of_year - 1
)
except ValueError:
return None |
def _got_response(self, msg):
resp_id = msg.get(, None)
if resp_id is None:
method = msg.get(, None)
if not method:
logger.error("Incoming server message had no ID nor method in it", msg)
return
result = msg.get(, None)
logger.debug("Traffic on subscription: %s" % method)
subs = self.subscriptions.get(method)
for q in subs:
self.loop.create_task(q.put(result))
return
assert not in msg
result = msg.get()
inf = self.inflight.pop(resp_id)
if not inf:
logger.error("Incoming server message had unknown ID in it: %s" % resp_id)
return
rv.set_exception(ElectrumErrorResponse(err, req))
else:
rv.set_result(result) | Decode and dispatch responses from the server.
Has already been unframed and deserialized into an object. | ### Input:
Decode and dispatch responses from the server.
Has already been unframed and deserialized into an object.
### Response:
def _got_response(self, msg):
resp_id = msg.get(, None)
if resp_id is None:
method = msg.get(, None)
if not method:
logger.error("Incoming server message had no ID nor method in it", msg)
return
result = msg.get(, None)
logger.debug("Traffic on subscription: %s" % method)
subs = self.subscriptions.get(method)
for q in subs:
self.loop.create_task(q.put(result))
return
assert not in msg
result = msg.get()
inf = self.inflight.pop(resp_id)
if not inf:
logger.error("Incoming server message had unknown ID in it: %s" % resp_id)
return
rv.set_exception(ElectrumErrorResponse(err, req))
else:
rv.set_result(result) |
def fixed_step_return(reward, value, length, discount, window):
timestep = tf.range(reward.shape[1].value)
mask = tf.cast(timestep[None, :] < length[:, None], tf.float32)
return_ = tf.zeros_like(reward)
for _ in range(window):
return_ += reward
reward = discount * tf.concat(
[reward[:, 1:], tf.zeros_like(reward[:, -1:])], 1)
return_ += discount ** window * tf.concat(
[value[:, window:], tf.zeros_like(value[:, -window:])], 1)
return tf.check_numerics(tf.stop_gradient(mask * return_), ) | N-step discounted return. | ### Input:
N-step discounted return.
### Response:
def fixed_step_return(reward, value, length, discount, window):
timestep = tf.range(reward.shape[1].value)
mask = tf.cast(timestep[None, :] < length[:, None], tf.float32)
return_ = tf.zeros_like(reward)
for _ in range(window):
return_ += reward
reward = discount * tf.concat(
[reward[:, 1:], tf.zeros_like(reward[:, -1:])], 1)
return_ += discount ** window * tf.concat(
[value[:, window:], tf.zeros_like(value[:, -window:])], 1)
return tf.check_numerics(tf.stop_gradient(mask * return_), ) |
def timeout(self, duration=3600):
self.room.check_owner()
self.conn.make_call("timeoutFile", self.fid, duration) | Timeout the uploader of this file | ### Input:
Timeout the uploader of this file
### Response:
def timeout(self, duration=3600):
self.room.check_owner()
self.conn.make_call("timeoutFile", self.fid, duration) |
def _cast_to_type(self, value):
try:
return float(value)
except (ValueError, TypeError):
self.fail(, value=value) | Convert the value to a float and raise error on failures | ### Input:
Convert the value to a float and raise error on failures
### Response:
def _cast_to_type(self, value):
try:
return float(value)
except (ValueError, TypeError):
self.fail(, value=value) |
def override_ssh_auth_env():
ssh_auth_sock = "SSH_AUTH_SOCK"
old_ssh_auth_sock = os.environ.get(ssh_auth_sock)
del os.environ[ssh_auth_sock]
yield
if old_ssh_auth_sock:
os.environ[ssh_auth_sock] = old_ssh_auth_sock | Override the `$SSH_AUTH_SOCK `env variable to mock the absence of an SSH agent. | ### Input:
Override the `$SSH_AUTH_SOCK `env variable to mock the absence of an SSH agent.
### Response:
def override_ssh_auth_env():
ssh_auth_sock = "SSH_AUTH_SOCK"
old_ssh_auth_sock = os.environ.get(ssh_auth_sock)
del os.environ[ssh_auth_sock]
yield
if old_ssh_auth_sock:
os.environ[ssh_auth_sock] = old_ssh_auth_sock |
def get_authorization_url(self, redirect_uri, client_id, options=None,
scope=None):
if not options:
options = {}
if not scope:
scope = "manage_accounts,collect_payments," \
"view_user,preapprove_payments," \
"manage_subscriptions,send_money"
options[] = scope
options[] = redirect_uri
options[] = client_id
return self.browser_endpoint + + \
urllib.urlencode(options) | Returns a URL to send the user to in order to get authorization.
After getting authorization the user will return to redirect_uri.
Optionally, scope can be set to limit permissions, and the options
dict can be loaded with any combination of state, user_name
or user_email.
:param str redirect_uri: The URI to redirect to after a authorization.
:param str client_id: The client ID issued by WePay to your app.
:keyword dict options: Allows for passing additional values to the
authorize call, aside from scope, redirect_uri, and etc.
:keyword str scope: A comma-separated string of permissions. | ### Input:
Returns a URL to send the user to in order to get authorization.
After getting authorization the user will return to redirect_uri.
Optionally, scope can be set to limit permissions, and the options
dict can be loaded with any combination of state, user_name
or user_email.
:param str redirect_uri: The URI to redirect to after a authorization.
:param str client_id: The client ID issued by WePay to your app.
:keyword dict options: Allows for passing additional values to the
authorize call, aside from scope, redirect_uri, and etc.
:keyword str scope: A comma-separated string of permissions.
### Response:
def get_authorization_url(self, redirect_uri, client_id, options=None,
scope=None):
if not options:
options = {}
if not scope:
scope = "manage_accounts,collect_payments," \
"view_user,preapprove_payments," \
"manage_subscriptions,send_money"
options[] = scope
options[] = redirect_uri
options[] = client_id
return self.browser_endpoint + + \
urllib.urlencode(options) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.