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 V1alpha1CronWorkflowSpec. # noqa: E501\n :rtype: str\n ' return self._timezone
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 V1alpha1CronWorkflowSpec. # noqa: E501\n :rtype: str\n ' return self._timezone
@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 V1alpha1CronWorkflowSpec. # noqa: E501\n :rtype: str\n ' return self._timezone<|docstring|>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<|endoftext|>
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 V1alpha1CronWorkflowSpec. # noqa: E501\n :type: str\n ' self._timezone = timezone
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 V1alpha1CronWorkflowSpec. # noqa: E501\n :type: str\n ' self._timezone = timezone
@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 V1alpha1CronWorkflowSpec. # noqa: E501\n :type: str\n ' self._timezone = timezone<|docstring|>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<|endoftext|>
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: V1ObjectMeta\n ' return self._workflow_metadata
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: V1ObjectMeta\n ' return self._workflow_metadata
@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: V1ObjectMeta\n ' return self._workflow_metadata<|docstring|>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<|endoftext|>
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 V1alpha1CronWorkflowSpec. # noqa: E501\n :type: V1ObjectMeta\n ' self._workflow_metadata = workflow_metadata
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 V1alpha1CronWorkflowSpec. # noqa: E501\n :type: V1ObjectMeta\n ' self._workflow_metadata = workflow_metadata
@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 V1alpha1CronWorkflowSpec. # noqa: E501\n :type: V1ObjectMeta\n ' self._workflow_metadata = workflow_metadata<|docstring|>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<|endoftext|>
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 ' return self._workflow_spec
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 ' return self._workflow_spec
@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 ' return self._workflow_spec<|docstring|>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<|endoftext|>
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: V1alpha1WorkflowSpec\n ' if (workflow_spec is None): raise ValueError('Invalid value for `workflow_spec`, must not be `None`') self._workflow_spec = workflow_spec
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: V1alpha1WorkflowSpec\n ' if (workflow_spec is None): raise ValueError('Invalid value for `workflow_spec`, must not be `None`') self._workflow_spec = workflow_spec
@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: V1alpha1WorkflowSpec\n ' if (workflow_spec is None): raise ValueError('Invalid value for `workflow_spec`, must not be `None`') self._workflow_spec = workflow_spec<|docstring|>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<|endoftext|>
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)) elif hasattr(value, 'to_dict'): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map((lambda item: ((item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item)), value.items())) else: result[attr] = value if issubclass(V1alpha1CronWorkflowSpec, dict): for (key, value) in self.items(): result[key] = value return result
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'): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map((lambda item: ((item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item)), value.items())) else: result[attr] = value if issubclass(V1alpha1CronWorkflowSpec, dict): for (key, value) in self.items(): result[key] = value return result
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'): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map((lambda item: ((item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item)), value.items())) else: result[attr] = value if issubclass(V1alpha1CronWorkflowSpec, dict): for (key, value) in self.items(): result[key] = value return result<|docstring|>Returns the model properties as a dict<|endoftext|>
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://github.com/dwavesystems/homebase>`_.\n\n Args:\n app_name (str, optional): The application name.\n Default is given by :obj:`.APPNAME`.\n app_author (str, optional): The application author. Default\n is given by :obj:`.APPAUTHOR`.\n filename (str, optional): The name of the database file.\n Default is given by :obj:`DATABASENAME`.\n\n Returns:\n str: The full path to the file that can be used as a cache.\n\n Notes:\n Creates the directory if it does not already exist.\n\n If run inside of a virtual environment, the cache will be stored\n in `/path/to/virtualenv/data/app_name`\n\n ' user_data_dir = homebase.user_data_dir(app_name=app_name, app_author=app_author, create=True) return os.path.join(user_data_dir, filename)
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. Default is given by :obj:`.APPNAME`. app_author (str, optional): The application author. Default is given by :obj:`.APPAUTHOR`. filename (str, optional): The name of the database file. Default is given by :obj:`DATABASENAME`. Returns: str: The full path to the file that can be used as a cache. Notes: Creates the directory if it does not already exist. If run inside of a virtual environment, the cache will be stored in `/path/to/virtualenv/data/app_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://github.com/dwavesystems/homebase>`_.\n\n Args:\n app_name (str, optional): The application name.\n Default is given by :obj:`.APPNAME`.\n app_author (str, optional): The application author. Default\n is given by :obj:`.APPAUTHOR`.\n filename (str, optional): The name of the database file.\n Default is given by :obj:`DATABASENAME`.\n\n Returns:\n str: The full path to the file that can be used as a cache.\n\n Notes:\n Creates the directory if it does not already exist.\n\n If run inside of a virtual environment, the cache will be stored\n in `/path/to/virtualenv/data/app_name`\n\n ' user_data_dir = homebase.user_data_dir(app_name=app_name, app_author=app_author, create=True) return os.path.join(user_data_dir, filename)
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://github.com/dwavesystems/homebase>`_.\n\n Args:\n app_name (str, optional): The application name.\n Default is given by :obj:`.APPNAME`.\n app_author (str, optional): The application author. Default\n is given by :obj:`.APPAUTHOR`.\n filename (str, optional): The name of the database file.\n Default is given by :obj:`DATABASENAME`.\n\n Returns:\n str: The full path to the file that can be used as a cache.\n\n Notes:\n Creates the directory if it does not already exist.\n\n If run inside of a virtual environment, the cache will be stored\n in `/path/to/virtualenv/data/app_name`\n\n ' user_data_dir = homebase.user_data_dir(app_name=app_name, app_author=app_author, create=True) return os.path.join(user_data_dir, filename)<|docstring|>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. Default is given by :obj:`.APPNAME`. app_author (str, optional): The application author. Default is given by :obj:`.APPAUTHOR`. filename (str, optional): The name of the database file. Default is given by :obj:`DATABASENAME`. Returns: str: The full path to the file that can be used as a cache. Notes: Creates the directory if it does not already exist. If run inside of a virtual environment, the cache will be stored in `/path/to/virtualenv/data/app_name`<|endoftext|>
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 Eigenvalues stored in the eigendata zip.\n eigen_vecs: numpy array\n Eigenvectors stored in the eigendata zip.\n ' eigen_data = np.load(eigen_data_path) (eigen_vals, eigen_vecs) = (eigen_data['eigen_vals'], eigen_data['eigen_vecs']) return (eigen_vals, eigen_vecs)
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 the eigendata zip.
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 Eigenvalues stored in the eigendata zip.\n eigen_vecs: numpy array\n Eigenvectors stored in the eigendata zip.\n ' eigen_data = np.load(eigen_data_path) (eigen_vals, eigen_vecs) = (eigen_data['eigen_vals'], eigen_data['eigen_vecs']) return (eigen_vals, eigen_vecs)
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 Eigenvalues stored in the eigendata zip.\n eigen_vecs: numpy array\n Eigenvectors stored in the eigendata zip.\n ' eigen_data = np.load(eigen_data_path) (eigen_vals, eigen_vecs) = (eigen_data['eigen_vals'], eigen_data['eigen_vecs']) return (eigen_vals, eigen_vecs)<|docstring|>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 the eigendata zip.<|endoftext|>
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.add_subplot(212) ax.plot(z_scores) ax.set_xlabel('Frame') ax.set_ylabel('Signal') if save_fig: file_name = os.path.join(outdir_path, title.split(' ')[0]) plt.savefig(file_name) else: plt.show() plt.close()
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.add_subplot(212) ax.plot(z_scores) ax.set_xlabel('Frame') ax.set_ylabel('Signal') if save_fig: file_name = os.path.join(outdir_path, title.split(' ')[0]) plt.savefig(file_name) else: plt.show() plt.close()
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.add_subplot(212) ax.plot(z_scores) ax.set_xlabel('Frame') ax.set_ylabel('Signal') if save_fig: file_name = os.path.join(outdir_path, title.split(' ')[0]) plt.savefig(file_name) else: plt.show() plt.close()<|docstring|>Plots eigenvalue time-series data, and a corresponding z-score curve.<|endoftext|>
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 microscopy video.\n eigen_vals: NumPy array (NXM)\n Matrix comprised of eigenvalue vectors. \n N represents the number of frames in the\n corresponding video, and M is the number of\n mixture components.\n outdir_path: string\n Path to a directory to save the plots and anomalous\n time points.\n k: int\n The number of leading eigenvalues to display.\n window: int\n The size of the window to be used for anomaly \n detection.\n threshold: float\n Value used to determine whether a signal value\n is anomalous. \n\n Returns\n -------\n NoneType object\n ' eigen_vals_avgs = [np.mean(x) for x in eigen_vals] moving_avgs = np.empty(shape=(eigen_vals.shape[0],), dtype=np.float) moving_stds = np.empty(shape=(eigen_vals.shape[0],), dtype=np.float) z_scores = np.empty(shape=(eigen_vals.shape[0],), dtype=np.float) signals = np.empty(shape=(eigen_vals.shape[0],), dtype=np.float) moving_avgs[:window] = 0 moving_stds[:window] = 0 z_scores[:window] = 0 for i in range(window, moving_avgs.shape[0]): moving_avgs[i] = np.mean(eigen_vals_avgs[(i - window):i]) moving_stds[i] = np.std(eigen_vals_avgs[(i - window):i]) z_scores[i] = ((eigen_vals_avgs[i] - moving_avgs[i]) / moving_stds[i]) plot_title = (vid_name + ' Signals Plot') timepoint_title = (vid_name + '.txt') with open(os.path.join(outdir_path, timepoint_title), 'w+') as writer: for (i, score) in enumerate(z_scores): if (score > threshold): signals[i] = 1 writer.write((str(i) + '\n')) elif (score < (threshold * (- 1))): signals[i] = (- 1) writer.write((str(i) + '\n')) else: signals[i] = 0 plot(eigen_vals[(:, :k)], signals, plot_title, False, outdir_path)
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 corresponding video, and M is the number of mixture components. outdir_path: string Path to a directory to save the plots and anomalous time points. k: int The number of leading eigenvalues to display. window: int The size of the window to be used for anomaly detection. threshold: float Value used to determine whether a signal value is anomalous. Returns ------- NoneType object
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 microscopy video.\n eigen_vals: NumPy array (NXM)\n Matrix comprised of eigenvalue vectors. \n N represents the number of frames in the\n corresponding video, and M is the number of\n mixture components.\n outdir_path: string\n Path to a directory to save the plots and anomalous\n time points.\n k: int\n The number of leading eigenvalues to display.\n window: int\n The size of the window to be used for anomaly \n detection.\n threshold: float\n Value used to determine whether a signal value\n is anomalous. \n\n Returns\n -------\n NoneType object\n ' eigen_vals_avgs = [np.mean(x) for x in eigen_vals] moving_avgs = np.empty(shape=(eigen_vals.shape[0],), dtype=np.float) moving_stds = np.empty(shape=(eigen_vals.shape[0],), dtype=np.float) z_scores = np.empty(shape=(eigen_vals.shape[0],), dtype=np.float) signals = np.empty(shape=(eigen_vals.shape[0],), dtype=np.float) moving_avgs[:window] = 0 moving_stds[:window] = 0 z_scores[:window] = 0 for i in range(window, moving_avgs.shape[0]): moving_avgs[i] = np.mean(eigen_vals_avgs[(i - window):i]) moving_stds[i] = np.std(eigen_vals_avgs[(i - window):i]) z_scores[i] = ((eigen_vals_avgs[i] - moving_avgs[i]) / moving_stds[i]) plot_title = (vid_name + ' Signals Plot') timepoint_title = (vid_name + '.txt') with open(os.path.join(outdir_path, timepoint_title), 'w+') as writer: for (i, score) in enumerate(z_scores): if (score > threshold): signals[i] = 1 writer.write((str(i) + '\n')) elif (score < (threshold * (- 1))): signals[i] = (- 1) writer.write((str(i) + '\n')) else: signals[i] = 0 plot(eigen_vals[(:, :k)], signals, plot_title, False, outdir_path)
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 microscopy video.\n eigen_vals: NumPy array (NXM)\n Matrix comprised of eigenvalue vectors. \n N represents the number of frames in the\n corresponding video, and M is the number of\n mixture components.\n outdir_path: string\n Path to a directory to save the plots and anomalous\n time points.\n k: int\n The number of leading eigenvalues to display.\n window: int\n The size of the window to be used for anomaly \n detection.\n threshold: float\n Value used to determine whether a signal value\n is anomalous. \n\n Returns\n -------\n NoneType object\n ' eigen_vals_avgs = [np.mean(x) for x in eigen_vals] moving_avgs = np.empty(shape=(eigen_vals.shape[0],), dtype=np.float) moving_stds = np.empty(shape=(eigen_vals.shape[0],), dtype=np.float) z_scores = np.empty(shape=(eigen_vals.shape[0],), dtype=np.float) signals = np.empty(shape=(eigen_vals.shape[0],), dtype=np.float) moving_avgs[:window] = 0 moving_stds[:window] = 0 z_scores[:window] = 0 for i in range(window, moving_avgs.shape[0]): moving_avgs[i] = np.mean(eigen_vals_avgs[(i - window):i]) moving_stds[i] = np.std(eigen_vals_avgs[(i - window):i]) z_scores[i] = ((eigen_vals_avgs[i] - moving_avgs[i]) / moving_stds[i]) plot_title = (vid_name + ' Signals Plot') timepoint_title = (vid_name + '.txt') with open(os.path.join(outdir_path, timepoint_title), 'w+') as writer: for (i, score) in enumerate(z_scores): if (score > threshold): signals[i] = 1 writer.write((str(i) + '\n')) elif (score < (threshold * (- 1))): signals[i] = (- 1) writer.write((str(i) + '\n')) else: signals[i] = 0 plot(eigen_vals[(:, :k)], signals, plot_title, False, outdir_path)<|docstring|>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 corresponding video, and M is the number of mixture components. outdir_path: string Path to a directory to save the plots and anomalous time points. k: int The number of leading eigenvalues to display. window: int The size of the window to be used for anomaly detection. threshold: float Value used to determine whether a signal value is anomalous. Returns ------- NoneType object<|endoftext|>
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 detection of of eigenvalue time-series data.') parser.add_argument('-i', '--input', required=True, help='Input directory of eigendata file (.npz).') parser.add_argument('-o', '--outdir', default=os.getcwd(), help='Output directory for plots.') return vars(parser.parse_args(input_args))
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 detection of of eigenvalue time-series data.') parser.add_argument('-i', '--input', required=True, help='Input directory of eigendata file (.npz).') parser.add_argument('-o', '--outdir', default=os.getcwd(), help='Output directory for plots.') return vars(parser.parse_args(input_args))
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 detection of of eigenvalue time-series data.') parser.add_argument('-i', '--input', required=True, help='Input directory of eigendata file (.npz).') parser.add_argument('-o', '--outdir', default=os.getcwd(), help='Output directory for plots.') return vars(parser.parse_args(input_args))<|docstring|>Parses the command line arguments. Parameters ---------- input_args: list Arguments to be parsed. Returns ------- parsed_args: dict Key value pairs of arguments.<|endoftext|>
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 = Gamma.param_dict_inv()['location_inv'](loc_fit) scale_init = Gamma.param_dict_inv()['scale_inv'](scale_fit) start_values = np.array([location_init, scale_init]) return start_values
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 = Gamma.param_dict_inv()['location_inv'](loc_fit) scale_init = Gamma.param_dict_inv()['scale_inv'](scale_fit) start_values = np.array([location_init, scale_init]) return start_values
@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 = Gamma.param_dict_inv()['location_inv'](loc_fit) scale_init = Gamma.param_dict_inv()['scale_inv'](scale_fit) start_values = np.array([location_init, scale_init]) return start_values<|docstring|>Function that calculates the starting values, for each distributional parameter individually. y: np.ndarray Data from which starting values are calculated.<|endoftext|>
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 (log == False) else loglik) return loglik
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) else loglik) return loglik
@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) else loglik) return loglik<|docstring|>Density function.<|endoftext|>
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)) * weights) return grad
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|>Calculates Gradient of location parameter.<|endoftext|>
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 parameter.<|endoftext|>
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))))) grad = stabilize_derivative(grad, Gamma.stabilize) grad = ((grad * (- 1)) * weights) return grad
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, Gamma.stabilize) grad = ((grad * (- 1)) * weights) return 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, Gamma.stabilize) grad = ((grad * (- 1)) * weights) return grad<|docstring|>Calculates Gradient of scale parameter.<|endoftext|>
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 hes
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 scale parameter.<|endoftext|>
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()['scale'](predt[(:, 1)]) if (data.get_weight().size == 0): weights = np.ones_like(target, dtype=float) else: weights = data.get_weight() grad = np.zeros(shape=(len(target), Gamma.n_dist_param())) hess = np.zeros(shape=(len(target), Gamma.n_dist_param())) grad[(:, 0)] = Gamma.gradient_location(y=target, location=preds_location, scale=preds_scale, weights=weights) hess[(:, 0)] = Gamma.hessian_location(location=preds_location, scale=preds_scale, weights=weights) grad[(:, 1)] = Gamma.gradient_scale(y=target, location=preds_location, scale=preds_scale, weights=weights) hess[(:, 1)] = Gamma.hessian_scale(scale=preds_scale, weights=weights) grad = grad.flatten() hess = hess.flatten() return (grad, hess)
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=float) else: weights = data.get_weight() grad = np.zeros(shape=(len(target), Gamma.n_dist_param())) hess = np.zeros(shape=(len(target), Gamma.n_dist_param())) grad[(:, 0)] = Gamma.gradient_location(y=target, location=preds_location, scale=preds_scale, weights=weights) hess[(:, 0)] = Gamma.hessian_location(location=preds_location, scale=preds_scale, weights=weights) grad[(:, 1)] = Gamma.gradient_scale(y=target, location=preds_location, scale=preds_scale, weights=weights) hess[(:, 1)] = Gamma.hessian_scale(scale=preds_scale, weights=weights) grad = grad.flatten() hess = hess.flatten() return (grad, hess)
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=float) else: weights = data.get_weight() grad = np.zeros(shape=(len(target), Gamma.n_dist_param())) hess = np.zeros(shape=(len(target), Gamma.n_dist_param())) grad[(:, 0)] = Gamma.gradient_location(y=target, location=preds_location, scale=preds_scale, weights=weights) hess[(:, 0)] = Gamma.hessian_location(location=preds_location, scale=preds_scale, weights=weights) grad[(:, 1)] = Gamma.gradient_scale(y=target, location=preds_location, scale=preds_scale, weights=weights) hess[(:, 1)] = Gamma.hessian_scale(scale=preds_scale, weights=weights) grad = grad.flatten() hess = hess.flatten() return (grad, hess)<|docstring|>A customized objective function to train each distributional parameter using custom gradient and hessian.<|endoftext|>
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[(:, 1)]) nll = (- np.nansum(Gamma.dGamma(y=target, location=preds_location, scale=preds_scale, log=True))) return ('NegLogLikelihood', nll)
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, log=True))) return ('NegLogLikelihood', nll)
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, log=True))) return ('NegLogLikelihood', nll)<|docstring|>A customized evaluation metric that evaluates the predictions using the negative log-likelihood.<|endoftext|>
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 draw from predicted response distribution.\n seed: int\n Manual seed.\n Returns\n -------\n pd.DataFrame with n_samples drawn from predicted response distribution.\n\n ' pred_dist_list = [] for i in range(pred_params.shape[0]): pred_dist_list.append(Gamma.rGamma(n=n_samples, location=np.array([pred_params.loc[(i, 'location')]]), scale=np.array([pred_params.loc[(i, 'scale')]]))) pred_dist = pd.DataFrame(pred_dist_list) return pred_dist
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 predicted response distribution.
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 draw from predicted response distribution.\n seed: int\n Manual seed.\n Returns\n -------\n pd.DataFrame with n_samples drawn from predicted response distribution.\n\n ' pred_dist_list = [] for i in range(pred_params.shape[0]): pred_dist_list.append(Gamma.rGamma(n=n_samples, location=np.array([pred_params.loc[(i, 'location')]]), scale=np.array([pred_params.loc[(i, 'scale')]]))) pred_dist = pd.DataFrame(pred_dist_list) return pred_dist
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 draw from predicted response distribution.\n seed: int\n Manual seed.\n Returns\n -------\n pd.DataFrame with n_samples drawn from predicted response distribution.\n\n ' pred_dist_list = [] for i in range(pred_params.shape[0]): pred_dist_list.append(Gamma.rGamma(n=n_samples, location=np.array([pred_params.loc[(i, 'location')]]), scale=np.array([pred_params.loc[(i, 'scale')]]))) pred_dist = pd.DataFrame(pred_dist_list) return pred_dist<|docstring|>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 predicted response distribution.<|endoftext|>
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 parameters.\n\n Returns\n -------\n pd.DataFrame with calculated quantiles.\n\n ' pred_quantiles_list = [] for i in range(len(quantiles)): pred_quantiles_list.append(Gamma.qGamma(p=quantiles[i], location=pred_params['location'], scale=pred_params['scale'])) pred_quantiles = pd.DataFrame(pred_quantiles_list).T return pred_quantiles
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 parameters.\n\n Returns\n -------\n pd.DataFrame with calculated quantiles.\n\n ' pred_quantiles_list = [] for i in range(len(quantiles)): pred_quantiles_list.append(Gamma.qGamma(p=quantiles[i], location=pred_params['location'], scale=pred_params['scale'])) pred_quantiles = pd.DataFrame(pred_quantiles_list).T return pred_quantiles
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 parameters.\n\n Returns\n -------\n pd.DataFrame with calculated quantiles.\n\n ' pred_quantiles_list = [] for i in range(len(quantiles)): pred_quantiles_list.append(Gamma.qGamma(p=quantiles[i], location=pred_params['location'], scale=pred_params['scale'])) pred_quantiles = pd.DataFrame(pred_quantiles_list).T return pred_quantiles<|docstring|>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.<|endoftext|>
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 computed_hash.startswith(('0' * Blockchain.DIFFICULTY))): block.nonce += 1 computed_hash = block.compute_hash() return computed_hash
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 computed_hash.startswith(('0' * Blockchain.DIFFICULTY))): block.nonce += 1 computed_hash = block.compute_hash() return computed_hash
@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 computed_hash.startswith(('0' * Blockchain.DIFFICULTY))): block.nonce += 1 computed_hash = block.compute_hash() return computed_hash<|docstring|>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.<|endoftext|>
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. \n ' previous_hash = self.last_block.hash if (previous_hash != block.previous_hash): return False if (not Blockchain.is_valid_proof(block, proof)): return False block.hash = proof self.chain.append(block) return True
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. \n ' previous_hash = self.last_block.hash if (previous_hash != block.previous_hash): return False if (not Blockchain.is_valid_proof(block, proof)): return False block.hash = proof self.chain.append(block) return True
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. \n ' previous_hash = self.last_block.hash if (previous_hash != block.previous_hash): return False if (not Blockchain.is_valid_proof(block, proof)): return False block.hash = proof self.chain.append(block) return True<|docstring|>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.<|endoftext|>
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<|endoftext|>
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 '{}' a bien été supprimée".format(cle))
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(cle))
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(cle))<|docstring|>Interprétation du paramètre<|endoftext|>
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)) payload = ('{"teach_language":{"language":"%s"},"page_size":%s,"user_timezone":"Europe/Madrid"}' % (language_id, str(to_crawl))) headers = {'Content-Type': 'application/json'} response = requests.request('POST', api_url, headers=headers, data=payload).json() return response['data'] else: pages_number = ceil((to_crawl / 20)) crawled = 0 data = [] for page_number in range(1, (pages_number + 1)): remaining = (to_crawl - crawled) if (remaining > 20): page_size = 20 else: page_size = remaining print('Querying API for {} in page {}'.format(language_id, page_number)) payload = ('{"teach_language":{"language":"%s"},"page":%s,"page_size":%s,"user_timezone":"Europe/Madrid"}' % (language_id, str(page_number), str(page_size))) headers = {'Content-Type': 'application/json'} response = requests.request('POST', api_url, headers=headers, data=payload).json() data.append(response['data']) crawled += page_size time.sleep(uniform(0, 2)) return data except Exception as e: print('Error querying {}'.format(language_id)) print(e) return None
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)) payload = ('{"teach_language":{"language":"%s"},"page_size":%s,"user_timezone":"Europe/Madrid"}' % (language_id, str(to_crawl))) headers = {'Content-Type': 'application/json'} response = requests.request('POST', api_url, headers=headers, data=payload).json() return response['data'] else: pages_number = ceil((to_crawl / 20)) crawled = 0 data = [] for page_number in range(1, (pages_number + 1)): remaining = (to_crawl - crawled) if (remaining > 20): page_size = 20 else: page_size = remaining print('Querying API for {} in page {}'.format(language_id, page_number)) payload = ('{"teach_language":{"language":"%s"},"page":%s,"page_size":%s,"user_timezone":"Europe/Madrid"}' % (language_id, str(page_number), str(page_size))) headers = {'Content-Type': 'application/json'} response = requests.request('POST', api_url, headers=headers, data=payload).json() data.append(response['data']) crawled += page_size time.sleep(uniform(0, 2)) return data except Exception as e: print('Error querying {}'.format(language_id)) print(e) return None
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)) payload = ('{"teach_language":{"language":"%s"},"page_size":%s,"user_timezone":"Europe/Madrid"}' % (language_id, str(to_crawl))) headers = {'Content-Type': 'application/json'} response = requests.request('POST', api_url, headers=headers, data=payload).json() return response['data'] else: pages_number = ceil((to_crawl / 20)) crawled = 0 data = [] for page_number in range(1, (pages_number + 1)): remaining = (to_crawl - crawled) if (remaining > 20): page_size = 20 else: page_size = remaining print('Querying API for {} in page {}'.format(language_id, page_number)) payload = ('{"teach_language":{"language":"%s"},"page":%s,"page_size":%s,"user_timezone":"Europe/Madrid"}' % (language_id, str(page_number), str(page_size))) headers = {'Content-Type': 'application/json'} response = requests.request('POST', api_url, headers=headers, data=payload).json() data.append(response['data']) crawled += page_size time.sleep(uniform(0, 2)) return data except Exception as e: print('Error querying {}'.format(language_id)) print(e) return None<|docstring|>Queries the API for teachers :return: JSON data containing conversations<|endoftext|>
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, 'r') as xyz_file: try: n_atoms = int(xyz_file.readline().split()[0]) except IndexError: raise FileMalformatted xyz_lines = xyz_file.readlines()[1:(n_atoms + 1)] for line in xyz_lines: try: (atom_label, x, y, z) = line.split()[:4] atoms.append(Atom(atomic_symbol=atom_label, x=x, y=y, z=z)) except (IndexError, TypeError, ValueError): raise FileMalformatted return atoms
/ 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, 'r') as xyz_file: try: n_atoms = int(xyz_file.readline().split()[0]) except IndexError: raise FileMalformatted xyz_lines = xyz_file.readlines()[1:(n_atoms + 1)] for line in xyz_lines: try: (atom_label, x, y, z) = line.split()[:4] atoms.append(Atom(atomic_symbol=atom_label, x=x, y=y, z=z)) except (IndexError, TypeError, ValueError): raise FileMalformatted return atoms
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, 'r') as xyz_file: try: n_atoms = int(xyz_file.readline().split()[0]) except IndexError: raise FileMalformatted xyz_lines = xyz_file.readlines()[1:(n_atoms + 1)] for line in xyz_lines: try: (atom_label, x, y, z) = line.split()[:4] atoms.append(Atom(atomic_symbol=atom_label, x=x, y=y, z=z)) except (IndexError, TypeError, ValueError): raise FileMalformatted return atoms<|docstring|>/ From an .xyz file get a list of atoms :param filename: (str) .xyz filename :return: (list(Atom))<|endoftext|>
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) for atom in atoms: (x, y, z) = atom.coord print(f'{atom.label:<3} {x:^10.5f} {y:^10.5f} {z:^10.5f}', file=xyz_file) return None
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) for atom in atoms: (x, y, z) = atom.coord print(f'{atom.label:<3} {x:^10.5f} {y:^10.5f} {z:^10.5f}', file=xyz_file) return None
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) for atom in atoms: (x, y, z) = atom.coord print(f'{atom.label:<3} {x:^10.5f} {y:^10.5f} {z:^10.5f}', file=xyz_file) return None<|docstring|>Print a standard .xyz file from a set of atoms :param atoms: (list(Atom)) :param filename: (str) :param title_line: (str)<|endoftext|>
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) else: raise CgbindCritical('Unsupported file format. Supported formats are{.xyz, .mol, .mol2}')
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('Unsupported file format. Supported formats are{.xyz, .mol, .mol2}')
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('Unsupported file format. Supported formats are{.xyz, .mol, .mol2}')<|docstring|>Get a list of atoms from a structure file<|endoftext|>
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') raise FileMalformatted atoms = [] with open(filename, 'r') as xyz_file: xyz_lines = xyz_file.readlines()[2:] for line in xyz_lines: (atom_label, x, y, z) = line.split() atoms.append(Atom(atom_label, float(x), float(y), float(z))) if (len(atoms) == 0): logger.error(f'Could not read xyz lines in {filename}') raise FileMalformatted return atoms
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') raise FileMalformatted atoms = [] with open(filename, 'r') as xyz_file: xyz_lines = xyz_file.readlines()[2:] for line in xyz_lines: (atom_label, x, y, z) = line.split() atoms.append(Atom(atom_label, float(x), float(y), float(z))) if (len(atoms) == 0): logger.error(f'Could not read xyz lines in {filename}') raise FileMalformatted return atoms
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') raise FileMalformatted atoms = [] with open(filename, 'r') as xyz_file: xyz_lines = xyz_file.readlines()[2:] for line in xyz_lines: (atom_label, x, y, z) = line.split() atoms.append(Atom(atom_label, float(x), float(y), float(z))) if (len(atoms) == 0): logger.error(f'Could not read xyz lines in {filename}') raise FileMalformatted return atoms<|docstring|>Convert a standard xyz file into a list of atoms :param filename: (str) :return: (list(cgbind.atoms.Atom))<|endoftext|>
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 0 0 0 0 0 0 0 0 0 0 0\n 0.7917 0.0756 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0\n -0.6349 -0.9294 -0.0876 H 0 0 0 0 0 0 0 0 0 0 0 0\n -0.6349 0.6539 -0.8266 H 0 0 0 0 0 0 0 0 0 0 0 0\n -0.6349 0.5022 0.9141 H 0 0 0 0 0 0 0 0 0 0 0 0\n 1 2 1 0 0 0 0\n 1 3 1 0 0 0 0\n 1 4 1 0 0 0 0\n 1 5 1 0 0 0 0\n M END\n _____________________\n ' atoms = [] if (not filename.endswith('.mol')): logger.error('Could not read .mol file') raise FileMalformatted with open(filename, 'r') as mol_file: mol_lines = mol_file.readlines()[3:] try: n_atoms = int(mol_lines[0].split()[0]) except ValueError: raise FileMalformatted for line in mol_lines[1:(n_atoms + 1)]: (x, y, z, atom_label) = line.split()[:4] atoms.append(Atom(atom_label, float(x), float(y), float(z))) if (len(atoms) == 0): logger.error(f'Could not read xyz lines in {filename}') raise FileMalformatted return atoms
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 0 0 0 0 0 0 0 0 0 0 0\n 0.7917 0.0756 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0\n -0.6349 -0.9294 -0.0876 H 0 0 0 0 0 0 0 0 0 0 0 0\n -0.6349 0.6539 -0.8266 H 0 0 0 0 0 0 0 0 0 0 0 0\n -0.6349 0.5022 0.9141 H 0 0 0 0 0 0 0 0 0 0 0 0\n 1 2 1 0 0 0 0\n 1 3 1 0 0 0 0\n 1 4 1 0 0 0 0\n 1 5 1 0 0 0 0\n M END\n _____________________\n ' atoms = [] if (not filename.endswith('.mol')): logger.error('Could not read .mol file') raise FileMalformatted with open(filename, 'r') as mol_file: mol_lines = mol_file.readlines()[3:] try: n_atoms = int(mol_lines[0].split()[0]) except ValueError: raise FileMalformatted for line in mol_lines[1:(n_atoms + 1)]: (x, y, z, atom_label) = line.split()[:4] atoms.append(Atom(atom_label, float(x), float(y), float(z))) if (len(atoms) == 0): logger.error(f'Could not read xyz lines in {filename}') raise FileMalformatted return atoms
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 0 0 0 0 0 0 0 0 0 0 0\n 0.7917 0.0756 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0\n -0.6349 -0.9294 -0.0876 H 0 0 0 0 0 0 0 0 0 0 0 0\n -0.6349 0.6539 -0.8266 H 0 0 0 0 0 0 0 0 0 0 0 0\n -0.6349 0.5022 0.9141 H 0 0 0 0 0 0 0 0 0 0 0 0\n 1 2 1 0 0 0 0\n 1 3 1 0 0 0 0\n 1 4 1 0 0 0 0\n 1 5 1 0 0 0 0\n M END\n _____________________\n ' atoms = [] if (not filename.endswith('.mol')): logger.error('Could not read .mol file') raise FileMalformatted with open(filename, 'r') as mol_file: mol_lines = mol_file.readlines()[3:] try: n_atoms = int(mol_lines[0].split()[0]) except ValueError: raise FileMalformatted for line in mol_lines[1:(n_atoms + 1)]: (x, y, z, atom_label) = line.split()[:4] atoms.append(Atom(atom_label, float(x), float(y), float(z))) if (len(atoms) == 0): logger.error(f'Could not read xyz lines in {filename}') raise FileMalformatted return atoms<|docstring|>Convert a .mol file to a list of atoms :param filename: (str) :return: (list(Atom))<|endoftext|>
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 FileMalformatted mol_file_lines = open(filename, 'r').readlines() (atoms, xyz_block) = ([], False) for (n_line, line) in enumerate(mol_file_lines): if (('@' in line) and xyz_block): break if xyz_block: try: (atom_label, x, y, z) = line.split()[1:5] try: atoms.append(Atom(atom_label, float(x), float(y), float(z))) except TypeError: logger.error('There was a problem with the .mol2 file') raise FileMalformatted except IndexError: logger.error('There was a problem with the .mol2 file') raise FileMalformatted if (('@' in line) and ('ATOM' in line) and (len(mol_file_lines[(n_line + 1)].split()) == 9)): xyz_block = True for atom in atoms: if (len(atom.label) == 1): continue elif (atom.label[0].isalpha() and (not atom.label[1].isalpha())): atom.label = atom.label[0] elif (atom.label[0].isalpha() and atom.label[1].isalpha()): atom.label = atom.label[:2].title() else: logger.error('Unrecognised atom type') raise FileMalformatted return atoms
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 FileMalformatted mol_file_lines = open(filename, 'r').readlines() (atoms, xyz_block) = ([], False) for (n_line, line) in enumerate(mol_file_lines): if (('@' in line) and xyz_block): break if xyz_block: try: (atom_label, x, y, z) = line.split()[1:5] try: atoms.append(Atom(atom_label, float(x), float(y), float(z))) except TypeError: logger.error('There was a problem with the .mol2 file') raise FileMalformatted except IndexError: logger.error('There was a problem with the .mol2 file') raise FileMalformatted if (('@' in line) and ('ATOM' in line) and (len(mol_file_lines[(n_line + 1)].split()) == 9)): xyz_block = True for atom in atoms: if (len(atom.label) == 1): continue elif (atom.label[0].isalpha() and (not atom.label[1].isalpha())): atom.label = atom.label[0] elif (atom.label[0].isalpha() and atom.label[1].isalpha()): atom.label = atom.label[:2].title() else: logger.error('Unrecognised atom type') raise FileMalformatted return atoms
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 FileMalformatted mol_file_lines = open(filename, 'r').readlines() (atoms, xyz_block) = ([], False) for (n_line, line) in enumerate(mol_file_lines): if (('@' in line) and xyz_block): break if xyz_block: try: (atom_label, x, y, z) = line.split()[1:5] try: atoms.append(Atom(atom_label, float(x), float(y), float(z))) except TypeError: logger.error('There was a problem with the .mol2 file') raise FileMalformatted except IndexError: logger.error('There was a problem with the .mol2 file') raise FileMalformatted if (('@' in line) and ('ATOM' in line) and (len(mol_file_lines[(n_line + 1)].split()) == 9)): xyz_block = True for atom in atoms: if (len(atom.label) == 1): continue elif (atom.label[0].isalpha() and (not atom.label[1].isalpha())): atom.label = atom.label[0] elif (atom.label[0].isalpha() and atom.label[1].isalpha()): atom.label = atom.label[:2].title() else: logger.error('Unrecognised atom type') raise FileMalformatted return atoms<|docstring|>Convert a .mol file into a standard set of atoms :param filename: (str) :return: (lis(Atom))<|endoftext|>
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 = ', '.join(list(builders.keys())) raise RuntimeError(f"Error unknown builder '{builder_name}', supported builders: [{builder_names}]") return builder_class(builder_name, builder_dict, build_context)
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"Error unknown builder '{builder_name}', supported builders: [{builder_names}]") return builder_class(builder_name, builder_dict, build_context)
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"Error unknown builder '{builder_name}', supported builders: [{builder_names}]") return builder_class(builder_name, builder_dict, build_context)<|docstring|>Instantiate a new builder with the given builder_name.<|endoftext|>
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('CC-MAIN-', '') for index in index_list] return indexes
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('CC-MAIN-', ) for index in index_list] return indexes
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('CC-MAIN-', ) for index in index_list] return indexes<|docstring|>Fetches the available Common Crawl Indexes to search. Returns: A list containing available indexes and information about them.<|endoftext|>
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) spec.loader.exec_module(configuration) if hasattr(configuration, name): value = getattr(configuration, name) if ((valid_types is None) or isinstance(value, valid_types)): return value else: return default else: return default
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) spec.loader.exec_module(configuration) if hasattr(configuration, name): value = getattr(configuration, name) if ((valid_types is None) or isinstance(value, valid_types)): return value else: return default else: return default
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) spec.loader.exec_module(configuration) if hasattr(configuration, name): value = getattr(configuration, name) if ((valid_types is None) or isinstance(value, valid_types)): return value else: return default else: return default<|docstring|>Get ``name`` from ``configuration.py`` Returns ``default`` if not present or not one of types in ``valid_types``<|endoftext|>
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 ``suffix``. Returns ``True`` or ``False``<|endoftext|>
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_SCENE_SUFFIX, default=''))] if (not items): return None elif (len(items) > 1): return None elif (items[0]['type'] not in itemtypesScene): return None else: return items[0]
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_SCENE_SUFFIX, default=))] if (not items): return None elif (len(items) > 1): return None elif (items[0]['type'] not in itemtypesScene): return None else: return items[0]
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_SCENE_SUFFIX, default=))] if (not items): return None elif (len(items) > 1): return None elif (items[0]['type'] not in itemtypesScene): return None else: return items[0]<|docstring|>Finds the scene item in a group. Returns the scene item or ``None`` if it does not find exactly one match.<|endoftext|>
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(get_value(item['name'], META_NAME_EOS, host)) is not None))] if ('members' in group) else [])
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(get_value(item['name'], META_NAME_EOS, host)) is not None))] if ('members' in group) else [])
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(get_value(item['name'], META_NAME_EOS, host)) is not None))] if ('members' in group) else [])<|docstring|>Finds all light items in a group. Returns a list of valid Eos lights.<|endoftext|>
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. Returns a list of valid Eos groups.<|endoftext|>
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'): return False elif (str(value).lower() == 'none'): return None else: try: return literal_eval(value) except ValueError: pass except SyntaxError: pass try: return int(value) except: pass try: return float(value) except: pass return value
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'): return False elif (str(value).lower() == 'none'): return None else: try: return literal_eval(value) except ValueError: pass except SyntaxError: pass try: return int(value) except: pass try: return float(value) except: pass return value
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'): return False elif (str(value).lower() == 'none'): return None else: try: return literal_eval(value) except ValueError: pass except SyntaxError: pass try: return int(value) except: pass try: return float(value) except: pass return value<|docstring|>Attempts to resolve the type of ``value``. It will return ``value`` as the python type if possible, otherwise will return value as string.<|endoftext|>
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 (len(groups) > 1): return None else: return validate_item(groups[0], host)
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 (len(groups) > 1): return None else: return validate_item(groups[0], host)
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 (len(groups) > 1): return None else: return validate_item(groups[0], host)<|docstring|>Gets the Eos group from the item's groups. Returns the group item or ``None`` if it does not find exactly one match.<|endoftext|>
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(group): others.pop(item['name'], None) for item in [item for item in group['members'] if (item['name'] == get_conf_value(CONF_KEY_REINIT_ITEM, str))]: others.pop(item['name'], None) for item in [others[key] for key in others]: if ((item['type'] not in itemtypesLight) and (item['type'] != itemtypesGroup)): others.pop(item['name'], None) others.pop(get_scene_item(group)['name'], None) return [others[key] for key in others]
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(group): others.pop(item['name'], None) for item in [item for item in group['members'] if (item['name'] == get_conf_value(CONF_KEY_REINIT_ITEM, str))]: others.pop(item['name'], None) for item in [others[key] for key in others]: if ((item['type'] not in itemtypesLight) and (item['type'] != itemtypesGroup)): others.pop(item['name'], None) others.pop(get_scene_item(group)['name'], None) return [others[key] for key in others]
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(group): others.pop(item['name'], None) for item in [item for item in group['members'] if (item['name'] == get_conf_value(CONF_KEY_REINIT_ITEM, str))]: others.pop(item['name'], None) for item in [others[key] for key in others]: if ((item['type'] not in itemtypesLight) and (item['type'] != itemtypesGroup)): others.pop(item['name'], None) others.pop(get_scene_item(group)['name'], None) return [others[key] for key in others]<|docstring|>Finds all non Eos items in a group. Returns a list of all non Eos items in the group.<|endoftext|>
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: d[k] = u[k] return d
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|>Recursively update dict ``d`` with dict ``u``<|endoftext|>
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 (just returned)\n :return: str to be printed if return_str is True\n ' strlen = len(message) padding = (' ' * (min_length - strlen)) message += padding s = [('=' * (max(min_length, strlen) + 4)), f'* {message} *', ('=' * (max(min_length, strlen) + 4))] if print_str: for line in s: printc(line, col=col) return '\n'.join(s)
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 (just returned)\n :return: str to be printed if return_str is True\n ' strlen = len(message) padding = (' ' * (min_length - strlen)) message += padding s = [('=' * (max(min_length, strlen) + 4)), f'* {message} *', ('=' * (max(min_length, strlen) + 4))] if print_str: for line in s: printc(line, col=col) return '\n'.join(s)
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 (just returned)\n :return: str to be printed if return_str is True\n ' strlen = len(message) padding = (' ' * (min_length - strlen)) message += padding s = [('=' * (max(min_length, strlen) + 4)), f'* {message} *', ('=' * (max(min_length, strlen) + 4))] if print_str: for line in s: printc(line, col=col) return '\n'.join(s)<|docstring|>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<|endoftext|>
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 fname_validator: Filename where the validator will be downloaded to :return: None<|endoftext|>
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: content = f.read() re_group_capture = '[a-zA-Z0-9_\\-\\$]+' pattern = re.compile(f'Profile: (?P<profile>{re_group_capture})[^\n]*\nParent: (?P<parent>{re_group_capture})[^\n]*\nId: (?P<id>{re_group_capture})', re.MULTILINE) fsh_profiles = [m.groupdict() for m in pattern.finditer(content)] pattern = re.compile(f'Instance: (?P<instance>{re_group_capture})[^\n]*\nInstanceOf: (?P<instanceof>{re_group_capture})', re.MULTILINE) fsh_instances = [m.groupdict() for m in pattern.finditer(content)] return (fsh_profiles, fsh_instances)
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: content = f.read() re_group_capture = '[a-zA-Z0-9_\\-\\$]+' pattern = re.compile(f'Profile: (?P<profile>{re_group_capture})[^\n]*\nParent: (?P<parent>{re_group_capture})[^\n]*\nId: (?P<id>{re_group_capture})', re.MULTILINE) fsh_profiles = [m.groupdict() for m in pattern.finditer(content)] pattern = re.compile(f'Instance: (?P<instance>{re_group_capture})[^\n]*\nInstanceOf: (?P<instanceof>{re_group_capture})', re.MULTILINE) fsh_instances = [m.groupdict() for m in pattern.finditer(content)] return (fsh_profiles, fsh_instances)
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: content = f.read() re_group_capture = '[a-zA-Z0-9_\\-\\$]+' pattern = re.compile(f'Profile: (?P<profile>{re_group_capture})[^\n]*\nParent: (?P<parent>{re_group_capture})[^\n]*\nId: (?P<id>{re_group_capture})', re.MULTILINE) fsh_profiles = [m.groupdict() for m in pattern.finditer(content)] pattern = re.compile(f'Instance: (?P<instance>{re_group_capture})[^\n]*\nInstanceOf: (?P<instanceof>{re_group_capture})', re.MULTILINE) fsh_instances = [m.groupdict() for m in pattern.finditer(content)] return (fsh_profiles, fsh_instances)<|docstring|>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<|endoftext|>
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 :return: StructureDefinitions, Instances, Dependencies, ValueSets, CodeSystems, Extensions\n ' def parse_structure_definition(fname: Path, json_data: str) -> Tuple[(Dict, str)]: url = parse('$.url').find(json_data)[0].value type = parse('$.type').find(json_data)[0].value base = parse('$.baseDefinition').find(json_data)[0].value abstract = parse('$.abstract').find(json_data)[0].value profilesAdditional = [x.value[0] for x in parse('$.differential.element[*].type[*].profile').find(json_data)] return ({url: {'filename': fname.resolve(), 'id': parse('$.id').find(json_data)[0].value, 'type': type, 'base': base, 'profilesAdditional': profilesAdditional, 'abstract': abstract}}, type) def parse_instance(fname: Path, json_data: str) -> Dict: resourceType = parse('$.resourceType').find(json_data)[0].value codeSystems = set((s.value for s in parse('$.*.coding[*].system').find(json_data))) profile = parse('$.meta.profile').find(json_data) if (len(profile) == 0): profile = resourceType else: profile = profile[0].value[0] profilesAdditional = [] if (resourceType == 'Bundle'): profilesAdditional = [p.value[0] for p in parse('$.entry[*].resource.meta.profile').find(json_data)] return {parse('$.id').find(json_data)[0].value: {'filename': fname.resolve(), 'profile': profile, 'resourceType': resourceType, 'codeSystems': codeSystems, 'profilesAdditional': profilesAdditional}} def parse_ig(fname: Path, json_data: str) -> Dict: deps = parse('$.dependsOn[*]').find(json_data) return {v.value['packageId']: v.value for v in deps} def parse_value_set(fname: Path, json_data: str) -> Dict: url = parse('$.url').find(json_data)[0].value return {url: {'filename': fname.resolve(), 'id': parse('$.id').find(json_data)[0].value}} def parse_code_system(fname: Path, json_data: str) -> Dict: url = parse('$.url').find(json_data)[0].value return {url: {'filename': fname.resolve(), 'id': parse('$.id').find(json_data)[0].value}} sdefs = {} instances = {} deps = {} vs = {} cs = {} extensions = {} for fname in path.glob('*.json'): json_data = json.load(open(fname)) resourceType = parse('$.resourceType').find(json_data)[0].value if (resourceType == 'StructureDefinition'): (sd, type) = parse_structure_definition(fname, json_data) if (type == 'Extension'): extensions.update(sd) else: sdefs.update(sd) elif (resourceType == 'ImplementationGuide'): deps.update(parse_ig(fname, json_data)) elif (resourceType == 'ValueSet'): vs.update(parse_value_set(fname, json_data)) elif (resourceType == 'CodeSystem'): cs.update(parse_code_system(fname, json_data)) else: instances.update(parse_instance(fname, json_data)) return (sdefs, instances, deps, vs, cs, extensions)
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 :return: StructureDefinitions, Instances, Dependencies, ValueSets, CodeSystems, Extensions\n ' def parse_structure_definition(fname: Path, json_data: str) -> Tuple[(Dict, str)]: url = parse('$.url').find(json_data)[0].value type = parse('$.type').find(json_data)[0].value base = parse('$.baseDefinition').find(json_data)[0].value abstract = parse('$.abstract').find(json_data)[0].value profilesAdditional = [x.value[0] for x in parse('$.differential.element[*].type[*].profile').find(json_data)] return ({url: {'filename': fname.resolve(), 'id': parse('$.id').find(json_data)[0].value, 'type': type, 'base': base, 'profilesAdditional': profilesAdditional, 'abstract': abstract}}, type) def parse_instance(fname: Path, json_data: str) -> Dict: resourceType = parse('$.resourceType').find(json_data)[0].value codeSystems = set((s.value for s in parse('$.*.coding[*].system').find(json_data))) profile = parse('$.meta.profile').find(json_data) if (len(profile) == 0): profile = resourceType else: profile = profile[0].value[0] profilesAdditional = [] if (resourceType == 'Bundle'): profilesAdditional = [p.value[0] for p in parse('$.entry[*].resource.meta.profile').find(json_data)] return {parse('$.id').find(json_data)[0].value: {'filename': fname.resolve(), 'profile': profile, 'resourceType': resourceType, 'codeSystems': codeSystems, 'profilesAdditional': profilesAdditional}} def parse_ig(fname: Path, json_data: str) -> Dict: deps = parse('$.dependsOn[*]').find(json_data) return {v.value['packageId']: v.value for v in deps} def parse_value_set(fname: Path, json_data: str) -> Dict: url = parse('$.url').find(json_data)[0].value return {url: {'filename': fname.resolve(), 'id': parse('$.id').find(json_data)[0].value}} def parse_code_system(fname: Path, json_data: str) -> Dict: url = parse('$.url').find(json_data)[0].value return {url: {'filename': fname.resolve(), 'id': parse('$.id').find(json_data)[0].value}} sdefs = {} instances = {} deps = {} vs = {} cs = {} extensions = {} for fname in path.glob('*.json'): json_data = json.load(open(fname)) resourceType = parse('$.resourceType').find(json_data)[0].value if (resourceType == 'StructureDefinition'): (sd, type) = parse_structure_definition(fname, json_data) if (type == 'Extension'): extensions.update(sd) else: sdefs.update(sd) elif (resourceType == 'ImplementationGuide'): deps.update(parse_ig(fname, json_data)) elif (resourceType == 'ValueSet'): vs.update(parse_value_set(fname, json_data)) elif (resourceType == 'CodeSystem'): cs.update(parse_code_system(fname, json_data)) else: instances.update(parse_instance(fname, json_data)) return (sdefs, instances, deps, vs, cs, extensions)
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 :return: StructureDefinitions, Instances, Dependencies, ValueSets, CodeSystems, Extensions\n ' def parse_structure_definition(fname: Path, json_data: str) -> Tuple[(Dict, str)]: url = parse('$.url').find(json_data)[0].value type = parse('$.type').find(json_data)[0].value base = parse('$.baseDefinition').find(json_data)[0].value abstract = parse('$.abstract').find(json_data)[0].value profilesAdditional = [x.value[0] for x in parse('$.differential.element[*].type[*].profile').find(json_data)] return ({url: {'filename': fname.resolve(), 'id': parse('$.id').find(json_data)[0].value, 'type': type, 'base': base, 'profilesAdditional': profilesAdditional, 'abstract': abstract}}, type) def parse_instance(fname: Path, json_data: str) -> Dict: resourceType = parse('$.resourceType').find(json_data)[0].value codeSystems = set((s.value for s in parse('$.*.coding[*].system').find(json_data))) profile = parse('$.meta.profile').find(json_data) if (len(profile) == 0): profile = resourceType else: profile = profile[0].value[0] profilesAdditional = [] if (resourceType == 'Bundle'): profilesAdditional = [p.value[0] for p in parse('$.entry[*].resource.meta.profile').find(json_data)] return {parse('$.id').find(json_data)[0].value: {'filename': fname.resolve(), 'profile': profile, 'resourceType': resourceType, 'codeSystems': codeSystems, 'profilesAdditional': profilesAdditional}} def parse_ig(fname: Path, json_data: str) -> Dict: deps = parse('$.dependsOn[*]').find(json_data) return {v.value['packageId']: v.value for v in deps} def parse_value_set(fname: Path, json_data: str) -> Dict: url = parse('$.url').find(json_data)[0].value return {url: {'filename': fname.resolve(), 'id': parse('$.id').find(json_data)[0].value}} def parse_code_system(fname: Path, json_data: str) -> Dict: url = parse('$.url').find(json_data)[0].value return {url: {'filename': fname.resolve(), 'id': parse('$.id').find(json_data)[0].value}} sdefs = {} instances = {} deps = {} vs = {} cs = {} extensions = {} for fname in path.glob('*.json'): json_data = json.load(open(fname)) resourceType = parse('$.resourceType').find(json_data)[0].value if (resourceType == 'StructureDefinition'): (sd, type) = parse_structure_definition(fname, json_data) if (type == 'Extension'): extensions.update(sd) else: sdefs.update(sd) elif (resourceType == 'ImplementationGuide'): deps.update(parse_ig(fname, json_data)) elif (resourceType == 'ValueSet'): vs.update(parse_value_set(fname, json_data)) elif (resourceType == 'CodeSystem'): cs.update(parse_code_system(fname, json_data)) else: instances.update(parse_instance(fname, json_data)) return (sdefs, instances, deps, vs, cs, extensions)<|docstring|>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<|endoftext|>
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'))<|docstring|>Get fsh input and output paths from base path. :param base_path: Base path :return: FSH input path, FSH output path<|endoftext|>
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: Base to get fsh base path from\n :return: FSH project base path\n ' path = Path(path).absolute() if ((path / 'input') / 'fsh').exists(): return path for i in range((len(path.parts) - 1)): if ((path.parts[i] == 'input') and (path.parts[(i + 1)] == 'fsh')): return Path(*path.parts[:i]).absolute() raise ValueError(f'Could not find fsh input path (input/fsh/) in "{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: Base to get fsh base path from\n :return: FSH project base path\n ' path = Path(path).absolute() if ((path / 'input') / 'fsh').exists(): return path for i in range((len(path.parts) - 1)): if ((path.parts[i] == 'input') and (path.parts[(i + 1)] == 'fsh')): return Path(*path.parts[:i]).absolute() raise ValueError(f'Could not find fsh input path (input/fsh/) in "{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: Base to get fsh base path from\n :return: FSH project base path\n ' path = Path(path).absolute() if ((path / 'input') / 'fsh').exists(): return path for i in range((len(path.parts) - 1)): if ((path.parts[i] == 'input') and (path.parts[(i + 1)] == 'fsh')): return Path(*path.parts[:i]).absolute() raise ValueError(f'Could not find fsh input path (input/fsh/) in "{path}"')<|docstring|>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<|endoftext|>
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-0203#OBI twice, but it has a cardinality of 1, resulting in an error\n by the FHIR validator. This workaround function actively removes the duplicates.\n\n MII Profile: https://www.medizininformatik-initiative.de/fhir/core/modul-labor/StructureDefinition/ObservationLab\n\n :param fname: Filename of instance to remove duplicates from\n :return: None\n ' def num_obi_codes(json_data: Dict): jp = parse("$.type.coding[?code = 'OBI' & system='http://terminology.hl7.org/CodeSystem/v2-0203']") return len(jp.find(json_data)) def del_obi_codes(identifier: Dict): codings = identifier['type']['coding'] for (i, coding) in enumerate(codings): if ((coding['system'] == 'http://terminology.hl7.org/CodeSystem/v2-0203') and (coding['code'] == 'OBI')): del codings[i] break json_data = json.load(open(fname)) if ('identifier' not in json_data): return for identifier in json_data['identifier']: if (num_obi_codes(identifier) > 1): warnings.warn(f'Found multiple OBI codes in {fname}, removing') del_obi_codes(identifier) json.dump(json_data, open(fname, 'w'), indent=2)
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 by the FHIR validator. This workaround function actively removes the duplicates. MII Profile: https://www.medizininformatik-initiative.de/fhir/core/modul-labor/StructureDefinition/ObservationLab :param fname: Filename of instance to remove duplicates from :return: None
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-0203#OBI twice, but it has a cardinality of 1, resulting in an error\n by the FHIR validator. This workaround function actively removes the duplicates.\n\n MII Profile: https://www.medizininformatik-initiative.de/fhir/core/modul-labor/StructureDefinition/ObservationLab\n\n :param fname: Filename of instance to remove duplicates from\n :return: None\n ' def num_obi_codes(json_data: Dict): jp = parse("$.type.coding[?code = 'OBI' & system='http://terminology.hl7.org/CodeSystem/v2-0203']") return len(jp.find(json_data)) def del_obi_codes(identifier: Dict): codings = identifier['type']['coding'] for (i, coding) in enumerate(codings): if ((coding['system'] == 'http://terminology.hl7.org/CodeSystem/v2-0203') and (coding['code'] == 'OBI')): del codings[i] break json_data = json.load(open(fname)) if ('identifier' not in json_data): return for identifier in json_data['identifier']: if (num_obi_codes(identifier) > 1): warnings.warn(f'Found multiple OBI codes in {fname}, removing') del_obi_codes(identifier) json.dump(json_data, open(fname, 'w'), indent=2)
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-0203#OBI twice, but it has a cardinality of 1, resulting in an error\n by the FHIR validator. This workaround function actively removes the duplicates.\n\n MII Profile: https://www.medizininformatik-initiative.de/fhir/core/modul-labor/StructureDefinition/ObservationLab\n\n :param fname: Filename of instance to remove duplicates from\n :return: None\n ' def num_obi_codes(json_data: Dict): jp = parse("$.type.coding[?code = 'OBI' & system='http://terminology.hl7.org/CodeSystem/v2-0203']") return len(jp.find(json_data)) def del_obi_codes(identifier: Dict): codings = identifier['type']['coding'] for (i, coding) in enumerate(codings): if ((coding['system'] == 'http://terminology.hl7.org/CodeSystem/v2-0203') and (coding['code'] == 'OBI')): del codings[i] break json_data = json.load(open(fname)) if ('identifier' not in json_data): return for identifier in json_data['identifier']: if (num_obi_codes(identifier) > 1): warnings.warn(f'Found multiple OBI codes in {fname}, removing') del_obi_codes(identifier) json.dump(json_data, open(fname, 'w'), indent=2)<|docstring|>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 by the FHIR validator. This workaround function actively removes the duplicates. MII Profile: https://www.medizininformatik-initiative.de/fhir/core/modul-labor/StructureDefinition/ObservationLab :param fname: Filename of instance to remove duplicates from :return: None<|endoftext|>
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['abstract']])
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['abstract']])
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['abstract']])<|docstring|>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<|endoftext|>
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 Instances defined in each FSH file\n - Run FHIR Java validator for each instance to validate it against its corresponding profile\n\n :param path_output: output path (of SUSHI project)\n :param fnames: FSH file names to validate (full paths)\n :param fname_validator: full path to FHIR Java validator file\n :param fhir_version: FHIR version to use in validator\n :param exclude_code_systems: Optional set of code systems which prevent instances from being validated\n :param exclude_resource_types: Optional set of resource types which prevent instances from being validated\n :param verbose: Print more information\n :return: ValidatorStatus objects\n ' (sdefs, instances, deps, vs, cs, extensions) = parse_fsh_generated(path_output) for (k, v) in instances.items(): deduplicate_obi_codes(v['filename']) results = [] for (i, fname) in enumerate(fnames): if (not fname.exists()): raise FileNotFoundError(fname) (fsh_profiles, fsh_instances) = parse_fsh(fname) percent = (((i + 1) / len(fnames)) * 100) print(f'[{percent: 5.1f}%] Processing file {fname} with {len(fsh_profiles)} profiles and {len(fsh_instances)} instances ({(i + 1)}/{len(fnames)})') profiles_without_instance = check_instances_availability(fsh_profiles, fsh_instances, get_abstract_profile_ids(sdefs)) if len(profiles_without_instance): for p in profiles_without_instance: status = ValidatorStatus(status=ValidatorStatus.Status.FAILURE, errors=[f'No instances defined for profile {p}'], profile=p) status.pretty_print(with_header=True) results.append(status) continue fsh_instances_cleaned = [] for fsh_instance in fsh_instances: instance = instances[fsh_instance['instance']] if ((exclude_code_systems is not None) and any(((cs in exclude_code_systems) for cs in instance['codeSystems']))): status = ValidatorStatus(status=ValidatorStatus.Status.WARNING, warnings=[f"Skipped instance {fsh_instance['instance']} due to excluded code system(s) used in the instance"], profile=fsh_instance['instanceof']) status.pretty_print(with_header=True) results.append(status) elif ((exclude_resource_types is not None) and (instance['resourceType'] in exclude_resource_types)): status = ValidatorStatus(status=ValidatorStatus.Status.WARNING, warnings=[f"Skipped instance {fsh_instance['instance']} due to excluded resource type {instance['resourceType']}"], profile=fsh_instance['instanceof']) status.pretty_print(with_header=True) results.append(status) else: fsh_instances_cleaned.append(fsh_instance) results += run_validation(fname_validator, fsh_instances_cleaned, sdefs, instances, deps, vs, cs, extensions, fhir_version=fhir_version, verbose=verbose) return results
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 path to FHIR Java validator file :param fhir_version: FHIR version to use in validator :param exclude_code_systems: Optional set of code systems which prevent instances from being validated :param exclude_resource_types: Optional set of resource types which prevent instances from being validated :param verbose: Print more information :return: ValidatorStatus objects
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 Instances defined in each FSH file\n - Run FHIR Java validator for each instance to validate it against its corresponding profile\n\n :param path_output: output path (of SUSHI project)\n :param fnames: FSH file names to validate (full paths)\n :param fname_validator: full path to FHIR Java validator file\n :param fhir_version: FHIR version to use in validator\n :param exclude_code_systems: Optional set of code systems which prevent instances from being validated\n :param exclude_resource_types: Optional set of resource types which prevent instances from being validated\n :param verbose: Print more information\n :return: ValidatorStatus objects\n ' (sdefs, instances, deps, vs, cs, extensions) = parse_fsh_generated(path_output) for (k, v) in instances.items(): deduplicate_obi_codes(v['filename']) results = [] for (i, fname) in enumerate(fnames): if (not fname.exists()): raise FileNotFoundError(fname) (fsh_profiles, fsh_instances) = parse_fsh(fname) percent = (((i + 1) / len(fnames)) * 100) print(f'[{percent: 5.1f}%] Processing file {fname} with {len(fsh_profiles)} profiles and {len(fsh_instances)} instances ({(i + 1)}/{len(fnames)})') profiles_without_instance = check_instances_availability(fsh_profiles, fsh_instances, get_abstract_profile_ids(sdefs)) if len(profiles_without_instance): for p in profiles_without_instance: status = ValidatorStatus(status=ValidatorStatus.Status.FAILURE, errors=[f'No instances defined for profile {p}'], profile=p) status.pretty_print(with_header=True) results.append(status) continue fsh_instances_cleaned = [] for fsh_instance in fsh_instances: instance = instances[fsh_instance['instance']] if ((exclude_code_systems is not None) and any(((cs in exclude_code_systems) for cs in instance['codeSystems']))): status = ValidatorStatus(status=ValidatorStatus.Status.WARNING, warnings=[f"Skipped instance {fsh_instance['instance']} due to excluded code system(s) used in the instance"], profile=fsh_instance['instanceof']) status.pretty_print(with_header=True) results.append(status) elif ((exclude_resource_types is not None) and (instance['resourceType'] in exclude_resource_types)): status = ValidatorStatus(status=ValidatorStatus.Status.WARNING, warnings=[f"Skipped instance {fsh_instance['instance']} due to excluded resource type {instance['resourceType']}"], profile=fsh_instance['instanceof']) status.pretty_print(with_header=True) results.append(status) else: fsh_instances_cleaned.append(fsh_instance) results += run_validation(fname_validator, fsh_instances_cleaned, sdefs, instances, deps, vs, cs, extensions, fhir_version=fhir_version, verbose=verbose) return results
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 Instances defined in each FSH file\n - Run FHIR Java validator for each instance to validate it against its corresponding profile\n\n :param path_output: output path (of SUSHI project)\n :param fnames: FSH file names to validate (full paths)\n :param fname_validator: full path to FHIR Java validator file\n :param fhir_version: FHIR version to use in validator\n :param exclude_code_systems: Optional set of code systems which prevent instances from being validated\n :param exclude_resource_types: Optional set of resource types which prevent instances from being validated\n :param verbose: Print more information\n :return: ValidatorStatus objects\n ' (sdefs, instances, deps, vs, cs, extensions) = parse_fsh_generated(path_output) for (k, v) in instances.items(): deduplicate_obi_codes(v['filename']) results = [] for (i, fname) in enumerate(fnames): if (not fname.exists()): raise FileNotFoundError(fname) (fsh_profiles, fsh_instances) = parse_fsh(fname) percent = (((i + 1) / len(fnames)) * 100) print(f'[{percent: 5.1f}%] Processing file {fname} with {len(fsh_profiles)} profiles and {len(fsh_instances)} instances ({(i + 1)}/{len(fnames)})') profiles_without_instance = check_instances_availability(fsh_profiles, fsh_instances, get_abstract_profile_ids(sdefs)) if len(profiles_without_instance): for p in profiles_without_instance: status = ValidatorStatus(status=ValidatorStatus.Status.FAILURE, errors=[f'No instances defined for profile {p}'], profile=p) status.pretty_print(with_header=True) results.append(status) continue fsh_instances_cleaned = [] for fsh_instance in fsh_instances: instance = instances[fsh_instance['instance']] if ((exclude_code_systems is not None) and any(((cs in exclude_code_systems) for cs in instance['codeSystems']))): status = ValidatorStatus(status=ValidatorStatus.Status.WARNING, warnings=[f"Skipped instance {fsh_instance['instance']} due to excluded code system(s) used in the instance"], profile=fsh_instance['instanceof']) status.pretty_print(with_header=True) results.append(status) elif ((exclude_resource_types is not None) and (instance['resourceType'] in exclude_resource_types)): status = ValidatorStatus(status=ValidatorStatus.Status.WARNING, warnings=[f"Skipped instance {fsh_instance['instance']} due to excluded resource type {instance['resourceType']}"], profile=fsh_instance['instanceof']) status.pretty_print(with_header=True) results.append(status) else: fsh_instances_cleaned.append(fsh_instance) results += run_validation(fname_validator, fsh_instances_cleaned, sdefs, instances, deps, vs, cs, extensions, fhir_version=fhir_version, verbose=verbose) return results<|docstring|>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 path to FHIR Java validator file :param fhir_version: FHIR version to use in validator :param exclude_code_systems: Optional set of code systems which prevent instances from being validated :param exclude_resource_types: Optional set of resource types which prevent instances from being validated :param verbose: Print more information :return: ValidatorStatus objects<|endoftext|>
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 defined in FSH file\n - Run FHIR Java validator for each instance to validate it against its corresponding profile\n\n :param fsh_filename: FSH file names\n :param fname_validator: Full path to FHIR Java validator file\n :param fhir_version: FHIR version to use in validator\n :param exclude_code_systems: Optional set of code systems which prevent instances from being validated\n :param exclude_resource_types: Optional set of resource types which prevent instances from being validated\n :param verbose: Print more information\n :return: List of validation status, full output and instance and profile names\n ' (_, path_output) = get_paths(fsh_filenames[0].fsh_base_path()) return _validate_fsh_files(path_output=path_output, fnames=[f.absolute() for f in fsh_filenames], fname_validator=fname_validator, fhir_version=fhir_version, exclude_code_systems=exclude_code_systems, exclude_resource_types=exclude_resource_types, verbose=verbose)
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 use in validator :param exclude_code_systems: Optional set of code systems which prevent instances from being validated :param exclude_resource_types: Optional set of resource types which prevent instances from being validated :param verbose: Print more information :return: List of validation status, full output and instance and profile names
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 defined in FSH file\n - Run FHIR Java validator for each instance to validate it against its corresponding profile\n\n :param fsh_filename: FSH file names\n :param fname_validator: Full path to FHIR Java validator file\n :param fhir_version: FHIR version to use in validator\n :param exclude_code_systems: Optional set of code systems which prevent instances from being validated\n :param exclude_resource_types: Optional set of resource types which prevent instances from being validated\n :param verbose: Print more information\n :return: List of validation status, full output and instance and profile names\n ' (_, path_output) = get_paths(fsh_filenames[0].fsh_base_path()) return _validate_fsh_files(path_output=path_output, fnames=[f.absolute() for f in fsh_filenames], fname_validator=fname_validator, fhir_version=fhir_version, exclude_code_systems=exclude_code_systems, exclude_resource_types=exclude_resource_types, verbose=verbose)
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 defined in FSH file\n - Run FHIR Java validator for each instance to validate it against its corresponding profile\n\n :param fsh_filename: FSH file names\n :param fname_validator: Full path to FHIR Java validator file\n :param fhir_version: FHIR version to use in validator\n :param exclude_code_systems: Optional set of code systems which prevent instances from being validated\n :param exclude_resource_types: Optional set of resource types which prevent instances from being validated\n :param verbose: Print more information\n :return: List of validation status, full output and instance and profile names\n ' (_, path_output) = get_paths(fsh_filenames[0].fsh_base_path()) return _validate_fsh_files(path_output=path_output, fnames=[f.absolute() for f in fsh_filenames], fname_validator=fname_validator, fhir_version=fhir_version, exclude_code_systems=exclude_code_systems, exclude_resource_types=exclude_resource_types, verbose=verbose)<|docstring|>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 use in validator :param exclude_code_systems: Optional set of code systems which prevent instances from being validated :param exclude_resource_types: Optional set of resource types which prevent instances from being validated :param verbose: Print more information :return: List of validation status, full output and instance and profile names<|endoftext|>
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 Instances defined in FSH file\n - Run FHIR Java validator for each instance to validate it against its corresponding profile\n\n :param base_path: base path (of SUSHI project)\n :param subdir: subdirectory of profiles\n :param fname_validator: full path to FHIR Java validator file\n :param fhir_version: FHIR version to use in validator\n :param verbose: Print more information\n :param exclude_code_systems: Optional set of code systems which prevent instances from being validated\n :param exclude_resource_types: Optional set of resource types which prevent instances from being validated\n :return: List of validation status, full output and instance and profile names\n ' (path_input, path_output) = get_paths(base_path) path_full = (path_input / subdir) if (not path_full.exists()): raise FileNotFoundError(path_full) fnames = list(path_full.rglob('*.fsh')) sys.stdout.flush() return _validate_fsh_files(path_output=path_output, fnames=fnames, fname_validator=fname_validator, fhir_version=fhir_version, exclude_code_systems=exclude_code_systems, exclude_resource_types=exclude_resource_types, verbose=verbose)
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 to FHIR Java validator file :param fhir_version: FHIR version to use in validator :param verbose: Print more information :param exclude_code_systems: Optional set of code systems which prevent instances from being validated :param exclude_resource_types: Optional set of resource types which prevent instances from being validated :return: List of validation status, full output and instance and profile names
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 Instances defined in FSH file\n - Run FHIR Java validator for each instance to validate it against its corresponding profile\n\n :param base_path: base path (of SUSHI project)\n :param subdir: subdirectory of profiles\n :param fname_validator: full path to FHIR Java validator file\n :param fhir_version: FHIR version to use in validator\n :param verbose: Print more information\n :param exclude_code_systems: Optional set of code systems which prevent instances from being validated\n :param exclude_resource_types: Optional set of resource types which prevent instances from being validated\n :return: List of validation status, full output and instance and profile names\n ' (path_input, path_output) = get_paths(base_path) path_full = (path_input / subdir) if (not path_full.exists()): raise FileNotFoundError(path_full) fnames = list(path_full.rglob('*.fsh')) sys.stdout.flush() return _validate_fsh_files(path_output=path_output, fnames=fnames, fname_validator=fname_validator, fhir_version=fhir_version, exclude_code_systems=exclude_code_systems, exclude_resource_types=exclude_resource_types, verbose=verbose)
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 Instances defined in FSH file\n - Run FHIR Java validator for each instance to validate it against its corresponding profile\n\n :param base_path: base path (of SUSHI project)\n :param subdir: subdirectory of profiles\n :param fname_validator: full path to FHIR Java validator file\n :param fhir_version: FHIR version to use in validator\n :param verbose: Print more information\n :param exclude_code_systems: Optional set of code systems which prevent instances from being validated\n :param exclude_resource_types: Optional set of resource types which prevent instances from being validated\n :return: List of validation status, full output and instance and profile names\n ' (path_input, path_output) = get_paths(base_path) path_full = (path_input / subdir) if (not path_full.exists()): raise FileNotFoundError(path_full) fnames = list(path_full.rglob('*.fsh')) sys.stdout.flush() return _validate_fsh_files(path_output=path_output, fnames=fnames, fname_validator=fname_validator, fhir_version=fhir_version, exclude_code_systems=exclude_code_systems, exclude_resource_types=exclude_resource_types, verbose=verbose)<|docstring|>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 to FHIR Java validator file :param fhir_version: FHIR version to use in validator :param verbose: Print more information :param exclude_code_systems: Optional set of code systems which prevent instances from being validated :param exclude_resource_types: Optional set of resource types which prevent instances from being validated :return: List of validation status, full output and instance and profile names<|endoftext|>
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: List of instances defined in FSH file\n :param abstract_profiles: Set of abstract profiles\n :return: List of profiles without instances\n ' profiles_without_instance = [] for p in fsh_profiles: if (p['id'] in abstract_profiles): continue if (not any(((i['instanceof'] == p['id']) for i in fsh_instances))): profiles_without_instance.append(p['id']) return profiles_without_instance
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: List of instances defined in FSH file\n :param abstract_profiles: Set of abstract profiles\n :return: List of profiles without instances\n ' profiles_without_instance = [] for p in fsh_profiles: if (p['id'] in abstract_profiles): continue if (not any(((i['instanceof'] == p['id']) for i in fsh_instances))): profiles_without_instance.append(p['id']) return profiles_without_instance
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: List of instances defined in FSH file\n :param abstract_profiles: Set of abstract profiles\n :return: List of profiles without instances\n ' profiles_without_instance = [] for p in fsh_profiles: if (p['id'] in abstract_profiles): continue if (not any(((i['instanceof'] == p['id']) for i in fsh_instances))): profiles_without_instance.append(p['id']) return profiles_without_instance<|docstring|>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<|endoftext|>
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 FHIR validator.\n\n :param sdefs: StructureDefinitions from SUSHI output\n :param profile: Profile name to get all parents profiles of\n :return: List of all parent profiles of supplied profile name (including the profile itself)\n ' res: List[str] = [] def _traverse(profile, res): res.append(profile) if (sdefs[profile]['base'] in sdefs): _traverse(sdefs[profile]['base'], res) _traverse(profile, res) return res
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: Profile name to get all parents profiles of :return: List of all parent profiles of supplied profile name (including the profile itself)
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 FHIR validator.\n\n :param sdefs: StructureDefinitions from SUSHI output\n :param profile: Profile name to get all parents profiles of\n :return: List of all parent profiles of supplied profile name (including the profile itself)\n ' res: List[str] = [] def _traverse(profile, res): res.append(profile) if (sdefs[profile]['base'] in sdefs): _traverse(sdefs[profile]['base'], res) _traverse(profile, res) return res
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 FHIR validator.\n\n :param sdefs: StructureDefinitions from SUSHI output\n :param profile: Profile name to get all parents profiles of\n :return: List of all parent profiles of supplied profile name (including the profile itself)\n ' res: List[str] = [] def _traverse(profile, res): res.append(profile) if (sdefs[profile]['base'] in sdefs): _traverse(sdefs[profile]['base'], res) _traverse(profile, res) return res<|docstring|>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: Profile name to get all parents profiles of :return: List of all parent profiles of supplied profile name (including the profile itself)<|endoftext|>
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 parent profiles of supplied instance name (including the instance itself)\n ' profiles_processed = [] if (instance['resourceType'] == 'Bundle'): profiles_queue = ([instance['profile']] + instance['profilesAdditional']) else: profiles_queue = [instance['profile']] profiles_to_include = [] for profile in profiles_queue: if (profile in profiles_processed): continue profiles_processed.append(profile) if (profile in sdefs): profiles_queue += [p for p in sdefs[profile]['profilesAdditional'] if (p not in profiles_processed)] profile_chain = get_profile_chain(sdefs, profile) profiles_to_include += profile_chain profiles_to_include = set(profiles_to_include) return profiles_to_include
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 parent profiles of supplied instance name (including the instance itself)\n ' profiles_processed = [] if (instance['resourceType'] == 'Bundle'): profiles_queue = ([instance['profile']] + instance['profilesAdditional']) else: profiles_queue = [instance['profile']] profiles_to_include = [] for profile in profiles_queue: if (profile in profiles_processed): continue profiles_processed.append(profile) if (profile in sdefs): profiles_queue += [p for p in sdefs[profile]['profilesAdditional'] if (p not in profiles_processed)] profile_chain = get_profile_chain(sdefs, profile) profiles_to_include += profile_chain profiles_to_include = set(profiles_to_include) return profiles_to_include
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 parent profiles of supplied instance name (including the instance itself)\n ' profiles_processed = [] if (instance['resourceType'] == 'Bundle'): profiles_queue = ([instance['profile']] + instance['profilesAdditional']) else: profiles_queue = [instance['profile']] profiles_to_include = [] for profile in profiles_queue: if (profile in profiles_processed): continue profiles_processed.append(profile) if (profile in sdefs): profiles_queue += [p for p in sdefs[profile]['profilesAdditional'] if (p not in profiles_processed)] profile_chain = get_profile_chain(sdefs, profile) profiles_to_include += profile_chain profiles_to_include = set(profiles_to_include) return profiles_to_include<|docstring|>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)<|endoftext|>
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 path to FHIR Java validator file\n :param fsh_instances: List of instances defined in FSH file\n :param sdefs: StructureDefinitions from SUSHI output\n :param instances: Instance from SUSHI output\n :param deps: Dependencies from SUSHI output\n :param vs: ValueSets from SUSHI output\n :param cs: CodeSystems from SUSHI output\n :param extensions: Extensions from SUSHI output\n :param fhir_version: FHIR version to use in validator\n :param verbose: Print more information\n :return: List of validation result dicts containing validation status, full output and instance and profile names\n ' cmd_base = ['java', f'-jar {fname_validator}', f'-version {fhir_version}', '-txLog logs/txlog.html'] cmd_base += [f"-ig {dep['packageId']}#{dep['version']}" for dep in deps.values()] cmds = {} questionnaires = [i['filename'] for i in instances.values() if (i['resourceType'] == 'Questionnaire')] for fsh_instance in fsh_instances: if (not (fsh_instance['instance'] in instances)): raise Exception(f"Could not find {fsh_instance['instance']} in instances") instance = instances[fsh_instance['instance']] profiles_include = get_profiles_to_include(sdefs, instance) cmd = list(cmd_base) cmd += [f"-ig {sdefs[profile]['filename']}" for profile in profiles_include] cmd += [f"-ig {valueset['filename']}" for valueset in vs.values()] cmd += [f"-ig {codesystem['filename']}" for codesystem in cs.values()] cmd += [f"-ig {extension['filename']}" for extension in extensions.values()] cmd += [f'-ig {qs}' for qs in questionnaires if (qs != instance['filename'])] cmd += [f"-profile {instance['profile']}", instance['filename']] cmds[fsh_instance['instance']] = cmd results = [] for fsh_instance_name in cmds: print_box(f"Validating {fsh_instance_name} against profile {instances[fsh_instance_name]['profile']}") status = execute_validator(cmds[fsh_instance_name], verbose=verbose) status.instance = fsh_instance_name status.profile = instance['profile'] results.append(status) return results
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 output :param vs: ValueSets from SUSHI output :param cs: CodeSystems from SUSHI output :param extensions: Extensions from SUSHI output :param fhir_version: FHIR version to use in validator :param verbose: Print more information :return: List of validation result dicts containing validation status, full output and instance and profile names
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 path to FHIR Java validator file\n :param fsh_instances: List of instances defined in FSH file\n :param sdefs: StructureDefinitions from SUSHI output\n :param instances: Instance from SUSHI output\n :param deps: Dependencies from SUSHI output\n :param vs: ValueSets from SUSHI output\n :param cs: CodeSystems from SUSHI output\n :param extensions: Extensions from SUSHI output\n :param fhir_version: FHIR version to use in validator\n :param verbose: Print more information\n :return: List of validation result dicts containing validation status, full output and instance and profile names\n ' cmd_base = ['java', f'-jar {fname_validator}', f'-version {fhir_version}', '-txLog logs/txlog.html'] cmd_base += [f"-ig {dep['packageId']}#{dep['version']}" for dep in deps.values()] cmds = {} questionnaires = [i['filename'] for i in instances.values() if (i['resourceType'] == 'Questionnaire')] for fsh_instance in fsh_instances: if (not (fsh_instance['instance'] in instances)): raise Exception(f"Could not find {fsh_instance['instance']} in instances") instance = instances[fsh_instance['instance']] profiles_include = get_profiles_to_include(sdefs, instance) cmd = list(cmd_base) cmd += [f"-ig {sdefs[profile]['filename']}" for profile in profiles_include] cmd += [f"-ig {valueset['filename']}" for valueset in vs.values()] cmd += [f"-ig {codesystem['filename']}" for codesystem in cs.values()] cmd += [f"-ig {extension['filename']}" for extension in extensions.values()] cmd += [f'-ig {qs}' for qs in questionnaires if (qs != instance['filename'])] cmd += [f"-profile {instance['profile']}", instance['filename']] cmds[fsh_instance['instance']] = cmd results = [] for fsh_instance_name in cmds: print_box(f"Validating {fsh_instance_name} against profile {instances[fsh_instance_name]['profile']}") status = execute_validator(cmds[fsh_instance_name], verbose=verbose) status.instance = fsh_instance_name status.profile = instance['profile'] results.append(status) return results
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 path to FHIR Java validator file\n :param fsh_instances: List of instances defined in FSH file\n :param sdefs: StructureDefinitions from SUSHI output\n :param instances: Instance from SUSHI output\n :param deps: Dependencies from SUSHI output\n :param vs: ValueSets from SUSHI output\n :param cs: CodeSystems from SUSHI output\n :param extensions: Extensions from SUSHI output\n :param fhir_version: FHIR version to use in validator\n :param verbose: Print more information\n :return: List of validation result dicts containing validation status, full output and instance and profile names\n ' cmd_base = ['java', f'-jar {fname_validator}', f'-version {fhir_version}', '-txLog logs/txlog.html'] cmd_base += [f"-ig {dep['packageId']}#{dep['version']}" for dep in deps.values()] cmds = {} questionnaires = [i['filename'] for i in instances.values() if (i['resourceType'] == 'Questionnaire')] for fsh_instance in fsh_instances: if (not (fsh_instance['instance'] in instances)): raise Exception(f"Could not find {fsh_instance['instance']} in instances") instance = instances[fsh_instance['instance']] profiles_include = get_profiles_to_include(sdefs, instance) cmd = list(cmd_base) cmd += [f"-ig {sdefs[profile]['filename']}" for profile in profiles_include] cmd += [f"-ig {valueset['filename']}" for valueset in vs.values()] cmd += [f"-ig {codesystem['filename']}" for codesystem in cs.values()] cmd += [f"-ig {extension['filename']}" for extension in extensions.values()] cmd += [f'-ig {qs}' for qs in questionnaires if (qs != instance['filename'])] cmd += [f"-profile {instance['profile']}", instance['filename']] cmds[fsh_instance['instance']] = cmd results = [] for fsh_instance_name in cmds: print_box(f"Validating {fsh_instance_name} against profile {instances[fsh_instance_name]['profile']}") status = execute_validator(cmds[fsh_instance_name], verbose=verbose) status.instance = fsh_instance_name status.profile = instance['profile'] results.append(status) return results<|docstring|>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 output :param vs: ValueSets from SUSHI output :param cs: CodeSystems from SUSHI output :param extensions: Extensions from SUSHI output :param fhir_version: FHIR version to use in validator :param verbose: Print more information :return: List of validation result dicts containing validation status, full output and instance and profile names<|endoftext|>
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 = ' '.join([str(s) for s in cmd]) c = subprocess.run(cmd, shell=True) if (c.returncode != 0): raise CommandNotSuccessfulException()
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 = ' '.join([str(s) for s in cmd]) c = subprocess.run(cmd, shell=True) if (c.returncode != 0): raise CommandNotSuccessfulException()
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 = ' '.join([str(s) for s in cmd]) c = subprocess.run(cmd, shell=True) if (c.returncode != 0): raise CommandNotSuccessfulException()<|docstring|>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<|endoftext|>
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|>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<|endoftext|>
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\n " if isinstance(cmd, list): cmd = ' '.join([str(s) for s in cmd]) if verbose: print(cmd) popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True, shell=True) if (popen.stdout is None): return ValidatorStatus(status=ValidatorStatus.Status.FAILURE, errors=['popen failed']) output = [] for line in popen.stdout: if (verbose or (line.strip() in ['Loading', 'Validating'])): printc(line, col=bcolors.HEADER, end='') sys.stdout.flush() output.append(line) popen.stdout.close() popen.wait() try: status = ValidatorStatus().parse(output) status.pretty_print() except Exception: print('Could not parse validator output:', flush=True) print(''.join(output), flush=True) status = ValidatorStatus(status=ValidatorStatus.Status.FAILURE, errors=['Error during validator execution'], output=output) return status
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\n " if isinstance(cmd, list): cmd = ' '.join([str(s) for s in cmd]) if verbose: print(cmd) popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True, shell=True) if (popen.stdout is None): return ValidatorStatus(status=ValidatorStatus.Status.FAILURE, errors=['popen failed']) output = [] for line in popen.stdout: if (verbose or (line.strip() in ['Loading', 'Validating'])): printc(line, col=bcolors.HEADER, end=) sys.stdout.flush() output.append(line) popen.stdout.close() popen.wait() try: status = ValidatorStatus().parse(output) status.pretty_print() except Exception: print('Could not parse validator output:', flush=True) print(.join(output), flush=True) status = ValidatorStatus(status=ValidatorStatus.Status.FAILURE, errors=['Error during validator execution'], output=output) return status
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\n " if isinstance(cmd, list): cmd = ' '.join([str(s) for s in cmd]) if verbose: print(cmd) popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True, shell=True) if (popen.stdout is None): return ValidatorStatus(status=ValidatorStatus.Status.FAILURE, errors=['popen failed']) output = [] for line in popen.stdout: if (verbose or (line.strip() in ['Loading', 'Validating'])): printc(line, col=bcolors.HEADER, end=) sys.stdout.flush() output.append(line) popen.stdout.close() popen.wait() try: status = ValidatorStatus().parse(output) status.pretty_print() except Exception: print('Could not parse validator output:', flush=True) print(.join(output), flush=True) status = ValidatorStatus(status=ValidatorStatus.Status.FAILURE, errors=['Error during validator execution'], output=output) return status<|docstring|>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<|endoftext|>
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_fsh_files()\n :param log_path: Path where log files are stored\n :return: None\n ' dfs = [] output = '' for status in results: dfs.append(status.to_frame()) if (status.instance != ''): output += print_box(f'Validating {status.instance} on profile {status.profile}', print_str=False) else: output += print_box(f'Profile {status.profile}', print_str=False) output += ''.join(status.output) output += '\n\n' df = pd.concat([s.to_frame() for s in results]).reset_index(drop=True) log_basename = ('validation_' + datetime.now().strftime('%y%m%dT%H%M%S')) with open((log_path / (log_basename + '.log')), 'w') as f: f.write(output) df.to_excel((log_path / (log_basename + '.xlsx')), index=False) df.to_markdown((log_path / (log_basename + '.md')), index=False)
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_fsh_files()\n :param log_path: Path where log files are stored\n :return: None\n ' dfs = [] output = for status in results: dfs.append(status.to_frame()) if (status.instance != ): output += print_box(f'Validating {status.instance} on profile {status.profile}', print_str=False) else: output += print_box(f'Profile {status.profile}', print_str=False) output += .join(status.output) output += '\n\n' df = pd.concat([s.to_frame() for s in results]).reset_index(drop=True) log_basename = ('validation_' + datetime.now().strftime('%y%m%dT%H%M%S')) with open((log_path / (log_basename + '.log')), 'w') as f: f.write(output) df.to_excel((log_path / (log_basename + '.xlsx')), index=False) df.to_markdown((log_path / (log_basename + '.md')), index=False)
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_fsh_files()\n :param log_path: Path where log files are stored\n :return: None\n ' dfs = [] output = for status in results: dfs.append(status.to_frame()) if (status.instance != ): output += print_box(f'Validating {status.instance} on profile {status.profile}', print_str=False) else: output += print_box(f'Profile {status.profile}', print_str=False) output += .join(status.output) output += '\n\n' df = pd.concat([s.to_frame() for s in results]).reset_index(drop=True) log_basename = ('validation_' + datetime.now().strftime('%y%m%dT%H%M%S')) with open((log_path / (log_basename + '.log')), 'w') as f: f.write(output) df.to_excel((log_path / (log_basename + '.xlsx')), index=False) df.to_markdown((log_path / (log_basename + '.md')), index=False)<|docstring|>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<|endoftext|>
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()): raise FileNotFoundError(f'Could not find {conf_filename}') with open(conf_filename, 'r') as f: conf = yaml.safe_load(f) fhir_version = conf['fhirVersion'] return fhir_version
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()): raise FileNotFoundError(f'Could not find {conf_filename}') with open(conf_filename, 'r') as f: conf = yaml.safe_load(f) fhir_version = conf['fhirVersion'] return fhir_version
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()): raise FileNotFoundError(f'Could not find {conf_filename}') with open(conf_filename, 'r') as f: conf = yaml.safe_load(f) fhir_version = conf['fhirVersion'] return fhir_version<|docstring|>Get the FHIR version from the SUSHI config file. :param base_path: Path to the SUSHI config file :return: FHIR version string<|endoftext|>
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 Sushi is an executable on the system. :return: None<|endoftext|>
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 arguments for BaseException\n ' args = tuple(([msg] + list(args))) super().__init__(*args)
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 arguments for BaseException\n ' args = tuple(([msg] + list(args))) super().__init__(*args)
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 arguments for BaseException\n ' args = tuple(([msg] + list(args))) super().__init__(*args)<|docstring|>Shell command not successfully executed. :param msg: Message to display :param args: Other positional arguments for BaseException :param kwargs: Other keyword arguments for BaseException<|endoftext|>
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: status string\n :param errors: list of errors during parsing\n :param warnings: list of warnings during parsing\n :param profile: name of profile against which validation was performed\n :param instance: name of instance that was validated\n ' def list_if_none(v: Optional[List]) -> List: return ([] if (v is None) else v) self.status = status self.errors = list_if_none(errors) self.warnings: List[str] = list_if_none(warnings) self.notes: List[str] = [] self.n_errors = len(self.errors) self.n_warnings = len(self.warnings) self.n_notes = len(self.notes) self.output = list_if_none(output) self.profile = profile self.instance = instance
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 validated
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: status string\n :param errors: list of errors during parsing\n :param warnings: list of warnings during parsing\n :param profile: name of profile against which validation was performed\n :param instance: name of instance that was validated\n ' def list_if_none(v: Optional[List]) -> List: return ([] if (v is None) else v) self.status = status self.errors = list_if_none(errors) self.warnings: List[str] = list_if_none(warnings) self.notes: List[str] = [] self.n_errors = len(self.errors) self.n_warnings = len(self.warnings) self.n_notes = len(self.notes) self.output = list_if_none(output) self.profile = profile self.instance = instance
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: status string\n :param errors: list of errors during parsing\n :param warnings: list of warnings during parsing\n :param profile: name of profile against which validation was performed\n :param instance: name of instance that was validated\n ' def list_if_none(v: Optional[List]) -> List: return ([] if (v is None) else v) self.status = status self.errors = list_if_none(errors) self.warnings: List[str] = list_if_none(warnings) self.notes: List[str] = [] self.n_errors = len(self.errors) self.n_warnings = len(self.warnings) self.n_notes = len(self.notes) self.output = list_if_none(output) self.profile = profile self.instance = instance<|docstring|>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 validated<|endoftext|>
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_notes>\\d+) notes') pattern_error = re.compile(' (Error @ .*)') pattern_warn = re.compile(' (Warning @ .*)') pattern_note = re.compile(' (Information @ .*)') self.output = output output_s = ''.join(output) m = pattern_status.search(output_s) status_map = {'Success': ValidatorStatus.Status.SUCCESS, '*FAILURE*': ValidatorStatus.Status.FAILURE} self.status = status_map[m.group(1)] (self.n_errors, self.n_warnings, self.n_notes) = (int(m.group((i + 2))) for i in range(3)) self.errors = [m.group().strip() for m in pattern_error.finditer(output_s)] self.warnings = [m.group().strip() for m in pattern_warn.finditer(output_s)] self.notes = [m.group().strip() for m in pattern_note.finditer(output_s)] if ((self.status == ValidatorStatus.Status.SUCCESS) and (len(self.warnings) > 0)): self.status = ValidatorStatus.Status.WARNING return self
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_notes>\\d+) notes') pattern_error = re.compile(' (Error @ .*)') pattern_warn = re.compile(' (Warning @ .*)') pattern_note = re.compile(' (Information @ .*)') self.output = output output_s = .join(output) m = pattern_status.search(output_s) status_map = {'Success': ValidatorStatus.Status.SUCCESS, '*FAILURE*': ValidatorStatus.Status.FAILURE} self.status = status_map[m.group(1)] (self.n_errors, self.n_warnings, self.n_notes) = (int(m.group((i + 2))) for i in range(3)) self.errors = [m.group().strip() for m in pattern_error.finditer(output_s)] self.warnings = [m.group().strip() for m in pattern_warn.finditer(output_s)] self.notes = [m.group().strip() for m in pattern_note.finditer(output_s)] if ((self.status == ValidatorStatus.Status.SUCCESS) and (len(self.warnings) > 0)): self.status = ValidatorStatus.Status.WARNING return self
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_notes>\\d+) notes') pattern_error = re.compile(' (Error @ .*)') pattern_warn = re.compile(' (Warning @ .*)') pattern_note = re.compile(' (Information @ .*)') self.output = output output_s = .join(output) m = pattern_status.search(output_s) status_map = {'Success': ValidatorStatus.Status.SUCCESS, '*FAILURE*': ValidatorStatus.Status.FAILURE} self.status = status_map[m.group(1)] (self.n_errors, self.n_warnings, self.n_notes) = (int(m.group((i + 2))) for i in range(3)) self.errors = [m.group().strip() for m in pattern_error.finditer(output_s)] self.warnings = [m.group().strip() for m in pattern_warn.finditer(output_s)] self.notes = [m.group().strip() for m in pattern_note.finditer(output_s)] if ((self.status == ValidatorStatus.Status.SUCCESS) and (len(self.warnings) > 0)): self.status = ValidatorStatus.Status.WARNING return self<|docstring|>Parse FHIR Validator output. :param output: Output of a validator run :return: None<|endoftext|>
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(f'Profile {self.profile}') if (self.n_errors > 0): col = bcolors.FAIL elif (self.n_warnings > 0): col = bcolors.WARNING else: col = bcolors.OKGREEN printc(f'{bcolors.BOLD}{self.status.value.title()}: {self.n_errors} errors, {self.n_warnings} warnings, {self.n_notes} notes', col) for msg in self.errors: printc(f' {msg}', bcolors.FAIL) for msg in self.warnings: printc(f' {msg}', bcolors.WARNING) for msg in self.notes: print(f' {msg}') sys.stdout.flush()
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(f'Profile {self.profile}') if (self.n_errors > 0): col = bcolors.FAIL elif (self.n_warnings > 0): col = bcolors.WARNING else: col = bcolors.OKGREEN printc(f'{bcolors.BOLD}{self.status.value.title()}: {self.n_errors} errors, {self.n_warnings} warnings, {self.n_notes} notes', col) for msg in self.errors: printc(f' {msg}', bcolors.FAIL) for msg in self.warnings: printc(f' {msg}', bcolors.WARNING) for msg in self.notes: print(f' {msg}') sys.stdout.flush()
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(f'Profile {self.profile}') if (self.n_errors > 0): col = bcolors.FAIL elif (self.n_warnings > 0): col = bcolors.WARNING else: col = bcolors.OKGREEN printc(f'{bcolors.BOLD}{self.status.value.title()}: {self.n_errors} errors, {self.n_warnings} warnings, {self.n_notes} notes', col) for msg in self.errors: printc(f' {msg}', bcolors.FAIL) for msg in self.warnings: printc(f' {msg}', bcolors.WARNING) for msg in self.notes: print(f' {msg}') sys.stdout.flush()<|docstring|>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<|endoftext|>
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<|endoftext|>
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])<|docstring|>Get status as pandas DataFrame. :return: Status as DataFrame<|endoftext|>
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): expressionVector = loadPointsInRange(bdir('positive_cells.npy'), ValidationRange) else: expressionVector = loadPointsInRange(expressedPoints, ValidationRange) if os.path.isfile(bdir('ground_truth.npy')): GroundTruth = np.loadtxt(bdir('Log.txt')) np.save(bdir('ground_truth.npy'), GroundTruth) GroundTruth = loadPointsInRange(bdir('ground_truth.npy'), ValidationRange) else: GroundTruth = loadPointsInRange(bdir('ground_truth.npy'), ValidationRange) nucleiVector = loadPointsInRange(bdir('spots_filtered.npy'), ValidationRange) print('Number of total nuclei detected:', nucleiVector.shape[0]) print('Number of cells in ground truth:', GroundTruth.shape[0]) print('Number of detected cells:', expressionVector.shape[0]) if (num_workers <= 1): start = time.time() accuracy = unParallelAccuracy(CorrectThreshold, DataResolution, GroundTruth, expressionVector) print('Serial time elapsed:', (time.time() - start)) else: (F1, precision, recall, TP, accuracy) = computeAccuracy(CorrectThreshold, DataResolution, GroundTruth, expressionVector, num_workers, nucleiVector) print('F1 score:', F1) print('Precision (TP/(TP + FP)):', precision) print('Recall (TP/(TP + FN)):', recall) if considerUnaccountedFor: if (not os.path.isfile(bdir('nuclei_counted.npy'))): accountedFor = [] for i in range(GroundTruth.shape[0]): found = False j = 0 while ((j < len(nucleiVector)) and (found == False)): if (distanceBetweenPoints(DataResolution, GroundTruth[i], nucleiVector[j]) <= CorrectThreshold): found = True accountedFor.append(nucleiVector[j]) j += 1 np.save(bdir('nuclei_counted.npy'), np.asarray(accountedFor)) numUnaccounted = (GroundTruth.shape[0] - len(accountedFor)) accountedFor = np.asarray(accountedFor) print('Number of unaccounted for:', numUnaccounted) else: accountedFor = loadPointsInRange(bdir('nuclei_counted.npy'), ValidationRange) F1_mod = ((2 * TP) / (expressionVector.shape[0] + len(accountedFor))) recall_mod = (TP / len(accountedFor)) print('Modified recall:', recall_mod) print('Modified F1 score:', F1_mod) else: F1_mod = F1 recall_mod = recall if visualizeErrors: for i in range(len(ValidationRange)): Rnge = ValidationRange[i] overlay = plt.overlayPoints(DataFile, accountedFor, pointColor=None, **Rnge) overlay2 = plt.overlayPoints(DataFile, expressionVector, pointColor=None, **Rnge) overlay = np.concatenate((overlay, overlay2[(:, :, :, 1:)]), axis=3) io.writeData(bdir(('groundtruth_overlaid_%d.tif' % i)), overlay) return (F1_mod, precision, recall_mod, recall)
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(bdir('positive_cells.npy'), ValidationRange) else: expressionVector = loadPointsInRange(expressedPoints, ValidationRange) if os.path.isfile(bdir('ground_truth.npy')): GroundTruth = np.loadtxt(bdir('Log.txt')) np.save(bdir('ground_truth.npy'), GroundTruth) GroundTruth = loadPointsInRange(bdir('ground_truth.npy'), ValidationRange) else: GroundTruth = loadPointsInRange(bdir('ground_truth.npy'), ValidationRange) nucleiVector = loadPointsInRange(bdir('spots_filtered.npy'), ValidationRange) print('Number of total nuclei detected:', nucleiVector.shape[0]) print('Number of cells in ground truth:', GroundTruth.shape[0]) print('Number of detected cells:', expressionVector.shape[0]) if (num_workers <= 1): start = time.time() accuracy = unParallelAccuracy(CorrectThreshold, DataResolution, GroundTruth, expressionVector) print('Serial time elapsed:', (time.time() - start)) else: (F1, precision, recall, TP, accuracy) = computeAccuracy(CorrectThreshold, DataResolution, GroundTruth, expressionVector, num_workers, nucleiVector) print('F1 score:', F1) print('Precision (TP/(TP + FP)):', precision) print('Recall (TP/(TP + FN)):', recall) if considerUnaccountedFor: if (not os.path.isfile(bdir('nuclei_counted.npy'))): accountedFor = [] for i in range(GroundTruth.shape[0]): found = False j = 0 while ((j < len(nucleiVector)) and (found == False)): if (distanceBetweenPoints(DataResolution, GroundTruth[i], nucleiVector[j]) <= CorrectThreshold): found = True accountedFor.append(nucleiVector[j]) j += 1 np.save(bdir('nuclei_counted.npy'), np.asarray(accountedFor)) numUnaccounted = (GroundTruth.shape[0] - len(accountedFor)) accountedFor = np.asarray(accountedFor) print('Number of unaccounted for:', numUnaccounted) else: accountedFor = loadPointsInRange(bdir('nuclei_counted.npy'), ValidationRange) F1_mod = ((2 * TP) / (expressionVector.shape[0] + len(accountedFor))) recall_mod = (TP / len(accountedFor)) print('Modified recall:', recall_mod) print('Modified F1 score:', F1_mod) else: F1_mod = F1 recall_mod = recall if visualizeErrors: for i in range(len(ValidationRange)): Rnge = ValidationRange[i] overlay = plt.overlayPoints(DataFile, accountedFor, pointColor=None, **Rnge) overlay2 = plt.overlayPoints(DataFile, expressionVector, pointColor=None, **Rnge) overlay = np.concatenate((overlay, overlay2[(:, :, :, 1:)]), axis=3) io.writeData(bdir(('groundtruth_overlaid_%d.tif' % i)), overlay) return (F1_mod, precision, recall_mod, recall)
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(bdir('positive_cells.npy'), ValidationRange) else: expressionVector = loadPointsInRange(expressedPoints, ValidationRange) if os.path.isfile(bdir('ground_truth.npy')): GroundTruth = np.loadtxt(bdir('Log.txt')) np.save(bdir('ground_truth.npy'), GroundTruth) GroundTruth = loadPointsInRange(bdir('ground_truth.npy'), ValidationRange) else: GroundTruth = loadPointsInRange(bdir('ground_truth.npy'), ValidationRange) nucleiVector = loadPointsInRange(bdir('spots_filtered.npy'), ValidationRange) print('Number of total nuclei detected:', nucleiVector.shape[0]) print('Number of cells in ground truth:', GroundTruth.shape[0]) print('Number of detected cells:', expressionVector.shape[0]) if (num_workers <= 1): start = time.time() accuracy = unParallelAccuracy(CorrectThreshold, DataResolution, GroundTruth, expressionVector) print('Serial time elapsed:', (time.time() - start)) else: (F1, precision, recall, TP, accuracy) = computeAccuracy(CorrectThreshold, DataResolution, GroundTruth, expressionVector, num_workers, nucleiVector) print('F1 score:', F1) print('Precision (TP/(TP + FP)):', precision) print('Recall (TP/(TP + FN)):', recall) if considerUnaccountedFor: if (not os.path.isfile(bdir('nuclei_counted.npy'))): accountedFor = [] for i in range(GroundTruth.shape[0]): found = False j = 0 while ((j < len(nucleiVector)) and (found == False)): if (distanceBetweenPoints(DataResolution, GroundTruth[i], nucleiVector[j]) <= CorrectThreshold): found = True accountedFor.append(nucleiVector[j]) j += 1 np.save(bdir('nuclei_counted.npy'), np.asarray(accountedFor)) numUnaccounted = (GroundTruth.shape[0] - len(accountedFor)) accountedFor = np.asarray(accountedFor) print('Number of unaccounted for:', numUnaccounted) else: accountedFor = loadPointsInRange(bdir('nuclei_counted.npy'), ValidationRange) F1_mod = ((2 * TP) / (expressionVector.shape[0] + len(accountedFor))) recall_mod = (TP / len(accountedFor)) print('Modified recall:', recall_mod) print('Modified F1 score:', F1_mod) else: F1_mod = F1 recall_mod = recall if visualizeErrors: for i in range(len(ValidationRange)): Rnge = ValidationRange[i] overlay = plt.overlayPoints(DataFile, accountedFor, pointColor=None, **Rnge) overlay2 = plt.overlayPoints(DataFile, expressionVector, pointColor=None, **Rnge) overlay = np.concatenate((overlay, overlay2[(:, :, :, 1:)]), axis=3) io.writeData(bdir(('groundtruth_overlaid_%d.tif' % i)), overlay) return (F1_mod, precision, recall_mod, recall)<|docstring|>Main script for cell phenotype validation.<|endoftext|>
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 object with a write() method that accepts a\n single string.\n ' for row in rowreader: rowwriter.writerow((r.strip() for r in row))
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 object with a write() method that accepts a\n single string.\n ' for row in rowreader: rowwriter.writerow((r.strip() for r in row))
@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 object with a write() method that accepts a\n single string.\n ' for row in rowreader: rowwriter.writerow((r.strip() for r in row))<|docstring|>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.<|endoftext|>
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 -------------------------\n This is a wrapper of the TransE implementation from the\n PyKeen library. Please refer to the PyKeen library documentation\n for details and posssible errors regarding this model.\n\n Parameters\n -------------------------\n embedding_size: int = 100\n The dimension of the embedding to compute.\n scoring_fct_norm: int = 2\n Norm exponent to use in the loss.\n epochs: int = 100\n The number of epochs to use to train the model for.\n batch_size: int = 2**10\n Size of the training batch.\n device: str = "auto"\n The devide to use to train the model.\n Can either be cpu or cuda.\n training_loop: Union[str, Type[TrainingLoop]\n ] = "Stochastic Local Closed World Assumption"\n The training loop to use to train the model.\n Can either be:\n - Stochastic Local Closed World Assumption\n - Local Closed World Assumption\n random_state: int = 42\n Random seed to use while training the model\n enable_cache: bool = False\n Whether to enable the cache, that is to\n store the computed embedding.\n ' self._scoring_fct_norm = scoring_fct_norm super().__init__(embedding_size=embedding_size, epochs=epochs, batch_size=batch_size, training_loop=training_loop, random_state=random_state, enable_cache=enable_cache)
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 dimension of the embedding to compute. scoring_fct_norm: int = 2 Norm exponent to use in the loss. epochs: int = 100 The number of epochs to use to train the model for. batch_size: int = 2**10 Size of the training batch. device: str = "auto" The devide to use to train the model. Can either be cpu or cuda. training_loop: Union[str, Type[TrainingLoop] ] = "Stochastic Local Closed World Assumption" The training loop to use to train the model. Can either be: - Stochastic Local Closed World Assumption - Local Closed World Assumption random_state: int = 42 Random seed to use while training the model enable_cache: bool = False Whether to enable the cache, that is to store the computed embedding.
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 -------------------------\n This is a wrapper of the TransE implementation from the\n PyKeen library. Please refer to the PyKeen library documentation\n for details and posssible errors regarding this model.\n\n Parameters\n -------------------------\n embedding_size: int = 100\n The dimension of the embedding to compute.\n scoring_fct_norm: int = 2\n Norm exponent to use in the loss.\n epochs: int = 100\n The number of epochs to use to train the model for.\n batch_size: int = 2**10\n Size of the training batch.\n device: str = "auto"\n The devide to use to train the model.\n Can either be cpu or cuda.\n training_loop: Union[str, Type[TrainingLoop]\n ] = "Stochastic Local Closed World Assumption"\n The training loop to use to train the model.\n Can either be:\n - Stochastic Local Closed World Assumption\n - Local Closed World Assumption\n random_state: int = 42\n Random seed to use while training the model\n enable_cache: bool = False\n Whether to enable the cache, that is to\n store the computed embedding.\n ' self._scoring_fct_norm = scoring_fct_norm super().__init__(embedding_size=embedding_size, epochs=epochs, batch_size=batch_size, training_loop=training_loop, random_state=random_state, enable_cache=enable_cache)
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 -------------------------\n This is a wrapper of the TransE implementation from the\n PyKeen library. Please refer to the PyKeen library documentation\n for details and posssible errors regarding this model.\n\n Parameters\n -------------------------\n embedding_size: int = 100\n The dimension of the embedding to compute.\n scoring_fct_norm: int = 2\n Norm exponent to use in the loss.\n epochs: int = 100\n The number of epochs to use to train the model for.\n batch_size: int = 2**10\n Size of the training batch.\n device: str = "auto"\n The devide to use to train the model.\n Can either be cpu or cuda.\n training_loop: Union[str, Type[TrainingLoop]\n ] = "Stochastic Local Closed World Assumption"\n The training loop to use to train the model.\n Can either be:\n - Stochastic Local Closed World Assumption\n - Local Closed World Assumption\n random_state: int = 42\n Random seed to use while training the model\n enable_cache: bool = False\n Whether to enable the cache, that is to\n store the computed embedding.\n ' self._scoring_fct_norm = scoring_fct_norm super().__init__(embedding_size=embedding_size, epochs=epochs, batch_size=batch_size, training_loop=training_loop, random_state=random_state, enable_cache=enable_cache)<|docstring|>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 dimension of the embedding to compute. scoring_fct_norm: int = 2 Norm exponent to use in the loss. epochs: int = 100 The number of epochs to use to train the model for. batch_size: int = 2**10 Size of the training batch. device: str = "auto" The devide to use to train the model. Can either be cpu or cuda. training_loop: Union[str, Type[TrainingLoop] ] = "Stochastic Local Closed World Assumption" The training loop to use to train the model. Can either be: - Stochastic Local Closed World Assumption - Local Closed World Assumption random_state: int = 42 Random seed to use while training the model enable_cache: bool = False Whether to enable the cache, that is to store the computed embedding.<|endoftext|>
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._embedding_size, scoring_fct_norm=self._scoring_fct_norm)
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._embedding_size, scoring_fct_norm=self._scoring_fct_norm)
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._embedding_size, scoring_fct_norm=self._scoring_fct_norm)<|docstring|>Build new TransE model for embedding. Parameters ------------------ graph: Graph The graph to build the model for.<|endoftext|>
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): if (pattern_type in PATTERNS): raise ValueError('Cannot have two patterns with the same name') PATTERNS[pattern_type] = cls return cls return decorator_pattern
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): if (pattern_type in PATTERNS): raise ValueError('Cannot have two patterns with the same name') PATTERNS[pattern_type] = cls return cls return decorator_pattern
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): if (pattern_type in PATTERNS): raise ValueError('Cannot have two patterns with the same name') PATTERNS[pattern_type] = cls return cls return decorator_pattern<|docstring|>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.<|endoftext|>
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 = [] while inspection_list: current = inspection_list.pop() if (current in visited): continue visited.append(current) if issubclass(current, DBComments): if hasattr(current, 'db_column_supplemental_comments'): for (column, comment) in current.db_column_supplemental_comments.items(): column_comments[column] = comment inspection_list = (inspection_list + list(current.__bases__)) return column_comments
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() if (current in visited): continue visited.append(current) if issubclass(current, DBComments): if hasattr(current, 'db_column_supplemental_comments'): for (column, comment) in current.db_column_supplemental_comments.items(): column_comments[column] = comment inspection_list = (inspection_list + list(current.__bases__)) return column_comments
@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() if (current in visited): continue visited.append(current) if issubclass(current, DBComments): if hasattr(current, 'db_column_supplemental_comments'): for (column, comment) in current.db_column_supplemental_comments.items(): column_comments[column] = comment inspection_list = (inspection_list + list(current.__bases__)) return column_comments<|docstring|>database table column comments, including supplemental overrides<|endoftext|>
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[(:, :, 0)] = (prediction[(:, :, 0)] - (prediction[(:, :, 2)] / 2)) box_corner[(:, :, 1)] = (prediction[(:, :, 1)] - (prediction[(:, :, 3)] / 2)) box_corner[(:, :, 2)] = (prediction[(:, :, 0)] + (prediction[(:, :, 2)] / 2)) box_corner[(:, :, 3)] = (prediction[(:, :, 1)] + (prediction[(:, :, 3)] / 2)) prediction[(:, :, :4)] = box_corner[(:, :, :4)] output = [None for _ in range(len(prediction))] for (i, image_pred) in enumerate(prediction): (class_conf, class_pred) = torch.max(image_pred[(:, 5:(5 + num_classes))], 1, keepdim=True) conf_mask = ((image_pred[(:, 4)] * class_conf[(:, 0)]) >= conf_thres).squeeze() image_pred = image_pred[conf_mask] class_conf = class_conf[conf_mask] class_pred = class_pred[conf_mask] if (not image_pred.size(0)): continue detections = torch.cat((image_pred[(:, :5)], class_conf.float(), class_pred.float()), 1) unique_labels = detections[(:, (- 1))].cpu().unique() if prediction.is_cuda: unique_labels = unique_labels.cuda() detections = detections.cuda() for c in unique_labels: detections_class = detections[(detections[(:, (- 1))] == c)] keep = nms(detections_class[(:, :4)], (detections_class[(:, 4)] * detections_class[(:, 5)]), nms_thres) max_detections = detections_class[keep] output[i] = (max_detections if (output[i] is None) else torch.cat((output[i], max_detections))) if (output[i] is not None): output[i] = output[i].cpu().numpy() (box_xy, box_wh) = (((output[i][(:, 0:2)] + output[i][(:, 2:4)]) / 2), (output[i][(:, 2:4)] - output[i][(:, 0:2)])) output[i][(:, :4)] = self.yolo_correct_boxes(box_xy, box_wh, input_shape, image_shape, letterbox_image) return output
原图上的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[(:, :, 0)] = (prediction[(:, :, 0)] - (prediction[(:, :, 2)] / 2)) box_corner[(:, :, 1)] = (prediction[(:, :, 1)] - (prediction[(:, :, 3)] / 2)) box_corner[(:, :, 2)] = (prediction[(:, :, 0)] + (prediction[(:, :, 2)] / 2)) box_corner[(:, :, 3)] = (prediction[(:, :, 1)] + (prediction[(:, :, 3)] / 2)) prediction[(:, :, :4)] = box_corner[(:, :, :4)] output = [None for _ in range(len(prediction))] for (i, image_pred) in enumerate(prediction): (class_conf, class_pred) = torch.max(image_pred[(:, 5:(5 + num_classes))], 1, keepdim=True) conf_mask = ((image_pred[(:, 4)] * class_conf[(:, 0)]) >= conf_thres).squeeze() image_pred = image_pred[conf_mask] class_conf = class_conf[conf_mask] class_pred = class_pred[conf_mask] if (not image_pred.size(0)): continue detections = torch.cat((image_pred[(:, :5)], class_conf.float(), class_pred.float()), 1) unique_labels = detections[(:, (- 1))].cpu().unique() if prediction.is_cuda: unique_labels = unique_labels.cuda() detections = detections.cuda() for c in unique_labels: detections_class = detections[(detections[(:, (- 1))] == c)] keep = nms(detections_class[(:, :4)], (detections_class[(:, 4)] * detections_class[(:, 5)]), nms_thres) max_detections = detections_class[keep] output[i] = (max_detections if (output[i] is None) else torch.cat((output[i], max_detections))) if (output[i] is not None): output[i] = output[i].cpu().numpy() (box_xy, box_wh) = (((output[i][(:, 0:2)] + output[i][(:, 2:4)]) / 2), (output[i][(:, 2:4)] - output[i][(:, 0:2)])) output[i][(:, :4)] = self.yolo_correct_boxes(box_xy, box_wh, input_shape, image_shape, letterbox_image) return output
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[(:, :, 0)] = (prediction[(:, :, 0)] - (prediction[(:, :, 2)] / 2)) box_corner[(:, :, 1)] = (prediction[(:, :, 1)] - (prediction[(:, :, 3)] / 2)) box_corner[(:, :, 2)] = (prediction[(:, :, 0)] + (prediction[(:, :, 2)] / 2)) box_corner[(:, :, 3)] = (prediction[(:, :, 1)] + (prediction[(:, :, 3)] / 2)) prediction[(:, :, :4)] = box_corner[(:, :, :4)] output = [None for _ in range(len(prediction))] for (i, image_pred) in enumerate(prediction): (class_conf, class_pred) = torch.max(image_pred[(:, 5:(5 + num_classes))], 1, keepdim=True) conf_mask = ((image_pred[(:, 4)] * class_conf[(:, 0)]) >= conf_thres).squeeze() image_pred = image_pred[conf_mask] class_conf = class_conf[conf_mask] class_pred = class_pred[conf_mask] if (not image_pred.size(0)): continue detections = torch.cat((image_pred[(:, :5)], class_conf.float(), class_pred.float()), 1) unique_labels = detections[(:, (- 1))].cpu().unique() if prediction.is_cuda: unique_labels = unique_labels.cuda() detections = detections.cuda() for c in unique_labels: detections_class = detections[(detections[(:, (- 1))] == c)] keep = nms(detections_class[(:, :4)], (detections_class[(:, 4)] * detections_class[(:, 5)]), nms_thres) max_detections = detections_class[keep] output[i] = (max_detections if (output[i] is None) else torch.cat((output[i], max_detections))) if (output[i] is not None): output[i] = output[i].cpu().numpy() (box_xy, box_wh) = (((output[i][(:, 0:2)] + output[i][(:, 2:4)]) / 2), (output[i][(:, 2:4)] - output[i][(:, 0:2)])) output[i][(:, :4)] = self.yolo_correct_boxes(box_xy, box_wh, input_shape, image_shape, letterbox_image) return output<|docstring|>原图上的box,首先利用conf_thres进行第一轮筛选,再进行非极大值抑制。当然conf_thres=0.5, nms_thres=0.4 都是默认值,是可以被修改的。nms_thres的值越小,nms越严格<|endoftext|>
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 (sha1, gzipped_data)
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(type + len + data), gzipped_data)<|endoftext|>
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(sha1) object_graph[sha1] = obj if isinstance(obj, Tree): for entry in obj.entries: get_connected_objects(entry.sha1, object_graph) elif isinstance(obj, Commit): get_connected_objects(obj.tree, object_graph) for parent in obj.parent: get_connected_objects(parent, object_graph) return object_graph
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(sha1) object_graph[sha1] = obj if isinstance(obj, Tree): for entry in obj.entries: get_connected_objects(entry.sha1, object_graph) elif isinstance(obj, Commit): get_connected_objects(obj.tree, object_graph) for parent in obj.parent: get_connected_objects(parent, object_graph) return object_graph
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(sha1) object_graph[sha1] = obj if isinstance(obj, Tree): for entry in obj.entries: get_connected_objects(entry.sha1, object_graph) elif isinstance(obj, Commit): get_connected_objects(obj.tree, object_graph) for parent in obj.parent: get_connected_objects(parent, object_graph) return object_graph<|docstring|>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}<|endoftext|>
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 help formatter failed, falling back.') return formatter
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.') return formatter
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.') return formatter<|docstring|>Return a wider HelpFormatter, if possible.<|endoftext|>
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() self.write_bmx_reg(self._BMX160_COMMAND_REG_ADDR, 17) time.sleep(0.05) self.write_bmx_reg(self._BMX160_COMMAND_REG_ADDR, 21) time.sleep(0.1) self.write_bmx_reg(self._BMX160_COMMAND_REG_ADDR, 25) time.sleep(0.01) self.set_magn_conf() return True
! @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() self.write_bmx_reg(self._BMX160_COMMAND_REG_ADDR, 17) time.sleep(0.05) self.write_bmx_reg(self._BMX160_COMMAND_REG_ADDR, 21) time.sleep(0.1) self.write_bmx_reg(self._BMX160_COMMAND_REG_ADDR, 25) time.sleep(0.01) self.set_magn_conf() return True
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() self.write_bmx_reg(self._BMX160_COMMAND_REG_ADDR, 17) time.sleep(0.05) self.write_bmx_reg(self._BMX160_COMMAND_REG_ADDR, 21) time.sleep(0.1) self.write_bmx_reg(self._BMX160_COMMAND_REG_ADDR, 25) time.sleep(0.01) self.set_magn_conf() return True<|docstring|>! @brief initialization the i2c. @return returns the initialization status @retval True Initialization succeeded @retval False Initialization failed<|endoftext|>