body_hash stringlengths 64 64 | body stringlengths 23 109k | docstring stringlengths 1 57k | path stringlengths 4 198 | name stringlengths 1 115 | repository_name stringlengths 7 111 | repository_stars float64 0 191k | lang stringclasses 1
value | body_without_docstring stringlengths 14 108k | unified stringlengths 45 133k |
|---|---|---|---|---|---|---|---|---|---|
f0113c27851b3985b63144ce5d653620c1082eebb8bd8bd04c49804bb14e94b5 | @property
def timezone(self):
'Gets the timezone of this V1alpha1CronWorkflowSpec. # noqa: E501\n\n Timezone is the timezone against which the cron schedule will be calculated, e.g. "Asia/Tokyo". Default is machine\'s local time. # noqa: E501\n\n :return: The timezone of this V1alpha1CronWorkflowSpe... | Gets the timezone of this V1alpha1CronWorkflowSpec. # noqa: E501
Timezone is the timezone against which the cron schedule will be calculated, e.g. "Asia/Tokyo". Default is machine's local time. # noqa: E501
:return: The timezone of this V1alpha1CronWorkflowSpec. # noqa: E501
:rtype: str | argo/workflows/client/models/v1alpha1_cron_workflow_spec.py | timezone | ButterflyNetwork/argo-client-python | 0 | python | @property
def timezone(self):
'Gets the timezone of this V1alpha1CronWorkflowSpec. # noqa: E501\n\n Timezone is the timezone against which the cron schedule will be calculated, e.g. "Asia/Tokyo". Default is machine\'s local time. # noqa: E501\n\n :return: The timezone of this V1alpha1CronWorkflowSpe... | @property
def timezone(self):
'Gets the timezone of this V1alpha1CronWorkflowSpec. # noqa: E501\n\n Timezone is the timezone against which the cron schedule will be calculated, e.g. "Asia/Tokyo". Default is machine\'s local time. # noqa: E501\n\n :return: The timezone of this V1alpha1CronWorkflowSpe... |
f937f483e9bb109edde994ff05316680bad268aeebdfa59430d19c1e02ca4886 | @timezone.setter
def timezone(self, timezone):
'Sets the timezone of this V1alpha1CronWorkflowSpec.\n\n Timezone is the timezone against which the cron schedule will be calculated, e.g. "Asia/Tokyo". Default is machine\'s local time. # noqa: E501\n\n :param timezone: The timezone of this V1alpha1Cron... | Sets the timezone of this V1alpha1CronWorkflowSpec.
Timezone is the timezone against which the cron schedule will be calculated, e.g. "Asia/Tokyo". Default is machine's local time. # noqa: E501
:param timezone: The timezone of this V1alpha1CronWorkflowSpec. # noqa: E501
:type: str | argo/workflows/client/models/v1alpha1_cron_workflow_spec.py | timezone | ButterflyNetwork/argo-client-python | 0 | python | @timezone.setter
def timezone(self, timezone):
'Sets the timezone of this V1alpha1CronWorkflowSpec.\n\n Timezone is the timezone against which the cron schedule will be calculated, e.g. "Asia/Tokyo". Default is machine\'s local time. # noqa: E501\n\n :param timezone: The timezone of this V1alpha1Cron... | @timezone.setter
def timezone(self, timezone):
'Sets the timezone of this V1alpha1CronWorkflowSpec.\n\n Timezone is the timezone against which the cron schedule will be calculated, e.g. "Asia/Tokyo". Default is machine\'s local time. # noqa: E501\n\n :param timezone: The timezone of this V1alpha1Cron... |
cf79e6694d3c8428d450d2cdf332aecc6128213f247e7a1983c37a0de327e9e5 | @property
def workflow_metadata(self):
'Gets the workflow_metadata of this V1alpha1CronWorkflowSpec. # noqa: E501\n\n WorkflowMetadata contains some metadata of the workflow to be run # noqa: E501\n\n :return: The workflow_metadata of this V1alpha1CronWorkflowSpec. # noqa: E501\n :rtype: V1O... | Gets the workflow_metadata of this V1alpha1CronWorkflowSpec. # noqa: E501
WorkflowMetadata contains some metadata of the workflow to be run # noqa: E501
:return: The workflow_metadata of this V1alpha1CronWorkflowSpec. # noqa: E501
:rtype: V1ObjectMeta | argo/workflows/client/models/v1alpha1_cron_workflow_spec.py | workflow_metadata | ButterflyNetwork/argo-client-python | 0 | python | @property
def workflow_metadata(self):
'Gets the workflow_metadata of this V1alpha1CronWorkflowSpec. # noqa: E501\n\n WorkflowMetadata contains some metadata of the workflow to be run # noqa: E501\n\n :return: The workflow_metadata of this V1alpha1CronWorkflowSpec. # noqa: E501\n :rtype: V1O... | @property
def workflow_metadata(self):
'Gets the workflow_metadata of this V1alpha1CronWorkflowSpec. # noqa: E501\n\n WorkflowMetadata contains some metadata of the workflow to be run # noqa: E501\n\n :return: The workflow_metadata of this V1alpha1CronWorkflowSpec. # noqa: E501\n :rtype: V1O... |
09cafb5ff0d5297dbdbba9ce3639e12047459d1a5226544f7efd8ad022778ab9 | @workflow_metadata.setter
def workflow_metadata(self, workflow_metadata):
'Sets the workflow_metadata of this V1alpha1CronWorkflowSpec.\n\n WorkflowMetadata contains some metadata of the workflow to be run # noqa: E501\n\n :param workflow_metadata: The workflow_metadata of this V1alpha1CronWorkflowSp... | Sets the workflow_metadata of this V1alpha1CronWorkflowSpec.
WorkflowMetadata contains some metadata of the workflow to be run # noqa: E501
:param workflow_metadata: The workflow_metadata of this V1alpha1CronWorkflowSpec. # noqa: E501
:type: V1ObjectMeta | argo/workflows/client/models/v1alpha1_cron_workflow_spec.py | workflow_metadata | ButterflyNetwork/argo-client-python | 0 | python | @workflow_metadata.setter
def workflow_metadata(self, workflow_metadata):
'Sets the workflow_metadata of this V1alpha1CronWorkflowSpec.\n\n WorkflowMetadata contains some metadata of the workflow to be run # noqa: E501\n\n :param workflow_metadata: The workflow_metadata of this V1alpha1CronWorkflowSp... | @workflow_metadata.setter
def workflow_metadata(self, workflow_metadata):
'Sets the workflow_metadata of this V1alpha1CronWorkflowSpec.\n\n WorkflowMetadata contains some metadata of the workflow to be run # noqa: E501\n\n :param workflow_metadata: The workflow_metadata of this V1alpha1CronWorkflowSp... |
7cbdc680b9bf004a14fadb016d217348c1a657c91fafeccfaf09d35f6ef8e569 | @property
def workflow_spec(self):
'Gets the workflow_spec of this V1alpha1CronWorkflowSpec. # noqa: E501\n\n WorkflowSpec is the spec of the workflow to be run # noqa: E501\n\n :return: The workflow_spec of this V1alpha1CronWorkflowSpec. # noqa: E501\n :rtype: V1alpha1WorkflowSpec\n ... | Gets the workflow_spec of this V1alpha1CronWorkflowSpec. # noqa: E501
WorkflowSpec is the spec of the workflow to be run # noqa: E501
:return: The workflow_spec of this V1alpha1CronWorkflowSpec. # noqa: E501
:rtype: V1alpha1WorkflowSpec | argo/workflows/client/models/v1alpha1_cron_workflow_spec.py | workflow_spec | ButterflyNetwork/argo-client-python | 0 | python | @property
def workflow_spec(self):
'Gets the workflow_spec of this V1alpha1CronWorkflowSpec. # noqa: E501\n\n WorkflowSpec is the spec of the workflow to be run # noqa: E501\n\n :return: The workflow_spec of this V1alpha1CronWorkflowSpec. # noqa: E501\n :rtype: V1alpha1WorkflowSpec\n ... | @property
def workflow_spec(self):
'Gets the workflow_spec of this V1alpha1CronWorkflowSpec. # noqa: E501\n\n WorkflowSpec is the spec of the workflow to be run # noqa: E501\n\n :return: The workflow_spec of this V1alpha1CronWorkflowSpec. # noqa: E501\n :rtype: V1alpha1WorkflowSpec\n ... |
f6ba94c5b45bc81d350fd8a5fc25474606c6df68459a6622ac3d08559fd97dd0 | @workflow_spec.setter
def workflow_spec(self, workflow_spec):
'Sets the workflow_spec of this V1alpha1CronWorkflowSpec.\n\n WorkflowSpec is the spec of the workflow to be run # noqa: E501\n\n :param workflow_spec: The workflow_spec of this V1alpha1CronWorkflowSpec. # noqa: E501\n :type: V1alp... | Sets the workflow_spec of this V1alpha1CronWorkflowSpec.
WorkflowSpec is the spec of the workflow to be run # noqa: E501
:param workflow_spec: The workflow_spec of this V1alpha1CronWorkflowSpec. # noqa: E501
:type: V1alpha1WorkflowSpec | argo/workflows/client/models/v1alpha1_cron_workflow_spec.py | workflow_spec | ButterflyNetwork/argo-client-python | 0 | python | @workflow_spec.setter
def workflow_spec(self, workflow_spec):
'Sets the workflow_spec of this V1alpha1CronWorkflowSpec.\n\n WorkflowSpec is the spec of the workflow to be run # noqa: E501\n\n :param workflow_spec: The workflow_spec of this V1alpha1CronWorkflowSpec. # noqa: E501\n :type: V1alp... | @workflow_spec.setter
def workflow_spec(self, workflow_spec):
'Sets the workflow_spec of this V1alpha1CronWorkflowSpec.\n\n WorkflowSpec is the spec of the workflow to be run # noqa: E501\n\n :param workflow_spec: The workflow_spec of this V1alpha1CronWorkflowSpec. # noqa: E501\n :type: V1alp... |
1a13f2940cee21f9114157e93c86a55415af1e0c823f09077439f0eff51428e3 | def to_dict(self):
'Returns the model properties as a dict'
result = {}
for (attr, _) in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value))
e... | Returns the model properties as a dict | argo/workflows/client/models/v1alpha1_cron_workflow_spec.py | to_dict | ButterflyNetwork/argo-client-python | 0 | python | def to_dict(self):
result = {}
for (attr, _) in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value))
elif hasattr(value, 'to_dict'):
... | def to_dict(self):
result = {}
for (attr, _) in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value))
elif hasattr(value, 'to_dict'):
... |
cbb19eaa2fc8a113d9e32f924ef280a7e97563f8915f94f65dab438997af2e99 | def to_str(self):
'Returns the string representation of the model'
return pprint.pformat(self.to_dict()) | Returns the string representation of the model | argo/workflows/client/models/v1alpha1_cron_workflow_spec.py | to_str | ButterflyNetwork/argo-client-python | 0 | python | def to_str(self):
return pprint.pformat(self.to_dict()) | def to_str(self):
return pprint.pformat(self.to_dict())<|docstring|>Returns the string representation of the model<|endoftext|> |
772243a2c2b3261a9b954d07aaf295e3c1242a579a495e2d6a5679c677861703 | def __repr__(self):
'For `print` and `pprint`'
return self.to_str() | For `print` and `pprint` | argo/workflows/client/models/v1alpha1_cron_workflow_spec.py | __repr__ | ButterflyNetwork/argo-client-python | 0 | python | def __repr__(self):
return self.to_str() | def __repr__(self):
return self.to_str()<|docstring|>For `print` and `pprint`<|endoftext|> |
f5dcf49a7454405ac7ee56f402144454758d0e96a0990cab4f8a167d28f372ff | def __eq__(self, other):
'Returns true if both objects are equal'
if (not isinstance(other, V1alpha1CronWorkflowSpec)):
return False
return (self.__dict__ == other.__dict__) | Returns true if both objects are equal | argo/workflows/client/models/v1alpha1_cron_workflow_spec.py | __eq__ | ButterflyNetwork/argo-client-python | 0 | python | def __eq__(self, other):
if (not isinstance(other, V1alpha1CronWorkflowSpec)):
return False
return (self.__dict__ == other.__dict__) | def __eq__(self, other):
if (not isinstance(other, V1alpha1CronWorkflowSpec)):
return False
return (self.__dict__ == other.__dict__)<|docstring|>Returns true if both objects are equal<|endoftext|> |
43dc6740163eb9fc1161d09cb2208a64c7ad0cc8d9c8637ac3264522d3ec7e42 | def __ne__(self, other):
'Returns true if both objects are not equal'
return (not (self == other)) | Returns true if both objects are not equal | argo/workflows/client/models/v1alpha1_cron_workflow_spec.py | __ne__ | ButterflyNetwork/argo-client-python | 0 | python | def __ne__(self, other):
return (not (self == other)) | def __ne__(self, other):
return (not (self == other))<|docstring|>Returns true if both objects are not equal<|endoftext|> |
74a4bdc93bcae731dc51b21ec65c767d78c95d85de9fd0ed382c7345d9fd58d3 | def cache_file(app_name=APPNAME, app_author=APPAUTHOR, filename=DATABASENAME):
'Returns the filename (including path) for the data cache.\n\n The path will depend on the operating system, certain environmental\n variables and whether it is being run inside a virtual environment.\n See `homebase <https://gi... | Returns the filename (including path) for the data cache.
The path will depend on the operating system, certain environmental
variables and whether it is being run inside a virtual environment.
See `homebase <https://github.com/dwavesystems/homebase>`_.
Args:
app_name (str, optional): The application name.
... | dwave/system/cache/cache_manager.py | cache_file | seatim/dwave-system | 85 | python | def cache_file(app_name=APPNAME, app_author=APPAUTHOR, filename=DATABASENAME):
'Returns the filename (including path) for the data cache.\n\n The path will depend on the operating system, certain environmental\n variables and whether it is being run inside a virtual environment.\n See `homebase <https://gi... | def cache_file(app_name=APPNAME, app_author=APPAUTHOR, filename=DATABASENAME):
'Returns the filename (including path) for the data cache.\n\n The path will depend on the operating system, certain environmental\n variables and whether it is being run inside a virtual environment.\n See `homebase <https://gi... |
dc48fbd46d0dcc3d2253c69e121d1d66fd03c811953473fe3d9214103e511eb3 | def data_loader(eigen_data_path):
'\n Loads the eigendata stored in a numpy zip and returns\n the eigenvalues and eigenvectors.\n\n Paramters\n ---------\n eigen_data_path: string\n Path to the eigendata numpy zip (.npz) file.\n\n Returns\n -------\n eigen_vals: numpy array\n E... | Loads the eigendata stored in a numpy zip and returns
the eigenvalues and eigenvectors.
Paramters
---------
eigen_data_path: string
Path to the eigendata numpy zip (.npz) file.
Returns
-------
eigen_vals: numpy array
Eigenvalues stored in the eigendata zip.
eigen_vecs: numpy array
Eigenvectors stored in t... | src/analysis/temporal_anomaly_detection.py | data_loader | quinngroup/ornet-JOSS | 3 | python | def data_loader(eigen_data_path):
'\n Loads the eigendata stored in a numpy zip and returns\n the eigenvalues and eigenvectors.\n\n Paramters\n ---------\n eigen_data_path: string\n Path to the eigendata numpy zip (.npz) file.\n\n Returns\n -------\n eigen_vals: numpy array\n E... | def data_loader(eigen_data_path):
'\n Loads the eigendata stored in a numpy zip and returns\n the eigenvalues and eigenvectors.\n\n Paramters\n ---------\n eigen_data_path: string\n Path to the eigendata numpy zip (.npz) file.\n\n Returns\n -------\n eigen_vals: numpy array\n E... |
a9fd1bf2e7120db1f479bfc77e84b601384e1881a056d2c3e9748394ee31b29e | def plot(eigen_vals, z_scores, title, save_fig, outdir_path=None):
'\n Plots eigenvalue time-series data, and a\n corresponding z-score curve.\n '
sns.set()
fig = plt.figure()
fig.suptitle(title)
ax = fig.add_subplot(211)
ax.plot(eigen_vals)
ax.set_ylabel('Magnitude')
ax = fig.a... | Plots eigenvalue time-series data, and a
corresponding z-score curve. | src/analysis/temporal_anomaly_detection.py | plot | quinngroup/ornet-JOSS | 3 | python | def plot(eigen_vals, z_scores, title, save_fig, outdir_path=None):
'\n Plots eigenvalue time-series data, and a\n corresponding z-score curve.\n '
sns.set()
fig = plt.figure()
fig.suptitle(title)
ax = fig.add_subplot(211)
ax.plot(eigen_vals)
ax.set_ylabel('Magnitude')
ax = fig.a... | def plot(eigen_vals, z_scores, title, save_fig, outdir_path=None):
'\n Plots eigenvalue time-series data, and a\n corresponding z-score curve.\n '
sns.set()
fig = plt.figure()
fig.suptitle(title)
ax = fig.add_subplot(211)
ax.plot(eigen_vals)
ax.set_ylabel('Magnitude')
ax = fig.a... |
4eb1ac80b858d65b12ecff00decda1cf6d33b70f4b5a8c0ea39df06097a92b56 | def temporal_anomaly_detection(vid_name, eigen_vals, outdir_path, k=10, window=20, threshold=2):
'\n Generates a figure comprised of a time-series plot\n of the eigenvalue vectors, and an outlier detection \n signals plot.\n\n Parameters\n ----------\n vid_name: string\n Name of the microsc... | Generates a figure comprised of a time-series plot
of the eigenvalue vectors, and an outlier detection
signals plot.
Parameters
----------
vid_name: string
Name of the microscopy video.
eigen_vals: NumPy array (NXM)
Matrix comprised of eigenvalue vectors.
N represents the number of frames in the
corr... | src/analysis/temporal_anomaly_detection.py | temporal_anomaly_detection | quinngroup/ornet-JOSS | 3 | python | def temporal_anomaly_detection(vid_name, eigen_vals, outdir_path, k=10, window=20, threshold=2):
'\n Generates a figure comprised of a time-series plot\n of the eigenvalue vectors, and an outlier detection \n signals plot.\n\n Parameters\n ----------\n vid_name: string\n Name of the microsc... | def temporal_anomaly_detection(vid_name, eigen_vals, outdir_path, k=10, window=20, threshold=2):
'\n Generates a figure comprised of a time-series plot\n of the eigenvalue vectors, and an outlier detection \n signals plot.\n\n Parameters\n ----------\n vid_name: string\n Name of the microsc... |
dbb77ea38863b550fea47b750655307f6a4ed45a4de236d264334284ebdabfaa | def parse_cli(input_args):
'\n Parses the command line arguments.\n\n Parameters\n ----------\n input_args: list\n Arguments to be parsed.\n\n Returns\n -------\n parsed_args: dict\n Key value pairs of arguments.\n '
parser = argparse.ArgumentParser(description='Anomaly det... | Parses the command line arguments.
Parameters
----------
input_args: list
Arguments to be parsed.
Returns
-------
parsed_args: dict
Key value pairs of arguments. | src/analysis/temporal_anomaly_detection.py | parse_cli | quinngroup/ornet-JOSS | 3 | python | def parse_cli(input_args):
'\n Parses the command line arguments.\n\n Parameters\n ----------\n input_args: list\n Arguments to be parsed.\n\n Returns\n -------\n parsed_args: dict\n Key value pairs of arguments.\n '
parser = argparse.ArgumentParser(description='Anomaly det... | def parse_cli(input_args):
'\n Parses the command line arguments.\n\n Parameters\n ----------\n input_args: list\n Arguments to be parsed.\n\n Returns\n -------\n parsed_args: dict\n Key value pairs of arguments.\n '
parser = argparse.ArgumentParser(description='Anomaly det... |
c69158b7f288ceeabdf5458488941e947be7edb105b6e73bf498ac7465dc841e | @staticmethod
def n_dist_param():
'Number of distributional parameter.\n\n '
n_param = 2
return n_param | Number of distributional parameter. | xgboostlss/distributions/Gamma.py | n_dist_param | Cattes/XGBoostLSS | 0 | python | @staticmethod
def n_dist_param():
'\n\n '
n_param = 2
return n_param | @staticmethod
def n_dist_param():
'\n\n '
n_param = 2
return n_param<|docstring|>Number of distributional parameter.<|endoftext|> |
166b7c8eebcc403fda2665da49fc18ddb2e2d5eddd479df023dd118ec793fc9f | @staticmethod
def param_dict():
' Dictionary that holds the name of distributional parameter and their corresponding response functions.\n\n '
param_dict = {'location': soft_plus, 'scale': soft_plus}
return param_dict | Dictionary that holds the name of distributional parameter and their corresponding response functions. | xgboostlss/distributions/Gamma.py | param_dict | Cattes/XGBoostLSS | 0 | python | @staticmethod
def param_dict():
' \n\n '
param_dict = {'location': soft_plus, 'scale': soft_plus}
return param_dict | @staticmethod
def param_dict():
' \n\n '
param_dict = {'location': soft_plus, 'scale': soft_plus}
return param_dict<|docstring|>Dictionary that holds the name of distributional parameter and their corresponding response functions.<|endoftext|> |
1fe57a04bee3b4caacdef8a2719bb07e970223d2439d1e8bde40bc09bc788cd9 | @staticmethod
def param_dict_inv():
' Dictionary that holds the name of distributional parameter and their corresponding link functions.\n\n '
param_dict_inv = {'location_inv': soft_plus_inv, 'scale_inv': soft_plus_inv}
return param_dict_inv | Dictionary that holds the name of distributional parameter and their corresponding link functions. | xgboostlss/distributions/Gamma.py | param_dict_inv | Cattes/XGBoostLSS | 0 | python | @staticmethod
def param_dict_inv():
' \n\n '
param_dict_inv = {'location_inv': soft_plus_inv, 'scale_inv': soft_plus_inv}
return param_dict_inv | @staticmethod
def param_dict_inv():
' \n\n '
param_dict_inv = {'location_inv': soft_plus_inv, 'scale_inv': soft_plus_inv}
return param_dict_inv<|docstring|>Dictionary that holds the name of distributional parameter and their corresponding link functions.<|endoftext|> |
74736eafaad7e25c33c563d490be283bb831433cea1f195ef992d85bd0168cfb | @staticmethod
def initialize(y: np.ndarray):
' Function that calculates the starting values, for each distributional parameter individually.\n\n y: np.ndarray\n Data from which starting values are calculated.\n\n '
(loc_fit, scale_fit) = (np.nanmean(y), np.nanstd(y))
location_init =... | Function that calculates the starting values, for each distributional parameter individually.
y: np.ndarray
Data from which starting values are calculated. | xgboostlss/distributions/Gamma.py | initialize | Cattes/XGBoostLSS | 0 | python | @staticmethod
def initialize(y: np.ndarray):
' Function that calculates the starting values, for each distributional parameter individually.\n\n y: np.ndarray\n Data from which starting values are calculated.\n\n '
(loc_fit, scale_fit) = (np.nanmean(y), np.nanstd(y))
location_init =... | @staticmethod
def initialize(y: np.ndarray):
' Function that calculates the starting values, for each distributional parameter individually.\n\n y: np.ndarray\n Data from which starting values are calculated.\n\n '
(loc_fit, scale_fit) = (np.nanmean(y), np.nanstd(y))
location_init =... |
0e8c101ff1bc30bb47d8f08b4e8d8ad135b3b5afdf77cd442336b8e76c4ddf64 | @staticmethod
def dGamma(y: np.ndarray, location: np.ndarray, scale: np.ndarray, log=True):
'Density function.\n\n '
loglik = (((((1 / (scale ** 2)) * np.log((y / (location * (scale ** 2))))) - (y / (location * (scale ** 2)))) - np.log(y)) - loggamma((1 / (scale ** 2))))
loglik = (np.exp(loglik) if (... | Density function. | xgboostlss/distributions/Gamma.py | dGamma | Cattes/XGBoostLSS | 0 | python | @staticmethod
def dGamma(y: np.ndarray, location: np.ndarray, scale: np.ndarray, log=True):
'\n\n '
loglik = (((((1 / (scale ** 2)) * np.log((y / (location * (scale ** 2))))) - (y / (location * (scale ** 2)))) - np.log(y)) - loggamma((1 / (scale ** 2))))
loglik = (np.exp(loglik) if (log == False) els... | @staticmethod
def dGamma(y: np.ndarray, location: np.ndarray, scale: np.ndarray, log=True):
'\n\n '
loglik = (((((1 / (scale ** 2)) * np.log((y / (location * (scale ** 2))))) - (y / (location * (scale ** 2)))) - np.log(y)) - loggamma((1 / (scale ** 2))))
loglik = (np.exp(loglik) if (log == False) els... |
9c90a89dc0f3a910ca79f33c4d435ebe161dfa3dc1c6153b64ca55d930b24603 | @staticmethod
def qGamma(p: float, location: np.ndarray, scale: np.ndarray):
'Quantile function.\n\n '
q = gamma.ppf(p, a=(1 / (scale ** 2)), scale=(location * (scale ** 2)))
return q | Quantile function. | xgboostlss/distributions/Gamma.py | qGamma | Cattes/XGBoostLSS | 0 | python | @staticmethod
def qGamma(p: float, location: np.ndarray, scale: np.ndarray):
'\n\n '
q = gamma.ppf(p, a=(1 / (scale ** 2)), scale=(location * (scale ** 2)))
return q | @staticmethod
def qGamma(p: float, location: np.ndarray, scale: np.ndarray):
'\n\n '
q = gamma.ppf(p, a=(1 / (scale ** 2)), scale=(location * (scale ** 2)))
return q<|docstring|>Quantile function.<|endoftext|> |
bc96c0a2308ab4ae88e0e9c9a59d318e506c9e73fdaf0fb0e2970a441e86f6c7 | def rGamma(n: int, location: np.ndarray, scale: np.ndarray):
'Random variable generation function.\n\n '
n = math.ceil(n)
p = np.random.uniform(0, 1, n)
r = Gamma.qGamma(p, location=location, scale=scale)
return r | Random variable generation function. | xgboostlss/distributions/Gamma.py | rGamma | Cattes/XGBoostLSS | 0 | python | def rGamma(n: int, location: np.ndarray, scale: np.ndarray):
'\n\n '
n = math.ceil(n)
p = np.random.uniform(0, 1, n)
r = Gamma.qGamma(p, location=location, scale=scale)
return r | def rGamma(n: int, location: np.ndarray, scale: np.ndarray):
'\n\n '
n = math.ceil(n)
p = np.random.uniform(0, 1, n)
r = Gamma.qGamma(p, location=location, scale=scale)
return r<|docstring|>Random variable generation function.<|endoftext|> |
96d89a9b018da8d7e27d866746a3cd4c73b6b702644ae2ed069b150f6def9437 | @staticmethod
def gradient_location(y: np.ndarray, location: np.ndarray, scale: np.ndarray, weights: np.ndarray):
'Calculates Gradient of location parameter.\n\n '
grad = ((y - location) / ((scale ** 2) * (location ** 2)))
grad = stabilize_derivative(grad, Gamma.stabilize)
grad = ((grad * (- 1)) ... | Calculates Gradient of location parameter. | xgboostlss/distributions/Gamma.py | gradient_location | Cattes/XGBoostLSS | 0 | python | @staticmethod
def gradient_location(y: np.ndarray, location: np.ndarray, scale: np.ndarray, weights: np.ndarray):
'\n\n '
grad = ((y - location) / ((scale ** 2) * (location ** 2)))
grad = stabilize_derivative(grad, Gamma.stabilize)
grad = ((grad * (- 1)) * weights)
return grad | @staticmethod
def gradient_location(y: np.ndarray, location: np.ndarray, scale: np.ndarray, weights: np.ndarray):
'\n\n '
grad = ((y - location) / ((scale ** 2) * (location ** 2)))
grad = stabilize_derivative(grad, Gamma.stabilize)
grad = ((grad * (- 1)) * weights)
return grad<|docstring|>Cal... |
8ebf9fd61d46d12c041ba0bcaf5e19f40a425268dbc13fa3bba2fc7247c3ab37 | @staticmethod
def hessian_location(location: np.ndarray, scale: np.ndarray, weights: np.ndarray):
'Calculates Hessian of location parameter.\n\n '
hes = ((- 1) / ((scale ** 2) * (location ** 2)))
hes = stabilize_derivative(hes, Gamma.stabilize)
hes = ((hes * (- 1)) * weights)
return hes | Calculates Hessian of location parameter. | xgboostlss/distributions/Gamma.py | hessian_location | Cattes/XGBoostLSS | 0 | python | @staticmethod
def hessian_location(location: np.ndarray, scale: np.ndarray, weights: np.ndarray):
'\n\n '
hes = ((- 1) / ((scale ** 2) * (location ** 2)))
hes = stabilize_derivative(hes, Gamma.stabilize)
hes = ((hes * (- 1)) * weights)
return hes | @staticmethod
def hessian_location(location: np.ndarray, scale: np.ndarray, weights: np.ndarray):
'\n\n '
hes = ((- 1) / ((scale ** 2) * (location ** 2)))
hes = stabilize_derivative(hes, Gamma.stabilize)
hes = ((hes * (- 1)) * weights)
return hes<|docstring|>Calculates Hessian of location par... |
d71b0b9f394748bb0ac0fbf624f9b1a129ab8200f32d92385a2d9201c2fb20bf | @staticmethod
def gradient_scale(y: np.ndarray, location: np.ndarray, scale: np.ndarray, weights: np.ndarray):
'Calculates Gradient of scale parameter.\n\n '
grad = ((2 / (scale ** 3)) * ((((((y / location) - np.log(y)) + np.log(location)) + np.log((scale ** 2))) - 1) + polygamma(0, (1 / (scale ** 2)))))... | Calculates Gradient of scale parameter. | xgboostlss/distributions/Gamma.py | gradient_scale | Cattes/XGBoostLSS | 0 | python | @staticmethod
def gradient_scale(y: np.ndarray, location: np.ndarray, scale: np.ndarray, weights: np.ndarray):
'\n\n '
grad = ((2 / (scale ** 3)) * ((((((y / location) - np.log(y)) + np.log(location)) + np.log((scale ** 2))) - 1) + polygamma(0, (1 / (scale ** 2)))))
grad = stabilize_derivative(grad, ... | @staticmethod
def gradient_scale(y: np.ndarray, location: np.ndarray, scale: np.ndarray, weights: np.ndarray):
'\n\n '
grad = ((2 / (scale ** 3)) * ((((((y / location) - np.log(y)) + np.log(location)) + np.log((scale ** 2))) - 1) + polygamma(0, (1 / (scale ** 2)))))
grad = stabilize_derivative(grad, ... |
add314fd459a6ef71b6b3961bd870afcdda27e14706902e22036c2f134bd4809 | @staticmethod
def hessian_scale(scale: np.ndarray, weights: np.ndarray):
'Calculates Hessian of scale parameter.\n\n '
hes = ((4 / (scale ** 4)) - ((4 / (scale ** 6)) * polygamma(1, (1 / (scale ** 2)))))
hes = stabilize_derivative(hes, Gamma.stabilize)
hes = ((hes * (- 1)) * weights)
return h... | Calculates Hessian of scale parameter. | xgboostlss/distributions/Gamma.py | hessian_scale | Cattes/XGBoostLSS | 0 | python | @staticmethod
def hessian_scale(scale: np.ndarray, weights: np.ndarray):
'\n\n '
hes = ((4 / (scale ** 4)) - ((4 / (scale ** 6)) * polygamma(1, (1 / (scale ** 2)))))
hes = stabilize_derivative(hes, Gamma.stabilize)
hes = ((hes * (- 1)) * weights)
return hes | @staticmethod
def hessian_scale(scale: np.ndarray, weights: np.ndarray):
'\n\n '
hes = ((4 / (scale ** 4)) - ((4 / (scale ** 6)) * polygamma(1, (1 / (scale ** 2)))))
hes = stabilize_derivative(hes, Gamma.stabilize)
hes = ((hes * (- 1)) * weights)
return hes<|docstring|>Calculates Hessian of s... |
d545f63797ccd6d9092813abbc7425c942228857f049f0fd5e64ecedbb558c05 | def Dist_Objective(predt: np.ndarray, data: xgb.DMatrix):
'A customized objective function to train each distributional parameter using custom gradient and hessian.\n\n '
target = data.get_label()
preds_location = Gamma.param_dict()['location'](predt[(:, 0)])
preds_scale = Gamma.param_dict()['sca... | A customized objective function to train each distributional parameter using custom gradient and hessian. | xgboostlss/distributions/Gamma.py | Dist_Objective | Cattes/XGBoostLSS | 0 | python | def Dist_Objective(predt: np.ndarray, data: xgb.DMatrix):
'\n\n '
target = data.get_label()
preds_location = Gamma.param_dict()['location'](predt[(:, 0)])
preds_scale = Gamma.param_dict()['scale'](predt[(:, 1)])
if (data.get_weight().size == 0):
weights = np.ones_like(target, dtype=fl... | def Dist_Objective(predt: np.ndarray, data: xgb.DMatrix):
'\n\n '
target = data.get_label()
preds_location = Gamma.param_dict()['location'](predt[(:, 0)])
preds_scale = Gamma.param_dict()['scale'](predt[(:, 1)])
if (data.get_weight().size == 0):
weights = np.ones_like(target, dtype=fl... |
16fafefd7f25b32e2b16703cbbec6dd9d476c85818cae9c7dde831a6ca57ac4f | def Dist_Metric(predt: np.ndarray, data: xgb.DMatrix):
'A customized evaluation metric that evaluates the predictions using the negative log-likelihood.\n\n '
target = data.get_label()
preds_location = Gamma.param_dict()['location'](predt[(:, 0)])
preds_scale = Gamma.param_dict()['scale'](predt[(... | A customized evaluation metric that evaluates the predictions using the negative log-likelihood. | xgboostlss/distributions/Gamma.py | Dist_Metric | Cattes/XGBoostLSS | 0 | python | def Dist_Metric(predt: np.ndarray, data: xgb.DMatrix):
'\n\n '
target = data.get_label()
preds_location = Gamma.param_dict()['location'](predt[(:, 0)])
preds_scale = Gamma.param_dict()['scale'](predt[(:, 1)])
nll = (- np.nansum(Gamma.dGamma(y=target, location=preds_location, scale=preds_scale... | def Dist_Metric(predt: np.ndarray, data: xgb.DMatrix):
'\n\n '
target = data.get_label()
preds_location = Gamma.param_dict()['location'](predt[(:, 0)])
preds_scale = Gamma.param_dict()['scale'](predt[(:, 1)])
nll = (- np.nansum(Gamma.dGamma(y=target, location=preds_location, scale=preds_scale... |
dadffea76faecb7bf8123464c5597af1d16f2a00074eda97e085918b7c325efa | def pred_dist_rvs(pred_params: pd.DataFrame, n_samples: int, seed: int):
'\n Function that draws n_samples from a predicted response distribution.\n\n pred_params: pd.DataFrame\n Dataframe with predicted distributional parameters.\n n_samples: int\n Number of sample to dra... | Function that draws n_samples from a predicted response distribution.
pred_params: pd.DataFrame
Dataframe with predicted distributional parameters.
n_samples: int
Number of sample to draw from predicted response distribution.
seed: int
Manual seed.
Returns
-------
pd.DataFrame with n_samples drawn from pre... | xgboostlss/distributions/Gamma.py | pred_dist_rvs | Cattes/XGBoostLSS | 0 | python | def pred_dist_rvs(pred_params: pd.DataFrame, n_samples: int, seed: int):
'\n Function that draws n_samples from a predicted response distribution.\n\n pred_params: pd.DataFrame\n Dataframe with predicted distributional parameters.\n n_samples: int\n Number of sample to dra... | def pred_dist_rvs(pred_params: pd.DataFrame, n_samples: int, seed: int):
'\n Function that draws n_samples from a predicted response distribution.\n\n pred_params: pd.DataFrame\n Dataframe with predicted distributional parameters.\n n_samples: int\n Number of sample to dra... |
f3b691ddc79cdb7d709e5eb973c200d331f66065ed1227afa54a8a80493caefa | def pred_dist_quantile(quantiles: list, pred_params: pd.DataFrame):
'\n Function that calculates the quantiles from the predicted response distribution.\n\n quantiles: list\n Which quantiles to calculate\n pred_params: pd.DataFrame\n Dataframe with predicted distributional... | Function that calculates the quantiles from the predicted response distribution.
quantiles: list
Which quantiles to calculate
pred_params: pd.DataFrame
Dataframe with predicted distributional parameters.
Returns
-------
pd.DataFrame with calculated quantiles. | xgboostlss/distributions/Gamma.py | pred_dist_quantile | Cattes/XGBoostLSS | 0 | python | def pred_dist_quantile(quantiles: list, pred_params: pd.DataFrame):
'\n Function that calculates the quantiles from the predicted response distribution.\n\n quantiles: list\n Which quantiles to calculate\n pred_params: pd.DataFrame\n Dataframe with predicted distributional... | def pred_dist_quantile(quantiles: list, pred_params: pd.DataFrame):
'\n Function that calculates the quantiles from the predicted response distribution.\n\n quantiles: list\n Which quantiles to calculate\n pred_params: pd.DataFrame\n Dataframe with predicted distributional... |
f52be5c1634e3920647a550127b19b14c7485916178e42ed9df0a211b7322791 | @property
def last_block(self):
'\n The last block in the chain, ie. the most recent block added\n '
return self.chain[(- 1)] | The last block in the chain, ie. the most recent block added | WebBlockChain/Blockchain.py | last_block | Johnson-Su/Certi-Chain | 1 | python | @property
def last_block(self):
'\n \n '
return self.chain[(- 1)] | @property
def last_block(self):
'\n \n '
return self.chain[(- 1)]<|docstring|>The last block in the chain, ie. the most recent block added<|endoftext|> |
71c2c942b1327a3d90c12ab2932092f432bca10dd191fd8b7ece84de0fe91b9c | @staticmethod
def proof_of_work(block):
"\n A proof of work is the process of adding a constraint to a block's\n hash. By adding the constraint, it makes it difficult for a valid \n hash to be computed.\n "
block.nonce = 0
computed_hash = block.compute_hash()
while (not compu... | A proof of work is the process of adding a constraint to a block's
hash. By adding the constraint, it makes it difficult for a valid
hash to be computed. | WebBlockChain/Blockchain.py | proof_of_work | Johnson-Su/Certi-Chain | 1 | python | @staticmethod
def proof_of_work(block):
"\n A proof of work is the process of adding a constraint to a block's\n hash. By adding the constraint, it makes it difficult for a valid \n hash to be computed.\n "
block.nonce = 0
computed_hash = block.compute_hash()
while (not compu... | @staticmethod
def proof_of_work(block):
"\n A proof of work is the process of adding a constraint to a block's\n hash. By adding the constraint, it makes it difficult for a valid \n hash to be computed.\n "
block.nonce = 0
computed_hash = block.compute_hash()
while (not compu... |
7ab171b527f7480224cfa701c9ec3d23ce7e9d235807a4f8711cf9de8dd47992 | def add_block(self, block, proof):
'\n To add a block into the blockchain, we must determine if the block \n to be added is in the correct chronological order (no adding \n transactions that occured before the last block), \n and we must determine if the data has not been tampered with. ... | To add a block into the blockchain, we must determine if the block
to be added is in the correct chronological order (no adding
transactions that occured before the last block),
and we must determine if the data has not been tampered with. | WebBlockChain/Blockchain.py | add_block | Johnson-Su/Certi-Chain | 1 | python | def add_block(self, block, proof):
'\n To add a block into the blockchain, we must determine if the block \n to be added is in the correct chronological order (no adding \n transactions that occured before the last block), \n and we must determine if the data has not been tampered with. ... | def add_block(self, block, proof):
'\n To add a block into the blockchain, we must determine if the block \n to be added is in the correct chronological order (no adding \n transactions that occured before the last block), \n and we must determine if the data has not been tampered with. ... |
fa94d78a5084626e352ad3856ce9806ba011ffddc2fd9eeda880c587d76bb6ed | def __init__(self):
'Constructeur du paramètre'
Parametre.__init__(self, 'supprimer', 'del')
self.schema = '<cle>'
self.aide_courte = 'supprime une auberge'
self.aide_longue = 'Cette commande permet simplement de supprimer une flottante. Vous devez préciser sa clé en paramètre.' | Constructeur du paramètre | src/secondaires/auberge/commandes/auberge/supprimer.py | __init__ | stormi/tsunami | 0 | python | def __init__(self):
Parametre.__init__(self, 'supprimer', 'del')
self.schema = '<cle>'
self.aide_courte = 'supprime une auberge'
self.aide_longue = 'Cette commande permet simplement de supprimer une flottante. Vous devez préciser sa clé en paramètre.' | def __init__(self):
Parametre.__init__(self, 'supprimer', 'del')
self.schema = '<cle>'
self.aide_courte = 'supprime une auberge'
self.aide_longue = 'Cette commande permet simplement de supprimer une flottante. Vous devez préciser sa clé en paramètre.'<|docstring|>Constructeur du paramètre<|endoftex... |
b3182ca6be824eb7d1f5fe2a2723d6e1a02c9cdf253d6d04b47a92ede52afbdd | def interpreter(self, personnage, dic_masques):
'Interprétation du paramètre'
cle = dic_masques['cle'].cle
if (cle not in importeur.auberge.auberges):
(personnage << "|err|Cette auberge n'existe pas.|ff|")
return
importeur.auberge.supprimer_auberge(cle)
(personnage << "L'auberge '{}'... | Interprétation du paramètre | src/secondaires/auberge/commandes/auberge/supprimer.py | interpreter | stormi/tsunami | 0 | python | def interpreter(self, personnage, dic_masques):
cle = dic_masques['cle'].cle
if (cle not in importeur.auberge.auberges):
(personnage << "|err|Cette auberge n'existe pas.|ff|")
return
importeur.auberge.supprimer_auberge(cle)
(personnage << "L'auberge '{}' a bien été supprimée".format... | def interpreter(self, personnage, dic_masques):
cle = dic_masques['cle'].cle
if (cle not in importeur.auberge.auberges):
(personnage << "|err|Cette auberge n'existe pas.|ff|")
return
importeur.auberge.supprimer_auberge(cle)
(personnage << "L'auberge '{}' a bien été supprimée".format... |
c5401225c52fb344f8f13e08a132a94bea0967ed3c07c29823269596abe46f5a | def get_teachers_info(language_id, api_url='https://api.italki.com/api/v2/teachers', to_crawl=50):
'\n Queries the API for teachers\n :return: JSON data containing conversations\n '
try:
if (to_crawl <= 100):
print('Querying API for {} in page'.format(language_id))
paylo... | Queries the API for teachers
:return: JSON data containing conversations | data_acquisition/crawlers/italki.py | get_teachers_info | javirandor/online-tutoring-analysis | 0 | python | def get_teachers_info(language_id, api_url='https://api.italki.com/api/v2/teachers', to_crawl=50):
'\n Queries the API for teachers\n :return: JSON data containing conversations\n '
try:
if (to_crawl <= 100):
print('Querying API for {} in page'.format(language_id))
paylo... | def get_teachers_info(language_id, api_url='https://api.italki.com/api/v2/teachers', to_crawl=50):
'\n Queries the API for teachers\n :return: JSON data containing conversations\n '
try:
if (to_crawl <= 100):
print('Querying API for {} in page'.format(language_id))
paylo... |
e1628ca4039ff4292c0f035d6ccd0d36036930e03d837a97abbfc39e89a3f77f | def xyz_file_to_atoms(filename):
'/\n From an .xyz file get a list of atoms\n\n :param filename: (str) .xyz filename\n :return: (list(Atom))\n '
logger.info(f'Getting atoms from {filename}')
atoms = []
if (not filename.endswith('.xyz')):
raise FileMalformatted
with open(filename,... | /
From an .xyz file get a list of atoms
:param filename: (str) .xyz filename
:return: (list(Atom)) | cgbind/input_output.py | xyz_file_to_atoms | duartegroup/cgbind | 7 | python | def xyz_file_to_atoms(filename):
'/\n From an .xyz file get a list of atoms\n\n :param filename: (str) .xyz filename\n :return: (list(Atom))\n '
logger.info(f'Getting atoms from {filename}')
atoms = []
if (not filename.endswith('.xyz')):
raise FileMalformatted
with open(filename,... | def xyz_file_to_atoms(filename):
'/\n From an .xyz file get a list of atoms\n\n :param filename: (str) .xyz filename\n :return: (list(Atom))\n '
logger.info(f'Getting atoms from {filename}')
atoms = []
if (not filename.endswith('.xyz')):
raise FileMalformatted
with open(filename,... |
ee47cb250954cc4ac1c7724be750620ee60092300388ba552cb8340f8473455d | def atoms_to_xyz_file(atoms, filename, title_line=''):
'\n Print a standard .xyz file from a set of atoms\n\n :param atoms: (list(Atom))\n :param filename: (str)\n :param title_line: (str)\n '
with open(filename, 'w') as xyz_file:
print(len(atoms), title_line, sep='\n', file=xyz_file)
... | Print a standard .xyz file from a set of atoms
:param atoms: (list(Atom))
:param filename: (str)
:param title_line: (str) | cgbind/input_output.py | atoms_to_xyz_file | duartegroup/cgbind | 7 | python | def atoms_to_xyz_file(atoms, filename, title_line=):
'\n Print a standard .xyz file from a set of atoms\n\n :param atoms: (list(Atom))\n :param filename: (str)\n :param title_line: (str)\n '
with open(filename, 'w') as xyz_file:
print(len(atoms), title_line, sep='\n', file=xyz_file)
... | def atoms_to_xyz_file(atoms, filename, title_line=):
'\n Print a standard .xyz file from a set of atoms\n\n :param atoms: (list(Atom))\n :param filename: (str)\n :param title_line: (str)\n '
with open(filename, 'w') as xyz_file:
print(len(atoms), title_line, sep='\n', file=xyz_file)
... |
7f3006436bb543940c9b2750ad5275a6cbfc496daf9ca7c908266c448606397f | def get_atoms_from_file(filename):
'Get a list of atoms from a structure file'
if filename.endswith('.xyz'):
return xyzfile_to_atoms(filename)
elif filename.endswith('.mol'):
return molfile_to_atoms(filename)
elif filename.endswith('.mol2'):
return mol2file_to_atoms(filename)
... | Get a list of atoms from a structure file | cgbind/input_output.py | get_atoms_from_file | duartegroup/cgbind | 7 | python | def get_atoms_from_file(filename):
if filename.endswith('.xyz'):
return xyzfile_to_atoms(filename)
elif filename.endswith('.mol'):
return molfile_to_atoms(filename)
elif filename.endswith('.mol2'):
return mol2file_to_atoms(filename)
else:
raise CgbindCritical('Unsupp... | def get_atoms_from_file(filename):
if filename.endswith('.xyz'):
return xyzfile_to_atoms(filename)
elif filename.endswith('.mol'):
return molfile_to_atoms(filename)
elif filename.endswith('.mol2'):
return mol2file_to_atoms(filename)
else:
raise CgbindCritical('Unsupp... |
87eb87f88768b6c1adf34bbc9d1ecac2797cd6b6575671cccc3b5682aa67bf9c | def xyzfile_to_atoms(filename):
'\n Convert a standard xyz file into a list of atoms\n\n :param filename: (str)\n :return: (list(cgbind.atoms.Atom))\n '
logger.info(f'Converting {filename} to list of atoms')
if (not filename.endswith('.xyz')):
logger.error('Could not read .xyz file')
... | Convert a standard xyz file into a list of atoms
:param filename: (str)
:return: (list(cgbind.atoms.Atom)) | cgbind/input_output.py | xyzfile_to_atoms | duartegroup/cgbind | 7 | python | def xyzfile_to_atoms(filename):
'\n Convert a standard xyz file into a list of atoms\n\n :param filename: (str)\n :return: (list(cgbind.atoms.Atom))\n '
logger.info(f'Converting {filename} to list of atoms')
if (not filename.endswith('.xyz')):
logger.error('Could not read .xyz file')
... | def xyzfile_to_atoms(filename):
'\n Convert a standard xyz file into a list of atoms\n\n :param filename: (str)\n :return: (list(cgbind.atoms.Atom))\n '
logger.info(f'Converting {filename} to list of atoms')
if (not filename.endswith('.xyz')):
logger.error('Could not read .xyz file')
... |
c61bc1c2be4ff874aed4c8339fba335d2d1d3f8264dd8a6541718d80853dd4ab | def molfile_to_atoms(filename):
'\n Convert a .mol file to a list of atoms\n\n :param filename: (str)\n :return: (list(Atom))\n '
'\n e.g. for methane:\n _____________________\n\n OpenBabel03272015013D\n\n 5 4 0 0 0 0 0 0 0 0999 V2000\n -0.2783 0.0756 0.0000 C 0... | Convert a .mol file to a list of atoms
:param filename: (str)
:return: (list(Atom)) | cgbind/input_output.py | molfile_to_atoms | duartegroup/cgbind | 7 | python | def molfile_to_atoms(filename):
'\n Convert a .mol file to a list of atoms\n\n :param filename: (str)\n :return: (list(Atom))\n '
'\n e.g. for methane:\n _____________________\n\n OpenBabel03272015013D\n\n 5 4 0 0 0 0 0 0 0 0999 V2000\n -0.2783 0.0756 0.0000 C 0... | def molfile_to_atoms(filename):
'\n Convert a .mol file to a list of atoms\n\n :param filename: (str)\n :return: (list(Atom))\n '
'\n e.g. for methane:\n _____________________\n\n OpenBabel03272015013D\n\n 5 4 0 0 0 0 0 0 0 0999 V2000\n -0.2783 0.0756 0.0000 C 0... |
aa5502d875ff8ffdf1be66cc06d04235c9fdb488cab6525d07e99394ae6f94bf | def mol2file_to_atoms(filename):
'\n Convert a .mol file into a standard set of atoms\n\n :param filename: (str)\n :return: (lis(Atom))\n '
logger.info('Converting .mol2 file to atoms')
if (not filename.endswith('.mol2')):
logger.error('Could not read .mol2 file')
raise FileMalfo... | Convert a .mol file into a standard set of atoms
:param filename: (str)
:return: (lis(Atom)) | cgbind/input_output.py | mol2file_to_atoms | duartegroup/cgbind | 7 | python | def mol2file_to_atoms(filename):
'\n Convert a .mol file into a standard set of atoms\n\n :param filename: (str)\n :return: (lis(Atom))\n '
logger.info('Converting .mol2 file to atoms')
if (not filename.endswith('.mol2')):
logger.error('Could not read .mol2 file')
raise FileMalfo... | def mol2file_to_atoms(filename):
'\n Convert a .mol file into a standard set of atoms\n\n :param filename: (str)\n :return: (lis(Atom))\n '
logger.info('Converting .mol2 file to atoms')
if (not filename.endswith('.mol2')):
logger.error('Could not read .mol2 file')
raise FileMalfo... |
fffe29c376880d80eda1da6d22e2332fad38d28c25ee0fb87ddfde1541fe195b | def create_builder_by_name(builder_name, *, builder_dict, build_context):
'Instantiate a new builder with the given builder_name.'
builders = {'doxygen': DoxygenBuilder, 'sphinx': SphinxBuilder}
builder_class = builders.get(builder_name, None)
if (builder_class is None):
builder_names = ', '.joi... | Instantiate a new builder with the given builder_name. | rosdoc2/verbs/build/builders/__init__.py | create_builder_by_name | rkent/rosdoc2 | 3 | python | def create_builder_by_name(builder_name, *, builder_dict, build_context):
builders = {'doxygen': DoxygenBuilder, 'sphinx': SphinxBuilder}
builder_class = builders.get(builder_name, None)
if (builder_class is None):
builder_names = ', '.join(list(builders.keys()))
raise RuntimeError(f"Er... | def create_builder_by_name(builder_name, *, builder_dict, build_context):
builders = {'doxygen': DoxygenBuilder, 'sphinx': SphinxBuilder}
builder_class = builders.get(builder_name, None)
if (builder_class is None):
builder_names = ', '.join(list(builders.keys()))
raise RuntimeError(f"Er... |
b55d9d12bbfca214734bf1555a677febd0800b96fd11f9ffebb781592cca4e1b | def fetch_available_indexes() -> IndexList:
'Fetches the available Common Crawl Indexes to search.\n\n Returns:\n A list containing available indexes and information about them.\n\n '
index_list = requests.get('https://index.commoncrawl.org/collinfo.json').json()
indexes = [index['id'].replace(... | Fetches the available Common Crawl Indexes to search.
Returns:
A list containing available indexes and information about them. | comcrawl/utils/initialization.py | fetch_available_indexes | akozlo/comcrawl | 118 | python | def fetch_available_indexes() -> IndexList:
'Fetches the available Common Crawl Indexes to search.\n\n Returns:\n A list containing available indexes and information about them.\n\n '
index_list = requests.get('https://index.commoncrawl.org/collinfo.json').json()
indexes = [index['id'].replace(... | def fetch_available_indexes() -> IndexList:
'Fetches the available Common Crawl Indexes to search.\n\n Returns:\n A list containing available indexes and information about them.\n\n '
index_list = requests.get('https://index.commoncrawl.org/collinfo.json').json()
indexes = [index['id'].replace(... |
366315aefa5022b700c9daa1ba0da7ac01cc375840a5ca91c312d85692ba09cc | def get_conf_value(name, valid_types=None, default=None):
'Get ``name`` from ``configuration.py``\n\n Returns ``default`` if not present or not one of types in ``valid_types``\n '
spec = importlib.util.spec_from_file_location('*', conf_path)
configuration = importlib.util.module_from_spec(spec)
sp... | Get ``name`` from ``configuration.py``
Returns ``default`` if not present or not one of types in ``valid_types`` | editor/utils.py | get_conf_value | CrazyIvan359/eos | 0 | python | def get_conf_value(name, valid_types=None, default=None):
'Get ``name`` from ``configuration.py``\n\n Returns ``default`` if not present or not one of types in ``valid_types``\n '
spec = importlib.util.spec_from_file_location('*', conf_path)
configuration = importlib.util.module_from_spec(spec)
sp... | def get_conf_value(name, valid_types=None, default=None):
'Get ``name`` from ``configuration.py``\n\n Returns ``default`` if not present or not one of types in ``valid_types``\n '
spec = importlib.util.spec_from_file_location('*', conf_path)
configuration = importlib.util.module_from_spec(spec)
sp... |
89b2d329451ef8ef9fc670f5bc131b6be67e48da514b4829fe5ddc4888acd0ad | def validate_item_name(name, prefix, suffix):
'Verifies that ``name`` starts with ``prefix`` and ends with ``suffix``.\n Returns ``True`` or ``False``'
return ((name[:len(prefix)] == prefix) and (name[(- len(suffix)):] == suffix)) | Verifies that ``name`` starts with ``prefix`` and ends with ``suffix``.
Returns ``True`` or ``False`` | editor/utils.py | validate_item_name | CrazyIvan359/eos | 0 | python | def validate_item_name(name, prefix, suffix):
'Verifies that ``name`` starts with ``prefix`` and ends with ``suffix``.\n Returns ``True`` or ``False``'
return ((name[:len(prefix)] == prefix) and (name[(- len(suffix)):] == suffix)) | def validate_item_name(name, prefix, suffix):
'Verifies that ``name`` starts with ``prefix`` and ends with ``suffix``.\n Returns ``True`` or ``False``'
return ((name[:len(prefix)] == prefix) and (name[(- len(suffix)):] == suffix))<|docstring|>Verifies that ``name`` starts with ``prefix`` and ends with ``suff... |
637d7f9a0bfe4314750f7b951f36a9b9c7b3fd69985d68da5b8738add30f81cf | def get_scene_item(group):
'Finds the scene item in a group.\n\n Returns the scene item or ``None`` if it does not find exactly one match.\n '
items = [item for item in group.get('members', {}) if validate_item_name(item['name'], get_conf_value(CONF_KEY_SCENE_PREFIX, default=''), get_conf_value(CONF_KEY_S... | Finds the scene item in a group.
Returns the scene item or ``None`` if it does not find exactly one match. | editor/utils.py | get_scene_item | CrazyIvan359/eos | 0 | python | def get_scene_item(group):
'Finds the scene item in a group.\n\n Returns the scene item or ``None`` if it does not find exactly one match.\n '
items = [item for item in group.get('members', {}) if validate_item_name(item['name'], get_conf_value(CONF_KEY_SCENE_PREFIX, default=), get_conf_value(CONF_KEY_SCE... | def get_scene_item(group):
'Finds the scene item in a group.\n\n Returns the scene item or ``None`` if it does not find exactly one match.\n '
items = [item for item in group.get('members', {}) if validate_item_name(item['name'], get_conf_value(CONF_KEY_SCENE_PREFIX, default=), get_conf_value(CONF_KEY_SCE... |
51b8f3f3b474bc985239e8a816cf003ec9ac34409067371c9fe5aab75cbbf7c1 | def get_light_items(group, host):
'Finds all light items in a group.\n\n Returns a list of valid Eos lights.\n '
return ([item for item in group['members'] if ((item['type'] not in itemtypesGroup) and (item['type'] in itemtypesLight) and (item['name'] != get_scene_item(group)['name']) and (resolve_type(ge... | Finds all light items in a group.
Returns a list of valid Eos lights. | editor/utils.py | get_light_items | CrazyIvan359/eos | 0 | python | def get_light_items(group, host):
'Finds all light items in a group.\n\n Returns a list of valid Eos lights.\n '
return ([item for item in group['members'] if ((item['type'] not in itemtypesGroup) and (item['type'] in itemtypesLight) and (item['name'] != get_scene_item(group)['name']) and (resolve_type(ge... | def get_light_items(group, host):
'Finds all light items in a group.\n\n Returns a list of valid Eos lights.\n '
return ([item for item in group['members'] if ((item['type'] not in itemtypesGroup) and (item['type'] in itemtypesLight) and (item['name'] != get_scene_item(group)['name']) and (resolve_type(ge... |
25d44bf3abafd06181ee60e76a59c32841dfb7c53ec146d465d1c55d3ca68d07 | def get_group_items(group):
'Finds all group items in a group.\n\n Returns a list of valid Eos groups.\n '
return ([item for item in group['members'] if ((item['type'] in itemtypesGroup) and (get_scene_item(group) is not None))] if ('members' in group) else []) | Finds all group items in a group.
Returns a list of valid Eos groups. | editor/utils.py | get_group_items | CrazyIvan359/eos | 0 | python | def get_group_items(group):
'Finds all group items in a group.\n\n Returns a list of valid Eos groups.\n '
return ([item for item in group['members'] if ((item['type'] in itemtypesGroup) and (get_scene_item(group) is not None))] if ('members' in group) else []) | def get_group_items(group):
'Finds all group items in a group.\n\n Returns a list of valid Eos groups.\n '
return ([item for item in group['members'] if ((item['type'] in itemtypesGroup) and (get_scene_item(group) is not None))] if ('members' in group) else [])<|docstring|>Finds all group items in a group... |
fbf6e94fb6698cb895865b5f12955f7c2d6c19e6751b8aa0d232441dded1a7fa | def resolve_type(value):
'Attempts to resolve the type of ``value``.\n\n It will return ``value`` as the python type if possible, otherwise will\n return value as string.\n '
value = str(value).strip()
if (str(value).lower() == 'true'):
return True
elif (str(value).lower() == 'false'):
... | Attempts to resolve the type of ``value``.
It will return ``value`` as the python type if possible, otherwise will
return value as string. | editor/utils.py | resolve_type | CrazyIvan359/eos | 0 | python | def resolve_type(value):
'Attempts to resolve the type of ``value``.\n\n It will return ``value`` as the python type if possible, otherwise will\n return value as string.\n '
value = str(value).strip()
if (str(value).lower() == 'true'):
return True
elif (str(value).lower() == 'false'):
... | def resolve_type(value):
'Attempts to resolve the type of ``value``.\n\n It will return ``value`` as the python type if possible, otherwise will\n return value as string.\n '
value = str(value).strip()
if (str(value).lower() == 'true'):
return True
elif (str(value).lower() == 'false'):
... |
bd5e20ca35cdf187909330a2439377573f4fdb175416947d4a64a30468cc206c | def get_item_eos_group(item, host):
"Gets the Eos group from the item's groups.\n\n Returns the group item or ``None`` if it does not find exactly one match.\n "
groups = [group for group in item['groupNames'] if get_scene_item(validate_item(group, host))]
if (not groups):
return None
elif... | Gets the Eos group from the item's groups.
Returns the group item or ``None`` if it does not find exactly one match. | editor/utils.py | get_item_eos_group | CrazyIvan359/eos | 0 | python | def get_item_eos_group(item, host):
"Gets the Eos group from the item's groups.\n\n Returns the group item or ``None`` if it does not find exactly one match.\n "
groups = [group for group in item['groupNames'] if get_scene_item(validate_item(group, host))]
if (not groups):
return None
elif... | def get_item_eos_group(item, host):
"Gets the Eos group from the item's groups.\n\n Returns the group item or ``None`` if it does not find exactly one match.\n "
groups = [group for group in item['groupNames'] if get_scene_item(validate_item(group, host))]
if (not groups):
return None
elif... |
3031aa579d7d44d77640f37652b649e06de3638d5c7152c06c71b5bc70f34cae | def get_other_items(group, host):
'Finds all non Eos items in a group.\n\n Returns a list of all non Eos items in the group.\n '
others = {item['name']: item for item in group['members']}
for item in get_light_items(group, host):
others.pop(item['name'], None)
for item in get_group_items(g... | Finds all non Eos items in a group.
Returns a list of all non Eos items in the group. | editor/utils.py | get_other_items | CrazyIvan359/eos | 0 | python | def get_other_items(group, host):
'Finds all non Eos items in a group.\n\n Returns a list of all non Eos items in the group.\n '
others = {item['name']: item for item in group['members']}
for item in get_light_items(group, host):
others.pop(item['name'], None)
for item in get_group_items(g... | def get_other_items(group, host):
'Finds all non Eos items in a group.\n\n Returns a list of all non Eos items in the group.\n '
others = {item['name']: item for item in group['members']}
for item in get_light_items(group, host):
others.pop(item['name'], None)
for item in get_group_items(g... |
fbdfdfb1003a48a6a094c37987e4ab6c4881c3aef2d27c01b300251369453eb7 | def update_dict(d, u):
'\n Recursively update dict ``d`` with dict ``u``\n '
for k in u:
dv = d.get(k, {})
if (not isinstance(dv, collections.Mapping)):
d[k] = u[k]
elif isinstance(u[k], collections.Mapping):
d[k] = update_dict(dv, u[k])
else:
... | Recursively update dict ``d`` with dict ``u`` | editor/utils.py | update_dict | CrazyIvan359/eos | 0 | python | def update_dict(d, u):
'\n \n '
for k in u:
dv = d.get(k, {})
if (not isinstance(dv, collections.Mapping)):
d[k] = u[k]
elif isinstance(u[k], collections.Mapping):
d[k] = update_dict(dv, u[k])
else:
d[k] = u[k]
return d | def update_dict(d, u):
'\n \n '
for k in u:
dv = d.get(k, {})
if (not isinstance(dv, collections.Mapping)):
d[k] = u[k]
elif isinstance(u[k], collections.Mapping):
d[k] = update_dict(dv, u[k])
else:
d[k] = u[k]
return d<|docstring|>Re... |
3a919d944b765b50ebddd97c08750f9f424ec1d46dd2dca0a4c6e3ca9fe9dec9 | def print_box(message: str, min_length: int=100, print_str: bool=True, col=bcolors.OKBLUE) -> str:
'\n Print a string in a neat box.\n\n :param message: Message to be printed\n :param min_length: Minimum length of box (in characters)\n :param print_str: if False, the generated string will not be printed... | Print a string in a neat box.
:param message: Message to be printed
:param min_length: Minimum length of box (in characters)
:param print_str: if False, the generated string will not be printed (just returned)
:return: str to be printed if return_str is True | fsh_validator/fsh_validator.py | print_box | glichtner/fsh-validator | 0 | python | def print_box(message: str, min_length: int=100, print_str: bool=True, col=bcolors.OKBLUE) -> str:
'\n Print a string in a neat box.\n\n :param message: Message to be printed\n :param min_length: Minimum length of box (in characters)\n :param print_str: if False, the generated string will not be printed... | def print_box(message: str, min_length: int=100, print_str: bool=True, col=bcolors.OKBLUE) -> str:
'\n Print a string in a neat box.\n\n :param message: Message to be printed\n :param min_length: Minimum length of box (in characters)\n :param print_str: if False, the generated string will not be printed... |
6ffb8ec96c1f86db471af8756561a1c76faedd0512ba8abf3b5b438cb467c33f | def download_validator(fname_validator: Path) -> None:
'\n Download FHIR Java validator.\n\n :param fname_validator: Filename where the validator will be downloaded to\n :return: None\n '
urllib.request.urlretrieve(VALIDATOR_URL, fname_validator) | Download FHIR Java validator.
:param fname_validator: Filename where the validator will be downloaded to
:return: None | fsh_validator/fsh_validator.py | download_validator | glichtner/fsh-validator | 0 | python | def download_validator(fname_validator: Path) -> None:
'\n Download FHIR Java validator.\n\n :param fname_validator: Filename where the validator will be downloaded to\n :return: None\n '
urllib.request.urlretrieve(VALIDATOR_URL, fname_validator) | def download_validator(fname_validator: Path) -> None:
'\n Download FHIR Java validator.\n\n :param fname_validator: Filename where the validator will be downloaded to\n :return: None\n '
urllib.request.urlretrieve(VALIDATOR_URL, fname_validator)<|docstring|>Download FHIR Java validator.
:param fna... |
a9d6e074be75a107b3e1a5514cee52fc2e58692315755efbe947ccf708bc5f01 | def parse_fsh(fname_fsh: Path) -> Tuple[(List[Dict], List[Dict])]:
'\n Parse FSH file to extract profiles and instances that are defined in it.\n\n :param fname_fsh: Filename of the FSH file to parse\n :return: List of defined profiles, List of defined instances\n '
with open(fname_fsh, 'r') as f:
... | Parse FSH file to extract profiles and instances that are defined in it.
:param fname_fsh: Filename of the FSH file to parse
:return: List of defined profiles, List of defined instances | fsh_validator/fsh_validator.py | parse_fsh | glichtner/fsh-validator | 0 | python | def parse_fsh(fname_fsh: Path) -> Tuple[(List[Dict], List[Dict])]:
'\n Parse FSH file to extract profiles and instances that are defined in it.\n\n :param fname_fsh: Filename of the FSH file to parse\n :return: List of defined profiles, List of defined instances\n '
with open(fname_fsh, 'r') as f:
... | def parse_fsh(fname_fsh: Path) -> Tuple[(List[Dict], List[Dict])]:
'\n Parse FSH file to extract profiles and instances that are defined in it.\n\n :param fname_fsh: Filename of the FSH file to parse\n :return: List of defined profiles, List of defined instances\n '
with open(fname_fsh, 'r') as f:
... |
09ff521520b343aac97c6ce95954195928fbb756fd50db88b6b3b8b6fac270b6 | def parse_fsh_generated(path: Path) -> Tuple[(Dict, Dict, Dict, Dict, Dict, Dict)]:
'\n Parse json files generated from FSH through SUSHI.\n\n Goal: Extract structure definitions, instances, value set and dependencies from generated JSON files.\n\n :param path: Path to generated files through SUSHI\n :r... | Parse json files generated from FSH through SUSHI.
Goal: Extract structure definitions, instances, value set and dependencies from generated JSON files.
:param path: Path to generated files through SUSHI
:return: StructureDefinitions, Instances, Dependencies, ValueSets, CodeSystems, Extensions | fsh_validator/fsh_validator.py | parse_fsh_generated | glichtner/fsh-validator | 0 | python | def parse_fsh_generated(path: Path) -> Tuple[(Dict, Dict, Dict, Dict, Dict, Dict)]:
'\n Parse json files generated from FSH through SUSHI.\n\n Goal: Extract structure definitions, instances, value set and dependencies from generated JSON files.\n\n :param path: Path to generated files through SUSHI\n :r... | def parse_fsh_generated(path: Path) -> Tuple[(Dict, Dict, Dict, Dict, Dict, Dict)]:
'\n Parse json files generated from FSH through SUSHI.\n\n Goal: Extract structure definitions, instances, value set and dependencies from generated JSON files.\n\n :param path: Path to generated files through SUSHI\n :r... |
b16e2bf22c47c2e64f26e577a13b06a63509e8b9ff4be009046043ab4009b895 | def get_paths(base_path: Union[(str, Path)]) -> Tuple[(Path, Path)]:
'\n Get fsh input and output paths from base path.\n\n :param base_path: Base path\n :return: FSH input path, FSH output path\n '
return (((Path(base_path) / 'input') / 'fsh'), ((Path(base_path) / 'fsh-generated') / 'resources')) | Get fsh input and output paths from base path.
:param base_path: Base path
:return: FSH input path, FSH output path | fsh_validator/fsh_validator.py | get_paths | glichtner/fsh-validator | 0 | python | def get_paths(base_path: Union[(str, Path)]) -> Tuple[(Path, Path)]:
'\n Get fsh input and output paths from base path.\n\n :param base_path: Base path\n :return: FSH input path, FSH output path\n '
return (((Path(base_path) / 'input') / 'fsh'), ((Path(base_path) / 'fsh-generated') / 'resources')) | def get_paths(base_path: Union[(str, Path)]) -> Tuple[(Path, Path)]:
'\n Get fsh input and output paths from base path.\n\n :param base_path: Base path\n :return: FSH input path, FSH output path\n '
return (((Path(base_path) / 'input') / 'fsh'), ((Path(base_path) / 'fsh-generated') / 'resources'))<|... |
1ccf12cd387992ac1326f6261862011fbdd90eccd480e6b8d274d4e1a364f9f3 | def get_fsh_base_path(path: Union[(str, Path)]) -> Path:
'\n Get the base path of an FSH project given a filename or path.\n\n FSH files in sushi projects are located in the subfolder "input/fsh/". This method returns the parent of this base\n path, if available, or throws an exception\n\n :param path: ... | Get the base path of an FSH project given a filename or path.
FSH files in sushi projects are located in the subfolder "input/fsh/". This method returns the parent of this base
path, if available, or throws an exception
:param path: Base to get fsh base path from
:return: FSH project base path | fsh_validator/fsh_validator.py | get_fsh_base_path | glichtner/fsh-validator | 0 | python | def get_fsh_base_path(path: Union[(str, Path)]) -> Path:
'\n Get the base path of an FSH project given a filename or path.\n\n FSH files in sushi projects are located in the subfolder "input/fsh/". This method returns the parent of this base\n path, if available, or throws an exception\n\n :param path: ... | def get_fsh_base_path(path: Union[(str, Path)]) -> Path:
'\n Get the base path of an FSH project given a filename or path.\n\n FSH files in sushi projects are located in the subfolder "input/fsh/". This method returns the parent of this base\n path, if available, or throws an exception\n\n :param path: ... |
cd928f00822bfcbaa652e7ae59a18432d2ead3f27d2081670c669ddb50f5befa | def deduplicate_obi_codes(fname: Path) -> None:
'\n Remove duplicate http://terminology.hl7.org/CodeSystem/v2-0203#OBI codes from an instance.\n\n When using the Medizininformatik Initiative Profile LabObservation, SUSHI v2.1.1 inserts the identifier.type code\n for http://terminology.hl7.org/CodeSystem/v2... | Remove duplicate http://terminology.hl7.org/CodeSystem/v2-0203#OBI codes from an instance.
When using the Medizininformatik Initiative Profile LabObservation, SUSHI v2.1.1 inserts the identifier.type code
for http://terminology.hl7.org/CodeSystem/v2-0203#OBI twice, but it has a cardinality of 1, resulting in an error
... | fsh_validator/fsh_validator.py | deduplicate_obi_codes | glichtner/fsh-validator | 0 | python | def deduplicate_obi_codes(fname: Path) -> None:
'\n Remove duplicate http://terminology.hl7.org/CodeSystem/v2-0203#OBI codes from an instance.\n\n When using the Medizininformatik Initiative Profile LabObservation, SUSHI v2.1.1 inserts the identifier.type code\n for http://terminology.hl7.org/CodeSystem/v2... | def deduplicate_obi_codes(fname: Path) -> None:
'\n Remove duplicate http://terminology.hl7.org/CodeSystem/v2-0203#OBI codes from an instance.\n\n When using the Medizininformatik Initiative Profile LabObservation, SUSHI v2.1.1 inserts the identifier.type code\n for http://terminology.hl7.org/CodeSystem/v2... |
b11d82d58b562cdcf34ee4edf72fb65641cc92e18f20471e487fb3070ff66e96 | def get_abstract_profile_ids(sdefs: Dict[(str, Dict)]) -> Set[str]:
'\n Get all abstract profile IDs from a set of StructureDefinitions.\n\n :param sdefs: StructureDefinitions to get abstract profile IDs from\n :return: Set of abstract profile IDs\n '
return set([v['id'] for v in sdefs.values() if v... | Get all abstract profile IDs from a set of StructureDefinitions.
:param sdefs: StructureDefinitions to get abstract profile IDs from
:return: Set of abstract profile IDs | fsh_validator/fsh_validator.py | get_abstract_profile_ids | glichtner/fsh-validator | 0 | python | def get_abstract_profile_ids(sdefs: Dict[(str, Dict)]) -> Set[str]:
'\n Get all abstract profile IDs from a set of StructureDefinitions.\n\n :param sdefs: StructureDefinitions to get abstract profile IDs from\n :return: Set of abstract profile IDs\n '
return set([v['id'] for v in sdefs.values() if v... | def get_abstract_profile_ids(sdefs: Dict[(str, Dict)]) -> Set[str]:
'\n Get all abstract profile IDs from a set of StructureDefinitions.\n\n :param sdefs: StructureDefinitions to get abstract profile IDs from\n :return: Set of abstract profile IDs\n '
return set([v['id'] for v in sdefs.values() if v... |
b2a695e7abfc1379a4f056e607b3396462178a7a5ef52bc548968cc7411b24ef | def _validate_fsh_files(path_output: Path, fnames: List[Path], fname_validator: str, fhir_version: str, exclude_code_systems: Optional[Set]=None, exclude_resource_types: Optional[Set]=None, verbose: bool=False) -> List[ValidatorStatus]:
'\n Validate FSH files.\n\n Process:\n - Extract Profiles and Instance... | Validate FSH files.
Process:
- Extract Profiles and Instances defined in each FSH file
- Run FHIR Java validator for each instance to validate it against its corresponding profile
:param path_output: output path (of SUSHI project)
:param fnames: FSH file names to validate (full paths)
:param fname_validator: full pat... | fsh_validator/fsh_validator.py | _validate_fsh_files | glichtner/fsh-validator | 0 | python | def _validate_fsh_files(path_output: Path, fnames: List[Path], fname_validator: str, fhir_version: str, exclude_code_systems: Optional[Set]=None, exclude_resource_types: Optional[Set]=None, verbose: bool=False) -> List[ValidatorStatus]:
'\n Validate FSH files.\n\n Process:\n - Extract Profiles and Instance... | def _validate_fsh_files(path_output: Path, fnames: List[Path], fname_validator: str, fhir_version: str, exclude_code_systems: Optional[Set]=None, exclude_resource_types: Optional[Set]=None, verbose: bool=False) -> List[ValidatorStatus]:
'\n Validate FSH files.\n\n Process:\n - Extract Profiles and Instance... |
fb73502f1250fae84b88d4b363a202903b05c2dd302fa594e450c6c0823914e7 | def validate_fsh(fsh_filenames: List[FshPath], fname_validator: str, fhir_version: str, exclude_code_systems: Optional[Set]=None, exclude_resource_types: Optional[Set]=None, verbose: bool=False) -> List[ValidatorStatus]:
'\n Validate specific fsh files.\n\n Process:\n - Extract Profiles and Instances defin... | Validate specific fsh files.
Process:
- Extract Profiles and Instances defined in FSH file
- Run FHIR Java validator for each instance to validate it against its corresponding profile
:param fsh_filename: FSH file names
:param fname_validator: Full path to FHIR Java validator file
:param fhir_version: FHIR version to... | fsh_validator/fsh_validator.py | validate_fsh | glichtner/fsh-validator | 0 | python | def validate_fsh(fsh_filenames: List[FshPath], fname_validator: str, fhir_version: str, exclude_code_systems: Optional[Set]=None, exclude_resource_types: Optional[Set]=None, verbose: bool=False) -> List[ValidatorStatus]:
'\n Validate specific fsh files.\n\n Process:\n - Extract Profiles and Instances defin... | def validate_fsh(fsh_filenames: List[FshPath], fname_validator: str, fhir_version: str, exclude_code_systems: Optional[Set]=None, exclude_resource_types: Optional[Set]=None, verbose: bool=False) -> List[ValidatorStatus]:
'\n Validate specific fsh files.\n\n Process:\n - Extract Profiles and Instances defin... |
3e00277415cabebe6150cc941f0b165bbee0b73e433271677ee90e54b9f9ca9a | def validate_all_fsh(base_path: str, subdir: str, fname_validator: str, fhir_version: str, exclude_code_systems: Optional[Set]=None, exclude_resource_types: Optional[Set]=None, verbose: bool=False) -> List[ValidatorStatus]:
'\n Validate all FSH files in a given subdir.\n\n Process:\n - Extract Profiles and... | Validate all FSH files in a given subdir.
Process:
- Extract Profiles and Instances defined in FSH file
- Run FHIR Java validator for each instance to validate it against its corresponding profile
:param base_path: base path (of SUSHI project)
:param subdir: subdirectory of profiles
:param fname_validator: full path ... | fsh_validator/fsh_validator.py | validate_all_fsh | glichtner/fsh-validator | 0 | python | def validate_all_fsh(base_path: str, subdir: str, fname_validator: str, fhir_version: str, exclude_code_systems: Optional[Set]=None, exclude_resource_types: Optional[Set]=None, verbose: bool=False) -> List[ValidatorStatus]:
'\n Validate all FSH files in a given subdir.\n\n Process:\n - Extract Profiles and... | def validate_all_fsh(base_path: str, subdir: str, fname_validator: str, fhir_version: str, exclude_code_systems: Optional[Set]=None, exclude_resource_types: Optional[Set]=None, verbose: bool=False) -> List[ValidatorStatus]:
'\n Validate all FSH files in a given subdir.\n\n Process:\n - Extract Profiles and... |
4f5ded68d1aa9f3395df69fa06639cc05fc2e8a6490546ee89204f910590a98e | def check_instances_availability(fsh_profiles: List[Dict], fsh_instances: List[Dict], abstract_profiles: Set[str]) -> List[str]:
'\n Check if at least one instance exists for each defined profile extracted from FSH file.\n\n :param fsh_profiles: List of profile defined in FSH file\n :param fsh_instances: L... | Check if at least one instance exists for each defined profile extracted from FSH file.
:param fsh_profiles: List of profile defined in FSH file
:param fsh_instances: List of instances defined in FSH file
:param abstract_profiles: Set of abstract profiles
:return: List of profiles without instances | fsh_validator/fsh_validator.py | check_instances_availability | glichtner/fsh-validator | 0 | python | def check_instances_availability(fsh_profiles: List[Dict], fsh_instances: List[Dict], abstract_profiles: Set[str]) -> List[str]:
'\n Check if at least one instance exists for each defined profile extracted from FSH file.\n\n :param fsh_profiles: List of profile defined in FSH file\n :param fsh_instances: L... | def check_instances_availability(fsh_profiles: List[Dict], fsh_instances: List[Dict], abstract_profiles: Set[str]) -> List[str]:
'\n Check if at least one instance exists for each defined profile extracted from FSH file.\n\n :param fsh_profiles: List of profile defined in FSH file\n :param fsh_instances: L... |
4fd9add56070724fed4051a68574ebcf815a8b8e2e9eeacd4068a176e338ee3c | def get_profile_chain(sdefs: Dict, profile: str) -> List[str]:
'\n Get a list of all profiles that a specific profile is based on and that are part of this SUSHI project.\n\n The objective of this function to provide a list of all parent profiles of a specific profile for inclusion as\n parameters to the F... | Get a list of all profiles that a specific profile is based on and that are part of this SUSHI project.
The objective of this function to provide a list of all parent profiles of a specific profile for inclusion as
parameters to the FHIR validator.
:param sdefs: StructureDefinitions from SUSHI output
:param profile: ... | fsh_validator/fsh_validator.py | get_profile_chain | glichtner/fsh-validator | 0 | python | def get_profile_chain(sdefs: Dict, profile: str) -> List[str]:
'\n Get a list of all profiles that a specific profile is based on and that are part of this SUSHI project.\n\n The objective of this function to provide a list of all parent profiles of a specific profile for inclusion as\n parameters to the F... | def get_profile_chain(sdefs: Dict, profile: str) -> List[str]:
'\n Get a list of all profiles that a specific profile is based on and that are part of this SUSHI project.\n\n The objective of this function to provide a list of all parent profiles of a specific profile for inclusion as\n parameters to the F... |
3bec1412fab541931e16d131412c30f28cc2197bcb5371a698470af7a6551873 | def get_profiles_to_include(sdefs, instance):
'\n Get a list of all profiles that a specific instance is based on and that are part of this SUSHI project.\n\n :param sdefs: StructureDefinitions from SUSHI output\n :param instance: Instance name to get all parents profiles of\n :return: List of all paren... | Get a list of all profiles that a specific instance is based on and that are part of this SUSHI project.
:param sdefs: StructureDefinitions from SUSHI output
:param instance: Instance name to get all parents profiles of
:return: List of all parent profiles of supplied instance name (including the instance itself) | fsh_validator/fsh_validator.py | get_profiles_to_include | glichtner/fsh-validator | 0 | python | def get_profiles_to_include(sdefs, instance):
'\n Get a list of all profiles that a specific instance is based on and that are part of this SUSHI project.\n\n :param sdefs: StructureDefinitions from SUSHI output\n :param instance: Instance name to get all parents profiles of\n :return: List of all paren... | def get_profiles_to_include(sdefs, instance):
'\n Get a list of all profiles that a specific instance is based on and that are part of this SUSHI project.\n\n :param sdefs: StructureDefinitions from SUSHI output\n :param instance: Instance name to get all parents profiles of\n :return: List of all paren... |
2ead2d1490360fdf31de4950b15075ee2ec55c6556d3194e090a4eeea7ed759c | def run_validation(fname_validator: str, fsh_instances: List[Dict], sdefs: Dict, instances: Dict, deps: Dict, vs: Dict, cs: Dict, extensions: Dict, fhir_version: str, verbose: bool) -> List[ValidatorStatus]:
'\n Run FHIR Java validator for each instance defined in FSH file.\n\n :param fname_validator: full pa... | Run FHIR Java validator for each instance defined in FSH file.
:param fname_validator: full path to FHIR Java validator file
:param fsh_instances: List of instances defined in FSH file
:param sdefs: StructureDefinitions from SUSHI output
:param instances: Instance from SUSHI output
:param deps: Dependencies from SUSHI... | fsh_validator/fsh_validator.py | run_validation | glichtner/fsh-validator | 0 | python | def run_validation(fname_validator: str, fsh_instances: List[Dict], sdefs: Dict, instances: Dict, deps: Dict, vs: Dict, cs: Dict, extensions: Dict, fhir_version: str, verbose: bool) -> List[ValidatorStatus]:
'\n Run FHIR Java validator for each instance defined in FSH file.\n\n :param fname_validator: full pa... | def run_validation(fname_validator: str, fsh_instances: List[Dict], sdefs: Dict, instances: Dict, deps: Dict, vs: Dict, cs: Dict, extensions: Dict, fhir_version: str, verbose: bool) -> List[ValidatorStatus]:
'\n Run FHIR Java validator for each instance defined in FSH file.\n\n :param fname_validator: full pa... |
6f8413b2d0b6ac9543f6276d1332ff32ae9913bb34f2c35826bad7e37e27bb44 | def run_command(cmd: Union[(str, List[str])]) -> None:
'\n Run a shell command.\n\n Raises CommandNotSuccessfulException if the return code of the command is not 0.\n\n :param cmd: Command to run as single string or list of strings\n :return: None\n '
if isinstance(cmd, list):
cmd = ' '.... | Run a shell command.
Raises CommandNotSuccessfulException if the return code of the command is not 0.
:param cmd: Command to run as single string or list of strings
:return: None | fsh_validator/fsh_validator.py | run_command | glichtner/fsh-validator | 0 | python | def run_command(cmd: Union[(str, List[str])]) -> None:
'\n Run a shell command.\n\n Raises CommandNotSuccessfulException if the return code of the command is not 0.\n\n :param cmd: Command to run as single string or list of strings\n :return: None\n '
if isinstance(cmd, list):
cmd = ' '.... | def run_command(cmd: Union[(str, List[str])]) -> None:
'\n Run a shell command.\n\n Raises CommandNotSuccessfulException if the return code of the command is not 0.\n\n :param cmd: Command to run as single string or list of strings\n :return: None\n '
if isinstance(cmd, list):
cmd = ' '.... |
6c06a6d86a59137de41149339018588dc2a51cc314ce90865b88e9fa09330ec6 | def printc(msg: str, col: str, end: str='\n') -> None:
'\n Print a message in color to console.\n\n :param msg: Message to print\n :param col: Color (from bcolors)\n :param end: end of line character(s)\n :return: None\n '
print(f'{col}{msg}{bcolors.ENDC}', end=end, flush=True) | Print a message in color to console.
:param msg: Message to print
:param col: Color (from bcolors)
:param end: end of line character(s)
:return: None | fsh_validator/fsh_validator.py | printc | glichtner/fsh-validator | 0 | python | def printc(msg: str, col: str, end: str='\n') -> None:
'\n Print a message in color to console.\n\n :param msg: Message to print\n :param col: Color (from bcolors)\n :param end: end of line character(s)\n :return: None\n '
print(f'{col}{msg}{bcolors.ENDC}', end=end, flush=True) | def printc(msg: str, col: str, end: str='\n') -> None:
'\n Print a message in color to console.\n\n :param msg: Message to print\n :param col: Color (from bcolors)\n :param end: end of line character(s)\n :return: None\n '
print(f'{col}{msg}{bcolors.ENDC}', end=end, flush=True)<|docstring|>Pri... |
d78253f1639cec2a2a6bff7e3fd86f400834b324b1e17c9afebaae51c908af6e | def execute_validator(cmd: Union[(str, List[str])], verbose: bool=False) -> ValidatorStatus:
"\n Execute the Java FHIR validator and parse it's output.\n\n :param cmd: Command to execute\n :param verbose: If true, all output from the validator will be printed to stdout.\n :return: ValidatorStatus object... | Execute the Java FHIR validator and parse it's output.
:param cmd: Command to execute
:param verbose: If true, all output from the validator will be printed to stdout.
:return: ValidatorStatus object | fsh_validator/fsh_validator.py | execute_validator | glichtner/fsh-validator | 0 | python | def execute_validator(cmd: Union[(str, List[str])], verbose: bool=False) -> ValidatorStatus:
"\n Execute the Java FHIR validator and parse it's output.\n\n :param cmd: Command to execute\n :param verbose: If true, all output from the validator will be printed to stdout.\n :return: ValidatorStatus object... | def execute_validator(cmd: Union[(str, List[str])], verbose: bool=False) -> ValidatorStatus:
"\n Execute the Java FHIR validator and parse it's output.\n\n :param cmd: Command to execute\n :param verbose: If true, all output from the validator will be printed to stdout.\n :return: ValidatorStatus object... |
79fe1a3a052eb5d2d809d52130d3231d448d3b452841e378548db6d329e429a5 | def store_log(results: List[ValidatorStatus], log_path: Path) -> None:
'\n Store parsed and full output from validator run to files.\n\n Parsed output will be saved to an excel file in tabular format, full output to a text file.\n\n :param results: List of ValidatorStatus objects as returned by _validate_f... | Store parsed and full output from validator run to files.
Parsed output will be saved to an excel file in tabular format, full output to a text file.
:param results: List of ValidatorStatus objects as returned by _validate_fsh_files()
:param log_path: Path where log files are stored
:return: None | fsh_validator/fsh_validator.py | store_log | glichtner/fsh-validator | 0 | python | def store_log(results: List[ValidatorStatus], log_path: Path) -> None:
'\n Store parsed and full output from validator run to files.\n\n Parsed output will be saved to an excel file in tabular format, full output to a text file.\n\n :param results: List of ValidatorStatus objects as returned by _validate_f... | def store_log(results: List[ValidatorStatus], log_path: Path) -> None:
'\n Store parsed and full output from validator run to files.\n\n Parsed output will be saved to an excel file in tabular format, full output to a text file.\n\n :param results: List of ValidatorStatus objects as returned by _validate_f... |
13d2fceb6785d07126347604dd2db4e331ebedeac94c5d7731a283e40fa35a80 | def get_fhir_version_from_sushi_config(base_path: Path) -> str:
'\n Get the FHIR version from the SUSHI config file.\n\n :param base_path: Path to the SUSHI config file\n :return: FHIR version string\n '
conf_filename = (base_path / 'sushi-config.yaml')
if (not conf_filename.exists()):
r... | Get the FHIR version from the SUSHI config file.
:param base_path: Path to the SUSHI config file
:return: FHIR version string | fsh_validator/fsh_validator.py | get_fhir_version_from_sushi_config | glichtner/fsh-validator | 0 | python | def get_fhir_version_from_sushi_config(base_path: Path) -> str:
'\n Get the FHIR version from the SUSHI config file.\n\n :param base_path: Path to the SUSHI config file\n :return: FHIR version string\n '
conf_filename = (base_path / 'sushi-config.yaml')
if (not conf_filename.exists()):
r... | def get_fhir_version_from_sushi_config(base_path: Path) -> str:
'\n Get the FHIR version from the SUSHI config file.\n\n :param base_path: Path to the SUSHI config file\n :return: FHIR version string\n '
conf_filename = (base_path / 'sushi-config.yaml')
if (not conf_filename.exists()):
r... |
e0140543422ce45306f8412dd9cc68c7f7971fea5ad6ed3ebc60f44a358059e2 | def assert_sushi_installed() -> None:
'\n Assert that FSH Sushi is an executable on the system.\n\n :return: None\n '
if (shutil.which('sushi') is None):
raise FileNotFoundError('Could not detect fsh sushi on the system. Install via "npm install -g fsh-sushi".') | Assert that FSH Sushi is an executable on the system.
:return: None | fsh_validator/fsh_validator.py | assert_sushi_installed | glichtner/fsh-validator | 0 | python | def assert_sushi_installed() -> None:
'\n Assert that FSH Sushi is an executable on the system.\n\n :return: None\n '
if (shutil.which('sushi') is None):
raise FileNotFoundError('Could not detect fsh sushi on the system. Install via "npm install -g fsh-sushi".') | def assert_sushi_installed() -> None:
'\n Assert that FSH Sushi is an executable on the system.\n\n :return: None\n '
if (shutil.which('sushi') is None):
raise FileNotFoundError('Could not detect fsh sushi on the system. Install via "npm install -g fsh-sushi".')<|docstring|>Assert that FSH Sush... |
02f3185e90547d0afda78f34a789c87edbfe9450e3f880c8c72e23e5df4120cf | def run_sushi(path: str) -> None:
'\n Run SUSHI to convert FSH files.\n\n :param path: Path to run SUSHI in\n :return: None\n '
assert_sushi_installed()
run_command(f'sushi {path}') | Run SUSHI to convert FSH files.
:param path: Path to run SUSHI in
:return: None | fsh_validator/fsh_validator.py | run_sushi | glichtner/fsh-validator | 0 | python | def run_sushi(path: str) -> None:
'\n Run SUSHI to convert FSH files.\n\n :param path: Path to run SUSHI in\n :return: None\n '
assert_sushi_installed()
run_command(f'sushi {path}') | def run_sushi(path: str) -> None:
'\n Run SUSHI to convert FSH files.\n\n :param path: Path to run SUSHI in\n :return: None\n '
assert_sushi_installed()
run_command(f'sushi {path}')<|docstring|>Run SUSHI to convert FSH files.
:param path: Path to run SUSHI in
:return: None<|endoftext|> |
dcfff34591110f80eb83142bf6b215ef109ad26ac74f3f2322941918e2e9093c | def __init__(self, msg: str='Command execution not successful - see command output for more information', *args):
'\n Shell command not successfully executed.\n\n :param msg: Message to display\n :param args: Other positional arguments for BaseException\n :param kwargs: Other keyword arg... | Shell command not successfully executed.
:param msg: Message to display
:param args: Other positional arguments for BaseException
:param kwargs: Other keyword arguments for BaseException | fsh_validator/fsh_validator.py | __init__ | glichtner/fsh-validator | 0 | python | def __init__(self, msg: str='Command execution not successful - see command output for more information', *args):
'\n Shell command not successfully executed.\n\n :param msg: Message to display\n :param args: Other positional arguments for BaseException\n :param kwargs: Other keyword arg... | def __init__(self, msg: str='Command execution not successful - see command output for more information', *args):
'\n Shell command not successfully executed.\n\n :param msg: Message to display\n :param args: Other positional arguments for BaseException\n :param kwargs: Other keyword arg... |
72208b4f6abcf0c1984eeeca9d02300e69a705ec9949073f0f5cd4bbebfde27c | def __init__(self, output: Optional[List[str]]=None, status: Status=Status.NOT_RUN, errors: Optional[List[str]]=None, warnings: Optional[List[str]]=None, profile: str='', instance: str=''):
'\n Status information of FHIR Validator run.\n\n :param output: Full validator output\n :param status: s... | Status information of FHIR Validator run.
:param output: Full validator output
:param status: status string
:param errors: list of errors during parsing
:param warnings: list of warnings during parsing
:param profile: name of profile against which validation was performed
:param instance: name of instance that was val... | fsh_validator/fsh_validator.py | __init__ | glichtner/fsh-validator | 0 | python | def __init__(self, output: Optional[List[str]]=None, status: Status=Status.NOT_RUN, errors: Optional[List[str]]=None, warnings: Optional[List[str]]=None, profile: str=, instance: str=):
'\n Status information of FHIR Validator run.\n\n :param output: Full validator output\n :param status: statu... | def __init__(self, output: Optional[List[str]]=None, status: Status=Status.NOT_RUN, errors: Optional[List[str]]=None, warnings: Optional[List[str]]=None, profile: str=, instance: str=):
'\n Status information of FHIR Validator run.\n\n :param output: Full validator output\n :param status: statu... |
b9e125b86c5e096de443f9ca0e441744c36b1514d7d9bd6fcd0a65f4185ba431 | def parse(self, output: List[str]) -> 'ValidatorStatus':
'\n Parse FHIR Validator output.\n\n :param output: Output of a validator run\n :return: None\n '
pattern_status = re.compile('(?P<status>\\*FAILURE\\*|Success): (?P<n_errors>\\d+) errors, (?P<n_warnings>\\d+) warnings, (?P<n_n... | Parse FHIR Validator output.
:param output: Output of a validator run
:return: None | fsh_validator/fsh_validator.py | parse | glichtner/fsh-validator | 0 | python | def parse(self, output: List[str]) -> 'ValidatorStatus':
'\n Parse FHIR Validator output.\n\n :param output: Output of a validator run\n :return: None\n '
pattern_status = re.compile('(?P<status>\\*FAILURE\\*|Success): (?P<n_errors>\\d+) errors, (?P<n_warnings>\\d+) warnings, (?P<n_n... | def parse(self, output: List[str]) -> 'ValidatorStatus':
'\n Parse FHIR Validator output.\n\n :param output: Output of a validator run\n :return: None\n '
pattern_status = re.compile('(?P<status>\\*FAILURE\\*|Success): (?P<n_errors>\\d+) errors, (?P<n_warnings>\\d+) warnings, (?P<n_n... |
08aa3a925e91caec233a728cb875f5948fb6b337e4b21697015e4cabb4318248 | def pretty_print(self, with_header: bool=False) -> None:
'\n Format and print the parsed output of fhir java validator to console.\n\n :param with_header: If true, print a header with information about the profile being validated\n :return: None\n '
if with_header:
print_box(... | Format and print the parsed output of fhir java validator to console.
:param with_header: If true, print a header with information about the profile being validated
:return: None | fsh_validator/fsh_validator.py | pretty_print | glichtner/fsh-validator | 0 | python | def pretty_print(self, with_header: bool=False) -> None:
'\n Format and print the parsed output of fhir java validator to console.\n\n :param with_header: If true, print a header with information about the profile being validated\n :return: None\n '
if with_header:
print_box(... | def pretty_print(self, with_header: bool=False) -> None:
'\n Format and print the parsed output of fhir java validator to console.\n\n :param with_header: If true, print a header with information about the profile being validated\n :return: None\n '
if with_header:
print_box(... |
36860a8c47e2a73cfa85c6cb1e4675cc58774182105fa6838e5469282927aec8 | def failed(self):
'\n Check if the validation run failed.\n\n :return: True if the validation run failed, False otherwise\n '
return (self.status == ValidatorStatus.Status.FAILURE) | Check if the validation run failed.
:return: True if the validation run failed, False otherwise | fsh_validator/fsh_validator.py | failed | glichtner/fsh-validator | 0 | python | def failed(self):
'\n Check if the validation run failed.\n\n :return: True if the validation run failed, False otherwise\n '
return (self.status == ValidatorStatus.Status.FAILURE) | def failed(self):
'\n Check if the validation run failed.\n\n :return: True if the validation run failed, False otherwise\n '
return (self.status == ValidatorStatus.Status.FAILURE)<|docstring|>Check if the validation run failed.
:return: True if the validation run failed, False otherwise<|... |
95b80a5c50a528168a220b54744ee6de7efa434711f9191e6dd16c659ee8c39d | def to_frame(self) -> pd.DataFrame:
'\n Get status as pandas DataFrame.\n\n :return: Status as DataFrame\n '
return pd.DataFrame(dict(status=self.status, n_errors=self.n_errors, n_warnings=self.n_warnings, n_notes=self.n_notes, instance=self.instance, profile=self.profile), index=[0]) | Get status as pandas DataFrame.
:return: Status as DataFrame | fsh_validator/fsh_validator.py | to_frame | glichtner/fsh-validator | 0 | python | def to_frame(self) -> pd.DataFrame:
'\n Get status as pandas DataFrame.\n\n :return: Status as DataFrame\n '
return pd.DataFrame(dict(status=self.status, n_errors=self.n_errors, n_warnings=self.n_warnings, n_notes=self.n_notes, instance=self.instance, profile=self.profile), index=[0]) | def to_frame(self) -> pd.DataFrame:
'\n Get status as pandas DataFrame.\n\n :return: Status as DataFrame\n '
return pd.DataFrame(dict(status=self.status, n_errors=self.n_errors, n_warnings=self.n_warnings, n_notes=self.n_notes, instance=self.instance, profile=self.profile), index=[0])<|docs... |
e6013c667bc98fee4a00e52d71fc4a1d306ba42388478e5c0897b763abd39df8 | def validate(ResultDirectory, DataFile, ValidationRange, CorrectThreshold, DataResolution, num_workers, visualizeErrors, expressedPoints=None, considerUnaccountedFor=True):
' Main script for cell phenotype validation. '
bdir = (lambda f: os.path.join(ResultDirectory, f))
if (expressedPoints is None):
... | Main script for cell phenotype validation. | clarity/CellTypeDetection/phenotypeValidation.py | validate | wjguan/phenocell | 0 | python | def validate(ResultDirectory, DataFile, ValidationRange, CorrectThreshold, DataResolution, num_workers, visualizeErrors, expressedPoints=None, considerUnaccountedFor=True):
' '
bdir = (lambda f: os.path.join(ResultDirectory, f))
if (expressedPoints is None):
expressionVector = loadPointsInRange(bdi... | def validate(ResultDirectory, DataFile, ValidationRange, CorrectThreshold, DataResolution, num_workers, visualizeErrors, expressedPoints=None, considerUnaccountedFor=True):
' '
bdir = (lambda f: os.path.join(ResultDirectory, f))
if (expressedPoints is None):
expressionVector = loadPointsInRange(bdi... |
ae97d9d9d1bbc0991cc4546938c205bad13f43b1eab5d006aad350dec30581f5 | @classmethod
def strip(cls, rowreader, rowwriter):
'\n Trim leading and trailing spaces from every field of delimited\n text.\n\n rowreader is an interator that provides a list or other\n interable of strings from each iteration (like\n csv.reader).\n\n rowwriter is an obje... | Trim leading and trailing spaces from every field of delimited
text.
rowreader is an interator that provides a list or other
interable of strings from each iteration (like
csv.reader).
rowwriter is an object with a write() method that accepts a
single string. | tabletext/fieldstrip.py | strip | iegorman/py-tabletext | 0 | python | @classmethod
def strip(cls, rowreader, rowwriter):
'\n Trim leading and trailing spaces from every field of delimited\n text.\n\n rowreader is an interator that provides a list or other\n interable of strings from each iteration (like\n csv.reader).\n\n rowwriter is an obje... | @classmethod
def strip(cls, rowreader, rowwriter):
'\n Trim leading and trailing spaces from every field of delimited\n text.\n\n rowreader is an interator that provides a list or other\n interable of strings from each iteration (like\n csv.reader).\n\n rowwriter is an obje... |
c276947003bf46bba3fb05a8545e825857d9dc955d164bf5e4f8372f3b5ed96c | def __init__(self, embedding_size: int=100, scoring_fct_norm: int=2, epochs: int=100, batch_size: int=(2 ** 10), training_loop: Union[(str, Type[TrainingLoop])]='Stochastic Local Closed World Assumption', random_state: int=42, enable_cache: bool=False):
'Create new PyKeen TransE model.\n \n Details\n ... | Create new PyKeen TransE model.
Details
-------------------------
This is a wrapper of the TransE implementation from the
PyKeen library. Please refer to the PyKeen library documentation
for details and posssible errors regarding this model.
Parameters
-------------------------
embedding_size: int = 100
The dimen... | embiggen/embedders/pykeen_embedders/transe.py | __init__ | monarch-initiative/N2V | 2 | python | def __init__(self, embedding_size: int=100, scoring_fct_norm: int=2, epochs: int=100, batch_size: int=(2 ** 10), training_loop: Union[(str, Type[TrainingLoop])]='Stochastic Local Closed World Assumption', random_state: int=42, enable_cache: bool=False):
'Create new PyKeen TransE model.\n \n Details\n ... | def __init__(self, embedding_size: int=100, scoring_fct_norm: int=2, epochs: int=100, batch_size: int=(2 ** 10), training_loop: Union[(str, Type[TrainingLoop])]='Stochastic Local Closed World Assumption', random_state: int=42, enable_cache: bool=False):
'Create new PyKeen TransE model.\n \n Details\n ... |
c1b3ab36bc7d850f8f549055264659291265b41e2192a1f7c08c17403dbabb73 | @staticmethod
def smoke_test_parameters() -> Dict[(str, Any)]:
'Returns parameters for smoke test.'
return dict(**EntityRelationEmbeddingModelPyKeen.smoke_test_parameters(), scoring_fct_norm=1) | Returns parameters for smoke test. | embiggen/embedders/pykeen_embedders/transe.py | smoke_test_parameters | monarch-initiative/N2V | 2 | python | @staticmethod
def smoke_test_parameters() -> Dict[(str, Any)]:
return dict(**EntityRelationEmbeddingModelPyKeen.smoke_test_parameters(), scoring_fct_norm=1) | @staticmethod
def smoke_test_parameters() -> Dict[(str, Any)]:
return dict(**EntityRelationEmbeddingModelPyKeen.smoke_test_parameters(), scoring_fct_norm=1)<|docstring|>Returns parameters for smoke test.<|endoftext|> |
9e389851a82afe09adf65518d5130e00935c33476ca1662ac39dbec1347ab92f | @staticmethod
def model_name() -> str:
'Return name of the model.'
return 'TransE' | Return name of the model. | embiggen/embedders/pykeen_embedders/transe.py | model_name | monarch-initiative/N2V | 2 | python | @staticmethod
def model_name() -> str:
return 'TransE' | @staticmethod
def model_name() -> str:
return 'TransE'<|docstring|>Return name of the model.<|endoftext|> |
09f37d8481826bf067604995af161c6c3d3de88d7fa7013c3a7c26464d08113f | def _build_model(self, triples_factory: CoreTriplesFactory) -> TransE:
'Build new TransE model for embedding.\n\n Parameters\n ------------------\n graph: Graph\n The graph to build the model for.\n '
return TransE(triples_factory=triples_factory, embedding_dim=self._embed... | Build new TransE model for embedding.
Parameters
------------------
graph: Graph
The graph to build the model for. | embiggen/embedders/pykeen_embedders/transe.py | _build_model | monarch-initiative/N2V | 2 | python | def _build_model(self, triples_factory: CoreTriplesFactory) -> TransE:
'Build new TransE model for embedding.\n\n Parameters\n ------------------\n graph: Graph\n The graph to build the model for.\n '
return TransE(triples_factory=triples_factory, embedding_dim=self._embed... | def _build_model(self, triples_factory: CoreTriplesFactory) -> TransE:
'Build new TransE model for embedding.\n\n Parameters\n ------------------\n graph: Graph\n The graph to build the model for.\n '
return TransE(triples_factory=triples_factory, embedding_dim=self._embed... |
a657b87b8ce30d0f2ff4fcb3b5ebdfe26cd0480cf45ced9041e83fa402e6b848 | def pattern_registry(pattern_type):
'The class decorator used to register all Algorithm subclasses.\n\n Args:\n cls (class): The class of register.\n pattern_type (str): The pattern registration name\n\n Returns:\n cls: The class of register.\n '
def decorator_pattern(cls):
... | The class decorator used to register all Algorithm subclasses.
Args:
cls (class): The class of register.
pattern_type (str): The pattern registration name
Returns:
cls: The class of register. | engine/compile/sub_graph/pattern.py | pattern_registry | intel/neural-compressor | 172 | python | def pattern_registry(pattern_type):
'The class decorator used to register all Algorithm subclasses.\n\n Args:\n cls (class): The class of register.\n pattern_type (str): The pattern registration name\n\n Returns:\n cls: The class of register.\n '
def decorator_pattern(cls):
... | def pattern_registry(pattern_type):
'The class decorator used to register all Algorithm subclasses.\n\n Args:\n cls (class): The class of register.\n pattern_type (str): The pattern registration name\n\n Returns:\n cls: The class of register.\n '
def decorator_pattern(cls):
... |
44a7fe51d2532041a0ef6a79963a65a177a428a53138967078129d1ea049e320 | @classmethod
def db_table_name(cls):
'database table name'
return cls._meta.db_table | database table name | backend/db_comments/model_mixins.py | db_table_name | WadeBarnes/tfrs | 18 | python | @classmethod
def db_table_name(cls):
return cls._meta.db_table | @classmethod
def db_table_name(cls):
return cls._meta.db_table<|docstring|>database table name<|endoftext|> |
56abee0714df3c85d1b822f646c77234b9b7f950c114b9caaf915fa93abf0997 | @classmethod
def db_table_comment_or_name(cls):
'database table comment (default to name if unset)'
return (cls.db_table_comment or cls.__name__) | database table comment (default to name if unset) | backend/db_comments/model_mixins.py | db_table_comment_or_name | WadeBarnes/tfrs | 18 | python | @classmethod
def db_table_comment_or_name(cls):
return (cls.db_table_comment or cls.__name__) | @classmethod
def db_table_comment_or_name(cls):
return (cls.db_table_comment or cls.__name__)<|docstring|>database table comment (default to name if unset)<|endoftext|> |
f60c9cc2c2bd86de8ea673ecd20ca8bc5c69d033b85d6070131791140b6534db | @classmethod
def db_column_comments(cls):
'database table column comments, including supplemental overrides'
column_comments = {}
for field in cls._meta.fields:
if hasattr(field, 'db_comment'):
column_comments[field.column] = field.db_comment
inspection_list = [cls]
visited = []
... | database table column comments, including supplemental overrides | backend/db_comments/model_mixins.py | db_column_comments | WadeBarnes/tfrs | 18 | python | @classmethod
def db_column_comments(cls):
column_comments = {}
for field in cls._meta.fields:
if hasattr(field, 'db_comment'):
column_comments[field.column] = field.db_comment
inspection_list = [cls]
visited = []
while inspection_list:
current = inspection_list.pop()... | @classmethod
def db_column_comments(cls):
column_comments = {}
for field in cls._meta.fields:
if hasattr(field, 'db_comment'):
column_comments[field.column] = field.db_comment
inspection_list = [cls]
visited = []
while inspection_list:
current = inspection_list.pop()... |
1bcb2118c3de981a2ec20a0d8fc80d65c85aa0bb96cca958771b44f54da75a16 | def non_max_suppression(self, prediction, num_classes, input_shape, image_shape, letterbox_image, conf_thres=0.5, nms_thres=0.4):
'原图上的box,首先利用conf_thres进行第一轮筛选,再进行非极大值抑制。当然conf_thres=0.5, nms_thres=0.4\n 都是默认值,是可以被修改的。nms_thres的值越小,nms越严格'
box_corner = prediction.new(prediction.shape)
box_corner[(:,... | 原图上的box,首先利用conf_thres进行第一轮筛选,再进行非极大值抑制。当然conf_thres=0.5, nms_thres=0.4
都是默认值,是可以被修改的。nms_thres的值越小,nms越严格 | utils/utils_bbox.py | non_max_suppression | ustber002/yolov3-pytorch | 1 | python | def non_max_suppression(self, prediction, num_classes, input_shape, image_shape, letterbox_image, conf_thres=0.5, nms_thres=0.4):
'原图上的box,首先利用conf_thres进行第一轮筛选,再进行非极大值抑制。当然conf_thres=0.5, nms_thres=0.4\n 都是默认值,是可以被修改的。nms_thres的值越小,nms越严格'
box_corner = prediction.new(prediction.shape)
box_corner[(:,... | def non_max_suppression(self, prediction, num_classes, input_shape, image_shape, letterbox_image, conf_thres=0.5, nms_thres=0.4):
'原图上的box,首先利用conf_thres进行第一轮筛选,再进行非极大值抑制。当然conf_thres=0.5, nms_thres=0.4\n 都是默认值,是可以被修改的。nms_thres的值越小,nms越严格'
box_corner = prediction.new(prediction.shape)
box_corner[(:,... |
8da9188186a9375efa7c353f5c5d0502fe4ea736388c74f4be2381307b718c60 | def read_ref(ref: str, kind='branch') -> str:
'\n get sha1 of commit that a ref (branch/tag) is pointing to e.g "master"\n '
ref_kind = ('heads' if (kind == 'branch') else 'tags')
with open(f'.git/refs/{ref_kind}/{ref}') as f:
return f.read().strip() | get sha1 of commit that a ref (branch/tag) is pointing to e.g "master" | src/git.py | read_ref | nojvek/pygit | 0 | python | def read_ref(ref: str, kind='branch') -> str:
'\n \n '
ref_kind = ('heads' if (kind == 'branch') else 'tags')
with open(f'.git/refs/{ref_kind}/{ref}') as f:
return f.read().strip() | def read_ref(ref: str, kind='branch') -> str:
'\n \n '
ref_kind = ('heads' if (kind == 'branch') else 'tags')
with open(f'.git/refs/{ref_kind}/{ref}') as f:
return f.read().strip()<|docstring|>get sha1 of commit that a ref (branch/tag) is pointing to e.g "master"<|endoftext|> |
38a62c2b5aea68db97348d1eea37d677a058d943415b5d944071b1b9b5eacc12 | def pack_object_data(obj_type: str, data: bytes) -> (str, bytes):
'\n Return a tuple of (sha1(type + len + data), gzipped_data)\n '
data_w_header = b'\x00'.join([f'{obj_type} {len(data)}', data])
sha1 = hashlib.sha1(data_w_header).hexdigest()
gzipped_data = zlib.compress(data_w_header)
return ... | Return a tuple of (sha1(type + len + data), gzipped_data) | src/git.py | pack_object_data | nojvek/pygit | 0 | python | def pack_object_data(obj_type: str, data: bytes) -> (str, bytes):
'\n \n '
data_w_header = b'\x00'.join([f'{obj_type} {len(data)}', data])
sha1 = hashlib.sha1(data_w_header).hexdigest()
gzipped_data = zlib.compress(data_w_header)
return (sha1, gzipped_data) | def pack_object_data(obj_type: str, data: bytes) -> (str, bytes):
'\n \n '
data_w_header = b'\x00'.join([f'{obj_type} {len(data)}', data])
sha1 = hashlib.sha1(data_w_header).hexdigest()
gzipped_data = zlib.compress(data_w_header)
return (sha1, gzipped_data)<|docstring|>Return a tuple of (sha1(... |
22e3d4f4009bf650336f1333828f2e0f5eec51d1e031fb2535e5ee7a0f385de2 | def get_connected_objects(sha1: str, object_graph: Dict=None) -> Dict:
'\n Starting from a sha1 of an object e.g commit/tree\n Return an object_graph\n where object_graph is a dictionary of {sha1: unpacked_object}\n '
if (object_graph is None):
object_graph = {}
obj = read_git_object(sha... | Starting from a sha1 of an object e.g commit/tree
Return an object_graph
where object_graph is a dictionary of {sha1: unpacked_object} | src/git.py | get_connected_objects | nojvek/pygit | 0 | python | def get_connected_objects(sha1: str, object_graph: Dict=None) -> Dict:
'\n Starting from a sha1 of an object e.g commit/tree\n Return an object_graph\n where object_graph is a dictionary of {sha1: unpacked_object}\n '
if (object_graph is None):
object_graph = {}
obj = read_git_object(sha... | def get_connected_objects(sha1: str, object_graph: Dict=None) -> Dict:
'\n Starting from a sha1 of an object e.g commit/tree\n Return an object_graph\n where object_graph is a dictionary of {sha1: unpacked_object}\n '
if (object_graph is None):
object_graph = {}
obj = read_git_object(sha... |
43b075b80ea5add3999e1c03ff42720bc9d3a5ed7438257ce9b31299028bc07f | def make_wide(formatter, w=120, h=36):
'Return a wider HelpFormatter, if possible.'
try:
kwargs = {'width': w, 'max_help_position': h}
formatter(None, **kwargs)
return (lambda prog: formatter(prog, **kwargs))
except TypeError:
import warnings
warnings.warn('argparse h... | Return a wider HelpFormatter, if possible. | haven/haven_wizard.py | make_wide | mariatippler/haven-ai | 0 | python | def make_wide(formatter, w=120, h=36):
try:
kwargs = {'width': w, 'max_help_position': h}
formatter(None, **kwargs)
return (lambda prog: formatter(prog, **kwargs))
except TypeError:
import warnings
warnings.warn('argparse help formatter failed, falling back.')
... | def make_wide(formatter, w=120, h=36):
try:
kwargs = {'width': w, 'max_help_position': h}
formatter(None, **kwargs)
return (lambda prog: formatter(prog, **kwargs))
except TypeError:
import warnings
warnings.warn('argparse help formatter failed, falling back.')
... |
9508b4bb132899b9d7ce7acaa760186e90afe25024bd012b66bc9a140c2b4301 | def __init__(self, interval=1):
'\n inteval is in seconds\n '
super(Service, self).__init__()
self.interval = (interval * 1000)
self.periodicalCb = None | inteval is in seconds | service.py | __init__ | liangsun/firstblog | 4 | python | def __init__(self, interval=1):
'\n \n '
super(Service, self).__init__()
self.interval = (interval * 1000)
self.periodicalCb = None | def __init__(self, interval=1):
'\n \n '
super(Service, self).__init__()
self.interval = (interval * 1000)
self.periodicalCb = None<|docstring|>inteval is in seconds<|endoftext|> |
a99a5aa73feeeabddc8e3a4078c234d7f06eb84002485b94140089bbae6cccf8 | def main(self):
'\n Subclass this method\n '
logging.error(('Subclass main method... %s' % time.clock())) | Subclass this method | service.py | main | liangsun/firstblog | 4 | python | def main(self):
'\n \n '
logging.error(('Subclass main method... %s' % time.clock())) | def main(self):
'\n \n '
logging.error(('Subclass main method... %s' % time.clock()))<|docstring|>Subclass this method<|endoftext|> |
65919d9497660ee3681985d1ca035305a7bb16ba2016d2c915823a1c62863659 | def begin(self):
'!\n @brief initialization the i2c.\n @return returns the initialization status\n @retval True Initialization succeeded\n @retval False Initialization failed\n '
if (not self.scan()):
return False
else:
self.soft_reset()
se... | !
@brief initialization the i2c.
@return returns the initialization status
@retval True Initialization succeeded
@retval False Initialization failed | python/raspberrypi/DFRobot_BMX160.py | begin | DFRobot/DFRobot_BMX160 | 9 | python | def begin(self):
'!\n @brief initialization the i2c.\n @return returns the initialization status\n @retval True Initialization succeeded\n @retval False Initialization failed\n '
if (not self.scan()):
return False
else:
self.soft_reset()
se... | def begin(self):
'!\n @brief initialization the i2c.\n @return returns the initialization status\n @retval True Initialization succeeded\n @retval False Initialization failed\n '
if (not self.scan()):
return False
else:
self.soft_reset()
se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.