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 |
|---|---|---|---|---|---|---|---|---|---|
572174e23411f312d2be85eab599c7d6661c91cffead052a789c47414a46754c | def reduce_dimension(self, raw_data, cleaned_data, id_col_name, to_lower_dim_filename=None, field_weights=None, to_dim=1, batch_size=1000, training_epoch=10, verbose=True, patience=60, patience_increase=2, improvement_threshold=0.9995):
'\n Reduce dimension of datasets for further clustering in lower dimension\n space.\n dat: pandas dataframe\n Data in the form just before being taken sigmoid.\n\n id_col_name: string\n The id/pk column name.\n\n to_dim: int\n The lower dimension the datasets reduced to.\n\n clustering_features: list of strings\n The features to reduce.\n\n batch_size: int\n The size of minibatch in statistic gradient descent.\n\n training_epoch: int\n The number of epochs to train the neuronetwork.\n\n '
self.raw_data = raw_data
self.id_col_name = id_col_name
self.cleaned_data = cleaned_data
if (to_lower_dim_filename is not None):
with open(to_lower_dim_filename, 'rb') as f:
to_lower_dim = pk.load(f)
self.one_dim_data = to_lower_dim(self.cleaned_data)
else:
self.da_reduce_dim(self.cleaned_data, field_weights=field_weights, to_dim=to_dim, batch_size=batch_size, training_epochs=training_epoch, verbose=verbose, patience=patience, patience_increase=patience_increase, improvement_threshold=improvement_threshold)
self.one_dim_data = self.to_lower_dim(self.cleaned_data) | Reduce dimension of datasets for further clustering in lower dimension
space.
dat: pandas dataframe
Data in the form just before being taken sigmoid.
id_col_name: string
The id/pk column name.
to_dim: int
The lower dimension the datasets reduced to.
clustering_features: list of strings
The features to reduce.
batch_size: int
The size of minibatch in statistic gradient descent.
training_epoch: int
The number of epochs to train the neuronetwork. | clusteror/implementation_layer.py | reduce_dimension | enfeizhan/clusteror | 0 | python | def reduce_dimension(self, raw_data, cleaned_data, id_col_name, to_lower_dim_filename=None, field_weights=None, to_dim=1, batch_size=1000, training_epoch=10, verbose=True, patience=60, patience_increase=2, improvement_threshold=0.9995):
'\n Reduce dimension of datasets for further clustering in lower dimension\n space.\n dat: pandas dataframe\n Data in the form just before being taken sigmoid.\n\n id_col_name: string\n The id/pk column name.\n\n to_dim: int\n The lower dimension the datasets reduced to.\n\n clustering_features: list of strings\n The features to reduce.\n\n batch_size: int\n The size of minibatch in statistic gradient descent.\n\n training_epoch: int\n The number of epochs to train the neuronetwork.\n\n '
self.raw_data = raw_data
self.id_col_name = id_col_name
self.cleaned_data = cleaned_data
if (to_lower_dim_filename is not None):
with open(to_lower_dim_filename, 'rb') as f:
to_lower_dim = pk.load(f)
self.one_dim_data = to_lower_dim(self.cleaned_data)
else:
self.da_reduce_dim(self.cleaned_data, field_weights=field_weights, to_dim=to_dim, batch_size=batch_size, training_epochs=training_epoch, verbose=verbose, patience=patience, patience_increase=patience_increase, improvement_threshold=improvement_threshold)
self.one_dim_data = self.to_lower_dim(self.cleaned_data) | def reduce_dimension(self, raw_data, cleaned_data, id_col_name, to_lower_dim_filename=None, field_weights=None, to_dim=1, batch_size=1000, training_epoch=10, verbose=True, patience=60, patience_increase=2, improvement_threshold=0.9995):
'\n Reduce dimension of datasets for further clustering in lower dimension\n space.\n dat: pandas dataframe\n Data in the form just before being taken sigmoid.\n\n id_col_name: string\n The id/pk column name.\n\n to_dim: int\n The lower dimension the datasets reduced to.\n\n clustering_features: list of strings\n The features to reduce.\n\n batch_size: int\n The size of minibatch in statistic gradient descent.\n\n training_epoch: int\n The number of epochs to train the neuronetwork.\n\n '
self.raw_data = raw_data
self.id_col_name = id_col_name
self.cleaned_data = cleaned_data
if (to_lower_dim_filename is not None):
with open(to_lower_dim_filename, 'rb') as f:
to_lower_dim = pk.load(f)
self.one_dim_data = to_lower_dim(self.cleaned_data)
else:
self.da_reduce_dim(self.cleaned_data, field_weights=field_weights, to_dim=to_dim, batch_size=batch_size, training_epochs=training_epoch, verbose=verbose, patience=patience, patience_increase=patience_increase, improvement_threshold=improvement_threshold)
self.one_dim_data = self.to_lower_dim(self.cleaned_data)<|docstring|>Reduce dimension of datasets for further clustering in lower dimension
space.
dat: pandas dataframe
Data in the form just before being taken sigmoid.
id_col_name: string
The id/pk column name.
to_dim: int
The lower dimension the datasets reduced to.
clustering_features: list of strings
The features to reduce.
batch_size: int
The size of minibatch in statistic gradient descent.
training_epoch: int
The number of epochs to train the neuronetwork.<|endoftext|> |
d2b39ccf22f6789c1b6bd1207931bbc83801afacca0e266e94c24ed5fbea23d6 | def add_segment(self, n_clusters=None, km_filename=None):
'\n Add segment column to existing raw dataset. Use K-Means model if\n provided, otherwise create a K-Means model.\n '
if (km_filename is None):
assert (n_clusters is not None), 'n_clusters could not be None while km is None!'
self.km = KMeans(n_clusters=n_clusters)
self.km.fit(self.one_dim_data)
else:
with open(km_filename, 'rb') as f:
self.km = pk.load(f)
self.raw_data.loc[(:, 'segment')] = self.km.predict(self.one_dim_data)
self.raw_data = self.raw_data.set_index(['segment', self.id_col_name]) | Add segment column to existing raw dataset. Use K-Means model if
provided, otherwise create a K-Means model. | clusteror/implementation_layer.py | add_segment | enfeizhan/clusteror | 0 | python | def add_segment(self, n_clusters=None, km_filename=None):
'\n Add segment column to existing raw dataset. Use K-Means model if\n provided, otherwise create a K-Means model.\n '
if (km_filename is None):
assert (n_clusters is not None), 'n_clusters could not be None while km is None!'
self.km = KMeans(n_clusters=n_clusters)
self.km.fit(self.one_dim_data)
else:
with open(km_filename, 'rb') as f:
self.km = pk.load(f)
self.raw_data.loc[(:, 'segment')] = self.km.predict(self.one_dim_data)
self.raw_data = self.raw_data.set_index(['segment', self.id_col_name]) | def add_segment(self, n_clusters=None, km_filename=None):
'\n Add segment column to existing raw dataset. Use K-Means model if\n provided, otherwise create a K-Means model.\n '
if (km_filename is None):
assert (n_clusters is not None), 'n_clusters could not be None while km is None!'
self.km = KMeans(n_clusters=n_clusters)
self.km.fit(self.one_dim_data)
else:
with open(km_filename, 'rb') as f:
self.km = pk.load(f)
self.raw_data.loc[(:, 'segment')] = self.km.predict(self.one_dim_data)
self.raw_data = self.raw_data.set_index(['segment', self.id_col_name])<|docstring|>Add segment column to existing raw dataset. Use K-Means model if
provided, otherwise create a K-Means model.<|endoftext|> |
42b68edeb11bee1c15871b97ff3b9304c6b4cf825d4c64506a13a53584ef4a88 | def __init__(self, name: str=None, mime_type: str=None, file_path: str=None, content: bytes=None):
'\n Initializes a new instance of the Attachment class\n :param name: the name\n :type name: str\n :param mime_type: the mime type\n :type mime_type: str\n :param file_path: the local file path\n :type file_path: str\n '
self._name = None
self._mime_type = None
self._content = None
self._content_id = None
self._custom_headers = []
if (file_path is not None):
self.readfile(file_path)
if (name is not None):
self._name = name
if (mime_type is not None):
self._mime_type = mime_type
if (content is not None):
self._content = base64.b64encode(content).decode('UTF-8') | Initializes a new instance of the Attachment class
:param name: the name
:type name: str
:param mime_type: the mime type
:type mime_type: str
:param file_path: the local file path
:type file_path: str | socketlabs/injectionapi/message/attachment.py | __init__ | ryan-lydz/socketlabs-python | 10 | python | def __init__(self, name: str=None, mime_type: str=None, file_path: str=None, content: bytes=None):
'\n Initializes a new instance of the Attachment class\n :param name: the name\n :type name: str\n :param mime_type: the mime type\n :type mime_type: str\n :param file_path: the local file path\n :type file_path: str\n '
self._name = None
self._mime_type = None
self._content = None
self._content_id = None
self._custom_headers = []
if (file_path is not None):
self.readfile(file_path)
if (name is not None):
self._name = name
if (mime_type is not None):
self._mime_type = mime_type
if (content is not None):
self._content = base64.b64encode(content).decode('UTF-8') | def __init__(self, name: str=None, mime_type: str=None, file_path: str=None, content: bytes=None):
'\n Initializes a new instance of the Attachment class\n :param name: the name\n :type name: str\n :param mime_type: the mime type\n :type mime_type: str\n :param file_path: the local file path\n :type file_path: str\n '
self._name = None
self._mime_type = None
self._content = None
self._content_id = None
self._custom_headers = []
if (file_path is not None):
self.readfile(file_path)
if (name is not None):
self._name = name
if (mime_type is not None):
self._mime_type = mime_type
if (content is not None):
self._content = base64.b64encode(content).decode('UTF-8')<|docstring|>Initializes a new instance of the Attachment class
:param name: the name
:type name: str
:param mime_type: the mime type
:type mime_type: str
:param file_path: the local file path
:type file_path: str<|endoftext|> |
a1d5b731c6fa7e4072e644652723548575a89a3237dea6ec1730a20702af9cb3 | @property
def name(self):
'\n Get the Name of attachment (displayed in email clients)\n :return the name\n :rtype str\n '
return self._name | Get the Name of attachment (displayed in email clients)
:return the name
:rtype str | socketlabs/injectionapi/message/attachment.py | name | ryan-lydz/socketlabs-python | 10 | python | @property
def name(self):
'\n Get the Name of attachment (displayed in email clients)\n :return the name\n :rtype str\n '
return self._name | @property
def name(self):
'\n Get the Name of attachment (displayed in email clients)\n :return the name\n :rtype str\n '
return self._name<|docstring|>Get the Name of attachment (displayed in email clients)
:return the name
:rtype str<|endoftext|> |
45c6707547d4014dd00c6483620265ba0d425cac8be498a36714edf74342d68c | @name.setter
def name(self, val: str):
'\n Set the Name of attachment (displayed in email clients)\n :param val: the name\n :type val: str\n '
self._name = val | Set the Name of attachment (displayed in email clients)
:param val: the name
:type val: str | socketlabs/injectionapi/message/attachment.py | name | ryan-lydz/socketlabs-python | 10 | python | @name.setter
def name(self, val: str):
'\n Set the Name of attachment (displayed in email clients)\n :param val: the name\n :type val: str\n '
self._name = val | @name.setter
def name(self, val: str):
'\n Set the Name of attachment (displayed in email clients)\n :param val: the name\n :type val: str\n '
self._name = val<|docstring|>Set the Name of attachment (displayed in email clients)
:param val: the name
:type val: str<|endoftext|> |
f5e66472bb474d86109b62f75979c1d937be841562b382264ec2eaaa9de61af7 | @property
def mime_type(self):
'\n Get the MIME type of the attachment.\n :return the mime type\n :rtype str\n '
return self._mime_type | Get the MIME type of the attachment.
:return the mime type
:rtype str | socketlabs/injectionapi/message/attachment.py | mime_type | ryan-lydz/socketlabs-python | 10 | python | @property
def mime_type(self):
'\n Get the MIME type of the attachment.\n :return the mime type\n :rtype str\n '
return self._mime_type | @property
def mime_type(self):
'\n Get the MIME type of the attachment.\n :return the mime type\n :rtype str\n '
return self._mime_type<|docstring|>Get the MIME type of the attachment.
:return the mime type
:rtype str<|endoftext|> |
a861120d02d4715cca84a7f5e4927d7571e54d3b601488b39aed006369dad190 | @mime_type.setter
def mime_type(self, val: str):
'\n Set the MIME type of the attachment.\n :param val: the mime type\n :type val: str\n '
self._mime_type = val | Set the MIME type of the attachment.
:param val: the mime type
:type val: str | socketlabs/injectionapi/message/attachment.py | mime_type | ryan-lydz/socketlabs-python | 10 | python | @mime_type.setter
def mime_type(self, val: str):
'\n Set the MIME type of the attachment.\n :param val: the mime type\n :type val: str\n '
self._mime_type = val | @mime_type.setter
def mime_type(self, val: str):
'\n Set the MIME type of the attachment.\n :param val: the mime type\n :type val: str\n '
self._mime_type = val<|docstring|>Set the MIME type of the attachment.
:param val: the mime type
:type val: str<|endoftext|> |
47c46ec69cf8497af2e379c17b9e244286e586f2144e4005c94084d55f9ae857 | @property
def content_id(self):
'\n Get ContentId for an Attachment. When set, used to embed an image within the body of an email message.\n :return the content id\n :rtype: str\n '
return self._content_id | Get ContentId for an Attachment. When set, used to embed an image within the body of an email message.
:return the content id
:rtype: str | socketlabs/injectionapi/message/attachment.py | content_id | ryan-lydz/socketlabs-python | 10 | python | @property
def content_id(self):
'\n Get ContentId for an Attachment. When set, used to embed an image within the body of an email message.\n :return the content id\n :rtype: str\n '
return self._content_id | @property
def content_id(self):
'\n Get ContentId for an Attachment. When set, used to embed an image within the body of an email message.\n :return the content id\n :rtype: str\n '
return self._content_id<|docstring|>Get ContentId for an Attachment. When set, used to embed an image within the body of an email message.
:return the content id
:rtype: str<|endoftext|> |
86b13e9a6725f4b9d065c85e929fbe7ffedc049ddc4d841f184a6ea97af345b3 | @content_id.setter
def content_id(self, val: str):
'\n Set ContentId for an Attachment. When set, used to embed an image within the body of an email message.\n :param val: the content id\n :type val: str\n '
self._content_id = val | Set ContentId for an Attachment. When set, used to embed an image within the body of an email message.
:param val: the content id
:type val: str | socketlabs/injectionapi/message/attachment.py | content_id | ryan-lydz/socketlabs-python | 10 | python | @content_id.setter
def content_id(self, val: str):
'\n Set ContentId for an Attachment. When set, used to embed an image within the body of an email message.\n :param val: the content id\n :type val: str\n '
self._content_id = val | @content_id.setter
def content_id(self, val: str):
'\n Set ContentId for an Attachment. When set, used to embed an image within the body of an email message.\n :param val: the content id\n :type val: str\n '
self._content_id = val<|docstring|>Set ContentId for an Attachment. When set, used to embed an image within the body of an email message.
:param val: the content id
:type val: str<|endoftext|> |
178b1ebfc412dce71baafddfd125f761e211f1480b086d5283f9b5062454f647 | @property
def content(self):
'\n Get Content of an Attachment. The BASE64 encoded str containing the contents of an attachment.\n :return the BASE64 encoded string of content\n :rtype str\n '
return self._content | Get Content of an Attachment. The BASE64 encoded str containing the contents of an attachment.
:return the BASE64 encoded string of content
:rtype str | socketlabs/injectionapi/message/attachment.py | content | ryan-lydz/socketlabs-python | 10 | python | @property
def content(self):
'\n Get Content of an Attachment. The BASE64 encoded str containing the contents of an attachment.\n :return the BASE64 encoded string of content\n :rtype str\n '
return self._content | @property
def content(self):
'\n Get Content of an Attachment. The BASE64 encoded str containing the contents of an attachment.\n :return the BASE64 encoded string of content\n :rtype str\n '
return self._content<|docstring|>Get Content of an Attachment. The BASE64 encoded str containing the contents of an attachment.
:return the BASE64 encoded string of content
:rtype str<|endoftext|> |
18f8669487d24c40a7c73cb9d899dbe9cb17a029af6e7db9b2638d5bc3791a09 | @content.setter
def content(self, val: str):
'\n Set Content of an Attachment. The BASE64 encoded str containing the contents of an attachment.\n :param val: the BASE64 encoded string of content\n :type val: str\n '
self._content = val | Set Content of an Attachment. The BASE64 encoded str containing the contents of an attachment.
:param val: the BASE64 encoded string of content
:type val: str | socketlabs/injectionapi/message/attachment.py | content | ryan-lydz/socketlabs-python | 10 | python | @content.setter
def content(self, val: str):
'\n Set Content of an Attachment. The BASE64 encoded str containing the contents of an attachment.\n :param val: the BASE64 encoded string of content\n :type val: str\n '
self._content = val | @content.setter
def content(self, val: str):
'\n Set Content of an Attachment. The BASE64 encoded str containing the contents of an attachment.\n :param val: the BASE64 encoded string of content\n :type val: str\n '
self._content = val<|docstring|>Set Content of an Attachment. The BASE64 encoded str containing the contents of an attachment.
:param val: the BASE64 encoded string of content
:type val: str<|endoftext|> |
b9de3e93d36f2c3ecd5631bc803f76d6b9e88f8bbeb8c7381b60e15ae86e2f36 | @property
def custom_headers(self):
'\n Get the list of custom message headers added to the attachment.\n :return list of CustomHeader\n :rtype list\n '
return self._custom_headers | Get the list of custom message headers added to the attachment.
:return list of CustomHeader
:rtype list | socketlabs/injectionapi/message/attachment.py | custom_headers | ryan-lydz/socketlabs-python | 10 | python | @property
def custom_headers(self):
'\n Get the list of custom message headers added to the attachment.\n :return list of CustomHeader\n :rtype list\n '
return self._custom_headers | @property
def custom_headers(self):
'\n Get the list of custom message headers added to the attachment.\n :return list of CustomHeader\n :rtype list\n '
return self._custom_headers<|docstring|>Get the list of custom message headers added to the attachment.
:return list of CustomHeader
:rtype list<|endoftext|> |
e13c4aaea5823fbc12a0882b978bc488a6bd8ac98ee2309320428b82dafadef2 | @custom_headers.setter
def custom_headers(self, val: list):
'\n Set the list of custom message headers added to the attachment.\n :param val: list of CustomHeader\n :type val: list\n '
self._custom_headers = []
if (val is not None):
for item in val:
if isinstance(item, CustomHeader):
self._custom_headers.append(item) | Set the list of custom message headers added to the attachment.
:param val: list of CustomHeader
:type val: list | socketlabs/injectionapi/message/attachment.py | custom_headers | ryan-lydz/socketlabs-python | 10 | python | @custom_headers.setter
def custom_headers(self, val: list):
'\n Set the list of custom message headers added to the attachment.\n :param val: list of CustomHeader\n :type val: list\n '
self._custom_headers = []
if (val is not None):
for item in val:
if isinstance(item, CustomHeader):
self._custom_headers.append(item) | @custom_headers.setter
def custom_headers(self, val: list):
'\n Set the list of custom message headers added to the attachment.\n :param val: list of CustomHeader\n :type val: list\n '
self._custom_headers = []
if (val is not None):
for item in val:
if isinstance(item, CustomHeader):
self._custom_headers.append(item)<|docstring|>Set the list of custom message headers added to the attachment.
:param val: list of CustomHeader
:type val: list<|endoftext|> |
04ceb641878507faecaebeb1be1e9b37add995fabe4b65102c1951ae135e6d94 | def add_custom_header(self, header, val: str=None):
'\n Add a CustomHeader to the attachment\n :param header: the CustomHeader. CustomHeader, dict, and string is allowed\n :type header: CustomHeader, dict, str\n :param val: the custom header value, required if header is str\n :type val: str\n '
if isinstance(header, CustomHeader):
self._custom_headers.append(header)
if isinstance(header, str):
self._custom_headers.append(CustomHeader(header, val))
if isinstance(header, dict):
for (name, value) in header.items():
self._custom_headers.append(CustomHeader(name, value)) | Add a CustomHeader to the attachment
:param header: the CustomHeader. CustomHeader, dict, and string is allowed
:type header: CustomHeader, dict, str
:param val: the custom header value, required if header is str
:type val: str | socketlabs/injectionapi/message/attachment.py | add_custom_header | ryan-lydz/socketlabs-python | 10 | python | def add_custom_header(self, header, val: str=None):
'\n Add a CustomHeader to the attachment\n :param header: the CustomHeader. CustomHeader, dict, and string is allowed\n :type header: CustomHeader, dict, str\n :param val: the custom header value, required if header is str\n :type val: str\n '
if isinstance(header, CustomHeader):
self._custom_headers.append(header)
if isinstance(header, str):
self._custom_headers.append(CustomHeader(header, val))
if isinstance(header, dict):
for (name, value) in header.items():
self._custom_headers.append(CustomHeader(name, value)) | def add_custom_header(self, header, val: str=None):
'\n Add a CustomHeader to the attachment\n :param header: the CustomHeader. CustomHeader, dict, and string is allowed\n :type header: CustomHeader, dict, str\n :param val: the custom header value, required if header is str\n :type val: str\n '
if isinstance(header, CustomHeader):
self._custom_headers.append(header)
if isinstance(header, str):
self._custom_headers.append(CustomHeader(header, val))
if isinstance(header, dict):
for (name, value) in header.items():
self._custom_headers.append(CustomHeader(name, value))<|docstring|>Add a CustomHeader to the attachment
:param header: the CustomHeader. CustomHeader, dict, and string is allowed
:type header: CustomHeader, dict, str
:param val: the custom header value, required if header is str
:type val: str<|endoftext|> |
1e2246cfa718960e279508234f9398d315bc316ee987ec6866909a6aee913b18 | def readfile(self, file_path: str):
'\n Read the specified file and get a str containing the resulting binary data.\n :param file_path: the file path to read\n :type: str\n '
mimes = mimetypes.MimeTypes()
with open(file_path, 'rb') as f:
self._name = os.path.split(f.name)[1]
mime = mimes.guess_type(f.name)
if (mime[0] is None):
ext = os.path.splitext(f.name)[1][1:].strip()
self._mime_type = self.__get_mime_type_from_ext(ext)
else:
self._mime_type = str(mime[0])
data = f.read()
self._content = base64.b64encode(data).decode('UTF-8')
f.close() | Read the specified file and get a str containing the resulting binary data.
:param file_path: the file path to read
:type: str | socketlabs/injectionapi/message/attachment.py | readfile | ryan-lydz/socketlabs-python | 10 | python | def readfile(self, file_path: str):
'\n Read the specified file and get a str containing the resulting binary data.\n :param file_path: the file path to read\n :type: str\n '
mimes = mimetypes.MimeTypes()
with open(file_path, 'rb') as f:
self._name = os.path.split(f.name)[1]
mime = mimes.guess_type(f.name)
if (mime[0] is None):
ext = os.path.splitext(f.name)[1][1:].strip()
self._mime_type = self.__get_mime_type_from_ext(ext)
else:
self._mime_type = str(mime[0])
data = f.read()
self._content = base64.b64encode(data).decode('UTF-8')
f.close() | def readfile(self, file_path: str):
'\n Read the specified file and get a str containing the resulting binary data.\n :param file_path: the file path to read\n :type: str\n '
mimes = mimetypes.MimeTypes()
with open(file_path, 'rb') as f:
self._name = os.path.split(f.name)[1]
mime = mimes.guess_type(f.name)
if (mime[0] is None):
ext = os.path.splitext(f.name)[1][1:].strip()
self._mime_type = self.__get_mime_type_from_ext(ext)
else:
self._mime_type = str(mime[0])
data = f.read()
self._content = base64.b64encode(data).decode('UTF-8')
f.close()<|docstring|>Read the specified file and get a str containing the resulting binary data.
:param file_path: the file path to read
:type: str<|endoftext|> |
600bd7eed3a330549d510d117b844a12b7c1f28ab97370eeb3c3d22e4823beb9 | @staticmethod
def __get_mime_type_from_ext(extension: str):
"\n Takes a file extension, minus the '.', and returns the corresponding MimeType for the given extension.\n :param extension: the file extension\n :type extension: str\n :return the mime type\n :rtype str\n "
switcher = {'txt': 'text/plain', 'ini': 'text/plain', 'sln': 'text/plain', 'cs': 'text/plain', 'js': 'text/plain', 'config': 'text/plain', 'vb': 'text/plain', 'jpg': 'image/jpeg', 'jpeg': 'image/jpeg', 'bmp': 'image/bmp', 'csv': 'text/csv', 'doc': 'application/msword', 'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'gif': 'image/gif', 'html': 'text/html', 'pdf': 'application/pdf', 'png': 'image/png', 'ppt': 'application/vnd.ms-powerpoint', 'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'xls': 'application/vnd.ms-excel', 'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'xml': 'application/xml', 'zip': 'application/x-zip-compressed', 'wav': 'audio/wav', 'eml': 'message/rfc822', 'mp3': 'audio/mpeg', 'mp4': 'video/mp4', 'mov': 'video/quicktime'}
return switcher.get(extension, 'application/octet-stream') | Takes a file extension, minus the '.', and returns the corresponding MimeType for the given extension.
:param extension: the file extension
:type extension: str
:return the mime type
:rtype str | socketlabs/injectionapi/message/attachment.py | __get_mime_type_from_ext | ryan-lydz/socketlabs-python | 10 | python | @staticmethod
def __get_mime_type_from_ext(extension: str):
"\n Takes a file extension, minus the '.', and returns the corresponding MimeType for the given extension.\n :param extension: the file extension\n :type extension: str\n :return the mime type\n :rtype str\n "
switcher = {'txt': 'text/plain', 'ini': 'text/plain', 'sln': 'text/plain', 'cs': 'text/plain', 'js': 'text/plain', 'config': 'text/plain', 'vb': 'text/plain', 'jpg': 'image/jpeg', 'jpeg': 'image/jpeg', 'bmp': 'image/bmp', 'csv': 'text/csv', 'doc': 'application/msword', 'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'gif': 'image/gif', 'html': 'text/html', 'pdf': 'application/pdf', 'png': 'image/png', 'ppt': 'application/vnd.ms-powerpoint', 'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'xls': 'application/vnd.ms-excel', 'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'xml': 'application/xml', 'zip': 'application/x-zip-compressed', 'wav': 'audio/wav', 'eml': 'message/rfc822', 'mp3': 'audio/mpeg', 'mp4': 'video/mp4', 'mov': 'video/quicktime'}
return switcher.get(extension, 'application/octet-stream') | @staticmethod
def __get_mime_type_from_ext(extension: str):
"\n Takes a file extension, minus the '.', and returns the corresponding MimeType for the given extension.\n :param extension: the file extension\n :type extension: str\n :return the mime type\n :rtype str\n "
switcher = {'txt': 'text/plain', 'ini': 'text/plain', 'sln': 'text/plain', 'cs': 'text/plain', 'js': 'text/plain', 'config': 'text/plain', 'vb': 'text/plain', 'jpg': 'image/jpeg', 'jpeg': 'image/jpeg', 'bmp': 'image/bmp', 'csv': 'text/csv', 'doc': 'application/msword', 'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'gif': 'image/gif', 'html': 'text/html', 'pdf': 'application/pdf', 'png': 'image/png', 'ppt': 'application/vnd.ms-powerpoint', 'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'xls': 'application/vnd.ms-excel', 'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'xml': 'application/xml', 'zip': 'application/x-zip-compressed', 'wav': 'audio/wav', 'eml': 'message/rfc822', 'mp3': 'audio/mpeg', 'mp4': 'video/mp4', 'mov': 'video/quicktime'}
return switcher.get(extension, 'application/octet-stream')<|docstring|>Takes a file extension, minus the '.', and returns the corresponding MimeType for the given extension.
:param extension: the file extension
:type extension: str
:return the mime type
:rtype str<|endoftext|> |
6365b816014f790cfe550cb2b575af086d140a32f4b829ea425f961d8579186f | def __str__(self):
'\n Get a str representation of this attachment.\n :return the string\n :rtype str\n '
return str(((self._name + ', ') + self._mime_type)) | Get a str representation of this attachment.
:return the string
:rtype str | socketlabs/injectionapi/message/attachment.py | __str__ | ryan-lydz/socketlabs-python | 10 | python | def __str__(self):
'\n Get a str representation of this attachment.\n :return the string\n :rtype str\n '
return str(((self._name + ', ') + self._mime_type)) | def __str__(self):
'\n Get a str representation of this attachment.\n :return the string\n :rtype str\n '
return str(((self._name + ', ') + self._mime_type))<|docstring|>Get a str representation of this attachment.
:return the string
:rtype str<|endoftext|> |
d479e450e3016ba058a68445f380ee421b523cef792e81aa91b2032cd8873cd3 | def _validate_isinstance(self, clazz, field, value):
" {'nullable': True } "
if (not isinstance(value, clazz)):
self._error(field, ('Should be instance of ' + clazz.__name__)) | {'nullable': True } | d7a/support/schema.py | _validate_isinstance | L-I-Am/pyd7a | 9 | python | def _validate_isinstance(self, clazz, field, value):
" "
if (not isinstance(value, clazz)):
self._error(field, ('Should be instance of ' + clazz.__name__)) | def _validate_isinstance(self, clazz, field, value):
" "
if (not isinstance(value, clazz)):
self._error(field, ('Should be instance of ' + clazz.__name__))<|docstring|>{'nullable': True }<|endoftext|> |
47712c8c2a35652243e359282032307d5d621cec6992b531af04ec6fa1182832 | def _validate_allowedmembers(self, allowed_members, field, value):
" {'nullable': True } "
for allowed_member in allowed_members:
if (value == allowed_member):
return
self._error(field, ('Only following enum values allowed: ' + ', '.join([m.name for m in allowed_members]))) | {'nullable': True } | d7a/support/schema.py | _validate_allowedmembers | L-I-Am/pyd7a | 9 | python | def _validate_allowedmembers(self, allowed_members, field, value):
" "
for allowed_member in allowed_members:
if (value == allowed_member):
return
self._error(field, ('Only following enum values allowed: ' + ', '.join([m.name for m in allowed_members]))) | def _validate_allowedmembers(self, allowed_members, field, value):
" "
for allowed_member in allowed_members:
if (value == allowed_member):
return
self._error(field, ('Only following enum values allowed: ' + ', '.join([m.name for m in allowed_members])))<|docstring|>{'nullable': True }<|endoftext|> |
239886fe45ab6fd5cc586faeb6df38c031d27ab59a1e5881be13f2b4723e896f | def template_info(self):
' Template information\n\n '
(fig, ax) = plt.subplots(figsize=(4, 4))
for src in self.templates:
sed.Plot(src)(axes=ax, name='', butterfly=False, fit_kwargs=dict(label=src.name, lw=2))
ax.legend(loc='upper left', prop=dict(size=12, family='monospace'))
ax.set_ylim(0.01, 20)
ax.set_xlim(100, 100000.0)
ax.set_title('Template SED plots')
return fig | Template information | python/uw/like2/analyze/sourcedetection.py | template_info | coclar/pointlike | 1 | python | def template_info(self):
' \n\n '
(fig, ax) = plt.subplots(figsize=(4, 4))
for src in self.templates:
sed.Plot(src)(axes=ax, name=, butterfly=False, fit_kwargs=dict(label=src.name, lw=2))
ax.legend(loc='upper left', prop=dict(size=12, family='monospace'))
ax.set_ylim(0.01, 20)
ax.set_xlim(100, 100000.0)
ax.set_title('Template SED plots')
return fig | def template_info(self):
' \n\n '
(fig, ax) = plt.subplots(figsize=(4, 4))
for src in self.templates:
sed.Plot(src)(axes=ax, name=, butterfly=False, fit_kwargs=dict(label=src.name, lw=2))
ax.legend(loc='upper left', prop=dict(size=12, family='monospace'))
ax.set_ylim(0.01, 20)
ax.set_xlim(100, 100000.0)
ax.set_title('Template SED plots')
return fig<|docstring|>Template information<|endoftext|> |
d2473451b187e81ee0bbed468109055a516656b43d2f08f80cc91046612ad52d | def seed_plots(self, bcut=5, subset=None, title=None):
' Seed plots\n\n Results of cluster analysis of the residual TS distribution. Analysis of %(n_seeds)d seeds from file \n <a href="../../%(seedfile)s">%(seedfile)s</a>. \n <br>Left: size of cluster, in 0.15 degree pixels\n <br>Center: maximum TS in the cluster\n <br>Right: distribution in sin(|b|), showing cut if any.\n '
z = self.seeddf
keys = list(set(z.key))
(fig, axx) = plt.subplots(1, 3, figsize=(12, 4))
plt.subplots_adjust(left=0.1)
bc = (np.abs(z.b) < bcut)
histkw = dict(histtype='step', lw=2)
def all_plot(ax, q, dom, label, log=False):
for key in keys:
ax.hist(q[(z.key == key)].clip(dom[0], dom[(- 1)]), dom, label=self.alias_dict[key], log=log, **histkw)
plt.setp(ax, xlabel=label, xlim=(None, dom[(- 1)]))
ax.grid()
ax.legend(prop=dict(size=10, family='monospace'))
if log:
ax.set_ylim(ymin=0.9)
all_plot(axx[0], z['size'], np.linspace(0.5, 10.5, 11), 'cluster size')
all_plot(axx[1], z.ts.clip(10, 25), np.linspace(10, 25, 16), 'TS', log=True)
all_plot(axx[2], np.sin(np.radians(z.b)), np.linspace((- 1), 1, 21), 'sin(b)')
axx[2].axvline(0, color='k')
fig.suptitle('{} seeds'.format(len(z)))
fig.set_facecolor('white')
return fig | Seed plots
Results of cluster analysis of the residual TS distribution. Analysis of %(n_seeds)d seeds from file
<a href="../../%(seedfile)s">%(seedfile)s</a>.
<br>Left: size of cluster, in 0.15 degree pixels
<br>Center: maximum TS in the cluster
<br>Right: distribution in sin(|b|), showing cut if any. | python/uw/like2/analyze/sourcedetection.py | seed_plots | coclar/pointlike | 1 | python | def seed_plots(self, bcut=5, subset=None, title=None):
' Seed plots\n\n Results of cluster analysis of the residual TS distribution. Analysis of %(n_seeds)d seeds from file \n <a href="../../%(seedfile)s">%(seedfile)s</a>. \n <br>Left: size of cluster, in 0.15 degree pixels\n <br>Center: maximum TS in the cluster\n <br>Right: distribution in sin(|b|), showing cut if any.\n '
z = self.seeddf
keys = list(set(z.key))
(fig, axx) = plt.subplots(1, 3, figsize=(12, 4))
plt.subplots_adjust(left=0.1)
bc = (np.abs(z.b) < bcut)
histkw = dict(histtype='step', lw=2)
def all_plot(ax, q, dom, label, log=False):
for key in keys:
ax.hist(q[(z.key == key)].clip(dom[0], dom[(- 1)]), dom, label=self.alias_dict[key], log=log, **histkw)
plt.setp(ax, xlabel=label, xlim=(None, dom[(- 1)]))
ax.grid()
ax.legend(prop=dict(size=10, family='monospace'))
if log:
ax.set_ylim(ymin=0.9)
all_plot(axx[0], z['size'], np.linspace(0.5, 10.5, 11), 'cluster size')
all_plot(axx[1], z.ts.clip(10, 25), np.linspace(10, 25, 16), 'TS', log=True)
all_plot(axx[2], np.sin(np.radians(z.b)), np.linspace((- 1), 1, 21), 'sin(b)')
axx[2].axvline(0, color='k')
fig.suptitle('{} seeds'.format(len(z)))
fig.set_facecolor('white')
return fig | def seed_plots(self, bcut=5, subset=None, title=None):
' Seed plots\n\n Results of cluster analysis of the residual TS distribution. Analysis of %(n_seeds)d seeds from file \n <a href="../../%(seedfile)s">%(seedfile)s</a>. \n <br>Left: size of cluster, in 0.15 degree pixels\n <br>Center: maximum TS in the cluster\n <br>Right: distribution in sin(|b|), showing cut if any.\n '
z = self.seeddf
keys = list(set(z.key))
(fig, axx) = plt.subplots(1, 3, figsize=(12, 4))
plt.subplots_adjust(left=0.1)
bc = (np.abs(z.b) < bcut)
histkw = dict(histtype='step', lw=2)
def all_plot(ax, q, dom, label, log=False):
for key in keys:
ax.hist(q[(z.key == key)].clip(dom[0], dom[(- 1)]), dom, label=self.alias_dict[key], log=log, **histkw)
plt.setp(ax, xlabel=label, xlim=(None, dom[(- 1)]))
ax.grid()
ax.legend(prop=dict(size=10, family='monospace'))
if log:
ax.set_ylim(ymin=0.9)
all_plot(axx[0], z['size'], np.linspace(0.5, 10.5, 11), 'cluster size')
all_plot(axx[1], z.ts.clip(10, 25), np.linspace(10, 25, 16), 'TS', log=True)
all_plot(axx[2], np.sin(np.radians(z.b)), np.linspace((- 1), 1, 21), 'sin(b)')
axx[2].axvline(0, color='k')
fig.suptitle('{} seeds'.format(len(z)))
fig.set_facecolor('white')
return fig<|docstring|>Seed plots
Results of cluster analysis of the residual TS distribution. Analysis of %(n_seeds)d seeds from file
<a href="../../%(seedfile)s">%(seedfile)s</a>.
<br>Left: size of cluster, in 0.15 degree pixels
<br>Center: maximum TS in the cluster
<br>Right: distribution in sin(|b|), showing cut if any.<|endoftext|> |
abb11a27cb965e47adccfcb80547294a4437be696eee1444755574e75f5b2c5a | def detection_plots(self):
'Detection plots\n\n Comparison of seed values with fits\n\n '
sdf = self.seeddf
ddf = sdf[(sdf.ok & (sdf.ts_fit > 10))]
(fig, axx) = plt.subplots(2, 2, figsize=(12, 12))
ax = axx[(0, 0)]
xlim = (1.0, 3.5)
hkw = dict(bins=np.linspace(xlim[0], xlim[1], 26), histtype='step', lw=2)
for t in self.templates:
if (t.name == 'pulsar'):
continue
key = t.key
ax.hist(sdf.pindex[(sdf.ok & (sdf.key == key))].clip(*xlim), label=t.name, **hkw)
ax.axvline(t.model['Index'], ls='--', color='grey')
ax.legend(prop=dict(family='monospace'))
ax.set_xlim(*xlim)
ax.set_xlabel('fit photon index')
ax.set_title('Power Law photon index')
ax.grid(alpha=0.5)
ax = axx[(0, 1)]
xlim = (0, 20)
ylim = (0, 40)
for t in self.templates:
key = t.key
sel = (ddf.key == key)
ax.plot(ddf.ts[sel].clip(*xlim), ddf.ts_fit[sel].clip(*ylim), '.', label=t.name)
ax.legend(prop=dict(size=12, family='monospace'))
ax.plot([10, 20], [10, 20], '--', color='grey')
plt.setp(ax, xlabel='seed TS', ylabel='fit TS', title='Test Statistic')
ax = axx[(1, 0)]
sinb = np.sin(np.radians(ddf.b))
hkw = dict(bins=np.linspace((- 1), 1, 21), histtype='step', lw=2)
for t in self.templates:
key = t.key
sel = (ddf.key == key)
ax.hist(sinb[sel], label=t.name, **hkw)
ax.legend(prop=dict(size=12, family='monospace'))
ax.set_xlim((- 1), 1)
ax.set_xlabel('sin(b)')
axx[(1, 1)].set_visible(False)
return fig | Detection plots
Comparison of seed values with fits | python/uw/like2/analyze/sourcedetection.py | detection_plots | coclar/pointlike | 1 | python | def detection_plots(self):
'Detection plots\n\n Comparison of seed values with fits\n\n '
sdf = self.seeddf
ddf = sdf[(sdf.ok & (sdf.ts_fit > 10))]
(fig, axx) = plt.subplots(2, 2, figsize=(12, 12))
ax = axx[(0, 0)]
xlim = (1.0, 3.5)
hkw = dict(bins=np.linspace(xlim[0], xlim[1], 26), histtype='step', lw=2)
for t in self.templates:
if (t.name == 'pulsar'):
continue
key = t.key
ax.hist(sdf.pindex[(sdf.ok & (sdf.key == key))].clip(*xlim), label=t.name, **hkw)
ax.axvline(t.model['Index'], ls='--', color='grey')
ax.legend(prop=dict(family='monospace'))
ax.set_xlim(*xlim)
ax.set_xlabel('fit photon index')
ax.set_title('Power Law photon index')
ax.grid(alpha=0.5)
ax = axx[(0, 1)]
xlim = (0, 20)
ylim = (0, 40)
for t in self.templates:
key = t.key
sel = (ddf.key == key)
ax.plot(ddf.ts[sel].clip(*xlim), ddf.ts_fit[sel].clip(*ylim), '.', label=t.name)
ax.legend(prop=dict(size=12, family='monospace'))
ax.plot([10, 20], [10, 20], '--', color='grey')
plt.setp(ax, xlabel='seed TS', ylabel='fit TS', title='Test Statistic')
ax = axx[(1, 0)]
sinb = np.sin(np.radians(ddf.b))
hkw = dict(bins=np.linspace((- 1), 1, 21), histtype='step', lw=2)
for t in self.templates:
key = t.key
sel = (ddf.key == key)
ax.hist(sinb[sel], label=t.name, **hkw)
ax.legend(prop=dict(size=12, family='monospace'))
ax.set_xlim((- 1), 1)
ax.set_xlabel('sin(b)')
axx[(1, 1)].set_visible(False)
return fig | def detection_plots(self):
'Detection plots\n\n Comparison of seed values with fits\n\n '
sdf = self.seeddf
ddf = sdf[(sdf.ok & (sdf.ts_fit > 10))]
(fig, axx) = plt.subplots(2, 2, figsize=(12, 12))
ax = axx[(0, 0)]
xlim = (1.0, 3.5)
hkw = dict(bins=np.linspace(xlim[0], xlim[1], 26), histtype='step', lw=2)
for t in self.templates:
if (t.name == 'pulsar'):
continue
key = t.key
ax.hist(sdf.pindex[(sdf.ok & (sdf.key == key))].clip(*xlim), label=t.name, **hkw)
ax.axvline(t.model['Index'], ls='--', color='grey')
ax.legend(prop=dict(family='monospace'))
ax.set_xlim(*xlim)
ax.set_xlabel('fit photon index')
ax.set_title('Power Law photon index')
ax.grid(alpha=0.5)
ax = axx[(0, 1)]
xlim = (0, 20)
ylim = (0, 40)
for t in self.templates:
key = t.key
sel = (ddf.key == key)
ax.plot(ddf.ts[sel].clip(*xlim), ddf.ts_fit[sel].clip(*ylim), '.', label=t.name)
ax.legend(prop=dict(size=12, family='monospace'))
ax.plot([10, 20], [10, 20], '--', color='grey')
plt.setp(ax, xlabel='seed TS', ylabel='fit TS', title='Test Statistic')
ax = axx[(1, 0)]
sinb = np.sin(np.radians(ddf.b))
hkw = dict(bins=np.linspace((- 1), 1, 21), histtype='step', lw=2)
for t in self.templates:
key = t.key
sel = (ddf.key == key)
ax.hist(sinb[sel], label=t.name, **hkw)
ax.legend(prop=dict(size=12, family='monospace'))
ax.set_xlim((- 1), 1)
ax.set_xlabel('sin(b)')
axx[(1, 1)].set_visible(False)
return fig<|docstring|>Detection plots
Comparison of seed values with fits<|endoftext|> |
b95fe09b5a1c3219529a2716bbadb01bef1f1c54d848cbb8603cb2a0b69ca991 | def test_puzzle_ex_8():
'\n Opcode 5 is jump-if-true: if the first parameter is non-zero,\n it sets the instruction pointer to the value from the second parameter.\n Otherwise, it does nothing.\n Opcode 6 is jump-if-false: if the first parameter is zero, it sets the\n instruction pointer to the value from the second parameter.\n Otherwise, it does nothing.\n '
code_list = [3, 12, 6, 12, 15, 1, 13, 14, 13, 4, 13, 99, (- 1), 0, 1, 9]
programme_input = 0
(code_list, output) = run_opcode(code_list, programme_input=programme_input)
assert (code_list == [3, 12, 6, 12, 15, 1, 13, 14, 13, 4, 13, 99, 0, 0, 1, 9])
assert (output == 0)
code_list = [3, 12, 6, 12, 15, 1, 13, 14, 13, 4, 13, 99, (- 1), 0, 1, 9]
programme_input = 3
(code_list, output) = run_opcode(code_list, programme_input=programme_input)
assert (code_list == [3, 12, 6, 12, 15, 1, 13, 14, 13, 4, 13, 99, 3, 1, 1, 9])
assert (output == 1) | Opcode 5 is jump-if-true: if the first parameter is non-zero,
it sets the instruction pointer to the value from the second parameter.
Otherwise, it does nothing.
Opcode 6 is jump-if-false: if the first parameter is zero, it sets the
instruction pointer to the value from the second parameter.
Otherwise, it does nothing. | tests/test_day05_puz2.py | test_puzzle_ex_8 | KirstieJane/advent-code-2019 | 2 | python | def test_puzzle_ex_8():
'\n Opcode 5 is jump-if-true: if the first parameter is non-zero,\n it sets the instruction pointer to the value from the second parameter.\n Otherwise, it does nothing.\n Opcode 6 is jump-if-false: if the first parameter is zero, it sets the\n instruction pointer to the value from the second parameter.\n Otherwise, it does nothing.\n '
code_list = [3, 12, 6, 12, 15, 1, 13, 14, 13, 4, 13, 99, (- 1), 0, 1, 9]
programme_input = 0
(code_list, output) = run_opcode(code_list, programme_input=programme_input)
assert (code_list == [3, 12, 6, 12, 15, 1, 13, 14, 13, 4, 13, 99, 0, 0, 1, 9])
assert (output == 0)
code_list = [3, 12, 6, 12, 15, 1, 13, 14, 13, 4, 13, 99, (- 1), 0, 1, 9]
programme_input = 3
(code_list, output) = run_opcode(code_list, programme_input=programme_input)
assert (code_list == [3, 12, 6, 12, 15, 1, 13, 14, 13, 4, 13, 99, 3, 1, 1, 9])
assert (output == 1) | def test_puzzle_ex_8():
'\n Opcode 5 is jump-if-true: if the first parameter is non-zero,\n it sets the instruction pointer to the value from the second parameter.\n Otherwise, it does nothing.\n Opcode 6 is jump-if-false: if the first parameter is zero, it sets the\n instruction pointer to the value from the second parameter.\n Otherwise, it does nothing.\n '
code_list = [3, 12, 6, 12, 15, 1, 13, 14, 13, 4, 13, 99, (- 1), 0, 1, 9]
programme_input = 0
(code_list, output) = run_opcode(code_list, programme_input=programme_input)
assert (code_list == [3, 12, 6, 12, 15, 1, 13, 14, 13, 4, 13, 99, 0, 0, 1, 9])
assert (output == 0)
code_list = [3, 12, 6, 12, 15, 1, 13, 14, 13, 4, 13, 99, (- 1), 0, 1, 9]
programme_input = 3
(code_list, output) = run_opcode(code_list, programme_input=programme_input)
assert (code_list == [3, 12, 6, 12, 15, 1, 13, 14, 13, 4, 13, 99, 3, 1, 1, 9])
assert (output == 1)<|docstring|>Opcode 5 is jump-if-true: if the first parameter is non-zero,
it sets the instruction pointer to the value from the second parameter.
Otherwise, it does nothing.
Opcode 6 is jump-if-false: if the first parameter is zero, it sets the
instruction pointer to the value from the second parameter.
Otherwise, it does nothing.<|endoftext|> |
c0fda2ac860b9ed49de0fc37dfea34360a03991df07a00185a3732967709c15c | def test_integration():
'I know the correct answer, lets check that the code gives me it!\n '
code_list = load_computer_data('day05/input.txt')
(code_list, output) = run_opcode(code_list, programme_input=5)
assert (output == 7161591) | I know the correct answer, lets check that the code gives me it! | tests/test_day05_puz2.py | test_integration | KirstieJane/advent-code-2019 | 2 | python | def test_integration():
'\n '
code_list = load_computer_data('day05/input.txt')
(code_list, output) = run_opcode(code_list, programme_input=5)
assert (output == 7161591) | def test_integration():
'\n '
code_list = load_computer_data('day05/input.txt')
(code_list, output) = run_opcode(code_list, programme_input=5)
assert (output == 7161591)<|docstring|>I know the correct answer, lets check that the code gives me it!<|endoftext|> |
3d537e6c6810aabfd223c0f235052ff8978addab409e1b449b0917cbf6efb0f8 | def test_tflite(env, model_dir, model_number, verify=False):
'Use tflite to make predictions and compare predictions to stablebaselines output'
tflite_model = (((model_dir + '/bittle_frozen_model') + args.model_number) + '.tflite')
interpreter = tf.lite.Interpreter(model_path=tflite_model, experimental_delegates=None)
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
if verify:
with open((((model_dir + '/saved_info_1ep_model') + model_number) + '.pickle'), 'rb') as handle:
saved_info = pickle.load(handle)
steps = len(saved_info['obs'])
else:
obs = env.reset()
steps = 500
for i in range(steps):
if verify:
obs = saved_info['obs'][i]
input_data = obs.reshape(1, (- 1))
input_data = np.array(input_data, dtype=np.float32)
interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()
output_data = interpreter.get_tensor(output_details[0]['index'])
output_data = np.array(output_data).flatten()
if verify:
print('TFLite Output:', output_data)
print('SB Saved Output', saved_info['actions'][i])
print('\n')
else:
(obs, reward, done, info) = env.step(output_data[:8])
if done:
obs = env.reset() | Use tflite to make predictions and compare predictions to stablebaselines output | motion_imitation/run_tflite.py | test_tflite | jasonjabbour/motion_imitation | 0 | python | def test_tflite(env, model_dir, model_number, verify=False):
tflite_model = (((model_dir + '/bittle_frozen_model') + args.model_number) + '.tflite')
interpreter = tf.lite.Interpreter(model_path=tflite_model, experimental_delegates=None)
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
if verify:
with open((((model_dir + '/saved_info_1ep_model') + model_number) + '.pickle'), 'rb') as handle:
saved_info = pickle.load(handle)
steps = len(saved_info['obs'])
else:
obs = env.reset()
steps = 500
for i in range(steps):
if verify:
obs = saved_info['obs'][i]
input_data = obs.reshape(1, (- 1))
input_data = np.array(input_data, dtype=np.float32)
interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()
output_data = interpreter.get_tensor(output_details[0]['index'])
output_data = np.array(output_data).flatten()
if verify:
print('TFLite Output:', output_data)
print('SB Saved Output', saved_info['actions'][i])
print('\n')
else:
(obs, reward, done, info) = env.step(output_data[:8])
if done:
obs = env.reset() | def test_tflite(env, model_dir, model_number, verify=False):
tflite_model = (((model_dir + '/bittle_frozen_model') + args.model_number) + '.tflite')
interpreter = tf.lite.Interpreter(model_path=tflite_model, experimental_delegates=None)
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
if verify:
with open((((model_dir + '/saved_info_1ep_model') + model_number) + '.pickle'), 'rb') as handle:
saved_info = pickle.load(handle)
steps = len(saved_info['obs'])
else:
obs = env.reset()
steps = 500
for i in range(steps):
if verify:
obs = saved_info['obs'][i]
input_data = obs.reshape(1, (- 1))
input_data = np.array(input_data, dtype=np.float32)
interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()
output_data = interpreter.get_tensor(output_details[0]['index'])
output_data = np.array(output_data).flatten()
if verify:
print('TFLite Output:', output_data)
print('SB Saved Output', saved_info['actions'][i])
print('\n')
else:
(obs, reward, done, info) = env.step(output_data[:8])
if done:
obs = env.reset()<|docstring|>Use tflite to make predictions and compare predictions to stablebaselines output<|endoftext|> |
34e9c1dff959550da45ea0e229c0333bbb50d351972cc1f754fe53e8078d4845 | def frozen_pb_2_tflite(model_dir, model_number, frozen_model_output_layer):
'Convert a frozen tensorflow protobuf model to tflite'
frozen_model_name = ((model_dir + '/bittle_frozen_model') + model_number)
path = (frozen_model_name + '.pb')
converter = tf.compat.v1.lite.TFLiteConverter.from_frozen_graph(path, input_arrays=['input/Ob'], output_arrays=[frozen_model_output_layer])
tflite_model = converter.convert()
tflite_save_file = (frozen_model_name + '.tflite')
with open(tflite_save_file, 'wb') as f:
f.write(tflite_model)
print(f'''
>>Model Converted to TFLite: {tflite_save_file} <<
''') | Convert a frozen tensorflow protobuf model to tflite | motion_imitation/run_tflite.py | frozen_pb_2_tflite | jasonjabbour/motion_imitation | 0 | python | def frozen_pb_2_tflite(model_dir, model_number, frozen_model_output_layer):
frozen_model_name = ((model_dir + '/bittle_frozen_model') + model_number)
path = (frozen_model_name + '.pb')
converter = tf.compat.v1.lite.TFLiteConverter.from_frozen_graph(path, input_arrays=['input/Ob'], output_arrays=[frozen_model_output_layer])
tflite_model = converter.convert()
tflite_save_file = (frozen_model_name + '.tflite')
with open(tflite_save_file, 'wb') as f:
f.write(tflite_model)
print(f'
>>Model Converted to TFLite: {tflite_save_file} <<
') | def frozen_pb_2_tflite(model_dir, model_number, frozen_model_output_layer):
frozen_model_name = ((model_dir + '/bittle_frozen_model') + model_number)
path = (frozen_model_name + '.pb')
converter = tf.compat.v1.lite.TFLiteConverter.from_frozen_graph(path, input_arrays=['input/Ob'], output_arrays=[frozen_model_output_layer])
tflite_model = converter.convert()
tflite_save_file = (frozen_model_name + '.tflite')
with open(tflite_save_file, 'wb') as f:
f.write(tflite_model)
print(f'
>>Model Converted to TFLite: {tflite_save_file} <<
')<|docstring|>Convert a frozen tensorflow protobuf model to tflite<|endoftext|> |
119020dad831f291ab368e34c74c5045b4ef0d414575bb11f0ae32e5a498cfc2 | def tf_2_frozen(model_dir, model_number, output_layer):
'Freeze a tensorflow protobuf model '
input_graph = (((model_dir + '/model') + model_number) + '_tf/saved_model.pb')
input_saved_model_dir = (((model_dir + '/model') + model_number) + '_tf')
input_binary = True
output_graph = (((model_dir + '/bittle_frozen_model') + model_number) + '.pb')
output_node_names = output_layer
input_saver = input_checkpoint = initializer_nodes = variable_names_whitelist = variable_names_blacklist = ''
restore_op_name = 'save/restore_all'
filename_tensor_name = 'save/Const:0'
clear_devices = True
freeze_graph.freeze_graph(input_graph, input_saver, input_binary, input_checkpoint, output_node_names, restore_op_name, filename_tensor_name, output_graph, clear_devices, initializer_nodes, variable_names_whitelist, variable_names_blacklist, input_saved_model_dir=input_saved_model_dir)
print(f'''
>> TF Protobuf was successfully frozen: {output_graph} <<
''') | Freeze a tensorflow protobuf model | motion_imitation/run_tflite.py | tf_2_frozen | jasonjabbour/motion_imitation | 0 | python | def tf_2_frozen(model_dir, model_number, output_layer):
' '
input_graph = (((model_dir + '/model') + model_number) + '_tf/saved_model.pb')
input_saved_model_dir = (((model_dir + '/model') + model_number) + '_tf')
input_binary = True
output_graph = (((model_dir + '/bittle_frozen_model') + model_number) + '.pb')
output_node_names = output_layer
input_saver = input_checkpoint = initializer_nodes = variable_names_whitelist = variable_names_blacklist =
restore_op_name = 'save/restore_all'
filename_tensor_name = 'save/Const:0'
clear_devices = True
freeze_graph.freeze_graph(input_graph, input_saver, input_binary, input_checkpoint, output_node_names, restore_op_name, filename_tensor_name, output_graph, clear_devices, initializer_nodes, variable_names_whitelist, variable_names_blacklist, input_saved_model_dir=input_saved_model_dir)
print(f'
>> TF Protobuf was successfully frozen: {output_graph} <<
') | def tf_2_frozen(model_dir, model_number, output_layer):
' '
input_graph = (((model_dir + '/model') + model_number) + '_tf/saved_model.pb')
input_saved_model_dir = (((model_dir + '/model') + model_number) + '_tf')
input_binary = True
output_graph = (((model_dir + '/bittle_frozen_model') + model_number) + '.pb')
output_node_names = output_layer
input_saver = input_checkpoint = initializer_nodes = variable_names_whitelist = variable_names_blacklist =
restore_op_name = 'save/restore_all'
filename_tensor_name = 'save/Const:0'
clear_devices = True
freeze_graph.freeze_graph(input_graph, input_saver, input_binary, input_checkpoint, output_node_names, restore_op_name, filename_tensor_name, output_graph, clear_devices, initializer_nodes, variable_names_whitelist, variable_names_blacklist, input_saved_model_dir=input_saved_model_dir)
print(f'
>> TF Protobuf was successfully frozen: {output_graph} <<
')<|docstring|>Freeze a tensorflow protobuf model<|endoftext|> |
0b3fec2fa7880694be795050c46f3f185f0e8f4d97fdaea8dabb70051443fce9 | def close_form(self):
'Method that closed forms by click on the area near the form'
self._click_with_offset(Common.dialog, 500, 50) | Method that closed forms by click on the area near the form | tests/ui_tests/app/pages.py | close_form | amleshkov/adcm | 0 | python | def close_form(self):
self._click_with_offset(Common.dialog, 500, 50) | def close_form(self):
self._click_with_offset(Common.dialog, 500, 50)<|docstring|>Method that closed forms by click on the area near the form<|endoftext|> |
a91742b19f2629e551d2bd5a55c0a5f4d355b1f7670daa421793639832a37964 | def _delete_first_element(self):
'Method that finds first item in list and delete his from list'
self.delete_row(0)
approve = self._getelement(Common.dialog)
approve.is_displayed()
self._getelement(Common.dialog_yes).click() | Method that finds first item in list and delete his from list | tests/ui_tests/app/pages.py | _delete_first_element | amleshkov/adcm | 0 | python | def _delete_first_element(self):
self.delete_row(0)
approve = self._getelement(Common.dialog)
approve.is_displayed()
self._getelement(Common.dialog_yes).click() | def _delete_first_element(self):
self.delete_row(0)
approve = self._getelement(Common.dialog)
approve.is_displayed()
self._getelement(Common.dialog_yes).click()<|docstring|>Method that finds first item in list and delete his from list<|endoftext|> |
5b7b532e048b0075cf805d22861db5da9c587d737d2b8f5c79661c11b2f5596a | def delete_row(self, row_number):
'Deleting specified row by his number\n :param: '
rows = self.get_rows()
_del = rows[row_number].find_element_by_xpath(Common.del_btn)
_del.click() | Deleting specified row by his number
:param: | tests/ui_tests/app/pages.py | delete_row | amleshkov/adcm | 0 | python | def delete_row(self, row_number):
'Deleting specified row by his number\n :param: '
rows = self.get_rows()
_del = rows[row_number].find_element_by_xpath(Common.del_btn)
_del.click() | def delete_row(self, row_number):
'Deleting specified row by his number\n :param: '
rows = self.get_rows()
_del = rows[row_number].find_element_by_xpath(Common.del_btn)
_del.click()<|docstring|>Deleting specified row by his number
:param:<|endoftext|> |
70c5a00a87b3cfea480c3ea3e5db9e17643108319664fb24e36d4e4ab2ea0933 | def check_task(self, action_name):
'We just check upper task in the list because in UI last runned task must be\n always at the top.'
self.list_element_contains(action_name) | We just check upper task in the list because in UI last runned task must be
always at the top. | tests/ui_tests/app/pages.py | check_task | amleshkov/adcm | 0 | python | def check_task(self, action_name):
'We just check upper task in the list because in UI last runned task must be\n always at the top.'
self.list_element_contains(action_name) | def check_task(self, action_name):
'We just check upper task in the list because in UI last runned task must be\n always at the top.'
self.list_element_contains(action_name)<|docstring|>We just check upper task in the list because in UI last runned task must be
always at the top.<|endoftext|> |
9967ceb1ef262bff1c88f09ebfc08430d43626eae448a28e0dceef3dc0b37227 | def group_is_active_by_element(self, group_element):
'\n\n :param group_element:\n :return:\n '
toogle = group_element.find_element(*Common.mat_slide_toggle)
if ('mat-checked' in toogle.get_attribute('class')):
return True
return False | :param group_element:
:return: | tests/ui_tests/app/pages.py | group_is_active_by_element | amleshkov/adcm | 0 | python | def group_is_active_by_element(self, group_element):
'\n\n :param group_element:\n :return:\n '
toogle = group_element.find_element(*Common.mat_slide_toggle)
if ('mat-checked' in toogle.get_attribute('class')):
return True
return False | def group_is_active_by_element(self, group_element):
'\n\n :param group_element:\n :return:\n '
toogle = group_element.find_element(*Common.mat_slide_toggle)
if ('mat-checked' in toogle.get_attribute('class')):
return True
return False<|docstring|>:param group_element:
:return:<|endoftext|> |
f6975c080798106613591a85f1dce3ceb9a84018c401da4427557bd66e10d669 | def group_is_active_by_name(self, group_name):
'Get group status\n :param group_name:\n :return:\n '
group = self._get_group_element_by_name(group_name)
toogle = group.find_element(*Common.mat_slide_toggle)
if ('mat-checked' in toogle.get_attribute('class')):
return True
return False | Get group status
:param group_name:
:return: | tests/ui_tests/app/pages.py | group_is_active_by_name | amleshkov/adcm | 0 | python | def group_is_active_by_name(self, group_name):
'Get group status\n :param group_name:\n :return:\n '
group = self._get_group_element_by_name(group_name)
toogle = group.find_element(*Common.mat_slide_toggle)
if ('mat-checked' in toogle.get_attribute('class')):
return True
return False | def group_is_active_by_name(self, group_name):
'Get group status\n :param group_name:\n :return:\n '
group = self._get_group_element_by_name(group_name)
toogle = group.find_element(*Common.mat_slide_toggle)
if ('mat-checked' in toogle.get_attribute('class')):
return True
return False<|docstring|>Get group status
:param group_name:
:return:<|endoftext|> |
42a70702da030a3d6a9dd165b1e6198646727601c293aae5432252445deb7b52 | def activate_group_by_element(self, group_element):
'Activate group by element\n\n :param group_element:\n :return:\n '
toogle = group_element.find_element(*Common.mat_slide_toggle)
if ('mat-checked' not in toogle.get_attribute('class')):
toogle.click() | Activate group by element
:param group_element:
:return: | tests/ui_tests/app/pages.py | activate_group_by_element | amleshkov/adcm | 0 | python | def activate_group_by_element(self, group_element):
'Activate group by element\n\n :param group_element:\n :return:\n '
toogle = group_element.find_element(*Common.mat_slide_toggle)
if ('mat-checked' not in toogle.get_attribute('class')):
toogle.click() | def activate_group_by_element(self, group_element):
'Activate group by element\n\n :param group_element:\n :return:\n '
toogle = group_element.find_element(*Common.mat_slide_toggle)
if ('mat-checked' not in toogle.get_attribute('class')):
toogle.click()<|docstring|>Activate group by element
:param group_element:
:return:<|endoftext|> |
86e50a4488234b05146a4651bb62088bbac71ad539c88eac2d686ee8f9512a4c | def activate_group_by_name(self, group_name):
'\n\n :param group_name:\n :return:\n '
group = self._get_group_element_by_name(group_name)
toogle = group.find_element(*Common.mat_slide_toggle)
if ('mat-checked' not in toogle.get_attribute('class')):
toogle.click() | :param group_name:
:return: | tests/ui_tests/app/pages.py | activate_group_by_name | amleshkov/adcm | 0 | python | def activate_group_by_name(self, group_name):
'\n\n :param group_name:\n :return:\n '
group = self._get_group_element_by_name(group_name)
toogle = group.find_element(*Common.mat_slide_toggle)
if ('mat-checked' not in toogle.get_attribute('class')):
toogle.click() | def activate_group_by_name(self, group_name):
'\n\n :param group_name:\n :return:\n '
group = self._get_group_element_by_name(group_name)
toogle = group.find_element(*Common.mat_slide_toggle)
if ('mat-checked' not in toogle.get_attribute('class')):
toogle.click()<|docstring|>:param group_name:
:return:<|endoftext|> |
48cba161e6a6cdb30dfa1ed0fa381302e0136b1b3372f7d53c0e900415f43a2c | def execute_action(self, action_name):
'Click action\n :param action_name:\n :return:\n '
assert self._click_button_by_name(action_name, *Common.mat_raised_button)
return self._click_button_by_name('Run', *Common.mat_raised_button) | Click action
:param action_name:
:return: | tests/ui_tests/app/pages.py | execute_action | amleshkov/adcm | 0 | python | def execute_action(self, action_name):
'Click action\n :param action_name:\n :return:\n '
assert self._click_button_by_name(action_name, *Common.mat_raised_button)
return self._click_button_by_name('Run', *Common.mat_raised_button) | def execute_action(self, action_name):
'Click action\n :param action_name:\n :return:\n '
assert self._click_button_by_name(action_name, *Common.mat_raised_button)
return self._click_button_by_name('Run', *Common.mat_raised_button)<|docstring|>Click action
:param action_name:
:return:<|endoftext|> |
be4b74cb90deab844d44a78d11238da3afad7d2e9e3e11c3249c2827b5bb0bd4 | def element_presented_by_name_and_locator(self, name, by, value):
'\n\n :param name:\n :param by:\n :param value:\n :return:\n '
elements = self.driver.find_elements(by, value)
if (not elements):
return False
for el in elements:
if (el.text == name):
return True
return False | :param name:
:param by:
:param value:
:return: | tests/ui_tests/app/pages.py | element_presented_by_name_and_locator | amleshkov/adcm | 0 | python | def element_presented_by_name_and_locator(self, name, by, value):
'\n\n :param name:\n :param by:\n :param value:\n :return:\n '
elements = self.driver.find_elements(by, value)
if (not elements):
return False
for el in elements:
if (el.text == name):
return True
return False | def element_presented_by_name_and_locator(self, name, by, value):
'\n\n :param name:\n :param by:\n :param value:\n :return:\n '
elements = self.driver.find_elements(by, value)
if (not elements):
return False
for el in elements:
if (el.text == name):
return True
return False<|docstring|>:param name:
:param by:
:param value:
:return:<|endoftext|> |
0be386b40ea21b0d3d076fc1b56aea4b9311134ea32679d17c5e62218e656301 | @staticmethod
def read_only_element(element):
'Check that field have read-only attribute\n\n :param element:\n :return:\n '
if ('read-only' in element.get_attribute('class')):
return True
return False | Check that field have read-only attribute
:param element:
:return: | tests/ui_tests/app/pages.py | read_only_element | amleshkov/adcm | 0 | python | @staticmethod
def read_only_element(element):
'Check that field have read-only attribute\n\n :param element:\n :return:\n '
if ('read-only' in element.get_attribute('class')):
return True
return False | @staticmethod
def read_only_element(element):
'Check that field have read-only attribute\n\n :param element:\n :return:\n '
if ('read-only' in element.get_attribute('class')):
return True
return False<|docstring|>Check that field have read-only attribute
:param element:
:return:<|endoftext|> |
206540d4b798543f40fe9d3cd167ee46856384a2beeaddc8f62dfbd807794760 | def background_thread():
'Example of how to send server generated events to clients.'
count = 0
while True:
time.sleep(10)
count += 1
emit('my response', {'data': 'Server generated event', 'count': count}, namespace='/CRAWLAB') | Example of how to send server generated events to clients. | Flask/Flask_SocketIO_WebRemote/app.py | background_thread | DocVaughan/CRAWLAB-Code-Snippets | 12 | python | def background_thread():
count = 0
while True:
time.sleep(10)
count += 1
emit('my response', {'data': 'Server generated event', 'count': count}, namespace='/CRAWLAB') | def background_thread():
count = 0
while True:
time.sleep(10)
count += 1
emit('my response', {'data': 'Server generated event', 'count': count}, namespace='/CRAWLAB')<|docstring|>Example of how to send server generated events to clients.<|endoftext|> |
640478fe94701f2e1afec7de1ab4f5ce9b3259be6a41c5795db5d4e28e40bac6 | @app.route('/')
def task_list():
'\n Create a route for base address\n\n :return: application page\n '
tasks = list_tasks()
return render_template('application.html', tasks=tasks) | Create a route for base address
:return: application page | todo/views.py | task_list | ygivenx/todo | 0 | python | @app.route('/')
def task_list():
'\n Create a route for base address\n\n :return: application page\n '
tasks = list_tasks()
return render_template('application.html', tasks=tasks) | @app.route('/')
def task_list():
'\n Create a route for base address\n\n :return: application page\n '
tasks = list_tasks()
return render_template('application.html', tasks=tasks)<|docstring|>Create a route for base address
:return: application page<|endoftext|> |
5788fb0b21b58f26621901d59b63c60fe7c041dacaaef33798bcb04ec64c7b34 | @app.route('/task', methods=['POST'])
def add_task():
'\n Define route for task\n\n :return: application page\n '
task = request.form['body']
if (task is None):
raise Exception('Empty task')
else:
add_task_to_db(task)
return redirect('/') | Define route for task
:return: application page | todo/views.py | add_task | ygivenx/todo | 0 | python | @app.route('/task', methods=['POST'])
def add_task():
'\n Define route for task\n\n :return: application page\n '
task = request.form['body']
if (task is None):
raise Exception('Empty task')
else:
add_task_to_db(task)
return redirect('/') | @app.route('/task', methods=['POST'])
def add_task():
'\n Define route for task\n\n :return: application page\n '
task = request.form['body']
if (task is None):
raise Exception('Empty task')
else:
add_task_to_db(task)
return redirect('/')<|docstring|>Define route for task
:return: application page<|endoftext|> |
a1036935d9df5a260af7535b0412d3925f103c1cb98d5e700a72119569bee831 | @app.route('/done/<id>')
def complete_task(id):
'\n Route to mark a task complete\n\n :param id: ID for task to be completed\n :return: application page\n '
finish_task(id)
return redirect('/') | Route to mark a task complete
:param id: ID for task to be completed
:return: application page | todo/views.py | complete_task | ygivenx/todo | 0 | python | @app.route('/done/<id>')
def complete_task(id):
'\n Route to mark a task complete\n\n :param id: ID for task to be completed\n :return: application page\n '
finish_task(id)
return redirect('/') | @app.route('/done/<id>')
def complete_task(id):
'\n Route to mark a task complete\n\n :param id: ID for task to be completed\n :return: application page\n '
finish_task(id)
return redirect('/')<|docstring|>Route to mark a task complete
:param id: ID for task to be completed
:return: application page<|endoftext|> |
872f740625366d4ac23b4909e5af7913bcbd866b8c1d71a3b713f4f45cc43458 | @app.route('/delete/<id>')
def remove_task(id):
'\n Route to mark delete a task\n\n :param id: ID of task to be deleted\n :return: application page\n '
delete_task(id)
return redirect('/') | Route to mark delete a task
:param id: ID of task to be deleted
:return: application page | todo/views.py | remove_task | ygivenx/todo | 0 | python | @app.route('/delete/<id>')
def remove_task(id):
'\n Route to mark delete a task\n\n :param id: ID of task to be deleted\n :return: application page\n '
delete_task(id)
return redirect('/') | @app.route('/delete/<id>')
def remove_task(id):
'\n Route to mark delete a task\n\n :param id: ID of task to be deleted\n :return: application page\n '
delete_task(id)
return redirect('/')<|docstring|>Route to mark delete a task
:param id: ID of task to be deleted
:return: application page<|endoftext|> |
94a1c369e0880628047fd99922dfc2a62d3684779098fae7e5b2bb4772be7362 | @task
def monitor(c, prod=True):
'Start system monitor process\n\n The process will get the system all kinds of metric data and publish them into kafka\n '
if prod:
load_dotenv()
start_monitor() | Start system monitor process
The process will get the system all kinds of metric data and publish them into kafka | tasks.py | monitor | jingwangian/aiven | 0 | python | @task
def monitor(c, prod=True):
'Start system monitor process\n\n The process will get the system all kinds of metric data and publish them into kafka\n '
if prod:
load_dotenv()
start_monitor() | @task
def monitor(c, prod=True):
'Start system monitor process\n\n The process will get the system all kinds of metric data and publish them into kafka\n '
if prod:
load_dotenv()
start_monitor()<|docstring|>Start system monitor process
The process will get the system all kinds of metric data and publish them into kafka<|endoftext|> |
7bad2141a3a03dbf417c9de58ff1c5703363b0db0744181888c41b0e0576c1f1 | @task
def etl(c, prod=True):
'Start etl process\n\n The etl process will get the data from kafka and save the result into database\n '
if prod:
load_dotenv()
start_etl() | Start etl process
The etl process will get the data from kafka and save the result into database | tasks.py | etl | jingwangian/aiven | 0 | python | @task
def etl(c, prod=True):
'Start etl process\n\n The etl process will get the data from kafka and save the result into database\n '
if prod:
load_dotenv()
start_etl() | @task
def etl(c, prod=True):
'Start etl process\n\n The etl process will get the data from kafka and save the result into database\n '
if prod:
load_dotenv()
start_etl()<|docstring|>Start etl process
The etl process will get the data from kafka and save the result into database<|endoftext|> |
691680962a39fda067bd61091a5c1be181ec336e5ab6583b0d2f236c7be8eba1 | def test_touched_segments():
'Test detection of touched segments and records of active segments\n '
rng = np.random.RandomState(42)
(H, W) = sig_support = (108, 53)
n_seg = (9, 3)
for h_radius in [5, 7, 9]:
for w_radius in [3, 11]:
for _ in range(20):
h0 = rng.randint((- h_radius), (sig_support[0] + h_radius))
w0 = rng.randint((- w_radius), (sig_support[1] + w_radius))
z = np.zeros(sig_support)
segments = Segmentation(n_seg, signal_support=sig_support)
touched_slice = (slice(max(0, (h0 - h_radius)), min(H, ((h0 + h_radius) + 1))), slice(max(0, (w0 - w_radius)), min(W, ((w0 + w_radius) + 1))))
z[touched_slice] = 1
touched_segments = segments.get_touched_segments((h0, w0), (h_radius, w_radius))
segments.set_inactive_segments(touched_segments)
n_active_segments = segments._n_active_segments
expected_n_active_segments = segments.effective_n_seg
for i_seg in range(segments.effective_n_seg):
seg_slice = segments.get_seg_slice(i_seg)
is_touched = np.any((z[seg_slice] == 1))
expected_n_active_segments -= is_touched
assert (segments.is_active_segment(i_seg) != is_touched)
assert (n_active_segments == expected_n_active_segments)
segments = Segmentation(n_seg, signal_support=sig_support)
with pytest.raises(ValueError, match='too large'):
segments.get_touched_segments((0, 0), (30, 2)) | Test detection of touched segments and records of active segments | dicodile/utils/tests/test_segmentation.py | test_touched_segments | hndgzkn/dicodile | 15 | python | def test_touched_segments():
'\n '
rng = np.random.RandomState(42)
(H, W) = sig_support = (108, 53)
n_seg = (9, 3)
for h_radius in [5, 7, 9]:
for w_radius in [3, 11]:
for _ in range(20):
h0 = rng.randint((- h_radius), (sig_support[0] + h_radius))
w0 = rng.randint((- w_radius), (sig_support[1] + w_radius))
z = np.zeros(sig_support)
segments = Segmentation(n_seg, signal_support=sig_support)
touched_slice = (slice(max(0, (h0 - h_radius)), min(H, ((h0 + h_radius) + 1))), slice(max(0, (w0 - w_radius)), min(W, ((w0 + w_radius) + 1))))
z[touched_slice] = 1
touched_segments = segments.get_touched_segments((h0, w0), (h_radius, w_radius))
segments.set_inactive_segments(touched_segments)
n_active_segments = segments._n_active_segments
expected_n_active_segments = segments.effective_n_seg
for i_seg in range(segments.effective_n_seg):
seg_slice = segments.get_seg_slice(i_seg)
is_touched = np.any((z[seg_slice] == 1))
expected_n_active_segments -= is_touched
assert (segments.is_active_segment(i_seg) != is_touched)
assert (n_active_segments == expected_n_active_segments)
segments = Segmentation(n_seg, signal_support=sig_support)
with pytest.raises(ValueError, match='too large'):
segments.get_touched_segments((0, 0), (30, 2)) | def test_touched_segments():
'\n '
rng = np.random.RandomState(42)
(H, W) = sig_support = (108, 53)
n_seg = (9, 3)
for h_radius in [5, 7, 9]:
for w_radius in [3, 11]:
for _ in range(20):
h0 = rng.randint((- h_radius), (sig_support[0] + h_radius))
w0 = rng.randint((- w_radius), (sig_support[1] + w_radius))
z = np.zeros(sig_support)
segments = Segmentation(n_seg, signal_support=sig_support)
touched_slice = (slice(max(0, (h0 - h_radius)), min(H, ((h0 + h_radius) + 1))), slice(max(0, (w0 - w_radius)), min(W, ((w0 + w_radius) + 1))))
z[touched_slice] = 1
touched_segments = segments.get_touched_segments((h0, w0), (h_radius, w_radius))
segments.set_inactive_segments(touched_segments)
n_active_segments = segments._n_active_segments
expected_n_active_segments = segments.effective_n_seg
for i_seg in range(segments.effective_n_seg):
seg_slice = segments.get_seg_slice(i_seg)
is_touched = np.any((z[seg_slice] == 1))
expected_n_active_segments -= is_touched
assert (segments.is_active_segment(i_seg) != is_touched)
assert (n_active_segments == expected_n_active_segments)
segments = Segmentation(n_seg, signal_support=sig_support)
with pytest.raises(ValueError, match='too large'):
segments.get_touched_segments((0, 0), (30, 2))<|docstring|>Test detection of touched segments and records of active segments<|endoftext|> |
ee27788a1122e38ea6225b55aca09f09e63268a61f92f1cce98ac85cb771310b | @select_query
def hkeys(self, query, attr):
'\n Enumerates the keys in the specified hstore.\n '
query.add_extra({'_': ('akeys("%s")' % attr)}, None, None, None, None, None)
result = query.get_compiler(self.db).execute_sql(SINGLE)
return (result[0] if result else []) | Enumerates the keys in the specified hstore. | django_hstore/query.py | hkeys | romantolkachyov/django-hstore | 206 | python | @select_query
def hkeys(self, query, attr):
'\n \n '
query.add_extra({'_': ('akeys("%s")' % attr)}, None, None, None, None, None)
result = query.get_compiler(self.db).execute_sql(SINGLE)
return (result[0] if result else []) | @select_query
def hkeys(self, query, attr):
'\n \n '
query.add_extra({'_': ('akeys("%s")' % attr)}, None, None, None, None, None)
result = query.get_compiler(self.db).execute_sql(SINGLE)
return (result[0] if result else [])<|docstring|>Enumerates the keys in the specified hstore.<|endoftext|> |
15c84d74c17acbba2217a3cc83f660cbfd492b502658d352f4d9e5f1caf270d5 | @select_query
def hpeek(self, query, attr, key):
'\n Peeks at a value of the specified key.\n '
query.add_extra({'_': ('%s -> %%s' % attr)}, [key], None, None, None, None)
result = query.get_compiler(self.db).execute_sql(SINGLE)
if (result and result[0]):
field = get_field(self, attr)
return field._value_to_python(result[0]) | Peeks at a value of the specified key. | django_hstore/query.py | hpeek | romantolkachyov/django-hstore | 206 | python | @select_query
def hpeek(self, query, attr, key):
'\n \n '
query.add_extra({'_': ('%s -> %%s' % attr)}, [key], None, None, None, None)
result = query.get_compiler(self.db).execute_sql(SINGLE)
if (result and result[0]):
field = get_field(self, attr)
return field._value_to_python(result[0]) | @select_query
def hpeek(self, query, attr, key):
'\n \n '
query.add_extra({'_': ('%s -> %%s' % attr)}, [key], None, None, None, None)
result = query.get_compiler(self.db).execute_sql(SINGLE)
if (result and result[0]):
field = get_field(self, attr)
return field._value_to_python(result[0])<|docstring|>Peeks at a value of the specified key.<|endoftext|> |
60512f86e98798f566a8506e1ec83e21db6e64144de13545da83fd71d24d2919 | @select_query
def hslice(self, query, attr, keys):
'\n Slices the specified key/value pairs.\n '
query.add_extra({'_': ('slice("%s", %%s)' % attr)}, [keys], None, None, None, None)
result = query.get_compiler(self.db).execute_sql(SINGLE)
if (result and result[0]):
field = get_field(self, attr)
return dict(((key, field._value_to_python(value)) for (key, value) in result[0].items()))
return {} | Slices the specified key/value pairs. | django_hstore/query.py | hslice | romantolkachyov/django-hstore | 206 | python | @select_query
def hslice(self, query, attr, keys):
'\n \n '
query.add_extra({'_': ('slice("%s", %%s)' % attr)}, [keys], None, None, None, None)
result = query.get_compiler(self.db).execute_sql(SINGLE)
if (result and result[0]):
field = get_field(self, attr)
return dict(((key, field._value_to_python(value)) for (key, value) in result[0].items()))
return {} | @select_query
def hslice(self, query, attr, keys):
'\n \n '
query.add_extra({'_': ('slice("%s", %%s)' % attr)}, [keys], None, None, None, None)
result = query.get_compiler(self.db).execute_sql(SINGLE)
if (result and result[0]):
field = get_field(self, attr)
return dict(((key, field._value_to_python(value)) for (key, value) in result[0].items()))
return {}<|docstring|>Slices the specified key/value pairs.<|endoftext|> |
f63107c0dc02c4d00ce62d6fba989ccea03517cedfaf4f7b69497fed0f6da735 | @update_query
def hremove(self, query, attr, keys):
'\n Removes the specified keys in the specified hstore.\n '
value = QueryWrapper(('delete("%s", %%s)' % attr), [keys])
field = get_field(self, attr)
query.add_update_fields([(field, None, value)])
return query | Removes the specified keys in the specified hstore. | django_hstore/query.py | hremove | romantolkachyov/django-hstore | 206 | python | @update_query
def hremove(self, query, attr, keys):
'\n \n '
value = QueryWrapper(('delete("%s", %%s)' % attr), [keys])
field = get_field(self, attr)
query.add_update_fields([(field, None, value)])
return query | @update_query
def hremove(self, query, attr, keys):
'\n \n '
value = QueryWrapper(('delete("%s", %%s)' % attr), [keys])
field = get_field(self, attr)
query.add_update_fields([(field, None, value)])
return query<|docstring|>Removes the specified keys in the specified hstore.<|endoftext|> |
844b61b9592b5f81ce658a548198e95a2d801e295ec9860267971e0a3d8964e5 | @update_query
def hupdate(self, query, attr, updates):
'\n Updates the specified hstore.\n '
field = get_field(self, attr)
if hasattr(field, 'serializer'):
updates = field.get_prep_value(updates)
value = QueryWrapper(('"%s" || %%s' % attr), [updates])
query.add_update_fields([(field, None, value)])
return query | Updates the specified hstore. | django_hstore/query.py | hupdate | romantolkachyov/django-hstore | 206 | python | @update_query
def hupdate(self, query, attr, updates):
'\n \n '
field = get_field(self, attr)
if hasattr(field, 'serializer'):
updates = field.get_prep_value(updates)
value = QueryWrapper(('"%s" || %%s' % attr), [updates])
query.add_update_fields([(field, None, value)])
return query | @update_query
def hupdate(self, query, attr, updates):
'\n \n '
field = get_field(self, attr)
if hasattr(field, 'serializer'):
updates = field.get_prep_value(updates)
value = QueryWrapper(('"%s" || %%s' % attr), [updates])
query.add_update_fields([(field, None, value)])
return query<|docstring|>Updates the specified hstore.<|endoftext|> |
9a20f081bb5ac8ffd97c531ce6dc7b3aaf9bcf97913d80270a8da9837ab4c854 | def __init__(self, **kwargs):
'\n Initializes a new ShuffleFormatEntry object with values from keyword arguments. The default value of the :py:attr:`~oci.data_safe.models.ShuffleFormatEntry.type` attribute\n of this class is ``SHUFFLE`` and it should not be changed.\n The following keyword arguments are supported (corresponding to the getters/setters of this class):\n\n :param type:\n The value to assign to the type property of this ShuffleFormatEntry.\n Allowed values for this property are: "DELETE_ROWS", "DETERMINISTIC_SUBSTITUTION", "DETERMINISTIC_ENCRYPTION", "DETERMINISTIC_ENCRYPTION_DATE", "FIXED_NUMBER", "FIXED_STRING", "LIBRARY_MASKING_FORMAT", "NULL_VALUE", "POST_PROCESSING_FUNCTION", "PRESERVE_ORIGINAL_DATA", "RANDOM_DATE", "RANDOM_DECIMAL_NUMBER", "RANDOM_DIGITS", "RANDOM_LIST", "RANDOM_NUMBER", "RANDOM_STRING", "RANDOM_SUBSTITUTION", "REGULAR_EXPRESSION", "SHUFFLE", "SQL_EXPRESSION", "SUBSTRING", "TRUNCATE_TABLE", "USER_DEFINED_FUNCTION"\n :type type: str\n\n :param description:\n The value to assign to the description property of this ShuffleFormatEntry.\n :type description: str\n\n :param grouping_columns:\n The value to assign to the grouping_columns property of this ShuffleFormatEntry.\n :type grouping_columns: list[str]\n\n '
self.swagger_types = {'type': 'str', 'description': 'str', 'grouping_columns': 'list[str]'}
self.attribute_map = {'type': 'type', 'description': 'description', 'grouping_columns': 'groupingColumns'}
self._type = None
self._description = None
self._grouping_columns = None
self._type = 'SHUFFLE' | Initializes a new ShuffleFormatEntry object with values from keyword arguments. The default value of the :py:attr:`~oci.data_safe.models.ShuffleFormatEntry.type` attribute
of this class is ``SHUFFLE`` and it should not be changed.
The following keyword arguments are supported (corresponding to the getters/setters of this class):
:param type:
The value to assign to the type property of this ShuffleFormatEntry.
Allowed values for this property are: "DELETE_ROWS", "DETERMINISTIC_SUBSTITUTION", "DETERMINISTIC_ENCRYPTION", "DETERMINISTIC_ENCRYPTION_DATE", "FIXED_NUMBER", "FIXED_STRING", "LIBRARY_MASKING_FORMAT", "NULL_VALUE", "POST_PROCESSING_FUNCTION", "PRESERVE_ORIGINAL_DATA", "RANDOM_DATE", "RANDOM_DECIMAL_NUMBER", "RANDOM_DIGITS", "RANDOM_LIST", "RANDOM_NUMBER", "RANDOM_STRING", "RANDOM_SUBSTITUTION", "REGULAR_EXPRESSION", "SHUFFLE", "SQL_EXPRESSION", "SUBSTRING", "TRUNCATE_TABLE", "USER_DEFINED_FUNCTION"
:type type: str
:param description:
The value to assign to the description property of this ShuffleFormatEntry.
:type description: str
:param grouping_columns:
The value to assign to the grouping_columns property of this ShuffleFormatEntry.
:type grouping_columns: list[str] | src/oci/data_safe/models/shuffle_format_entry.py | __init__ | ionaryu/oci-python-sdk | 0 | python | def __init__(self, **kwargs):
'\n Initializes a new ShuffleFormatEntry object with values from keyword arguments. The default value of the :py:attr:`~oci.data_safe.models.ShuffleFormatEntry.type` attribute\n of this class is ``SHUFFLE`` and it should not be changed.\n The following keyword arguments are supported (corresponding to the getters/setters of this class):\n\n :param type:\n The value to assign to the type property of this ShuffleFormatEntry.\n Allowed values for this property are: "DELETE_ROWS", "DETERMINISTIC_SUBSTITUTION", "DETERMINISTIC_ENCRYPTION", "DETERMINISTIC_ENCRYPTION_DATE", "FIXED_NUMBER", "FIXED_STRING", "LIBRARY_MASKING_FORMAT", "NULL_VALUE", "POST_PROCESSING_FUNCTION", "PRESERVE_ORIGINAL_DATA", "RANDOM_DATE", "RANDOM_DECIMAL_NUMBER", "RANDOM_DIGITS", "RANDOM_LIST", "RANDOM_NUMBER", "RANDOM_STRING", "RANDOM_SUBSTITUTION", "REGULAR_EXPRESSION", "SHUFFLE", "SQL_EXPRESSION", "SUBSTRING", "TRUNCATE_TABLE", "USER_DEFINED_FUNCTION"\n :type type: str\n\n :param description:\n The value to assign to the description property of this ShuffleFormatEntry.\n :type description: str\n\n :param grouping_columns:\n The value to assign to the grouping_columns property of this ShuffleFormatEntry.\n :type grouping_columns: list[str]\n\n '
self.swagger_types = {'type': 'str', 'description': 'str', 'grouping_columns': 'list[str]'}
self.attribute_map = {'type': 'type', 'description': 'description', 'grouping_columns': 'groupingColumns'}
self._type = None
self._description = None
self._grouping_columns = None
self._type = 'SHUFFLE' | def __init__(self, **kwargs):
'\n Initializes a new ShuffleFormatEntry object with values from keyword arguments. The default value of the :py:attr:`~oci.data_safe.models.ShuffleFormatEntry.type` attribute\n of this class is ``SHUFFLE`` and it should not be changed.\n The following keyword arguments are supported (corresponding to the getters/setters of this class):\n\n :param type:\n The value to assign to the type property of this ShuffleFormatEntry.\n Allowed values for this property are: "DELETE_ROWS", "DETERMINISTIC_SUBSTITUTION", "DETERMINISTIC_ENCRYPTION", "DETERMINISTIC_ENCRYPTION_DATE", "FIXED_NUMBER", "FIXED_STRING", "LIBRARY_MASKING_FORMAT", "NULL_VALUE", "POST_PROCESSING_FUNCTION", "PRESERVE_ORIGINAL_DATA", "RANDOM_DATE", "RANDOM_DECIMAL_NUMBER", "RANDOM_DIGITS", "RANDOM_LIST", "RANDOM_NUMBER", "RANDOM_STRING", "RANDOM_SUBSTITUTION", "REGULAR_EXPRESSION", "SHUFFLE", "SQL_EXPRESSION", "SUBSTRING", "TRUNCATE_TABLE", "USER_DEFINED_FUNCTION"\n :type type: str\n\n :param description:\n The value to assign to the description property of this ShuffleFormatEntry.\n :type description: str\n\n :param grouping_columns:\n The value to assign to the grouping_columns property of this ShuffleFormatEntry.\n :type grouping_columns: list[str]\n\n '
self.swagger_types = {'type': 'str', 'description': 'str', 'grouping_columns': 'list[str]'}
self.attribute_map = {'type': 'type', 'description': 'description', 'grouping_columns': 'groupingColumns'}
self._type = None
self._description = None
self._grouping_columns = None
self._type = 'SHUFFLE'<|docstring|>Initializes a new ShuffleFormatEntry object with values from keyword arguments. The default value of the :py:attr:`~oci.data_safe.models.ShuffleFormatEntry.type` attribute
of this class is ``SHUFFLE`` and it should not be changed.
The following keyword arguments are supported (corresponding to the getters/setters of this class):
:param type:
The value to assign to the type property of this ShuffleFormatEntry.
Allowed values for this property are: "DELETE_ROWS", "DETERMINISTIC_SUBSTITUTION", "DETERMINISTIC_ENCRYPTION", "DETERMINISTIC_ENCRYPTION_DATE", "FIXED_NUMBER", "FIXED_STRING", "LIBRARY_MASKING_FORMAT", "NULL_VALUE", "POST_PROCESSING_FUNCTION", "PRESERVE_ORIGINAL_DATA", "RANDOM_DATE", "RANDOM_DECIMAL_NUMBER", "RANDOM_DIGITS", "RANDOM_LIST", "RANDOM_NUMBER", "RANDOM_STRING", "RANDOM_SUBSTITUTION", "REGULAR_EXPRESSION", "SHUFFLE", "SQL_EXPRESSION", "SUBSTRING", "TRUNCATE_TABLE", "USER_DEFINED_FUNCTION"
:type type: str
:param description:
The value to assign to the description property of this ShuffleFormatEntry.
:type description: str
:param grouping_columns:
The value to assign to the grouping_columns property of this ShuffleFormatEntry.
:type grouping_columns: list[str]<|endoftext|> |
a3ad75f03ff7d6506b7c358dc570194df49a2c046929a682a75e6d341f49f9a0 | @property
def grouping_columns(self):
'\n Gets the grouping_columns of this ShuffleFormatEntry.\n One or more reference columns to be used to group column values so that\n they can be shuffled within their own group. The grouping columns and\n the column to be masked must belong to the same table.\n\n\n :return: The grouping_columns of this ShuffleFormatEntry.\n :rtype: list[str]\n '
return self._grouping_columns | Gets the grouping_columns of this ShuffleFormatEntry.
One or more reference columns to be used to group column values so that
they can be shuffled within their own group. The grouping columns and
the column to be masked must belong to the same table.
:return: The grouping_columns of this ShuffleFormatEntry.
:rtype: list[str] | src/oci/data_safe/models/shuffle_format_entry.py | grouping_columns | ionaryu/oci-python-sdk | 0 | python | @property
def grouping_columns(self):
'\n Gets the grouping_columns of this ShuffleFormatEntry.\n One or more reference columns to be used to group column values so that\n they can be shuffled within their own group. The grouping columns and\n the column to be masked must belong to the same table.\n\n\n :return: The grouping_columns of this ShuffleFormatEntry.\n :rtype: list[str]\n '
return self._grouping_columns | @property
def grouping_columns(self):
'\n Gets the grouping_columns of this ShuffleFormatEntry.\n One or more reference columns to be used to group column values so that\n they can be shuffled within their own group. The grouping columns and\n the column to be masked must belong to the same table.\n\n\n :return: The grouping_columns of this ShuffleFormatEntry.\n :rtype: list[str]\n '
return self._grouping_columns<|docstring|>Gets the grouping_columns of this ShuffleFormatEntry.
One or more reference columns to be used to group column values so that
they can be shuffled within their own group. The grouping columns and
the column to be masked must belong to the same table.
:return: The grouping_columns of this ShuffleFormatEntry.
:rtype: list[str]<|endoftext|> |
e81341f22ad535880434a19eaed1ab238e80c2cee8c58b8eb88ddfecbe762a88 | @grouping_columns.setter
def grouping_columns(self, grouping_columns):
'\n Sets the grouping_columns of this ShuffleFormatEntry.\n One or more reference columns to be used to group column values so that\n they can be shuffled within their own group. The grouping columns and\n the column to be masked must belong to the same table.\n\n\n :param grouping_columns: The grouping_columns of this ShuffleFormatEntry.\n :type: list[str]\n '
self._grouping_columns = grouping_columns | Sets the grouping_columns of this ShuffleFormatEntry.
One or more reference columns to be used to group column values so that
they can be shuffled within their own group. The grouping columns and
the column to be masked must belong to the same table.
:param grouping_columns: The grouping_columns of this ShuffleFormatEntry.
:type: list[str] | src/oci/data_safe/models/shuffle_format_entry.py | grouping_columns | ionaryu/oci-python-sdk | 0 | python | @grouping_columns.setter
def grouping_columns(self, grouping_columns):
'\n Sets the grouping_columns of this ShuffleFormatEntry.\n One or more reference columns to be used to group column values so that\n they can be shuffled within their own group. The grouping columns and\n the column to be masked must belong to the same table.\n\n\n :param grouping_columns: The grouping_columns of this ShuffleFormatEntry.\n :type: list[str]\n '
self._grouping_columns = grouping_columns | @grouping_columns.setter
def grouping_columns(self, grouping_columns):
'\n Sets the grouping_columns of this ShuffleFormatEntry.\n One or more reference columns to be used to group column values so that\n they can be shuffled within their own group. The grouping columns and\n the column to be masked must belong to the same table.\n\n\n :param grouping_columns: The grouping_columns of this ShuffleFormatEntry.\n :type: list[str]\n '
self._grouping_columns = grouping_columns<|docstring|>Sets the grouping_columns of this ShuffleFormatEntry.
One or more reference columns to be used to group column values so that
they can be shuffled within their own group. The grouping columns and
the column to be masked must belong to the same table.
:param grouping_columns: The grouping_columns of this ShuffleFormatEntry.
:type: list[str]<|endoftext|> |
11a88b3953dcbd5840217b78cfc33fb43617513daaa404cb44b140862ac51109 | def validate_plan(plan):
' "\n Ensure that maximum amount of resources with current plan is not reached yet.\n '
if (not plan.is_active):
raise rf_exceptions.ValidationError({'plan': _('Plan is not available because limit has been reached.')}) | "
Ensure that maximum amount of resources with current plan is not reached yet. | src/waldur_mastermind/marketplace/serializers.py | validate_plan | ServerAnt/Billing-Backend | 26 | python | def validate_plan(plan):
' "\n Ensure that maximum amount of resources with current plan is not reached yet.\n '
if (not plan.is_active):
raise rf_exceptions.ValidationError({'plan': _('Plan is not available because limit has been reached.')}) | def validate_plan(plan):
' "\n Ensure that maximum amount of resources with current plan is not reached yet.\n '
if (not plan.is_active):
raise rf_exceptions.ValidationError({'plan': _('Plan is not available because limit has been reached.')})<|docstring|>"
Ensure that maximum amount of resources with current plan is not reached yet.<|endoftext|> |
f9a7f856db6eb577b632b2dbd3e6615fcab8a96d3a7ac6f5b87d0bcec664ac59 | def _create_service(self, validated_data):
"\n Marketplace offering model does not accept service_attributes field as is,\n therefore we should remove it from validated_data and create service settings object.\n Then we need to specify created object and offering's scope.\n "
offering_type = validated_data.get('type')
service_type = plugins.manager.get_service_type(offering_type)
name = validated_data['name']
service_attributes = validated_data.pop('service_attributes', {})
if (not service_type):
return validated_data
if (not service_attributes):
raise ValidationError({'service_attributes': _('This field is required.')})
payload = dict(name=name, customer=self.initial_data['customer'], type=service_type, options=service_attributes)
serializer = ServiceSettingsSerializer(data=payload, context=self.context)
serializer.is_valid(raise_exception=True)
service_settings = serializer.save()
if validated_data.get('shared'):
service_settings.shared = True
service_settings.save()
transaction.on_commit((lambda : ServiceSettingsCreateExecutor.execute(service_settings)))
validated_data['scope'] = service_settings
return validated_data | Marketplace offering model does not accept service_attributes field as is,
therefore we should remove it from validated_data and create service settings object.
Then we need to specify created object and offering's scope. | src/waldur_mastermind/marketplace/serializers.py | _create_service | ServerAnt/Billing-Backend | 26 | python | def _create_service(self, validated_data):
"\n Marketplace offering model does not accept service_attributes field as is,\n therefore we should remove it from validated_data and create service settings object.\n Then we need to specify created object and offering's scope.\n "
offering_type = validated_data.get('type')
service_type = plugins.manager.get_service_type(offering_type)
name = validated_data['name']
service_attributes = validated_data.pop('service_attributes', {})
if (not service_type):
return validated_data
if (not service_attributes):
raise ValidationError({'service_attributes': _('This field is required.')})
payload = dict(name=name, customer=self.initial_data['customer'], type=service_type, options=service_attributes)
serializer = ServiceSettingsSerializer(data=payload, context=self.context)
serializer.is_valid(raise_exception=True)
service_settings = serializer.save()
if validated_data.get('shared'):
service_settings.shared = True
service_settings.save()
transaction.on_commit((lambda : ServiceSettingsCreateExecutor.execute(service_settings)))
validated_data['scope'] = service_settings
return validated_data | def _create_service(self, validated_data):
"\n Marketplace offering model does not accept service_attributes field as is,\n therefore we should remove it from validated_data and create service settings object.\n Then we need to specify created object and offering's scope.\n "
offering_type = validated_data.get('type')
service_type = plugins.manager.get_service_type(offering_type)
name = validated_data['name']
service_attributes = validated_data.pop('service_attributes', {})
if (not service_type):
return validated_data
if (not service_attributes):
raise ValidationError({'service_attributes': _('This field is required.')})
payload = dict(name=name, customer=self.initial_data['customer'], type=service_type, options=service_attributes)
serializer = ServiceSettingsSerializer(data=payload, context=self.context)
serializer.is_valid(raise_exception=True)
service_settings = serializer.save()
if validated_data.get('shared'):
service_settings.shared = True
service_settings.save()
transaction.on_commit((lambda : ServiceSettingsCreateExecutor.execute(service_settings)))
validated_data['scope'] = service_settings
return validated_data<|docstring|>Marketplace offering model does not accept service_attributes field as is,
therefore we should remove it from validated_data and create service settings object.
Then we need to specify created object and offering's scope.<|endoftext|> |
b3e042e7692dfa9eeec347dfe7a816f4fcf4d4cbba80db521735c8fae05b6ef9 | @transaction.atomic
def update(self, instance, validated_data):
"\n Components and plans are specified using nested list serializers with many=True.\n These serializers return empty list even if value is not provided explicitly.\n See also: https://github.com/encode/django-rest-framework/issues/3434\n Consider the case when offering's thumbnail is uploaded, but plans and components are not specified.\n It leads to tricky bug when all components are removed and plans are marked as archived.\n In order to distinguish between case when user asks to remove all plans and\n case when user wants to update only one attribute these we need to check not only\n validated data, but also initial data.\n "
if ('components' in validated_data):
components = validated_data.pop('components', [])
if ('components' in self.initial_data):
self._update_components(instance, components)
if ('plans' in validated_data):
new_plans = validated_data.pop('plans', [])
if ('plans' in self.initial_data):
self._update_plans(instance, new_plans)
limits = validated_data.pop('limits', {})
if limits:
self._update_limits(instance, limits)
offering = super(OfferingUpdateSerializer, self).update(instance, validated_data)
return offering | Components and plans are specified using nested list serializers with many=True.
These serializers return empty list even if value is not provided explicitly.
See also: https://github.com/encode/django-rest-framework/issues/3434
Consider the case when offering's thumbnail is uploaded, but plans and components are not specified.
It leads to tricky bug when all components are removed and plans are marked as archived.
In order to distinguish between case when user asks to remove all plans and
case when user wants to update only one attribute these we need to check not only
validated data, but also initial data. | src/waldur_mastermind/marketplace/serializers.py | update | ServerAnt/Billing-Backend | 26 | python | @transaction.atomic
def update(self, instance, validated_data):
"\n Components and plans are specified using nested list serializers with many=True.\n These serializers return empty list even if value is not provided explicitly.\n See also: https://github.com/encode/django-rest-framework/issues/3434\n Consider the case when offering's thumbnail is uploaded, but plans and components are not specified.\n It leads to tricky bug when all components are removed and plans are marked as archived.\n In order to distinguish between case when user asks to remove all plans and\n case when user wants to update only one attribute these we need to check not only\n validated data, but also initial data.\n "
if ('components' in validated_data):
components = validated_data.pop('components', [])
if ('components' in self.initial_data):
self._update_components(instance, components)
if ('plans' in validated_data):
new_plans = validated_data.pop('plans', [])
if ('plans' in self.initial_data):
self._update_plans(instance, new_plans)
limits = validated_data.pop('limits', {})
if limits:
self._update_limits(instance, limits)
offering = super(OfferingUpdateSerializer, self).update(instance, validated_data)
return offering | @transaction.atomic
def update(self, instance, validated_data):
"\n Components and plans are specified using nested list serializers with many=True.\n These serializers return empty list even if value is not provided explicitly.\n See also: https://github.com/encode/django-rest-framework/issues/3434\n Consider the case when offering's thumbnail is uploaded, but plans and components are not specified.\n It leads to tricky bug when all components are removed and plans are marked as archived.\n In order to distinguish between case when user asks to remove all plans and\n case when user wants to update only one attribute these we need to check not only\n validated data, but also initial data.\n "
if ('components' in validated_data):
components = validated_data.pop('components', [])
if ('components' in self.initial_data):
self._update_components(instance, components)
if ('plans' in validated_data):
new_plans = validated_data.pop('plans', [])
if ('plans' in self.initial_data):
self._update_plans(instance, new_plans)
limits = validated_data.pop('limits', {})
if limits:
self._update_limits(instance, limits)
offering = super(OfferingUpdateSerializer, self).update(instance, validated_data)
return offering<|docstring|>Components and plans are specified using nested list serializers with many=True.
These serializers return empty list even if value is not provided explicitly.
See also: https://github.com/encode/django-rest-framework/issues/3434
Consider the case when offering's thumbnail is uploaded, but plans and components are not specified.
It leads to tricky bug when all components are removed and plans are marked as archived.
In order to distinguish between case when user asks to remove all plans and
case when user wants to update only one attribute these we need to check not only
validated data, but also initial data.<|endoftext|> |
179faf9b4eeede1c0c5c6e95908a7c71aa864e3011490fca31524dc808505ce5 | @classmethod
def validate_user(cls, first_name, password):
'\n checks if the name and password entered are correct\n '
current_user = ''
for user in User.users_list:
if ((user.first_name == first_name) and (user.password == password)):
current_user = user.first_name
return current_user | checks if the name and password entered are correct | credential_class/credentialclass.py | validate_user | NderituMwanu/PasswdLock | 0 | python | @classmethod
def validate_user(cls, first_name, password):
'\n \n '
current_user =
for user in User.users_list:
if ((user.first_name == first_name) and (user.password == password)):
current_user = user.first_name
return current_user | @classmethod
def validate_user(cls, first_name, password):
'\n \n '
current_user =
for user in User.users_list:
if ((user.first_name == first_name) and (user.password == password)):
current_user = user.first_name
return current_user<|docstring|>checks if the name and password entered are correct<|endoftext|> |
65b1e3ce34635ed220dbd5a77542210846893584a54e842b2d1acb5f1d3ca717 | def __init__(self, first_name, platform_name, ac_name, password):
'\n for each object created, its properties\n '
self.first_name = first_name
self.platformname = platform_name
self.ac_name = ac_name
self.password = password | for each object created, its properties | credential_class/credentialclass.py | __init__ | NderituMwanu/PasswdLock | 0 | python | def __init__(self, first_name, platform_name, ac_name, password):
'\n \n '
self.first_name = first_name
self.platformname = platform_name
self.ac_name = ac_name
self.password = password | def __init__(self, first_name, platform_name, ac_name, password):
'\n \n '
self.first_name = first_name
self.platformname = platform_name
self.ac_name = ac_name
self.password = password<|docstring|>for each object created, its properties<|endoftext|> |
de9df5fd50df9f82996abddc8862ee7b1c198319dae77de3e38d5d91d6988bcc | def save_cred(self):
'\n saves a new credential\n '
Credentials.credentials_list.append(self) | saves a new credential | credential_class/credentialclass.py | save_cred | NderituMwanu/PasswdLock | 0 | python | def save_cred(self):
'\n \n '
Credentials.credentials_list.append(self) | def save_cred(self):
'\n \n '
Credentials.credentials_list.append(self)<|docstring|>saves a new credential<|endoftext|> |
4501cdce7d27f84e2013acb2e8e5a5bfb3cc79182520f3f77236a2b6e9e9ec48 | def delete_credential(self):
'\n Deletes a credential added\n '
Credentials.credentials_list.remove(self) | Deletes a credential added | credential_class/credentialclass.py | delete_credential | NderituMwanu/PasswdLock | 0 | python | def delete_credential(self):
'\n \n '
Credentials.credentials_list.remove(self) | def delete_credential(self):
'\n \n '
Credentials.credentials_list.remove(self)<|docstring|>Deletes a credential added<|endoftext|> |
02da9ceef771c4b418d015a1a9744e0e0f53be22c367b3a8b734b38157d85676 | def generate_passkey(char=(string.ascii_uppercase + string.digits)):
'\n generates 10 character passkey\n '
key_pass = ''.join((random.choice(char) for _ in range(0, 10)))
return key_pass | generates 10 character passkey | credential_class/credentialclass.py | generate_passkey | NderituMwanu/PasswdLock | 0 | python | def generate_passkey(char=(string.ascii_uppercase + string.digits)):
'\n \n '
key_pass = .join((random.choice(char) for _ in range(0, 10)))
return key_pass | def generate_passkey(char=(string.ascii_uppercase + string.digits)):
'\n \n '
key_pass = .join((random.choice(char) for _ in range(0, 10)))
return key_pass<|docstring|>generates 10 character passkey<|endoftext|> |
17f8c2785350efcc676632ea29d40f48d197d4be1f61aae32eb68fae3751b60e | @classmethod
def get_site_name(cls, site_name):
'\n takes a site name and returns creds\n '
for credential in cls.credentials_list:
if (credential.site_name == site_name):
return credential | takes a site name and returns creds | credential_class/credentialclass.py | get_site_name | NderituMwanu/PasswdLock | 0 | python | @classmethod
def get_site_name(cls, site_name):
'\n \n '
for credential in cls.credentials_list:
if (credential.site_name == site_name):
return credential | @classmethod
def get_site_name(cls, site_name):
'\n \n '
for credential in cls.credentials_list:
if (credential.site_name == site_name):
return credential<|docstring|>takes a site name and returns creds<|endoftext|> |
4dfa40f97519cdf32b508e97c28b438b38deff22ff4cfb23c29da65840a87afe | @classmethod
def show_cred(cls, first_name):
"'\n shows all credentials\n "
user_cred_list = []
for credential in cls.credentials_list:
if (credential.first_name == first_name):
user_cred_list.append(credential)
return user_cred_list | '
shows all credentials | credential_class/credentialclass.py | show_cred | NderituMwanu/PasswdLock | 0 | python | @classmethod
def show_cred(cls, first_name):
"'\n shows all credentials\n "
user_cred_list = []
for credential in cls.credentials_list:
if (credential.first_name == first_name):
user_cred_list.append(credential)
return user_cred_list | @classmethod
def show_cred(cls, first_name):
"'\n shows all credentials\n "
user_cred_list = []
for credential in cls.credentials_list:
if (credential.first_name == first_name):
user_cred_list.append(credential)
return user_cred_list<|docstring|>'
shows all credentials<|endoftext|> |
ded23ed2a7fa21ede18137cbfbff8fb4bf237013c14dc5b1b0a14239770bbce1 | def __init__(self, first_name, lastname, password):
'\n properties for each user\n '
self.first_name = first_name
self.lastname = lastname
self.password = password | properties for each user | credential_class/credentialclass.py | __init__ | NderituMwanu/PasswdLock | 0 | python | def __init__(self, first_name, lastname, password):
'\n \n '
self.first_name = first_name
self.lastname = lastname
self.password = password | def __init__(self, first_name, lastname, password):
'\n \n '
self.first_name = first_name
self.lastname = lastname
self.password = password<|docstring|>properties for each user<|endoftext|> |
e3ba082d4ea281a4718e36472447e6f09b4a05361b4b51cfdc0cd4baf7e9c65c | def save_usr(self):
'\n saves a newly created user\n '
User.users_list.append(self) | saves a newly created user | credential_class/credentialclass.py | save_usr | NderituMwanu/PasswdLock | 0 | python | def save_usr(self):
'\n \n '
User.users_list.append(self) | def save_usr(self):
'\n \n '
User.users_list.append(self)<|docstring|>saves a newly created user<|endoftext|> |
f4a6477b4712708b95f4cab7063d27155331a186cdb7a07a977f4fc3d7eb4289 | @classmethod
def show_cred(cls, first_name):
"'\n shows all credentials\n "
user_cred_list = []
for credentials in cls.credentials_list:
if (credential.first_name == first_name):
user_cred_list.append(credentials)
return user_credentials_list | '
shows all credentials | credential_class/credentialclass.py | show_cred | NderituMwanu/PasswdLock | 0 | python | @classmethod
def show_cred(cls, first_name):
"'\n shows all credentials\n "
user_cred_list = []
for credentials in cls.credentials_list:
if (credential.first_name == first_name):
user_cred_list.append(credentials)
return user_credentials_list | @classmethod
def show_cred(cls, first_name):
"'\n shows all credentials\n "
user_cred_list = []
for credentials in cls.credentials_list:
if (credential.first_name == first_name):
user_cred_list.append(credentials)
return user_credentials_list<|docstring|>'
shows all credentials<|endoftext|> |
be8169688b9568767aa46298e727071b6b3e06cc38a66a4bef55d18d9e12d6ce | @staticmethod
@callback
def async_get_options_flow(config_entry):
'Get the options flow for this handler.'
return OptionsFlowHandler(config_entry) | Get the options flow for this handler. | custom_components/googlewifi/config_flow.py | async_get_options_flow | szamfirov/hagooglewifi | 38 | python | @staticmethod
@callback
def async_get_options_flow(config_entry):
return OptionsFlowHandler(config_entry) | @staticmethod
@callback
def async_get_options_flow(config_entry):
return OptionsFlowHandler(config_entry)<|docstring|>Get the options flow for this handler.<|endoftext|> |
544efd5543eaedae75ab4c10184b48d5180494b8416845e33cade84634871991 | async def async_step_user(self, user_input=None):
'Handle the initial step.'
errors = {}
config_entry = self.hass.config_entries.async_entries(DOMAIN)
if config_entry:
return self.async_abort(reason='single_instance_allowed')
if (user_input is not None):
session = aiohttp_client.async_get_clientsession(self.hass)
token = user_input[REFRESH_TOKEN]
api_client = GoogleWifi(token, session)
try:
(await api_client.connect())
except ValueError:
errors['base'] = 'invalid_auth'
except ConnectionError:
errors['base'] = 'cannot_connect'
except Exception:
_LOGGER.exception('Unexpected exception')
errors['base'] = 'unknown'
else:
(await self.async_set_unique_id(user_input[REFRESH_TOKEN]))
self._abort_if_unique_id_configured()
return self.async_create_entry(title='Google Wifi', data=user_input)
return self.async_show_form(step_id='user', data_schema=vol.Schema({vol.Required(REFRESH_TOKEN): str, vol.Required(ADD_DISABLED, default=True): bool}), errors=errors) | Handle the initial step. | custom_components/googlewifi/config_flow.py | async_step_user | szamfirov/hagooglewifi | 38 | python | async def async_step_user(self, user_input=None):
errors = {}
config_entry = self.hass.config_entries.async_entries(DOMAIN)
if config_entry:
return self.async_abort(reason='single_instance_allowed')
if (user_input is not None):
session = aiohttp_client.async_get_clientsession(self.hass)
token = user_input[REFRESH_TOKEN]
api_client = GoogleWifi(token, session)
try:
(await api_client.connect())
except ValueError:
errors['base'] = 'invalid_auth'
except ConnectionError:
errors['base'] = 'cannot_connect'
except Exception:
_LOGGER.exception('Unexpected exception')
errors['base'] = 'unknown'
else:
(await self.async_set_unique_id(user_input[REFRESH_TOKEN]))
self._abort_if_unique_id_configured()
return self.async_create_entry(title='Google Wifi', data=user_input)
return self.async_show_form(step_id='user', data_schema=vol.Schema({vol.Required(REFRESH_TOKEN): str, vol.Required(ADD_DISABLED, default=True): bool}), errors=errors) | async def async_step_user(self, user_input=None):
errors = {}
config_entry = self.hass.config_entries.async_entries(DOMAIN)
if config_entry:
return self.async_abort(reason='single_instance_allowed')
if (user_input is not None):
session = aiohttp_client.async_get_clientsession(self.hass)
token = user_input[REFRESH_TOKEN]
api_client = GoogleWifi(token, session)
try:
(await api_client.connect())
except ValueError:
errors['base'] = 'invalid_auth'
except ConnectionError:
errors['base'] = 'cannot_connect'
except Exception:
_LOGGER.exception('Unexpected exception')
errors['base'] = 'unknown'
else:
(await self.async_set_unique_id(user_input[REFRESH_TOKEN]))
self._abort_if_unique_id_configured()
return self.async_create_entry(title='Google Wifi', data=user_input)
return self.async_show_form(step_id='user', data_schema=vol.Schema({vol.Required(REFRESH_TOKEN): str, vol.Required(ADD_DISABLED, default=True): bool}), errors=errors)<|docstring|>Handle the initial step.<|endoftext|> |
5865c492004e421d73e30bc7207c58989112e05adafcbad48fceb5bc142b7fde | def __init__(self, config_entry):
'Initialize options flow.'
self.config_entry = config_entry | Initialize options flow. | custom_components/googlewifi/config_flow.py | __init__ | szamfirov/hagooglewifi | 38 | python | def __init__(self, config_entry):
self.config_entry = config_entry | def __init__(self, config_entry):
self.config_entry = config_entry<|docstring|>Initialize options flow.<|endoftext|> |
2fa97dcc126ced2dbce89b7ad5f7b435a187537356a193f5940e35cf145c9c7a | async def async_step_init(self, user_input=None):
'Manage options.'
if (user_input is not None):
return self.async_create_entry(title='', data=user_input)
return self.async_show_form(step_id='init', data_schema=vol.Schema({vol.Optional(CONF_SCAN_INTERVAL, default=self.config_entry.options.get(CONF_SCAN_INTERVAL, POLLING_INTERVAL)): vol.All(vol.Coerce(int), vol.Range(min=3)), vol.Optional(CONF_SPEEDTEST, default=self.config_entry.options.get(CONF_SPEEDTEST, DEFAULT_SPEEDTEST)): bool, vol.Optional(CONF_SPEEDTEST_INTERVAL, default=self.config_entry.options.get(CONF_SPEEDTEST_INTERVAL, DEFAULT_SPEEDTEST_INTERVAL)): vol.Coerce(int), vol.Optional(CONF_SPEED_UNITS, default=self.config_entry.options.get(CONF_SPEED_UNITS, DATA_RATE_MEGABITS_PER_SECOND)): vol.In({DATA_RATE_KILOBITS_PER_SECOND: 'kbits/s', DATA_RATE_MEGABITS_PER_SECOND: 'Mbit/s', DATA_RATE_GIGABITS_PER_SECOND: 'Gbit/s', DATA_RATE_BYTES_PER_SECOND: 'B/s', DATA_RATE_KILOBYTES_PER_SECOND: 'kB/s', DATA_RATE_MEGABYTES_PER_SECOND: 'MB/s', DATA_RATE_GIGABYTES_PER_SECOND: 'GB/s'})})) | Manage options. | custom_components/googlewifi/config_flow.py | async_step_init | szamfirov/hagooglewifi | 38 | python | async def async_step_init(self, user_input=None):
if (user_input is not None):
return self.async_create_entry(title=, data=user_input)
return self.async_show_form(step_id='init', data_schema=vol.Schema({vol.Optional(CONF_SCAN_INTERVAL, default=self.config_entry.options.get(CONF_SCAN_INTERVAL, POLLING_INTERVAL)): vol.All(vol.Coerce(int), vol.Range(min=3)), vol.Optional(CONF_SPEEDTEST, default=self.config_entry.options.get(CONF_SPEEDTEST, DEFAULT_SPEEDTEST)): bool, vol.Optional(CONF_SPEEDTEST_INTERVAL, default=self.config_entry.options.get(CONF_SPEEDTEST_INTERVAL, DEFAULT_SPEEDTEST_INTERVAL)): vol.Coerce(int), vol.Optional(CONF_SPEED_UNITS, default=self.config_entry.options.get(CONF_SPEED_UNITS, DATA_RATE_MEGABITS_PER_SECOND)): vol.In({DATA_RATE_KILOBITS_PER_SECOND: 'kbits/s', DATA_RATE_MEGABITS_PER_SECOND: 'Mbit/s', DATA_RATE_GIGABITS_PER_SECOND: 'Gbit/s', DATA_RATE_BYTES_PER_SECOND: 'B/s', DATA_RATE_KILOBYTES_PER_SECOND: 'kB/s', DATA_RATE_MEGABYTES_PER_SECOND: 'MB/s', DATA_RATE_GIGABYTES_PER_SECOND: 'GB/s'})})) | async def async_step_init(self, user_input=None):
if (user_input is not None):
return self.async_create_entry(title=, data=user_input)
return self.async_show_form(step_id='init', data_schema=vol.Schema({vol.Optional(CONF_SCAN_INTERVAL, default=self.config_entry.options.get(CONF_SCAN_INTERVAL, POLLING_INTERVAL)): vol.All(vol.Coerce(int), vol.Range(min=3)), vol.Optional(CONF_SPEEDTEST, default=self.config_entry.options.get(CONF_SPEEDTEST, DEFAULT_SPEEDTEST)): bool, vol.Optional(CONF_SPEEDTEST_INTERVAL, default=self.config_entry.options.get(CONF_SPEEDTEST_INTERVAL, DEFAULT_SPEEDTEST_INTERVAL)): vol.Coerce(int), vol.Optional(CONF_SPEED_UNITS, default=self.config_entry.options.get(CONF_SPEED_UNITS, DATA_RATE_MEGABITS_PER_SECOND)): vol.In({DATA_RATE_KILOBITS_PER_SECOND: 'kbits/s', DATA_RATE_MEGABITS_PER_SECOND: 'Mbit/s', DATA_RATE_GIGABITS_PER_SECOND: 'Gbit/s', DATA_RATE_BYTES_PER_SECOND: 'B/s', DATA_RATE_KILOBYTES_PER_SECOND: 'kB/s', DATA_RATE_MEGABYTES_PER_SECOND: 'MB/s', DATA_RATE_GIGABYTES_PER_SECOND: 'GB/s'})}))<|docstring|>Manage options.<|endoftext|> |
aaca504cb5055333aeb3be97adfd2342db128ff73ae84a74ae22d52ae07e9687 | def load_data(data_dir):
'Loads a data set and returns two lists:\n \n images: a list of Numpy arrays, each representing an image.\n labels: a list of numbers that represent the images labels.\n '
directories = [d for d in os.listdir(data_dir) if os.path.isdir(os.path.join(data_dir, d))]
labels = []
images = []
for d in directories:
label_dir = os.path.join(data_dir, d)
file_names = [os.path.join(label_dir, f) for f in os.listdir(label_dir) if f.endswith('.ppm')]
for f in file_names:
images.append(skimage.data.imread(f))
labels.append(int(d))
return (images, labels) | Loads a data set and returns two lists:
images: a list of Numpy arrays, each representing an image.
labels: a list of numbers that represent the images labels. | Chapter03/Traffic/custom.py | load_data | PacktPublishing/Practical-Convolutional-Neural-Networks | 23 | python | def load_data(data_dir):
'Loads a data set and returns two lists:\n \n images: a list of Numpy arrays, each representing an image.\n labels: a list of numbers that represent the images labels.\n '
directories = [d for d in os.listdir(data_dir) if os.path.isdir(os.path.join(data_dir, d))]
labels = []
images = []
for d in directories:
label_dir = os.path.join(data_dir, d)
file_names = [os.path.join(label_dir, f) for f in os.listdir(label_dir) if f.endswith('.ppm')]
for f in file_names:
images.append(skimage.data.imread(f))
labels.append(int(d))
return (images, labels) | def load_data(data_dir):
'Loads a data set and returns two lists:\n \n images: a list of Numpy arrays, each representing an image.\n labels: a list of numbers that represent the images labels.\n '
directories = [d for d in os.listdir(data_dir) if os.path.isdir(os.path.join(data_dir, d))]
labels = []
images = []
for d in directories:
label_dir = os.path.join(data_dir, d)
file_names = [os.path.join(label_dir, f) for f in os.listdir(label_dir) if f.endswith('.ppm')]
for f in file_names:
images.append(skimage.data.imread(f))
labels.append(int(d))
return (images, labels)<|docstring|>Loads a data set and returns two lists:
images: a list of Numpy arrays, each representing an image.
labels: a list of numbers that represent the images labels.<|endoftext|> |
97b70fa34c35cabb4ac24610f97b0512f90872565ca7f0624a25d329b215d89c | def display_images_and_labels(images, labels):
'Display the first image of each label.'
unique_labels = set(labels)
plt.figure(figsize=(15, 15))
i = 1
for label in unique_labels:
image = images[labels.index(label)]
plt.subplot(8, 8, i)
plt.axis('off')
plt.title('Label {0} ({1})'.format(label, labels.count(label)))
i += 1
_ = plt.imshow(image)
plt.show() | Display the first image of each label. | Chapter03/Traffic/custom.py | display_images_and_labels | PacktPublishing/Practical-Convolutional-Neural-Networks | 23 | python | def display_images_and_labels(images, labels):
unique_labels = set(labels)
plt.figure(figsize=(15, 15))
i = 1
for label in unique_labels:
image = images[labels.index(label)]
plt.subplot(8, 8, i)
plt.axis('off')
plt.title('Label {0} ({1})'.format(label, labels.count(label)))
i += 1
_ = plt.imshow(image)
plt.show() | def display_images_and_labels(images, labels):
unique_labels = set(labels)
plt.figure(figsize=(15, 15))
i = 1
for label in unique_labels:
image = images[labels.index(label)]
plt.subplot(8, 8, i)
plt.axis('off')
plt.title('Label {0} ({1})'.format(label, labels.count(label)))
i += 1
_ = plt.imshow(image)
plt.show()<|docstring|>Display the first image of each label.<|endoftext|> |
38aad1aa4dc6c4939b0fb62a7690df6a04fe92150242d9496bf2ccb8da6e25fe | def display_label_images(images, label):
'Display images of a specific label.'
limit = 15
plt.figure(figsize=(12, 8))
i = 1
start = labels.index(label)
end = (start + labels.count(label))
for image in images[start:end][:limit]:
plt.subplot(3, 5, i)
plt.axis('off')
i += 1
plt.imshow(image)
plt.show() | Display images of a specific label. | Chapter03/Traffic/custom.py | display_label_images | PacktPublishing/Practical-Convolutional-Neural-Networks | 23 | python | def display_label_images(images, label):
limit = 15
plt.figure(figsize=(12, 8))
i = 1
start = labels.index(label)
end = (start + labels.count(label))
for image in images[start:end][:limit]:
plt.subplot(3, 5, i)
plt.axis('off')
i += 1
plt.imshow(image)
plt.show() | def display_label_images(images, label):
limit = 15
plt.figure(figsize=(12, 8))
i = 1
start = labels.index(label)
end = (start + labels.count(label))
for image in images[start:end][:limit]:
plt.subplot(3, 5, i)
plt.axis('off')
i += 1
plt.imshow(image)
plt.show()<|docstring|>Display images of a specific label.<|endoftext|> |
e99bf20610c0ba7436218f0c1d0983bd84b0d1e830aa8ee75dcfb4d1a6a2df86 | def request_port(self):
'Port in use for this request\n https://github.com/python-social-auth/social-app-django/blob/master/social_django/strategy.py#L76\n '
try:
return self.request.get_port()
except AttributeError:
host_parts = self.request.get_host().split(':')
try:
return host_parts[1]
except IndexError:
return self.request.META['SERVER_PORT'] | Port in use for this request
https://github.com/python-social-auth/social-app-django/blob/master/social_django/strategy.py#L76 | awx/sso/strategies/django_strategy.py | request_port | mabashian/awx | 0 | python | def request_port(self):
'Port in use for this request\n https://github.com/python-social-auth/social-app-django/blob/master/social_django/strategy.py#L76\n '
try:
return self.request.get_port()
except AttributeError:
host_parts = self.request.get_host().split(':')
try:
return host_parts[1]
except IndexError:
return self.request.META['SERVER_PORT'] | def request_port(self):
'Port in use for this request\n https://github.com/python-social-auth/social-app-django/blob/master/social_django/strategy.py#L76\n '
try:
return self.request.get_port()
except AttributeError:
host_parts = self.request.get_host().split(':')
try:
return host_parts[1]
except IndexError:
return self.request.META['SERVER_PORT']<|docstring|>Port in use for this request
https://github.com/python-social-auth/social-app-django/blob/master/social_django/strategy.py#L76<|endoftext|> |
cc1c5c6c7d15fd5e590b01b262e87fa5a8f801bda1694b640110c216128fb4fa | def get_moment_class(moment: cirq.Moment):
'For a given moment, return the Gate class which every operation\n is an instantiation or `None` for non-homogeneous or non-hardware moments.\n '
mom_class_vec = [_homogeneous_gate_type(moment, gc) for gc in MOMENT_GATE_CLASSES]
if (np.sum(mom_class_vec) != 1):
return None
return MOMENT_GATE_CLASSES[np.argmax(mom_class_vec)] | For a given moment, return the Gate class which every operation
is an instantiation or `None` for non-homogeneous or non-hardware moments. | recirq/qaoa/circuit_structure.py | get_moment_class | augustehirth/ReCirq | 195 | python | def get_moment_class(moment: cirq.Moment):
'For a given moment, return the Gate class which every operation\n is an instantiation or `None` for non-homogeneous or non-hardware moments.\n '
mom_class_vec = [_homogeneous_gate_type(moment, gc) for gc in MOMENT_GATE_CLASSES]
if (np.sum(mom_class_vec) != 1):
return None
return MOMENT_GATE_CLASSES[np.argmax(mom_class_vec)] | def get_moment_class(moment: cirq.Moment):
'For a given moment, return the Gate class which every operation\n is an instantiation or `None` for non-homogeneous or non-hardware moments.\n '
mom_class_vec = [_homogeneous_gate_type(moment, gc) for gc in MOMENT_GATE_CLASSES]
if (np.sum(mom_class_vec) != 1):
return None
return MOMENT_GATE_CLASSES[np.argmax(mom_class_vec)]<|docstring|>For a given moment, return the Gate class which every operation
is an instantiation or `None` for non-homogeneous or non-hardware moments.<|endoftext|> |
3a6296eb15c64b129ce234a619c35cc4bbf5112798f09b9b39e75f9c9d7c9bb7 | def get_moment_classes(circuit: cirq.Circuit):
"Return the 'moment class' for each moment in the circuit.\n\n A moment class is the Gate class of which every operation\n is an instantiation or `None` for non-homogeneous or non-hardware moments.\n "
return [get_moment_class(moment) for moment in circuit.moments] | Return the 'moment class' for each moment in the circuit.
A moment class is the Gate class of which every operation
is an instantiation or `None` for non-homogeneous or non-hardware moments. | recirq/qaoa/circuit_structure.py | get_moment_classes | augustehirth/ReCirq | 195 | python | def get_moment_classes(circuit: cirq.Circuit):
"Return the 'moment class' for each moment in the circuit.\n\n A moment class is the Gate class of which every operation\n is an instantiation or `None` for non-homogeneous or non-hardware moments.\n "
return [get_moment_class(moment) for moment in circuit.moments] | def get_moment_classes(circuit: cirq.Circuit):
"Return the 'moment class' for each moment in the circuit.\n\n A moment class is the Gate class of which every operation\n is an instantiation or `None` for non-homogeneous or non-hardware moments.\n "
return [get_moment_class(moment) for moment in circuit.moments]<|docstring|>Return the 'moment class' for each moment in the circuit.
A moment class is the Gate class of which every operation
is an instantiation or `None` for non-homogeneous or non-hardware moments.<|endoftext|> |
7bedeb0bbaf7bd38b28655895de6a507b657ff8dd3f9cd444359a3e035e36768 | def find_circuit_structure_violations(circuit: cirq.Circuit):
'Return indices where the circuit contains non-homogenous\n non-hardware moments.\n '
mom_classes = get_moment_classes(circuit)
return _find_circuit_structure_violations(mom_classes) | Return indices where the circuit contains non-homogenous
non-hardware moments. | recirq/qaoa/circuit_structure.py | find_circuit_structure_violations | augustehirth/ReCirq | 195 | python | def find_circuit_structure_violations(circuit: cirq.Circuit):
'Return indices where the circuit contains non-homogenous\n non-hardware moments.\n '
mom_classes = get_moment_classes(circuit)
return _find_circuit_structure_violations(mom_classes) | def find_circuit_structure_violations(circuit: cirq.Circuit):
'Return indices where the circuit contains non-homogenous\n non-hardware moments.\n '
mom_classes = get_moment_classes(circuit)
return _find_circuit_structure_violations(mom_classes)<|docstring|>Return indices where the circuit contains non-homogenous
non-hardware moments.<|endoftext|> |
975d6cd231891924b4f20799c5eae78752a43e7bd622ea236ea505ada93519dc | def validate_well_structured(circuit: cirq.Circuit, allow_terminal_permutations=False):
'Raises a ValueError if the circuit is not structured, otherwise returns\n a list of moment classes (see `get_moment_classes`) and a\n `HomogeneousCircuitStats` set of statistics.\n\n A "structured circuit" means that each moment contains either all-PhX,\n all-Z, all-SYC, or all-SQRT_ISWAP (i.e. moments have homogeneous gate types).\n The gate type common in a given moment can be called the "moment class".\n In structured circuits, moments are arranged so that the layers are always\n PhX, Z, (SYC/SQRT_ISWAP) for many layers, optionally ending with a\n measurement layer.\n\n If `allow_terminal_permutations` is set to `True`, a\n `QuirkQubitPermutationGate` is permitted preceding a measurement.\n Use `circuits2.measure_with_final_permutation` to append a measurement\n gate and track the permutation for implementation via post-processing.\n '
mom_classes = get_moment_classes(circuit)
violation_indices = _find_circuit_structure_violations(mom_classes)
if (len(violation_indices) > 0):
raise BadlyStructuredCircuitError('Badly structured circuit. Inhomogeneous or non-device moments at indices {}'.format(violation_indices))
num_phx = 0
num_z = 0
hit_permutation = False
hit_measurement = False
tot_n_phx = 0
tot_n_z = 0
tot_n_syc = 0
for mom_class in mom_classes:
if (mom_class in [cirq.PhasedXPowGate, cirq.ZPowGate, cg.SycamoreGate]):
if hit_permutation:
raise BadlyStructuredCircuitError('Permutations must be terminal')
if hit_measurement:
raise BadlyStructuredCircuitError('Measurements must be terminal')
if (mom_class == cirq.PhasedXPowGate):
num_phx += 1
tot_n_phx += 1
elif (mom_class == cirq.ZPowGate):
num_z += 1
tot_n_z += 1
elif (mom_class == cg.SycamoreGate):
tot_n_syc += 1
if (num_phx > 1):
raise BadlyStructuredCircuitError('Too many PhX in this slice')
if (num_z > 1):
raise BadlyStructuredCircuitError('Too many Z in this slice')
if (num_phx < 1):
print('Warning: no PhX in this slice')
num_phx = 0
num_z = 0
elif (mom_class == cirq.MeasurementGate):
if hit_measurement:
raise BadlyStructuredCircuitError('Too many measurements')
if hit_permutation:
pass
hit_measurement = True
elif (mom_class == QuirkQubitPermutationGate):
if (not allow_terminal_permutations):
raise BadlyStructuredCircuitError('Circuit contains permutation gates')
if hit_measurement:
raise BadlyStructuredCircuitError('Measurements must be terminal')
if hit_permutation:
raise BadlyStructuredCircuitError('Too many permutations')
hit_permutation = True
else:
raise BadlyStructuredCircuitError('Unknown moment class')
return (mom_classes, HomogeneousCircuitStats(tot_n_phx, tot_n_z, tot_n_syc, hit_permutation, hit_measurement)) | Raises a ValueError if the circuit is not structured, otherwise returns
a list of moment classes (see `get_moment_classes`) and a
`HomogeneousCircuitStats` set of statistics.
A "structured circuit" means that each moment contains either all-PhX,
all-Z, all-SYC, or all-SQRT_ISWAP (i.e. moments have homogeneous gate types).
The gate type common in a given moment can be called the "moment class".
In structured circuits, moments are arranged so that the layers are always
PhX, Z, (SYC/SQRT_ISWAP) for many layers, optionally ending with a
measurement layer.
If `allow_terminal_permutations` is set to `True`, a
`QuirkQubitPermutationGate` is permitted preceding a measurement.
Use `circuits2.measure_with_final_permutation` to append a measurement
gate and track the permutation for implementation via post-processing. | recirq/qaoa/circuit_structure.py | validate_well_structured | augustehirth/ReCirq | 195 | python | def validate_well_structured(circuit: cirq.Circuit, allow_terminal_permutations=False):
'Raises a ValueError if the circuit is not structured, otherwise returns\n a list of moment classes (see `get_moment_classes`) and a\n `HomogeneousCircuitStats` set of statistics.\n\n A "structured circuit" means that each moment contains either all-PhX,\n all-Z, all-SYC, or all-SQRT_ISWAP (i.e. moments have homogeneous gate types).\n The gate type common in a given moment can be called the "moment class".\n In structured circuits, moments are arranged so that the layers are always\n PhX, Z, (SYC/SQRT_ISWAP) for many layers, optionally ending with a\n measurement layer.\n\n If `allow_terminal_permutations` is set to `True`, a\n `QuirkQubitPermutationGate` is permitted preceding a measurement.\n Use `circuits2.measure_with_final_permutation` to append a measurement\n gate and track the permutation for implementation via post-processing.\n '
mom_classes = get_moment_classes(circuit)
violation_indices = _find_circuit_structure_violations(mom_classes)
if (len(violation_indices) > 0):
raise BadlyStructuredCircuitError('Badly structured circuit. Inhomogeneous or non-device moments at indices {}'.format(violation_indices))
num_phx = 0
num_z = 0
hit_permutation = False
hit_measurement = False
tot_n_phx = 0
tot_n_z = 0
tot_n_syc = 0
for mom_class in mom_classes:
if (mom_class in [cirq.PhasedXPowGate, cirq.ZPowGate, cg.SycamoreGate]):
if hit_permutation:
raise BadlyStructuredCircuitError('Permutations must be terminal')
if hit_measurement:
raise BadlyStructuredCircuitError('Measurements must be terminal')
if (mom_class == cirq.PhasedXPowGate):
num_phx += 1
tot_n_phx += 1
elif (mom_class == cirq.ZPowGate):
num_z += 1
tot_n_z += 1
elif (mom_class == cg.SycamoreGate):
tot_n_syc += 1
if (num_phx > 1):
raise BadlyStructuredCircuitError('Too many PhX in this slice')
if (num_z > 1):
raise BadlyStructuredCircuitError('Too many Z in this slice')
if (num_phx < 1):
print('Warning: no PhX in this slice')
num_phx = 0
num_z = 0
elif (mom_class == cirq.MeasurementGate):
if hit_measurement:
raise BadlyStructuredCircuitError('Too many measurements')
if hit_permutation:
pass
hit_measurement = True
elif (mom_class == QuirkQubitPermutationGate):
if (not allow_terminal_permutations):
raise BadlyStructuredCircuitError('Circuit contains permutation gates')
if hit_measurement:
raise BadlyStructuredCircuitError('Measurements must be terminal')
if hit_permutation:
raise BadlyStructuredCircuitError('Too many permutations')
hit_permutation = True
else:
raise BadlyStructuredCircuitError('Unknown moment class')
return (mom_classes, HomogeneousCircuitStats(tot_n_phx, tot_n_z, tot_n_syc, hit_permutation, hit_measurement)) | def validate_well_structured(circuit: cirq.Circuit, allow_terminal_permutations=False):
'Raises a ValueError if the circuit is not structured, otherwise returns\n a list of moment classes (see `get_moment_classes`) and a\n `HomogeneousCircuitStats` set of statistics.\n\n A "structured circuit" means that each moment contains either all-PhX,\n all-Z, all-SYC, or all-SQRT_ISWAP (i.e. moments have homogeneous gate types).\n The gate type common in a given moment can be called the "moment class".\n In structured circuits, moments are arranged so that the layers are always\n PhX, Z, (SYC/SQRT_ISWAP) for many layers, optionally ending with a\n measurement layer.\n\n If `allow_terminal_permutations` is set to `True`, a\n `QuirkQubitPermutationGate` is permitted preceding a measurement.\n Use `circuits2.measure_with_final_permutation` to append a measurement\n gate and track the permutation for implementation via post-processing.\n '
mom_classes = get_moment_classes(circuit)
violation_indices = _find_circuit_structure_violations(mom_classes)
if (len(violation_indices) > 0):
raise BadlyStructuredCircuitError('Badly structured circuit. Inhomogeneous or non-device moments at indices {}'.format(violation_indices))
num_phx = 0
num_z = 0
hit_permutation = False
hit_measurement = False
tot_n_phx = 0
tot_n_z = 0
tot_n_syc = 0
for mom_class in mom_classes:
if (mom_class in [cirq.PhasedXPowGate, cirq.ZPowGate, cg.SycamoreGate]):
if hit_permutation:
raise BadlyStructuredCircuitError('Permutations must be terminal')
if hit_measurement:
raise BadlyStructuredCircuitError('Measurements must be terminal')
if (mom_class == cirq.PhasedXPowGate):
num_phx += 1
tot_n_phx += 1
elif (mom_class == cirq.ZPowGate):
num_z += 1
tot_n_z += 1
elif (mom_class == cg.SycamoreGate):
tot_n_syc += 1
if (num_phx > 1):
raise BadlyStructuredCircuitError('Too many PhX in this slice')
if (num_z > 1):
raise BadlyStructuredCircuitError('Too many Z in this slice')
if (num_phx < 1):
print('Warning: no PhX in this slice')
num_phx = 0
num_z = 0
elif (mom_class == cirq.MeasurementGate):
if hit_measurement:
raise BadlyStructuredCircuitError('Too many measurements')
if hit_permutation:
pass
hit_measurement = True
elif (mom_class == QuirkQubitPermutationGate):
if (not allow_terminal_permutations):
raise BadlyStructuredCircuitError('Circuit contains permutation gates')
if hit_measurement:
raise BadlyStructuredCircuitError('Measurements must be terminal')
if hit_permutation:
raise BadlyStructuredCircuitError('Too many permutations')
hit_permutation = True
else:
raise BadlyStructuredCircuitError('Unknown moment class')
return (mom_classes, HomogeneousCircuitStats(tot_n_phx, tot_n_z, tot_n_syc, hit_permutation, hit_measurement))<|docstring|>Raises a ValueError if the circuit is not structured, otherwise returns
a list of moment classes (see `get_moment_classes`) and a
`HomogeneousCircuitStats` set of statistics.
A "structured circuit" means that each moment contains either all-PhX,
all-Z, all-SYC, or all-SQRT_ISWAP (i.e. moments have homogeneous gate types).
The gate type common in a given moment can be called the "moment class".
In structured circuits, moments are arranged so that the layers are always
PhX, Z, (SYC/SQRT_ISWAP) for many layers, optionally ending with a
measurement layer.
If `allow_terminal_permutations` is set to `True`, a
`QuirkQubitPermutationGate` is permitted preceding a measurement.
Use `circuits2.measure_with_final_permutation` to append a measurement
gate and track the permutation for implementation via post-processing.<|endoftext|> |
e6c510db7ca2e6a9c0b1aabb31827793949a6fcf496b30705ec4de03c3737442 | def count_circuit_holes(circuit: cirq.Circuit):
'Count the number of "holes" in a circuit where nothing is happening.'
return sum((len(iq) for (_, iq) in _idle_qubits_by_moment(circuit))) | Count the number of "holes" in a circuit where nothing is happening. | recirq/qaoa/circuit_structure.py | count_circuit_holes | augustehirth/ReCirq | 195 | python | def count_circuit_holes(circuit: cirq.Circuit):
return sum((len(iq) for (_, iq) in _idle_qubits_by_moment(circuit))) | def count_circuit_holes(circuit: cirq.Circuit):
return sum((len(iq) for (_, iq) in _idle_qubits_by_moment(circuit)))<|docstring|>Count the number of "holes" in a circuit where nothing is happening.<|endoftext|> |
3f02c425b1ff153d972d9bc5ece67b11ee25733213419e6160febb05d14d4cac | def read(file):
'Parses an Altium ".SchDoc" schematic file and returns a Sheet object\n '
ole = OleFileIO(file)
stream = ole.openstream('FileHeader')
records = iter_records(stream)
records = (parse_properties(stream, record) for record in records)
header = next(records)
parse_header(header)
header.check_unknown()
sheet = Object(properties=next(records))
objects = [sheet]
for properties in records:
obj = Object(properties=properties)
objects[obj.properties.get_int('OWNERINDEX')].children.append(obj)
objects.append(obj)
if ole.exists('Additional'):
stream = ole.openstream('Additional')
records = iter_records(stream)
records = (parse_properties(stream, record) for record in records)
header = next(records)
parse_header(header)
header.check_unknown()
for properties in records:
obj = Object(properties=properties)
owner = obj.properties.get_int('OWNERINDEX')
objects[owner].children.append(obj)
objects.append(obj)
storage_stream = ole.openstream('Storage')
records = iter_records(storage_stream)
header = parse_properties(storage_stream, next(records))
header.check('HEADER', b'Icon storage')
header.get_int('WEIGHT')
header.check_unknown()
storage_files = dict()
for [type, length] in records:
if (type != 1):
warn('Unexpected record type {} in Storage'.format(type))
continue
header = storage_stream.read(1)
if (header != b'\xd0'):
warn(('Unexpected Storage record header byte ' + repr(header)))
continue
[length] = storage_stream.read(1)
filename = storage_stream.read(length)
pos = storage_stream.tell()
if (storage_files.setdefault(filename, pos) != pos):
warn(('Duplicate Storage record for ' + repr(filename)))
streams = set(map(tuple, ole.listdir()))
streams -= {('FileHeader',), ('Additional',), ('Storage',)}
if streams:
warn(('Extra OLE file streams: ' + ', '.join(map('/'.join, streams))))
return (sheet, storage_stream, storage_files) | Parses an Altium ".SchDoc" schematic file and returns a Sheet object | altium.py | read | lrh2999/python-altium | 1 | python | def read(file):
'\n '
ole = OleFileIO(file)
stream = ole.openstream('FileHeader')
records = iter_records(stream)
records = (parse_properties(stream, record) for record in records)
header = next(records)
parse_header(header)
header.check_unknown()
sheet = Object(properties=next(records))
objects = [sheet]
for properties in records:
obj = Object(properties=properties)
objects[obj.properties.get_int('OWNERINDEX')].children.append(obj)
objects.append(obj)
if ole.exists('Additional'):
stream = ole.openstream('Additional')
records = iter_records(stream)
records = (parse_properties(stream, record) for record in records)
header = next(records)
parse_header(header)
header.check_unknown()
for properties in records:
obj = Object(properties=properties)
owner = obj.properties.get_int('OWNERINDEX')
objects[owner].children.append(obj)
objects.append(obj)
storage_stream = ole.openstream('Storage')
records = iter_records(storage_stream)
header = parse_properties(storage_stream, next(records))
header.check('HEADER', b'Icon storage')
header.get_int('WEIGHT')
header.check_unknown()
storage_files = dict()
for [type, length] in records:
if (type != 1):
warn('Unexpected record type {} in Storage'.format(type))
continue
header = storage_stream.read(1)
if (header != b'\xd0'):
warn(('Unexpected Storage record header byte ' + repr(header)))
continue
[length] = storage_stream.read(1)
filename = storage_stream.read(length)
pos = storage_stream.tell()
if (storage_files.setdefault(filename, pos) != pos):
warn(('Duplicate Storage record for ' + repr(filename)))
streams = set(map(tuple, ole.listdir()))
streams -= {('FileHeader',), ('Additional',), ('Storage',)}
if streams:
warn(('Extra OLE file streams: ' + ', '.join(map('/'.join, streams))))
return (sheet, storage_stream, storage_files) | def read(file):
'\n '
ole = OleFileIO(file)
stream = ole.openstream('FileHeader')
records = iter_records(stream)
records = (parse_properties(stream, record) for record in records)
header = next(records)
parse_header(header)
header.check_unknown()
sheet = Object(properties=next(records))
objects = [sheet]
for properties in records:
obj = Object(properties=properties)
objects[obj.properties.get_int('OWNERINDEX')].children.append(obj)
objects.append(obj)
if ole.exists('Additional'):
stream = ole.openstream('Additional')
records = iter_records(stream)
records = (parse_properties(stream, record) for record in records)
header = next(records)
parse_header(header)
header.check_unknown()
for properties in records:
obj = Object(properties=properties)
owner = obj.properties.get_int('OWNERINDEX')
objects[owner].children.append(obj)
objects.append(obj)
storage_stream = ole.openstream('Storage')
records = iter_records(storage_stream)
header = parse_properties(storage_stream, next(records))
header.check('HEADER', b'Icon storage')
header.get_int('WEIGHT')
header.check_unknown()
storage_files = dict()
for [type, length] in records:
if (type != 1):
warn('Unexpected record type {} in Storage'.format(type))
continue
header = storage_stream.read(1)
if (header != b'\xd0'):
warn(('Unexpected Storage record header byte ' + repr(header)))
continue
[length] = storage_stream.read(1)
filename = storage_stream.read(length)
pos = storage_stream.tell()
if (storage_files.setdefault(filename, pos) != pos):
warn(('Duplicate Storage record for ' + repr(filename)))
streams = set(map(tuple, ole.listdir()))
streams -= {('FileHeader',), ('Additional',), ('Storage',)}
if streams:
warn(('Extra OLE file streams: ' + ', '.join(map('/'.join, streams))))
return (sheet, storage_stream, storage_files)<|docstring|>Parses an Altium ".SchDoc" schematic file and returns a Sheet object<|endoftext|> |
741879759f761c15e8ca85cae37e472cbc2e8aac66c65b5ac3ae3c05ab32d6e3 | def iter_records(stream):
'Finds object records from a stream in an Altium ".SchDoc" file\n '
while True:
length = stream.read(2)
if (not length):
break
(length,) = struct.unpack('<H', length)
byte = stream.read(1)
if (byte != b'\x00'):
warn('Expected 0x00 byte after record length')
[type] = stream.read(1)
if (type > 1):
warn(('Unexpected record type ' + format(type)))
end = (stream.tell() + length)
(yield (type, length))
if (stream.tell() > end):
warn('Read past end of record')
stream.seek(end) | Finds object records from a stream in an Altium ".SchDoc" file | altium.py | iter_records | lrh2999/python-altium | 1 | python | def iter_records(stream):
'\n '
while True:
length = stream.read(2)
if (not length):
break
(length,) = struct.unpack('<H', length)
byte = stream.read(1)
if (byte != b'\x00'):
warn('Expected 0x00 byte after record length')
[type] = stream.read(1)
if (type > 1):
warn(('Unexpected record type ' + format(type)))
end = (stream.tell() + length)
(yield (type, length))
if (stream.tell() > end):
warn('Read past end of record')
stream.seek(end) | def iter_records(stream):
'\n '
while True:
length = stream.read(2)
if (not length):
break
(length,) = struct.unpack('<H', length)
byte = stream.read(1)
if (byte != b'\x00'):
warn('Expected 0x00 byte after record length')
[type] = stream.read(1)
if (type > 1):
warn(('Unexpected record type ' + format(type)))
end = (stream.tell() + length)
(yield (type, length))
if (stream.tell() > end):
warn('Read past end of record')
stream.seek(end)<|docstring|>Finds object records from a stream in an Altium ".SchDoc" file<|endoftext|> |
503967174242cce6bed49c06e2b673f01abd45e550567bcdd2c36827dfd9c01e | def get_sheet_style(sheet):
'Returns the size of the sheet: (name, (width, height))'
STYLES = {SheetStyle.A4: ('A4', (1150, 760)), SheetStyle.A3: ('A3', (1550, 1110)), SheetStyle.A2: ('A2', (2230, 1570)), SheetStyle.A1: ('A1', (3150, 2230)), SheetStyle.A0: ('A0', (4460, 3150)), SheetStyle.A: ('A', (950, 750)), SheetStyle.B: ('B', (1500, 950)), SheetStyle.C: ('C', (2000, 1500)), SheetStyle.D: ('D', (3200, 2000)), SheetStyle.E: ('E', (4200, 3200)), SheetStyle.LETTER: ('Letter', (1100, 850)), SheetStyle.LEGAL: ('Legal', (1400, 850)), SheetStyle.TABLOID: ('Tabloid', (1700, 1100)), SheetStyle.ORCAD_A: ('OrCAD A', (990, 790)), SheetStyle.ORCAD_B: ('OrCAD B', (1540, 990)), SheetStyle.ORCAD_C: ('OrCAD C', (2060, 1560)), SheetStyle.ORCAD_D: ('OrCAD D', (3260, 2060)), SheetStyle.ORCAD_E: ('OrCAD E', (4280, 3280))}
[sheetstyle, size] = STYLES[sheet.get_int('SHEETSTYLE')]
if sheet.get_bool('USECUSTOMSHEET'):
size = tuple((sheet.get_int(('CUSTOM' + 'XY'[x])) for x in range(2)))
if sheet.get_int('WORKSPACEORIENTATION'):
[height, width] = size
size = (width, height)
return (sheetstyle, size) | Returns the size of the sheet: (name, (width, height)) | altium.py | get_sheet_style | lrh2999/python-altium | 1 | python | def get_sheet_style(sheet):
STYLES = {SheetStyle.A4: ('A4', (1150, 760)), SheetStyle.A3: ('A3', (1550, 1110)), SheetStyle.A2: ('A2', (2230, 1570)), SheetStyle.A1: ('A1', (3150, 2230)), SheetStyle.A0: ('A0', (4460, 3150)), SheetStyle.A: ('A', (950, 750)), SheetStyle.B: ('B', (1500, 950)), SheetStyle.C: ('C', (2000, 1500)), SheetStyle.D: ('D', (3200, 2000)), SheetStyle.E: ('E', (4200, 3200)), SheetStyle.LETTER: ('Letter', (1100, 850)), SheetStyle.LEGAL: ('Legal', (1400, 850)), SheetStyle.TABLOID: ('Tabloid', (1700, 1100)), SheetStyle.ORCAD_A: ('OrCAD A', (990, 790)), SheetStyle.ORCAD_B: ('OrCAD B', (1540, 990)), SheetStyle.ORCAD_C: ('OrCAD C', (2060, 1560)), SheetStyle.ORCAD_D: ('OrCAD D', (3260, 2060)), SheetStyle.ORCAD_E: ('OrCAD E', (4280, 3280))}
[sheetstyle, size] = STYLES[sheet.get_int('SHEETSTYLE')]
if sheet.get_bool('USECUSTOMSHEET'):
size = tuple((sheet.get_int(('CUSTOM' + 'XY'[x])) for x in range(2)))
if sheet.get_int('WORKSPACEORIENTATION'):
[height, width] = size
size = (width, height)
return (sheetstyle, size) | def get_sheet_style(sheet):
STYLES = {SheetStyle.A4: ('A4', (1150, 760)), SheetStyle.A3: ('A3', (1550, 1110)), SheetStyle.A2: ('A2', (2230, 1570)), SheetStyle.A1: ('A1', (3150, 2230)), SheetStyle.A0: ('A0', (4460, 3150)), SheetStyle.A: ('A', (950, 750)), SheetStyle.B: ('B', (1500, 950)), SheetStyle.C: ('C', (2000, 1500)), SheetStyle.D: ('D', (3200, 2000)), SheetStyle.E: ('E', (4200, 3200)), SheetStyle.LETTER: ('Letter', (1100, 850)), SheetStyle.LEGAL: ('Legal', (1400, 850)), SheetStyle.TABLOID: ('Tabloid', (1700, 1100)), SheetStyle.ORCAD_A: ('OrCAD A', (990, 790)), SheetStyle.ORCAD_B: ('OrCAD B', (1540, 990)), SheetStyle.ORCAD_C: ('OrCAD C', (2060, 1560)), SheetStyle.ORCAD_D: ('OrCAD D', (3260, 2060)), SheetStyle.ORCAD_E: ('OrCAD E', (4280, 3280))}
[sheetstyle, size] = STYLES[sheet.get_int('SHEETSTYLE')]
if sheet.get_bool('USECUSTOMSHEET'):
size = tuple((sheet.get_int(('CUSTOM' + 'XY'[x])) for x in range(2)))
if sheet.get_int('WORKSPACEORIENTATION'):
[height, width] = size
size = (width, height)
return (sheetstyle, size)<|docstring|>Returns the size of the sheet: (name, (width, height))<|endoftext|> |
32cd92ee36ba2ce2c98648befb3fb0121033b8d762aa0394085eee6515d5c961 | def iter_fonts(sheet):
"Yield a dictionary for each font defined for a sheet\n \n Dictionary keys:\n \n id: Positive integer\n line: Font's line spacing\n family: Typeface name\n italic, bold, underline: Boolean values\n "
for i in range(sheet.get_int('FONTIDCOUNT')):
id = (1 + i)
n = format(id)
(yield dict(id=id, line=sheet.get_int(('SIZE' + n)), family=sheet[('FONTNAME' + n)].decode('ascii'), italic=sheet.get_bool(('ITALIC' + n)), bold=sheet.get_bool(('BOLD' + n)), underline=sheet.get_bool(('UNDERLINE' + n))))
sheet.get('ROTATION{}'.format((1 + i))) | Yield a dictionary for each font defined for a sheet
Dictionary keys:
id: Positive integer
line: Font's line spacing
family: Typeface name
italic, bold, underline: Boolean values | altium.py | iter_fonts | lrh2999/python-altium | 1 | python | def iter_fonts(sheet):
"Yield a dictionary for each font defined for a sheet\n \n Dictionary keys:\n \n id: Positive integer\n line: Font's line spacing\n family: Typeface name\n italic, bold, underline: Boolean values\n "
for i in range(sheet.get_int('FONTIDCOUNT')):
id = (1 + i)
n = format(id)
(yield dict(id=id, line=sheet.get_int(('SIZE' + n)), family=sheet[('FONTNAME' + n)].decode('ascii'), italic=sheet.get_bool(('ITALIC' + n)), bold=sheet.get_bool(('BOLD' + n)), underline=sheet.get_bool(('UNDERLINE' + n))))
sheet.get('ROTATION{}'.format((1 + i))) | def iter_fonts(sheet):
"Yield a dictionary for each font defined for a sheet\n \n Dictionary keys:\n \n id: Positive integer\n line: Font's line spacing\n family: Typeface name\n italic, bold, underline: Boolean values\n "
for i in range(sheet.get_int('FONTIDCOUNT')):
id = (1 + i)
n = format(id)
(yield dict(id=id, line=sheet.get_int(('SIZE' + n)), family=sheet[('FONTNAME' + n)].decode('ascii'), italic=sheet.get_bool(('ITALIC' + n)), bold=sheet.get_bool(('BOLD' + n)), underline=sheet.get_bool(('UNDERLINE' + n))))
sheet.get('ROTATION{}'.format((1 + i)))<|docstring|>Yield a dictionary for each font defined for a sheet
Dictionary keys:
id: Positive integer
line: Font's line spacing
family: Typeface name
italic, bold, underline: Boolean values<|endoftext|> |
7b84306b4eefac84980b38dd1af22cf2bb4eacd6630e59914e968dd2faf31ec3 | def get_int_frac(obj, property):
'Return full value of a field with separate integer and fraction'
value = obj.get_int(property)
value += (obj.get_int((property + '_FRAC')) / FRAC_DENOM)
return value | Return full value of a field with separate integer and fraction | altium.py | get_int_frac | lrh2999/python-altium | 1 | python | def get_int_frac(obj, property):
value = obj.get_int(property)
value += (obj.get_int((property + '_FRAC')) / FRAC_DENOM)
return value | def get_int_frac(obj, property):
value = obj.get_int(property)
value += (obj.get_int((property + '_FRAC')) / FRAC_DENOM)
return value<|docstring|>Return full value of a field with separate integer and fraction<|endoftext|> |
87d01bebe54b07afeb7953d16e4d97f832526f1c1cd0918bd6a63dd65d0936ea | def get_int_frac1(obj, property):
'Return full value of field with separate x10 integer and fraction\n \n In contrast to all other elements, DISTANCEFROMTOP uses x10 coordinates.\n '
value = (obj.get_int(property) * 10)
value += (obj.get_int((property + '_FRAC1')) / FRAC_DENOM)
return value | Return full value of field with separate x10 integer and fraction
In contrast to all other elements, DISTANCEFROMTOP uses x10 coordinates. | altium.py | get_int_frac1 | lrh2999/python-altium | 1 | python | def get_int_frac1(obj, property):
'Return full value of field with separate x10 integer and fraction\n \n In contrast to all other elements, DISTANCEFROMTOP uses x10 coordinates.\n '
value = (obj.get_int(property) * 10)
value += (obj.get_int((property + '_FRAC1')) / FRAC_DENOM)
return value | def get_int_frac1(obj, property):
'Return full value of field with separate x10 integer and fraction\n \n In contrast to all other elements, DISTANCEFROMTOP uses x10 coordinates.\n '
value = (obj.get_int(property) * 10)
value += (obj.get_int((property + '_FRAC1')) / FRAC_DENOM)
return value<|docstring|>Return full value of field with separate x10 integer and fraction
In contrast to all other elements, DISTANCEFROMTOP uses x10 coordinates.<|endoftext|> |
e478e57034bc717d3b0b9a0f04c0536c3e1819553c77fabce31d8a8c0cd500c9 | def get_location(obj):
'Return location property co-ordinates as a tuple'
return tuple((get_int_frac(obj, ('LOCATION.' + x)) for x in 'XY')) | Return location property co-ordinates as a tuple | altium.py | get_location | lrh2999/python-altium | 1 | python | def get_location(obj):
return tuple((get_int_frac(obj, ('LOCATION.' + x)) for x in 'XY')) | def get_location(obj):
return tuple((get_int_frac(obj, ('LOCATION.' + x)) for x in 'XY'))<|docstring|>Return location property co-ordinates as a tuple<|endoftext|> |
ce43bfa2696a278eaace816a5c75a0ee45b8815d88313d7040eea4f6232dad1e | def display_part(objects, obj):
"Determine if obj is in the component's current part and display mode\n "
part = obj.get('OWNERPARTID')
owner = objects.properties
mode = obj.get_int('OWNERPARTDISPLAYMODE')
return (((part == b'-1') or (part == owner.get('CURRENTPARTID'))) and (mode == owner.get_int('DISPLAYMODE'))) | Determine if obj is in the component's current part and display mode | altium.py | display_part | lrh2999/python-altium | 1 | python | def display_part(objects, obj):
"\n "
part = obj.get('OWNERPARTID')
owner = objects.properties
mode = obj.get_int('OWNERPARTDISPLAYMODE')
return (((part == b'-1') or (part == owner.get('CURRENTPARTID'))) and (mode == owner.get_int('DISPLAYMODE'))) | def display_part(objects, obj):
"\n "
part = obj.get('OWNERPARTID')
owner = objects.properties
mode = obj.get_int('OWNERPARTDISPLAYMODE')
return (((part == b'-1') or (part == owner.get('CURRENTPARTID'))) and (mode == owner.get_int('DISPLAYMODE')))<|docstring|>Determine if obj is in the component's current part and display mode<|endoftext|> |
168e54734ac31111513d87b25ad4c008b8e764e2675903d8d2398530e3453b88 | def arrow_neck(inside, outside, hang, *, thick=1):
'Distance to shaft junction from point'
return ((hang * (outside - inside)) + ((thick / 2) * outside)) | Distance to shaft junction from point | altium.py | arrow_neck | lrh2999/python-altium | 1 | python | def arrow_neck(inside, outside, hang, *, thick=1):
return ((hang * (outside - inside)) + ((thick / 2) * outside)) | def arrow_neck(inside, outside, hang, *, thick=1):
return ((hang * (outside - inside)) + ((thick / 2) * outside))<|docstring|>Distance to shaft junction from point<|endoftext|> |
1f11dd520d25346602850c186deba3a15a6bd12d3b9481dfec21f7da20e44325 | def colour(obj, property='COLOR'):
'Convert a TColor property value to a fractional RGB tuple'
c = obj.get_int(property)
return ((x / 255) for x in int((c & 16777215)).to_bytes(3, 'little')) | Convert a TColor property value to a fractional RGB tuple | altium.py | colour | lrh2999/python-altium | 1 | python | def colour(obj, property='COLOR'):
c = obj.get_int(property)
return ((x / 255) for x in int((c & 16777215)).to_bytes(3, 'little')) | def colour(obj, property='COLOR'):
c = obj.get_int(property)
return ((x / 255) for x in int((c & 16777215)).to_bytes(3, 'little'))<|docstring|>Convert a TColor property value to a fractional RGB tuple<|endoftext|> |
96eb9c7699cce75c1b31f567195cf775ff903160b65bbcf90ad5ae0cbd788aac | def font_name(id):
'Convert Altium font number to text name for renderer'
return 'font{}'.format(id) | Convert Altium font number to text name for renderer | altium.py | font_name | lrh2999/python-altium | 1 | python | def font_name(id):
return 'font{}'.format(id) | def font_name(id):
return 'font{}'.format(id)<|docstring|>Convert Altium font number to text name for renderer<|endoftext|> |
905b30d2efcb159bc9c84a176d10202d0b5ab41723dfc502c8875382cf559165 | def __str__(self):
'Return a string listing all the properties'
properties = sorted(self._properties.items())
return ''.join(('|{}={!r}'.format(p, v) for (p, v) in properties)) | Return a string listing all the properties | altium.py | __str__ | lrh2999/python-altium | 1 | python | def __str__(self):
properties = sorted(self._properties.items())
return .join(('|{}={!r}'.format(p, v) for (p, v) in properties)) | def __str__(self):
properties = sorted(self._properties.items())
return .join(('|{}={!r}'.format(p, v) for (p, v) in properties))<|docstring|>Return a string listing all the properties<|endoftext|> |
daed630a7589bfa1d1e79a03022cb8d73166d9617fa5bad1972945ef1022a038 | def check(self, name, *values):
'Check that a property is set to an expected value'
value = self.get(name)
if (value not in values):
msg = 'Unhandled property |{}={!r}; expected {}'
msg = msg.format(name, value, ', '.join(map(repr, values)))
warn(msg, stacklevel=2) | Check that a property is set to an expected value | altium.py | check | lrh2999/python-altium | 1 | python | def check(self, name, *values):
value = self.get(name)
if (value not in values):
msg = 'Unhandled property |{}={!r}; expected {}'
msg = msg.format(name, value, ', '.join(map(repr, values)))
warn(msg, stacklevel=2) | def check(self, name, *values):
value = self.get(name)
if (value not in values):
msg = 'Unhandled property |{}={!r}; expected {}'
msg = msg.format(name, value, ', '.join(map(repr, values)))
warn(msg, stacklevel=2)<|docstring|>Check that a property is set to an expected value<|endoftext|> |
6abb7d02af238de789a54ccca5676ddf0d56c38ead04dd74d641d87477601bf1 | def check_unknown(self):
"Warn if there are properties that weren't queried"
unhandled = (self._properties.keys() - self._known)
if unhandled:
unhandled = ', '.join(sorted(unhandled))
warn('{} unhandled in {}'.format(unhandled, self), stacklevel=2) | Warn if there are properties that weren't queried | altium.py | check_unknown | lrh2999/python-altium | 1 | python | def check_unknown(self):
unhandled = (self._properties.keys() - self._known)
if unhandled:
unhandled = ', '.join(sorted(unhandled))
warn('{} unhandled in {}'.format(unhandled, self), stacklevel=2) | def check_unknown(self):
unhandled = (self._properties.keys() - self._known)
if unhandled:
unhandled = ', '.join(sorted(unhandled))
warn('{} unhandled in {}'.format(unhandled, self), stacklevel=2)<|docstring|>Warn if there are properties that weren't queried<|endoftext|> |
25be32631aee5a2bf42985d7d9ee96dc0ba475d7afc7acd966dd2a0d7a3b4671 | def validate(input_schema=None, output_schema=None, input_example=None, output_example=None, format_checker=None, on_empty_404=False):
'Parameterized decorator for schema validation\n\n :type format_checker: jsonschema.FormatChecker or None\n :type on_empty_404: bool\n :param on_empty_404: If this is set, and the result from the\n decorated method is a falsy value, a 404 will be raised.\n '
@container
def _validate(rh_method):
'Decorator for RequestHandler schema validation\n\n This decorator:\n\n - Validates request body against input schema of the method\n - Calls the ``rh_method`` and gets output from it\n - Validates output against output schema of the method\n - Calls ``JSendMixin.success`` to write the validated output\n\n :type rh_method: function\n :param rh_method: The RequestHandler method to be decorated\n :returns: The decorated method\n :raises ValidationError: If input is invalid as per the schema\n or malformed\n :raises TypeError: If the output is invalid as per the schema\n or malformed\n :raises APIError: If the output is a falsy value and\n on_empty_404 is True, an HTTP 404 error is returned\n '
@wraps(rh_method)
@tornado.gen.coroutine
def _wrapper(self, *args, **kwargs):
if (input_schema is not None):
try:
encoding = 'UTF-8'
input_ = json.loads(self.request.body.decode(encoding))
except ValueError as e:
raise jsonschema.ValidationError('Input is malformed; could not decode JSON object.')
jsonschema.validate(input_, input_schema, format_checker=format_checker)
else:
input_ = None
setattr(self, 'body', input_)
output = rh_method(self, *args, **kwargs)
if is_future(output):
output = (yield output)
if ((not output) and on_empty_404):
raise APIError(404, 'Resource not found.')
if (output_schema is not None):
try:
jsonschema.validate({'result': output}, {'type': 'object', 'properties': {'result': output_schema}, 'required': ['result']})
except jsonschema.ValidationError as e:
raise TypeError(str(e))
self.success(output)
setattr(_wrapper, 'input_schema', input_schema)
setattr(_wrapper, 'output_schema', output_schema)
setattr(_wrapper, 'input_example', input_example)
setattr(_wrapper, 'output_example', output_example)
return _wrapper
return _validate | Parameterized decorator for schema validation
:type format_checker: jsonschema.FormatChecker or None
:type on_empty_404: bool
:param on_empty_404: If this is set, and the result from the
decorated method is a falsy value, a 404 will be raised. | tornado_json/schema.py | validate | master-zhuang/SearchMax | 0 | python | def validate(input_schema=None, output_schema=None, input_example=None, output_example=None, format_checker=None, on_empty_404=False):
'Parameterized decorator for schema validation\n\n :type format_checker: jsonschema.FormatChecker or None\n :type on_empty_404: bool\n :param on_empty_404: If this is set, and the result from the\n decorated method is a falsy value, a 404 will be raised.\n '
@container
def _validate(rh_method):
'Decorator for RequestHandler schema validation\n\n This decorator:\n\n - Validates request body against input schema of the method\n - Calls the ``rh_method`` and gets output from it\n - Validates output against output schema of the method\n - Calls ``JSendMixin.success`` to write the validated output\n\n :type rh_method: function\n :param rh_method: The RequestHandler method to be decorated\n :returns: The decorated method\n :raises ValidationError: If input is invalid as per the schema\n or malformed\n :raises TypeError: If the output is invalid as per the schema\n or malformed\n :raises APIError: If the output is a falsy value and\n on_empty_404 is True, an HTTP 404 error is returned\n '
@wraps(rh_method)
@tornado.gen.coroutine
def _wrapper(self, *args, **kwargs):
if (input_schema is not None):
try:
encoding = 'UTF-8'
input_ = json.loads(self.request.body.decode(encoding))
except ValueError as e:
raise jsonschema.ValidationError('Input is malformed; could not decode JSON object.')
jsonschema.validate(input_, input_schema, format_checker=format_checker)
else:
input_ = None
setattr(self, 'body', input_)
output = rh_method(self, *args, **kwargs)
if is_future(output):
output = (yield output)
if ((not output) and on_empty_404):
raise APIError(404, 'Resource not found.')
if (output_schema is not None):
try:
jsonschema.validate({'result': output}, {'type': 'object', 'properties': {'result': output_schema}, 'required': ['result']})
except jsonschema.ValidationError as e:
raise TypeError(str(e))
self.success(output)
setattr(_wrapper, 'input_schema', input_schema)
setattr(_wrapper, 'output_schema', output_schema)
setattr(_wrapper, 'input_example', input_example)
setattr(_wrapper, 'output_example', output_example)
return _wrapper
return _validate | def validate(input_schema=None, output_schema=None, input_example=None, output_example=None, format_checker=None, on_empty_404=False):
'Parameterized decorator for schema validation\n\n :type format_checker: jsonschema.FormatChecker or None\n :type on_empty_404: bool\n :param on_empty_404: If this is set, and the result from the\n decorated method is a falsy value, a 404 will be raised.\n '
@container
def _validate(rh_method):
'Decorator for RequestHandler schema validation\n\n This decorator:\n\n - Validates request body against input schema of the method\n - Calls the ``rh_method`` and gets output from it\n - Validates output against output schema of the method\n - Calls ``JSendMixin.success`` to write the validated output\n\n :type rh_method: function\n :param rh_method: The RequestHandler method to be decorated\n :returns: The decorated method\n :raises ValidationError: If input is invalid as per the schema\n or malformed\n :raises TypeError: If the output is invalid as per the schema\n or malformed\n :raises APIError: If the output is a falsy value and\n on_empty_404 is True, an HTTP 404 error is returned\n '
@wraps(rh_method)
@tornado.gen.coroutine
def _wrapper(self, *args, **kwargs):
if (input_schema is not None):
try:
encoding = 'UTF-8'
input_ = json.loads(self.request.body.decode(encoding))
except ValueError as e:
raise jsonschema.ValidationError('Input is malformed; could not decode JSON object.')
jsonschema.validate(input_, input_schema, format_checker=format_checker)
else:
input_ = None
setattr(self, 'body', input_)
output = rh_method(self, *args, **kwargs)
if is_future(output):
output = (yield output)
if ((not output) and on_empty_404):
raise APIError(404, 'Resource not found.')
if (output_schema is not None):
try:
jsonschema.validate({'result': output}, {'type': 'object', 'properties': {'result': output_schema}, 'required': ['result']})
except jsonschema.ValidationError as e:
raise TypeError(str(e))
self.success(output)
setattr(_wrapper, 'input_schema', input_schema)
setattr(_wrapper, 'output_schema', output_schema)
setattr(_wrapper, 'input_example', input_example)
setattr(_wrapper, 'output_example', output_example)
return _wrapper
return _validate<|docstring|>Parameterized decorator for schema validation
:type format_checker: jsonschema.FormatChecker or None
:type on_empty_404: bool
:param on_empty_404: If this is set, and the result from the
decorated method is a falsy value, a 404 will be raised.<|endoftext|> |
e5f222a8376c23402cc510446498ae7832afb8f49d91723c7df5aeb75442860b | @container
def _validate(rh_method):
'Decorator for RequestHandler schema validation\n\n This decorator:\n\n - Validates request body against input schema of the method\n - Calls the ``rh_method`` and gets output from it\n - Validates output against output schema of the method\n - Calls ``JSendMixin.success`` to write the validated output\n\n :type rh_method: function\n :param rh_method: The RequestHandler method to be decorated\n :returns: The decorated method\n :raises ValidationError: If input is invalid as per the schema\n or malformed\n :raises TypeError: If the output is invalid as per the schema\n or malformed\n :raises APIError: If the output is a falsy value and\n on_empty_404 is True, an HTTP 404 error is returned\n '
@wraps(rh_method)
@tornado.gen.coroutine
def _wrapper(self, *args, **kwargs):
if (input_schema is not None):
try:
encoding = 'UTF-8'
input_ = json.loads(self.request.body.decode(encoding))
except ValueError as e:
raise jsonschema.ValidationError('Input is malformed; could not decode JSON object.')
jsonschema.validate(input_, input_schema, format_checker=format_checker)
else:
input_ = None
setattr(self, 'body', input_)
output = rh_method(self, *args, **kwargs)
if is_future(output):
output = (yield output)
if ((not output) and on_empty_404):
raise APIError(404, 'Resource not found.')
if (output_schema is not None):
try:
jsonschema.validate({'result': output}, {'type': 'object', 'properties': {'result': output_schema}, 'required': ['result']})
except jsonschema.ValidationError as e:
raise TypeError(str(e))
self.success(output)
setattr(_wrapper, 'input_schema', input_schema)
setattr(_wrapper, 'output_schema', output_schema)
setattr(_wrapper, 'input_example', input_example)
setattr(_wrapper, 'output_example', output_example)
return _wrapper | Decorator for RequestHandler schema validation
This decorator:
- Validates request body against input schema of the method
- Calls the ``rh_method`` and gets output from it
- Validates output against output schema of the method
- Calls ``JSendMixin.success`` to write the validated output
:type rh_method: function
:param rh_method: The RequestHandler method to be decorated
:returns: The decorated method
:raises ValidationError: If input is invalid as per the schema
or malformed
:raises TypeError: If the output is invalid as per the schema
or malformed
:raises APIError: If the output is a falsy value and
on_empty_404 is True, an HTTP 404 error is returned | tornado_json/schema.py | _validate | master-zhuang/SearchMax | 0 | python | @container
def _validate(rh_method):
'Decorator for RequestHandler schema validation\n\n This decorator:\n\n - Validates request body against input schema of the method\n - Calls the ``rh_method`` and gets output from it\n - Validates output against output schema of the method\n - Calls ``JSendMixin.success`` to write the validated output\n\n :type rh_method: function\n :param rh_method: The RequestHandler method to be decorated\n :returns: The decorated method\n :raises ValidationError: If input is invalid as per the schema\n or malformed\n :raises TypeError: If the output is invalid as per the schema\n or malformed\n :raises APIError: If the output is a falsy value and\n on_empty_404 is True, an HTTP 404 error is returned\n '
@wraps(rh_method)
@tornado.gen.coroutine
def _wrapper(self, *args, **kwargs):
if (input_schema is not None):
try:
encoding = 'UTF-8'
input_ = json.loads(self.request.body.decode(encoding))
except ValueError as e:
raise jsonschema.ValidationError('Input is malformed; could not decode JSON object.')
jsonschema.validate(input_, input_schema, format_checker=format_checker)
else:
input_ = None
setattr(self, 'body', input_)
output = rh_method(self, *args, **kwargs)
if is_future(output):
output = (yield output)
if ((not output) and on_empty_404):
raise APIError(404, 'Resource not found.')
if (output_schema is not None):
try:
jsonschema.validate({'result': output}, {'type': 'object', 'properties': {'result': output_schema}, 'required': ['result']})
except jsonschema.ValidationError as e:
raise TypeError(str(e))
self.success(output)
setattr(_wrapper, 'input_schema', input_schema)
setattr(_wrapper, 'output_schema', output_schema)
setattr(_wrapper, 'input_example', input_example)
setattr(_wrapper, 'output_example', output_example)
return _wrapper | @container
def _validate(rh_method):
'Decorator for RequestHandler schema validation\n\n This decorator:\n\n - Validates request body against input schema of the method\n - Calls the ``rh_method`` and gets output from it\n - Validates output against output schema of the method\n - Calls ``JSendMixin.success`` to write the validated output\n\n :type rh_method: function\n :param rh_method: The RequestHandler method to be decorated\n :returns: The decorated method\n :raises ValidationError: If input is invalid as per the schema\n or malformed\n :raises TypeError: If the output is invalid as per the schema\n or malformed\n :raises APIError: If the output is a falsy value and\n on_empty_404 is True, an HTTP 404 error is returned\n '
@wraps(rh_method)
@tornado.gen.coroutine
def _wrapper(self, *args, **kwargs):
if (input_schema is not None):
try:
encoding = 'UTF-8'
input_ = json.loads(self.request.body.decode(encoding))
except ValueError as e:
raise jsonschema.ValidationError('Input is malformed; could not decode JSON object.')
jsonschema.validate(input_, input_schema, format_checker=format_checker)
else:
input_ = None
setattr(self, 'body', input_)
output = rh_method(self, *args, **kwargs)
if is_future(output):
output = (yield output)
if ((not output) and on_empty_404):
raise APIError(404, 'Resource not found.')
if (output_schema is not None):
try:
jsonschema.validate({'result': output}, {'type': 'object', 'properties': {'result': output_schema}, 'required': ['result']})
except jsonschema.ValidationError as e:
raise TypeError(str(e))
self.success(output)
setattr(_wrapper, 'input_schema', input_schema)
setattr(_wrapper, 'output_schema', output_schema)
setattr(_wrapper, 'input_example', input_example)
setattr(_wrapper, 'output_example', output_example)
return _wrapper<|docstring|>Decorator for RequestHandler schema validation
This decorator:
- Validates request body against input schema of the method
- Calls the ``rh_method`` and gets output from it
- Validates output against output schema of the method
- Calls ``JSendMixin.success`` to write the validated output
:type rh_method: function
:param rh_method: The RequestHandler method to be decorated
:returns: The decorated method
:raises ValidationError: If input is invalid as per the schema
or malformed
:raises TypeError: If the output is invalid as per the schema
or malformed
:raises APIError: If the output is a falsy value and
on_empty_404 is True, an HTTP 404 error is returned<|endoftext|> |
ff152bc0e61f5828ab79e2fbc00064dc56d90a83d75f91bb39ba771fc6c496f9 | def __init__(self, vpn_json):
'Create one VPN object.'
super(Vpn, self).__init__(vpn_json) | Create one VPN object. | skytap/models/Vpn.py | __init__ | mapledyne/skytap | 3 | python | def __init__(self, vpn_json):
super(Vpn, self).__init__(vpn_json) | def __init__(self, vpn_json):
super(Vpn, self).__init__(vpn_json)<|docstring|>Create one VPN object.<|endoftext|> |
6350589953b7d015de43fa00291b03421bdb0bfa57928e86b4c834c2e196520c | def _calculate_custom_data(self):
"Add custom data.\n\n Create an 'active' flag based on the status of the VPN.\n "
self.active = (self.status == 'active') | Add custom data.
Create an 'active' flag based on the status of the VPN. | skytap/models/Vpn.py | _calculate_custom_data | mapledyne/skytap | 3 | python | def _calculate_custom_data(self):
"Add custom data.\n\n Create an 'active' flag based on the status of the VPN.\n "
self.active = (self.status == 'active') | def _calculate_custom_data(self):
"Add custom data.\n\n Create an 'active' flag based on the status of the VPN.\n "
self.active = (self.status == 'active')<|docstring|>Add custom data.
Create an 'active' flag based on the status of the VPN.<|endoftext|> |
9287c3e8d24db622f9e52a937b85398710f6471451106a0ac2fecf3af810e35e | def build_multiple(self, config: BaseBenchmarkerConfig) -> MultipleContextEmbeddings:
"Create multiple context embeddings.\n\n Args:\n config: model's configuration\n\n Returns\n sequence with created embeddings\n\n "
return MultipleContextEmbeddings([self.build(chosen_embeddings_type=context_embeddings['embedding_type'], embeddings_size=config.hidden_size, model_config=config, **context_embeddings) for context_embeddings in config.context_embeddings]) | Create multiple context embeddings.
Args:
config: model's configuration
Returns
sequence with created embeddings | benchmarker/embedding/factory/context.py | build_multiple | due-benchmark/baselines | 23 | python | def build_multiple(self, config: BaseBenchmarkerConfig) -> MultipleContextEmbeddings:
"Create multiple context embeddings.\n\n Args:\n config: model's configuration\n\n Returns\n sequence with created embeddings\n\n "
return MultipleContextEmbeddings([self.build(chosen_embeddings_type=context_embeddings['embedding_type'], embeddings_size=config.hidden_size, model_config=config, **context_embeddings) for context_embeddings in config.context_embeddings]) | def build_multiple(self, config: BaseBenchmarkerConfig) -> MultipleContextEmbeddings:
"Create multiple context embeddings.\n\n Args:\n config: model's configuration\n\n Returns\n sequence with created embeddings\n\n "
return MultipleContextEmbeddings([self.build(chosen_embeddings_type=context_embeddings['embedding_type'], embeddings_size=config.hidden_size, model_config=config, **context_embeddings) for context_embeddings in config.context_embeddings])<|docstring|>Create multiple context embeddings.
Args:
config: model's configuration
Returns
sequence with created embeddings<|endoftext|> |
3b8394c178d697eac827f15aa67005e437d7b450e947924c0577c6b8b65e957b | def build_conditionally(self, config: BaseBenchmarkerConfig) -> Optional[ContextEmbeddings]:
'Build if needed.\n\n Args:\n config: type of embeddings to initialize\n\n Returns:\n instance of ContextEmbeddings or None\n\n '
if (len(config.context_embeddings) > 0):
return self.build_multiple(config)
else:
warnings.warn('Config does not contain parameter which define type of context embeddings.Layout information will not be used by the model.')
return None | Build if needed.
Args:
config: type of embeddings to initialize
Returns:
instance of ContextEmbeddings or None | benchmarker/embedding/factory/context.py | build_conditionally | due-benchmark/baselines | 23 | python | def build_conditionally(self, config: BaseBenchmarkerConfig) -> Optional[ContextEmbeddings]:
'Build if needed.\n\n Args:\n config: type of embeddings to initialize\n\n Returns:\n instance of ContextEmbeddings or None\n\n '
if (len(config.context_embeddings) > 0):
return self.build_multiple(config)
else:
warnings.warn('Config does not contain parameter which define type of context embeddings.Layout information will not be used by the model.')
return None | def build_conditionally(self, config: BaseBenchmarkerConfig) -> Optional[ContextEmbeddings]:
'Build if needed.\n\n Args:\n config: type of embeddings to initialize\n\n Returns:\n instance of ContextEmbeddings or None\n\n '
if (len(config.context_embeddings) > 0):
return self.build_multiple(config)
else:
warnings.warn('Config does not contain parameter which define type of context embeddings.Layout information will not be used by the model.')
return None<|docstring|>Build if needed.
Args:
config: type of embeddings to initialize
Returns:
instance of ContextEmbeddings or None<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.