repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
adobe-apiplatform/umapi-client.py
umapi_client/functional.py
UserAction.update
def update(self, email=None, username=None, first_name=None, last_name=None, country=None): """ Update values on an existing user. See the API docs for what kinds of update are possible. :param email: new email for this user :param username: new username for this user :param first_name: new first name for this user :param last_name: new last name for this user :param country: new country for this user :return: the User, so you can do User(...).update(...).add_to_groups(...) """ if username and self.id_type != IdentityTypes.federatedID: raise ArgumentError("You cannot set username except for a federated ID") if username and '@' in username and not email: raise ArgumentError("Cannot update email-type username when email is not specified") if email and username and email.lower() == username.lower(): raise ArgumentError("Specify just email to set both email and username for a federated ID") updates = {} for k, v in six.iteritems(dict(email=email, username=username, firstname=first_name, lastname=last_name, country=country)): if v: updates[k] = v return self.append(update=updates)
python
def update(self, email=None, username=None, first_name=None, last_name=None, country=None): """ Update values on an existing user. See the API docs for what kinds of update are possible. :param email: new email for this user :param username: new username for this user :param first_name: new first name for this user :param last_name: new last name for this user :param country: new country for this user :return: the User, so you can do User(...).update(...).add_to_groups(...) """ if username and self.id_type != IdentityTypes.federatedID: raise ArgumentError("You cannot set username except for a federated ID") if username and '@' in username and not email: raise ArgumentError("Cannot update email-type username when email is not specified") if email and username and email.lower() == username.lower(): raise ArgumentError("Specify just email to set both email and username for a federated ID") updates = {} for k, v in six.iteritems(dict(email=email, username=username, firstname=first_name, lastname=last_name, country=country)): if v: updates[k] = v return self.append(update=updates)
[ "def", "update", "(", "self", ",", "email", "=", "None", ",", "username", "=", "None", ",", "first_name", "=", "None", ",", "last_name", "=", "None", ",", "country", "=", "None", ")", ":", "if", "username", "and", "self", ".", "id_type", "!=", "Ident...
Update values on an existing user. See the API docs for what kinds of update are possible. :param email: new email for this user :param username: new username for this user :param first_name: new first name for this user :param last_name: new last name for this user :param country: new country for this user :return: the User, so you can do User(...).update(...).add_to_groups(...)
[ "Update", "values", "on", "an", "existing", "user", ".", "See", "the", "API", "docs", "for", "what", "kinds", "of", "update", "are", "possible", ".", ":", "param", "email", ":", "new", "email", "for", "this", "user", ":", "param", "username", ":", "new...
1c446d79643cc8615adaa23e12dce3ac5782cf76
https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/functional.py#L158-L180
train
adobe-apiplatform/umapi-client.py
umapi_client/functional.py
UserAction.add_to_groups
def add_to_groups(self, groups=None, all_groups=False, group_type=None): """ Add user to some (typically PLC) groups. Note that, if you add to no groups, the effect is simply to do an "add to organization Everybody group", so we let that be done. :param groups: list of group names the user should be added to :param all_groups: a boolean meaning add to all (don't specify groups or group_type in this case) :param group_type: the type of group (defaults to "product") :return: the User, so you can do User(...).add_to_groups(...).add_role(...) """ if all_groups: if groups or group_type: raise ArgumentError("When adding to all groups, do not specify specific groups or types") glist = "all" else: if not groups: groups = [] if not group_type: group_type = GroupTypes.product elif group_type in GroupTypes.__members__: group_type = GroupTypes[group_type] if group_type not in GroupTypes: raise ArgumentError("You must specify a GroupType value for argument group_type") glist = {group_type.name: [group for group in groups]} return self.append(add=glist)
python
def add_to_groups(self, groups=None, all_groups=False, group_type=None): """ Add user to some (typically PLC) groups. Note that, if you add to no groups, the effect is simply to do an "add to organization Everybody group", so we let that be done. :param groups: list of group names the user should be added to :param all_groups: a boolean meaning add to all (don't specify groups or group_type in this case) :param group_type: the type of group (defaults to "product") :return: the User, so you can do User(...).add_to_groups(...).add_role(...) """ if all_groups: if groups or group_type: raise ArgumentError("When adding to all groups, do not specify specific groups or types") glist = "all" else: if not groups: groups = [] if not group_type: group_type = GroupTypes.product elif group_type in GroupTypes.__members__: group_type = GroupTypes[group_type] if group_type not in GroupTypes: raise ArgumentError("You must specify a GroupType value for argument group_type") glist = {group_type.name: [group for group in groups]} return self.append(add=glist)
[ "def", "add_to_groups", "(", "self", ",", "groups", "=", "None", ",", "all_groups", "=", "False", ",", "group_type", "=", "None", ")", ":", "if", "all_groups", ":", "if", "groups", "or", "group_type", ":", "raise", "ArgumentError", "(", "\"When adding to all...
Add user to some (typically PLC) groups. Note that, if you add to no groups, the effect is simply to do an "add to organization Everybody group", so we let that be done. :param groups: list of group names the user should be added to :param all_groups: a boolean meaning add to all (don't specify groups or group_type in this case) :param group_type: the type of group (defaults to "product") :return: the User, so you can do User(...).add_to_groups(...).add_role(...)
[ "Add", "user", "to", "some", "(", "typically", "PLC", ")", "groups", ".", "Note", "that", "if", "you", "add", "to", "no", "groups", "the", "effect", "is", "simply", "to", "do", "an", "add", "to", "organization", "Everybody", "group", "so", "we", "let",...
1c446d79643cc8615adaa23e12dce3ac5782cf76
https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/functional.py#L182-L205
train
adobe-apiplatform/umapi-client.py
umapi_client/functional.py
UserAction.remove_from_groups
def remove_from_groups(self, groups=None, all_groups=False, group_type=None): """ Remove user from some PLC groups, or all of them. :param groups: list of group names the user should be removed from :param all_groups: a boolean meaning remove from all (don't specify groups or group_type in this case) :param group_type: the type of group (defaults to "product") :return: the User, so you can do User(...).remove_from_groups(...).add_role(...) """ if all_groups: if groups or group_type: raise ArgumentError("When removing from all groups, do not specify specific groups or types") glist = "all" else: if not groups: raise ArgumentError("You must specify groups from which to remove the user") if not group_type: group_type = GroupTypes.product elif group_type in GroupTypes.__members__: group_type = GroupTypes[group_type] if group_type not in GroupTypes: raise ArgumentError("You must specify a GroupType value for argument group_type") glist = {group_type.name: [group for group in groups]} return self.append(remove=glist)
python
def remove_from_groups(self, groups=None, all_groups=False, group_type=None): """ Remove user from some PLC groups, or all of them. :param groups: list of group names the user should be removed from :param all_groups: a boolean meaning remove from all (don't specify groups or group_type in this case) :param group_type: the type of group (defaults to "product") :return: the User, so you can do User(...).remove_from_groups(...).add_role(...) """ if all_groups: if groups or group_type: raise ArgumentError("When removing from all groups, do not specify specific groups or types") glist = "all" else: if not groups: raise ArgumentError("You must specify groups from which to remove the user") if not group_type: group_type = GroupTypes.product elif group_type in GroupTypes.__members__: group_type = GroupTypes[group_type] if group_type not in GroupTypes: raise ArgumentError("You must specify a GroupType value for argument group_type") glist = {group_type.name: [group for group in groups]} return self.append(remove=glist)
[ "def", "remove_from_groups", "(", "self", ",", "groups", "=", "None", ",", "all_groups", "=", "False", ",", "group_type", "=", "None", ")", ":", "if", "all_groups", ":", "if", "groups", "or", "group_type", ":", "raise", "ArgumentError", "(", "\"When removing...
Remove user from some PLC groups, or all of them. :param groups: list of group names the user should be removed from :param all_groups: a boolean meaning remove from all (don't specify groups or group_type in this case) :param group_type: the type of group (defaults to "product") :return: the User, so you can do User(...).remove_from_groups(...).add_role(...)
[ "Remove", "user", "from", "some", "PLC", "groups", "or", "all", "of", "them", ".", ":", "param", "groups", ":", "list", "of", "group", "names", "the", "user", "should", "be", "removed", "from", ":", "param", "all_groups", ":", "a", "boolean", "meaning", ...
1c446d79643cc8615adaa23e12dce3ac5782cf76
https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/functional.py#L207-L229
train
adobe-apiplatform/umapi-client.py
umapi_client/functional.py
UserAction.add_role
def add_role(self, groups=None, role_type=RoleTypes.admin): """ Make user have a role (typically PLC admin) with respect to some PLC groups. :param groups: list of group names the user should have this role for :param role_type: the role (defaults to "admin") :return: the User, so you can do User(...).add_role(...).add_to_groups(...) """ if not groups: raise ArgumentError("You must specify groups to which to add the role for this user") if role_type in RoleTypes.__members__: role_type = RoleTypes[role_type] if role_type not in RoleTypes: raise ArgumentError("You must specify a RoleType value for argument role_type") glist = {role_type.name: [group for group in groups]} return self.append(addRoles=glist)
python
def add_role(self, groups=None, role_type=RoleTypes.admin): """ Make user have a role (typically PLC admin) with respect to some PLC groups. :param groups: list of group names the user should have this role for :param role_type: the role (defaults to "admin") :return: the User, so you can do User(...).add_role(...).add_to_groups(...) """ if not groups: raise ArgumentError("You must specify groups to which to add the role for this user") if role_type in RoleTypes.__members__: role_type = RoleTypes[role_type] if role_type not in RoleTypes: raise ArgumentError("You must specify a RoleType value for argument role_type") glist = {role_type.name: [group for group in groups]} return self.append(addRoles=glist)
[ "def", "add_role", "(", "self", ",", "groups", "=", "None", ",", "role_type", "=", "RoleTypes", ".", "admin", ")", ":", "if", "not", "groups", ":", "raise", "ArgumentError", "(", "\"You must specify groups to which to add the role for this user\"", ")", "if", "rol...
Make user have a role (typically PLC admin) with respect to some PLC groups. :param groups: list of group names the user should have this role for :param role_type: the role (defaults to "admin") :return: the User, so you can do User(...).add_role(...).add_to_groups(...)
[ "Make", "user", "have", "a", "role", "(", "typically", "PLC", "admin", ")", "with", "respect", "to", "some", "PLC", "groups", ".", ":", "param", "groups", ":", "list", "of", "group", "names", "the", "user", "should", "have", "this", "role", "for", ":",...
1c446d79643cc8615adaa23e12dce3ac5782cf76
https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/functional.py#L231-L245
train
adobe-apiplatform/umapi-client.py
umapi_client/functional.py
UserAction.remove_role
def remove_role(self, groups=None, role_type=RoleTypes.admin): """ Remove user from a role (typically admin) of some groups. :param groups: list of group names the user should NOT have this role for :param role_type: the type of role (defaults to "admin") :return: the User, so you can do User(...).remove_role(...).remove_from_groups(...) """ if not groups: raise ArgumentError("You must specify groups from which to remove the role for this user") if role_type in RoleTypes.__members__: role_type = RoleTypes[role_type] if role_type not in RoleTypes: raise ArgumentError("You must specify a RoleType value for argument role_type") glist = {role_type.name: [group for group in groups]} return self.append(removeRoles=glist)
python
def remove_role(self, groups=None, role_type=RoleTypes.admin): """ Remove user from a role (typically admin) of some groups. :param groups: list of group names the user should NOT have this role for :param role_type: the type of role (defaults to "admin") :return: the User, so you can do User(...).remove_role(...).remove_from_groups(...) """ if not groups: raise ArgumentError("You must specify groups from which to remove the role for this user") if role_type in RoleTypes.__members__: role_type = RoleTypes[role_type] if role_type not in RoleTypes: raise ArgumentError("You must specify a RoleType value for argument role_type") glist = {role_type.name: [group for group in groups]} return self.append(removeRoles=glist)
[ "def", "remove_role", "(", "self", ",", "groups", "=", "None", ",", "role_type", "=", "RoleTypes", ".", "admin", ")", ":", "if", "not", "groups", ":", "raise", "ArgumentError", "(", "\"You must specify groups from which to remove the role for this user\"", ")", "if"...
Remove user from a role (typically admin) of some groups. :param groups: list of group names the user should NOT have this role for :param role_type: the type of role (defaults to "admin") :return: the User, so you can do User(...).remove_role(...).remove_from_groups(...)
[ "Remove", "user", "from", "a", "role", "(", "typically", "admin", ")", "of", "some", "groups", ".", ":", "param", "groups", ":", "list", "of", "group", "names", "the", "user", "should", "NOT", "have", "this", "role", "for", ":", "param", "role_type", "...
1c446d79643cc8615adaa23e12dce3ac5782cf76
https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/functional.py#L247-L261
train
adobe-apiplatform/umapi-client.py
umapi_client/functional.py
UserAction.remove_from_organization
def remove_from_organization(self, delete_account=False): """ Remove a user from the organization's list of visible users. Optionally also delete the account. Deleting the account can only be done if the organization owns the account's domain. :param delete_account: Whether to delete the account after removing from the organization (default false) :return: None, because you cannot follow this command with another. """ self.append(removeFromOrg={"deleteAccount": True if delete_account else False}) return None
python
def remove_from_organization(self, delete_account=False): """ Remove a user from the organization's list of visible users. Optionally also delete the account. Deleting the account can only be done if the organization owns the account's domain. :param delete_account: Whether to delete the account after removing from the organization (default false) :return: None, because you cannot follow this command with another. """ self.append(removeFromOrg={"deleteAccount": True if delete_account else False}) return None
[ "def", "remove_from_organization", "(", "self", ",", "delete_account", "=", "False", ")", ":", "self", ".", "append", "(", "removeFromOrg", "=", "{", "\"deleteAccount\"", ":", "True", "if", "delete_account", "else", "False", "}", ")", "return", "None" ]
Remove a user from the organization's list of visible users. Optionally also delete the account. Deleting the account can only be done if the organization owns the account's domain. :param delete_account: Whether to delete the account after removing from the organization (default false) :return: None, because you cannot follow this command with another.
[ "Remove", "a", "user", "from", "the", "organization", "s", "list", "of", "visible", "users", ".", "Optionally", "also", "delete", "the", "account", ".", "Deleting", "the", "account", "can", "only", "be", "done", "if", "the", "organization", "owns", "the", ...
1c446d79643cc8615adaa23e12dce3ac5782cf76
https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/functional.py#L263-L271
train
adobe-apiplatform/umapi-client.py
umapi_client/functional.py
UserAction.delete_account
def delete_account(self): """ Delete a user's account. Deleting the user's account can only be done if the user's domain is controlled by the authorized organization, and removing the account will also remove the user from all organizations with access to that domain. :return: None, because you cannot follow this command with another. """ if self.id_type == IdentityTypes.adobeID: raise ArgumentError("You cannot delete an Adobe ID account.") self.append(removeFromDomain={}) return None
python
def delete_account(self): """ Delete a user's account. Deleting the user's account can only be done if the user's domain is controlled by the authorized organization, and removing the account will also remove the user from all organizations with access to that domain. :return: None, because you cannot follow this command with another. """ if self.id_type == IdentityTypes.adobeID: raise ArgumentError("You cannot delete an Adobe ID account.") self.append(removeFromDomain={}) return None
[ "def", "delete_account", "(", "self", ")", ":", "if", "self", ".", "id_type", "==", "IdentityTypes", ".", "adobeID", ":", "raise", "ArgumentError", "(", "\"You cannot delete an Adobe ID account.\"", ")", "self", ".", "append", "(", "removeFromDomain", "=", "{", ...
Delete a user's account. Deleting the user's account can only be done if the user's domain is controlled by the authorized organization, and removing the account will also remove the user from all organizations with access to that domain. :return: None, because you cannot follow this command with another.
[ "Delete", "a", "user", "s", "account", ".", "Deleting", "the", "user", "s", "account", "can", "only", "be", "done", "if", "the", "user", "s", "domain", "is", "controlled", "by", "the", "authorized", "organization", "and", "removing", "the", "account", "wil...
1c446d79643cc8615adaa23e12dce3ac5782cf76
https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/functional.py#L273-L283
train
adobe-apiplatform/umapi-client.py
umapi_client/functional.py
UserGroupAction._validate
def _validate(cls, group_name): """ Validates the group name Input values must be strings (standard or unicode). Throws ArgumentError if any input is invalid :param group_name: name of group """ if group_name and not cls._group_name_regex.match(group_name): raise ArgumentError("'%s': Illegal group name" % (group_name,)) if group_name and len(group_name) > 255: raise ArgumentError("'%s': Group name is too long" % (group_name,))
python
def _validate(cls, group_name): """ Validates the group name Input values must be strings (standard or unicode). Throws ArgumentError if any input is invalid :param group_name: name of group """ if group_name and not cls._group_name_regex.match(group_name): raise ArgumentError("'%s': Illegal group name" % (group_name,)) if group_name and len(group_name) > 255: raise ArgumentError("'%s': Group name is too long" % (group_name,))
[ "def", "_validate", "(", "cls", ",", "group_name", ")", ":", "if", "group_name", "and", "not", "cls", ".", "_group_name_regex", ".", "match", "(", "group_name", ")", ":", "raise", "ArgumentError", "(", "\"'%s': Illegal group name\"", "%", "(", "group_name", ",...
Validates the group name Input values must be strings (standard or unicode). Throws ArgumentError if any input is invalid :param group_name: name of group
[ "Validates", "the", "group", "name", "Input", "values", "must", "be", "strings", "(", "standard", "or", "unicode", ")", ".", "Throws", "ArgumentError", "if", "any", "input", "is", "invalid", ":", "param", "group_name", ":", "name", "of", "group" ]
1c446d79643cc8615adaa23e12dce3ac5782cf76
https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/functional.py#L329-L338
train
adobe-apiplatform/umapi-client.py
umapi_client/functional.py
UserGroupAction.add_to_products
def add_to_products(self, products=None, all_products=False): """ Add user group to some product license configuration groups (PLCs), or all of them. :param products: list of product names the user should be added to :param all_products: a boolean meaning add to all (don't specify products in this case) :return: the Group, so you can do Group(...).add_to_products(...).add_users(...) """ if all_products: if products: raise ArgumentError("When adding to all products, do not specify specific products") plist = "all" else: if not products: raise ArgumentError("You must specify products to which to add the user group") plist = {GroupTypes.productConfiguration.name: [product for product in products]} return self.append(add=plist)
python
def add_to_products(self, products=None, all_products=False): """ Add user group to some product license configuration groups (PLCs), or all of them. :param products: list of product names the user should be added to :param all_products: a boolean meaning add to all (don't specify products in this case) :return: the Group, so you can do Group(...).add_to_products(...).add_users(...) """ if all_products: if products: raise ArgumentError("When adding to all products, do not specify specific products") plist = "all" else: if not products: raise ArgumentError("You must specify products to which to add the user group") plist = {GroupTypes.productConfiguration.name: [product for product in products]} return self.append(add=plist)
[ "def", "add_to_products", "(", "self", ",", "products", "=", "None", ",", "all_products", "=", "False", ")", ":", "if", "all_products", ":", "if", "products", ":", "raise", "ArgumentError", "(", "\"When adding to all products, do not specify specific products\"", ")",...
Add user group to some product license configuration groups (PLCs), or all of them. :param products: list of product names the user should be added to :param all_products: a boolean meaning add to all (don't specify products in this case) :return: the Group, so you can do Group(...).add_to_products(...).add_users(...)
[ "Add", "user", "group", "to", "some", "product", "license", "configuration", "groups", "(", "PLCs", ")", "or", "all", "of", "them", ".", ":", "param", "products", ":", "list", "of", "product", "names", "the", "user", "should", "be", "added", "to", ":", ...
1c446d79643cc8615adaa23e12dce3ac5782cf76
https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/functional.py#L350-L365
train
adobe-apiplatform/umapi-client.py
umapi_client/functional.py
UserGroupAction.remove_from_products
def remove_from_products(self, products=None, all_products=False): """ Remove user group from some product license configuration groups (PLCs), or all of them. :param products: list of product names the user group should be removed from :param all_products: a boolean meaning remove from all (don't specify products in this case) :return: the Group, so you can do Group(...).remove_from_products(...).add_users(...) """ if all_products: if products: raise ArgumentError("When removing from all products, do not specify specific products") plist = "all" else: if not products: raise ArgumentError("You must specify products from which to remove the user group") plist = {GroupTypes.productConfiguration.name: [product for product in products]} return self.append(remove=plist)
python
def remove_from_products(self, products=None, all_products=False): """ Remove user group from some product license configuration groups (PLCs), or all of them. :param products: list of product names the user group should be removed from :param all_products: a boolean meaning remove from all (don't specify products in this case) :return: the Group, so you can do Group(...).remove_from_products(...).add_users(...) """ if all_products: if products: raise ArgumentError("When removing from all products, do not specify specific products") plist = "all" else: if not products: raise ArgumentError("You must specify products from which to remove the user group") plist = {GroupTypes.productConfiguration.name: [product for product in products]} return self.append(remove=plist)
[ "def", "remove_from_products", "(", "self", ",", "products", "=", "None", ",", "all_products", "=", "False", ")", ":", "if", "all_products", ":", "if", "products", ":", "raise", "ArgumentError", "(", "\"When removing from all products, do not specify specific products\"...
Remove user group from some product license configuration groups (PLCs), or all of them. :param products: list of product names the user group should be removed from :param all_products: a boolean meaning remove from all (don't specify products in this case) :return: the Group, so you can do Group(...).remove_from_products(...).add_users(...)
[ "Remove", "user", "group", "from", "some", "product", "license", "configuration", "groups", "(", "PLCs", ")", "or", "all", "of", "them", ".", ":", "param", "products", ":", "list", "of", "product", "names", "the", "user", "group", "should", "be", "removed"...
1c446d79643cc8615adaa23e12dce3ac5782cf76
https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/functional.py#L367-L382
train
adobe-apiplatform/umapi-client.py
umapi_client/functional.py
UserGroupAction.add_users
def add_users(self, users=None): """ Add users (specified by email address) to this user group. In case of ambiguity (two users with same email address), the non-AdobeID user is preferred. :param users: list of emails for users to add to the group. :return: the Group, so you can do Group(...).add_users(...).add_to_products(...) """ if not users: raise ArgumentError("You must specify emails for users to add to the user group") ulist = {"user": [user for user in users]} return self.append(add=ulist)
python
def add_users(self, users=None): """ Add users (specified by email address) to this user group. In case of ambiguity (two users with same email address), the non-AdobeID user is preferred. :param users: list of emails for users to add to the group. :return: the Group, so you can do Group(...).add_users(...).add_to_products(...) """ if not users: raise ArgumentError("You must specify emails for users to add to the user group") ulist = {"user": [user for user in users]} return self.append(add=ulist)
[ "def", "add_users", "(", "self", ",", "users", "=", "None", ")", ":", "if", "not", "users", ":", "raise", "ArgumentError", "(", "\"You must specify emails for users to add to the user group\"", ")", "ulist", "=", "{", "\"user\"", ":", "[", "user", "for", "user",...
Add users (specified by email address) to this user group. In case of ambiguity (two users with same email address), the non-AdobeID user is preferred. :param users: list of emails for users to add to the group. :return: the Group, so you can do Group(...).add_users(...).add_to_products(...)
[ "Add", "users", "(", "specified", "by", "email", "address", ")", "to", "this", "user", "group", ".", "In", "case", "of", "ambiguity", "(", "two", "users", "with", "same", "email", "address", ")", "the", "non", "-", "AdobeID", "user", "is", "preferred", ...
1c446d79643cc8615adaa23e12dce3ac5782cf76
https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/functional.py#L384-L394
train
adobe-apiplatform/umapi-client.py
umapi_client/functional.py
UserGroupAction.remove_users
def remove_users(self, users=None): """ Remove users (specified by email address) from this user group. In case of ambiguity (two users with same email address), the non-AdobeID user is preferred. :param users: list of emails for users to remove from the group. :return: the Group, so you can do Group(...).remove_users(...).add_to_products(...) """ if not users: raise ArgumentError("You must specify emails for users to remove from the user group") ulist = {"user": [user for user in users]} return self.append(remove=ulist)
python
def remove_users(self, users=None): """ Remove users (specified by email address) from this user group. In case of ambiguity (two users with same email address), the non-AdobeID user is preferred. :param users: list of emails for users to remove from the group. :return: the Group, so you can do Group(...).remove_users(...).add_to_products(...) """ if not users: raise ArgumentError("You must specify emails for users to remove from the user group") ulist = {"user": [user for user in users]} return self.append(remove=ulist)
[ "def", "remove_users", "(", "self", ",", "users", "=", "None", ")", ":", "if", "not", "users", ":", "raise", "ArgumentError", "(", "\"You must specify emails for users to remove from the user group\"", ")", "ulist", "=", "{", "\"user\"", ":", "[", "user", "for", ...
Remove users (specified by email address) from this user group. In case of ambiguity (two users with same email address), the non-AdobeID user is preferred. :param users: list of emails for users to remove from the group. :return: the Group, so you can do Group(...).remove_users(...).add_to_products(...)
[ "Remove", "users", "(", "specified", "by", "email", "address", ")", "from", "this", "user", "group", ".", "In", "case", "of", "ambiguity", "(", "two", "users", "with", "same", "email", "address", ")", "the", "non", "-", "AdobeID", "user", "is", "preferre...
1c446d79643cc8615adaa23e12dce3ac5782cf76
https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/functional.py#L396-L406
train
rm-hull/luma.emulator
luma/emulator/render.py
transformer.scale2x
def scale2x(self, surface): """ Scales using the AdvanceMAME Scale2X algorithm which does a 'jaggie-less' scale of bitmap graphics. """ assert(self._scale == 2) return self._pygame.transform.scale2x(surface)
python
def scale2x(self, surface): """ Scales using the AdvanceMAME Scale2X algorithm which does a 'jaggie-less' scale of bitmap graphics. """ assert(self._scale == 2) return self._pygame.transform.scale2x(surface)
[ "def", "scale2x", "(", "self", ",", "surface", ")", ":", "assert", "(", "self", ".", "_scale", "==", "2", ")", "return", "self", ".", "_pygame", ".", "transform", ".", "scale2x", "(", "surface", ")" ]
Scales using the AdvanceMAME Scale2X algorithm which does a 'jaggie-less' scale of bitmap graphics.
[ "Scales", "using", "the", "AdvanceMAME", "Scale2X", "algorithm", "which", "does", "a", "jaggie", "-", "less", "scale", "of", "bitmap", "graphics", "." ]
ca3db028b33d17cda9247ea5189873ff0408d013
https://github.com/rm-hull/luma.emulator/blob/ca3db028b33d17cda9247ea5189873ff0408d013/luma/emulator/render.py#L31-L37
train
rm-hull/luma.emulator
luma/emulator/render.py
transformer.smoothscale
def smoothscale(self, surface): """ Smooth scaling using MMX or SSE extensions if available """ return self._pygame.transform.smoothscale(surface, self._output_size)
python
def smoothscale(self, surface): """ Smooth scaling using MMX or SSE extensions if available """ return self._pygame.transform.smoothscale(surface, self._output_size)
[ "def", "smoothscale", "(", "self", ",", "surface", ")", ":", "return", "self", ".", "_pygame", ".", "transform", ".", "smoothscale", "(", "surface", ",", "self", ".", "_output_size", ")" ]
Smooth scaling using MMX or SSE extensions if available
[ "Smooth", "scaling", "using", "MMX", "or", "SSE", "extensions", "if", "available" ]
ca3db028b33d17cda9247ea5189873ff0408d013
https://github.com/rm-hull/luma.emulator/blob/ca3db028b33d17cda9247ea5189873ff0408d013/luma/emulator/render.py#L39-L43
train
rm-hull/luma.emulator
luma/emulator/render.py
transformer.identity
def identity(self, surface): """ Fast scale operation that does not sample the results """ return self._pygame.transform.scale(surface, self._output_size)
python
def identity(self, surface): """ Fast scale operation that does not sample the results """ return self._pygame.transform.scale(surface, self._output_size)
[ "def", "identity", "(", "self", ",", "surface", ")", ":", "return", "self", ".", "_pygame", ".", "transform", ".", "scale", "(", "surface", ",", "self", ".", "_output_size", ")" ]
Fast scale operation that does not sample the results
[ "Fast", "scale", "operation", "that", "does", "not", "sample", "the", "results" ]
ca3db028b33d17cda9247ea5189873ff0408d013
https://github.com/rm-hull/luma.emulator/blob/ca3db028b33d17cda9247ea5189873ff0408d013/luma/emulator/render.py#L45-L49
train
rm-hull/luma.emulator
luma/emulator/render.py
transformer.led_matrix
def led_matrix(self, surface): """ Transforms the input surface into an LED matrix (1 pixel = 1 LED) """ scale = self._led_on.get_width() w, h = self._input_size pix = self._pygame.PixelArray(surface) img = self._pygame.Surface((w * scale, h * scale)) for y in range(h): for x in range(w): led = self._led_on if pix[x, y] & 0xFFFFFF > 0 else self._led_off img.blit(led, (x * scale, y * scale)) return img
python
def led_matrix(self, surface): """ Transforms the input surface into an LED matrix (1 pixel = 1 LED) """ scale = self._led_on.get_width() w, h = self._input_size pix = self._pygame.PixelArray(surface) img = self._pygame.Surface((w * scale, h * scale)) for y in range(h): for x in range(w): led = self._led_on if pix[x, y] & 0xFFFFFF > 0 else self._led_off img.blit(led, (x * scale, y * scale)) return img
[ "def", "led_matrix", "(", "self", ",", "surface", ")", ":", "scale", "=", "self", ".", "_led_on", ".", "get_width", "(", ")", "w", ",", "h", "=", "self", ".", "_input_size", "pix", "=", "self", ".", "_pygame", ".", "PixelArray", "(", "surface", ")", ...
Transforms the input surface into an LED matrix (1 pixel = 1 LED)
[ "Transforms", "the", "input", "surface", "into", "an", "LED", "matrix", "(", "1", "pixel", "=", "1", "LED", ")" ]
ca3db028b33d17cda9247ea5189873ff0408d013
https://github.com/rm-hull/luma.emulator/blob/ca3db028b33d17cda9247ea5189873ff0408d013/luma/emulator/render.py#L51-L65
train
rm-hull/luma.emulator
luma/emulator/clut.py
rgb2short
def rgb2short(r, g, b): """ Converts RGB values to the nearest equivalent xterm-256 color. """ # Using list of snap points, convert RGB value to cube indexes r, g, b = [len(tuple(s for s in snaps if s < x)) for x in (r, g, b)] # Simple colorcube transform return (r * 36) + (g * 6) + b + 16
python
def rgb2short(r, g, b): """ Converts RGB values to the nearest equivalent xterm-256 color. """ # Using list of snap points, convert RGB value to cube indexes r, g, b = [len(tuple(s for s in snaps if s < x)) for x in (r, g, b)] # Simple colorcube transform return (r * 36) + (g * 6) + b + 16
[ "def", "rgb2short", "(", "r", ",", "g", ",", "b", ")", ":", "# Using list of snap points, convert RGB value to cube indexes", "r", ",", "g", ",", "b", "=", "[", "len", "(", "tuple", "(", "s", "for", "s", "in", "snaps", "if", "s", "<", "x", ")", ")", ...
Converts RGB values to the nearest equivalent xterm-256 color.
[ "Converts", "RGB", "values", "to", "the", "nearest", "equivalent", "xterm", "-", "256", "color", "." ]
ca3db028b33d17cda9247ea5189873ff0408d013
https://github.com/rm-hull/luma.emulator/blob/ca3db028b33d17cda9247ea5189873ff0408d013/luma/emulator/clut.py#L14-L22
train
rm-hull/luma.emulator
luma/emulator/device.py
emulator.to_surface
def to_surface(self, image, alpha=1.0): """ Converts a :py:mod:`PIL.Image` into a :class:`pygame.Surface`, transforming it according to the ``transform`` and ``scale`` constructor arguments. """ assert(0.0 <= alpha <= 1.0) if alpha < 1.0: im = image.convert("RGBA") black = Image.new(im.mode, im.size, "black") im = Image.blend(black, im, alpha) else: im = image.convert("RGB") mode = im.mode size = im.size data = im.tobytes() del im surface = self._pygame.image.fromstring(data, size, mode) return self._transform(surface)
python
def to_surface(self, image, alpha=1.0): """ Converts a :py:mod:`PIL.Image` into a :class:`pygame.Surface`, transforming it according to the ``transform`` and ``scale`` constructor arguments. """ assert(0.0 <= alpha <= 1.0) if alpha < 1.0: im = image.convert("RGBA") black = Image.new(im.mode, im.size, "black") im = Image.blend(black, im, alpha) else: im = image.convert("RGB") mode = im.mode size = im.size data = im.tobytes() del im surface = self._pygame.image.fromstring(data, size, mode) return self._transform(surface)
[ "def", "to_surface", "(", "self", ",", "image", ",", "alpha", "=", "1.0", ")", ":", "assert", "(", "0.0", "<=", "alpha", "<=", "1.0", ")", "if", "alpha", "<", "1.0", ":", "im", "=", "image", ".", "convert", "(", "\"RGBA\"", ")", "black", "=", "Im...
Converts a :py:mod:`PIL.Image` into a :class:`pygame.Surface`, transforming it according to the ``transform`` and ``scale`` constructor arguments.
[ "Converts", "a", ":", "py", ":", "mod", ":", "PIL", ".", "Image", "into", "a", ":", "class", ":", "pygame", ".", "Surface", "transforming", "it", "according", "to", "the", "transform", "and", "scale", "constructor", "arguments", "." ]
ca3db028b33d17cda9247ea5189873ff0408d013
https://github.com/rm-hull/luma.emulator/blob/ca3db028b33d17cda9247ea5189873ff0408d013/luma/emulator/device.py#L64-L84
train
rm-hull/luma.emulator
luma/emulator/device.py
capture.display
def display(self, image): """ Takes a :py:mod:`PIL.Image` and dumps it to a numbered PNG file. """ assert(image.size == self.size) self._last_image = image self._count += 1 filename = self._file_template.format(self._count) image = self.preprocess(image) surface = self.to_surface(image, alpha=self._contrast) logger.debug("Writing: {0}".format(filename)) self._pygame.image.save(surface, filename)
python
def display(self, image): """ Takes a :py:mod:`PIL.Image` and dumps it to a numbered PNG file. """ assert(image.size == self.size) self._last_image = image self._count += 1 filename = self._file_template.format(self._count) image = self.preprocess(image) surface = self.to_surface(image, alpha=self._contrast) logger.debug("Writing: {0}".format(filename)) self._pygame.image.save(surface, filename)
[ "def", "display", "(", "self", ",", "image", ")", ":", "assert", "(", "image", ".", "size", "==", "self", ".", "size", ")", "self", ".", "_last_image", "=", "image", "self", ".", "_count", "+=", "1", "filename", "=", "self", ".", "_file_template", "....
Takes a :py:mod:`PIL.Image` and dumps it to a numbered PNG file.
[ "Takes", "a", ":", "py", ":", "mod", ":", "PIL", ".", "Image", "and", "dumps", "it", "to", "a", "numbered", "PNG", "file", "." ]
ca3db028b33d17cda9247ea5189873ff0408d013
https://github.com/rm-hull/luma.emulator/blob/ca3db028b33d17cda9247ea5189873ff0408d013/luma/emulator/device.py#L100-L112
train
rm-hull/luma.emulator
luma/emulator/device.py
gifanim.display
def display(self, image): """ Takes an image, scales it according to the nominated transform, and stores it for later building into an animated GIF. """ assert(image.size == self.size) self._last_image = image image = self.preprocess(image) surface = self.to_surface(image, alpha=self._contrast) rawbytes = self._pygame.image.tostring(surface, "RGB", False) im = Image.frombytes("RGB", surface.get_size(), rawbytes) self._images.append(im) self._count += 1 logger.debug("Recording frame: {0}".format(self._count)) if self._max_frames and self._count >= self._max_frames: sys.exit(0)
python
def display(self, image): """ Takes an image, scales it according to the nominated transform, and stores it for later building into an animated GIF. """ assert(image.size == self.size) self._last_image = image image = self.preprocess(image) surface = self.to_surface(image, alpha=self._contrast) rawbytes = self._pygame.image.tostring(surface, "RGB", False) im = Image.frombytes("RGB", surface.get_size(), rawbytes) self._images.append(im) self._count += 1 logger.debug("Recording frame: {0}".format(self._count)) if self._max_frames and self._count >= self._max_frames: sys.exit(0)
[ "def", "display", "(", "self", ",", "image", ")", ":", "assert", "(", "image", ".", "size", "==", "self", ".", "size", ")", "self", ".", "_last_image", "=", "image", "image", "=", "self", ".", "preprocess", "(", "image", ")", "surface", "=", "self", ...
Takes an image, scales it according to the nominated transform, and stores it for later building into an animated GIF.
[ "Takes", "an", "image", "scales", "it", "according", "to", "the", "nominated", "transform", "and", "stores", "it", "for", "later", "building", "into", "an", "animated", "GIF", "." ]
ca3db028b33d17cda9247ea5189873ff0408d013
https://github.com/rm-hull/luma.emulator/blob/ca3db028b33d17cda9247ea5189873ff0408d013/luma/emulator/device.py#L134-L152
train
rm-hull/luma.emulator
luma/emulator/device.py
pygame.display
def display(self, image): """ Takes a :py:mod:`PIL.Image` and renders it to a pygame display surface. """ assert(image.size == self.size) self._last_image = image image = self.preprocess(image) self._clock.tick(self._fps) self._pygame.event.pump() if self._abort(): self._pygame.quit() sys.exit() surface = self.to_surface(image, alpha=self._contrast) if self._screen is None: self._screen = self._pygame.display.set_mode(surface.get_size()) self._screen.blit(surface, (0, 0)) self._pygame.display.flip()
python
def display(self, image): """ Takes a :py:mod:`PIL.Image` and renders it to a pygame display surface. """ assert(image.size == self.size) self._last_image = image image = self.preprocess(image) self._clock.tick(self._fps) self._pygame.event.pump() if self._abort(): self._pygame.quit() sys.exit() surface = self.to_surface(image, alpha=self._contrast) if self._screen is None: self._screen = self._pygame.display.set_mode(surface.get_size()) self._screen.blit(surface, (0, 0)) self._pygame.display.flip()
[ "def", "display", "(", "self", ",", "image", ")", ":", "assert", "(", "image", ".", "size", "==", "self", ".", "size", ")", "self", ".", "_last_image", "=", "image", "image", "=", "self", ".", "preprocess", "(", "image", ")", "self", ".", "_clock", ...
Takes a :py:mod:`PIL.Image` and renders it to a pygame display surface.
[ "Takes", "a", ":", "py", ":", "mod", ":", "PIL", ".", "Image", "and", "renders", "it", "to", "a", "pygame", "display", "surface", "." ]
ca3db028b33d17cda9247ea5189873ff0408d013
https://github.com/rm-hull/luma.emulator/blob/ca3db028b33d17cda9247ea5189873ff0408d013/luma/emulator/device.py#L193-L212
train
rm-hull/luma.emulator
luma/emulator/device.py
asciiart._char_density
def _char_density(self, c, font=ImageFont.load_default()): """ Count the number of black pixels in a rendered character. """ image = Image.new('1', font.getsize(c), color=255) draw = ImageDraw.Draw(image) draw.text((0, 0), c, fill="white", font=font) return collections.Counter(image.getdata())[0]
python
def _char_density(self, c, font=ImageFont.load_default()): """ Count the number of black pixels in a rendered character. """ image = Image.new('1', font.getsize(c), color=255) draw = ImageDraw.Draw(image) draw.text((0, 0), c, fill="white", font=font) return collections.Counter(image.getdata())[0]
[ "def", "_char_density", "(", "self", ",", "c", ",", "font", "=", "ImageFont", ".", "load_default", "(", ")", ")", ":", "image", "=", "Image", ".", "new", "(", "'1'", ",", "font", ".", "getsize", "(", "c", ")", ",", "color", "=", "255", ")", "draw...
Count the number of black pixels in a rendered character.
[ "Count", "the", "number", "of", "black", "pixels", "in", "a", "rendered", "character", "." ]
ca3db028b33d17cda9247ea5189873ff0408d013
https://github.com/rm-hull/luma.emulator/blob/ca3db028b33d17cda9247ea5189873ff0408d013/luma/emulator/device.py#L253-L260
train
rm-hull/luma.emulator
luma/emulator/device.py
asciiart._generate_art
def _generate_art(self, image, width, height): """ Return an iterator that produces the ascii art. """ # Characters aren't square, so scale the output by the aspect ratio of a charater height = int(height * self._char_width / float(self._char_height)) image = image.resize((width, height), Image.ANTIALIAS).convert("RGB") for (r, g, b) in image.getdata(): greyscale = int(0.299 * r + 0.587 * g + 0.114 * b) ch = self._chars[int(greyscale / 255. * (len(self._chars) - 1) + 0.5)] yield (ch, rgb2short(r, g, b))
python
def _generate_art(self, image, width, height): """ Return an iterator that produces the ascii art. """ # Characters aren't square, so scale the output by the aspect ratio of a charater height = int(height * self._char_width / float(self._char_height)) image = image.resize((width, height), Image.ANTIALIAS).convert("RGB") for (r, g, b) in image.getdata(): greyscale = int(0.299 * r + 0.587 * g + 0.114 * b) ch = self._chars[int(greyscale / 255. * (len(self._chars) - 1) + 0.5)] yield (ch, rgb2short(r, g, b))
[ "def", "_generate_art", "(", "self", ",", "image", ",", "width", ",", "height", ")", ":", "# Characters aren't square, so scale the output by the aspect ratio of a charater", "height", "=", "int", "(", "height", "*", "self", ".", "_char_width", "/", "float", "(", "s...
Return an iterator that produces the ascii art.
[ "Return", "an", "iterator", "that", "produces", "the", "ascii", "art", "." ]
ca3db028b33d17cda9247ea5189873ff0408d013
https://github.com/rm-hull/luma.emulator/blob/ca3db028b33d17cda9247ea5189873ff0408d013/luma/emulator/device.py#L262-L273
train
rm-hull/luma.emulator
luma/emulator/device.py
asciiart.display
def display(self, image): """ Takes a :py:mod:`PIL.Image` and renders it to the current terminal as ASCII-art. """ assert(image.size == self.size) self._last_image = image surface = self.to_surface(self.preprocess(image), alpha=self._contrast) rawbytes = self._pygame.image.tostring(surface, "RGB", False) image = Image.frombytes("RGB", surface.get_size(), rawbytes) scr_width = self._stdscr.getmaxyx()[1] scale = float(scr_width) / image.width self._stdscr.erase() self._stdscr.move(0, 0) try: for (ch, color) in self._generate_art(image, int(image.width * scale), int(image.height * scale)): self._stdscr.addstr(ch, curses.color_pair(color)) except curses.error: # End of screen reached pass self._stdscr.refresh()
python
def display(self, image): """ Takes a :py:mod:`PIL.Image` and renders it to the current terminal as ASCII-art. """ assert(image.size == self.size) self._last_image = image surface = self.to_surface(self.preprocess(image), alpha=self._contrast) rawbytes = self._pygame.image.tostring(surface, "RGB", False) image = Image.frombytes("RGB", surface.get_size(), rawbytes) scr_width = self._stdscr.getmaxyx()[1] scale = float(scr_width) / image.width self._stdscr.erase() self._stdscr.move(0, 0) try: for (ch, color) in self._generate_art(image, int(image.width * scale), int(image.height * scale)): self._stdscr.addstr(ch, curses.color_pair(color)) except curses.error: # End of screen reached pass self._stdscr.refresh()
[ "def", "display", "(", "self", ",", "image", ")", ":", "assert", "(", "image", ".", "size", "==", "self", ".", "size", ")", "self", ".", "_last_image", "=", "image", "surface", "=", "self", ".", "to_surface", "(", "self", ".", "preprocess", "(", "ima...
Takes a :py:mod:`PIL.Image` and renders it to the current terminal as ASCII-art.
[ "Takes", "a", ":", "py", ":", "mod", ":", "PIL", ".", "Image", "and", "renders", "it", "to", "the", "current", "terminal", "as", "ASCII", "-", "art", "." ]
ca3db028b33d17cda9247ea5189873ff0408d013
https://github.com/rm-hull/luma.emulator/blob/ca3db028b33d17cda9247ea5189873ff0408d013/luma/emulator/device.py#L275-L300
train
rm-hull/luma.emulator
luma/emulator/device.py
asciiblock._generate_art
def _generate_art(self, image, width, height): """ Return an iterator that produces the ascii art. """ image = image.resize((width, height), Image.ANTIALIAS).convert("RGB") pixels = list(image.getdata()) for y in range(0, height - 1, 2): for x in range(width): i = y * width + x bg = rgb2short(*(pixels[i])) fg = rgb2short(*(pixels[i + width])) yield (fg, bg)
python
def _generate_art(self, image, width, height): """ Return an iterator that produces the ascii art. """ image = image.resize((width, height), Image.ANTIALIAS).convert("RGB") pixels = list(image.getdata()) for y in range(0, height - 1, 2): for x in range(width): i = y * width + x bg = rgb2short(*(pixels[i])) fg = rgb2short(*(pixels[i + width])) yield (fg, bg)
[ "def", "_generate_art", "(", "self", ",", "image", ",", "width", ",", "height", ")", ":", "image", "=", "image", ".", "resize", "(", "(", "width", ",", "height", ")", ",", "Image", ".", "ANTIALIAS", ")", ".", "convert", "(", "\"RGB\"", ")", "pixels",...
Return an iterator that produces the ascii art.
[ "Return", "an", "iterator", "that", "produces", "the", "ascii", "art", "." ]
ca3db028b33d17cda9247ea5189873ff0408d013
https://github.com/rm-hull/luma.emulator/blob/ca3db028b33d17cda9247ea5189873ff0408d013/luma/emulator/device.py#L341-L353
train
rm-hull/luma.emulator
luma/emulator/device.py
asciiblock._CSI
def _CSI(self, cmd): """ Control sequence introducer """ sys.stdout.write('\x1b[') sys.stdout.write(cmd)
python
def _CSI(self, cmd): """ Control sequence introducer """ sys.stdout.write('\x1b[') sys.stdout.write(cmd)
[ "def", "_CSI", "(", "self", ",", "cmd", ")", ":", "sys", ".", "stdout", ".", "write", "(", "'\\x1b['", ")", "sys", ".", "stdout", ".", "write", "(", "cmd", ")" ]
Control sequence introducer
[ "Control", "sequence", "introducer" ]
ca3db028b33d17cda9247ea5189873ff0408d013
https://github.com/rm-hull/luma.emulator/blob/ca3db028b33d17cda9247ea5189873ff0408d013/luma/emulator/device.py#L355-L360
train
rm-hull/luma.emulator
luma/emulator/device.py
asciiblock.display
def display(self, image): """ Takes a :py:mod:`PIL.Image` and renders it to the current terminal as ASCII-blocks. """ assert(image.size == self.size) self._last_image = image surface = self.to_surface(self.preprocess(image), alpha=self._contrast) rawbytes = self._pygame.image.tostring(surface, "RGB", False) image = Image.frombytes("RGB", surface.get_size(), rawbytes) scr_width = self._terminal_size()[1] scale = float(scr_width) / image.width self._CSI('1;1H') # Move to top/left for (fg, bg) in self._generate_art(image, int(image.width * scale), int(image.height * scale)): self._CSI('38;5;{0};48;5;{1}m'.format(fg, bg)) sys.stdout.write('▄') self._CSI('0m') sys.stdout.flush()
python
def display(self, image): """ Takes a :py:mod:`PIL.Image` and renders it to the current terminal as ASCII-blocks. """ assert(image.size == self.size) self._last_image = image surface = self.to_surface(self.preprocess(image), alpha=self._contrast) rawbytes = self._pygame.image.tostring(surface, "RGB", False) image = Image.frombytes("RGB", surface.get_size(), rawbytes) scr_width = self._terminal_size()[1] scale = float(scr_width) / image.width self._CSI('1;1H') # Move to top/left for (fg, bg) in self._generate_art(image, int(image.width * scale), int(image.height * scale)): self._CSI('38;5;{0};48;5;{1}m'.format(fg, bg)) sys.stdout.write('▄') self._CSI('0m') sys.stdout.flush()
[ "def", "display", "(", "self", ",", "image", ")", ":", "assert", "(", "image", ".", "size", "==", "self", ".", "size", ")", "self", ".", "_last_image", "=", "image", "surface", "=", "self", ".", "to_surface", "(", "self", ".", "preprocess", "(", "ima...
Takes a :py:mod:`PIL.Image` and renders it to the current terminal as ASCII-blocks.
[ "Takes", "a", ":", "py", ":", "mod", ":", "PIL", ".", "Image", "and", "renders", "it", "to", "the", "current", "terminal", "as", "ASCII", "-", "blocks", "." ]
ca3db028b33d17cda9247ea5189873ff0408d013
https://github.com/rm-hull/luma.emulator/blob/ca3db028b33d17cda9247ea5189873ff0408d013/luma/emulator/device.py#L362-L384
train
Auzzy/1846-routes
routes1846/find_best_routes.py
chunk_sequence
def chunk_sequence(sequence, chunk_length): """Yield successive n-sized chunks from l.""" for index in range(0, len(sequence), chunk_length): yield sequence[index:index + chunk_length]
python
def chunk_sequence(sequence, chunk_length): """Yield successive n-sized chunks from l.""" for index in range(0, len(sequence), chunk_length): yield sequence[index:index + chunk_length]
[ "def", "chunk_sequence", "(", "sequence", ",", "chunk_length", ")", ":", "for", "index", "in", "range", "(", "0", ",", "len", "(", "sequence", ")", ",", "chunk_length", ")", ":", "yield", "sequence", "[", "index", ":", "index", "+", "chunk_length", "]" ]
Yield successive n-sized chunks from l.
[ "Yield", "successive", "n", "-", "sized", "chunks", "from", "l", "." ]
60c90928e184cbcc09c9fef46c2df07f5f14c2c2
https://github.com/Auzzy/1846-routes/blob/60c90928e184cbcc09c9fef46c2df07f5f14c2c2/routes1846/find_best_routes.py#L72-L75
train
Auzzy/1846-routes
routes1846/find_best_routes.py
_filter_invalid_routes
def _filter_invalid_routes(routes, board, railroad): """ Given a collection of routes, returns a new set containing only valid routes. Invalid routes removed: - contain less than 2 cities, or - go through Chicago using an impassable exit - only contain Chicago as a station, but don't use the correct exit path This fltering after the fact keeps the path finding algorithm simpler. It allows groups of 3 cells to be considered (important for the Chicago checks), which would be tricky, since the algorithm operates on pairs of cells (at the time of writing). """ chicago_space = board.get_space(CHICAGO_CELL) chicago_neighbor_cells = [cell for cell in CHICAGO_CELL.neighbors.values() if cell != CHICAGO_CONNECTIONS_CELL] stations = board.stations(railroad.name) # A sieve style filter. If a condition isn't met, iteration continues to the next item. Items meeting all conditions # are added to valid_routes at the end of the loop iteration. valid_routes = set() for route in routes: # A route must connect at least 2 cities. if len(route.cities) < 2: continue # A route cannot run from east to east if isinstance(route.cities[0], EastTerminalCity) and isinstance(route.cities[-1], EastTerminalCity): continue # If the route goes through Chicago and isn't [C5, D6], ensure the path it took either contains its station or is unblocked if route.contains_cell(CHICAGO_CONNECTIONS_CELL) and len(route.cities) != 2: # Finds the subroute which starts at Chicago and is 3 tiles long. That is, it will go [C5, D6, chicago exit] all_chicago_subroutes = [subroute for subroute in route.subroutes(CHICAGO_CONNECTIONS_CELL) if len(subroute) == 3] chicago_subroute = all_chicago_subroutes[0] if all_chicago_subroutes else None for cell in chicago_neighbor_cells: chicago_exit = chicago_subroute and chicago_subroute.contains_cell(cell) if chicago_exit and chicago_space.passable(cell, railroad): break else: continue # Each route must contain at least 1 station stations_on_route = [station for station in stations if route.contains_cell(station.cell)] if not stations_on_route: continue # If the only station is Chicago, the path must be [D6, C5], or exit through the appropriate side. elif [CHICAGO_CELL] == [station.cell for station in stations_on_route]: exit_cell = board.get_space(CHICAGO_CELL).get_station_exit_cell(stations_on_route[0]) chicago_exit_route = Route.create([chicago_space, board.get_space(exit_cell)]) if not (len(route) == 2 and route.contains_cell(CHICAGO_CONNECTIONS_CELL)) and not route.overlap(chicago_exit_route): continue valid_routes.add(route) return valid_routes
python
def _filter_invalid_routes(routes, board, railroad): """ Given a collection of routes, returns a new set containing only valid routes. Invalid routes removed: - contain less than 2 cities, or - go through Chicago using an impassable exit - only contain Chicago as a station, but don't use the correct exit path This fltering after the fact keeps the path finding algorithm simpler. It allows groups of 3 cells to be considered (important for the Chicago checks), which would be tricky, since the algorithm operates on pairs of cells (at the time of writing). """ chicago_space = board.get_space(CHICAGO_CELL) chicago_neighbor_cells = [cell for cell in CHICAGO_CELL.neighbors.values() if cell != CHICAGO_CONNECTIONS_CELL] stations = board.stations(railroad.name) # A sieve style filter. If a condition isn't met, iteration continues to the next item. Items meeting all conditions # are added to valid_routes at the end of the loop iteration. valid_routes = set() for route in routes: # A route must connect at least 2 cities. if len(route.cities) < 2: continue # A route cannot run from east to east if isinstance(route.cities[0], EastTerminalCity) and isinstance(route.cities[-1], EastTerminalCity): continue # If the route goes through Chicago and isn't [C5, D6], ensure the path it took either contains its station or is unblocked if route.contains_cell(CHICAGO_CONNECTIONS_CELL) and len(route.cities) != 2: # Finds the subroute which starts at Chicago and is 3 tiles long. That is, it will go [C5, D6, chicago exit] all_chicago_subroutes = [subroute for subroute in route.subroutes(CHICAGO_CONNECTIONS_CELL) if len(subroute) == 3] chicago_subroute = all_chicago_subroutes[0] if all_chicago_subroutes else None for cell in chicago_neighbor_cells: chicago_exit = chicago_subroute and chicago_subroute.contains_cell(cell) if chicago_exit and chicago_space.passable(cell, railroad): break else: continue # Each route must contain at least 1 station stations_on_route = [station for station in stations if route.contains_cell(station.cell)] if not stations_on_route: continue # If the only station is Chicago, the path must be [D6, C5], or exit through the appropriate side. elif [CHICAGO_CELL] == [station.cell for station in stations_on_route]: exit_cell = board.get_space(CHICAGO_CELL).get_station_exit_cell(stations_on_route[0]) chicago_exit_route = Route.create([chicago_space, board.get_space(exit_cell)]) if not (len(route) == 2 and route.contains_cell(CHICAGO_CONNECTIONS_CELL)) and not route.overlap(chicago_exit_route): continue valid_routes.add(route) return valid_routes
[ "def", "_filter_invalid_routes", "(", "routes", ",", "board", ",", "railroad", ")", ":", "chicago_space", "=", "board", ".", "get_space", "(", "CHICAGO_CELL", ")", "chicago_neighbor_cells", "=", "[", "cell", "for", "cell", "in", "CHICAGO_CELL", ".", "neighbors",...
Given a collection of routes, returns a new set containing only valid routes. Invalid routes removed: - contain less than 2 cities, or - go through Chicago using an impassable exit - only contain Chicago as a station, but don't use the correct exit path This fltering after the fact keeps the path finding algorithm simpler. It allows groups of 3 cells to be considered (important for the Chicago checks), which would be tricky, since the algorithm operates on pairs of cells (at the time of writing).
[ "Given", "a", "collection", "of", "routes", "returns", "a", "new", "set", "containing", "only", "valid", "routes", ".", "Invalid", "routes", "removed", ":", "-", "contain", "less", "than", "2", "cities", "or", "-", "go", "through", "Chicago", "using", "an"...
60c90928e184cbcc09c9fef46c2df07f5f14c2c2
https://github.com/Auzzy/1846-routes/blob/60c90928e184cbcc09c9fef46c2df07f5f14c2c2/routes1846/find_best_routes.py#L171-L224
train
MacHu-GWU/loggerFactory-project
loggerFactory/logfilter.py
find
def find(path, level=None, message=None, time_lower=None, time_upper=None, case_sensitive=False): # pragma: no cover """ Filter log message. **中文文档** 根据level名称, message中的关键字, 和log的时间的区间, 筛选出相关的日志 """ if level: level = level.upper() # level name has to be capitalized. if not case_sensitive: message = message.lower() with open(path, "r") as f: result = Result(path=path, level=level, message=message, time_lower=time_lower, time_upper=time_upper, case_sensitive=case_sensitive, ) for line in f: try: _time, _level, _message = [i.strip() for i in line.split(";")] if level: if _level != level: continue if time_lower: if _time < time_lower: continue if time_upper: if _time > time_upper: continue if message: if not case_sensitive: _message = _message.lower() if message not in _message: continue result.lines.append(line) except Exception as e: print(e) return result
python
def find(path, level=None, message=None, time_lower=None, time_upper=None, case_sensitive=False): # pragma: no cover """ Filter log message. **中文文档** 根据level名称, message中的关键字, 和log的时间的区间, 筛选出相关的日志 """ if level: level = level.upper() # level name has to be capitalized. if not case_sensitive: message = message.lower() with open(path, "r") as f: result = Result(path=path, level=level, message=message, time_lower=time_lower, time_upper=time_upper, case_sensitive=case_sensitive, ) for line in f: try: _time, _level, _message = [i.strip() for i in line.split(";")] if level: if _level != level: continue if time_lower: if _time < time_lower: continue if time_upper: if _time > time_upper: continue if message: if not case_sensitive: _message = _message.lower() if message not in _message: continue result.lines.append(line) except Exception as e: print(e) return result
[ "def", "find", "(", "path", ",", "level", "=", "None", ",", "message", "=", "None", ",", "time_lower", "=", "None", ",", "time_upper", "=", "None", ",", "case_sensitive", "=", "False", ")", ":", "# pragma: no cover", "if", "level", ":", "level", "=", "...
Filter log message. **中文文档** 根据level名称, message中的关键字, 和log的时间的区间, 筛选出相关的日志
[ "Filter", "log", "message", "." ]
4de19e275e01dc583b1af9ceeacef0c6084cd6e0
https://github.com/MacHu-GWU/loggerFactory-project/blob/4de19e275e01dc583b1af9ceeacef0c6084cd6e0/loggerFactory/logfilter.py#L49-L101
train
MacHu-GWU/loggerFactory-project
loggerFactory/logger.py
get_logger_by_name
def get_logger_by_name(name=None, rand_name=False, charset=Charset.HEX): """ Get a logger by name. :param name: None / str, logger name. :param rand_name: if True, ``name`` will be ignored, a random name will be used. """ if rand_name: name = rand_str(charset) logger = logging.getLogger(name) return logger
python
def get_logger_by_name(name=None, rand_name=False, charset=Charset.HEX): """ Get a logger by name. :param name: None / str, logger name. :param rand_name: if True, ``name`` will be ignored, a random name will be used. """ if rand_name: name = rand_str(charset) logger = logging.getLogger(name) return logger
[ "def", "get_logger_by_name", "(", "name", "=", "None", ",", "rand_name", "=", "False", ",", "charset", "=", "Charset", ".", "HEX", ")", ":", "if", "rand_name", ":", "name", "=", "rand_str", "(", "charset", ")", "logger", "=", "logging", ".", "getLogger",...
Get a logger by name. :param name: None / str, logger name. :param rand_name: if True, ``name`` will be ignored, a random name will be used.
[ "Get", "a", "logger", "by", "name", "." ]
4de19e275e01dc583b1af9ceeacef0c6084cd6e0
https://github.com/MacHu-GWU/loggerFactory-project/blob/4de19e275e01dc583b1af9ceeacef0c6084cd6e0/loggerFactory/logger.py#L17-L27
train
MacHu-GWU/loggerFactory-project
loggerFactory/logger.py
BaseLogger.debug
def debug(self, msg, indent=0, **kwargs): """invoke ``self.logger.debug``""" return self.logger.debug(self._indent(msg, indent), **kwargs)
python
def debug(self, msg, indent=0, **kwargs): """invoke ``self.logger.debug``""" return self.logger.debug(self._indent(msg, indent), **kwargs)
[ "def", "debug", "(", "self", ",", "msg", ",", "indent", "=", "0", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "logger", ".", "debug", "(", "self", ".", "_indent", "(", "msg", ",", "indent", ")", ",", "*", "*", "kwargs", ")" ]
invoke ``self.logger.debug``
[ "invoke", "self", ".", "logger", ".", "debug" ]
4de19e275e01dc583b1af9ceeacef0c6084cd6e0
https://github.com/MacHu-GWU/loggerFactory-project/blob/4de19e275e01dc583b1af9ceeacef0c6084cd6e0/loggerFactory/logger.py#L59-L61
train
MacHu-GWU/loggerFactory-project
loggerFactory/logger.py
BaseLogger.info
def info(self, msg, indent=0, **kwargs): """invoke ``self.info.debug``""" return self.logger.info(self._indent(msg, indent), **kwargs)
python
def info(self, msg, indent=0, **kwargs): """invoke ``self.info.debug``""" return self.logger.info(self._indent(msg, indent), **kwargs)
[ "def", "info", "(", "self", ",", "msg", ",", "indent", "=", "0", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "logger", ".", "info", "(", "self", ".", "_indent", "(", "msg", ",", "indent", ")", ",", "*", "*", "kwargs", ")" ]
invoke ``self.info.debug``
[ "invoke", "self", ".", "info", ".", "debug" ]
4de19e275e01dc583b1af9ceeacef0c6084cd6e0
https://github.com/MacHu-GWU/loggerFactory-project/blob/4de19e275e01dc583b1af9ceeacef0c6084cd6e0/loggerFactory/logger.py#L63-L65
train
MacHu-GWU/loggerFactory-project
loggerFactory/logger.py
BaseLogger.warning
def warning(self, msg, indent=0, **kwargs): """invoke ``self.logger.warning``""" return self.logger.warning(self._indent(msg, indent), **kwargs)
python
def warning(self, msg, indent=0, **kwargs): """invoke ``self.logger.warning``""" return self.logger.warning(self._indent(msg, indent), **kwargs)
[ "def", "warning", "(", "self", ",", "msg", ",", "indent", "=", "0", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "logger", ".", "warning", "(", "self", ".", "_indent", "(", "msg", ",", "indent", ")", ",", "*", "*", "kwargs", ")" ]
invoke ``self.logger.warning``
[ "invoke", "self", ".", "logger", ".", "warning" ]
4de19e275e01dc583b1af9ceeacef0c6084cd6e0
https://github.com/MacHu-GWU/loggerFactory-project/blob/4de19e275e01dc583b1af9ceeacef0c6084cd6e0/loggerFactory/logger.py#L67-L69
train
MacHu-GWU/loggerFactory-project
loggerFactory/logger.py
BaseLogger.error
def error(self, msg, indent=0, **kwargs): """invoke ``self.logger.error``""" return self.logger.error(self._indent(msg, indent), **kwargs)
python
def error(self, msg, indent=0, **kwargs): """invoke ``self.logger.error``""" return self.logger.error(self._indent(msg, indent), **kwargs)
[ "def", "error", "(", "self", ",", "msg", ",", "indent", "=", "0", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "logger", ".", "error", "(", "self", ".", "_indent", "(", "msg", ",", "indent", ")", ",", "*", "*", "kwargs", ")" ]
invoke ``self.logger.error``
[ "invoke", "self", ".", "logger", ".", "error" ]
4de19e275e01dc583b1af9ceeacef0c6084cd6e0
https://github.com/MacHu-GWU/loggerFactory-project/blob/4de19e275e01dc583b1af9ceeacef0c6084cd6e0/loggerFactory/logger.py#L71-L73
train
MacHu-GWU/loggerFactory-project
loggerFactory/logger.py
BaseLogger.critical
def critical(self, msg, indent=0, **kwargs): """invoke ``self.logger.critical``""" return self.logger.critical(self._indent(msg, indent), **kwargs)
python
def critical(self, msg, indent=0, **kwargs): """invoke ``self.logger.critical``""" return self.logger.critical(self._indent(msg, indent), **kwargs)
[ "def", "critical", "(", "self", ",", "msg", ",", "indent", "=", "0", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "logger", ".", "critical", "(", "self", ".", "_indent", "(", "msg", ",", "indent", ")", ",", "*", "*", "kwargs", ")" ]
invoke ``self.logger.critical``
[ "invoke", "self", ".", "logger", ".", "critical" ]
4de19e275e01dc583b1af9ceeacef0c6084cd6e0
https://github.com/MacHu-GWU/loggerFactory-project/blob/4de19e275e01dc583b1af9ceeacef0c6084cd6e0/loggerFactory/logger.py#L75-L77
train
MacHu-GWU/loggerFactory-project
loggerFactory/logger.py
BaseLogger.show
def show(self, msg, indent=0, style="", **kwargs): """ Print message to console, indent format may apply. """ if self.enable_verbose: new_msg = self.MessageTemplate.with_style.format( indent=self.tab * indent, style=style, msg=msg, ) print(new_msg, **kwargs)
python
def show(self, msg, indent=0, style="", **kwargs): """ Print message to console, indent format may apply. """ if self.enable_verbose: new_msg = self.MessageTemplate.with_style.format( indent=self.tab * indent, style=style, msg=msg, ) print(new_msg, **kwargs)
[ "def", "show", "(", "self", ",", "msg", ",", "indent", "=", "0", ",", "style", "=", "\"\"", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "enable_verbose", ":", "new_msg", "=", "self", ".", "MessageTemplate", ".", "with_style", ".", "format",...
Print message to console, indent format may apply.
[ "Print", "message", "to", "console", "indent", "format", "may", "apply", "." ]
4de19e275e01dc583b1af9ceeacef0c6084cd6e0
https://github.com/MacHu-GWU/loggerFactory-project/blob/4de19e275e01dc583b1af9ceeacef0c6084cd6e0/loggerFactory/logger.py#L79-L89
train
MacHu-GWU/loggerFactory-project
loggerFactory/logger.py
BaseLogger.remove_all_handler
def remove_all_handler(self): """ Unlink the file handler association. """ for handler in self.logger.handlers[:]: self.logger.removeHandler(handler) self._handler_cache.append(handler)
python
def remove_all_handler(self): """ Unlink the file handler association. """ for handler in self.logger.handlers[:]: self.logger.removeHandler(handler) self._handler_cache.append(handler)
[ "def", "remove_all_handler", "(", "self", ")", ":", "for", "handler", "in", "self", ".", "logger", ".", "handlers", "[", ":", "]", ":", "self", ".", "logger", ".", "removeHandler", "(", "handler", ")", "self", ".", "_handler_cache", ".", "append", "(", ...
Unlink the file handler association.
[ "Unlink", "the", "file", "handler", "association", "." ]
4de19e275e01dc583b1af9ceeacef0c6084cd6e0
https://github.com/MacHu-GWU/loggerFactory-project/blob/4de19e275e01dc583b1af9ceeacef0c6084cd6e0/loggerFactory/logger.py#L111-L117
train
MacHu-GWU/loggerFactory-project
loggerFactory/logger.py
BaseLogger.recover_all_handler
def recover_all_handler(self): """ Relink the file handler association you just removed. """ for handler in self._handler_cache: self.logger.addHandler(handler) self._handler_cache = list()
python
def recover_all_handler(self): """ Relink the file handler association you just removed. """ for handler in self._handler_cache: self.logger.addHandler(handler) self._handler_cache = list()
[ "def", "recover_all_handler", "(", "self", ")", ":", "for", "handler", "in", "self", ".", "_handler_cache", ":", "self", ".", "logger", ".", "addHandler", "(", "handler", ")", "self", ".", "_handler_cache", "=", "list", "(", ")" ]
Relink the file handler association you just removed.
[ "Relink", "the", "file", "handler", "association", "you", "just", "removed", "." ]
4de19e275e01dc583b1af9ceeacef0c6084cd6e0
https://github.com/MacHu-GWU/loggerFactory-project/blob/4de19e275e01dc583b1af9ceeacef0c6084cd6e0/loggerFactory/logger.py#L119-L125
train
IceflowRE/unidown
unidown/plugin/link_item.py
LinkItem.from_protobuf
def from_protobuf(cls, proto: LinkItemProto) -> LinkItem: """ Constructor from protobuf. :param proto: protobuf structure :type proto: ~unidown.plugin.protobuf.link_item_pb2.LinkItemProto :return: the LinkItem :rtype: ~unidown.plugin.link_item.LinkItem :raises ValueError: name of LinkItem does not exist inside the protobuf or is empty """ if proto.name == '': raise ValueError("name of LinkItem does not exist or is empty inside the protobuf.") return cls(proto.name, Timestamp.ToDatetime(proto.time))
python
def from_protobuf(cls, proto: LinkItemProto) -> LinkItem: """ Constructor from protobuf. :param proto: protobuf structure :type proto: ~unidown.plugin.protobuf.link_item_pb2.LinkItemProto :return: the LinkItem :rtype: ~unidown.plugin.link_item.LinkItem :raises ValueError: name of LinkItem does not exist inside the protobuf or is empty """ if proto.name == '': raise ValueError("name of LinkItem does not exist or is empty inside the protobuf.") return cls(proto.name, Timestamp.ToDatetime(proto.time))
[ "def", "from_protobuf", "(", "cls", ",", "proto", ":", "LinkItemProto", ")", "->", "LinkItem", ":", "if", "proto", ".", "name", "==", "''", ":", "raise", "ValueError", "(", "\"name of LinkItem does not exist or is empty inside the protobuf.\"", ")", "return", "cls",...
Constructor from protobuf. :param proto: protobuf structure :type proto: ~unidown.plugin.protobuf.link_item_pb2.LinkItemProto :return: the LinkItem :rtype: ~unidown.plugin.link_item.LinkItem :raises ValueError: name of LinkItem does not exist inside the protobuf or is empty
[ "Constructor", "from", "protobuf", "." ]
2a6f82ab780bb825668bfc55b67c11c4f72ec05c
https://github.com/IceflowRE/unidown/blob/2a6f82ab780bb825668bfc55b67c11c4f72ec05c/unidown/plugin/link_item.py#L37-L49
train
IceflowRE/unidown
unidown/plugin/link_item.py
LinkItem.to_protobuf
def to_protobuf(self) -> LinkItemProto: """ Create protobuf item. :return: protobuf structure :rtype: ~unidown.plugin.protobuf.link_item_pb2.LinkItemProto """ result = LinkItemProto() result.name = self._name result.time.CopyFrom(datetime_to_timestamp(self._time)) return result
python
def to_protobuf(self) -> LinkItemProto: """ Create protobuf item. :return: protobuf structure :rtype: ~unidown.plugin.protobuf.link_item_pb2.LinkItemProto """ result = LinkItemProto() result.name = self._name result.time.CopyFrom(datetime_to_timestamp(self._time)) return result
[ "def", "to_protobuf", "(", "self", ")", "->", "LinkItemProto", ":", "result", "=", "LinkItemProto", "(", ")", "result", ".", "name", "=", "self", ".", "_name", "result", ".", "time", ".", "CopyFrom", "(", "datetime_to_timestamp", "(", "self", ".", "_time",...
Create protobuf item. :return: protobuf structure :rtype: ~unidown.plugin.protobuf.link_item_pb2.LinkItemProto
[ "Create", "protobuf", "item", "." ]
2a6f82ab780bb825668bfc55b67c11c4f72ec05c
https://github.com/IceflowRE/unidown/blob/2a6f82ab780bb825668bfc55b67c11c4f72ec05c/unidown/plugin/link_item.py#L70-L80
train
HiPERCAM/hcam_widgets
hcam_widgets/logs.py
Logger.update
def update(self, fname): """ Adds a handler to save to a file. Includes debug stuff. """ ltfh = FileHandler(fname) self._log.addHandler(ltfh)
python
def update(self, fname): """ Adds a handler to save to a file. Includes debug stuff. """ ltfh = FileHandler(fname) self._log.addHandler(ltfh)
[ "def", "update", "(", "self", ",", "fname", ")", ":", "ltfh", "=", "FileHandler", "(", "fname", ")", "self", ".", "_log", ".", "addHandler", "(", "ltfh", ")" ]
Adds a handler to save to a file. Includes debug stuff.
[ "Adds", "a", "handler", "to", "save", "to", "a", "file", ".", "Includes", "debug", "stuff", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/logs.py#L117-L122
train
IceflowRE/unidown
unidown/tools.py
delete_dir_rec
def delete_dir_rec(path: Path): """ Delete a folder recursive. :param path: folder to deleted :type path: ~pathlib.Path """ if not path.exists() or not path.is_dir(): return for sub in path.iterdir(): if sub.is_dir(): delete_dir_rec(sub) else: sub.unlink() path.rmdir()
python
def delete_dir_rec(path: Path): """ Delete a folder recursive. :param path: folder to deleted :type path: ~pathlib.Path """ if not path.exists() or not path.is_dir(): return for sub in path.iterdir(): if sub.is_dir(): delete_dir_rec(sub) else: sub.unlink() path.rmdir()
[ "def", "delete_dir_rec", "(", "path", ":", "Path", ")", ":", "if", "not", "path", ".", "exists", "(", ")", "or", "not", "path", ".", "is_dir", "(", ")", ":", "return", "for", "sub", "in", "path", ".", "iterdir", "(", ")", ":", "if", "sub", ".", ...
Delete a folder recursive. :param path: folder to deleted :type path: ~pathlib.Path
[ "Delete", "a", "folder", "recursive", "." ]
2a6f82ab780bb825668bfc55b67c11c4f72ec05c
https://github.com/IceflowRE/unidown/blob/2a6f82ab780bb825668bfc55b67c11c4f72ec05c/unidown/tools.py#L13-L27
train
IceflowRE/unidown
unidown/tools.py
create_dir_rec
def create_dir_rec(path: Path): """ Create a folder recursive. :param path: path :type path: ~pathlib.Path """ if not path.exists(): Path.mkdir(path, parents=True, exist_ok=True)
python
def create_dir_rec(path: Path): """ Create a folder recursive. :param path: path :type path: ~pathlib.Path """ if not path.exists(): Path.mkdir(path, parents=True, exist_ok=True)
[ "def", "create_dir_rec", "(", "path", ":", "Path", ")", ":", "if", "not", "path", ".", "exists", "(", ")", ":", "Path", ".", "mkdir", "(", "path", ",", "parents", "=", "True", ",", "exist_ok", "=", "True", ")" ]
Create a folder recursive. :param path: path :type path: ~pathlib.Path
[ "Create", "a", "folder", "recursive", "." ]
2a6f82ab780bb825668bfc55b67c11c4f72ec05c
https://github.com/IceflowRE/unidown/blob/2a6f82ab780bb825668bfc55b67c11c4f72ec05c/unidown/tools.py#L30-L38
train
IceflowRE/unidown
unidown/tools.py
datetime_to_timestamp
def datetime_to_timestamp(time: datetime) -> Timestamp: """ Convert datetime to protobuf.timestamp. :param time: time :type time: ~datetime.datetime :return: protobuf.timestamp :rtype: ~google.protobuf.timestamp_pb2.Timestamp """ protime = Timestamp() protime.FromDatetime(time) return protime
python
def datetime_to_timestamp(time: datetime) -> Timestamp: """ Convert datetime to protobuf.timestamp. :param time: time :type time: ~datetime.datetime :return: protobuf.timestamp :rtype: ~google.protobuf.timestamp_pb2.Timestamp """ protime = Timestamp() protime.FromDatetime(time) return protime
[ "def", "datetime_to_timestamp", "(", "time", ":", "datetime", ")", "->", "Timestamp", ":", "protime", "=", "Timestamp", "(", ")", "protime", ".", "FromDatetime", "(", "time", ")", "return", "protime" ]
Convert datetime to protobuf.timestamp. :param time: time :type time: ~datetime.datetime :return: protobuf.timestamp :rtype: ~google.protobuf.timestamp_pb2.Timestamp
[ "Convert", "datetime", "to", "protobuf", ".", "timestamp", "." ]
2a6f82ab780bb825668bfc55b67c11c4f72ec05c
https://github.com/IceflowRE/unidown/blob/2a6f82ab780bb825668bfc55b67c11c4f72ec05c/unidown/tools.py#L41-L52
train
IceflowRE/unidown
unidown/tools.py
print_plugin_list
def print_plugin_list(plugins: Dict[str, pkg_resources.EntryPoint]): """ Prints all registered plugins and checks if they can be loaded or not. :param plugins: plugins :type plugins: Dict[str, ~pkg_resources.EntryPoint] """ for trigger, entry_point in plugins.items(): try: plugin_class = entry_point.load() version = str(plugin_class._info.version) print( f"{trigger} (ok)\n" f" {version}" ) except Exception: print( f"{trigger} (failed)" )
python
def print_plugin_list(plugins: Dict[str, pkg_resources.EntryPoint]): """ Prints all registered plugins and checks if they can be loaded or not. :param plugins: plugins :type plugins: Dict[str, ~pkg_resources.EntryPoint] """ for trigger, entry_point in plugins.items(): try: plugin_class = entry_point.load() version = str(plugin_class._info.version) print( f"{trigger} (ok)\n" f" {version}" ) except Exception: print( f"{trigger} (failed)" )
[ "def", "print_plugin_list", "(", "plugins", ":", "Dict", "[", "str", ",", "pkg_resources", ".", "EntryPoint", "]", ")", ":", "for", "trigger", ",", "entry_point", "in", "plugins", ".", "items", "(", ")", ":", "try", ":", "plugin_class", "=", "entry_point",...
Prints all registered plugins and checks if they can be loaded or not. :param plugins: plugins :type plugins: Dict[str, ~pkg_resources.EntryPoint]
[ "Prints", "all", "registered", "plugins", "and", "checks", "if", "they", "can", "be", "loaded", "or", "not", "." ]
2a6f82ab780bb825668bfc55b67c11c4f72ec05c
https://github.com/IceflowRE/unidown/blob/2a6f82ab780bb825668bfc55b67c11c4f72ec05c/unidown/tools.py#L55-L73
train
HiPERCAM/hcam_widgets
hcam_widgets/misc.py
overlap
def overlap(xl1, yl1, nx1, ny1, xl2, yl2, nx2, ny2): """ Determines whether two windows overlap """ return (xl2 < xl1+nx1 and xl2+nx2 > xl1 and yl2 < yl1+ny1 and yl2+ny2 > yl1)
python
def overlap(xl1, yl1, nx1, ny1, xl2, yl2, nx2, ny2): """ Determines whether two windows overlap """ return (xl2 < xl1+nx1 and xl2+nx2 > xl1 and yl2 < yl1+ny1 and yl2+ny2 > yl1)
[ "def", "overlap", "(", "xl1", ",", "yl1", ",", "nx1", ",", "ny1", ",", "xl2", ",", "yl2", ",", "nx2", ",", "ny2", ")", ":", "return", "(", "xl2", "<", "xl1", "+", "nx1", "and", "xl2", "+", "nx2", ">", "xl1", "and", "yl2", "<", "yl1", "+", "...
Determines whether two windows overlap
[ "Determines", "whether", "two", "windows", "overlap" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/misc.py#L140-L145
train
HiPERCAM/hcam_widgets
hcam_widgets/misc.py
saveJSON
def saveJSON(g, data, backup=False): """ Saves the current setup to disk. g : hcam_drivers.globals.Container Container with globals data : dict The current setup in JSON compatible dictionary format. backup : bool If we are saving a backup on close, don't prompt for filename """ if not backup: fname = filedialog.asksaveasfilename( defaultextension='.json', filetypes=[('json files', '.json'), ], initialdir=g.cpars['app_directory'] ) else: fname = os.path.join(os.path.expanduser('~/.hdriver'), 'app.json') if not fname: g.clog.warn('Aborted save to disk') return False with open(fname, 'w') as of: of.write( json.dumps(data, sort_keys=True, indent=4, separators=(',', ': ')) ) g.clog.info('Saved setup to' + fname) return True
python
def saveJSON(g, data, backup=False): """ Saves the current setup to disk. g : hcam_drivers.globals.Container Container with globals data : dict The current setup in JSON compatible dictionary format. backup : bool If we are saving a backup on close, don't prompt for filename """ if not backup: fname = filedialog.asksaveasfilename( defaultextension='.json', filetypes=[('json files', '.json'), ], initialdir=g.cpars['app_directory'] ) else: fname = os.path.join(os.path.expanduser('~/.hdriver'), 'app.json') if not fname: g.clog.warn('Aborted save to disk') return False with open(fname, 'w') as of: of.write( json.dumps(data, sort_keys=True, indent=4, separators=(',', ': ')) ) g.clog.info('Saved setup to' + fname) return True
[ "def", "saveJSON", "(", "g", ",", "data", ",", "backup", "=", "False", ")", ":", "if", "not", "backup", ":", "fname", "=", "filedialog", ".", "asksaveasfilename", "(", "defaultextension", "=", "'.json'", ",", "filetypes", "=", "[", "(", "'json files'", "...
Saves the current setup to disk. g : hcam_drivers.globals.Container Container with globals data : dict The current setup in JSON compatible dictionary format. backup : bool If we are saving a backup on close, don't prompt for filename
[ "Saves", "the", "current", "setup", "to", "disk", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/misc.py#L195-L227
train
HiPERCAM/hcam_widgets
hcam_widgets/misc.py
postJSON
def postJSON(g, data): """ Posts the current setup to the camera and data servers. g : hcam_drivers.globals.Container Container with globals data : dict The current setup in JSON compatible dictionary format. """ g.clog.debug('Entering postJSON') # encode data as json json_data = json.dumps(data).encode('utf-8') # Send the xml to the server url = urllib.parse.urljoin(g.cpars['hipercam_server'], g.SERVER_POST_PATH) g.clog.debug('Server URL = ' + url) opener = urllib.request.build_opener() g.clog.debug('content length = ' + str(len(json_data))) req = urllib.request.Request(url, data=json_data, headers={'Content-type': 'application/json'}) response = opener.open(req, timeout=15).read() g.rlog.debug('Server response: ' + response.decode()) csr = ReadServer(response, status_msg=False) if not csr.ok: g.clog.warn('Server response was not OK') g.rlog.warn('postJSON response: ' + response.decode()) g.clog.warn('Server error = ' + csr.err) return False # now try to setup nodding server if appropriate if g.cpars['telins_name'] == 'GTC': url = urllib.parse.urljoin(g.cpars['gtc_offset_server'], 'setup') g.clog.debug('Offset Server URL = ' + url) opener = urllib.request.build_opener() try: req = urllib.request.Request(url, data=json_data, headers={'Content-type': 'application/json'}) response = opener.open(req, timeout=5).read().decode() except Exception as err: g.clog.warn('Could not communicate with GTC offsetter') g.clog.warn(str(err)) return False g.rlog.info('Offset Server Response: ' + response) if not json.loads(response)['status'] == 'OK': g.clog.warn('Offset Server response was not OK') return False g.clog.debug('Leaving postJSON') return True
python
def postJSON(g, data): """ Posts the current setup to the camera and data servers. g : hcam_drivers.globals.Container Container with globals data : dict The current setup in JSON compatible dictionary format. """ g.clog.debug('Entering postJSON') # encode data as json json_data = json.dumps(data).encode('utf-8') # Send the xml to the server url = urllib.parse.urljoin(g.cpars['hipercam_server'], g.SERVER_POST_PATH) g.clog.debug('Server URL = ' + url) opener = urllib.request.build_opener() g.clog.debug('content length = ' + str(len(json_data))) req = urllib.request.Request(url, data=json_data, headers={'Content-type': 'application/json'}) response = opener.open(req, timeout=15).read() g.rlog.debug('Server response: ' + response.decode()) csr = ReadServer(response, status_msg=False) if not csr.ok: g.clog.warn('Server response was not OK') g.rlog.warn('postJSON response: ' + response.decode()) g.clog.warn('Server error = ' + csr.err) return False # now try to setup nodding server if appropriate if g.cpars['telins_name'] == 'GTC': url = urllib.parse.urljoin(g.cpars['gtc_offset_server'], 'setup') g.clog.debug('Offset Server URL = ' + url) opener = urllib.request.build_opener() try: req = urllib.request.Request(url, data=json_data, headers={'Content-type': 'application/json'}) response = opener.open(req, timeout=5).read().decode() except Exception as err: g.clog.warn('Could not communicate with GTC offsetter') g.clog.warn(str(err)) return False g.rlog.info('Offset Server Response: ' + response) if not json.loads(response)['status'] == 'OK': g.clog.warn('Offset Server response was not OK') return False g.clog.debug('Leaving postJSON') return True
[ "def", "postJSON", "(", "g", ",", "data", ")", ":", "g", ".", "clog", ".", "debug", "(", "'Entering postJSON'", ")", "# encode data as json", "json_data", "=", "json", ".", "dumps", "(", "data", ")", ".", "encode", "(", "'utf-8'", ")", "# Send the xml to t...
Posts the current setup to the camera and data servers. g : hcam_drivers.globals.Container Container with globals data : dict The current setup in JSON compatible dictionary format.
[ "Posts", "the", "current", "setup", "to", "the", "camera", "and", "data", "servers", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/misc.py#L230-L280
train
HiPERCAM/hcam_widgets
hcam_widgets/misc.py
createJSON
def createJSON(g, full=True): """ Create JSON compatible dictionary from current settings Parameters ---------- g : hcam_drivers.globals.Container Container with globals """ data = dict() if 'gps_attached' not in g.cpars: data['gps_attached'] = 1 else: data['gps_attached'] = 1 if g.cpars['gps_attached'] else 0 data['appdata'] = g.ipars.dumpJSON() data['user'] = g.rpars.dumpJSON() if full: data['hardware'] = g.ccd_hw.dumpJSON() data['tcs'] = g.info.dumpJSON() if g.cpars['telins_name'].lower() == 'gtc' and has_corba: try: s = get_telescope_server() data['gtc_headers'] = dict( create_header_from_telpars(s.getTelescopeParams()) ) except: g.clog.warn('cannot get GTC headers from telescope server') return data
python
def createJSON(g, full=True): """ Create JSON compatible dictionary from current settings Parameters ---------- g : hcam_drivers.globals.Container Container with globals """ data = dict() if 'gps_attached' not in g.cpars: data['gps_attached'] = 1 else: data['gps_attached'] = 1 if g.cpars['gps_attached'] else 0 data['appdata'] = g.ipars.dumpJSON() data['user'] = g.rpars.dumpJSON() if full: data['hardware'] = g.ccd_hw.dumpJSON() data['tcs'] = g.info.dumpJSON() if g.cpars['telins_name'].lower() == 'gtc' and has_corba: try: s = get_telescope_server() data['gtc_headers'] = dict( create_header_from_telpars(s.getTelescopeParams()) ) except: g.clog.warn('cannot get GTC headers from telescope server') return data
[ "def", "createJSON", "(", "g", ",", "full", "=", "True", ")", ":", "data", "=", "dict", "(", ")", "if", "'gps_attached'", "not", "in", "g", ".", "cpars", ":", "data", "[", "'gps_attached'", "]", "=", "1", "else", ":", "data", "[", "'gps_attached'", ...
Create JSON compatible dictionary from current settings Parameters ---------- g : hcam_drivers.globals.Container Container with globals
[ "Create", "JSON", "compatible", "dictionary", "from", "current", "settings" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/misc.py#L283-L311
train
HiPERCAM/hcam_widgets
hcam_widgets/misc.py
insertFITSHDU
def insertFITSHDU(g): """ Uploads a table of TCS data to the servers, which is appended onto a run. Arguments --------- g : hcam_drivers.globals.Container the Container object of application globals """ if not g.cpars['hcam_server_on']: g.clog.warn('insertFITSHDU: servers are not active') return False run_number = getRunNumber(g) tcs_table = g.info.tcs_table g.clog.info('Adding TCS table data to run{:04d}.fits'.format(run_number)) url = g.cpars['hipercam_server'] + 'addhdu' try: fd = StringIO() ascii.write(tcs_table, format='ecsv', output=fd) files = {'file': fd.getvalue()} r = requests.post(url, data={'run': 'run{:04d}.fits'.format(run_number)}, files=files) fd.close() rs = ReadServer(r.content, status_msg=False) if rs.ok: g.clog.info('Response from server was OK') return True else: g.clog.warn('Response from server was not OK') g.clog.warn('Reason: ' + rs.err) return False except Exception as err: g.clog.warn('insertFITSHDU failed') g.clog.warn(str(err))
python
def insertFITSHDU(g): """ Uploads a table of TCS data to the servers, which is appended onto a run. Arguments --------- g : hcam_drivers.globals.Container the Container object of application globals """ if not g.cpars['hcam_server_on']: g.clog.warn('insertFITSHDU: servers are not active') return False run_number = getRunNumber(g) tcs_table = g.info.tcs_table g.clog.info('Adding TCS table data to run{:04d}.fits'.format(run_number)) url = g.cpars['hipercam_server'] + 'addhdu' try: fd = StringIO() ascii.write(tcs_table, format='ecsv', output=fd) files = {'file': fd.getvalue()} r = requests.post(url, data={'run': 'run{:04d}.fits'.format(run_number)}, files=files) fd.close() rs = ReadServer(r.content, status_msg=False) if rs.ok: g.clog.info('Response from server was OK') return True else: g.clog.warn('Response from server was not OK') g.clog.warn('Reason: ' + rs.err) return False except Exception as err: g.clog.warn('insertFITSHDU failed') g.clog.warn(str(err))
[ "def", "insertFITSHDU", "(", "g", ")", ":", "if", "not", "g", ".", "cpars", "[", "'hcam_server_on'", "]", ":", "g", ".", "clog", ".", "warn", "(", "'insertFITSHDU: servers are not active'", ")", "return", "False", "run_number", "=", "getRunNumber", "(", "g",...
Uploads a table of TCS data to the servers, which is appended onto a run. Arguments --------- g : hcam_drivers.globals.Container the Container object of application globals
[ "Uploads", "a", "table", "of", "TCS", "data", "to", "the", "servers", "which", "is", "appended", "onto", "a", "run", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/misc.py#L395-L430
train
HiPERCAM/hcam_widgets
hcam_widgets/misc.py
execCommand
def execCommand(g, command, timeout=10): """ Executes a command by sending it to the rack server Arguments: g : hcam_drivers.globals.Container the Container object of application globals command : (string) the command (see below) Possible commands are: start : starts a run stop : stops a run abort : aborts a run online : bring ESO control server online and power up hardware off : put ESO control server in idle state and power down standby : server can communicate, but child processes disabled reset : resets the NGC controller front end Returns True/False according to whether the command succeeded or not. """ if not g.cpars['hcam_server_on']: g.clog.warn('execCommand: servers are not active') return False try: url = g.cpars['hipercam_server'] + command g.clog.info('execCommand, command = "' + command + '"') response = urllib.request.urlopen(url, timeout=timeout) rs = ReadServer(response.read(), status_msg=False) g.rlog.info('Server response =\n' + rs.resp()) if rs.ok: g.clog.info('Response from server was OK') return True else: g.clog.warn('Response from server was not OK') g.clog.warn('Reason: ' + rs.err) return False except urllib.error.URLError as err: g.clog.warn('execCommand failed') g.clog.warn(str(err)) return False
python
def execCommand(g, command, timeout=10): """ Executes a command by sending it to the rack server Arguments: g : hcam_drivers.globals.Container the Container object of application globals command : (string) the command (see below) Possible commands are: start : starts a run stop : stops a run abort : aborts a run online : bring ESO control server online and power up hardware off : put ESO control server in idle state and power down standby : server can communicate, but child processes disabled reset : resets the NGC controller front end Returns True/False according to whether the command succeeded or not. """ if not g.cpars['hcam_server_on']: g.clog.warn('execCommand: servers are not active') return False try: url = g.cpars['hipercam_server'] + command g.clog.info('execCommand, command = "' + command + '"') response = urllib.request.urlopen(url, timeout=timeout) rs = ReadServer(response.read(), status_msg=False) g.rlog.info('Server response =\n' + rs.resp()) if rs.ok: g.clog.info('Response from server was OK') return True else: g.clog.warn('Response from server was not OK') g.clog.warn('Reason: ' + rs.err) return False except urllib.error.URLError as err: g.clog.warn('execCommand failed') g.clog.warn(str(err)) return False
[ "def", "execCommand", "(", "g", ",", "command", ",", "timeout", "=", "10", ")", ":", "if", "not", "g", ".", "cpars", "[", "'hcam_server_on'", "]", ":", "g", ".", "clog", ".", "warn", "(", "'execCommand: servers are not active'", ")", "return", "False", "...
Executes a command by sending it to the rack server Arguments: g : hcam_drivers.globals.Container the Container object of application globals command : (string) the command (see below) Possible commands are: start : starts a run stop : stops a run abort : aborts a run online : bring ESO control server online and power up hardware off : put ESO control server in idle state and power down standby : server can communicate, but child processes disabled reset : resets the NGC controller front end Returns True/False according to whether the command succeeded or not.
[ "Executes", "a", "command", "by", "sending", "it", "to", "the", "rack", "server" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/misc.py#L433-L478
train
HiPERCAM/hcam_widgets
hcam_widgets/misc.py
isRunActive
def isRunActive(g): """ Polls the data server to see if a run is active """ if g.cpars['hcam_server_on']: url = g.cpars['hipercam_server'] + 'summary' response = urllib.request.urlopen(url, timeout=2) rs = ReadServer(response.read(), status_msg=True) if not rs.ok: raise DriverError('isRunActive error: ' + str(rs.err)) if rs.state == 'idle': return False elif rs.state == 'active': return True else: raise DriverError('isRunActive error, state = ' + rs.state) else: raise DriverError('isRunActive error: servers are not active')
python
def isRunActive(g): """ Polls the data server to see if a run is active """ if g.cpars['hcam_server_on']: url = g.cpars['hipercam_server'] + 'summary' response = urllib.request.urlopen(url, timeout=2) rs = ReadServer(response.read(), status_msg=True) if not rs.ok: raise DriverError('isRunActive error: ' + str(rs.err)) if rs.state == 'idle': return False elif rs.state == 'active': return True else: raise DriverError('isRunActive error, state = ' + rs.state) else: raise DriverError('isRunActive error: servers are not active')
[ "def", "isRunActive", "(", "g", ")", ":", "if", "g", ".", "cpars", "[", "'hcam_server_on'", "]", ":", "url", "=", "g", ".", "cpars", "[", "'hipercam_server'", "]", "+", "'summary'", "response", "=", "urllib", ".", "request", ".", "urlopen", "(", "url",...
Polls the data server to see if a run is active
[ "Polls", "the", "data", "server", "to", "see", "if", "a", "run", "is", "active" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/misc.py#L481-L498
train
HiPERCAM/hcam_widgets
hcam_widgets/misc.py
getFrameNumber
def getFrameNumber(g): """ Polls the data server to find the current frame number. Throws an exceotion if it cannot determine it. """ if not g.cpars['hcam_server_on']: raise DriverError('getRunNumber error: servers are not active') url = g.cpars['hipercam_server'] + 'status/DET.FRAM2.NO' response = urllib.request.urlopen(url, timeout=2) rs = ReadServer(response.read(), status_msg=False) try: msg = rs.msg except: raise DriverError('getFrameNumber error: no message found') try: frame_no = int(msg.split()[1]) except: raise DriverError('getFrameNumber error: invalid msg ' + msg) return frame_no
python
def getFrameNumber(g): """ Polls the data server to find the current frame number. Throws an exceotion if it cannot determine it. """ if not g.cpars['hcam_server_on']: raise DriverError('getRunNumber error: servers are not active') url = g.cpars['hipercam_server'] + 'status/DET.FRAM2.NO' response = urllib.request.urlopen(url, timeout=2) rs = ReadServer(response.read(), status_msg=False) try: msg = rs.msg except: raise DriverError('getFrameNumber error: no message found') try: frame_no = int(msg.split()[1]) except: raise DriverError('getFrameNumber error: invalid msg ' + msg) return frame_no
[ "def", "getFrameNumber", "(", "g", ")", ":", "if", "not", "g", ".", "cpars", "[", "'hcam_server_on'", "]", ":", "raise", "DriverError", "(", "'getRunNumber error: servers are not active'", ")", "url", "=", "g", ".", "cpars", "[", "'hipercam_server'", "]", "+",...
Polls the data server to find the current frame number. Throws an exceotion if it cannot determine it.
[ "Polls", "the", "data", "server", "to", "find", "the", "current", "frame", "number", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/misc.py#L535-L554
train
HiPERCAM/hcam_widgets
hcam_widgets/misc.py
getRunNumber
def getRunNumber(g): """ Polls the data server to find the current run number. Throws exceptions if it can't determine it. """ if not g.cpars['hcam_server_on']: raise DriverError('getRunNumber error: servers are not active') url = g.cpars['hipercam_server'] + 'summary' response = urllib.request.urlopen(url, timeout=2) rs = ReadServer(response.read(), status_msg=True) if rs.ok: return rs.run else: raise DriverError('getRunNumber error: ' + str(rs.err))
python
def getRunNumber(g): """ Polls the data server to find the current run number. Throws exceptions if it can't determine it. """ if not g.cpars['hcam_server_on']: raise DriverError('getRunNumber error: servers are not active') url = g.cpars['hipercam_server'] + 'summary' response = urllib.request.urlopen(url, timeout=2) rs = ReadServer(response.read(), status_msg=True) if rs.ok: return rs.run else: raise DriverError('getRunNumber error: ' + str(rs.err))
[ "def", "getRunNumber", "(", "g", ")", ":", "if", "not", "g", ".", "cpars", "[", "'hcam_server_on'", "]", ":", "raise", "DriverError", "(", "'getRunNumber error: servers are not active'", ")", "url", "=", "g", ".", "cpars", "[", "'hipercam_server'", "]", "+", ...
Polls the data server to find the current run number. Throws exceptions if it can't determine it.
[ "Polls", "the", "data", "server", "to", "find", "the", "current", "run", "number", ".", "Throws", "exceptions", "if", "it", "can", "t", "determine", "it", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/misc.py#L557-L570
train
HiPERCAM/hcam_widgets
hcam_widgets/misc.py
checkSimbad
def checkSimbad(g, target, maxobj=5, timeout=5): """ Sends off a request to Simbad to check whether a target is recognised. Returns with a list of results, or raises an exception if it times out """ url = 'http://simbad.u-strasbg.fr/simbad/sim-script' q = 'set limit ' + str(maxobj) + \ '\nformat object form1 "Target: %IDLIST(1) | %COO(A D;ICRS)"\nquery ' \ + target query = urllib.parse.urlencode({'submit': 'submit script', 'script': q}) resp = urllib.request.urlopen(url, query.encode(), timeout) data = False error = False results = [] for line in resp: line = line.decode() if line.startswith('::data::'): data = True if line.startswith('::error::'): error = True if data and line.startswith('Target:'): name, coords = line[7:].split(' | ') results.append( {'Name': name.strip(), 'Position': coords.strip(), 'Frame': 'ICRS'}) resp.close() if error and len(results): g.clog.warn('drivers.check: Simbad: there appear to be some ' + 'results but an error was unexpectedly raised.') return results
python
def checkSimbad(g, target, maxobj=5, timeout=5): """ Sends off a request to Simbad to check whether a target is recognised. Returns with a list of results, or raises an exception if it times out """ url = 'http://simbad.u-strasbg.fr/simbad/sim-script' q = 'set limit ' + str(maxobj) + \ '\nformat object form1 "Target: %IDLIST(1) | %COO(A D;ICRS)"\nquery ' \ + target query = urllib.parse.urlencode({'submit': 'submit script', 'script': q}) resp = urllib.request.urlopen(url, query.encode(), timeout) data = False error = False results = [] for line in resp: line = line.decode() if line.startswith('::data::'): data = True if line.startswith('::error::'): error = True if data and line.startswith('Target:'): name, coords = line[7:].split(' | ') results.append( {'Name': name.strip(), 'Position': coords.strip(), 'Frame': 'ICRS'}) resp.close() if error and len(results): g.clog.warn('drivers.check: Simbad: there appear to be some ' + 'results but an error was unexpectedly raised.') return results
[ "def", "checkSimbad", "(", "g", ",", "target", ",", "maxobj", "=", "5", ",", "timeout", "=", "5", ")", ":", "url", "=", "'http://simbad.u-strasbg.fr/simbad/sim-script'", "q", "=", "'set limit '", "+", "str", "(", "maxobj", ")", "+", "'\\nformat object form1 \"...
Sends off a request to Simbad to check whether a target is recognised. Returns with a list of results, or raises an exception if it times out
[ "Sends", "off", "a", "request", "to", "Simbad", "to", "check", "whether", "a", "target", "is", "recognised", ".", "Returns", "with", "a", "list", "of", "results", "or", "raises", "an", "exception", "if", "it", "times", "out" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/misc.py#L573-L603
train
HiPERCAM/hcam_widgets
hcam_widgets/misc.py
FifoThread.run
def run(self): """ Version of run that traps Exceptions and stores them in the fifo """ try: threading.Thread.run(self) except Exception: t, v, tb = sys.exc_info() error = traceback.format_exception_only(t, v)[0][:-1] tback = (self.name + ' Traceback (most recent call last):\n' + ''.join(traceback.format_tb(tb))) self.fifo.put((self.name, error, tback))
python
def run(self): """ Version of run that traps Exceptions and stores them in the fifo """ try: threading.Thread.run(self) except Exception: t, v, tb = sys.exc_info() error = traceback.format_exception_only(t, v)[0][:-1] tback = (self.name + ' Traceback (most recent call last):\n' + ''.join(traceback.format_tb(tb))) self.fifo.put((self.name, error, tback))
[ "def", "run", "(", "self", ")", ":", "try", ":", "threading", ".", "Thread", ".", "run", "(", "self", ")", "except", "Exception", ":", "t", ",", "v", ",", "tb", "=", "sys", ".", "exc_info", "(", ")", "error", "=", "traceback", ".", "format_exceptio...
Version of run that traps Exceptions and stores them in the fifo
[ "Version", "of", "run", "that", "traps", "Exceptions", "and", "stores", "them", "in", "the", "fifo" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/misc.py#L618-L630
train
MacHu-GWU/loggerFactory-project
loggerFactory/rand_str.py
rand_str
def rand_str(charset, length=32): """ Generate random string. """ return "".join([random.choice(charset) for _ in range(length)])
python
def rand_str(charset, length=32): """ Generate random string. """ return "".join([random.choice(charset) for _ in range(length)])
[ "def", "rand_str", "(", "charset", ",", "length", "=", "32", ")", ":", "return", "\"\"", ".", "join", "(", "[", "random", ".", "choice", "(", "charset", ")", "for", "_", "in", "range", "(", "length", ")", "]", ")" ]
Generate random string.
[ "Generate", "random", "string", "." ]
4de19e275e01dc583b1af9ceeacef0c6084cd6e0
https://github.com/MacHu-GWU/loggerFactory-project/blob/4de19e275e01dc583b1af9ceeacef0c6084cd6e0/loggerFactory/rand_str.py#L16-L20
train
HiPERCAM/hcam_widgets
hcam_widgets/tkutils.py
get_root
def get_root(w): """ Simple method to access root for a widget """ next_level = w while next_level.master: next_level = next_level.master return next_level
python
def get_root(w): """ Simple method to access root for a widget """ next_level = w while next_level.master: next_level = next_level.master return next_level
[ "def", "get_root", "(", "w", ")", ":", "next_level", "=", "w", "while", "next_level", ".", "master", ":", "next_level", "=", "next_level", ".", "master", "return", "next_level" ]
Simple method to access root for a widget
[ "Simple", "method", "to", "access", "root", "for", "a", "widget" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/tkutils.py#L18-L25
train
HiPERCAM/hcam_widgets
hcam_widgets/tkutils.py
addStyle
def addStyle(w): """ Styles the GUI: global fonts and colours. Parameters ---------- w : tkinter.tk widget element to style """ # access global container in root widget root = get_root(w) g = root.globals fsize = g.cpars['font_size'] family = g.cpars['font_family'] # Default font g.DEFAULT_FONT = font.nametofont("TkDefaultFont") g.DEFAULT_FONT.configure(size=fsize, weight='bold', family=family) w.option_add('*Font', g.DEFAULT_FONT) # Menu font g.MENU_FONT = font.nametofont("TkMenuFont") g.MENU_FONT.configure(family=family) w.option_add('*Menu.Font', g.MENU_FONT) # Entry font g.ENTRY_FONT = font.nametofont("TkTextFont") g.ENTRY_FONT.configure(size=fsize, family=family) w.option_add('*Entry.Font', g.ENTRY_FONT) # position and size # root.geometry("320x240+325+200") # Default colours. Note there is a difference between # specifying 'background' with a capital B or lowercase b w.option_add('*background', g.COL['main']) w.option_add('*HighlightBackground', g.COL['main']) w.config(background=g.COL['main'])
python
def addStyle(w): """ Styles the GUI: global fonts and colours. Parameters ---------- w : tkinter.tk widget element to style """ # access global container in root widget root = get_root(w) g = root.globals fsize = g.cpars['font_size'] family = g.cpars['font_family'] # Default font g.DEFAULT_FONT = font.nametofont("TkDefaultFont") g.DEFAULT_FONT.configure(size=fsize, weight='bold', family=family) w.option_add('*Font', g.DEFAULT_FONT) # Menu font g.MENU_FONT = font.nametofont("TkMenuFont") g.MENU_FONT.configure(family=family) w.option_add('*Menu.Font', g.MENU_FONT) # Entry font g.ENTRY_FONT = font.nametofont("TkTextFont") g.ENTRY_FONT.configure(size=fsize, family=family) w.option_add('*Entry.Font', g.ENTRY_FONT) # position and size # root.geometry("320x240+325+200") # Default colours. Note there is a difference between # specifying 'background' with a capital B or lowercase b w.option_add('*background', g.COL['main']) w.option_add('*HighlightBackground', g.COL['main']) w.config(background=g.COL['main'])
[ "def", "addStyle", "(", "w", ")", ":", "# access global container in root widget", "root", "=", "get_root", "(", "w", ")", "g", "=", "root", ".", "globals", "fsize", "=", "g", ".", "cpars", "[", "'font_size'", "]", "family", "=", "g", ".", "cpars", "[", ...
Styles the GUI: global fonts and colours. Parameters ---------- w : tkinter.tk widget element to style
[ "Styles", "the", "GUI", ":", "global", "fonts", "and", "colours", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/tkutils.py#L28-L65
train
IceflowRE/unidown
unidown/core/manager.py
init
def init(main_dir: Path, logfile_path: Path, log_level: str): """ Initialize the _downloader. TODO. :param main_dir: main directory :type main_dir: ~pathlib.Path :param logfile_path: logfile path :type logfile_path: ~pathlib.Path :param log_level: logging level :type log_level: str """ dynamic_data.reset() dynamic_data.init_dirs(main_dir, logfile_path) dynamic_data.check_dirs() tools.create_dir_rec(dynamic_data.MAIN_DIR) tools.create_dir_rec(dynamic_data.TEMP_DIR) tools.create_dir_rec(dynamic_data.DOWNLOAD_DIR) tools.create_dir_rec(dynamic_data.SAVESTAT_DIR) tools.create_dir_rec(Path.resolve(dynamic_data.LOGFILE_PATH).parent) dynamic_data.LOG_LEVEL = log_level logging.basicConfig(filename=dynamic_data.LOGFILE_PATH, filemode='a', level=dynamic_data.LOG_LEVEL, format='%(asctime)s.%(msecs)03d | %(levelname)s - %(name)s | %(module)s.%(funcName)s: %(' 'message)s', datefmt='%Y.%m.%d %H:%M:%S') logging.captureWarnings(True) cores = multiprocessing.cpu_count() dynamic_data.USING_CORES = min(4, max(1, cores - 1)) info = f"{static_data.NAME} {static_data.VERSION}\n\n" \ f"System: {platform.system()} - {platform.version()} - {platform.machine()} - {cores} cores\n" \ f"Python: {platform.python_version()} - {' - '.join(platform.python_build())}\n" \ f"Arguments: main={main_dir.resolve()} | logfile={logfile_path.resolve()} | loglevel={log_level}\n" \ f"Using cores: {dynamic_data.USING_CORES}\n\n" with dynamic_data.LOGFILE_PATH.open(mode='w', encoding="utf8") as writer: writer.write(info) dynamic_data.AVAIL_PLUGINS = APlugin.get_plugins()
python
def init(main_dir: Path, logfile_path: Path, log_level: str): """ Initialize the _downloader. TODO. :param main_dir: main directory :type main_dir: ~pathlib.Path :param logfile_path: logfile path :type logfile_path: ~pathlib.Path :param log_level: logging level :type log_level: str """ dynamic_data.reset() dynamic_data.init_dirs(main_dir, logfile_path) dynamic_data.check_dirs() tools.create_dir_rec(dynamic_data.MAIN_DIR) tools.create_dir_rec(dynamic_data.TEMP_DIR) tools.create_dir_rec(dynamic_data.DOWNLOAD_DIR) tools.create_dir_rec(dynamic_data.SAVESTAT_DIR) tools.create_dir_rec(Path.resolve(dynamic_data.LOGFILE_PATH).parent) dynamic_data.LOG_LEVEL = log_level logging.basicConfig(filename=dynamic_data.LOGFILE_PATH, filemode='a', level=dynamic_data.LOG_LEVEL, format='%(asctime)s.%(msecs)03d | %(levelname)s - %(name)s | %(module)s.%(funcName)s: %(' 'message)s', datefmt='%Y.%m.%d %H:%M:%S') logging.captureWarnings(True) cores = multiprocessing.cpu_count() dynamic_data.USING_CORES = min(4, max(1, cores - 1)) info = f"{static_data.NAME} {static_data.VERSION}\n\n" \ f"System: {platform.system()} - {platform.version()} - {platform.machine()} - {cores} cores\n" \ f"Python: {platform.python_version()} - {' - '.join(platform.python_build())}\n" \ f"Arguments: main={main_dir.resolve()} | logfile={logfile_path.resolve()} | loglevel={log_level}\n" \ f"Using cores: {dynamic_data.USING_CORES}\n\n" with dynamic_data.LOGFILE_PATH.open(mode='w', encoding="utf8") as writer: writer.write(info) dynamic_data.AVAIL_PLUGINS = APlugin.get_plugins()
[ "def", "init", "(", "main_dir", ":", "Path", ",", "logfile_path", ":", "Path", ",", "log_level", ":", "str", ")", ":", "dynamic_data", ".", "reset", "(", ")", "dynamic_data", ".", "init_dirs", "(", "main_dir", ",", "logfile_path", ")", "dynamic_data", ".",...
Initialize the _downloader. TODO. :param main_dir: main directory :type main_dir: ~pathlib.Path :param logfile_path: logfile path :type logfile_path: ~pathlib.Path :param log_level: logging level :type log_level: str
[ "Initialize", "the", "_downloader", ".", "TODO", "." ]
2a6f82ab780bb825668bfc55b67c11c4f72ec05c
https://github.com/IceflowRE/unidown/blob/2a6f82ab780bb825668bfc55b67c11c4f72ec05c/unidown/core/manager.py#L17-L56
train
IceflowRE/unidown
unidown/core/manager.py
download_from_plugin
def download_from_plugin(plugin: APlugin): """ Download routine. 1. get newest update time 2. load savestate 3. compare last update time with savestate time 4. get download links 5. compare with savestate 6. download new/updated data 7. check downloads 8. update savestate 9. write new savestate :param plugin: plugin :type plugin: ~unidown.plugin.a_plugin.APlugin """ # get last update date plugin.log.info('Get last update') plugin.update_last_update() # load old save state save_state = plugin.load_save_state() if plugin.last_update <= save_state.last_update: plugin.log.info('No update. Nothing to do.') return # get download links plugin.log.info('Get download links') plugin.update_download_links() # compare with save state down_link_item_dict = plugin.get_updated_data(save_state.link_item_dict) plugin.log.info('Compared with save state: ' + str(len(plugin.download_data))) if not down_link_item_dict: plugin.log.info('No new data. Nothing to do.') return # download new/updated data plugin.log.info(f"Download new {plugin.unit}s: {len(down_link_item_dict)}") plugin.download(down_link_item_dict, plugin.download_path, 'Download new ' + plugin.unit + 's', plugin.unit) # check which downloads are succeeded succeed_link_item_dict, lost_link_item_dict = plugin.check_download(down_link_item_dict, plugin.download_path) plugin.log.info(f"Downloaded: {len(succeed_link_item_dict)}/{len(down_link_item_dict)}") # update savestate link_item_dict with succeeded downloads dict plugin.log.info('Update savestate') plugin.update_dict(save_state.link_item_dict, succeed_link_item_dict) # write new savestate plugin.log.info('Write savestate') plugin.save_save_state(save_state.link_item_dict)
python
def download_from_plugin(plugin: APlugin): """ Download routine. 1. get newest update time 2. load savestate 3. compare last update time with savestate time 4. get download links 5. compare with savestate 6. download new/updated data 7. check downloads 8. update savestate 9. write new savestate :param plugin: plugin :type plugin: ~unidown.plugin.a_plugin.APlugin """ # get last update date plugin.log.info('Get last update') plugin.update_last_update() # load old save state save_state = plugin.load_save_state() if plugin.last_update <= save_state.last_update: plugin.log.info('No update. Nothing to do.') return # get download links plugin.log.info('Get download links') plugin.update_download_links() # compare with save state down_link_item_dict = plugin.get_updated_data(save_state.link_item_dict) plugin.log.info('Compared with save state: ' + str(len(plugin.download_data))) if not down_link_item_dict: plugin.log.info('No new data. Nothing to do.') return # download new/updated data plugin.log.info(f"Download new {plugin.unit}s: {len(down_link_item_dict)}") plugin.download(down_link_item_dict, plugin.download_path, 'Download new ' + plugin.unit + 's', plugin.unit) # check which downloads are succeeded succeed_link_item_dict, lost_link_item_dict = plugin.check_download(down_link_item_dict, plugin.download_path) plugin.log.info(f"Downloaded: {len(succeed_link_item_dict)}/{len(down_link_item_dict)}") # update savestate link_item_dict with succeeded downloads dict plugin.log.info('Update savestate') plugin.update_dict(save_state.link_item_dict, succeed_link_item_dict) # write new savestate plugin.log.info('Write savestate') plugin.save_save_state(save_state.link_item_dict)
[ "def", "download_from_plugin", "(", "plugin", ":", "APlugin", ")", ":", "# get last update date", "plugin", ".", "log", ".", "info", "(", "'Get last update'", ")", "plugin", ".", "update_last_update", "(", ")", "# load old save state", "save_state", "=", "plugin", ...
Download routine. 1. get newest update time 2. load savestate 3. compare last update time with savestate time 4. get download links 5. compare with savestate 6. download new/updated data 7. check downloads 8. update savestate 9. write new savestate :param plugin: plugin :type plugin: ~unidown.plugin.a_plugin.APlugin
[ "Download", "routine", "." ]
2a6f82ab780bb825668bfc55b67c11c4f72ec05c
https://github.com/IceflowRE/unidown/blob/2a6f82ab780bb825668bfc55b67c11c4f72ec05c/unidown/core/manager.py#L66-L111
train
IceflowRE/unidown
unidown/core/manager.py
run
def run(plugin_name: str, options: List[str] = None) -> PluginState: """ Run a plugin so use the download routine and clean up after. :param plugin_name: name of plugin :type plugin_name: str :param options: parameters which will be send to the plugin initialization :type options: List[str] :return: success :rtype: ~unidown.plugin.plugin_state.PluginState """ if options is None: options = [] if plugin_name not in dynamic_data.AVAIL_PLUGINS: msg = 'Plugin ' + plugin_name + ' was not found.' logging.error(msg) print(msg) return PluginState.NOT_FOUND try: plugin_class = dynamic_data.AVAIL_PLUGINS[plugin_name].load() plugin = plugin_class(options) except Exception: msg = 'Plugin ' + plugin_name + ' crashed while loading.' logging.exception(msg) print(msg + ' Check log for more information.') return PluginState.LOAD_CRASH else: logging.info('Loaded plugin: ' + plugin_name) try: download_from_plugin(plugin) plugin.clean_up() except PluginException as ex: msg = f"Plugin {plugin.name} stopped working. Reason: {'unknown' if (ex.msg == '') else ex.msg}" logging.error(msg) print(msg) return PluginState.RUN_FAIL except Exception: msg = 'Plugin ' + plugin.name + ' crashed.' logging.exception(msg) print(msg + ' Check log for more information.') return PluginState.RUN_CRASH else: logging.info(plugin.name + ' ends without errors.') return PluginState.END_SUCCESS
python
def run(plugin_name: str, options: List[str] = None) -> PluginState: """ Run a plugin so use the download routine and clean up after. :param plugin_name: name of plugin :type plugin_name: str :param options: parameters which will be send to the plugin initialization :type options: List[str] :return: success :rtype: ~unidown.plugin.plugin_state.PluginState """ if options is None: options = [] if plugin_name not in dynamic_data.AVAIL_PLUGINS: msg = 'Plugin ' + plugin_name + ' was not found.' logging.error(msg) print(msg) return PluginState.NOT_FOUND try: plugin_class = dynamic_data.AVAIL_PLUGINS[plugin_name].load() plugin = plugin_class(options) except Exception: msg = 'Plugin ' + plugin_name + ' crashed while loading.' logging.exception(msg) print(msg + ' Check log for more information.') return PluginState.LOAD_CRASH else: logging.info('Loaded plugin: ' + plugin_name) try: download_from_plugin(plugin) plugin.clean_up() except PluginException as ex: msg = f"Plugin {plugin.name} stopped working. Reason: {'unknown' if (ex.msg == '') else ex.msg}" logging.error(msg) print(msg) return PluginState.RUN_FAIL except Exception: msg = 'Plugin ' + plugin.name + ' crashed.' logging.exception(msg) print(msg + ' Check log for more information.') return PluginState.RUN_CRASH else: logging.info(plugin.name + ' ends without errors.') return PluginState.END_SUCCESS
[ "def", "run", "(", "plugin_name", ":", "str", ",", "options", ":", "List", "[", "str", "]", "=", "None", ")", "->", "PluginState", ":", "if", "options", "is", "None", ":", "options", "=", "[", "]", "if", "plugin_name", "not", "in", "dynamic_data", "....
Run a plugin so use the download routine and clean up after. :param plugin_name: name of plugin :type plugin_name: str :param options: parameters which will be send to the plugin initialization :type options: List[str] :return: success :rtype: ~unidown.plugin.plugin_state.PluginState
[ "Run", "a", "plugin", "so", "use", "the", "download", "routine", "and", "clean", "up", "after", "." ]
2a6f82ab780bb825668bfc55b67c11c4f72ec05c
https://github.com/IceflowRE/unidown/blob/2a6f82ab780bb825668bfc55b67c11c4f72ec05c/unidown/core/manager.py#L114-L160
train
IceflowRE/unidown
unidown/core/manager.py
check_update
def check_update(): """ Check for app updates and print/log them. """ logging.info('Check for app updates.') try: update = updater.check_for_app_updates() except Exception: logging.exception('Check for updates failed.') return if update: print("!!! UPDATE AVAILABLE !!!\n" "" + static_data.PROJECT_URL + "\n\n") logging.info("Update available: " + static_data.PROJECT_URL) else: logging.info("No update available.")
python
def check_update(): """ Check for app updates and print/log them. """ logging.info('Check for app updates.') try: update = updater.check_for_app_updates() except Exception: logging.exception('Check for updates failed.') return if update: print("!!! UPDATE AVAILABLE !!!\n" "" + static_data.PROJECT_URL + "\n\n") logging.info("Update available: " + static_data.PROJECT_URL) else: logging.info("No update available.")
[ "def", "check_update", "(", ")", ":", "logging", ".", "info", "(", "'Check for app updates.'", ")", "try", ":", "update", "=", "updater", ".", "check_for_app_updates", "(", ")", "except", "Exception", ":", "logging", ".", "exception", "(", "'Check for updates fa...
Check for app updates and print/log them.
[ "Check", "for", "app", "updates", "and", "print", "/", "log", "them", "." ]
2a6f82ab780bb825668bfc55b67c11c4f72ec05c
https://github.com/IceflowRE/unidown/blob/2a6f82ab780bb825668bfc55b67c11c4f72ec05c/unidown/core/manager.py#L163-L178
train
IceflowRE/unidown
unidown/core/updater.py
get_newest_app_version
def get_newest_app_version() -> Version: """ Download the version tag from remote. :return: version from remote :rtype: ~packaging.version.Version """ with urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where()) as p_man: pypi_json = p_man.urlopen('GET', static_data.PYPI_JSON_URL).data.decode('utf-8') releases = json.loads(pypi_json).get('releases', []) online_version = Version('0.0.0') for release in releases: cur_version = Version(release) if not cur_version.is_prerelease: online_version = max(online_version, cur_version) return online_version
python
def get_newest_app_version() -> Version: """ Download the version tag from remote. :return: version from remote :rtype: ~packaging.version.Version """ with urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where()) as p_man: pypi_json = p_man.urlopen('GET', static_data.PYPI_JSON_URL).data.decode('utf-8') releases = json.loads(pypi_json).get('releases', []) online_version = Version('0.0.0') for release in releases: cur_version = Version(release) if not cur_version.is_prerelease: online_version = max(online_version, cur_version) return online_version
[ "def", "get_newest_app_version", "(", ")", "->", "Version", ":", "with", "urllib3", ".", "PoolManager", "(", "cert_reqs", "=", "'CERT_REQUIRED'", ",", "ca_certs", "=", "certifi", ".", "where", "(", ")", ")", "as", "p_man", ":", "pypi_json", "=", "p_man", "...
Download the version tag from remote. :return: version from remote :rtype: ~packaging.version.Version
[ "Download", "the", "version", "tag", "from", "remote", "." ]
2a6f82ab780bb825668bfc55b67c11c4f72ec05c
https://github.com/IceflowRE/unidown/blob/2a6f82ab780bb825668bfc55b67c11c4f72ec05c/unidown/core/updater.py#L13-L28
train
HiPERCAM/hcam_widgets
hcam_widgets/hcam.py
InstPars.setupNodding
def setupNodding(self): """ Setup Nodding for GTC """ g = get_root(self).globals if not self.nod(): # re-enable clear mode box if not drift if not self.isDrift(): self.clear.enable() # clear existing nod pattern self.nodPattern = {} self.check() return # Do nothing if we're not at the GTC if g.cpars['telins_name'] != 'GTC': messagebox.showerror('Error', 'Cannot dither WHT') self.nod.set(False) self.nodPattern = {} return # check for drift mode and bomb out if self.isDrift(): messagebox.showerror('Error', 'Cannot dither telescope in drift mode') self.nod.set(False) self.nodPattern = {} return # check for clear not enabled and warn if not self.clear(): if not messagebox.askokcancel('Warning', 'Dithering telescope will enable clear mode. Continue?'): self.nod.set(False) self.nodPattern = {} return # Ask for nod pattern try: home = expanduser('~') fname = filedialog.askopenfilename( title='Open offsets text file', defaultextension='.txt', filetypes=[('text files', '.txt')], initialdir=home) if not fname: g.clog.warn('Aborted load from disk') raise ValueError ra, dec = np.loadtxt(fname).T if len(ra) != len(dec): g.clog.warn('Mismatched lengths of RA and Dec offsets') raise ValueError data = dict( ra=ra.tolist(), dec=dec.tolist() ) except: g.clog.warn('Setting dither pattern failed. Disabling dithering') self.nod.set(False) self.nodPattern = {} return # store nodding on ipars object self.nodPattern = data # enable clear mode self.clear.set(True) # update self.check()
python
def setupNodding(self): """ Setup Nodding for GTC """ g = get_root(self).globals if not self.nod(): # re-enable clear mode box if not drift if not self.isDrift(): self.clear.enable() # clear existing nod pattern self.nodPattern = {} self.check() return # Do nothing if we're not at the GTC if g.cpars['telins_name'] != 'GTC': messagebox.showerror('Error', 'Cannot dither WHT') self.nod.set(False) self.nodPattern = {} return # check for drift mode and bomb out if self.isDrift(): messagebox.showerror('Error', 'Cannot dither telescope in drift mode') self.nod.set(False) self.nodPattern = {} return # check for clear not enabled and warn if not self.clear(): if not messagebox.askokcancel('Warning', 'Dithering telescope will enable clear mode. Continue?'): self.nod.set(False) self.nodPattern = {} return # Ask for nod pattern try: home = expanduser('~') fname = filedialog.askopenfilename( title='Open offsets text file', defaultextension='.txt', filetypes=[('text files', '.txt')], initialdir=home) if not fname: g.clog.warn('Aborted load from disk') raise ValueError ra, dec = np.loadtxt(fname).T if len(ra) != len(dec): g.clog.warn('Mismatched lengths of RA and Dec offsets') raise ValueError data = dict( ra=ra.tolist(), dec=dec.tolist() ) except: g.clog.warn('Setting dither pattern failed. Disabling dithering') self.nod.set(False) self.nodPattern = {} return # store nodding on ipars object self.nodPattern = data # enable clear mode self.clear.set(True) # update self.check()
[ "def", "setupNodding", "(", "self", ")", ":", "g", "=", "get_root", "(", "self", ")", ".", "globals", "if", "not", "self", ".", "nod", "(", ")", ":", "# re-enable clear mode box if not drift", "if", "not", "self", ".", "isDrift", "(", ")", ":", "self", ...
Setup Nodding for GTC
[ "Setup", "Nodding", "for", "GTC" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/hcam.py#L286-L357
train
HiPERCAM/hcam_widgets
hcam_widgets/hcam.py
InstPars.dumpJSON
def dumpJSON(self): """ Encodes current parameters to JSON compatible dictionary """ numexp = self.number.get() expTime, _, _, _, _ = self.timing() if numexp == 0: numexp = -1 data = dict( numexp=self.number.value(), app=self.app.value(), led_flsh=self.led(), dummy_out=self.dummy(), fast_clks=self.fastClk(), readout=self.readSpeed(), dwell=self.expose.value(), exptime=expTime, oscan=self.oscan(), oscany=self.oscany(), xbin=self.wframe.xbin.value(), ybin=self.wframe.ybin.value(), multipliers=self.nmult.getall(), clear=self.clear() ) # only allow nodding in clear mode, even if GUI has got confused if data['clear'] and self.nodPattern: data['nodpattern'] = self.nodPattern # no mixing clear and multipliers, no matter what GUI says if data['clear']: data['multipliers'] = [1 for i in self.nmult.getall()] # add window mode if not self.isFF(): if self.isDrift(): # no clear, multipliers or oscan in drift for setting in ('clear', 'oscan', 'oscany'): data[setting] = 0 data['multipliers'] = [1 for i in self.nmult.getall()] for iw, (xsl, xsr, ys, nx, ny) in enumerate(self.wframe): data['x{}start_left'.format(iw+1)] = xsl data['x{}start_right'.format(iw+1)] = xsr data['y{}start'.format(iw+1)] = ys data['y{}size'.format(iw+1)] = ny data['x{}size'.format(iw+1)] = nx else: # no oscany in window mode data['oscany'] = 0 for iw, (xsll, xsul, xslr, xsur, ys, nx, ny) in enumerate(self.wframe): data['x{}start_upperleft'.format(iw+1)] = xsul data['x{}start_lowerleft'.format(iw+1)] = xsll data['x{}start_upperright'.format(iw+1)] = xsur data['x{}start_lowerright'.format(iw+1)] = xslr data['y{}start'.format(iw+1)] = ys data['x{}size'.format(iw+1)] = nx data['y{}size'.format(iw+1)] = ny return data
python
def dumpJSON(self): """ Encodes current parameters to JSON compatible dictionary """ numexp = self.number.get() expTime, _, _, _, _ = self.timing() if numexp == 0: numexp = -1 data = dict( numexp=self.number.value(), app=self.app.value(), led_flsh=self.led(), dummy_out=self.dummy(), fast_clks=self.fastClk(), readout=self.readSpeed(), dwell=self.expose.value(), exptime=expTime, oscan=self.oscan(), oscany=self.oscany(), xbin=self.wframe.xbin.value(), ybin=self.wframe.ybin.value(), multipliers=self.nmult.getall(), clear=self.clear() ) # only allow nodding in clear mode, even if GUI has got confused if data['clear'] and self.nodPattern: data['nodpattern'] = self.nodPattern # no mixing clear and multipliers, no matter what GUI says if data['clear']: data['multipliers'] = [1 for i in self.nmult.getall()] # add window mode if not self.isFF(): if self.isDrift(): # no clear, multipliers or oscan in drift for setting in ('clear', 'oscan', 'oscany'): data[setting] = 0 data['multipliers'] = [1 for i in self.nmult.getall()] for iw, (xsl, xsr, ys, nx, ny) in enumerate(self.wframe): data['x{}start_left'.format(iw+1)] = xsl data['x{}start_right'.format(iw+1)] = xsr data['y{}start'.format(iw+1)] = ys data['y{}size'.format(iw+1)] = ny data['x{}size'.format(iw+1)] = nx else: # no oscany in window mode data['oscany'] = 0 for iw, (xsll, xsul, xslr, xsur, ys, nx, ny) in enumerate(self.wframe): data['x{}start_upperleft'.format(iw+1)] = xsul data['x{}start_lowerleft'.format(iw+1)] = xsll data['x{}start_upperright'.format(iw+1)] = xsur data['x{}start_lowerright'.format(iw+1)] = xslr data['y{}start'.format(iw+1)] = ys data['x{}size'.format(iw+1)] = nx data['y{}size'.format(iw+1)] = ny return data
[ "def", "dumpJSON", "(", "self", ")", ":", "numexp", "=", "self", ".", "number", ".", "get", "(", ")", "expTime", ",", "_", ",", "_", ",", "_", ",", "_", "=", "self", ".", "timing", "(", ")", "if", "numexp", "==", "0", ":", "numexp", "=", "-",...
Encodes current parameters to JSON compatible dictionary
[ "Encodes", "current", "parameters", "to", "JSON", "compatible", "dictionary" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/hcam.py#L404-L464
train
HiPERCAM/hcam_widgets
hcam_widgets/hcam.py
InstPars.loadJSON
def loadJSON(self, json_string): """ Loads in an application saved in JSON format. """ g = get_root(self).globals data = json.loads(json_string)['appdata'] # first set the parameters which change regardless of mode # number of exposures numexp = data.get('numexp', 0) if numexp == -1: numexp = 0 self.number.set(numexp) # Overscan (x, y) if 'oscan' in data: self.oscan.set(data['oscan']) if 'oscany' in data: self.oscan.set(data['oscany']) # LED setting self.led.set(data.get('led_flsh', 0)) # Dummy output enabled self.dummy.set(data.get('dummy_out', 0)) # Fast clocking option? self.fastClk.set(data.get('fast_clks', 0)) # readout speed self.readSpeed.set(data.get('readout', 'Slow')) # dwell dwell = data.get('dwell', 0) self.expose.set(str(float(dwell))) # multipliers mult_values = data.get('multipliers', (1, 1, 1, 1, 1)) self.nmult.setall(mult_values) # look for nodpattern in data nodPattern = data.get('nodpattern', {}) if nodPattern and g.cpars['telins_name'] == 'GTC': self.nodPattern = nodPattern self.nod.set(True) self.clear.set(True) else: self.nodPattern = {} self.nod.set(False) # binning self.quad_frame.xbin.set(data.get('xbin', 1)) self.quad_frame.ybin.set(data.get('ybin', 1)) self.drift_frame.xbin.set(data.get('xbin', 1)) self.drift_frame.ybin.set(data.get('ybin', 1)) # now for the behaviour which depends on mode if 'app' in data: self.app.set(data['app']) app = data['app'] if app == 'Drift': # disable clear mode in drift self.clear.set(0) # only one pair allowed self.wframe.npair.set(1) # set the window pair values labels = ('x1start_left', 'y1start', 'x1start_right', 'x1size', 'y1size') if not all(label in data for label in labels): raise DriverError('Drift mode application missing window params') # now actually set them self.wframe.xsl[0].set(data['x1start_left']) self.wframe.xsr[0].set(data['x1start_right']) self.wframe.ys[0].set(data['y1start']) self.wframe.nx[0].set(data['x1size']) self.wframe.ny[0].set(data['y1size']) self.wframe.check() elif app == 'FullFrame': # enable clear mode if set self.clear.set(data.get('clear', 0)) elif app == 'Windows': # enable clear mode if set self.clear.set(data.get('clear', 0)) nquad = 0 for nw in range(2): labels = ('x{0}start_lowerleft y{0}start x{0}start_upperleft x{0}start_upperright ' + 'x{0}start_lowerright x{0}size y{0}size').format(nw+1).split() if all(label in data for label in labels): xsll = data[labels[0]] xslr = data[labels[4]] xsul = data[labels[2]] xsur = data[labels[3]] ys = data[labels[1]] nx = data[labels[5]] ny = data[labels[6]] self.wframe.xsll[nw].set(xsll) self.wframe.xslr[nw].set(xslr) self.wframe.xsul[nw].set(xsul) self.wframe.xsur[nw].set(xsur) self.wframe.ys[nw].set(ys) self.wframe.nx[nw].set(nx) self.wframe.ny[nw].set(ny) nquad += 1 else: break self.wframe.nquad.set(nquad) self.wframe.check()
python
def loadJSON(self, json_string): """ Loads in an application saved in JSON format. """ g = get_root(self).globals data = json.loads(json_string)['appdata'] # first set the parameters which change regardless of mode # number of exposures numexp = data.get('numexp', 0) if numexp == -1: numexp = 0 self.number.set(numexp) # Overscan (x, y) if 'oscan' in data: self.oscan.set(data['oscan']) if 'oscany' in data: self.oscan.set(data['oscany']) # LED setting self.led.set(data.get('led_flsh', 0)) # Dummy output enabled self.dummy.set(data.get('dummy_out', 0)) # Fast clocking option? self.fastClk.set(data.get('fast_clks', 0)) # readout speed self.readSpeed.set(data.get('readout', 'Slow')) # dwell dwell = data.get('dwell', 0) self.expose.set(str(float(dwell))) # multipliers mult_values = data.get('multipliers', (1, 1, 1, 1, 1)) self.nmult.setall(mult_values) # look for nodpattern in data nodPattern = data.get('nodpattern', {}) if nodPattern and g.cpars['telins_name'] == 'GTC': self.nodPattern = nodPattern self.nod.set(True) self.clear.set(True) else: self.nodPattern = {} self.nod.set(False) # binning self.quad_frame.xbin.set(data.get('xbin', 1)) self.quad_frame.ybin.set(data.get('ybin', 1)) self.drift_frame.xbin.set(data.get('xbin', 1)) self.drift_frame.ybin.set(data.get('ybin', 1)) # now for the behaviour which depends on mode if 'app' in data: self.app.set(data['app']) app = data['app'] if app == 'Drift': # disable clear mode in drift self.clear.set(0) # only one pair allowed self.wframe.npair.set(1) # set the window pair values labels = ('x1start_left', 'y1start', 'x1start_right', 'x1size', 'y1size') if not all(label in data for label in labels): raise DriverError('Drift mode application missing window params') # now actually set them self.wframe.xsl[0].set(data['x1start_left']) self.wframe.xsr[0].set(data['x1start_right']) self.wframe.ys[0].set(data['y1start']) self.wframe.nx[0].set(data['x1size']) self.wframe.ny[0].set(data['y1size']) self.wframe.check() elif app == 'FullFrame': # enable clear mode if set self.clear.set(data.get('clear', 0)) elif app == 'Windows': # enable clear mode if set self.clear.set(data.get('clear', 0)) nquad = 0 for nw in range(2): labels = ('x{0}start_lowerleft y{0}start x{0}start_upperleft x{0}start_upperright ' + 'x{0}start_lowerright x{0}size y{0}size').format(nw+1).split() if all(label in data for label in labels): xsll = data[labels[0]] xslr = data[labels[4]] xsul = data[labels[2]] xsur = data[labels[3]] ys = data[labels[1]] nx = data[labels[5]] ny = data[labels[6]] self.wframe.xsll[nw].set(xsll) self.wframe.xslr[nw].set(xslr) self.wframe.xsul[nw].set(xsul) self.wframe.xsur[nw].set(xsur) self.wframe.ys[nw].set(ys) self.wframe.nx[nw].set(nx) self.wframe.ny[nw].set(ny) nquad += 1 else: break self.wframe.nquad.set(nquad) self.wframe.check()
[ "def", "loadJSON", "(", "self", ",", "json_string", ")", ":", "g", "=", "get_root", "(", "self", ")", ".", "globals", "data", "=", "json", ".", "loads", "(", "json_string", ")", "[", "'appdata'", "]", "# first set the parameters which change regardless of mode",...
Loads in an application saved in JSON format.
[ "Loads", "in", "an", "application", "saved", "in", "JSON", "format", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/hcam.py#L466-L571
train
HiPERCAM/hcam_widgets
hcam_widgets/hcam.py
InstPars.check
def check(self, *args): """ Callback to check validity of instrument parameters. Performs the following tasks: - spots and flags overlapping windows or null window parameters - flags windows with invalid dimensions given the binning parameter - sets the correct number of enabled windows - disables or enables clear and nod buttons depending on drift mode or not - checks for window synchronisation, enabling sync button if required - enables or disables start button if settings are OK Returns ------- status : bool True or False according to whether the settings are OK. """ status = True g = get_root(self).globals # clear errors on binning (may be set later if FF) xbinw, ybinw = self.wframe.xbin, self.wframe.ybin xbinw.config(bg=g.COL['main']) ybinw.config(bg=g.COL['main']) # keep binning factors of drift mode and windowed mode up to date oframe, aframe = ((self.quad_frame, self.drift_frame) if self.drift_frame.winfo_ismapped() else (self.drift_frame, self.quad_frame)) xbin, ybin = aframe.xbin.value(), aframe.ybin.value() oframe.xbin.set(xbin) oframe.ybin.set(ybin) if not self.frozen: if self.clear() or self.isDrift(): # disable nmult in clear or drift mode self.nmult.disable() else: self.nmult.enable() if self.isDrift(): self.clearLab.config(state='disable') self.nodLab.config(state='disable') if not self.drift_frame.winfo_ismapped(): self.quad_frame.grid_forget() self.drift_frame.grid(row=10, column=0, columnspan=3, sticky=tk.W+tk.N) if not self.frozen: self.oscany.config(state='disable') self.oscan.config(state='disable') self.clear.config(state='disable') self.nod.config(state='disable') self.wframe.enable() status = self.wframe.check() elif self.isFF(): # special case check of binning from window frame if 1024 % xbin != 0: status = False xbinw.config(bg=g.COL['error']) elif (1024 // xbin) % 4 != 0: status = False xbinw.config(bg=g.COL['error']) if 512 % ybin != 0: status = False ybinw.config(bg=g.COL['error']) if not self.quad_frame.winfo_ismapped(): self.drift_frame.grid_forget() self.quad_frame.grid(row=10, column=0, columnspan=3, sticky=tk.W+tk.N) self.clearLab.config(state='normal') if g.cpars['telins_name'] == 'GTC': self.nodLab.config(state='normal') else: self.nodLab.config(state='disable') if not self.frozen: self.oscany.config(state='normal') self.oscan.config(state='normal') self.clear.config(state='normal') if g.cpars['telins_name'] == 'GTC': self.nod.config(state='normal') else: self.nod.config(state='disable') self.wframe.disable() else: self.clearLab.config(state='normal') if g.cpars['telins_name'] == 'GTC': self.nodLab.config(state='normal') else: self.nodLab.config(state='disable') if not self.quad_frame.winfo_ismapped(): self.drift_frame.grid_forget() self.quad_frame.grid(row=10, column=0, columnspan=3, sticky=tk.W+tk.N) if not self.frozen: self.oscany.config(state='disable') self.oscan.config(state='normal') self.clear.config(state='normal') if g.cpars['telins_name'] == 'GTC': self.nod.config(state='normal') else: self.nod.config(state='disable') self.wframe.enable() status = self.wframe.check() # exposure delay if self.expose.ok(): self.expose.config(bg=g.COL['main']) else: self.expose.config(bg=g.COL['warn']) status = False # don't allow binning other than 1, 2 in overscan or prescan mode if self.oscan() or self.oscany(): if xbin not in (1, 2): status = False xbinw.config(bg=g.COL['error']) if ybin not in (1, 2): status = False ybinw.config(bg=g.COL['error']) # disable clear if nodding enabled. re-enable if not drift if not self.frozen: if self.nod() or self.nodPattern: self.clear.config(state='disabled') self.clearLab.config(state='disabled') elif not self.isDrift(): self.clear.config(state='normal') self.clearLab.config(state='normal') # allow posting if parameters are OK. update count and SN estimates too if status: if (g.cpars['hcam_server_on'] and g.cpars['eso_server_online'] and g.observe.start['state'] == 'disabled' and not isRunActive(g)): g.observe.start.enable() g.count.update() else: g.observe.start.disable() return status
python
def check(self, *args): """ Callback to check validity of instrument parameters. Performs the following tasks: - spots and flags overlapping windows or null window parameters - flags windows with invalid dimensions given the binning parameter - sets the correct number of enabled windows - disables or enables clear and nod buttons depending on drift mode or not - checks for window synchronisation, enabling sync button if required - enables or disables start button if settings are OK Returns ------- status : bool True or False according to whether the settings are OK. """ status = True g = get_root(self).globals # clear errors on binning (may be set later if FF) xbinw, ybinw = self.wframe.xbin, self.wframe.ybin xbinw.config(bg=g.COL['main']) ybinw.config(bg=g.COL['main']) # keep binning factors of drift mode and windowed mode up to date oframe, aframe = ((self.quad_frame, self.drift_frame) if self.drift_frame.winfo_ismapped() else (self.drift_frame, self.quad_frame)) xbin, ybin = aframe.xbin.value(), aframe.ybin.value() oframe.xbin.set(xbin) oframe.ybin.set(ybin) if not self.frozen: if self.clear() or self.isDrift(): # disable nmult in clear or drift mode self.nmult.disable() else: self.nmult.enable() if self.isDrift(): self.clearLab.config(state='disable') self.nodLab.config(state='disable') if not self.drift_frame.winfo_ismapped(): self.quad_frame.grid_forget() self.drift_frame.grid(row=10, column=0, columnspan=3, sticky=tk.W+tk.N) if not self.frozen: self.oscany.config(state='disable') self.oscan.config(state='disable') self.clear.config(state='disable') self.nod.config(state='disable') self.wframe.enable() status = self.wframe.check() elif self.isFF(): # special case check of binning from window frame if 1024 % xbin != 0: status = False xbinw.config(bg=g.COL['error']) elif (1024 // xbin) % 4 != 0: status = False xbinw.config(bg=g.COL['error']) if 512 % ybin != 0: status = False ybinw.config(bg=g.COL['error']) if not self.quad_frame.winfo_ismapped(): self.drift_frame.grid_forget() self.quad_frame.grid(row=10, column=0, columnspan=3, sticky=tk.W+tk.N) self.clearLab.config(state='normal') if g.cpars['telins_name'] == 'GTC': self.nodLab.config(state='normal') else: self.nodLab.config(state='disable') if not self.frozen: self.oscany.config(state='normal') self.oscan.config(state='normal') self.clear.config(state='normal') if g.cpars['telins_name'] == 'GTC': self.nod.config(state='normal') else: self.nod.config(state='disable') self.wframe.disable() else: self.clearLab.config(state='normal') if g.cpars['telins_name'] == 'GTC': self.nodLab.config(state='normal') else: self.nodLab.config(state='disable') if not self.quad_frame.winfo_ismapped(): self.drift_frame.grid_forget() self.quad_frame.grid(row=10, column=0, columnspan=3, sticky=tk.W+tk.N) if not self.frozen: self.oscany.config(state='disable') self.oscan.config(state='normal') self.clear.config(state='normal') if g.cpars['telins_name'] == 'GTC': self.nod.config(state='normal') else: self.nod.config(state='disable') self.wframe.enable() status = self.wframe.check() # exposure delay if self.expose.ok(): self.expose.config(bg=g.COL['main']) else: self.expose.config(bg=g.COL['warn']) status = False # don't allow binning other than 1, 2 in overscan or prescan mode if self.oscan() or self.oscany(): if xbin not in (1, 2): status = False xbinw.config(bg=g.COL['error']) if ybin not in (1, 2): status = False ybinw.config(bg=g.COL['error']) # disable clear if nodding enabled. re-enable if not drift if not self.frozen: if self.nod() or self.nodPattern: self.clear.config(state='disabled') self.clearLab.config(state='disabled') elif not self.isDrift(): self.clear.config(state='normal') self.clearLab.config(state='normal') # allow posting if parameters are OK. update count and SN estimates too if status: if (g.cpars['hcam_server_on'] and g.cpars['eso_server_online'] and g.observe.start['state'] == 'disabled' and not isRunActive(g)): g.observe.start.enable() g.count.update() else: g.observe.start.disable() return status
[ "def", "check", "(", "self", ",", "*", "args", ")", ":", "status", "=", "True", "g", "=", "get_root", "(", "self", ")", ".", "globals", "# clear errors on binning (may be set later if FF)", "xbinw", ",", "ybinw", "=", "self", ".", "wframe", ".", "xbin", ",...
Callback to check validity of instrument parameters. Performs the following tasks: - spots and flags overlapping windows or null window parameters - flags windows with invalid dimensions given the binning parameter - sets the correct number of enabled windows - disables or enables clear and nod buttons depending on drift mode or not - checks for window synchronisation, enabling sync button if required - enables or disables start button if settings are OK Returns ------- status : bool True or False according to whether the settings are OK.
[ "Callback", "to", "check", "validity", "of", "instrument", "parameters", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/hcam.py#L573-L717
train
HiPERCAM/hcam_widgets
hcam_widgets/hcam.py
InstPars.freeze
def freeze(self): """ Freeze all settings so they cannot be altered """ self.app.disable() self.clear.disable() self.nod.disable() self.led.disable() self.dummy.disable() self.readSpeed.disable() self.expose.disable() self.number.disable() self.wframe.disable(everything=True) self.nmult.disable() self.frozen = True
python
def freeze(self): """ Freeze all settings so they cannot be altered """ self.app.disable() self.clear.disable() self.nod.disable() self.led.disable() self.dummy.disable() self.readSpeed.disable() self.expose.disable() self.number.disable() self.wframe.disable(everything=True) self.nmult.disable() self.frozen = True
[ "def", "freeze", "(", "self", ")", ":", "self", ".", "app", ".", "disable", "(", ")", "self", ".", "clear", ".", "disable", "(", ")", "self", ".", "nod", ".", "disable", "(", ")", "self", ".", "led", ".", "disable", "(", ")", "self", ".", "dumm...
Freeze all settings so they cannot be altered
[ "Freeze", "all", "settings", "so", "they", "cannot", "be", "altered" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/hcam.py#L719-L733
train
HiPERCAM/hcam_widgets
hcam_widgets/hcam.py
InstPars.unfreeze
def unfreeze(self): """ Reverse of freeze """ self.app.enable() self.clear.enable() self.nod.enable() self.led.enable() self.dummy.enable() self.readSpeed.enable() self.expose.enable() self.number.enable() self.wframe.enable() self.nmult.enable() self.frozen = False
python
def unfreeze(self): """ Reverse of freeze """ self.app.enable() self.clear.enable() self.nod.enable() self.led.enable() self.dummy.enable() self.readSpeed.enable() self.expose.enable() self.number.enable() self.wframe.enable() self.nmult.enable() self.frozen = False
[ "def", "unfreeze", "(", "self", ")", ":", "self", ".", "app", ".", "enable", "(", ")", "self", ".", "clear", ".", "enable", "(", ")", "self", ".", "nod", ".", "enable", "(", ")", "self", ".", "led", ".", "enable", "(", ")", "self", ".", "dummy"...
Reverse of freeze
[ "Reverse", "of", "freeze" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/hcam.py#L735-L749
train
HiPERCAM/hcam_widgets
hcam_widgets/hcam.py
InstPars.getRtplotWins
def getRtplotWins(self): """" Returns a string suitable to sending off to rtplot when it asks for window parameters. Returns null string '' if the windows are not OK. This operates on the basis of trying to send something back, even if it might not be OK as a window setup. Note that we have to take care here not to update any GUI components because this is called outside of the main thread. """ try: if self.isFF(): return 'fullframe\r\n' elif self.isDrift(): xbin = self.wframe.xbin.value() ybin = self.wframe.ybin.value() nwin = 2*self.wframe.npair.value() ret = str(xbin) + ' ' + str(ybin) + ' ' + str(nwin) + '\r\n' for xsl, xsr, ys, nx, ny in self.wframe: ret += '{:d} {:d} {:d} {:d}\r\n'.format( xsl, ys, nx, ny ) ret += '{:d} {:d} {:d} {:d}'.format( xsr, ys, nx, ny ) return ret else: xbin = self.wframe.xbin.value() ybin = self.wframe.ybin.value() nwin = 4*self.wframe.nquad.value() ret = str(xbin) + ' ' + str(ybin) + ' ' + str(nwin) + '\r\n' for xsll, xsul, xslr, xsur, ys, nx, ny in self.wframe: ret += '{:d} {:d} {:d} {:d}\r\n'.format( xsll, ys, nx, ny ) ret += '{:d} {:d} {:d} {:d}\r\n'.format( xsul, 1025 - ys - ny, nx, ny ) ret += '{:d} {:d} {:d} {:d}\r\n'.format( xslr, ys, nx, ny ) ret += '{:d} {:d} {:d} {:d}\r\n'.format( xsur, 1025 - ys - ny, nx, ny ) return ret except: return ''
python
def getRtplotWins(self): """" Returns a string suitable to sending off to rtplot when it asks for window parameters. Returns null string '' if the windows are not OK. This operates on the basis of trying to send something back, even if it might not be OK as a window setup. Note that we have to take care here not to update any GUI components because this is called outside of the main thread. """ try: if self.isFF(): return 'fullframe\r\n' elif self.isDrift(): xbin = self.wframe.xbin.value() ybin = self.wframe.ybin.value() nwin = 2*self.wframe.npair.value() ret = str(xbin) + ' ' + str(ybin) + ' ' + str(nwin) + '\r\n' for xsl, xsr, ys, nx, ny in self.wframe: ret += '{:d} {:d} {:d} {:d}\r\n'.format( xsl, ys, nx, ny ) ret += '{:d} {:d} {:d} {:d}'.format( xsr, ys, nx, ny ) return ret else: xbin = self.wframe.xbin.value() ybin = self.wframe.ybin.value() nwin = 4*self.wframe.nquad.value() ret = str(xbin) + ' ' + str(ybin) + ' ' + str(nwin) + '\r\n' for xsll, xsul, xslr, xsur, ys, nx, ny in self.wframe: ret += '{:d} {:d} {:d} {:d}\r\n'.format( xsll, ys, nx, ny ) ret += '{:d} {:d} {:d} {:d}\r\n'.format( xsul, 1025 - ys - ny, nx, ny ) ret += '{:d} {:d} {:d} {:d}\r\n'.format( xslr, ys, nx, ny ) ret += '{:d} {:d} {:d} {:d}\r\n'.format( xsur, 1025 - ys - ny, nx, ny ) return ret except: return ''
[ "def", "getRtplotWins", "(", "self", ")", ":", "try", ":", "if", "self", ".", "isFF", "(", ")", ":", "return", "'fullframe\\r\\n'", "elif", "self", ".", "isDrift", "(", ")", ":", "xbin", "=", "self", ".", "wframe", ".", "xbin", ".", "value", "(", "...
Returns a string suitable to sending off to rtplot when it asks for window parameters. Returns null string '' if the windows are not OK. This operates on the basis of trying to send something back, even if it might not be OK as a window setup. Note that we have to take care here not to update any GUI components because this is called outside of the main thread.
[ "Returns", "a", "string", "suitable", "to", "sending", "off", "to", "rtplot", "when", "it", "asks", "for", "window", "parameters", ".", "Returns", "null", "string", "if", "the", "windows", "are", "not", "OK", ".", "This", "operates", "on", "the", "basis", ...
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/hcam.py#L751-L797
train
HiPERCAM/hcam_widgets
hcam_widgets/hcam.py
InstPars.timing
def timing(self): """ Estimates timing information for the current setup. You should run a check on the instrument parameters before calling this. Returns: (expTime, deadTime, cycleTime, dutyCycle) expTime : exposure time per frame (seconds) deadTime : dead time per frame (seconds) cycleTime : sampling time (cadence), (seconds) dutyCycle : percentage time exposing. frameRate : number of frames per second """ # drift mode y/n? isDriftMode = self.isDrift() # FF y/n? isFF = self.isFF() # Set the readout speed readSpeed = self.readSpeed() if readSpeed == 'Fast' and self.dummy(): video = VIDEO_FAST elif readSpeed == 'Slow' and self.dummy(): video = VIDEO_SLOW elif not self.dummy(): video = VIDEO_SLOW_SE else: raise DriverError('InstPars.timing: readout speed = ' + readSpeed + ' not recognised.') if self.fastClk(): DUMP_TIME = DUMP_TIME_FAST VCLOCK_FRAME = VCLOCK_FAST VCLOCK_STORAGE = VCLOCK_FAST HCLOCK = HCLOCK_FAST else: DUMP_TIME = DUMP_TIME_SLOW VCLOCK_FRAME = VCLOCK_FRAME_SLOW VCLOCK_STORAGE = VCLOCK_STORAGE_SLOW HCLOCK = HCLOCK_SLOW # clear chip on/off? lclear = not isDriftMode and self.clear() # overscan read or not oscan = not isDriftMode and self.oscan() oscany = not isDriftMode and self.oscany() # get exposure delay expose = self.expose.value() # window parameters xbin = self.wframe.xbin.value() ybin = self.wframe.ybin.value() if isDriftMode: nwin = 1 # number of windows per output dys = self.wframe.ys[0].value() - 1 dnx = self.wframe.nx[0].value() dny = self.wframe.ny[0].value() dxsl = self.wframe.xsl[0].value() dxsr = self.wframe.xsr[0].value() # differential shift needed to line both # windows up with the edge of the chip diffshift = abs(dxsl - 1 - (2*FFX - dxsr - dnx + 1)) elif isFF: nwin = 1 ys, nx, ny = [0], [1024], [512] else: ys, nx, ny = [], [], [] xse, xsf, xsg, xsh = [], [], [], [] nwin = self.wframe.nquad.value() for xsll, xsul, xslr, xsur, ysv, nxv, nyv in self.wframe: xse.append(xsll - 1) xsf.append(2049 - xslr - nxv) xsg.append(2049 - xsur - nxv) xsh.append(xsul - 1) ys.append(ysv-1) nx.append(nxv) ny.append(nyv) # convert timing parameters to seconds expose_delay = expose # clear chip by VCLOCK-ing the image and area and dumping storage area (x5) if lclear: clear_time = 5*(FFY*VCLOCK_FRAME + FFY*DUMP_TIME) else: clear_time = 0.0 if isDriftMode: # for drift mode, we need the number of windows in the pipeline # and the pipeshift nrows = FFY # number of rows in storage area pnwin = int(((nrows / dny) + 1)/2) pshift = nrows - (2*pnwin-1)*dny frame_transfer = (dny+dys)*VCLOCK_FRAME yshift = [dys*VCLOCK_STORAGE] # After placing the window adjacent to the serial register, the # register must be cleared by clocking out the entire register, # taking FFX hclocks. line_clear = [0.] if yshift[0] != 0: line_clear[0] = DUMP_TIME # to calculate number of HCLOCKS needed to read a line in # drift mode we have to account for the diff shifts and dumping. # first perform diff shifts # for now we need this *2 (for quadrants E, H or F, G) numhclocks = 2*diffshift # now add the amount of clocks needed to get # both windows to edge of chip if dxsl - 1 > 2*FFX - dxsr - dnx + 1: # it was the left window that got the diff shift, # so the number of hclocks increases by the amount # needed to get the RH window to the edge numhclocks += 2*FFX - dxsr - dnx + 1 else: # vice versa numhclocks += dxsl - 1 # now we actually clock the windows themselves numhclocks += dnx # finally, we need to hclock the additional pre-scan pixels numhclocks += 2*PRSCX # here is the total time to read the whole line line_read = [VCLOCK_STORAGE*ybin + numhclocks*HCLOCK + video*dnx/xbin + DUMP_TIME + 2*SETUP_READ] readout = [(dny/ybin) * line_read[0]] elif isFF: # move entire image into storage area frame_transfer = FFY*VCLOCK_FRAME + DUMP_TIME yshift = [0] line_clear = [0] numhclocks = FFX + PRSCX line_read = [VCLOCK_STORAGE*ybin + numhclocks*HCLOCK + video*nx[0]/xbin + SETUP_READ] if oscan: line_read[0] += video*PRSCX/xbin nlines = ny[0]/ybin if not oscany else (ny[0] + 8/ybin) readout = [nlines*line_read[0]] else: # windowed mode # move entire image into storage area frame_transfer = FFY*VCLOCK_FRAME + DUMP_TIME # dump rows in storage area up to start of the window without changing the # image area. yshift = nwin*[0.] yshift[0] = ys[0]*DUMP_TIME for nw in range(1, nwin): yshift[nw] = (ys[nw]-ys[nw-1]-ny[nw-1])*DUMP_TIME line_clear = nwin*[0.] # Naidu always dumps the serial register, in windowed mode # regardless of whether we need to or not for nw in range(nwin): line_clear[nw] = DUMP_TIME # calculate how long it takes to shift one row into the serial # register shift along serial register and then read out the data. # total number of hclocks needs to account for diff shifts of # windows, carried out in serial numhclocks = nwin*[0] for nw in range(nwin): common_shift = min(xse[nw], xsf[nw], xsg[nw], xsh[nw]) diffshifts = sum((xs-common_shift for xs in (xse[nw], xsf[nw], xsg[nw], xsh[nw]))) numhclocks[nw] = 2*PRSCX + common_shift + diffshifts + nx[nw] line_read = nwin*[0.] # line read includes vclocking a row, all the hclocks, digitising pixels and dumping serial register # when windows are read out. for nw in range(nwin): line_read[nw] = (VCLOCK_STORAGE*ybin + numhclocks[nw]*HCLOCK + video*nx[nw]/xbin + 2*SETUP_READ + DUMP_TIME) if oscan: line_read[nw] += video*PRSCX/xbin # multiply time to shift one row into serial register by # number of rows for total readout time readout = nwin*[0.] for nw in range(nwin): nlines = ny[nw]/ybin if not oscany else (ny[nw] + 8/ybin) readout[nw] = nlines * line_read[nw] # now get the total time to read out one exposure. cycleTime = expose_delay + clear_time + frame_transfer if isDriftMode: cycleTime += pshift*VCLOCK_STORAGE + yshift[0] + line_clear[0] + readout[0] else: for nw in range(nwin): cycleTime += yshift[nw] + line_clear[nw] + readout[nw] # use 5sec estimate for nod time # TODO: replace with accurate estimate if self.nod() and lclear: cycleTime += 5 elif self.nod(): g = get_root(self).globals g.clog.warn('ERR: dithering enabled with clear mode off') frameRate = 1.0/cycleTime expTime = expose_delay if lclear else cycleTime - frame_transfer deadTime = cycleTime - expTime dutyCycle = 100.0*expTime/cycleTime return (expTime, deadTime, cycleTime, dutyCycle, frameRate)
python
def timing(self): """ Estimates timing information for the current setup. You should run a check on the instrument parameters before calling this. Returns: (expTime, deadTime, cycleTime, dutyCycle) expTime : exposure time per frame (seconds) deadTime : dead time per frame (seconds) cycleTime : sampling time (cadence), (seconds) dutyCycle : percentage time exposing. frameRate : number of frames per second """ # drift mode y/n? isDriftMode = self.isDrift() # FF y/n? isFF = self.isFF() # Set the readout speed readSpeed = self.readSpeed() if readSpeed == 'Fast' and self.dummy(): video = VIDEO_FAST elif readSpeed == 'Slow' and self.dummy(): video = VIDEO_SLOW elif not self.dummy(): video = VIDEO_SLOW_SE else: raise DriverError('InstPars.timing: readout speed = ' + readSpeed + ' not recognised.') if self.fastClk(): DUMP_TIME = DUMP_TIME_FAST VCLOCK_FRAME = VCLOCK_FAST VCLOCK_STORAGE = VCLOCK_FAST HCLOCK = HCLOCK_FAST else: DUMP_TIME = DUMP_TIME_SLOW VCLOCK_FRAME = VCLOCK_FRAME_SLOW VCLOCK_STORAGE = VCLOCK_STORAGE_SLOW HCLOCK = HCLOCK_SLOW # clear chip on/off? lclear = not isDriftMode and self.clear() # overscan read or not oscan = not isDriftMode and self.oscan() oscany = not isDriftMode and self.oscany() # get exposure delay expose = self.expose.value() # window parameters xbin = self.wframe.xbin.value() ybin = self.wframe.ybin.value() if isDriftMode: nwin = 1 # number of windows per output dys = self.wframe.ys[0].value() - 1 dnx = self.wframe.nx[0].value() dny = self.wframe.ny[0].value() dxsl = self.wframe.xsl[0].value() dxsr = self.wframe.xsr[0].value() # differential shift needed to line both # windows up with the edge of the chip diffshift = abs(dxsl - 1 - (2*FFX - dxsr - dnx + 1)) elif isFF: nwin = 1 ys, nx, ny = [0], [1024], [512] else: ys, nx, ny = [], [], [] xse, xsf, xsg, xsh = [], [], [], [] nwin = self.wframe.nquad.value() for xsll, xsul, xslr, xsur, ysv, nxv, nyv in self.wframe: xse.append(xsll - 1) xsf.append(2049 - xslr - nxv) xsg.append(2049 - xsur - nxv) xsh.append(xsul - 1) ys.append(ysv-1) nx.append(nxv) ny.append(nyv) # convert timing parameters to seconds expose_delay = expose # clear chip by VCLOCK-ing the image and area and dumping storage area (x5) if lclear: clear_time = 5*(FFY*VCLOCK_FRAME + FFY*DUMP_TIME) else: clear_time = 0.0 if isDriftMode: # for drift mode, we need the number of windows in the pipeline # and the pipeshift nrows = FFY # number of rows in storage area pnwin = int(((nrows / dny) + 1)/2) pshift = nrows - (2*pnwin-1)*dny frame_transfer = (dny+dys)*VCLOCK_FRAME yshift = [dys*VCLOCK_STORAGE] # After placing the window adjacent to the serial register, the # register must be cleared by clocking out the entire register, # taking FFX hclocks. line_clear = [0.] if yshift[0] != 0: line_clear[0] = DUMP_TIME # to calculate number of HCLOCKS needed to read a line in # drift mode we have to account for the diff shifts and dumping. # first perform diff shifts # for now we need this *2 (for quadrants E, H or F, G) numhclocks = 2*diffshift # now add the amount of clocks needed to get # both windows to edge of chip if dxsl - 1 > 2*FFX - dxsr - dnx + 1: # it was the left window that got the diff shift, # so the number of hclocks increases by the amount # needed to get the RH window to the edge numhclocks += 2*FFX - dxsr - dnx + 1 else: # vice versa numhclocks += dxsl - 1 # now we actually clock the windows themselves numhclocks += dnx # finally, we need to hclock the additional pre-scan pixels numhclocks += 2*PRSCX # here is the total time to read the whole line line_read = [VCLOCK_STORAGE*ybin + numhclocks*HCLOCK + video*dnx/xbin + DUMP_TIME + 2*SETUP_READ] readout = [(dny/ybin) * line_read[0]] elif isFF: # move entire image into storage area frame_transfer = FFY*VCLOCK_FRAME + DUMP_TIME yshift = [0] line_clear = [0] numhclocks = FFX + PRSCX line_read = [VCLOCK_STORAGE*ybin + numhclocks*HCLOCK + video*nx[0]/xbin + SETUP_READ] if oscan: line_read[0] += video*PRSCX/xbin nlines = ny[0]/ybin if not oscany else (ny[0] + 8/ybin) readout = [nlines*line_read[0]] else: # windowed mode # move entire image into storage area frame_transfer = FFY*VCLOCK_FRAME + DUMP_TIME # dump rows in storage area up to start of the window without changing the # image area. yshift = nwin*[0.] yshift[0] = ys[0]*DUMP_TIME for nw in range(1, nwin): yshift[nw] = (ys[nw]-ys[nw-1]-ny[nw-1])*DUMP_TIME line_clear = nwin*[0.] # Naidu always dumps the serial register, in windowed mode # regardless of whether we need to or not for nw in range(nwin): line_clear[nw] = DUMP_TIME # calculate how long it takes to shift one row into the serial # register shift along serial register and then read out the data. # total number of hclocks needs to account for diff shifts of # windows, carried out in serial numhclocks = nwin*[0] for nw in range(nwin): common_shift = min(xse[nw], xsf[nw], xsg[nw], xsh[nw]) diffshifts = sum((xs-common_shift for xs in (xse[nw], xsf[nw], xsg[nw], xsh[nw]))) numhclocks[nw] = 2*PRSCX + common_shift + diffshifts + nx[nw] line_read = nwin*[0.] # line read includes vclocking a row, all the hclocks, digitising pixels and dumping serial register # when windows are read out. for nw in range(nwin): line_read[nw] = (VCLOCK_STORAGE*ybin + numhclocks[nw]*HCLOCK + video*nx[nw]/xbin + 2*SETUP_READ + DUMP_TIME) if oscan: line_read[nw] += video*PRSCX/xbin # multiply time to shift one row into serial register by # number of rows for total readout time readout = nwin*[0.] for nw in range(nwin): nlines = ny[nw]/ybin if not oscany else (ny[nw] + 8/ybin) readout[nw] = nlines * line_read[nw] # now get the total time to read out one exposure. cycleTime = expose_delay + clear_time + frame_transfer if isDriftMode: cycleTime += pshift*VCLOCK_STORAGE + yshift[0] + line_clear[0] + readout[0] else: for nw in range(nwin): cycleTime += yshift[nw] + line_clear[nw] + readout[nw] # use 5sec estimate for nod time # TODO: replace with accurate estimate if self.nod() and lclear: cycleTime += 5 elif self.nod(): g = get_root(self).globals g.clog.warn('ERR: dithering enabled with clear mode off') frameRate = 1.0/cycleTime expTime = expose_delay if lclear else cycleTime - frame_transfer deadTime = cycleTime - expTime dutyCycle = 100.0*expTime/cycleTime return (expTime, deadTime, cycleTime, dutyCycle, frameRate)
[ "def", "timing", "(", "self", ")", ":", "# drift mode y/n?", "isDriftMode", "=", "self", ".", "isDrift", "(", ")", "# FF y/n?", "isFF", "=", "self", ".", "isFF", "(", ")", "# Set the readout speed", "readSpeed", "=", "self", ".", "readSpeed", "(", ")", "if...
Estimates timing information for the current setup. You should run a check on the instrument parameters before calling this. Returns: (expTime, deadTime, cycleTime, dutyCycle) expTime : exposure time per frame (seconds) deadTime : dead time per frame (seconds) cycleTime : sampling time (cadence), (seconds) dutyCycle : percentage time exposing. frameRate : number of frames per second
[ "Estimates", "timing", "information", "for", "the", "current", "setup", ".", "You", "should", "run", "a", "check", "on", "the", "instrument", "parameters", "before", "calling", "this", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/hcam.py#L799-L1009
train
HiPERCAM/hcam_widgets
hcam_widgets/hcam.py
RunPars.loadJSON
def loadJSON(self, json_string): """ Sets the values of the run parameters given an JSON string """ g = get_root(self).globals user = json.loads(json_string)['user'] def setField(widget, field): val = user.get(field) if val is not None: widget.set(val) setField(self.prog_ob.obid, 'OB') setField(self.target, 'target') setField(self.prog_ob.progid, 'ID') setField(self.pi, 'PI') setField(self.observers, 'Observers') setField(self.comment, 'comment') setField(self.filter, 'filters') setField(g.observe.rtype, 'flags')
python
def loadJSON(self, json_string): """ Sets the values of the run parameters given an JSON string """ g = get_root(self).globals user = json.loads(json_string)['user'] def setField(widget, field): val = user.get(field) if val is not None: widget.set(val) setField(self.prog_ob.obid, 'OB') setField(self.target, 'target') setField(self.prog_ob.progid, 'ID') setField(self.pi, 'PI') setField(self.observers, 'Observers') setField(self.comment, 'comment') setField(self.filter, 'filters') setField(g.observe.rtype, 'flags')
[ "def", "loadJSON", "(", "self", ",", "json_string", ")", ":", "g", "=", "get_root", "(", "self", ")", ".", "globals", "user", "=", "json", ".", "loads", "(", "json_string", ")", "[", "'user'", "]", "def", "setField", "(", "widget", ",", "field", ")",...
Sets the values of the run parameters given an JSON string
[ "Sets", "the", "values", "of", "the", "run", "parameters", "given", "an", "JSON", "string" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/hcam.py#L1075-L1094
train
HiPERCAM/hcam_widgets
hcam_widgets/hcam.py
RunPars.dumpJSON
def dumpJSON(self): """ Encodes current parameters to JSON compatible dictionary """ g = get_root(self).globals dtype = g.observe.rtype() if dtype == 'bias': target = 'BIAS' elif dtype == 'flat': target = 'FLAT' elif dtype == 'dark': target = 'DARK' else: target = self.target.value() return dict( target=target, ID=self.prog_ob.progid.value(), PI=self.pi.value(), OB='{:04d}'.format(self.prog_ob.obid.value()), Observers=self.observers.value(), comment=self.comment.value(), flags=dtype, filters=self.filter.value() )
python
def dumpJSON(self): """ Encodes current parameters to JSON compatible dictionary """ g = get_root(self).globals dtype = g.observe.rtype() if dtype == 'bias': target = 'BIAS' elif dtype == 'flat': target = 'FLAT' elif dtype == 'dark': target = 'DARK' else: target = self.target.value() return dict( target=target, ID=self.prog_ob.progid.value(), PI=self.pi.value(), OB='{:04d}'.format(self.prog_ob.obid.value()), Observers=self.observers.value(), comment=self.comment.value(), flags=dtype, filters=self.filter.value() )
[ "def", "dumpJSON", "(", "self", ")", ":", "g", "=", "get_root", "(", "self", ")", ".", "globals", "dtype", "=", "g", ".", "observe", ".", "rtype", "(", ")", "if", "dtype", "==", "'bias'", ":", "target", "=", "'BIAS'", "elif", "dtype", "==", "'flat'...
Encodes current parameters to JSON compatible dictionary
[ "Encodes", "current", "parameters", "to", "JSON", "compatible", "dictionary" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/hcam.py#L1096-L1120
train
HiPERCAM/hcam_widgets
hcam_widgets/hcam.py
RunPars.check
def check(self, *args): """ Checks the validity of the run parameters. Returns flag (True = OK), and a message which indicates the nature of the problem if the flag is False. """ ok = True msg = '' g = get_root(self).globals dtype = g.observe.rtype() expert = g.cpars['expert_level'] > 0 if dtype == 'bias' or dtype == 'flat' or dtype == 'dark': self.pi.configure(state='disable') self.prog_ob.configure(state='disable') self.target.disable() else: if expert: self.pi.configure(state='normal') self.prog_ob.configure(state='normal') self.prog_ob.enable() else: self.prog_ob.configure(state='disable') self.pi.configure(state='disable') self.prog_ob.disable() self.target.enable() if g.cpars['require_run_params']: if self.target.ok(): self.target.entry.config(bg=g.COL['main']) else: self.target.entry.config(bg=g.COL['error']) ok = False msg += 'Target name field cannot be blank\n' if dtype == 'data caution' or \ dtype == 'data' or dtype == 'technical': if self.prog_ob.ok(): self.prog_ob.config(bg=g.COL['main']) else: self.prog_ob.config(bg=g.COL['error']) ok = False msg += 'Programme or OB ID field cannot be blank\n' if self.pi.ok(): self.pi.config(bg=g.COL['main']) else: self.pi.config(bg=g.COL['error']) ok = False msg += 'Principal Investigator field cannot be blank\n' if self.observers.ok(): self.observers.config(bg=g.COL['main']) else: self.observers.config(bg=g.COL['error']) ok = False msg += 'Observers field cannot be blank' return (ok, msg)
python
def check(self, *args): """ Checks the validity of the run parameters. Returns flag (True = OK), and a message which indicates the nature of the problem if the flag is False. """ ok = True msg = '' g = get_root(self).globals dtype = g.observe.rtype() expert = g.cpars['expert_level'] > 0 if dtype == 'bias' or dtype == 'flat' or dtype == 'dark': self.pi.configure(state='disable') self.prog_ob.configure(state='disable') self.target.disable() else: if expert: self.pi.configure(state='normal') self.prog_ob.configure(state='normal') self.prog_ob.enable() else: self.prog_ob.configure(state='disable') self.pi.configure(state='disable') self.prog_ob.disable() self.target.enable() if g.cpars['require_run_params']: if self.target.ok(): self.target.entry.config(bg=g.COL['main']) else: self.target.entry.config(bg=g.COL['error']) ok = False msg += 'Target name field cannot be blank\n' if dtype == 'data caution' or \ dtype == 'data' or dtype == 'technical': if self.prog_ob.ok(): self.prog_ob.config(bg=g.COL['main']) else: self.prog_ob.config(bg=g.COL['error']) ok = False msg += 'Programme or OB ID field cannot be blank\n' if self.pi.ok(): self.pi.config(bg=g.COL['main']) else: self.pi.config(bg=g.COL['error']) ok = False msg += 'Principal Investigator field cannot be blank\n' if self.observers.ok(): self.observers.config(bg=g.COL['main']) else: self.observers.config(bg=g.COL['error']) ok = False msg += 'Observers field cannot be blank' return (ok, msg)
[ "def", "check", "(", "self", ",", "*", "args", ")", ":", "ok", "=", "True", "msg", "=", "''", "g", "=", "get_root", "(", "self", ")", ".", "globals", "dtype", "=", "g", ".", "observe", ".", "rtype", "(", ")", "expert", "=", "g", ".", "cpars", ...
Checks the validity of the run parameters. Returns flag (True = OK), and a message which indicates the nature of the problem if the flag is False.
[ "Checks", "the", "validity", "of", "the", "run", "parameters", ".", "Returns", "flag", "(", "True", "=", "OK", ")", "and", "a", "message", "which", "indicates", "the", "nature", "of", "the", "problem", "if", "the", "flag", "is", "False", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/hcam.py#L1122-L1181
train
HiPERCAM/hcam_widgets
hcam_widgets/hcam.py
RunPars.freeze
def freeze(self): """ Freeze all settings so that they can't be altered """ self.target.disable() self.filter.configure(state='disable') self.prog_ob.configure(state='disable') self.pi.configure(state='disable') self.observers.configure(state='disable') self.comment.configure(state='disable')
python
def freeze(self): """ Freeze all settings so that they can't be altered """ self.target.disable() self.filter.configure(state='disable') self.prog_ob.configure(state='disable') self.pi.configure(state='disable') self.observers.configure(state='disable') self.comment.configure(state='disable')
[ "def", "freeze", "(", "self", ")", ":", "self", ".", "target", ".", "disable", "(", ")", "self", ".", "filter", ".", "configure", "(", "state", "=", "'disable'", ")", "self", ".", "prog_ob", ".", "configure", "(", "state", "=", "'disable'", ")", "sel...
Freeze all settings so that they can't be altered
[ "Freeze", "all", "settings", "so", "that", "they", "can", "t", "be", "altered" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/hcam.py#L1195-L1204
train
HiPERCAM/hcam_widgets
hcam_widgets/hcam.py
RunPars.unfreeze
def unfreeze(self): """ Unfreeze all settings so that they can be altered """ g = get_root(self).globals self.filter.configure(state='normal') dtype = g.observe.rtype() if dtype == 'data caution' or dtype == 'data' or dtype == 'technical': self.prog_ob.configure(state='normal') self.pi.configure(state='normal') self.target.enable() self.observers.configure(state='normal') self.comment.configure(state='normal')
python
def unfreeze(self): """ Unfreeze all settings so that they can be altered """ g = get_root(self).globals self.filter.configure(state='normal') dtype = g.observe.rtype() if dtype == 'data caution' or dtype == 'data' or dtype == 'technical': self.prog_ob.configure(state='normal') self.pi.configure(state='normal') self.target.enable() self.observers.configure(state='normal') self.comment.configure(state='normal')
[ "def", "unfreeze", "(", "self", ")", ":", "g", "=", "get_root", "(", "self", ")", ".", "globals", "self", ".", "filter", ".", "configure", "(", "state", "=", "'normal'", ")", "dtype", "=", "g", ".", "observe", ".", "rtype", "(", ")", "if", "dtype",...
Unfreeze all settings so that they can be altered
[ "Unfreeze", "all", "settings", "so", "that", "they", "can", "be", "altered" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/hcam.py#L1206-L1218
train
HiPERCAM/hcam_widgets
hcam_widgets/hcam.py
CountsFrame.checkUpdate
def checkUpdate(self, *args): """ Updates values after first checking instrument parameters are OK. This is not integrated within update to prevent ifinite recursion since update gets called from ipars. """ g = get_root(self).globals if not self.check(): g.clog.warn('Current observing parameters are not valid.') return False if not g.ipars.check(): g.clog.warn('Current instrument parameters are not valid.') return False
python
def checkUpdate(self, *args): """ Updates values after first checking instrument parameters are OK. This is not integrated within update to prevent ifinite recursion since update gets called from ipars. """ g = get_root(self).globals if not self.check(): g.clog.warn('Current observing parameters are not valid.') return False if not g.ipars.check(): g.clog.warn('Current instrument parameters are not valid.') return False
[ "def", "checkUpdate", "(", "self", ",", "*", "args", ")", ":", "g", "=", "get_root", "(", "self", ")", ".", "globals", "if", "not", "self", ".", "check", "(", ")", ":", "g", ".", "clog", ".", "warn", "(", "'Current observing parameters are not valid.'", ...
Updates values after first checking instrument parameters are OK. This is not integrated within update to prevent ifinite recursion since update gets called from ipars.
[ "Updates", "values", "after", "first", "checking", "instrument", "parameters", "are", "OK", ".", "This", "is", "not", "integrated", "within", "update", "to", "prevent", "ifinite", "recursion", "since", "update", "gets", "called", "from", "ipars", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/hcam.py#L1314-L1327
train
HiPERCAM/hcam_widgets
hcam_widgets/hcam.py
CountsFrame.check
def check(self): """ Checks values """ status = True g = get_root(self).globals if self.mag.ok(): self.mag.config(bg=g.COL['main']) else: self.mag.config(bg=g.COL['warn']) status = False if self.airmass.ok(): self.airmass.config(bg=g.COL['main']) else: self.airmass.config(bg=g.COL['warn']) status = False if self.seeing.ok(): self.seeing.config(bg=g.COL['main']) else: self.seeing.config(bg=g.COL['warn']) status = False return status
python
def check(self): """ Checks values """ status = True g = get_root(self).globals if self.mag.ok(): self.mag.config(bg=g.COL['main']) else: self.mag.config(bg=g.COL['warn']) status = False if self.airmass.ok(): self.airmass.config(bg=g.COL['main']) else: self.airmass.config(bg=g.COL['warn']) status = False if self.seeing.ok(): self.seeing.config(bg=g.COL['main']) else: self.seeing.config(bg=g.COL['warn']) status = False return status
[ "def", "check", "(", "self", ")", ":", "status", "=", "True", "g", "=", "get_root", "(", "self", ")", ".", "globals", "if", "self", ".", "mag", ".", "ok", "(", ")", ":", "self", ".", "mag", ".", "config", "(", "bg", "=", "g", ".", "COL", "[",...
Checks values
[ "Checks", "values" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/hcam.py#L1329-L1353
train
HiPERCAM/hcam_widgets
hcam_widgets/hcam.py
CountsFrame.update
def update(self, *args): """ Updates values. You should run a check on the instrument and target parameters before calling this. """ g = get_root(self).globals expTime, deadTime, cycleTime, dutyCycle, frameRate = g.ipars.timing() total, peak, peakSat, peakWarn, ston, ston3 = \ self.counts(expTime, cycleTime) if cycleTime < 0.01: self.cadence.config(text='{0:7.5f} s'.format(cycleTime)) elif cycleTime < 0.1: self.cadence.config(text='{0:6.4f} s'.format(cycleTime)) elif cycleTime < 1.: self.cadence.config(text='{0:5.3f} s'.format(cycleTime)) elif cycleTime < 10.: self.cadence.config(text='{0:4.2f} s'.format(cycleTime)) elif cycleTime < 100.: self.cadence.config(text='{0:4.1f} s'.format(cycleTime)) elif cycleTime < 1000.: self.cadence.config(text='{0:4.0f} s'.format(cycleTime)) else: self.cadence.config(text='{0:5.0f} s'.format(cycleTime)) if expTime < 0.01: self.exposure.config(text='{0:7.5f} s'.format(expTime)) elif expTime < 0.1: self.exposure.config(text='{0:6.4f} s'.format(expTime)) elif expTime < 1.: self.exposure.config(text='{0:5.3f} s'.format(expTime)) elif expTime < 10.: self.exposure.config(text='{0:4.2f} s'.format(expTime)) elif expTime < 100.: self.exposure.config(text='{0:4.1f} s'.format(expTime)) elif expTime < 1000.: self.exposure.config(text='{0:4.0f} s'.format(expTime)) else: self.exposure.config(text='{0:5.0f} s'.format(expTime)) self.duty.config(text='{0:4.1f} %'.format(dutyCycle)) self.peak.config(text='{0:d} cts'.format(int(round(peak)))) if peakSat: self.peak.config(bg=g.COL['error']) elif peakWarn: self.peak.config(bg=g.COL['warn']) else: self.peak.config(bg=g.COL['main']) self.total.config(text='{0:d} cts'.format(int(round(total)))) self.ston.config(text='{0:.1f}'.format(ston)) self.ston3.config(text='{0:.1f}'.format(ston3))
python
def update(self, *args): """ Updates values. You should run a check on the instrument and target parameters before calling this. """ g = get_root(self).globals expTime, deadTime, cycleTime, dutyCycle, frameRate = g.ipars.timing() total, peak, peakSat, peakWarn, ston, ston3 = \ self.counts(expTime, cycleTime) if cycleTime < 0.01: self.cadence.config(text='{0:7.5f} s'.format(cycleTime)) elif cycleTime < 0.1: self.cadence.config(text='{0:6.4f} s'.format(cycleTime)) elif cycleTime < 1.: self.cadence.config(text='{0:5.3f} s'.format(cycleTime)) elif cycleTime < 10.: self.cadence.config(text='{0:4.2f} s'.format(cycleTime)) elif cycleTime < 100.: self.cadence.config(text='{0:4.1f} s'.format(cycleTime)) elif cycleTime < 1000.: self.cadence.config(text='{0:4.0f} s'.format(cycleTime)) else: self.cadence.config(text='{0:5.0f} s'.format(cycleTime)) if expTime < 0.01: self.exposure.config(text='{0:7.5f} s'.format(expTime)) elif expTime < 0.1: self.exposure.config(text='{0:6.4f} s'.format(expTime)) elif expTime < 1.: self.exposure.config(text='{0:5.3f} s'.format(expTime)) elif expTime < 10.: self.exposure.config(text='{0:4.2f} s'.format(expTime)) elif expTime < 100.: self.exposure.config(text='{0:4.1f} s'.format(expTime)) elif expTime < 1000.: self.exposure.config(text='{0:4.0f} s'.format(expTime)) else: self.exposure.config(text='{0:5.0f} s'.format(expTime)) self.duty.config(text='{0:4.1f} %'.format(dutyCycle)) self.peak.config(text='{0:d} cts'.format(int(round(peak)))) if peakSat: self.peak.config(bg=g.COL['error']) elif peakWarn: self.peak.config(bg=g.COL['warn']) else: self.peak.config(bg=g.COL['main']) self.total.config(text='{0:d} cts'.format(int(round(total)))) self.ston.config(text='{0:.1f}'.format(ston)) self.ston3.config(text='{0:.1f}'.format(ston3))
[ "def", "update", "(", "self", ",", "*", "args", ")", ":", "g", "=", "get_root", "(", "self", ")", ".", "globals", "expTime", ",", "deadTime", ",", "cycleTime", ",", "dutyCycle", ",", "frameRate", "=", "g", ".", "ipars", ".", "timing", "(", ")", "to...
Updates values. You should run a check on the instrument and target parameters before calling this.
[ "Updates", "values", ".", "You", "should", "run", "a", "check", "on", "the", "instrument", "and", "target", "parameters", "before", "calling", "this", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/hcam.py#L1355-L1407
train
HiPERCAM/hcam_widgets
hcam_widgets/hcam.py
CountsFrame.counts
def counts(self, expTime, cycleTime, ap_scale=1.6, ndiv=5): """ Computes counts per pixel, total counts, sky counts etc given current magnitude, seeing etc. You should run a check on the instrument parameters before calling this. expTime : exposure time per frame (seconds) cycleTime : sampling, cadence (seconds) ap_scale : aperture radius as multiple of seeing Returns: (total, peak, peakSat, peakWarn, ston, ston3) total -- total number of object counts in aperture peak -- peak counts in a pixel peakSat -- flag to indicate saturation peakWarn -- flag to indication level approaching saturation ston -- signal-to-noise per exposure ston3 -- signal-to-noise after 3 hours on target """ # code directly translated from Java equivalent. g = get_root(self).globals # Set the readout speed readSpeed = g.ipars.readSpeed() if readSpeed == 'Fast': gain = GAIN_FAST read = RNO_FAST elif readSpeed == 'Slow': gain = GAIN_SLOW read = RNO_SLOW else: raise DriverError('CountsFrame.counts: readout speed = ' + readSpeed + ' not recognised.') xbin, ybin = g.ipars.wframe.xbin.value(), g.ipars.wframe.ybin.value() # calculate SN info. zero, sky, skyTot, darkTot = 0., 0., 0., 0. total, peak, correct, signal, readTot, seeing = 0., 0., 0., 0., 0., 0. noise, narcsec, npix, signalToNoise3 = 1., 0., 0., 0. tinfo = g.TINS[g.cpars['telins_name']] filtnam = self.filter.value() zero = tinfo['zerop'][filtnam] mag = self.mag.value() seeing = self.seeing.value() sky = g.SKY[self.moon.value()][filtnam] airmass = self.airmass.value() plateScale = tinfo['plateScale'] # calculate expected electrons total = 10.**((zero-mag-airmass*g.EXTINCTION[filtnam])/2.5)*expTime # compute fraction that fall in central pixel # assuming target exactly at its centre. Do this # by splitting each pixel of the central (potentially # binned) pixel into ndiv * ndiv points at # which the seeing profile is added. sigma is the # RMS seeing in terms of pixels. sigma = seeing/g.EFAC/plateScale sum = 0. for iyp in range(ybin): yoff = -ybin/2.+iyp for ixp in range(xbin): xoff = -xbin/2.+ixp for iys in range(ndiv): y = (yoff + (iys+0.5)/ndiv)/sigma for ixs in range(ndiv): x = (xoff + (ixs+0.5)/ndiv)/sigma sum += math.exp(-(x*x+y*y)/2.) peak = total*sum/(2.*math.pi*sigma**2*ndiv**2) # Work out fraction of flux in aperture with radius AP_SCALE*seeing correct = 1. - math.exp(-(g.EFAC*ap_scale)**2/2.) # expected sky e- per arcsec skyPerArcsec = 10.**((zero-sky)/2.5)*expTime # skyPerPixel = skyPerArcsec*plateScale**2*xbin*ybin narcsec = math.pi*(ap_scale*seeing)**2 skyTot = skyPerArcsec*narcsec npix = math.pi*(ap_scale*seeing/plateScale)**2/xbin/ybin signal = correct*total # in electrons darkTot = npix*DARK_E*expTime # in electrons readTot = npix*read**2 # in electrons # noise, in electrons noise = math.sqrt(readTot + darkTot + skyTot + signal) # Now compute signal-to-noise in 3 hour seconds run signalToNoise3 = signal/noise*math.sqrt(3*3600./cycleTime) # convert from electrons to counts total /= gain peak /= gain warn = 25000 sat = 60000 peakSat = peak > sat peakWarn = peak > warn return (total, peak, peakSat, peakWarn, signal/noise, signalToNoise3)
python
def counts(self, expTime, cycleTime, ap_scale=1.6, ndiv=5): """ Computes counts per pixel, total counts, sky counts etc given current magnitude, seeing etc. You should run a check on the instrument parameters before calling this. expTime : exposure time per frame (seconds) cycleTime : sampling, cadence (seconds) ap_scale : aperture radius as multiple of seeing Returns: (total, peak, peakSat, peakWarn, ston, ston3) total -- total number of object counts in aperture peak -- peak counts in a pixel peakSat -- flag to indicate saturation peakWarn -- flag to indication level approaching saturation ston -- signal-to-noise per exposure ston3 -- signal-to-noise after 3 hours on target """ # code directly translated from Java equivalent. g = get_root(self).globals # Set the readout speed readSpeed = g.ipars.readSpeed() if readSpeed == 'Fast': gain = GAIN_FAST read = RNO_FAST elif readSpeed == 'Slow': gain = GAIN_SLOW read = RNO_SLOW else: raise DriverError('CountsFrame.counts: readout speed = ' + readSpeed + ' not recognised.') xbin, ybin = g.ipars.wframe.xbin.value(), g.ipars.wframe.ybin.value() # calculate SN info. zero, sky, skyTot, darkTot = 0., 0., 0., 0. total, peak, correct, signal, readTot, seeing = 0., 0., 0., 0., 0., 0. noise, narcsec, npix, signalToNoise3 = 1., 0., 0., 0. tinfo = g.TINS[g.cpars['telins_name']] filtnam = self.filter.value() zero = tinfo['zerop'][filtnam] mag = self.mag.value() seeing = self.seeing.value() sky = g.SKY[self.moon.value()][filtnam] airmass = self.airmass.value() plateScale = tinfo['plateScale'] # calculate expected electrons total = 10.**((zero-mag-airmass*g.EXTINCTION[filtnam])/2.5)*expTime # compute fraction that fall in central pixel # assuming target exactly at its centre. Do this # by splitting each pixel of the central (potentially # binned) pixel into ndiv * ndiv points at # which the seeing profile is added. sigma is the # RMS seeing in terms of pixels. sigma = seeing/g.EFAC/plateScale sum = 0. for iyp in range(ybin): yoff = -ybin/2.+iyp for ixp in range(xbin): xoff = -xbin/2.+ixp for iys in range(ndiv): y = (yoff + (iys+0.5)/ndiv)/sigma for ixs in range(ndiv): x = (xoff + (ixs+0.5)/ndiv)/sigma sum += math.exp(-(x*x+y*y)/2.) peak = total*sum/(2.*math.pi*sigma**2*ndiv**2) # Work out fraction of flux in aperture with radius AP_SCALE*seeing correct = 1. - math.exp(-(g.EFAC*ap_scale)**2/2.) # expected sky e- per arcsec skyPerArcsec = 10.**((zero-sky)/2.5)*expTime # skyPerPixel = skyPerArcsec*plateScale**2*xbin*ybin narcsec = math.pi*(ap_scale*seeing)**2 skyTot = skyPerArcsec*narcsec npix = math.pi*(ap_scale*seeing/plateScale)**2/xbin/ybin signal = correct*total # in electrons darkTot = npix*DARK_E*expTime # in electrons readTot = npix*read**2 # in electrons # noise, in electrons noise = math.sqrt(readTot + darkTot + skyTot + signal) # Now compute signal-to-noise in 3 hour seconds run signalToNoise3 = signal/noise*math.sqrt(3*3600./cycleTime) # convert from electrons to counts total /= gain peak /= gain warn = 25000 sat = 60000 peakSat = peak > sat peakWarn = peak > warn return (total, peak, peakSat, peakWarn, signal/noise, signalToNoise3)
[ "def", "counts", "(", "self", ",", "expTime", ",", "cycleTime", ",", "ap_scale", "=", "1.6", ",", "ndiv", "=", "5", ")", ":", "# code directly translated from Java equivalent.", "g", "=", "get_root", "(", "self", ")", ".", "globals", "# Set the readout speed", ...
Computes counts per pixel, total counts, sky counts etc given current magnitude, seeing etc. You should run a check on the instrument parameters before calling this. expTime : exposure time per frame (seconds) cycleTime : sampling, cadence (seconds) ap_scale : aperture radius as multiple of seeing Returns: (total, peak, peakSat, peakWarn, ston, ston3) total -- total number of object counts in aperture peak -- peak counts in a pixel peakSat -- flag to indicate saturation peakWarn -- flag to indication level approaching saturation ston -- signal-to-noise per exposure ston3 -- signal-to-noise after 3 hours on target
[ "Computes", "counts", "per", "pixel", "total", "counts", "sky", "counts", "etc", "given", "current", "magnitude", "seeing", "etc", ".", "You", "should", "run", "a", "check", "on", "the", "instrument", "parameters", "before", "calling", "this", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/hcam.py#L1409-L1515
train
HiPERCAM/hcam_widgets
hcam_widgets/hcam.py
Start.disable
def disable(self): """ Disable the button, if in non-expert mode. """ w.ActButton.disable(self) g = get_root(self).globals if self._expert: self.config(bg=g.COL['start']) else: self.config(bg=g.COL['startD'])
python
def disable(self): """ Disable the button, if in non-expert mode. """ w.ActButton.disable(self) g = get_root(self).globals if self._expert: self.config(bg=g.COL['start']) else: self.config(bg=g.COL['startD'])
[ "def", "disable", "(", "self", ")", ":", "w", ".", "ActButton", ".", "disable", "(", "self", ")", "g", "=", "get_root", "(", "self", ")", ".", "globals", "if", "self", ".", "_expert", ":", "self", ".", "config", "(", "bg", "=", "g", ".", "COL", ...
Disable the button, if in non-expert mode.
[ "Disable", "the", "button", "if", "in", "non", "-", "expert", "mode", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/hcam.py#L1592-L1601
train
HiPERCAM/hcam_widgets
hcam_widgets/hcam.py
Start.setExpert
def setExpert(self): """ Turns on 'expert' status whereby the button is always enabled, regardless of its activity status. """ w.ActButton.setExpert(self) g = get_root(self).globals self.config(bg=g.COL['start'])
python
def setExpert(self): """ Turns on 'expert' status whereby the button is always enabled, regardless of its activity status. """ w.ActButton.setExpert(self) g = get_root(self).globals self.config(bg=g.COL['start'])
[ "def", "setExpert", "(", "self", ")", ":", "w", ".", "ActButton", ".", "setExpert", "(", "self", ")", "g", "=", "get_root", "(", "self", ")", ".", "globals", "self", ".", "config", "(", "bg", "=", "g", ".", "COL", "[", "'start'", "]", ")" ]
Turns on 'expert' status whereby the button is always enabled, regardless of its activity status.
[ "Turns", "on", "expert", "status", "whereby", "the", "button", "is", "always", "enabled", "regardless", "of", "its", "activity", "status", "." ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/hcam.py#L1603-L1610
train
HiPERCAM/hcam_widgets
hcam_widgets/hcam.py
Start.act
def act(self): """ Carries out action associated with start button """ g = get_root(self).globals # check binning against overscan msg = """ HiperCAM has an o/scan of 50 pixels. Your binning does not fit into this region. Some columns will contain a mix of o/scan and data. Click OK if you wish to continue.""" if g.ipars.oscan(): xbin, ybin = g.ipars.wframe.xbin.value(), g.ipars.wframe.ybin.value() if xbin not in (1, 2, 5, 10) or ybin not in (1, 2, 5, 10): if not messagebox.askokcancel('Binning alert', msg): return False # Check instrument pars are OK if not g.ipars.check(): g.clog.warn('Invalid instrument parameters; save failed.') return False # create JSON to post data = createJSON(g) # POST try: success = postJSON(g, data) if not success: raise Exception('postJSON returned False') except Exception as err: g.clog.warn("Failed to post data to servers") g.clog.warn(str(err)) return False # Is nod enabled? Should we start GTC offsetter? try: success = startNodding(g, data) if not success: raise Exception('Failed to start dither: response was false') except Exception as err: g.clog.warn("Failed to start GTC offsetter") g.clog.warn(str(err)) return False # START try: success = execCommand(g, 'start') if not success: raise Exception("Start command failed: check server response") except Exception as err: g.clog.warn('Failed to start run') g.clog.warn(str(err)) return False # Send first offset if nodding enabled. # Initial trigger is sent after first offset, otherwise we'll hang indefinitely try: success = forceNod(g, data) if not success: raise Exception('Failed to send intitial offset and trigger - exposure will be paused indefinitely') except Exception as err: g.clog.warn('Run is paused indefinitely') g.clog.warn('use "ngcbCmd seq start" to fix') g.clog.warn(str(err)) # Run successfully started. # enable stop button, disable Start # also make inactive until RunType select box makes active again # start run timer # finally, clear table which stores TCS info during this run self.disable() self.run_type_set = False g.observe.stop.enable() g.info.timer.start() g.info.clear_tcs_table() return True
python
def act(self): """ Carries out action associated with start button """ g = get_root(self).globals # check binning against overscan msg = """ HiperCAM has an o/scan of 50 pixels. Your binning does not fit into this region. Some columns will contain a mix of o/scan and data. Click OK if you wish to continue.""" if g.ipars.oscan(): xbin, ybin = g.ipars.wframe.xbin.value(), g.ipars.wframe.ybin.value() if xbin not in (1, 2, 5, 10) or ybin not in (1, 2, 5, 10): if not messagebox.askokcancel('Binning alert', msg): return False # Check instrument pars are OK if not g.ipars.check(): g.clog.warn('Invalid instrument parameters; save failed.') return False # create JSON to post data = createJSON(g) # POST try: success = postJSON(g, data) if not success: raise Exception('postJSON returned False') except Exception as err: g.clog.warn("Failed to post data to servers") g.clog.warn(str(err)) return False # Is nod enabled? Should we start GTC offsetter? try: success = startNodding(g, data) if not success: raise Exception('Failed to start dither: response was false') except Exception as err: g.clog.warn("Failed to start GTC offsetter") g.clog.warn(str(err)) return False # START try: success = execCommand(g, 'start') if not success: raise Exception("Start command failed: check server response") except Exception as err: g.clog.warn('Failed to start run') g.clog.warn(str(err)) return False # Send first offset if nodding enabled. # Initial trigger is sent after first offset, otherwise we'll hang indefinitely try: success = forceNod(g, data) if not success: raise Exception('Failed to send intitial offset and trigger - exposure will be paused indefinitely') except Exception as err: g.clog.warn('Run is paused indefinitely') g.clog.warn('use "ngcbCmd seq start" to fix') g.clog.warn(str(err)) # Run successfully started. # enable stop button, disable Start # also make inactive until RunType select box makes active again # start run timer # finally, clear table which stores TCS info during this run self.disable() self.run_type_set = False g.observe.stop.enable() g.info.timer.start() g.info.clear_tcs_table() return True
[ "def", "act", "(", "self", ")", ":", "g", "=", "get_root", "(", "self", ")", ".", "globals", "# check binning against overscan", "msg", "=", "\"\"\"\n HiperCAM has an o/scan of 50 pixels.\n Your binning does not fit into this\n region. Some columns will contain...
Carries out action associated with start button
[ "Carries", "out", "action", "associated", "with", "start", "button" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/hcam.py#L1622-L1700
train
HiPERCAM/hcam_widgets
hcam_widgets/hcam.py
Load.act
def act(self): """ Carries out the action associated with the Load button """ g = get_root(self).globals fname = filedialog.askopenfilename( defaultextension='.json', filetypes=[('json files', '.json'), ('fits files', '.fits')], initialdir=g.cpars['app_directory']) if not fname: g.clog.warn('Aborted load from disk') return False # load json if fname.endswith('.json'): with open(fname) as ifname: json_string = ifname.read() else: json_string = jsonFromFits(fname) # load up the instrument settings g.ipars.loadJSON(json_string) # load up the run parameters g.rpars.loadJSON(json_string) return True
python
def act(self): """ Carries out the action associated with the Load button """ g = get_root(self).globals fname = filedialog.askopenfilename( defaultextension='.json', filetypes=[('json files', '.json'), ('fits files', '.fits')], initialdir=g.cpars['app_directory']) if not fname: g.clog.warn('Aborted load from disk') return False # load json if fname.endswith('.json'): with open(fname) as ifname: json_string = ifname.read() else: json_string = jsonFromFits(fname) # load up the instrument settings g.ipars.loadJSON(json_string) # load up the run parameters g.rpars.loadJSON(json_string) return True
[ "def", "act", "(", "self", ")", ":", "g", "=", "get_root", "(", "self", ")", ".", "globals", "fname", "=", "filedialog", ".", "askopenfilename", "(", "defaultextension", "=", "'.json'", ",", "filetypes", "=", "[", "(", "'json files'", ",", "'.json'", ")"...
Carries out the action associated with the Load button
[ "Carries", "out", "the", "action", "associated", "with", "the", "Load", "button" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/hcam.py#L1716-L1742
train
HiPERCAM/hcam_widgets
hcam_widgets/hcam.py
Save.act
def act(self): """ Carries out the action associated with the Save button """ g = get_root(self).globals g.clog.info('\nSaving current application to disk') # check instrument parameters if not g.ipars.check(): g.clog.warn('Invalid instrument parameters; save failed.') return False # check run parameters rok, msg = g.rpars.check() if not rok: g.clog.warn('Invalid run parameters; save failed.') g.clog.warn(msg) return False # Get data to save data = createJSON(g, full=False) # Save to disk if saveJSON(g, data): # modify buttons g.observe.load.enable() g.observe.unfreeze.disable() # unfreeze the instrument and run params g.ipars.unfreeze() g.rpars.unfreeze() return True else: return False
python
def act(self): """ Carries out the action associated with the Save button """ g = get_root(self).globals g.clog.info('\nSaving current application to disk') # check instrument parameters if not g.ipars.check(): g.clog.warn('Invalid instrument parameters; save failed.') return False # check run parameters rok, msg = g.rpars.check() if not rok: g.clog.warn('Invalid run parameters; save failed.') g.clog.warn(msg) return False # Get data to save data = createJSON(g, full=False) # Save to disk if saveJSON(g, data): # modify buttons g.observe.load.enable() g.observe.unfreeze.disable() # unfreeze the instrument and run params g.ipars.unfreeze() g.rpars.unfreeze() return True else: return False
[ "def", "act", "(", "self", ")", ":", "g", "=", "get_root", "(", "self", ")", ".", "globals", "g", ".", "clog", ".", "info", "(", "'\\nSaving current application to disk'", ")", "# check instrument parameters", "if", "not", "g", ".", "ipars", ".", "check", ...
Carries out the action associated with the Save button
[ "Carries", "out", "the", "action", "associated", "with", "the", "Save", "button" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/hcam.py#L1757-L1790
train
HiPERCAM/hcam_widgets
hcam_widgets/hcam.py
Unfreeze.act
def act(self): """ Carries out the action associated with the Unfreeze button """ g = get_root(self).globals g.ipars.unfreeze() g.rpars.unfreeze() g.observe.load.enable() self.disable()
python
def act(self): """ Carries out the action associated with the Unfreeze button """ g = get_root(self).globals g.ipars.unfreeze() g.rpars.unfreeze() g.observe.load.enable() self.disable()
[ "def", "act", "(", "self", ")", ":", "g", "=", "get_root", "(", "self", ")", ".", "globals", "g", ".", "ipars", ".", "unfreeze", "(", ")", "g", ".", "rpars", ".", "unfreeze", "(", ")", "g", ".", "observe", ".", "load", ".", "enable", "(", ")", ...
Carries out the action associated with the Unfreeze button
[ "Carries", "out", "the", "action", "associated", "with", "the", "Unfreeze", "button" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/hcam.py#L1804-L1812
train
HiPERCAM/hcam_widgets
hcam_widgets/hcam.py
Observe.setExpertLevel
def setExpertLevel(self): """ Set expert level """ g = get_root(self).globals level = g.cpars['expert_level'] # now set whether buttons are permanently enabled or not if level == 0 or level == 1: self.load.setNonExpert() self.save.setNonExpert() self.unfreeze.setNonExpert() self.start.setNonExpert() self.stop.setNonExpert() elif level == 2: self.load.setExpert() self.save.setExpert() self.unfreeze.setExpert() self.start.setExpert() self.stop.setExpert()
python
def setExpertLevel(self): """ Set expert level """ g = get_root(self).globals level = g.cpars['expert_level'] # now set whether buttons are permanently enabled or not if level == 0 or level == 1: self.load.setNonExpert() self.save.setNonExpert() self.unfreeze.setNonExpert() self.start.setNonExpert() self.stop.setNonExpert() elif level == 2: self.load.setExpert() self.save.setExpert() self.unfreeze.setExpert() self.start.setExpert() self.stop.setExpert()
[ "def", "setExpertLevel", "(", "self", ")", ":", "g", "=", "get_root", "(", "self", ")", ".", "globals", "level", "=", "g", ".", "cpars", "[", "'expert_level'", "]", "# now set whether buttons are permanently enabled or not", "if", "level", "==", "0", "or", "le...
Set expert level
[ "Set", "expert", "level" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/hcam.py#L1846-L1866
train
briancappello/py-meta-utils
py_meta_utils.py
process_factory_meta_options
def process_factory_meta_options( mcs_args: McsArgs, default_factory_class: Type[MetaOptionsFactory] = MetaOptionsFactory, factory_attr_name: str = META_OPTIONS_FACTORY_CLASS_ATTR_NAME) \ -> MetaOptionsFactory: """ Main entry point for consumer metaclasses. Usage:: from py_meta_utils import (AbstractMetaOption, McsArgs, MetaOptionsFactory, process_factory_meta_options) class YourMetaOptionsFactory(MetaOptionsFactory): _options = [AbstractMetaOption] class YourMetaclass(type): def __new__(mcs, name, bases, clsdict): mcs_args = McsArgs(mcs, name, bases, clsdict) # process_factory_meta_options must come *before* super().__new__() process_factory_meta_options(mcs_args, YourMetaOptionsFactory) return super().__new__(*mcs_args) class YourClass(metaclass=YourMetaclass): pass Subclasses of ``YourClass`` may set their ``_meta_options_factory_class`` attribute to a subclass of ``YourMetaOptionsFactory`` to customize their own supported meta options:: from py_meta_utils import MetaOption class FooMetaOption(MetaOption): def __init__(self): super().__init__(name='foo', default=None, inherit=True) class FooMetaOptionsFactory(YourMetaOptionsFactory): _options = YourMetaOptionsFactory._options + [ FooMetaOption, ] class FooClass(YourClass): _meta_options_factory_class = FooMetaOptionsFactory class Meta: foo = 'bar' :param mcs_args: The :class:`McsArgs` for the class-under-construction :param default_factory_class: The default MetaOptionsFactory class to use, if the ``factory_attr_name`` attribute is not set on the class-under-construction :param factory_attr_name: The attribute name to look for an overridden factory meta options class on the class-under-construction :return: The populated instance of the factory class """ factory_cls = mcs_args.getattr( factory_attr_name or META_OPTIONS_FACTORY_CLASS_ATTR_NAME, default_factory_class) options_factory = factory_cls() options_factory._contribute_to_class(mcs_args) return options_factory
python
def process_factory_meta_options( mcs_args: McsArgs, default_factory_class: Type[MetaOptionsFactory] = MetaOptionsFactory, factory_attr_name: str = META_OPTIONS_FACTORY_CLASS_ATTR_NAME) \ -> MetaOptionsFactory: """ Main entry point for consumer metaclasses. Usage:: from py_meta_utils import (AbstractMetaOption, McsArgs, MetaOptionsFactory, process_factory_meta_options) class YourMetaOptionsFactory(MetaOptionsFactory): _options = [AbstractMetaOption] class YourMetaclass(type): def __new__(mcs, name, bases, clsdict): mcs_args = McsArgs(mcs, name, bases, clsdict) # process_factory_meta_options must come *before* super().__new__() process_factory_meta_options(mcs_args, YourMetaOptionsFactory) return super().__new__(*mcs_args) class YourClass(metaclass=YourMetaclass): pass Subclasses of ``YourClass`` may set their ``_meta_options_factory_class`` attribute to a subclass of ``YourMetaOptionsFactory`` to customize their own supported meta options:: from py_meta_utils import MetaOption class FooMetaOption(MetaOption): def __init__(self): super().__init__(name='foo', default=None, inherit=True) class FooMetaOptionsFactory(YourMetaOptionsFactory): _options = YourMetaOptionsFactory._options + [ FooMetaOption, ] class FooClass(YourClass): _meta_options_factory_class = FooMetaOptionsFactory class Meta: foo = 'bar' :param mcs_args: The :class:`McsArgs` for the class-under-construction :param default_factory_class: The default MetaOptionsFactory class to use, if the ``factory_attr_name`` attribute is not set on the class-under-construction :param factory_attr_name: The attribute name to look for an overridden factory meta options class on the class-under-construction :return: The populated instance of the factory class """ factory_cls = mcs_args.getattr( factory_attr_name or META_OPTIONS_FACTORY_CLASS_ATTR_NAME, default_factory_class) options_factory = factory_cls() options_factory._contribute_to_class(mcs_args) return options_factory
[ "def", "process_factory_meta_options", "(", "mcs_args", ":", "McsArgs", ",", "default_factory_class", ":", "Type", "[", "MetaOptionsFactory", "]", "=", "MetaOptionsFactory", ",", "factory_attr_name", ":", "str", "=", "META_OPTIONS_FACTORY_CLASS_ATTR_NAME", ")", "->", "M...
Main entry point for consumer metaclasses. Usage:: from py_meta_utils import (AbstractMetaOption, McsArgs, MetaOptionsFactory, process_factory_meta_options) class YourMetaOptionsFactory(MetaOptionsFactory): _options = [AbstractMetaOption] class YourMetaclass(type): def __new__(mcs, name, bases, clsdict): mcs_args = McsArgs(mcs, name, bases, clsdict) # process_factory_meta_options must come *before* super().__new__() process_factory_meta_options(mcs_args, YourMetaOptionsFactory) return super().__new__(*mcs_args) class YourClass(metaclass=YourMetaclass): pass Subclasses of ``YourClass`` may set their ``_meta_options_factory_class`` attribute to a subclass of ``YourMetaOptionsFactory`` to customize their own supported meta options:: from py_meta_utils import MetaOption class FooMetaOption(MetaOption): def __init__(self): super().__init__(name='foo', default=None, inherit=True) class FooMetaOptionsFactory(YourMetaOptionsFactory): _options = YourMetaOptionsFactory._options + [ FooMetaOption, ] class FooClass(YourClass): _meta_options_factory_class = FooMetaOptionsFactory class Meta: foo = 'bar' :param mcs_args: The :class:`McsArgs` for the class-under-construction :param default_factory_class: The default MetaOptionsFactory class to use, if the ``factory_attr_name`` attribute is not set on the class-under-construction :param factory_attr_name: The attribute name to look for an overridden factory meta options class on the class-under-construction :return: The populated instance of the factory class
[ "Main", "entry", "point", "for", "consumer", "metaclasses", ".", "Usage", "::" ]
8de20be00768b7749dc2207a98331a9f23187918
https://github.com/briancappello/py-meta-utils/blob/8de20be00768b7749dc2207a98331a9f23187918/py_meta_utils.py#L321-L386
train
briancappello/py-meta-utils
py_meta_utils.py
deep_getattr
def deep_getattr(clsdict: Dict[str, Any], bases: Tuple[Type[object], ...], name: str, default: Any = _missing) -> Any: """ Acts just like ``getattr`` would on a constructed class object, except this operates on the pre-construction class dictionary and base classes. In other words, first we look for the attribute in the class dictionary, and then we search all the base classes (in method resolution order), finally returning the default value if the attribute was not found in any of the class dictionary or base classes (or it raises ``AttributeError`` if no default was given). """ value = clsdict.get(name, _missing) if value != _missing: return value for base in bases: value = getattr(base, name, _missing) if value != _missing: return value if default != _missing: return default raise AttributeError(name)
python
def deep_getattr(clsdict: Dict[str, Any], bases: Tuple[Type[object], ...], name: str, default: Any = _missing) -> Any: """ Acts just like ``getattr`` would on a constructed class object, except this operates on the pre-construction class dictionary and base classes. In other words, first we look for the attribute in the class dictionary, and then we search all the base classes (in method resolution order), finally returning the default value if the attribute was not found in any of the class dictionary or base classes (or it raises ``AttributeError`` if no default was given). """ value = clsdict.get(name, _missing) if value != _missing: return value for base in bases: value = getattr(base, name, _missing) if value != _missing: return value if default != _missing: return default raise AttributeError(name)
[ "def", "deep_getattr", "(", "clsdict", ":", "Dict", "[", "str", ",", "Any", "]", ",", "bases", ":", "Tuple", "[", "Type", "[", "object", "]", ",", "...", "]", ",", "name", ":", "str", ",", "default", ":", "Any", "=", "_missing", ")", "->", "Any",...
Acts just like ``getattr`` would on a constructed class object, except this operates on the pre-construction class dictionary and base classes. In other words, first we look for the attribute in the class dictionary, and then we search all the base classes (in method resolution order), finally returning the default value if the attribute was not found in any of the class dictionary or base classes (or it raises ``AttributeError`` if no default was given).
[ "Acts", "just", "like", "getattr", "would", "on", "a", "constructed", "class", "object", "except", "this", "operates", "on", "the", "pre", "-", "construction", "class", "dictionary", "and", "base", "classes", ".", "In", "other", "words", "first", "we", "look...
8de20be00768b7749dc2207a98331a9f23187918
https://github.com/briancappello/py-meta-utils/blob/8de20be00768b7749dc2207a98331a9f23187918/py_meta_utils.py#L437-L458
train
briancappello/py-meta-utils
py_meta_utils.py
McsArgs.getattr
def getattr(self, name, default: Any = _missing): """ Convenience method equivalent to ``deep_getattr(mcs_args.clsdict, mcs_args.bases, 'attr_name'[, default])`` """ return deep_getattr(self.clsdict, self.bases, name, default)
python
def getattr(self, name, default: Any = _missing): """ Convenience method equivalent to ``deep_getattr(mcs_args.clsdict, mcs_args.bases, 'attr_name'[, default])`` """ return deep_getattr(self.clsdict, self.bases, name, default)
[ "def", "getattr", "(", "self", ",", "name", ",", "default", ":", "Any", "=", "_missing", ")", ":", "return", "deep_getattr", "(", "self", ".", "clsdict", ",", "self", ".", "bases", ",", "name", ",", "default", ")" ]
Convenience method equivalent to ``deep_getattr(mcs_args.clsdict, mcs_args.bases, 'attr_name'[, default])``
[ "Convenience", "method", "equivalent", "to", "deep_getattr", "(", "mcs_args", ".", "clsdict", "mcs_args", ".", "bases", "attr_name", "[", "default", "]", ")" ]
8de20be00768b7749dc2207a98331a9f23187918
https://github.com/briancappello/py-meta-utils/blob/8de20be00768b7749dc2207a98331a9f23187918/py_meta_utils.py#L42-L47
train
briancappello/py-meta-utils
py_meta_utils.py
McsArgs.qualname
def qualname(self) -> str: """ Returns the fully qualified name of the class-under-construction, if possible, otherwise just the class name. """ if self.module: return self.module + '.' + self.name return self.name
python
def qualname(self) -> str: """ Returns the fully qualified name of the class-under-construction, if possible, otherwise just the class name. """ if self.module: return self.module + '.' + self.name return self.name
[ "def", "qualname", "(", "self", ")", "->", "str", ":", "if", "self", ".", "module", ":", "return", "self", ".", "module", "+", "'.'", "+", "self", ".", "name", "return", "self", ".", "name" ]
Returns the fully qualified name of the class-under-construction, if possible, otherwise just the class name.
[ "Returns", "the", "fully", "qualified", "name", "of", "the", "class", "-", "under", "-", "construction", "if", "possible", "otherwise", "just", "the", "class", "name", "." ]
8de20be00768b7749dc2207a98331a9f23187918
https://github.com/briancappello/py-meta-utils/blob/8de20be00768b7749dc2207a98331a9f23187918/py_meta_utils.py#L57-L64
train
briancappello/py-meta-utils
py_meta_utils.py
McsArgs.is_abstract
def is_abstract(self) -> bool: """ Whether or not the class-under-construction was declared as abstract (**NOTE:** this property is usable even *before* the :class:`MetaOptionsFactory` has run) """ meta_value = getattr(self.clsdict.get('Meta'), 'abstract', False) return self.clsdict.get(ABSTRACT_ATTR, meta_value) is True
python
def is_abstract(self) -> bool: """ Whether or not the class-under-construction was declared as abstract (**NOTE:** this property is usable even *before* the :class:`MetaOptionsFactory` has run) """ meta_value = getattr(self.clsdict.get('Meta'), 'abstract', False) return self.clsdict.get(ABSTRACT_ATTR, meta_value) is True
[ "def", "is_abstract", "(", "self", ")", "->", "bool", ":", "meta_value", "=", "getattr", "(", "self", ".", "clsdict", ".", "get", "(", "'Meta'", ")", ",", "'abstract'", ",", "False", ")", "return", "self", ".", "clsdict", ".", "get", "(", "ABSTRACT_ATT...
Whether or not the class-under-construction was declared as abstract (**NOTE:** this property is usable even *before* the :class:`MetaOptionsFactory` has run)
[ "Whether", "or", "not", "the", "class", "-", "under", "-", "construction", "was", "declared", "as", "abstract", "(", "**", "NOTE", ":", "**", "this", "property", "is", "usable", "even", "*", "before", "*", "the", ":", "class", ":", "MetaOptionsFactory", ...
8de20be00768b7749dc2207a98331a9f23187918
https://github.com/briancappello/py-meta-utils/blob/8de20be00768b7749dc2207a98331a9f23187918/py_meta_utils.py#L76-L82
train
briancappello/py-meta-utils
py_meta_utils.py
MetaOption.get_value
def get_value(self, Meta: Type[object], base_classes_meta, mcs_args: McsArgs) -> Any: """ Returns the value for ``self.name`` given the class-under-construction's class ``Meta``. If it's not found there, and ``self.inherit == True`` and there is a base class that has a class ``Meta``, use that value, otherwise ``self.default``. :param Meta: the class ``Meta`` (if any) from the class-under-construction (**NOTE:** this will be an ``object`` or ``None``, NOT an instance of :class:`MetaOptionsFactory`) :param base_classes_meta: the :class:`MetaOptionsFactory` instance (if any) from the base class of the class-under-construction :param mcs_args: the :class:`McsArgs` for the class-under-construction """ value = self.default if self.inherit and base_classes_meta is not None: value = getattr(base_classes_meta, self.name, value) if Meta is not None: value = getattr(Meta, self.name, value) return value
python
def get_value(self, Meta: Type[object], base_classes_meta, mcs_args: McsArgs) -> Any: """ Returns the value for ``self.name`` given the class-under-construction's class ``Meta``. If it's not found there, and ``self.inherit == True`` and there is a base class that has a class ``Meta``, use that value, otherwise ``self.default``. :param Meta: the class ``Meta`` (if any) from the class-under-construction (**NOTE:** this will be an ``object`` or ``None``, NOT an instance of :class:`MetaOptionsFactory`) :param base_classes_meta: the :class:`MetaOptionsFactory` instance (if any) from the base class of the class-under-construction :param mcs_args: the :class:`McsArgs` for the class-under-construction """ value = self.default if self.inherit and base_classes_meta is not None: value = getattr(base_classes_meta, self.name, value) if Meta is not None: value = getattr(Meta, self.name, value) return value
[ "def", "get_value", "(", "self", ",", "Meta", ":", "Type", "[", "object", "]", ",", "base_classes_meta", ",", "mcs_args", ":", "McsArgs", ")", "->", "Any", ":", "value", "=", "self", ".", "default", "if", "self", ".", "inherit", "and", "base_classes_meta...
Returns the value for ``self.name`` given the class-under-construction's class ``Meta``. If it's not found there, and ``self.inherit == True`` and there is a base class that has a class ``Meta``, use that value, otherwise ``self.default``. :param Meta: the class ``Meta`` (if any) from the class-under-construction (**NOTE:** this will be an ``object`` or ``None``, NOT an instance of :class:`MetaOptionsFactory`) :param base_classes_meta: the :class:`MetaOptionsFactory` instance (if any) from the base class of the class-under-construction :param mcs_args: the :class:`McsArgs` for the class-under-construction
[ "Returns", "the", "value", "for", "self", ".", "name", "given", "the", "class", "-", "under", "-", "construction", "s", "class", "Meta", ".", "If", "it", "s", "not", "found", "there", "and", "self", ".", "inherit", "==", "True", "and", "there", "is", ...
8de20be00768b7749dc2207a98331a9f23187918
https://github.com/briancappello/py-meta-utils/blob/8de20be00768b7749dc2207a98331a9f23187918/py_meta_utils.py#L113-L131
train
briancappello/py-meta-utils
py_meta_utils.py
MetaOptionsFactory._get_meta_options
def _get_meta_options(self) -> List[MetaOption]: """ Returns a list of :class:`MetaOption` instances that this factory supports. """ return [option if isinstance(option, MetaOption) else option() for option in self._options]
python
def _get_meta_options(self) -> List[MetaOption]: """ Returns a list of :class:`MetaOption` instances that this factory supports. """ return [option if isinstance(option, MetaOption) else option() for option in self._options]
[ "def", "_get_meta_options", "(", "self", ")", "->", "List", "[", "MetaOption", "]", ":", "return", "[", "option", "if", "isinstance", "(", "option", ",", "MetaOption", ")", "else", "option", "(", ")", "for", "option", "in", "self", ".", "_options", "]" ]
Returns a list of :class:`MetaOption` instances that this factory supports.
[ "Returns", "a", "list", "of", ":", "class", ":", "MetaOption", "instances", "that", "this", "factory", "supports", "." ]
8de20be00768b7749dc2207a98331a9f23187918
https://github.com/briancappello/py-meta-utils/blob/8de20be00768b7749dc2207a98331a9f23187918/py_meta_utils.py#L245-L250
train
briancappello/py-meta-utils
py_meta_utils.py
MetaOptionsFactory._contribute_to_class
def _contribute_to_class(self, mcs_args: McsArgs): """ Where the magic happens. Takes one parameter, the :class:`McsArgs` of the class-under-construction, and processes the declared ``class Meta`` from it (if any). We fill ourself with the declared meta options' name/value pairs, give the declared meta options a chance to also contribute to the class-under- construction, and finally replace the class-under-construction's ``class Meta`` with this populated factory instance (aka ``self``). """ self._mcs_args = mcs_args Meta = mcs_args.clsdict.pop('Meta', None) # type: Type[object] base_classes_meta = mcs_args.getattr('Meta', None) # type: MetaOptionsFactory mcs_args.clsdict['Meta'] = self # must come before _fill_from_meta, because # some meta options may depend upon having # access to the values of earlier meta options self._fill_from_meta(Meta, base_classes_meta, mcs_args) for option in self._get_meta_options(): option_value = getattr(self, option.name, None) option.contribute_to_class(mcs_args, option_value)
python
def _contribute_to_class(self, mcs_args: McsArgs): """ Where the magic happens. Takes one parameter, the :class:`McsArgs` of the class-under-construction, and processes the declared ``class Meta`` from it (if any). We fill ourself with the declared meta options' name/value pairs, give the declared meta options a chance to also contribute to the class-under- construction, and finally replace the class-under-construction's ``class Meta`` with this populated factory instance (aka ``self``). """ self._mcs_args = mcs_args Meta = mcs_args.clsdict.pop('Meta', None) # type: Type[object] base_classes_meta = mcs_args.getattr('Meta', None) # type: MetaOptionsFactory mcs_args.clsdict['Meta'] = self # must come before _fill_from_meta, because # some meta options may depend upon having # access to the values of earlier meta options self._fill_from_meta(Meta, base_classes_meta, mcs_args) for option in self._get_meta_options(): option_value = getattr(self, option.name, None) option.contribute_to_class(mcs_args, option_value)
[ "def", "_contribute_to_class", "(", "self", ",", "mcs_args", ":", "McsArgs", ")", ":", "self", ".", "_mcs_args", "=", "mcs_args", "Meta", "=", "mcs_args", ".", "clsdict", ".", "pop", "(", "'Meta'", ",", "None", ")", "# type: Type[object]", "base_classes_meta",...
Where the magic happens. Takes one parameter, the :class:`McsArgs` of the class-under-construction, and processes the declared ``class Meta`` from it (if any). We fill ourself with the declared meta options' name/value pairs, give the declared meta options a chance to also contribute to the class-under- construction, and finally replace the class-under-construction's ``class Meta`` with this populated factory instance (aka ``self``).
[ "Where", "the", "magic", "happens", ".", "Takes", "one", "parameter", "the", ":", "class", ":", "McsArgs", "of", "the", "class", "-", "under", "-", "construction", "and", "processes", "the", "declared", "class", "Meta", "from", "it", "(", "if", "any", ")...
8de20be00768b7749dc2207a98331a9f23187918
https://github.com/briancappello/py-meta-utils/blob/8de20be00768b7749dc2207a98331a9f23187918/py_meta_utils.py#L252-L273
train
briancappello/py-meta-utils
py_meta_utils.py
MetaOptionsFactory._fill_from_meta
def _fill_from_meta(self, Meta: Type[object], base_classes_meta, mcs_args: McsArgs): """ Iterate over our supported meta options, and set attributes on the factory instance (self) for each meta option's name/value. Raises ``TypeError`` if we discover any unsupported meta options on the class-under-construction's ``class Meta``. """ # Exclude private/protected fields from the Meta meta_attrs = {} if not Meta else {k: v for k, v in vars(Meta).items() if not k.startswith('_')} for option in self._get_meta_options(): existing = getattr(self, option.name, None) if existing and not (existing in self._allowed_properties and not isinstance(existing, property)): raise RuntimeError("Can't override field {name}." "".format(name=option.name)) value = option.get_value(Meta, base_classes_meta, mcs_args) option.check_value(value, mcs_args) meta_attrs.pop(option.name, None) if option.name != '_': setattr(self, option.name, value) if meta_attrs: # Only allow attributes on the Meta that have a respective MetaOption raise TypeError( '`class Meta` for {cls} got unknown attribute(s) {attrs}'.format( cls=mcs_args.name, attrs=', '.join(sorted(meta_attrs.keys()))))
python
def _fill_from_meta(self, Meta: Type[object], base_classes_meta, mcs_args: McsArgs): """ Iterate over our supported meta options, and set attributes on the factory instance (self) for each meta option's name/value. Raises ``TypeError`` if we discover any unsupported meta options on the class-under-construction's ``class Meta``. """ # Exclude private/protected fields from the Meta meta_attrs = {} if not Meta else {k: v for k, v in vars(Meta).items() if not k.startswith('_')} for option in self._get_meta_options(): existing = getattr(self, option.name, None) if existing and not (existing in self._allowed_properties and not isinstance(existing, property)): raise RuntimeError("Can't override field {name}." "".format(name=option.name)) value = option.get_value(Meta, base_classes_meta, mcs_args) option.check_value(value, mcs_args) meta_attrs.pop(option.name, None) if option.name != '_': setattr(self, option.name, value) if meta_attrs: # Only allow attributes on the Meta that have a respective MetaOption raise TypeError( '`class Meta` for {cls} got unknown attribute(s) {attrs}'.format( cls=mcs_args.name, attrs=', '.join(sorted(meta_attrs.keys()))))
[ "def", "_fill_from_meta", "(", "self", ",", "Meta", ":", "Type", "[", "object", "]", ",", "base_classes_meta", ",", "mcs_args", ":", "McsArgs", ")", ":", "# Exclude private/protected fields from the Meta", "meta_attrs", "=", "{", "}", "if", "not", "Meta", "else"...
Iterate over our supported meta options, and set attributes on the factory instance (self) for each meta option's name/value. Raises ``TypeError`` if we discover any unsupported meta options on the class-under-construction's ``class Meta``.
[ "Iterate", "over", "our", "supported", "meta", "options", "and", "set", "attributes", "on", "the", "factory", "instance", "(", "self", ")", "for", "each", "meta", "option", "s", "name", "/", "value", ".", "Raises", "TypeError", "if", "we", "discover", "any...
8de20be00768b7749dc2207a98331a9f23187918
https://github.com/briancappello/py-meta-utils/blob/8de20be00768b7749dc2207a98331a9f23187918/py_meta_utils.py#L275-L303
train
HiPERCAM/hcam_widgets
hcam_widgets/gtc/corba.py
CORBAConnection.get_object
def get_object(self, binding_name, cls): """ Get a reference to a remote object using CORBA """ return self._state.get_object(self, binding_name, cls)
python
def get_object(self, binding_name, cls): """ Get a reference to a remote object using CORBA """ return self._state.get_object(self, binding_name, cls)
[ "def", "get_object", "(", "self", ",", "binding_name", ",", "cls", ")", ":", "return", "self", ".", "_state", ".", "get_object", "(", "self", ",", "binding_name", ",", "cls", ")" ]
Get a reference to a remote object using CORBA
[ "Get", "a", "reference", "to", "a", "remote", "object", "using", "CORBA" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/gtc/corba.py#L40-L44
train
HiPERCAM/hcam_widgets
hcam_widgets/gtc/corba.py
ReadyCORBAState.get_object
def get_object(conn, binding_name, object_cls): """ Get a reference to a remote object using CORBA """ try: obj = conn.rootContext.resolve(binding_name) narrowed = obj._narrow(object_cls) except CORBA.TRANSIENT: raise IOError('Attempt to retrieve object failed') if narrowed is None: raise IOError('Attempt to retrieve object got a different class of object') return narrowed
python
def get_object(conn, binding_name, object_cls): """ Get a reference to a remote object using CORBA """ try: obj = conn.rootContext.resolve(binding_name) narrowed = obj._narrow(object_cls) except CORBA.TRANSIENT: raise IOError('Attempt to retrieve object failed') if narrowed is None: raise IOError('Attempt to retrieve object got a different class of object') return narrowed
[ "def", "get_object", "(", "conn", ",", "binding_name", ",", "object_cls", ")", ":", "try", ":", "obj", "=", "conn", ".", "rootContext", ".", "resolve", "(", "binding_name", ")", "narrowed", "=", "obj", ".", "_narrow", "(", "object_cls", ")", "except", "C...
Get a reference to a remote object using CORBA
[ "Get", "a", "reference", "to", "a", "remote", "object", "using", "CORBA" ]
7219f0d96dd3a8ebe3139c7f542a72c02d02fce8
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/gtc/corba.py#L116-L129
train