partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
valid
ChangesetDAG.path
Return nodes in the path between 'a' and 'b' going from parent to child NOT including 'a'
lrcloud/__main__.py
def path(self, a_hash, b_hash): """Return nodes in the path between 'a' and 'b' going from parent to child NOT including 'a' """ def _path(a, b): if a is b: return [a] else: assert len(a.children) == 1 return [a] + _path(a.children[0], b) a = self.nodes[a_hash] b = self.nodes[b_hash] return _path(a, b)[1:]
def path(self, a_hash, b_hash): """Return nodes in the path between 'a' and 'b' going from parent to child NOT including 'a' """ def _path(a, b): if a is b: return [a] else: assert len(a.children) == 1 return [a] + _path(a.children[0], b) a = self.nodes[a_hash] b = self.nodes[b_hash] return _path(a, b)[1:]
[ "Return", "nodes", "in", "the", "path", "between", "a", "and", "b", "going", "from", "parent", "to", "child", "NOT", "including", "a" ]
madsbk/lrcloud
python
https://github.com/madsbk/lrcloud/blob/8d99be3e1abdf941642e9a1c86b7d775dc373c0b/lrcloud/__main__.py#L150-L163
[ "def", "path", "(", "self", ",", "a_hash", ",", "b_hash", ")", ":", "def", "_path", "(", "a", ",", "b", ")", ":", "if", "a", "is", "b", ":", "return", "[", "a", "]", "else", ":", "assert", "len", "(", "a", ".", "children", ")", "==", "1", "return", "[", "a", "]", "+", "_path", "(", "a", ".", "children", "[", "0", "]", ",", "b", ")", "a", "=", "self", ".", "nodes", "[", "a_hash", "]", "b", "=", "self", ".", "nodes", "[", "b_hash", "]", "return", "_path", "(", "a", ",", "b", ")", "[", "1", ":", "]" ]
8d99be3e1abdf941642e9a1c86b7d775dc373c0b
valid
_rindex
Index of the last occurrence of x in the sequence.
hedgehog/protocol/zmq/__init__.py
def _rindex(mylist: Sequence[T], x: T) -> int: """Index of the last occurrence of x in the sequence.""" return len(mylist) - mylist[::-1].index(x) - 1
def _rindex(mylist: Sequence[T], x: T) -> int: """Index of the last occurrence of x in the sequence.""" return len(mylist) - mylist[::-1].index(x) - 1
[ "Index", "of", "the", "last", "occurrence", "of", "x", "in", "the", "sequence", "." ]
PRIArobotics/HedgehogProtocol
python
https://github.com/PRIArobotics/HedgehogProtocol/blob/140df1ade46fbfee7eea7a6c0b35cbc7ffbf89fe/hedgehog/protocol/zmq/__init__.py#L17-L19
[ "def", "_rindex", "(", "mylist", ":", "Sequence", "[", "T", "]", ",", "x", ":", "T", ")", "->", "int", ":", "return", "len", "(", "mylist", ")", "-", "mylist", "[", ":", ":", "-", "1", "]", ".", "index", "(", "x", ")", "-", "1" ]
140df1ade46fbfee7eea7a6c0b35cbc7ffbf89fe
valid
raw_to_delimited
\ Returns a message consisting of header frames, delimiter frame, and payload frames. The payload frames may be given as sequences of bytes (raw) or as `Message`s.
hedgehog/protocol/zmq/__init__.py
def raw_to_delimited(header: Header, raw_payload: RawPayload) -> DelimitedMsg: """\ Returns a message consisting of header frames, delimiter frame, and payload frames. The payload frames may be given as sequences of bytes (raw) or as `Message`s. """ return tuple(header) + (b'',) + tuple(raw_payload)
def raw_to_delimited(header: Header, raw_payload: RawPayload) -> DelimitedMsg: """\ Returns a message consisting of header frames, delimiter frame, and payload frames. The payload frames may be given as sequences of bytes (raw) or as `Message`s. """ return tuple(header) + (b'',) + tuple(raw_payload)
[ "\\", "Returns", "a", "message", "consisting", "of", "header", "frames", "delimiter", "frame", "and", "payload", "frames", ".", "The", "payload", "frames", "may", "be", "given", "as", "sequences", "of", "bytes", "(", "raw", ")", "or", "as", "Message", "s", "." ]
PRIArobotics/HedgehogProtocol
python
https://github.com/PRIArobotics/HedgehogProtocol/blob/140df1ade46fbfee7eea7a6c0b35cbc7ffbf89fe/hedgehog/protocol/zmq/__init__.py#L22-L27
[ "def", "raw_to_delimited", "(", "header", ":", "Header", ",", "raw_payload", ":", "RawPayload", ")", "->", "DelimitedMsg", ":", "return", "tuple", "(", "header", ")", "+", "(", "b''", ",", ")", "+", "tuple", "(", "raw_payload", ")" ]
140df1ade46fbfee7eea7a6c0b35cbc7ffbf89fe
valid
to_delimited
\ Returns a message consisting of header frames, delimiter frame, and payload frames. The payload frames may be given as sequences of bytes (raw) or as `Message`s.
hedgehog/protocol/zmq/__init__.py
def to_delimited(header: Header, payload: Payload, side: CommSide) -> DelimitedMsg: """\ Returns a message consisting of header frames, delimiter frame, and payload frames. The payload frames may be given as sequences of bytes (raw) or as `Message`s. """ return raw_to_delimited(header, [side.serialize(msg) for msg in payload])
def to_delimited(header: Header, payload: Payload, side: CommSide) -> DelimitedMsg: """\ Returns a message consisting of header frames, delimiter frame, and payload frames. The payload frames may be given as sequences of bytes (raw) or as `Message`s. """ return raw_to_delimited(header, [side.serialize(msg) for msg in payload])
[ "\\", "Returns", "a", "message", "consisting", "of", "header", "frames", "delimiter", "frame", "and", "payload", "frames", ".", "The", "payload", "frames", "may", "be", "given", "as", "sequences", "of", "bytes", "(", "raw", ")", "or", "as", "Message", "s", "." ]
PRIArobotics/HedgehogProtocol
python
https://github.com/PRIArobotics/HedgehogProtocol/blob/140df1ade46fbfee7eea7a6c0b35cbc7ffbf89fe/hedgehog/protocol/zmq/__init__.py#L30-L35
[ "def", "to_delimited", "(", "header", ":", "Header", ",", "payload", ":", "Payload", ",", "side", ":", "CommSide", ")", "->", "DelimitedMsg", ":", "return", "raw_to_delimited", "(", "header", ",", "[", "side", ".", "serialize", "(", "msg", ")", "for", "msg", "in", "payload", "]", ")" ]
140df1ade46fbfee7eea7a6c0b35cbc7ffbf89fe
valid
raw_from_delimited
\ From a message consisting of header frames, delimiter frame, and payload frames, return a tuple `(header, payload)`. The payload frames may be returned as sequences of bytes (raw) or as `Message`s.
hedgehog/protocol/zmq/__init__.py
def raw_from_delimited(msgs: DelimitedMsg) -> RawMsgs: """\ From a message consisting of header frames, delimiter frame, and payload frames, return a tuple `(header, payload)`. The payload frames may be returned as sequences of bytes (raw) or as `Message`s. """ delim = _rindex(msgs, b'') return tuple(msgs[:delim]), tuple(msgs[delim + 1:])
def raw_from_delimited(msgs: DelimitedMsg) -> RawMsgs: """\ From a message consisting of header frames, delimiter frame, and payload frames, return a tuple `(header, payload)`. The payload frames may be returned as sequences of bytes (raw) or as `Message`s. """ delim = _rindex(msgs, b'') return tuple(msgs[:delim]), tuple(msgs[delim + 1:])
[ "\\", "From", "a", "message", "consisting", "of", "header", "frames", "delimiter", "frame", "and", "payload", "frames", "return", "a", "tuple", "(", "header", "payload", ")", ".", "The", "payload", "frames", "may", "be", "returned", "as", "sequences", "of", "bytes", "(", "raw", ")", "or", "as", "Message", "s", "." ]
PRIArobotics/HedgehogProtocol
python
https://github.com/PRIArobotics/HedgehogProtocol/blob/140df1ade46fbfee7eea7a6c0b35cbc7ffbf89fe/hedgehog/protocol/zmq/__init__.py#L38-L44
[ "def", "raw_from_delimited", "(", "msgs", ":", "DelimitedMsg", ")", "->", "RawMsgs", ":", "delim", "=", "_rindex", "(", "msgs", ",", "b''", ")", "return", "tuple", "(", "msgs", "[", ":", "delim", "]", ")", ",", "tuple", "(", "msgs", "[", "delim", "+", "1", ":", "]", ")" ]
140df1ade46fbfee7eea7a6c0b35cbc7ffbf89fe
valid
from_delimited
\ From a message consisting of header frames, delimiter frame, and payload frames, return a tuple `(header, payload)`. The payload frames may be returned as sequences of bytes (raw) or as `Message`s.
hedgehog/protocol/zmq/__init__.py
def from_delimited(msgs: DelimitedMsg, side: CommSide) -> Msgs: """\ From a message consisting of header frames, delimiter frame, and payload frames, return a tuple `(header, payload)`. The payload frames may be returned as sequences of bytes (raw) or as `Message`s. """ header, raw_payload = raw_from_delimited(msgs) return header, tuple(side.parse(msg_raw) for msg_raw in raw_payload)
def from_delimited(msgs: DelimitedMsg, side: CommSide) -> Msgs: """\ From a message consisting of header frames, delimiter frame, and payload frames, return a tuple `(header, payload)`. The payload frames may be returned as sequences of bytes (raw) or as `Message`s. """ header, raw_payload = raw_from_delimited(msgs) return header, tuple(side.parse(msg_raw) for msg_raw in raw_payload)
[ "\\", "From", "a", "message", "consisting", "of", "header", "frames", "delimiter", "frame", "and", "payload", "frames", "return", "a", "tuple", "(", "header", "payload", ")", ".", "The", "payload", "frames", "may", "be", "returned", "as", "sequences", "of", "bytes", "(", "raw", ")", "or", "as", "Message", "s", "." ]
PRIArobotics/HedgehogProtocol
python
https://github.com/PRIArobotics/HedgehogProtocol/blob/140df1ade46fbfee7eea7a6c0b35cbc7ffbf89fe/hedgehog/protocol/zmq/__init__.py#L47-L53
[ "def", "from_delimited", "(", "msgs", ":", "DelimitedMsg", ",", "side", ":", "CommSide", ")", "->", "Msgs", ":", "header", ",", "raw_payload", "=", "raw_from_delimited", "(", "msgs", ")", "return", "header", ",", "tuple", "(", "side", ".", "parse", "(", "msg_raw", ")", "for", "msg_raw", "in", "raw_payload", ")" ]
140df1ade46fbfee7eea7a6c0b35cbc7ffbf89fe
valid
figure
Creates a figure with *\*\*kwargs* with a window title *title*. Returns class :class:`matplotlib.figure.Figure`.
scisalt/matplotlib/figure.py
def figure(title=None, **kwargs): """ Creates a figure with *\*\*kwargs* with a window title *title*. Returns class :class:`matplotlib.figure.Figure`. """ fig = _figure(**kwargs) if title is not None: fig.canvas.set_window_title(title) return fig
def figure(title=None, **kwargs): """ Creates a figure with *\*\*kwargs* with a window title *title*. Returns class :class:`matplotlib.figure.Figure`. """ fig = _figure(**kwargs) if title is not None: fig.canvas.set_window_title(title) return fig
[ "Creates", "a", "figure", "with", "*", "\\", "*", "\\", "*", "kwargs", "*", "with", "a", "window", "title", "*", "title", "*", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/matplotlib/figure.py#L7-L16
[ "def", "figure", "(", "title", "=", "None", ",", "*", "*", "kwargs", ")", ":", "fig", "=", "_figure", "(", "*", "*", "kwargs", ")", "if", "title", "is", "not", "None", ":", "fig", ".", "canvas", ".", "set_window_title", "(", "title", ")", "return", "fig" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
create_admin
Create and save an admin user. :param username: Admin account's username. Defaults to 'admin' :param email: Admin account's email address. Defaults to 'admin@admin.com' :param password: Admin account's password. Defaults to 'admin' :returns: Django user with staff and superuser privileges
awl/waelsteng.py
def create_admin(username='admin', email='admin@admin.com', password='admin'): """Create and save an admin user. :param username: Admin account's username. Defaults to 'admin' :param email: Admin account's email address. Defaults to 'admin@admin.com' :param password: Admin account's password. Defaults to 'admin' :returns: Django user with staff and superuser privileges """ admin = User.objects.create_user(username, email, password) admin.is_staff = True admin.is_superuser = True admin.save() return admin
def create_admin(username='admin', email='admin@admin.com', password='admin'): """Create and save an admin user. :param username: Admin account's username. Defaults to 'admin' :param email: Admin account's email address. Defaults to 'admin@admin.com' :param password: Admin account's password. Defaults to 'admin' :returns: Django user with staff and superuser privileges """ admin = User.objects.create_user(username, email, password) admin.is_staff = True admin.is_superuser = True admin.save() return admin
[ "Create", "and", "save", "an", "admin", "user", "." ]
cltrudeau/django-awl
python
https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/waelsteng.py#L55-L71
[ "def", "create_admin", "(", "username", "=", "'admin'", ",", "email", "=", "'admin@admin.com'", ",", "password", "=", "'admin'", ")", ":", "admin", "=", "User", ".", "objects", ".", "create_user", "(", "username", ",", "email", ",", "password", ")", "admin", ".", "is_staff", "=", "True", "admin", ".", "is_superuser", "=", "True", "admin", ".", "save", "(", ")", "return", "admin" ]
70d469ef9a161c1170b53aa017cf02d7c15eb90c
valid
messages_from_response
Returns a list of the messages from the django MessageMiddleware package contained within the given response. This is to be used during unit testing when trying to see if a message was set properly in a view. :param response: HttpResponse object, likely obtained through a test client.get() or client.post() call :returns: a list of tuples (message_string, message_level), one for each message in the response context
awl/waelsteng.py
def messages_from_response(response): """Returns a list of the messages from the django MessageMiddleware package contained within the given response. This is to be used during unit testing when trying to see if a message was set properly in a view. :param response: HttpResponse object, likely obtained through a test client.get() or client.post() call :returns: a list of tuples (message_string, message_level), one for each message in the response context """ messages = [] if hasattr(response, 'context') and response.context and \ 'messages' in response.context: messages = response.context['messages'] elif hasattr(response, 'cookies'): # no "context" set-up or no messages item, check for message info in # the cookies morsel = response.cookies.get('messages') if not morsel: return [] # use the decoder in the CookieStore to process and get a list of # messages from django.contrib.messages.storage.cookie import CookieStorage store = CookieStorage(FakeRequest()) messages = store._decode(morsel.value) else: return [] return [(m.message, m.level) for m in messages]
def messages_from_response(response): """Returns a list of the messages from the django MessageMiddleware package contained within the given response. This is to be used during unit testing when trying to see if a message was set properly in a view. :param response: HttpResponse object, likely obtained through a test client.get() or client.post() call :returns: a list of tuples (message_string, message_level), one for each message in the response context """ messages = [] if hasattr(response, 'context') and response.context and \ 'messages' in response.context: messages = response.context['messages'] elif hasattr(response, 'cookies'): # no "context" set-up or no messages item, check for message info in # the cookies morsel = response.cookies.get('messages') if not morsel: return [] # use the decoder in the CookieStore to process and get a list of # messages from django.contrib.messages.storage.cookie import CookieStorage store = CookieStorage(FakeRequest()) messages = store._decode(morsel.value) else: return [] return [(m.message, m.level) for m in messages]
[ "Returns", "a", "list", "of", "the", "messages", "from", "the", "django", "MessageMiddleware", "package", "contained", "within", "the", "given", "response", ".", "This", "is", "to", "be", "used", "during", "unit", "testing", "when", "trying", "to", "see", "if", "a", "message", "was", "set", "properly", "in", "a", "view", "." ]
cltrudeau/django-awl
python
https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/waelsteng.py#L74-L104
[ "def", "messages_from_response", "(", "response", ")", ":", "messages", "=", "[", "]", "if", "hasattr", "(", "response", ",", "'context'", ")", "and", "response", ".", "context", "and", "'messages'", "in", "response", ".", "context", ":", "messages", "=", "response", ".", "context", "[", "'messages'", "]", "elif", "hasattr", "(", "response", ",", "'cookies'", ")", ":", "# no \"context\" set-up or no messages item, check for message info in", "# the cookies", "morsel", "=", "response", ".", "cookies", ".", "get", "(", "'messages'", ")", "if", "not", "morsel", ":", "return", "[", "]", "# use the decoder in the CookieStore to process and get a list of", "# messages", "from", "django", ".", "contrib", ".", "messages", ".", "storage", ".", "cookie", "import", "CookieStorage", "store", "=", "CookieStorage", "(", "FakeRequest", "(", ")", ")", "messages", "=", "store", ".", "_decode", "(", "morsel", ".", "value", ")", "else", ":", "return", "[", "]", "return", "[", "(", "m", ".", "message", ",", "m", ".", "level", ")", "for", "m", "in", "messages", "]" ]
70d469ef9a161c1170b53aa017cf02d7c15eb90c
valid
AdminToolsMixin.initiate
Sets up the :class:`AdminSite` and creates a user with the appropriate privileges. This should be called from the inheritor's :class:`TestCase.setUp` method.
awl/waelsteng.py
def initiate(self): """Sets up the :class:`AdminSite` and creates a user with the appropriate privileges. This should be called from the inheritor's :class:`TestCase.setUp` method. """ self.site = admin.sites.AdminSite() self.admin_user = create_admin(self.USERNAME, self.EMAIL, self.PASSWORD) self.authed = False
def initiate(self): """Sets up the :class:`AdminSite` and creates a user with the appropriate privileges. This should be called from the inheritor's :class:`TestCase.setUp` method. """ self.site = admin.sites.AdminSite() self.admin_user = create_admin(self.USERNAME, self.EMAIL, self.PASSWORD) self.authed = False
[ "Sets", "up", "the", ":", "class", ":", "AdminSite", "and", "creates", "a", "user", "with", "the", "appropriate", "privileges", ".", "This", "should", "be", "called", "from", "the", "inheritor", "s", ":", "class", ":", "TestCase", ".", "setUp", "method", "." ]
cltrudeau/django-awl
python
https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/waelsteng.py#L135-L142
[ "def", "initiate", "(", "self", ")", ":", "self", ".", "site", "=", "admin", ".", "sites", ".", "AdminSite", "(", ")", "self", ".", "admin_user", "=", "create_admin", "(", "self", ".", "USERNAME", ",", "self", ".", "EMAIL", ",", "self", ".", "PASSWORD", ")", "self", ".", "authed", "=", "False" ]
70d469ef9a161c1170b53aa017cf02d7c15eb90c
valid
AdminToolsMixin.authorize
Authenticates the superuser account via the web login.
awl/waelsteng.py
def authorize(self): """Authenticates the superuser account via the web login.""" response = self.client.login(username=self.USERNAME, password=self.PASSWORD) self.assertTrue(response) self.authed = True
def authorize(self): """Authenticates the superuser account via the web login.""" response = self.client.login(username=self.USERNAME, password=self.PASSWORD) self.assertTrue(response) self.authed = True
[ "Authenticates", "the", "superuser", "account", "via", "the", "web", "login", "." ]
cltrudeau/django-awl
python
https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/waelsteng.py#L144-L149
[ "def", "authorize", "(", "self", ")", ":", "response", "=", "self", ".", "client", ".", "login", "(", "username", "=", "self", ".", "USERNAME", ",", "password", "=", "self", ".", "PASSWORD", ")", "self", ".", "assertTrue", "(", "response", ")", "self", ".", "authed", "=", "True" ]
70d469ef9a161c1170b53aa017cf02d7c15eb90c
valid
AdminToolsMixin.authed_get
Does a django test client ``get`` against the given url after logging in the admin first. :param url: URL to fetch :param response_code: Expected response code from the URL fetch. This value is asserted. Defaults to 200 :param headers: Optional dictionary of headers to send in the request :param follow: When True, the get call will follow any redirect requests. Defaults to False. :returns: Django testing ``Response`` object
awl/waelsteng.py
def authed_get(self, url, response_code=200, headers={}, follow=False): """Does a django test client ``get`` against the given url after logging in the admin first. :param url: URL to fetch :param response_code: Expected response code from the URL fetch. This value is asserted. Defaults to 200 :param headers: Optional dictionary of headers to send in the request :param follow: When True, the get call will follow any redirect requests. Defaults to False. :returns: Django testing ``Response`` object """ if not self.authed: self.authorize() response = self.client.get(url, follow=follow, **headers) self.assertEqual(response_code, response.status_code) return response
def authed_get(self, url, response_code=200, headers={}, follow=False): """Does a django test client ``get`` against the given url after logging in the admin first. :param url: URL to fetch :param response_code: Expected response code from the URL fetch. This value is asserted. Defaults to 200 :param headers: Optional dictionary of headers to send in the request :param follow: When True, the get call will follow any redirect requests. Defaults to False. :returns: Django testing ``Response`` object """ if not self.authed: self.authorize() response = self.client.get(url, follow=follow, **headers) self.assertEqual(response_code, response.status_code) return response
[ "Does", "a", "django", "test", "client", "get", "against", "the", "given", "url", "after", "logging", "in", "the", "admin", "first", "." ]
cltrudeau/django-awl
python
https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/waelsteng.py#L151-L173
[ "def", "authed_get", "(", "self", ",", "url", ",", "response_code", "=", "200", ",", "headers", "=", "{", "}", ",", "follow", "=", "False", ")", ":", "if", "not", "self", ".", "authed", ":", "self", ".", "authorize", "(", ")", "response", "=", "self", ".", "client", ".", "get", "(", "url", ",", "follow", "=", "follow", ",", "*", "*", "headers", ")", "self", ".", "assertEqual", "(", "response_code", ",", "response", ".", "status_code", ")", "return", "response" ]
70d469ef9a161c1170b53aa017cf02d7c15eb90c
valid
AdminToolsMixin.authed_post
Does a django test client ``post`` against the given url after logging in the admin first. :param url: URL to fetch :param data: Dictionary to form contents to post :param response_code: Expected response code from the URL fetch. This value is asserted. Defaults to 200 :param headers: Optional dictionary of headers to send in with the request :returns: Django testing ``Response`` object
awl/waelsteng.py
def authed_post(self, url, data, response_code=200, follow=False, headers={}): """Does a django test client ``post`` against the given url after logging in the admin first. :param url: URL to fetch :param data: Dictionary to form contents to post :param response_code: Expected response code from the URL fetch. This value is asserted. Defaults to 200 :param headers: Optional dictionary of headers to send in with the request :returns: Django testing ``Response`` object """ if not self.authed: self.authorize() response = self.client.post(url, data, follow=follow, **headers) self.assertEqual(response_code, response.status_code) return response
def authed_post(self, url, data, response_code=200, follow=False, headers={}): """Does a django test client ``post`` against the given url after logging in the admin first. :param url: URL to fetch :param data: Dictionary to form contents to post :param response_code: Expected response code from the URL fetch. This value is asserted. Defaults to 200 :param headers: Optional dictionary of headers to send in with the request :returns: Django testing ``Response`` object """ if not self.authed: self.authorize() response = self.client.post(url, data, follow=follow, **headers) self.assertEqual(response_code, response.status_code) return response
[ "Does", "a", "django", "test", "client", "post", "against", "the", "given", "url", "after", "logging", "in", "the", "admin", "first", "." ]
cltrudeau/django-awl
python
https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/waelsteng.py#L175-L197
[ "def", "authed_post", "(", "self", ",", "url", ",", "data", ",", "response_code", "=", "200", ",", "follow", "=", "False", ",", "headers", "=", "{", "}", ")", ":", "if", "not", "self", ".", "authed", ":", "self", ".", "authorize", "(", ")", "response", "=", "self", ".", "client", ".", "post", "(", "url", ",", "data", ",", "follow", "=", "follow", ",", "*", "*", "headers", ")", "self", ".", "assertEqual", "(", "response_code", ",", "response", ".", "status_code", ")", "return", "response" ]
70d469ef9a161c1170b53aa017cf02d7c15eb90c
valid
AdminToolsMixin.visit_admin_link
This method is used for testing links that are in the change list view of the django admin. For the given instance and field name, the HTML link tags in the column are parsed for a URL and then invoked with :class:`AdminToolsMixin.authed_get`. :param admin_model: Instance of a :class:`admin.ModelAdmin` object that is responsible for displaying the change list :param instance: Object instance that is the row in the admin change list :param field_name: Name of the field/column to containing the HTML link to get a URL from to visit :param response_code: Expected HTTP status code resulting from the call. The value of this is asserted. Defaults to 200. :param headers: Optional dictionary of headers to send in the request :returns: Django test ``Response`` object :raises AttributeError: If the column does not contain a URL that can be parsed
awl/waelsteng.py
def visit_admin_link(self, admin_model, instance, field_name, response_code=200, headers={}): """This method is used for testing links that are in the change list view of the django admin. For the given instance and field name, the HTML link tags in the column are parsed for a URL and then invoked with :class:`AdminToolsMixin.authed_get`. :param admin_model: Instance of a :class:`admin.ModelAdmin` object that is responsible for displaying the change list :param instance: Object instance that is the row in the admin change list :param field_name: Name of the field/column to containing the HTML link to get a URL from to visit :param response_code: Expected HTTP status code resulting from the call. The value of this is asserted. Defaults to 200. :param headers: Optional dictionary of headers to send in the request :returns: Django test ``Response`` object :raises AttributeError: If the column does not contain a URL that can be parsed """ html = self.field_value(admin_model, instance, field_name) url, text = parse_link(html) if not url: raise AttributeError('href could not be parsed from *%s*' % html) return self.authed_get(url, response_code=response_code, headers=headers)
def visit_admin_link(self, admin_model, instance, field_name, response_code=200, headers={}): """This method is used for testing links that are in the change list view of the django admin. For the given instance and field name, the HTML link tags in the column are parsed for a URL and then invoked with :class:`AdminToolsMixin.authed_get`. :param admin_model: Instance of a :class:`admin.ModelAdmin` object that is responsible for displaying the change list :param instance: Object instance that is the row in the admin change list :param field_name: Name of the field/column to containing the HTML link to get a URL from to visit :param response_code: Expected HTTP status code resulting from the call. The value of this is asserted. Defaults to 200. :param headers: Optional dictionary of headers to send in the request :returns: Django test ``Response`` object :raises AttributeError: If the column does not contain a URL that can be parsed """ html = self.field_value(admin_model, instance, field_name) url, text = parse_link(html) if not url: raise AttributeError('href could not be parsed from *%s*' % html) return self.authed_get(url, response_code=response_code, headers=headers)
[ "This", "method", "is", "used", "for", "testing", "links", "that", "are", "in", "the", "change", "list", "view", "of", "the", "django", "admin", ".", "For", "the", "given", "instance", "and", "field", "name", "the", "HTML", "link", "tags", "in", "the", "column", "are", "parsed", "for", "a", "URL", "and", "then", "invoked", "with", ":", "class", ":", "AdminToolsMixin", ".", "authed_get", "." ]
cltrudeau/django-awl
python
https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/waelsteng.py#L199-L230
[ "def", "visit_admin_link", "(", "self", ",", "admin_model", ",", "instance", ",", "field_name", ",", "response_code", "=", "200", ",", "headers", "=", "{", "}", ")", ":", "html", "=", "self", ".", "field_value", "(", "admin_model", ",", "instance", ",", "field_name", ")", "url", ",", "text", "=", "parse_link", "(", "html", ")", "if", "not", "url", ":", "raise", "AttributeError", "(", "'href could not be parsed from *%s*'", "%", "html", ")", "return", "self", ".", "authed_get", "(", "url", ",", "response_code", "=", "response_code", ",", "headers", "=", "headers", ")" ]
70d469ef9a161c1170b53aa017cf02d7c15eb90c
valid
AdminToolsMixin.field_value
Returns the value displayed in the column on the web interface for a given instance. :param admin_model: Instance of a :class:`admin.ModelAdmin` object that is responsible for displaying the change list :param instance: Object instance that is the row in the admin change list :field_name: Name of the field/column to fetch
awl/waelsteng.py
def field_value(self, admin_model, instance, field_name): """Returns the value displayed in the column on the web interface for a given instance. :param admin_model: Instance of a :class:`admin.ModelAdmin` object that is responsible for displaying the change list :param instance: Object instance that is the row in the admin change list :field_name: Name of the field/column to fetch """ _, _, value = lookup_field(field_name, instance, admin_model) return value
def field_value(self, admin_model, instance, field_name): """Returns the value displayed in the column on the web interface for a given instance. :param admin_model: Instance of a :class:`admin.ModelAdmin` object that is responsible for displaying the change list :param instance: Object instance that is the row in the admin change list :field_name: Name of the field/column to fetch """ _, _, value = lookup_field(field_name, instance, admin_model) return value
[ "Returns", "the", "value", "displayed", "in", "the", "column", "on", "the", "web", "interface", "for", "a", "given", "instance", "." ]
cltrudeau/django-awl
python
https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/waelsteng.py#L232-L245
[ "def", "field_value", "(", "self", ",", "admin_model", ",", "instance", ",", "field_name", ")", ":", "_", ",", "_", ",", "value", "=", "lookup_field", "(", "field_name", ",", "instance", ",", "admin_model", ")", "return", "value" ]
70d469ef9a161c1170b53aa017cf02d7c15eb90c
valid
AdminToolsMixin.field_names
Returns the names of the fields/columns used by the given admin model. :param admin_model: Instance of a :class:`admin.ModelAdmin` object that is responsible for displaying the change list :returns: List of field names
awl/waelsteng.py
def field_names(self, admin_model): """Returns the names of the fields/columns used by the given admin model. :param admin_model: Instance of a :class:`admin.ModelAdmin` object that is responsible for displaying the change list :returns: List of field names """ request = FakeRequest(user=self.admin_user) return admin_model.get_list_display(request)
def field_names(self, admin_model): """Returns the names of the fields/columns used by the given admin model. :param admin_model: Instance of a :class:`admin.ModelAdmin` object that is responsible for displaying the change list :returns: List of field names """ request = FakeRequest(user=self.admin_user) return admin_model.get_list_display(request)
[ "Returns", "the", "names", "of", "the", "fields", "/", "columns", "used", "by", "the", "given", "admin", "model", "." ]
cltrudeau/django-awl
python
https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/waelsteng.py#L247-L258
[ "def", "field_names", "(", "self", ",", "admin_model", ")", ":", "request", "=", "FakeRequest", "(", "user", "=", "self", ".", "admin_user", ")", "return", "admin_model", ".", "get_list_display", "(", "request", ")" ]
70d469ef9a161c1170b53aa017cf02d7c15eb90c
valid
githubtunnel
Opens a nested tunnel, first to *user1*@*server1*, then to *user2*@*server2*, for accessing on *port*. If *verbose* is true, prints various ssh commands. If *stanford* is true, shifts ports up by 1. Attempts to get *user1*, *user2* from environment variable ``USER_NAME`` if called from the command line.
scisalt/utils/githubtunnel.py
def githubtunnel(user1, server1, user2, server2, port, verbose, stanford=False): """ Opens a nested tunnel, first to *user1*@*server1*, then to *user2*@*server2*, for accessing on *port*. If *verbose* is true, prints various ssh commands. If *stanford* is true, shifts ports up by 1. Attempts to get *user1*, *user2* from environment variable ``USER_NAME`` if called from the command line. """ if stanford: port_shift = 1 else: port_shift = 0 # command1 = 'ssh -nNf -L {}:quickpicmac3.slac.stanford.edu:22 {}@{}'.format(port, user, server) command1 = 'ssh -nNf -L {}:{}:22 {}@{}'.format(port-1-port_shift, server2, user1, server1) command2 = 'ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -nNf -L {}:cardinal.stanford.edu:22 -p {} {}@localhost'.format(port-port_shift, port-port_shift-1, user2) command3 = 'ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -nNf -L {}:github.com:22 -p {} {}@localhost'.format(port, port-1, user2) if verbose: print(command1) if stanford: print(command2) print(command3) try: call(shlex.split(command1)) if stanford: call(shlex.split(command2)) call(shlex.split(command3)) except: print('Failure!') pass
def githubtunnel(user1, server1, user2, server2, port, verbose, stanford=False): """ Opens a nested tunnel, first to *user1*@*server1*, then to *user2*@*server2*, for accessing on *port*. If *verbose* is true, prints various ssh commands. If *stanford* is true, shifts ports up by 1. Attempts to get *user1*, *user2* from environment variable ``USER_NAME`` if called from the command line. """ if stanford: port_shift = 1 else: port_shift = 0 # command1 = 'ssh -nNf -L {}:quickpicmac3.slac.stanford.edu:22 {}@{}'.format(port, user, server) command1 = 'ssh -nNf -L {}:{}:22 {}@{}'.format(port-1-port_shift, server2, user1, server1) command2 = 'ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -nNf -L {}:cardinal.stanford.edu:22 -p {} {}@localhost'.format(port-port_shift, port-port_shift-1, user2) command3 = 'ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -nNf -L {}:github.com:22 -p {} {}@localhost'.format(port, port-1, user2) if verbose: print(command1) if stanford: print(command2) print(command3) try: call(shlex.split(command1)) if stanford: call(shlex.split(command2)) call(shlex.split(command3)) except: print('Failure!') pass
[ "Opens", "a", "nested", "tunnel", "first", "to", "*", "user1", "*", "@", "*", "server1", "*", "then", "to", "*", "user2", "*", "@", "*", "server2", "*", "for", "accessing", "on", "*", "port", "*", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/utils/githubtunnel.py#L11-L42
[ "def", "githubtunnel", "(", "user1", ",", "server1", ",", "user2", ",", "server2", ",", "port", ",", "verbose", ",", "stanford", "=", "False", ")", ":", "if", "stanford", ":", "port_shift", "=", "1", "else", ":", "port_shift", "=", "0", "# command1 = 'ssh -nNf -L {}:quickpicmac3.slac.stanford.edu:22 {}@{}'.format(port, user, server)", "command1", "=", "'ssh -nNf -L {}:{}:22 {}@{}'", ".", "format", "(", "port", "-", "1", "-", "port_shift", ",", "server2", ",", "user1", ",", "server1", ")", "command2", "=", "'ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -nNf -L {}:cardinal.stanford.edu:22 -p {} {}@localhost'", ".", "format", "(", "port", "-", "port_shift", ",", "port", "-", "port_shift", "-", "1", ",", "user2", ")", "command3", "=", "'ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -nNf -L {}:github.com:22 -p {} {}@localhost'", ".", "format", "(", "port", ",", "port", "-", "1", ",", "user2", ")", "if", "verbose", ":", "print", "(", "command1", ")", "if", "stanford", ":", "print", "(", "command2", ")", "print", "(", "command3", ")", "try", ":", "call", "(", "shlex", ".", "split", "(", "command1", ")", ")", "if", "stanford", ":", "call", "(", "shlex", ".", "split", "(", "command2", ")", ")", "call", "(", "shlex", ".", "split", "(", "command3", ")", ")", "except", ":", "print", "(", "'Failure!'", ")", "pass" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
Imshow_Slider_Array.imgmax
Highest value of input image.
scisalt/matplotlib/Imshow_Slider_Array_mod.py
def imgmax(self): """ Highest value of input image. """ if not hasattr(self, '_imgmax'): imgmax = _np.max(self.images[0]) for img in self.images: imax = _np.max(img) if imax > imgmax: imgmax = imax self._imgmax = imgmax return self._imgmax
def imgmax(self): """ Highest value of input image. """ if not hasattr(self, '_imgmax'): imgmax = _np.max(self.images[0]) for img in self.images: imax = _np.max(img) if imax > imgmax: imgmax = imax self._imgmax = imgmax return self._imgmax
[ "Highest", "value", "of", "input", "image", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/matplotlib/Imshow_Slider_Array_mod.py#L225-L238
[ "def", "imgmax", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_imgmax'", ")", ":", "imgmax", "=", "_np", ".", "max", "(", "self", ".", "images", "[", "0", "]", ")", "for", "img", "in", "self", ".", "images", ":", "imax", "=", "_np", ".", "max", "(", "img", ")", "if", "imax", ">", "imgmax", ":", "imgmax", "=", "imax", "self", ".", "_imgmax", "=", "imgmax", "return", "self", ".", "_imgmax" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
Imshow_Slider_Array.imgmin
Lowest value of input image.
scisalt/matplotlib/Imshow_Slider_Array_mod.py
def imgmin(self): """ Lowest value of input image. """ if not hasattr(self, '_imgmin'): imgmin = _np.min(self.images[0]) for img in self.images: imin = _np.min(img) if imin > imgmin: imgmin = imin self._imgmin = imgmin return _np.min(self.image)
def imgmin(self): """ Lowest value of input image. """ if not hasattr(self, '_imgmin'): imgmin = _np.min(self.images[0]) for img in self.images: imin = _np.min(img) if imin > imgmin: imgmin = imin self._imgmin = imgmin return _np.min(self.image)
[ "Lowest", "value", "of", "input", "image", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/matplotlib/Imshow_Slider_Array_mod.py#L244-L256
[ "def", "imgmin", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_imgmin'", ")", ":", "imgmin", "=", "_np", ".", "min", "(", "self", ".", "images", "[", "0", "]", ")", "for", "img", "in", "self", ".", "images", ":", "imin", "=", "_np", ".", "min", "(", "img", ")", "if", "imin", ">", "imgmin", ":", "imgmin", "=", "imin", "self", ".", "_imgmin", "=", "imgmin", "return", "_np", ".", "min", "(", "self", ".", "image", ")" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
spawn
spawns a greenlet that does not print exceptions to the screen. if you use this function you MUST use this module's join or joinall otherwise the exception will be lost
src/infi/gevent_utils/silent_greenlets.py
def spawn(func, *args, **kwargs): """ spawns a greenlet that does not print exceptions to the screen. if you use this function you MUST use this module's join or joinall otherwise the exception will be lost """ return gevent.spawn(wrap_uncaught_greenlet_exceptions(func), *args, **kwargs)
def spawn(func, *args, **kwargs): """ spawns a greenlet that does not print exceptions to the screen. if you use this function you MUST use this module's join or joinall otherwise the exception will be lost """ return gevent.spawn(wrap_uncaught_greenlet_exceptions(func), *args, **kwargs)
[ "spawns", "a", "greenlet", "that", "does", "not", "print", "exceptions", "to", "the", "screen", ".", "if", "you", "use", "this", "function", "you", "MUST", "use", "this", "module", "s", "join", "or", "joinall", "otherwise", "the", "exception", "will", "be", "lost" ]
Infinidat/infi.gevent_utils
python
https://github.com/Infinidat/infi.gevent_utils/blob/7eb3c1601b8f2c9aaa3a83154ee7dfce8e5e5a5a/src/infi/gevent_utils/silent_greenlets.py#L32-L35
[ "def", "spawn", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "gevent", ".", "spawn", "(", "wrap_uncaught_greenlet_exceptions", "(", "func", ")", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
7eb3c1601b8f2c9aaa3a83154ee7dfce8e5e5a5a
valid
_usage
Returns usage string with no trailing whitespace.
cuts/main.py
def _usage(prog_name=os.path.basename(sys.argv[0])): '''Returns usage string with no trailing whitespace.''' spacer = ' ' * len('usage: ') usage = prog_name + ' -b LIST [-S SEPARATOR] [file ...]\n' \ + spacer + prog_name + ' -c LIST [-S SEPERATOR] [file ...]\n' \ + spacer + prog_name \ + ' -f LIST [-d DELIM] [-e] [-S SEPERATOR] [-s] [file ...]' # Return usage message with trailing whitespace removed. return "usage: " + usage.rstrip()
def _usage(prog_name=os.path.basename(sys.argv[0])): '''Returns usage string with no trailing whitespace.''' spacer = ' ' * len('usage: ') usage = prog_name + ' -b LIST [-S SEPARATOR] [file ...]\n' \ + spacer + prog_name + ' -c LIST [-S SEPERATOR] [file ...]\n' \ + spacer + prog_name \ + ' -f LIST [-d DELIM] [-e] [-S SEPERATOR] [-s] [file ...]' # Return usage message with trailing whitespace removed. return "usage: " + usage.rstrip()
[ "Returns", "usage", "string", "with", "no", "trailing", "whitespace", "." ]
jpweiser/cuts
python
https://github.com/jpweiser/cuts/blob/5baf7f2e145045942ee8dcaccbc47f8f821fcb56/cuts/main.py#L11-L20
[ "def", "_usage", "(", "prog_name", "=", "os", ".", "path", ".", "basename", "(", "sys", ".", "argv", "[", "0", "]", ")", ")", ":", "spacer", "=", "' '", "*", "len", "(", "'usage: '", ")", "usage", "=", "prog_name", "+", "' -b LIST [-S SEPARATOR] [file ...]\\n'", "+", "spacer", "+", "prog_name", "+", "' -c LIST [-S SEPERATOR] [file ...]\\n'", "+", "spacer", "+", "prog_name", "+", "' -f LIST [-d DELIM] [-e] [-S SEPERATOR] [-s] [file ...]'", "# Return usage message with trailing whitespace removed.", "return", "\"usage: \"", "+", "usage", ".", "rstrip", "(", ")" ]
5baf7f2e145045942ee8dcaccbc47f8f821fcb56
valid
_parse_args
Setup argparser to process arguments and generate help
cuts/main.py
def _parse_args(args): """Setup argparser to process arguments and generate help""" # parser uses custom usage string, with 'usage: ' removed, as it is # added automatically via argparser. parser = argparse.ArgumentParser(description="Remove and/or rearrange " + "sections from each line of a file(s).", usage=_usage()[len('usage: '):]) parser.add_argument('-b', "--bytes", action='store', type=lst, default=[], help="Bytes to select") parser.add_argument('-c', "--chars", action='store', type=lst, default=[], help="Character to select") parser.add_argument('-f', "--fields", action='store', type=lst, default=[], help="Fields to select") parser.add_argument('-d', "--delimiter", action='store', default="\t", help="Sets field delimiter(default is TAB)") parser.add_argument('-e', "--regex", action='store_true', help='Enable regular expressions to be used as input '+ 'delimiter') parser.add_argument('-s', '--skip', action='store_true', help="Skip lines that do not contain input delimiter.") parser.add_argument('-S', "--separator", action='store', default="\t", help="Sets field separator for output.") parser.add_argument('file', nargs='*', default="-", help="File(s) to cut") return parser.parse_args(args)
def _parse_args(args): """Setup argparser to process arguments and generate help""" # parser uses custom usage string, with 'usage: ' removed, as it is # added automatically via argparser. parser = argparse.ArgumentParser(description="Remove and/or rearrange " + "sections from each line of a file(s).", usage=_usage()[len('usage: '):]) parser.add_argument('-b', "--bytes", action='store', type=lst, default=[], help="Bytes to select") parser.add_argument('-c', "--chars", action='store', type=lst, default=[], help="Character to select") parser.add_argument('-f', "--fields", action='store', type=lst, default=[], help="Fields to select") parser.add_argument('-d', "--delimiter", action='store', default="\t", help="Sets field delimiter(default is TAB)") parser.add_argument('-e', "--regex", action='store_true', help='Enable regular expressions to be used as input '+ 'delimiter') parser.add_argument('-s', '--skip', action='store_true', help="Skip lines that do not contain input delimiter.") parser.add_argument('-S', "--separator", action='store', default="\t", help="Sets field separator for output.") parser.add_argument('file', nargs='*', default="-", help="File(s) to cut") return parser.parse_args(args)
[ "Setup", "argparser", "to", "process", "arguments", "and", "generate", "help" ]
jpweiser/cuts
python
https://github.com/jpweiser/cuts/blob/5baf7f2e145045942ee8dcaccbc47f8f821fcb56/cuts/main.py#L34-L60
[ "def", "_parse_args", "(", "args", ")", ":", "# parser uses custom usage string, with 'usage: ' removed, as it is", "# added automatically via argparser.", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Remove and/or rearrange \"", "+", "\"sections from each line of a file(s).\"", ",", "usage", "=", "_usage", "(", ")", "[", "len", "(", "'usage: '", ")", ":", "]", ")", "parser", ".", "add_argument", "(", "'-b'", ",", "\"--bytes\"", ",", "action", "=", "'store'", ",", "type", "=", "lst", ",", "default", "=", "[", "]", ",", "help", "=", "\"Bytes to select\"", ")", "parser", ".", "add_argument", "(", "'-c'", ",", "\"--chars\"", ",", "action", "=", "'store'", ",", "type", "=", "lst", ",", "default", "=", "[", "]", ",", "help", "=", "\"Character to select\"", ")", "parser", ".", "add_argument", "(", "'-f'", ",", "\"--fields\"", ",", "action", "=", "'store'", ",", "type", "=", "lst", ",", "default", "=", "[", "]", ",", "help", "=", "\"Fields to select\"", ")", "parser", ".", "add_argument", "(", "'-d'", ",", "\"--delimiter\"", ",", "action", "=", "'store'", ",", "default", "=", "\"\\t\"", ",", "help", "=", "\"Sets field delimiter(default is TAB)\"", ")", "parser", ".", "add_argument", "(", "'-e'", ",", "\"--regex\"", ",", "action", "=", "'store_true'", ",", "help", "=", "'Enable regular expressions to be used as input '", "+", "'delimiter'", ")", "parser", ".", "add_argument", "(", "'-s'", ",", "'--skip'", ",", "action", "=", "'store_true'", ",", "help", "=", "\"Skip lines that do not contain input delimiter.\"", ")", "parser", ".", "add_argument", "(", "'-S'", ",", "\"--separator\"", ",", "action", "=", "'store'", ",", "default", "=", "\"\\t\"", ",", "help", "=", "\"Sets field separator for output.\"", ")", "parser", ".", "add_argument", "(", "'file'", ",", "nargs", "=", "'*'", ",", "default", "=", "\"-\"", ",", "help", "=", "\"File(s) to cut\"", ")", "return", "parser", ".", "parse_args", "(", "args", ")" ]
5baf7f2e145045942ee8dcaccbc47f8f821fcb56
valid
main
Processes command line arguments and file i/o
cuts/main.py
def main(args=sys.argv[1:]): '''Processes command line arguments and file i/o''' if not args: sys.stderr.write(_usage() + '\n') sys.exit(4) else: parsed = _parse_args(args) # Set delim based on whether or not regex is desired by user delim = parsed.delimiter if parsed.regex else re.escape(parsed.delimiter) # Keep track of number of cutters used to allow error handling if # multiple options selected (only one at a time is accepted) num_cutters = 0 # Read mode will be used as file read mode later. 'r' is default, changed # to 'rb' in the event that binary read mode is selected by user read_mode = 'r' if parsed.bytes: positions = parsed.bytes cutter = ByteCutter(positions) num_cutters += 1 read_mode = 'rb' if parsed.chars: positions = parsed.chars cutter = CharCutter(positions) num_cutters += 1 if parsed.fields: positions = parsed.fields cutter = FieldCutter(positions, delim, parsed.separator) num_cutters += 1 # Make sure only one option of -b,-c, or -f is used if num_cutters > 1: sys.stderr.write('Only one option permitted of -b, -c, -f.\n') sys.stderr.write(_usage() + '\n') sys.exit(1) # Check for possible specification of zero index, which is not allowed. # Regular expression checks for zero by itself, or in range specification if [n for n in positions if re.search("0:?|0$", n)]: sys.stderr.write('Zero is an invalid position.\n') sys.stderr.write(_usage() + '\n') sys.exit(2) try: for line in fileinput.input(parsed.file, mode=read_mode): if parsed.skip and not re.search(parsed.delimiter, line): pass else: # Using sys.stdout.write for consistency between Py 2 and 3, # keeping linter happy print(cutter.cut(line)) except IOError: sys.stderr.write('File \'' + fileinput.filename() + '\' could not be found.\n') sys.exit(3) fileinput.close()
def main(args=sys.argv[1:]): '''Processes command line arguments and file i/o''' if not args: sys.stderr.write(_usage() + '\n') sys.exit(4) else: parsed = _parse_args(args) # Set delim based on whether or not regex is desired by user delim = parsed.delimiter if parsed.regex else re.escape(parsed.delimiter) # Keep track of number of cutters used to allow error handling if # multiple options selected (only one at a time is accepted) num_cutters = 0 # Read mode will be used as file read mode later. 'r' is default, changed # to 'rb' in the event that binary read mode is selected by user read_mode = 'r' if parsed.bytes: positions = parsed.bytes cutter = ByteCutter(positions) num_cutters += 1 read_mode = 'rb' if parsed.chars: positions = parsed.chars cutter = CharCutter(positions) num_cutters += 1 if parsed.fields: positions = parsed.fields cutter = FieldCutter(positions, delim, parsed.separator) num_cutters += 1 # Make sure only one option of -b,-c, or -f is used if num_cutters > 1: sys.stderr.write('Only one option permitted of -b, -c, -f.\n') sys.stderr.write(_usage() + '\n') sys.exit(1) # Check for possible specification of zero index, which is not allowed. # Regular expression checks for zero by itself, or in range specification if [n for n in positions if re.search("0:?|0$", n)]: sys.stderr.write('Zero is an invalid position.\n') sys.stderr.write(_usage() + '\n') sys.exit(2) try: for line in fileinput.input(parsed.file, mode=read_mode): if parsed.skip and not re.search(parsed.delimiter, line): pass else: # Using sys.stdout.write for consistency between Py 2 and 3, # keeping linter happy print(cutter.cut(line)) except IOError: sys.stderr.write('File \'' + fileinput.filename() + '\' could not be found.\n') sys.exit(3) fileinput.close()
[ "Processes", "command", "line", "arguments", "and", "file", "i", "/", "o" ]
jpweiser/cuts
python
https://github.com/jpweiser/cuts/blob/5baf7f2e145045942ee8dcaccbc47f8f821fcb56/cuts/main.py#L62-L124
[ "def", "main", "(", "args", "=", "sys", ".", "argv", "[", "1", ":", "]", ")", ":", "if", "not", "args", ":", "sys", ".", "stderr", ".", "write", "(", "_usage", "(", ")", "+", "'\\n'", ")", "sys", ".", "exit", "(", "4", ")", "else", ":", "parsed", "=", "_parse_args", "(", "args", ")", "# Set delim based on whether or not regex is desired by user", "delim", "=", "parsed", ".", "delimiter", "if", "parsed", ".", "regex", "else", "re", ".", "escape", "(", "parsed", ".", "delimiter", ")", "# Keep track of number of cutters used to allow error handling if", "# multiple options selected (only one at a time is accepted)", "num_cutters", "=", "0", "# Read mode will be used as file read mode later. 'r' is default, changed", "# to 'rb' in the event that binary read mode is selected by user", "read_mode", "=", "'r'", "if", "parsed", ".", "bytes", ":", "positions", "=", "parsed", ".", "bytes", "cutter", "=", "ByteCutter", "(", "positions", ")", "num_cutters", "+=", "1", "read_mode", "=", "'rb'", "if", "parsed", ".", "chars", ":", "positions", "=", "parsed", ".", "chars", "cutter", "=", "CharCutter", "(", "positions", ")", "num_cutters", "+=", "1", "if", "parsed", ".", "fields", ":", "positions", "=", "parsed", ".", "fields", "cutter", "=", "FieldCutter", "(", "positions", ",", "delim", ",", "parsed", ".", "separator", ")", "num_cutters", "+=", "1", "# Make sure only one option of -b,-c, or -f is used", "if", "num_cutters", ">", "1", ":", "sys", ".", "stderr", ".", "write", "(", "'Only one option permitted of -b, -c, -f.\\n'", ")", "sys", ".", "stderr", ".", "write", "(", "_usage", "(", ")", "+", "'\\n'", ")", "sys", ".", "exit", "(", "1", ")", "# Check for possible specification of zero index, which is not allowed.", "# Regular expression checks for zero by itself, or in range specification", "if", "[", "n", "for", "n", "in", "positions", "if", "re", ".", "search", "(", "\"0:?|0$\"", ",", "n", ")", "]", ":", "sys", ".", "stderr", ".", "write", "(", "'Zero is an invalid position.\\n'", ")", "sys", ".", "stderr", ".", "write", "(", "_usage", "(", ")", "+", "'\\n'", ")", "sys", ".", "exit", "(", "2", ")", "try", ":", "for", "line", "in", "fileinput", ".", "input", "(", "parsed", ".", "file", ",", "mode", "=", "read_mode", ")", ":", "if", "parsed", ".", "skip", "and", "not", "re", ".", "search", "(", "parsed", ".", "delimiter", ",", "line", ")", ":", "pass", "else", ":", "# Using sys.stdout.write for consistency between Py 2 and 3,", "# keeping linter happy", "print", "(", "cutter", ".", "cut", "(", "line", ")", ")", "except", "IOError", ":", "sys", ".", "stderr", ".", "write", "(", "'File \\''", "+", "fileinput", ".", "filename", "(", ")", "+", "'\\' could not be found.\\n'", ")", "sys", ".", "exit", "(", "3", ")", "fileinput", ".", "close", "(", ")" ]
5baf7f2e145045942ee8dcaccbc47f8f821fcb56
valid
NonUniformImage_axes
Returns axes *x, y* for a given image *img* to be used with :func:`scisalt.matplotlib.NonUniformImage`. Returns ------- x, y : float, float
scisalt/matplotlib/NonUniformImage_axes.py
def NonUniformImage_axes(img): """ Returns axes *x, y* for a given image *img* to be used with :func:`scisalt.matplotlib.NonUniformImage`. Returns ------- x, y : float, float """ xmin = 0 xmax = img.shape[1]-1 ymin = 0 ymax = img.shape[0]-1 x = _np.linspace(xmin, xmax, img.shape[1]) y = _np.linspace(ymin, ymax, img.shape[0]) return x, y
def NonUniformImage_axes(img): """ Returns axes *x, y* for a given image *img* to be used with :func:`scisalt.matplotlib.NonUniformImage`. Returns ------- x, y : float, float """ xmin = 0 xmax = img.shape[1]-1 ymin = 0 ymax = img.shape[0]-1 x = _np.linspace(xmin, xmax, img.shape[1]) y = _np.linspace(ymin, ymax, img.shape[0]) return x, y
[ "Returns", "axes", "*", "x", "y", "*", "for", "a", "given", "image", "*", "img", "*", "to", "be", "used", "with", ":", "func", ":", "scisalt", ".", "matplotlib", ".", "NonUniformImage", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/matplotlib/NonUniformImage_axes.py#L7-L21
[ "def", "NonUniformImage_axes", "(", "img", ")", ":", "xmin", "=", "0", "xmax", "=", "img", ".", "shape", "[", "1", "]", "-", "1", "ymin", "=", "0", "ymax", "=", "img", ".", "shape", "[", "0", "]", "-", "1", "x", "=", "_np", ".", "linspace", "(", "xmin", ",", "xmax", ",", "img", ".", "shape", "[", "1", "]", ")", "y", "=", "_np", ".", "linspace", "(", "ymin", ",", "ymax", ",", "img", ".", "shape", "[", "0", "]", ")", "return", "x", ",", "y" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
move
View to be used in the django admin for changing a :class:`RankedModel` object's rank. See :func:`admin_link_move_up` and :func:`admin_link_move_down` for helper functions to incoroprate in your admin models. Upon completion this view sends the caller back to the referring page. :param content_type_id: ``ContentType`` id of object being moved :param obj_id: ID of object being moved :param rank: New rank of the object
awl/rankedmodel/views.py
def move(request, content_type_id, obj_id, rank): """View to be used in the django admin for changing a :class:`RankedModel` object's rank. See :func:`admin_link_move_up` and :func:`admin_link_move_down` for helper functions to incoroprate in your admin models. Upon completion this view sends the caller back to the referring page. :param content_type_id: ``ContentType`` id of object being moved :param obj_id: ID of object being moved :param rank: New rank of the object """ content_type = ContentType.objects.get_for_id(content_type_id) obj = get_object_or_404(content_type.model_class(), id=obj_id) obj.rank = int(rank) obj.save() return HttpResponseRedirect(request.META['HTTP_REFERER'])
def move(request, content_type_id, obj_id, rank): """View to be used in the django admin for changing a :class:`RankedModel` object's rank. See :func:`admin_link_move_up` and :func:`admin_link_move_down` for helper functions to incoroprate in your admin models. Upon completion this view sends the caller back to the referring page. :param content_type_id: ``ContentType`` id of object being moved :param obj_id: ID of object being moved :param rank: New rank of the object """ content_type = ContentType.objects.get_for_id(content_type_id) obj = get_object_or_404(content_type.model_class(), id=obj_id) obj.rank = int(rank) obj.save() return HttpResponseRedirect(request.META['HTTP_REFERER'])
[ "View", "to", "be", "used", "in", "the", "django", "admin", "for", "changing", "a", ":", "class", ":", "RankedModel", "object", "s", "rank", ".", "See", ":", "func", ":", "admin_link_move_up", "and", ":", "func", ":", "admin_link_move_down", "for", "helper", "functions", "to", "incoroprate", "in", "your", "admin", "models", "." ]
cltrudeau/django-awl
python
https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/rankedmodel/views.py#L11-L31
[ "def", "move", "(", "request", ",", "content_type_id", ",", "obj_id", ",", "rank", ")", ":", "content_type", "=", "ContentType", ".", "objects", ".", "get_for_id", "(", "content_type_id", ")", "obj", "=", "get_object_or_404", "(", "content_type", ".", "model_class", "(", ")", ",", "id", "=", "obj_id", ")", "obj", ".", "rank", "=", "int", "(", "rank", ")", "obj", ".", "save", "(", ")", "return", "HttpResponseRedirect", "(", "request", ".", "META", "[", "'HTTP_REFERER'", "]", ")" ]
70d469ef9a161c1170b53aa017cf02d7c15eb90c
valid
open_s3
Opens connection to S3 returning bucket and key
paved/s3.py
def open_s3(bucket): """ Opens connection to S3 returning bucket and key """ conn = boto.connect_s3(options.paved.s3.access_id, options.paved.s3.secret) try: bucket = conn.get_bucket(bucket) except boto.exception.S3ResponseError: bucket = conn.create_bucket(bucket) return bucket
def open_s3(bucket): """ Opens connection to S3 returning bucket and key """ conn = boto.connect_s3(options.paved.s3.access_id, options.paved.s3.secret) try: bucket = conn.get_bucket(bucket) except boto.exception.S3ResponseError: bucket = conn.create_bucket(bucket) return bucket
[ "Opens", "connection", "to", "S3", "returning", "bucket", "and", "key" ]
eykd/paved
python
https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/s3.py#L32-L41
[ "def", "open_s3", "(", "bucket", ")", ":", "conn", "=", "boto", ".", "connect_s3", "(", "options", ".", "paved", ".", "s3", ".", "access_id", ",", "options", ".", "paved", ".", "s3", ".", "secret", ")", "try", ":", "bucket", "=", "conn", ".", "get_bucket", "(", "bucket", ")", "except", "boto", ".", "exception", ".", "S3ResponseError", ":", "bucket", "=", "conn", ".", "create_bucket", "(", "bucket", ")", "return", "bucket" ]
f04f8a4248c571f3d5ce882b325884a3e5d80203
valid
upload_s3
Upload a local file to S3.
paved/s3.py
def upload_s3(file_path, bucket_name, file_key, force=False, acl='private'): """Upload a local file to S3. """ file_path = path(file_path) bucket = open_s3(bucket_name) if file_path.isdir(): # Upload the contents of the dir path. paths = file_path.listdir() paths_keys = list(zip(paths, ['%s/%s' % (file_key, p.name) for p in paths])) else: # Upload just the given file path. paths_keys = [(file_path, file_key)] for p, k in paths_keys: headers = {} s3_key = bucket.get_key(k) if not s3_key: from boto.s3.key import Key s3_key = Key(bucket, k) content_type = mimetypes.guess_type(p)[0] if content_type: headers['Content-Type'] = content_type file_size = p.stat().st_size file_data = p.bytes() file_md5, file_md5_64 = s3_key.get_md5_from_hexdigest(hashlib.md5(file_data).hexdigest()) # Check the hash. if s3_key.etag: s3_md5 = s3_key.etag.replace('"', '') if s3_md5 == file_md5: info('Hash is the same. Skipping %s' % file_path) continue elif not force: # Check if file on S3 is older than local file. s3_datetime = datetime.datetime(*time.strptime( s3_key.last_modified, '%a, %d %b %Y %H:%M:%S %Z')[0:6]) local_datetime = datetime.datetime.utcfromtimestamp(p.stat().st_mtime) if local_datetime < s3_datetime: info("File %s hasn't been modified since last " \ "being uploaded" % (file_key)) continue # File is newer, let's process and upload info("Uploading %s..." % (file_key)) try: s3_key.set_contents_from_string(file_data, headers, policy=acl, replace=True, md5=(file_md5, file_md5_64)) except Exception as e: error("Failed: %s" % e) raise
def upload_s3(file_path, bucket_name, file_key, force=False, acl='private'): """Upload a local file to S3. """ file_path = path(file_path) bucket = open_s3(bucket_name) if file_path.isdir(): # Upload the contents of the dir path. paths = file_path.listdir() paths_keys = list(zip(paths, ['%s/%s' % (file_key, p.name) for p in paths])) else: # Upload just the given file path. paths_keys = [(file_path, file_key)] for p, k in paths_keys: headers = {} s3_key = bucket.get_key(k) if not s3_key: from boto.s3.key import Key s3_key = Key(bucket, k) content_type = mimetypes.guess_type(p)[0] if content_type: headers['Content-Type'] = content_type file_size = p.stat().st_size file_data = p.bytes() file_md5, file_md5_64 = s3_key.get_md5_from_hexdigest(hashlib.md5(file_data).hexdigest()) # Check the hash. if s3_key.etag: s3_md5 = s3_key.etag.replace('"', '') if s3_md5 == file_md5: info('Hash is the same. Skipping %s' % file_path) continue elif not force: # Check if file on S3 is older than local file. s3_datetime = datetime.datetime(*time.strptime( s3_key.last_modified, '%a, %d %b %Y %H:%M:%S %Z')[0:6]) local_datetime = datetime.datetime.utcfromtimestamp(p.stat().st_mtime) if local_datetime < s3_datetime: info("File %s hasn't been modified since last " \ "being uploaded" % (file_key)) continue # File is newer, let's process and upload info("Uploading %s..." % (file_key)) try: s3_key.set_contents_from_string(file_data, headers, policy=acl, replace=True, md5=(file_md5, file_md5_64)) except Exception as e: error("Failed: %s" % e) raise
[ "Upload", "a", "local", "file", "to", "S3", "." ]
eykd/paved
python
https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/s3.py#L44-L94
[ "def", "upload_s3", "(", "file_path", ",", "bucket_name", ",", "file_key", ",", "force", "=", "False", ",", "acl", "=", "'private'", ")", ":", "file_path", "=", "path", "(", "file_path", ")", "bucket", "=", "open_s3", "(", "bucket_name", ")", "if", "file_path", ".", "isdir", "(", ")", ":", "# Upload the contents of the dir path.", "paths", "=", "file_path", ".", "listdir", "(", ")", "paths_keys", "=", "list", "(", "zip", "(", "paths", ",", "[", "'%s/%s'", "%", "(", "file_key", ",", "p", ".", "name", ")", "for", "p", "in", "paths", "]", ")", ")", "else", ":", "# Upload just the given file path.", "paths_keys", "=", "[", "(", "file_path", ",", "file_key", ")", "]", "for", "p", ",", "k", "in", "paths_keys", ":", "headers", "=", "{", "}", "s3_key", "=", "bucket", ".", "get_key", "(", "k", ")", "if", "not", "s3_key", ":", "from", "boto", ".", "s3", ".", "key", "import", "Key", "s3_key", "=", "Key", "(", "bucket", ",", "k", ")", "content_type", "=", "mimetypes", ".", "guess_type", "(", "p", ")", "[", "0", "]", "if", "content_type", ":", "headers", "[", "'Content-Type'", "]", "=", "content_type", "file_size", "=", "p", ".", "stat", "(", ")", ".", "st_size", "file_data", "=", "p", ".", "bytes", "(", ")", "file_md5", ",", "file_md5_64", "=", "s3_key", ".", "get_md5_from_hexdigest", "(", "hashlib", ".", "md5", "(", "file_data", ")", ".", "hexdigest", "(", ")", ")", "# Check the hash.", "if", "s3_key", ".", "etag", ":", "s3_md5", "=", "s3_key", ".", "etag", ".", "replace", "(", "'\"'", ",", "''", ")", "if", "s3_md5", "==", "file_md5", ":", "info", "(", "'Hash is the same. Skipping %s'", "%", "file_path", ")", "continue", "elif", "not", "force", ":", "# Check if file on S3 is older than local file.", "s3_datetime", "=", "datetime", ".", "datetime", "(", "*", "time", ".", "strptime", "(", "s3_key", ".", "last_modified", ",", "'%a, %d %b %Y %H:%M:%S %Z'", ")", "[", "0", ":", "6", "]", ")", "local_datetime", "=", "datetime", ".", "datetime", ".", "utcfromtimestamp", "(", "p", ".", "stat", "(", ")", ".", "st_mtime", ")", "if", "local_datetime", "<", "s3_datetime", ":", "info", "(", "\"File %s hasn't been modified since last \"", "\"being uploaded\"", "%", "(", "file_key", ")", ")", "continue", "# File is newer, let's process and upload", "info", "(", "\"Uploading %s...\"", "%", "(", "file_key", ")", ")", "try", ":", "s3_key", ".", "set_contents_from_string", "(", "file_data", ",", "headers", ",", "policy", "=", "acl", ",", "replace", "=", "True", ",", "md5", "=", "(", "file_md5", ",", "file_md5_64", ")", ")", "except", "Exception", "as", "e", ":", "error", "(", "\"Failed: %s\"", "%", "e", ")", "raise" ]
f04f8a4248c571f3d5ce882b325884a3e5d80203
valid
download_s3
Download a remote file from S3.
paved/s3.py
def download_s3(bucket_name, file_key, file_path, force=False): """Download a remote file from S3. """ file_path = path(file_path) bucket = open_s3(bucket_name) file_dir = file_path.dirname() file_dir.makedirs() s3_key = bucket.get_key(file_key) if file_path.exists(): file_data = file_path.bytes() file_md5, file_md5_64 = s3_key.get_md5_from_hexdigest(hashlib.md5(file_data).hexdigest()) # Check the hash. try: s3_md5 = s3_key.etag.replace('"', '') except KeyError: pass else: if s3_md5 == file_md5: info('Hash is the same. Skipping %s' % file_path) return elif not force: # Check if file on S3 is older than local file. s3_datetime = datetime.datetime(*time.strptime( s3_key.last_modified, '%a, %d %b %Y %H:%M:%S %Z')[0:6]) local_datetime = datetime.datetime.utcfromtimestamp(file_path.stat().st_mtime) if s3_datetime < local_datetime: info("File at %s is less recent than the local version." % (file_key)) return # If it is newer, let's process and upload info("Downloading %s..." % (file_key)) try: with open(file_path, 'w') as fo: s3_key.get_contents_to_file(fo) except Exception as e: error("Failed: %s" % e) raise
def download_s3(bucket_name, file_key, file_path, force=False): """Download a remote file from S3. """ file_path = path(file_path) bucket = open_s3(bucket_name) file_dir = file_path.dirname() file_dir.makedirs() s3_key = bucket.get_key(file_key) if file_path.exists(): file_data = file_path.bytes() file_md5, file_md5_64 = s3_key.get_md5_from_hexdigest(hashlib.md5(file_data).hexdigest()) # Check the hash. try: s3_md5 = s3_key.etag.replace('"', '') except KeyError: pass else: if s3_md5 == file_md5: info('Hash is the same. Skipping %s' % file_path) return elif not force: # Check if file on S3 is older than local file. s3_datetime = datetime.datetime(*time.strptime( s3_key.last_modified, '%a, %d %b %Y %H:%M:%S %Z')[0:6]) local_datetime = datetime.datetime.utcfromtimestamp(file_path.stat().st_mtime) if s3_datetime < local_datetime: info("File at %s is less recent than the local version." % (file_key)) return # If it is newer, let's process and upload info("Downloading %s..." % (file_key)) try: with open(file_path, 'w') as fo: s3_key.get_contents_to_file(fo) except Exception as e: error("Failed: %s" % e) raise
[ "Download", "a", "remote", "file", "from", "S3", "." ]
eykd/paved
python
https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/s3.py#L97-L138
[ "def", "download_s3", "(", "bucket_name", ",", "file_key", ",", "file_path", ",", "force", "=", "False", ")", ":", "file_path", "=", "path", "(", "file_path", ")", "bucket", "=", "open_s3", "(", "bucket_name", ")", "file_dir", "=", "file_path", ".", "dirname", "(", ")", "file_dir", ".", "makedirs", "(", ")", "s3_key", "=", "bucket", ".", "get_key", "(", "file_key", ")", "if", "file_path", ".", "exists", "(", ")", ":", "file_data", "=", "file_path", ".", "bytes", "(", ")", "file_md5", ",", "file_md5_64", "=", "s3_key", ".", "get_md5_from_hexdigest", "(", "hashlib", ".", "md5", "(", "file_data", ")", ".", "hexdigest", "(", ")", ")", "# Check the hash.", "try", ":", "s3_md5", "=", "s3_key", ".", "etag", ".", "replace", "(", "'\"'", ",", "''", ")", "except", "KeyError", ":", "pass", "else", ":", "if", "s3_md5", "==", "file_md5", ":", "info", "(", "'Hash is the same. Skipping %s'", "%", "file_path", ")", "return", "elif", "not", "force", ":", "# Check if file on S3 is older than local file.", "s3_datetime", "=", "datetime", ".", "datetime", "(", "*", "time", ".", "strptime", "(", "s3_key", ".", "last_modified", ",", "'%a, %d %b %Y %H:%M:%S %Z'", ")", "[", "0", ":", "6", "]", ")", "local_datetime", "=", "datetime", ".", "datetime", ".", "utcfromtimestamp", "(", "file_path", ".", "stat", "(", ")", ".", "st_mtime", ")", "if", "s3_datetime", "<", "local_datetime", ":", "info", "(", "\"File at %s is less recent than the local version.\"", "%", "(", "file_key", ")", ")", "return", "# If it is newer, let's process and upload", "info", "(", "\"Downloading %s...\"", "%", "(", "file_key", ")", ")", "try", ":", "with", "open", "(", "file_path", ",", "'w'", ")", "as", "fo", ":", "s3_key", ".", "get_contents_to_file", "(", "fo", ")", "except", "Exception", "as", "e", ":", "error", "(", "\"Failed: %s\"", "%", "e", ")", "raise" ]
f04f8a4248c571f3d5ce882b325884a3e5d80203
valid
create_ical
Creates an ical .ics file for an event using python-card-me.
build/lib/happenings/views.py
def create_ical(request, slug): """ Creates an ical .ics file for an event using python-card-me. """ event = get_object_or_404(Event, slug=slug) # convert dates to datetimes. # when we change code to datetimes, we won't have to do this. start = event.start_date start = datetime.datetime(start.year, start.month, start.day) if event.end_date: end = event.end_date end = datetime.datetime(end.year, end.month, end.day) else: end = start cal = card_me.iCalendar() cal.add('method').value = 'PUBLISH' vevent = cal.add('vevent') vevent.add('dtstart').value = start vevent.add('dtend').value = end vevent.add('dtstamp').value = datetime.datetime.now() vevent.add('summary').value = event.name response = HttpResponse(cal.serialize(), content_type='text/calendar') response['Filename'] = 'filename.ics' response['Content-Disposition'] = 'attachment; filename=filename.ics' return response
def create_ical(request, slug): """ Creates an ical .ics file for an event using python-card-me. """ event = get_object_or_404(Event, slug=slug) # convert dates to datetimes. # when we change code to datetimes, we won't have to do this. start = event.start_date start = datetime.datetime(start.year, start.month, start.day) if event.end_date: end = event.end_date end = datetime.datetime(end.year, end.month, end.day) else: end = start cal = card_me.iCalendar() cal.add('method').value = 'PUBLISH' vevent = cal.add('vevent') vevent.add('dtstart').value = start vevent.add('dtend').value = end vevent.add('dtstamp').value = datetime.datetime.now() vevent.add('summary').value = event.name response = HttpResponse(cal.serialize(), content_type='text/calendar') response['Filename'] = 'filename.ics' response['Content-Disposition'] = 'attachment; filename=filename.ics' return response
[ "Creates", "an", "ical", ".", "ics", "file", "for", "an", "event", "using", "python", "-", "card", "-", "me", "." ]
tBaxter/tango-happenings
python
https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/views.py#L125-L149
[ "def", "create_ical", "(", "request", ",", "slug", ")", ":", "event", "=", "get_object_or_404", "(", "Event", ",", "slug", "=", "slug", ")", "# convert dates to datetimes.", "# when we change code to datetimes, we won't have to do this.", "start", "=", "event", ".", "start_date", "start", "=", "datetime", ".", "datetime", "(", "start", ".", "year", ",", "start", ".", "month", ",", "start", ".", "day", ")", "if", "event", ".", "end_date", ":", "end", "=", "event", ".", "end_date", "end", "=", "datetime", ".", "datetime", "(", "end", ".", "year", ",", "end", ".", "month", ",", "end", ".", "day", ")", "else", ":", "end", "=", "start", "cal", "=", "card_me", ".", "iCalendar", "(", ")", "cal", ".", "add", "(", "'method'", ")", ".", "value", "=", "'PUBLISH'", "vevent", "=", "cal", ".", "add", "(", "'vevent'", ")", "vevent", ".", "add", "(", "'dtstart'", ")", ".", "value", "=", "start", "vevent", ".", "add", "(", "'dtend'", ")", ".", "value", "=", "end", "vevent", ".", "add", "(", "'dtstamp'", ")", ".", "value", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "vevent", ".", "add", "(", "'summary'", ")", ".", "value", "=", "event", ".", "name", "response", "=", "HttpResponse", "(", "cal", ".", "serialize", "(", ")", ",", "content_type", "=", "'text/calendar'", ")", "response", "[", "'Filename'", "]", "=", "'filename.ics'", "response", "[", "'Content-Disposition'", "]", "=", "'attachment; filename=filename.ics'", "return", "response" ]
cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2
valid
event_all_comments_list
Returns a list view of all comments for a given event. Combines event comments and update comments in one list.
build/lib/happenings/views.py
def event_all_comments_list(request, slug): """ Returns a list view of all comments for a given event. Combines event comments and update comments in one list. """ event = get_object_or_404(Event, slug=slug) comments = event.all_comments page = int(request.GET.get('page', 99999)) # feed empty page by default to push to last page is_paginated = False if comments: paginator = Paginator(comments, 50) # Show 50 comments per page try: comments = paginator.page(page) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. comments = paginator.page(paginator.num_pages) is_paginated = comments.has_other_pages() return render(request, 'happenings/event_comments.html', { "event": event, "comment_list": comments, "object_list": comments, "page_obj": comments, "page": page, "is_paginated": is_paginated, "key": key })
def event_all_comments_list(request, slug): """ Returns a list view of all comments for a given event. Combines event comments and update comments in one list. """ event = get_object_or_404(Event, slug=slug) comments = event.all_comments page = int(request.GET.get('page', 99999)) # feed empty page by default to push to last page is_paginated = False if comments: paginator = Paginator(comments, 50) # Show 50 comments per page try: comments = paginator.page(page) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. comments = paginator.page(paginator.num_pages) is_paginated = comments.has_other_pages() return render(request, 'happenings/event_comments.html', { "event": event, "comment_list": comments, "object_list": comments, "page_obj": comments, "page": page, "is_paginated": is_paginated, "key": key })
[ "Returns", "a", "list", "view", "of", "all", "comments", "for", "a", "given", "event", ".", "Combines", "event", "comments", "and", "update", "comments", "in", "one", "list", "." ]
tBaxter/tango-happenings
python
https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/views.py#L152-L178
[ "def", "event_all_comments_list", "(", "request", ",", "slug", ")", ":", "event", "=", "get_object_or_404", "(", "Event", ",", "slug", "=", "slug", ")", "comments", "=", "event", ".", "all_comments", "page", "=", "int", "(", "request", ".", "GET", ".", "get", "(", "'page'", ",", "99999", ")", ")", "# feed empty page by default to push to last page", "is_paginated", "=", "False", "if", "comments", ":", "paginator", "=", "Paginator", "(", "comments", ",", "50", ")", "# Show 50 comments per page", "try", ":", "comments", "=", "paginator", ".", "page", "(", "page", ")", "except", "EmptyPage", ":", "# If page is out of range (e.g. 9999), deliver last page of results.", "comments", "=", "paginator", ".", "page", "(", "paginator", ".", "num_pages", ")", "is_paginated", "=", "comments", ".", "has_other_pages", "(", ")", "return", "render", "(", "request", ",", "'happenings/event_comments.html'", ",", "{", "\"event\"", ":", "event", ",", "\"comment_list\"", ":", "comments", ",", "\"object_list\"", ":", "comments", ",", "\"page_obj\"", ":", "comments", ",", "\"page\"", ":", "page", ",", "\"is_paginated\"", ":", "is_paginated", ",", "\"key\"", ":", "key", "}", ")" ]
cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2
valid
event_update_list
Returns a list view of updates for a given event. If the event is over, it will be in chronological order. If the event is upcoming or still going, it will be in reverse chronological order.
build/lib/happenings/views.py
def event_update_list(request, slug): """ Returns a list view of updates for a given event. If the event is over, it will be in chronological order. If the event is upcoming or still going, it will be in reverse chronological order. """ event = get_object_or_404(Event, slug=slug) updates = Update.objects.filter(event__slug=slug) if event.recently_ended(): # if the event is over, use chronological order updates = updates.order_by('id') else: # if not, use reverse chronological updates = updates.order_by('-id') return render(request, 'happenings/updates/update_list.html', { 'event': event, 'object_list': updates, })
def event_update_list(request, slug): """ Returns a list view of updates for a given event. If the event is over, it will be in chronological order. If the event is upcoming or still going, it will be in reverse chronological order. """ event = get_object_or_404(Event, slug=slug) updates = Update.objects.filter(event__slug=slug) if event.recently_ended(): # if the event is over, use chronological order updates = updates.order_by('id') else: # if not, use reverse chronological updates = updates.order_by('-id') return render(request, 'happenings/updates/update_list.html', { 'event': event, 'object_list': updates, })
[ "Returns", "a", "list", "view", "of", "updates", "for", "a", "given", "event", ".", "If", "the", "event", "is", "over", "it", "will", "be", "in", "chronological", "order", ".", "If", "the", "event", "is", "upcoming", "or", "still", "going", "it", "will", "be", "in", "reverse", "chronological", "order", "." ]
tBaxter/tango-happenings
python
https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/views.py#L181-L199
[ "def", "event_update_list", "(", "request", ",", "slug", ")", ":", "event", "=", "get_object_or_404", "(", "Event", ",", "slug", "=", "slug", ")", "updates", "=", "Update", ".", "objects", ".", "filter", "(", "event__slug", "=", "slug", ")", "if", "event", ".", "recently_ended", "(", ")", ":", "# if the event is over, use chronological order", "updates", "=", "updates", ".", "order_by", "(", "'id'", ")", "else", ":", "# if not, use reverse chronological", "updates", "=", "updates", ".", "order_by", "(", "'-id'", ")", "return", "render", "(", "request", ",", "'happenings/updates/update_list.html'", ",", "{", "'event'", ":", "event", ",", "'object_list'", ":", "updates", ",", "}", ")" ]
cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2
valid
video_list
Displays list of videos for given event.
build/lib/happenings/views.py
def video_list(request, slug): """ Displays list of videos for given event. """ event = get_object_or_404(Event, slug=slug) return render(request, 'video/video_list.html', { 'event': event, 'video_list': event.eventvideo_set.all() })
def video_list(request, slug): """ Displays list of videos for given event. """ event = get_object_or_404(Event, slug=slug) return render(request, 'video/video_list.html', { 'event': event, 'video_list': event.eventvideo_set.all() })
[ "Displays", "list", "of", "videos", "for", "given", "event", "." ]
tBaxter/tango-happenings
python
https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/views.py#L202-L210
[ "def", "video_list", "(", "request", ",", "slug", ")", ":", "event", "=", "get_object_or_404", "(", "Event", ",", "slug", "=", "slug", ")", "return", "render", "(", "request", ",", "'video/video_list.html'", ",", "{", "'event'", ":", "event", ",", "'video_list'", ":", "event", ".", "eventvideo_set", ".", "all", "(", ")", "}", ")" ]
cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2
valid
add_event
Public form to add an event.
build/lib/happenings/views.py
def add_event(request): """ Public form to add an event. """ form = AddEventForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.sites = settings.SITE_ID instance.submitted_by = request.user instance.approved = True instance.slug = slugify(instance.name) instance.save() messages.success(request, 'Your event has been added.') return HttpResponseRedirect(reverse('events_index')) return render(request, 'happenings/event_form.html', { 'form': form, 'form_title': 'Add an event' })
def add_event(request): """ Public form to add an event. """ form = AddEventForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.sites = settings.SITE_ID instance.submitted_by = request.user instance.approved = True instance.slug = slugify(instance.name) instance.save() messages.success(request, 'Your event has been added.') return HttpResponseRedirect(reverse('events_index')) return render(request, 'happenings/event_form.html', { 'form': form, 'form_title': 'Add an event' })
[ "Public", "form", "to", "add", "an", "event", "." ]
tBaxter/tango-happenings
python
https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/views.py#L214-L229
[ "def", "add_event", "(", "request", ")", ":", "form", "=", "AddEventForm", "(", "request", ".", "POST", "or", "None", ")", "if", "form", ".", "is_valid", "(", ")", ":", "instance", "=", "form", ".", "save", "(", "commit", "=", "False", ")", "instance", ".", "sites", "=", "settings", ".", "SITE_ID", "instance", ".", "submitted_by", "=", "request", ".", "user", "instance", ".", "approved", "=", "True", "instance", ".", "slug", "=", "slugify", "(", "instance", ".", "name", ")", "instance", ".", "save", "(", ")", "messages", ".", "success", "(", "request", ",", "'Your event has been added.'", ")", "return", "HttpResponseRedirect", "(", "reverse", "(", "'events_index'", ")", ")", "return", "render", "(", "request", ",", "'happenings/event_form.html'", ",", "{", "'form'", ":", "form", ",", "'form_title'", ":", "'Add an event'", "}", ")" ]
cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2
valid
add_memory
Adds a memory to an event.
build/lib/happenings/views.py
def add_memory(request, slug): """ Adds a memory to an event. """ event = get_object_or_404(Event, slug=slug) form = MemoryForm(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.event = event instance.save() msg = "Your thoughts were added. " if request.FILES: photo_list = request.FILES.getlist('photos') photo_count = len(photo_list) for upload_file in photo_list: process_upload(upload_file, instance, form, event, request) if photo_count > 1: msg += "{} images were added and should appear soon.".format(photo_count) else: msg += "{} image was added and should appear soon.".format(photo_count) messages.success(request, msg) return HttpResponseRedirect('../') return render(request, 'happenings/add_memories.html', {'form': form, 'event': event})
def add_memory(request, slug): """ Adds a memory to an event. """ event = get_object_or_404(Event, slug=slug) form = MemoryForm(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.event = event instance.save() msg = "Your thoughts were added. " if request.FILES: photo_list = request.FILES.getlist('photos') photo_count = len(photo_list) for upload_file in photo_list: process_upload(upload_file, instance, form, event, request) if photo_count > 1: msg += "{} images were added and should appear soon.".format(photo_count) else: msg += "{} image was added and should appear soon.".format(photo_count) messages.success(request, msg) return HttpResponseRedirect('../') return render(request, 'happenings/add_memories.html', {'form': form, 'event': event})
[ "Adds", "a", "memory", "to", "an", "event", "." ]
tBaxter/tango-happenings
python
https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/views.py#L266-L288
[ "def", "add_memory", "(", "request", ",", "slug", ")", ":", "event", "=", "get_object_or_404", "(", "Event", ",", "slug", "=", "slug", ")", "form", "=", "MemoryForm", "(", "request", ".", "POST", "or", "None", ",", "request", ".", "FILES", "or", "None", ")", "if", "form", ".", "is_valid", "(", ")", ":", "instance", "=", "form", ".", "save", "(", "commit", "=", "False", ")", "instance", ".", "user", "=", "request", ".", "user", "instance", ".", "event", "=", "event", "instance", ".", "save", "(", ")", "msg", "=", "\"Your thoughts were added. \"", "if", "request", ".", "FILES", ":", "photo_list", "=", "request", ".", "FILES", ".", "getlist", "(", "'photos'", ")", "photo_count", "=", "len", "(", "photo_list", ")", "for", "upload_file", "in", "photo_list", ":", "process_upload", "(", "upload_file", ",", "instance", ",", "form", ",", "event", ",", "request", ")", "if", "photo_count", ">", "1", ":", "msg", "+=", "\"{} images were added and should appear soon.\"", ".", "format", "(", "photo_count", ")", "else", ":", "msg", "+=", "\"{} image was added and should appear soon.\"", ".", "format", "(", "photo_count", ")", "messages", ".", "success", "(", "request", ",", "msg", ")", "return", "HttpResponseRedirect", "(", "'../'", ")", "return", "render", "(", "request", ",", "'happenings/add_memories.html'", ",", "{", "'form'", ":", "form", ",", "'event'", ":", "event", "}", ")" ]
cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2
valid
process_upload
Helper function that actually processes and saves the upload(s). Segregated out for readability.
build/lib/happenings/views.py
def process_upload(upload_file, instance, form, event, request): """ Helper function that actually processes and saves the upload(s). Segregated out for readability. """ caption = form.cleaned_data.get('caption') upload_name = upload_file.name.lower() if upload_name.endswith('.jpg') or upload_name.endswith('.jpeg'): try: upload = Image( event=event, image=upload_file, caption=caption, ) upload.save() instance.photos.add(upload) except Exception as error: messages.error(request, 'Error saving image: {}.'.format(error))
def process_upload(upload_file, instance, form, event, request): """ Helper function that actually processes and saves the upload(s). Segregated out for readability. """ caption = form.cleaned_data.get('caption') upload_name = upload_file.name.lower() if upload_name.endswith('.jpg') or upload_name.endswith('.jpeg'): try: upload = Image( event=event, image=upload_file, caption=caption, ) upload.save() instance.photos.add(upload) except Exception as error: messages.error(request, 'Error saving image: {}.'.format(error))
[ "Helper", "function", "that", "actually", "processes", "and", "saves", "the", "upload", "(", "s", ")", ".", "Segregated", "out", "for", "readability", "." ]
tBaxter/tango-happenings
python
https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/views.py#L313-L330
[ "def", "process_upload", "(", "upload_file", ",", "instance", ",", "form", ",", "event", ",", "request", ")", ":", "caption", "=", "form", ".", "cleaned_data", ".", "get", "(", "'caption'", ")", "upload_name", "=", "upload_file", ".", "name", ".", "lower", "(", ")", "if", "upload_name", ".", "endswith", "(", "'.jpg'", ")", "or", "upload_name", ".", "endswith", "(", "'.jpeg'", ")", ":", "try", ":", "upload", "=", "Image", "(", "event", "=", "event", ",", "image", "=", "upload_file", ",", "caption", "=", "caption", ",", ")", "upload", ".", "save", "(", ")", "instance", ".", "photos", ".", "add", "(", "upload", ")", "except", "Exception", "as", "error", ":", "messages", ".", "error", "(", "request", ",", "'Error saving image: {}.'", ".", "format", "(", "error", ")", ")" ]
cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2
valid
_get_search_path
Find the parent python path that contains the __main__'s file directory :param main_file_dir: __main__'s file directory :param sys_path: paths list to match directory against (like sys.path)
rel_imp.py
def _get_search_path(main_file_dir, sys_path): ''' Find the parent python path that contains the __main__'s file directory :param main_file_dir: __main__'s file directory :param sys_path: paths list to match directory against (like sys.path) ''' # List to gather candidate parent paths paths = [] # look for paths containing the directory for pth in sys_path: # convert relative path to absolute pth = path.abspath(pth) # filter out __main__'s file directory, it will be in the sys.path # filter in parent paths containing the package if (pth != main_file_dir and pth == path.commonprefix((pth, main_file_dir))): paths.append(pth) # check if we have results if paths: # we found candidates, look for the largest(closest) parent search path paths.sort() return paths[-1]
def _get_search_path(main_file_dir, sys_path): ''' Find the parent python path that contains the __main__'s file directory :param main_file_dir: __main__'s file directory :param sys_path: paths list to match directory against (like sys.path) ''' # List to gather candidate parent paths paths = [] # look for paths containing the directory for pth in sys_path: # convert relative path to absolute pth = path.abspath(pth) # filter out __main__'s file directory, it will be in the sys.path # filter in parent paths containing the package if (pth != main_file_dir and pth == path.commonprefix((pth, main_file_dir))): paths.append(pth) # check if we have results if paths: # we found candidates, look for the largest(closest) parent search path paths.sort() return paths[-1]
[ "Find", "the", "parent", "python", "path", "that", "contains", "the", "__main__", "s", "file", "directory" ]
joaduo/rel_imp
python
https://github.com/joaduo/rel_imp/blob/eff2d4608d6857d18ec8acda661cdf106a9f32d0/rel_imp.py#L37-L59
[ "def", "_get_search_path", "(", "main_file_dir", ",", "sys_path", ")", ":", "# List to gather candidate parent paths", "paths", "=", "[", "]", "# look for paths containing the directory", "for", "pth", "in", "sys_path", ":", "# convert relative path to absolute", "pth", "=", "path", ".", "abspath", "(", "pth", ")", "# filter out __main__'s file directory, it will be in the sys.path", "# filter in parent paths containing the package", "if", "(", "pth", "!=", "main_file_dir", "and", "pth", "==", "path", ".", "commonprefix", "(", "(", "pth", ",", "main_file_dir", ")", ")", ")", ":", "paths", ".", "append", "(", "pth", ")", "# check if we have results", "if", "paths", ":", "# we found candidates, look for the largest(closest) parent search path", "paths", ".", "sort", "(", ")", "return", "paths", "[", "-", "1", "]" ]
eff2d4608d6857d18ec8acda661cdf106a9f32d0
valid
_try_search_paths
Try different strategies to found the path containing the __main__'s file. Will try strategies, in the following order: 1. Building file's path with PWD env var. 2. Building file's path from absolute file's path. 3. Buidling file's path from real file's path. :param main_globals: globals dictionary in __main__
rel_imp.py
def _try_search_paths(main_globals): ''' Try different strategies to found the path containing the __main__'s file. Will try strategies, in the following order: 1. Building file's path with PWD env var. 2. Building file's path from absolute file's path. 3. Buidling file's path from real file's path. :param main_globals: globals dictionary in __main__ ''' # try with abspath fl = main_globals['__file__'] search_path = None if not path.isabs(fl) and os.getenv('PWD'): # Build absolute path from PWD if possible cwd_fl = path.abspath(path.join(os.getenv('PWD'), fl)) main_dir = path.dirname(cwd_fl) search_path = _get_search_path(main_dir, sys.path) if not search_path: # try absolute strategy (will fail on some symlinks configs) main_dir = path.dirname(path.abspath(fl)) search_path = _get_search_path(main_dir, sys.path) if not search_path: # try real path strategy main_dir = path.dirname(path.realpath(fl)) sys_path = [path.realpath(p) for p in sys.path] search_path = _get_search_path(main_dir, sys_path) return main_dir, search_path
def _try_search_paths(main_globals): ''' Try different strategies to found the path containing the __main__'s file. Will try strategies, in the following order: 1. Building file's path with PWD env var. 2. Building file's path from absolute file's path. 3. Buidling file's path from real file's path. :param main_globals: globals dictionary in __main__ ''' # try with abspath fl = main_globals['__file__'] search_path = None if not path.isabs(fl) and os.getenv('PWD'): # Build absolute path from PWD if possible cwd_fl = path.abspath(path.join(os.getenv('PWD'), fl)) main_dir = path.dirname(cwd_fl) search_path = _get_search_path(main_dir, sys.path) if not search_path: # try absolute strategy (will fail on some symlinks configs) main_dir = path.dirname(path.abspath(fl)) search_path = _get_search_path(main_dir, sys.path) if not search_path: # try real path strategy main_dir = path.dirname(path.realpath(fl)) sys_path = [path.realpath(p) for p in sys.path] search_path = _get_search_path(main_dir, sys_path) return main_dir, search_path
[ "Try", "different", "strategies", "to", "found", "the", "path", "containing", "the", "__main__", "s", "file", ".", "Will", "try", "strategies", "in", "the", "following", "order", ":", "1", ".", "Building", "file", "s", "path", "with", "PWD", "env", "var", ".", "2", ".", "Building", "file", "s", "path", "from", "absolute", "file", "s", "path", ".", "3", ".", "Buidling", "file", "s", "path", "from", "real", "file", "s", "path", "." ]
joaduo/rel_imp
python
https://github.com/joaduo/rel_imp/blob/eff2d4608d6857d18ec8acda661cdf106a9f32d0/rel_imp.py#L72-L102
[ "def", "_try_search_paths", "(", "main_globals", ")", ":", "# try with abspath", "fl", "=", "main_globals", "[", "'__file__'", "]", "search_path", "=", "None", "if", "not", "path", ".", "isabs", "(", "fl", ")", "and", "os", ".", "getenv", "(", "'PWD'", ")", ":", "# Build absolute path from PWD if possible", "cwd_fl", "=", "path", ".", "abspath", "(", "path", ".", "join", "(", "os", ".", "getenv", "(", "'PWD'", ")", ",", "fl", ")", ")", "main_dir", "=", "path", ".", "dirname", "(", "cwd_fl", ")", "search_path", "=", "_get_search_path", "(", "main_dir", ",", "sys", ".", "path", ")", "if", "not", "search_path", ":", "# try absolute strategy (will fail on some symlinks configs)", "main_dir", "=", "path", ".", "dirname", "(", "path", ".", "abspath", "(", "fl", ")", ")", "search_path", "=", "_get_search_path", "(", "main_dir", ",", "sys", ".", "path", ")", "if", "not", "search_path", ":", "# try real path strategy", "main_dir", "=", "path", ".", "dirname", "(", "path", ".", "realpath", "(", "fl", ")", ")", "sys_path", "=", "[", "path", ".", "realpath", "(", "p", ")", "for", "p", "in", "sys", ".", "path", "]", "search_path", "=", "_get_search_path", "(", "main_dir", ",", "sys_path", ")", "return", "main_dir", ",", "search_path" ]
eff2d4608d6857d18ec8acda661cdf106a9f32d0
valid
_solve_pkg
Find parent python path of __main__. From there solve the package containing __main__, import it and set __package__ variable. :param main_globals: globals dictionary in __main__
rel_imp.py
def _solve_pkg(main_globals): ''' Find parent python path of __main__. From there solve the package containing __main__, import it and set __package__ variable. :param main_globals: globals dictionary in __main__ ''' # find __main__'s file directory and search path main_dir, search_path = _try_search_paths(main_globals) if not search_path: _log_debug('Could not solve parent python path for %r' % main_dir) # no candidates for search path, return return # solve package name from search path pkg_str = path.relpath(main_dir, search_path).replace(path.sep, '.') # Remove wrong starting string for site-packages site_pkgs = 'site-packages.' if pkg_str.startswith(site_pkgs): pkg_str = pkg_str[len(site_pkgs):] assert pkg_str _log_debug('pkg_str=%r' % pkg_str) # import the package in order to set __package__ value later try: if '__init__.py' in main_globals['__file__']: _log_debug('__init__ script. This module is its own package') # The __main__ is __init__.py => its own package # If we treat it as a normal module it would be imported twice # So we simply reuse it sys.modules[pkg_str] = sys.modules['__main__'] # We need to set __path__ because its needed for # relative importing sys.modules[pkg_str].__path__ = [main_dir] # We need to import parent package, something that would # happen automatically in non-faked import parent_pkg_str = '.'.join(pkg_str.split('.')[:-1]) if parent_pkg_str: importlib.import_module(parent_pkg_str) else: _log_debug('Importing package %r' % pkg_str) # we need to import the package to be available importlib.import_module(pkg_str) # finally enable relative import main_globals['__package__'] = pkg_str return pkg_str except ImportError as e: # In many situations we won't care if it fails, simply report error # main will fail anyway if finds an explicit relative import _print_exc(e)
def _solve_pkg(main_globals): ''' Find parent python path of __main__. From there solve the package containing __main__, import it and set __package__ variable. :param main_globals: globals dictionary in __main__ ''' # find __main__'s file directory and search path main_dir, search_path = _try_search_paths(main_globals) if not search_path: _log_debug('Could not solve parent python path for %r' % main_dir) # no candidates for search path, return return # solve package name from search path pkg_str = path.relpath(main_dir, search_path).replace(path.sep, '.') # Remove wrong starting string for site-packages site_pkgs = 'site-packages.' if pkg_str.startswith(site_pkgs): pkg_str = pkg_str[len(site_pkgs):] assert pkg_str _log_debug('pkg_str=%r' % pkg_str) # import the package in order to set __package__ value later try: if '__init__.py' in main_globals['__file__']: _log_debug('__init__ script. This module is its own package') # The __main__ is __init__.py => its own package # If we treat it as a normal module it would be imported twice # So we simply reuse it sys.modules[pkg_str] = sys.modules['__main__'] # We need to set __path__ because its needed for # relative importing sys.modules[pkg_str].__path__ = [main_dir] # We need to import parent package, something that would # happen automatically in non-faked import parent_pkg_str = '.'.join(pkg_str.split('.')[:-1]) if parent_pkg_str: importlib.import_module(parent_pkg_str) else: _log_debug('Importing package %r' % pkg_str) # we need to import the package to be available importlib.import_module(pkg_str) # finally enable relative import main_globals['__package__'] = pkg_str return pkg_str except ImportError as e: # In many situations we won't care if it fails, simply report error # main will fail anyway if finds an explicit relative import _print_exc(e)
[ "Find", "parent", "python", "path", "of", "__main__", ".", "From", "there", "solve", "the", "package", "containing", "__main__", "import", "it", "and", "set", "__package__", "variable", "." ]
joaduo/rel_imp
python
https://github.com/joaduo/rel_imp/blob/eff2d4608d6857d18ec8acda661cdf106a9f32d0/rel_imp.py#L105-L152
[ "def", "_solve_pkg", "(", "main_globals", ")", ":", "# find __main__'s file directory and search path", "main_dir", ",", "search_path", "=", "_try_search_paths", "(", "main_globals", ")", "if", "not", "search_path", ":", "_log_debug", "(", "'Could not solve parent python path for %r'", "%", "main_dir", ")", "# no candidates for search path, return", "return", "# solve package name from search path", "pkg_str", "=", "path", ".", "relpath", "(", "main_dir", ",", "search_path", ")", ".", "replace", "(", "path", ".", "sep", ",", "'.'", ")", "# Remove wrong starting string for site-packages", "site_pkgs", "=", "'site-packages.'", "if", "pkg_str", ".", "startswith", "(", "site_pkgs", ")", ":", "pkg_str", "=", "pkg_str", "[", "len", "(", "site_pkgs", ")", ":", "]", "assert", "pkg_str", "_log_debug", "(", "'pkg_str=%r'", "%", "pkg_str", ")", "# import the package in order to set __package__ value later", "try", ":", "if", "'__init__.py'", "in", "main_globals", "[", "'__file__'", "]", ":", "_log_debug", "(", "'__init__ script. This module is its own package'", ")", "# The __main__ is __init__.py => its own package", "# If we treat it as a normal module it would be imported twice", "# So we simply reuse it", "sys", ".", "modules", "[", "pkg_str", "]", "=", "sys", ".", "modules", "[", "'__main__'", "]", "# We need to set __path__ because its needed for", "# relative importing", "sys", ".", "modules", "[", "pkg_str", "]", ".", "__path__", "=", "[", "main_dir", "]", "# We need to import parent package, something that would", "# happen automatically in non-faked import", "parent_pkg_str", "=", "'.'", ".", "join", "(", "pkg_str", ".", "split", "(", "'.'", ")", "[", ":", "-", "1", "]", ")", "if", "parent_pkg_str", ":", "importlib", ".", "import_module", "(", "parent_pkg_str", ")", "else", ":", "_log_debug", "(", "'Importing package %r'", "%", "pkg_str", ")", "# we need to import the package to be available", "importlib", ".", "import_module", "(", "pkg_str", ")", "# finally enable relative import", "main_globals", "[", "'__package__'", "]", "=", "pkg_str", "return", "pkg_str", "except", "ImportError", "as", "e", ":", "# In many situations we won't care if it fails, simply report error", "# main will fail anyway if finds an explicit relative import", "_print_exc", "(", "e", ")" ]
eff2d4608d6857d18ec8acda661cdf106a9f32d0
valid
_log_debug
Log at debug level :param msg: message to log
rel_imp.py
def _log_debug(msg): ''' Log at debug level :param msg: message to log ''' if _log_level <= DEBUG: if _log_level == TRACE: traceback.print_stack() _log(msg)
def _log_debug(msg): ''' Log at debug level :param msg: message to log ''' if _log_level <= DEBUG: if _log_level == TRACE: traceback.print_stack() _log(msg)
[ "Log", "at", "debug", "level", ":", "param", "msg", ":", "message", "to", "log" ]
joaduo/rel_imp
python
https://github.com/joaduo/rel_imp/blob/eff2d4608d6857d18ec8acda661cdf106a9f32d0/rel_imp.py#L164-L172
[ "def", "_log_debug", "(", "msg", ")", ":", "if", "_log_level", "<=", "DEBUG", ":", "if", "_log_level", "==", "TRACE", ":", "traceback", ".", "print_stack", "(", ")", "_log", "(", "msg", ")" ]
eff2d4608d6857d18ec8acda661cdf106a9f32d0
valid
init
Enables explicit relative import in sub-modules when ran as __main__ :param log_level: module's inner logger level (equivalent to logging pkg)
rel_imp.py
def init(log_level=ERROR): ''' Enables explicit relative import in sub-modules when ran as __main__ :param log_level: module's inner logger level (equivalent to logging pkg) ''' global _initialized if _initialized: return else: _initialized = True # find caller's frame frame = currentframe() # go 1 frame back to find who imported us frame = frame.f_back _init(frame, log_level)
def init(log_level=ERROR): ''' Enables explicit relative import in sub-modules when ran as __main__ :param log_level: module's inner logger level (equivalent to logging pkg) ''' global _initialized if _initialized: return else: _initialized = True # find caller's frame frame = currentframe() # go 1 frame back to find who imported us frame = frame.f_back _init(frame, log_level)
[ "Enables", "explicit", "relative", "import", "in", "sub", "-", "modules", "when", "ran", "as", "__main__", ":", "param", "log_level", ":", "module", "s", "inner", "logger", "level", "(", "equivalent", "to", "logging", "pkg", ")" ]
joaduo/rel_imp
python
https://github.com/joaduo/rel_imp/blob/eff2d4608d6857d18ec8acda661cdf106a9f32d0/rel_imp.py#L195-L209
[ "def", "init", "(", "log_level", "=", "ERROR", ")", ":", "global", "_initialized", "if", "_initialized", ":", "return", "else", ":", "_initialized", "=", "True", "# find caller's frame", "frame", "=", "currentframe", "(", ")", "# go 1 frame back to find who imported us", "frame", "=", "frame", ".", "f_back", "_init", "(", "frame", ",", "log_level", ")" ]
eff2d4608d6857d18ec8acda661cdf106a9f32d0
valid
_init
Enables explicit relative import in sub-modules when ran as __main__ :param log_level: module's inner logger level (equivalent to logging pkg)
rel_imp.py
def _init(frame, log_level=ERROR): ''' Enables explicit relative import in sub-modules when ran as __main__ :param log_level: module's inner logger level (equivalent to logging pkg) ''' global _log_level _log_level = log_level # now we have access to the module globals main_globals = frame.f_globals # If __package__ set or it isn't the __main__, stop and return. # (in some cases relative_import could be called once from outside # __main__ if it was not called in __main__) # (also a reload of relative_import could trigger this function) pkg = main_globals.get('__package__') file_ = main_globals.get('__file__') if pkg or not file_: _log_debug('Package solved or init was called from interactive ' 'console. __package__=%r, __file__=%r' % (pkg, file_)) return try: _solve_pkg(main_globals) except Exception as e: _print_exc(e)
def _init(frame, log_level=ERROR): ''' Enables explicit relative import in sub-modules when ran as __main__ :param log_level: module's inner logger level (equivalent to logging pkg) ''' global _log_level _log_level = log_level # now we have access to the module globals main_globals = frame.f_globals # If __package__ set or it isn't the __main__, stop and return. # (in some cases relative_import could be called once from outside # __main__ if it was not called in __main__) # (also a reload of relative_import could trigger this function) pkg = main_globals.get('__package__') file_ = main_globals.get('__file__') if pkg or not file_: _log_debug('Package solved or init was called from interactive ' 'console. __package__=%r, __file__=%r' % (pkg, file_)) return try: _solve_pkg(main_globals) except Exception as e: _print_exc(e)
[ "Enables", "explicit", "relative", "import", "in", "sub", "-", "modules", "when", "ran", "as", "__main__", ":", "param", "log_level", ":", "module", "s", "inner", "logger", "level", "(", "equivalent", "to", "logging", "pkg", ")" ]
joaduo/rel_imp
python
https://github.com/joaduo/rel_imp/blob/eff2d4608d6857d18ec8acda661cdf106a9f32d0/rel_imp.py#L225-L248
[ "def", "_init", "(", "frame", ",", "log_level", "=", "ERROR", ")", ":", "global", "_log_level", "_log_level", "=", "log_level", "# now we have access to the module globals", "main_globals", "=", "frame", ".", "f_globals", "# If __package__ set or it isn't the __main__, stop and return.", "# (in some cases relative_import could be called once from outside", "# __main__ if it was not called in __main__)", "# (also a reload of relative_import could trigger this function)", "pkg", "=", "main_globals", ".", "get", "(", "'__package__'", ")", "file_", "=", "main_globals", ".", "get", "(", "'__file__'", ")", "if", "pkg", "or", "not", "file_", ":", "_log_debug", "(", "'Package solved or init was called from interactive '", "'console. __package__=%r, __file__=%r'", "%", "(", "pkg", ",", "file_", ")", ")", "return", "try", ":", "_solve_pkg", "(", "main_globals", ")", "except", "Exception", "as", "e", ":", "_print_exc", "(", "e", ")" ]
eff2d4608d6857d18ec8acda661cdf106a9f32d0
valid
curve_fit_unscaled
Use the reduced chi square to unscale :mod:`scipy`'s scaled :func:`scipy.optimize.curve_fit`. *\*args* and *\*\*kwargs* are passed through to :func:`scipy.optimize.curve_fit`. The tuple *popt, pcov, chisq_red* is returned, where *popt* is the optimal values for the parameters, *pcov* is the estimated covariance of *popt*, and *chisq_red* is the reduced chi square. See http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.optimize.curve_fit.html.
scisalt/scipy/curve_fit_unscaled.py
def curve_fit_unscaled(*args, **kwargs): """ Use the reduced chi square to unscale :mod:`scipy`'s scaled :func:`scipy.optimize.curve_fit`. *\*args* and *\*\*kwargs* are passed through to :func:`scipy.optimize.curve_fit`. The tuple *popt, pcov, chisq_red* is returned, where *popt* is the optimal values for the parameters, *pcov* is the estimated covariance of *popt*, and *chisq_red* is the reduced chi square. See http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.optimize.curve_fit.html. """ # Extract verbosity verbose = kwargs.pop('verbose', False) # Do initial fit popt, pcov = _spopt.curve_fit(*args, **kwargs) # Expand positional arguments func = args[0] x = args[1] y = args[2] ddof = len(popt) # Try to use sigma to unscale pcov try: sigma = kwargs['sigma'] if sigma is None: sigma = _np.ones(len(y)) # Get reduced chi-square y_expect = func(x, *popt) chisq_red = _chisquare(y, y_expect, sigma, ddof, verbose=verbose) # Correct scaled covariance matrix pcov = pcov / chisq_red return popt, pcov, chisq_red except ValueError: print('hello')
def curve_fit_unscaled(*args, **kwargs): """ Use the reduced chi square to unscale :mod:`scipy`'s scaled :func:`scipy.optimize.curve_fit`. *\*args* and *\*\*kwargs* are passed through to :func:`scipy.optimize.curve_fit`. The tuple *popt, pcov, chisq_red* is returned, where *popt* is the optimal values for the parameters, *pcov* is the estimated covariance of *popt*, and *chisq_red* is the reduced chi square. See http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.optimize.curve_fit.html. """ # Extract verbosity verbose = kwargs.pop('verbose', False) # Do initial fit popt, pcov = _spopt.curve_fit(*args, **kwargs) # Expand positional arguments func = args[0] x = args[1] y = args[2] ddof = len(popt) # Try to use sigma to unscale pcov try: sigma = kwargs['sigma'] if sigma is None: sigma = _np.ones(len(y)) # Get reduced chi-square y_expect = func(x, *popt) chisq_red = _chisquare(y, y_expect, sigma, ddof, verbose=verbose) # Correct scaled covariance matrix pcov = pcov / chisq_red return popt, pcov, chisq_red except ValueError: print('hello')
[ "Use", "the", "reduced", "chi", "square", "to", "unscale", ":", "mod", ":", "scipy", "s", "scaled", ":", "func", ":", "scipy", ".", "optimize", ".", "curve_fit", ".", "*", "\\", "*", "args", "*", "and", "*", "\\", "*", "\\", "*", "kwargs", "*", "are", "passed", "through", "to", ":", "func", ":", "scipy", ".", "optimize", ".", "curve_fit", ".", "The", "tuple", "*", "popt", "pcov", "chisq_red", "*", "is", "returned", "where", "*", "popt", "*", "is", "the", "optimal", "values", "for", "the", "parameters", "*", "pcov", "*", "is", "the", "estimated", "covariance", "of", "*", "popt", "*", "and", "*", "chisq_red", "*", "is", "the", "reduced", "chi", "square", ".", "See", "http", ":", "//", "docs", ".", "scipy", ".", "org", "/", "doc", "/", "scipy", "-", "0", ".", "15", ".", "1", "/", "reference", "/", "generated", "/", "scipy", ".", "optimize", ".", "curve_fit", ".", "html", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/scipy/curve_fit_unscaled.py#L9-L39
[ "def", "curve_fit_unscaled", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Extract verbosity", "verbose", "=", "kwargs", ".", "pop", "(", "'verbose'", ",", "False", ")", "# Do initial fit", "popt", ",", "pcov", "=", "_spopt", ".", "curve_fit", "(", "*", "args", ",", "*", "*", "kwargs", ")", "# Expand positional arguments", "func", "=", "args", "[", "0", "]", "x", "=", "args", "[", "1", "]", "y", "=", "args", "[", "2", "]", "ddof", "=", "len", "(", "popt", ")", "# Try to use sigma to unscale pcov", "try", ":", "sigma", "=", "kwargs", "[", "'sigma'", "]", "if", "sigma", "is", "None", ":", "sigma", "=", "_np", ".", "ones", "(", "len", "(", "y", ")", ")", "# Get reduced chi-square", "y_expect", "=", "func", "(", "x", ",", "*", "popt", ")", "chisq_red", "=", "_chisquare", "(", "y", ",", "y_expect", ",", "sigma", ",", "ddof", ",", "verbose", "=", "verbose", ")", "# Correct scaled covariance matrix", "pcov", "=", "pcov", "/", "chisq_red", "return", "popt", ",", "pcov", ",", "chisq_red", "except", "ValueError", ":", "print", "(", "'hello'", ")" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
fitimageslice
Fits a gaussian to a slice of an image *img* specified by *xslice* x-coordinates and *yslice* y-coordinates. *res_x* and *res_y* specify image resolution in x and y. *avg_e_func* is a function that returns the energy of the image as a function of x. It should have the form: *avg_e_func(x_1, x_2, h5file, res_y)* Fits a gaussian to a slice of an image. Parameters ---------- img : array Image to be fitted. res_x : int Image resolution in :math:`x`. res_y : int Image resolution in :math:`y`. xslice : (int, int) Slice coordinates in :math:`x` yslice : (int, int) Slice coordinates in :math:`y` avg_e_func : function Of the form *avg_e_func(x_1, x_2, h5file, res_y)*, returns the energy of the image as a function of :math:`x`. h5file : h5file Instance from dataset. plot : boolean Whether to plot or not.
scisalt/accelphys/fitimageslice.py
def fitimageslice(img, res_x, res_y, xslice, yslice, avg_e_func=None, h5file=None, plot=False): """ Fits a gaussian to a slice of an image *img* specified by *xslice* x-coordinates and *yslice* y-coordinates. *res_x* and *res_y* specify image resolution in x and y. *avg_e_func* is a function that returns the energy of the image as a function of x. It should have the form: *avg_e_func(x_1, x_2, h5file, res_y)* Fits a gaussian to a slice of an image. Parameters ---------- img : array Image to be fitted. res_x : int Image resolution in :math:`x`. res_y : int Image resolution in :math:`y`. xslice : (int, int) Slice coordinates in :math:`x` yslice : (int, int) Slice coordinates in :math:`y` avg_e_func : function Of the form *avg_e_func(x_1, x_2, h5file, res_y)*, returns the energy of the image as a function of :math:`x`. h5file : h5file Instance from dataset. plot : boolean Whether to plot or not. """ # ====================================== # Extract start and end values # (NOT necessarily indices!) # ====================================== x_start = xslice[0] x_end = xslice[1] y_start = yslice[0] y_end = yslice[1] # ====================================== # Round to pixel edges. Pixel edges in # px units are at 0.5, 1.5, 2.5, etc. # ====================================== y_low = _np.round(y_start-0.5) + 0.5 y_high = _np.round(y_end-0.5) + 0.5 # ====================================== # Take a strip between edges # ====================================== y_px = linspacestep(1, img.shape[0]) y_bool = _np.logical_and(y_low < y_px, y_px < y_high) strip = img[y_bool, x_start:x_end] # ====================================== # Sum over the strip to get an average # ====================================== histdata = _np.sum(strip, 0) xbins = len(histdata) x = _np.linspace(1, xbins, xbins)*res_x # ====================================== # Fit with a Gaussian to find spot size # ====================================== # plotbool=True # plotbool = False # varbool = False varbool = True gaussout = _sp.GaussResults( x, histdata, sigma_y = _np.ones(xbins), variance = varbool, background = True, p0 = [16000, 0.003, 1e-6, 0] ) if avg_e_func is not None: # ====================================== # Get average energy of strip # ====================================== # Sum to get relative counts of pixels relcounts = _np.sum(strip, 1) / _np.float(_np.sum(strip)) # Integrate each pixel strip Eavg = 0 for i, val in enumerate(linspacestep(y_low, y_high-1)): Eavg = Eavg + avg_e_func(val, val+1, h5file, res_y)*relcounts[i] return Eavg, gaussout else: return gaussout
def fitimageslice(img, res_x, res_y, xslice, yslice, avg_e_func=None, h5file=None, plot=False): """ Fits a gaussian to a slice of an image *img* specified by *xslice* x-coordinates and *yslice* y-coordinates. *res_x* and *res_y* specify image resolution in x and y. *avg_e_func* is a function that returns the energy of the image as a function of x. It should have the form: *avg_e_func(x_1, x_2, h5file, res_y)* Fits a gaussian to a slice of an image. Parameters ---------- img : array Image to be fitted. res_x : int Image resolution in :math:`x`. res_y : int Image resolution in :math:`y`. xslice : (int, int) Slice coordinates in :math:`x` yslice : (int, int) Slice coordinates in :math:`y` avg_e_func : function Of the form *avg_e_func(x_1, x_2, h5file, res_y)*, returns the energy of the image as a function of :math:`x`. h5file : h5file Instance from dataset. plot : boolean Whether to plot or not. """ # ====================================== # Extract start and end values # (NOT necessarily indices!) # ====================================== x_start = xslice[0] x_end = xslice[1] y_start = yslice[0] y_end = yslice[1] # ====================================== # Round to pixel edges. Pixel edges in # px units are at 0.5, 1.5, 2.5, etc. # ====================================== y_low = _np.round(y_start-0.5) + 0.5 y_high = _np.round(y_end-0.5) + 0.5 # ====================================== # Take a strip between edges # ====================================== y_px = linspacestep(1, img.shape[0]) y_bool = _np.logical_and(y_low < y_px, y_px < y_high) strip = img[y_bool, x_start:x_end] # ====================================== # Sum over the strip to get an average # ====================================== histdata = _np.sum(strip, 0) xbins = len(histdata) x = _np.linspace(1, xbins, xbins)*res_x # ====================================== # Fit with a Gaussian to find spot size # ====================================== # plotbool=True # plotbool = False # varbool = False varbool = True gaussout = _sp.GaussResults( x, histdata, sigma_y = _np.ones(xbins), variance = varbool, background = True, p0 = [16000, 0.003, 1e-6, 0] ) if avg_e_func is not None: # ====================================== # Get average energy of strip # ====================================== # Sum to get relative counts of pixels relcounts = _np.sum(strip, 1) / _np.float(_np.sum(strip)) # Integrate each pixel strip Eavg = 0 for i, val in enumerate(linspacestep(y_low, y_high-1)): Eavg = Eavg + avg_e_func(val, val+1, h5file, res_y)*relcounts[i] return Eavg, gaussout else: return gaussout
[ "Fits", "a", "gaussian", "to", "a", "slice", "of", "an", "image", "*", "img", "*", "specified", "by", "*", "xslice", "*", "x", "-", "coordinates", "and", "*", "yslice", "*", "y", "-", "coordinates", ".", "*", "res_x", "*", "and", "*", "res_y", "*", "specify", "image", "resolution", "in", "x", "and", "y", ".", "*", "avg_e_func", "*", "is", "a", "function", "that", "returns", "the", "energy", "of", "the", "image", "as", "a", "function", "of", "x", ".", "It", "should", "have", "the", "form", ":" ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/accelphys/fitimageslice.py#L10-L96
[ "def", "fitimageslice", "(", "img", ",", "res_x", ",", "res_y", ",", "xslice", ",", "yslice", ",", "avg_e_func", "=", "None", ",", "h5file", "=", "None", ",", "plot", "=", "False", ")", ":", "# ======================================", "# Extract start and end values", "# (NOT necessarily indices!)", "# ======================================", "x_start", "=", "xslice", "[", "0", "]", "x_end", "=", "xslice", "[", "1", "]", "y_start", "=", "yslice", "[", "0", "]", "y_end", "=", "yslice", "[", "1", "]", "# ======================================", "# Round to pixel edges. Pixel edges in", "# px units are at 0.5, 1.5, 2.5, etc.", "# ======================================", "y_low", "=", "_np", ".", "round", "(", "y_start", "-", "0.5", ")", "+", "0.5", "y_high", "=", "_np", ".", "round", "(", "y_end", "-", "0.5", ")", "+", "0.5", "# ======================================", "# Take a strip between edges", "# ======================================", "y_px", "=", "linspacestep", "(", "1", ",", "img", ".", "shape", "[", "0", "]", ")", "y_bool", "=", "_np", ".", "logical_and", "(", "y_low", "<", "y_px", ",", "y_px", "<", "y_high", ")", "strip", "=", "img", "[", "y_bool", ",", "x_start", ":", "x_end", "]", "# ======================================", "# Sum over the strip to get an average", "# ======================================", "histdata", "=", "_np", ".", "sum", "(", "strip", ",", "0", ")", "xbins", "=", "len", "(", "histdata", ")", "x", "=", "_np", ".", "linspace", "(", "1", ",", "xbins", ",", "xbins", ")", "*", "res_x", "# ======================================", "# Fit with a Gaussian to find spot size", "# ======================================", "# plotbool=True", "# plotbool = False", "# varbool = False", "varbool", "=", "True", "gaussout", "=", "_sp", ".", "GaussResults", "(", "x", ",", "histdata", ",", "sigma_y", "=", "_np", ".", "ones", "(", "xbins", ")", ",", "variance", "=", "varbool", ",", "background", "=", "True", ",", "p0", "=", "[", "16000", ",", "0.003", ",", "1e-6", ",", "0", "]", ")", "if", "avg_e_func", "is", "not", "None", ":", "# ======================================", "# Get average energy of strip", "# ======================================", "# Sum to get relative counts of pixels", "relcounts", "=", "_np", ".", "sum", "(", "strip", ",", "1", ")", "/", "_np", ".", "float", "(", "_np", ".", "sum", "(", "strip", ")", ")", "# Integrate each pixel strip", "Eavg", "=", "0", "for", "i", ",", "val", "in", "enumerate", "(", "linspacestep", "(", "y_low", ",", "y_high", "-", "1", ")", ")", ":", "Eavg", "=", "Eavg", "+", "avg_e_func", "(", "val", ",", "val", "+", "1", ",", "h5file", ",", "res_y", ")", "*", "relcounts", "[", "i", "]", "return", "Eavg", ",", "gaussout", "else", ":", "return", "gaussout" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
encode
:returns: a JSON-representation of the object
src/infi/gevent_utils/json_utils.py
def encode(python_object, indent=None, large_object=False): """:returns: a JSON-representation of the object""" # sorted keys is easier to read; however, Python-2.7.2 does not have this feature kwargs = dict(indent=indent) if can_dumps_sort_keys(): kwargs.update(sort_keys=True) try: if large_object: out = GreenletFriendlyStringIO() json.dump(python_object, out, **kwargs) return out.getvalue() else: return json.dumps(python_object, **kwargs) except Exception: logger.exception() raise EncodeError('Cannot encode {!r}', python_object)
def encode(python_object, indent=None, large_object=False): """:returns: a JSON-representation of the object""" # sorted keys is easier to read; however, Python-2.7.2 does not have this feature kwargs = dict(indent=indent) if can_dumps_sort_keys(): kwargs.update(sort_keys=True) try: if large_object: out = GreenletFriendlyStringIO() json.dump(python_object, out, **kwargs) return out.getvalue() else: return json.dumps(python_object, **kwargs) except Exception: logger.exception() raise EncodeError('Cannot encode {!r}', python_object)
[ ":", "returns", ":", "a", "JSON", "-", "representation", "of", "the", "object" ]
Infinidat/infi.gevent_utils
python
https://github.com/Infinidat/infi.gevent_utils/blob/7eb3c1601b8f2c9aaa3a83154ee7dfce8e5e5a5a/src/infi/gevent_utils/json_utils.py#L41-L56
[ "def", "encode", "(", "python_object", ",", "indent", "=", "None", ",", "large_object", "=", "False", ")", ":", "# sorted keys is easier to read; however, Python-2.7.2 does not have this feature", "kwargs", "=", "dict", "(", "indent", "=", "indent", ")", "if", "can_dumps_sort_keys", "(", ")", ":", "kwargs", ".", "update", "(", "sort_keys", "=", "True", ")", "try", ":", "if", "large_object", ":", "out", "=", "GreenletFriendlyStringIO", "(", ")", "json", ".", "dump", "(", "python_object", ",", "out", ",", "*", "*", "kwargs", ")", "return", "out", ".", "getvalue", "(", ")", "else", ":", "return", "json", ".", "dumps", "(", "python_object", ",", "*", "*", "kwargs", ")", "except", "Exception", ":", "logger", ".", "exception", "(", ")", "raise", "EncodeError", "(", "'Cannot encode {!r}'", ",", "python_object", ")" ]
7eb3c1601b8f2c9aaa3a83154ee7dfce8e5e5a5a
valid
SketchRunner.__register_library
Inserts Interpreter Library of imports into sketch in a very non-consensual way
sketches/__init__.py
def __register_library(self, module_name: str, attr: str, fallback: str = None): """Inserts Interpreter Library of imports into sketch in a very non-consensual way""" # Import the module Named in the string try: module = importlib.import_module(module_name) # If module is not found it checks if an alternative is is listed # If it is then it substitutes it, just so that the code can run except ImportError: if fallback is not None: module = importlib.import_module(fallback) self.__logger.warn(module_name + " not available: Replaced with " + fallback) else: self.__logger.warn(module_name + " not available: No Replacement Specified") # Cram the module into the __sketch in the form of module -> "attr" # AKA the same as `import module as attr` if not attr in dir(self.__sketch): setattr(self.__sketch, attr, module) else: self.__logger.warn(attr +" could not be imported as it's label is already used in the sketch")
def __register_library(self, module_name: str, attr: str, fallback: str = None): """Inserts Interpreter Library of imports into sketch in a very non-consensual way""" # Import the module Named in the string try: module = importlib.import_module(module_name) # If module is not found it checks if an alternative is is listed # If it is then it substitutes it, just so that the code can run except ImportError: if fallback is not None: module = importlib.import_module(fallback) self.__logger.warn(module_name + " not available: Replaced with " + fallback) else: self.__logger.warn(module_name + " not available: No Replacement Specified") # Cram the module into the __sketch in the form of module -> "attr" # AKA the same as `import module as attr` if not attr in dir(self.__sketch): setattr(self.__sketch, attr, module) else: self.__logger.warn(attr +" could not be imported as it's label is already used in the sketch")
[ "Inserts", "Interpreter", "Library", "of", "imports", "into", "sketch", "in", "a", "very", "non", "-", "consensual", "way" ]
IGBC/PySketch
python
https://github.com/IGBC/PySketch/blob/3b39410a85693b46704e75739e70301cfea33523/sketches/__init__.py#L44-L65
[ "def", "__register_library", "(", "self", ",", "module_name", ":", "str", ",", "attr", ":", "str", ",", "fallback", ":", "str", "=", "None", ")", ":", "# Import the module Named in the string", "try", ":", "module", "=", "importlib", ".", "import_module", "(", "module_name", ")", "# If module is not found it checks if an alternative is is listed", "# If it is then it substitutes it, just so that the code can run", "except", "ImportError", ":", "if", "fallback", "is", "not", "None", ":", "module", "=", "importlib", ".", "import_module", "(", "fallback", ")", "self", ".", "__logger", ".", "warn", "(", "module_name", "+", "\" not available: Replaced with \"", "+", "fallback", ")", "else", ":", "self", ".", "__logger", ".", "warn", "(", "module_name", "+", "\" not available: No Replacement Specified\"", ")", "# Cram the module into the __sketch in the form of module -> \"attr\"", "# AKA the same as `import module as attr`", "if", "not", "attr", "in", "dir", "(", "self", ".", "__sketch", ")", ":", "setattr", "(", "self", ".", "__sketch", ",", "attr", ",", "module", ")", "else", ":", "self", ".", "__logger", ".", "warn", "(", "attr", "+", "\" could not be imported as it's label is already used in the sketch\"", ")" ]
3b39410a85693b46704e75739e70301cfea33523
valid
EllipseBeam.set_moments
Sets the beam moments directly. Parameters ---------- sx : float Beam moment where :math:`\\text{sx}^2 = \\langle x^2 \\rangle`. sxp : float Beam moment where :math:`\\text{sxp}^2 = \\langle x'^2 \\rangle`. sxxp : float Beam moment where :math:`\\text{sxxp} = \\langle x x' \\rangle`.
scisalt/PWFA/beam.py
def set_moments(self, sx, sxp, sxxp): """ Sets the beam moments directly. Parameters ---------- sx : float Beam moment where :math:`\\text{sx}^2 = \\langle x^2 \\rangle`. sxp : float Beam moment where :math:`\\text{sxp}^2 = \\langle x'^2 \\rangle`. sxxp : float Beam moment where :math:`\\text{sxxp} = \\langle x x' \\rangle`. """ self._sx = sx self._sxp = sxp self._sxxp = sxxp emit = _np.sqrt(sx**2 * sxp**2 - sxxp**2) self._store_emit(emit=emit)
def set_moments(self, sx, sxp, sxxp): """ Sets the beam moments directly. Parameters ---------- sx : float Beam moment where :math:`\\text{sx}^2 = \\langle x^2 \\rangle`. sxp : float Beam moment where :math:`\\text{sxp}^2 = \\langle x'^2 \\rangle`. sxxp : float Beam moment where :math:`\\text{sxxp} = \\langle x x' \\rangle`. """ self._sx = sx self._sxp = sxp self._sxxp = sxxp emit = _np.sqrt(sx**2 * sxp**2 - sxxp**2) self._store_emit(emit=emit)
[ "Sets", "the", "beam", "moments", "directly", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/PWFA/beam.py#L133-L150
[ "def", "set_moments", "(", "self", ",", "sx", ",", "sxp", ",", "sxxp", ")", ":", "self", ".", "_sx", "=", "sx", "self", ".", "_sxp", "=", "sxp", "self", ".", "_sxxp", "=", "sxxp", "emit", "=", "_np", ".", "sqrt", "(", "sx", "**", "2", "*", "sxp", "**", "2", "-", "sxxp", "**", "2", ")", "self", ".", "_store_emit", "(", "emit", "=", "emit", ")" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
EllipseBeam.set_Courant_Snyder
Sets the beam moments indirectly using Courant-Snyder parameters. Parameters ---------- beta : float Courant-Snyder parameter :math:`\\beta`. alpha : float Courant-Snyder parameter :math:`\\alpha`. emit : float Beam emittance :math:`\\epsilon`. emit_n : float Normalized beam emittance :math:`\\gamma \\epsilon`.
scisalt/PWFA/beam.py
def set_Courant_Snyder(self, beta, alpha, emit=None, emit_n=None): """ Sets the beam moments indirectly using Courant-Snyder parameters. Parameters ---------- beta : float Courant-Snyder parameter :math:`\\beta`. alpha : float Courant-Snyder parameter :math:`\\alpha`. emit : float Beam emittance :math:`\\epsilon`. emit_n : float Normalized beam emittance :math:`\\gamma \\epsilon`. """ self._store_emit(emit=emit, emit_n=emit_n) self._sx = _np.sqrt(beta*self.emit) self._sxp = _np.sqrt((1+alpha**2)/beta*self.emit) self._sxxp = -alpha*self.emit
def set_Courant_Snyder(self, beta, alpha, emit=None, emit_n=None): """ Sets the beam moments indirectly using Courant-Snyder parameters. Parameters ---------- beta : float Courant-Snyder parameter :math:`\\beta`. alpha : float Courant-Snyder parameter :math:`\\alpha`. emit : float Beam emittance :math:`\\epsilon`. emit_n : float Normalized beam emittance :math:`\\gamma \\epsilon`. """ self._store_emit(emit=emit, emit_n=emit_n) self._sx = _np.sqrt(beta*self.emit) self._sxp = _np.sqrt((1+alpha**2)/beta*self.emit) self._sxxp = -alpha*self.emit
[ "Sets", "the", "beam", "moments", "indirectly", "using", "Courant", "-", "Snyder", "parameters", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/PWFA/beam.py#L173-L193
[ "def", "set_Courant_Snyder", "(", "self", ",", "beta", ",", "alpha", ",", "emit", "=", "None", ",", "emit_n", "=", "None", ")", ":", "self", ".", "_store_emit", "(", "emit", "=", "emit", ",", "emit_n", "=", "emit_n", ")", "self", ".", "_sx", "=", "_np", ".", "sqrt", "(", "beta", "*", "self", ".", "emit", ")", "self", ".", "_sxp", "=", "_np", ".", "sqrt", "(", "(", "1", "+", "alpha", "**", "2", ")", "/", "beta", "*", "self", ".", "emit", ")", "self", ".", "_sxxp", "=", "-", "alpha", "*", "self", ".", "emit" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
EllipseBeam.beta
Courant-Snyder parameter :math:`\\beta`.
scisalt/PWFA/beam.py
def beta(self): """ Courant-Snyder parameter :math:`\\beta`. """ beta = _np.sqrt(self.sx)/self.emit return beta
def beta(self): """ Courant-Snyder parameter :math:`\\beta`. """ beta = _np.sqrt(self.sx)/self.emit return beta
[ "Courant", "-", "Snyder", "parameter", ":", "math", ":", "\\\\", "beta", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/PWFA/beam.py#L196-L201
[ "def", "beta", "(", "self", ")", ":", "beta", "=", "_np", ".", "sqrt", "(", "self", ".", "sx", ")", "/", "self", ".", "emit", "return", "beta" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
normalize_slice
Given a slice object, return appropriate values for use in the range function :param slice_obj: The slice object or integer provided in the `[]` notation :param length: For negative indexing we need to know the max length of the object.
randomlineaccess/utils.py
def normalize_slice(slice_obj, length): """ Given a slice object, return appropriate values for use in the range function :param slice_obj: The slice object or integer provided in the `[]` notation :param length: For negative indexing we need to know the max length of the object. """ if isinstance(slice_obj, slice): start, stop, step = slice_obj.start, slice_obj.stop, slice_obj.step if start is None: start = 0 if stop is None: stop = length if step is None: step = 1 if start < 0: start += length if stop < 0: stop += length elif isinstance(slice_obj, int): start = slice_obj if start < 0: start += length stop = start + 1 step = 1 else: raise TypeError if (0 <= start <= length) and (0 <= stop <= length): return start, stop, step raise IndexError
def normalize_slice(slice_obj, length): """ Given a slice object, return appropriate values for use in the range function :param slice_obj: The slice object or integer provided in the `[]` notation :param length: For negative indexing we need to know the max length of the object. """ if isinstance(slice_obj, slice): start, stop, step = slice_obj.start, slice_obj.stop, slice_obj.step if start is None: start = 0 if stop is None: stop = length if step is None: step = 1 if start < 0: start += length if stop < 0: stop += length elif isinstance(slice_obj, int): start = slice_obj if start < 0: start += length stop = start + 1 step = 1 else: raise TypeError if (0 <= start <= length) and (0 <= stop <= length): return start, stop, step raise IndexError
[ "Given", "a", "slice", "object", "return", "appropriate", "values", "for", "use", "in", "the", "range", "function" ]
brycedrennan/random-line-access
python
https://github.com/brycedrennan/random-line-access/blob/ad46749252ffbe5885f2f001f5abb5a180939268/randomlineaccess/utils.py#L1-L36
[ "def", "normalize_slice", "(", "slice_obj", ",", "length", ")", ":", "if", "isinstance", "(", "slice_obj", ",", "slice", ")", ":", "start", ",", "stop", ",", "step", "=", "slice_obj", ".", "start", ",", "slice_obj", ".", "stop", ",", "slice_obj", ".", "step", "if", "start", "is", "None", ":", "start", "=", "0", "if", "stop", "is", "None", ":", "stop", "=", "length", "if", "step", "is", "None", ":", "step", "=", "1", "if", "start", "<", "0", ":", "start", "+=", "length", "if", "stop", "<", "0", ":", "stop", "+=", "length", "elif", "isinstance", "(", "slice_obj", ",", "int", ")", ":", "start", "=", "slice_obj", "if", "start", "<", "0", ":", "start", "+=", "length", "stop", "=", "start", "+", "1", "step", "=", "1", "else", ":", "raise", "TypeError", "if", "(", "0", "<=", "start", "<=", "length", ")", "and", "(", "0", "<=", "stop", "<=", "length", ")", ":", "return", "start", ",", "stop", ",", "step", "raise", "IndexError" ]
ad46749252ffbe5885f2f001f5abb5a180939268
valid
BaseValidator.error
Helper to add error to messages field. It fills placeholder with extra call parameters or values from message_value map. :param error_code: Error code to use :rparam error_code: str :param value: Value checked :param kwargs: Map of values to use in placeholders
dirty_validators/basic.py
def error(self, error_code, value, **kwargs): """ Helper to add error to messages field. It fills placeholder with extra call parameters or values from message_value map. :param error_code: Error code to use :rparam error_code: str :param value: Value checked :param kwargs: Map of values to use in placeholders """ code = self.error_code_map.get(error_code, error_code) try: message = Template(self.error_messages[code]) except KeyError: message = Template(self.error_messages[error_code]) placeholders = {"value": self.hidden_value if self.hidden else value} placeholders.update(kwargs) placeholders.update(self.message_values) self.messages[code] = message.safe_substitute(placeholders)
def error(self, error_code, value, **kwargs): """ Helper to add error to messages field. It fills placeholder with extra call parameters or values from message_value map. :param error_code: Error code to use :rparam error_code: str :param value: Value checked :param kwargs: Map of values to use in placeholders """ code = self.error_code_map.get(error_code, error_code) try: message = Template(self.error_messages[code]) except KeyError: message = Template(self.error_messages[error_code]) placeholders = {"value": self.hidden_value if self.hidden else value} placeholders.update(kwargs) placeholders.update(self.message_values) self.messages[code] = message.safe_substitute(placeholders)
[ "Helper", "to", "add", "error", "to", "messages", "field", ".", "It", "fills", "placeholder", "with", "extra", "call", "parameters", "or", "values", "from", "message_value", "map", "." ]
alfred82santa/dirty-validators
python
https://github.com/alfred82santa/dirty-validators/blob/95af84fb8e6452c8a6d88af496cbdb31bca7a608/dirty_validators/basic.py#L73-L94
[ "def", "error", "(", "self", ",", "error_code", ",", "value", ",", "*", "*", "kwargs", ")", ":", "code", "=", "self", ".", "error_code_map", ".", "get", "(", "error_code", ",", "error_code", ")", "try", ":", "message", "=", "Template", "(", "self", ".", "error_messages", "[", "code", "]", ")", "except", "KeyError", ":", "message", "=", "Template", "(", "self", ".", "error_messages", "[", "error_code", "]", ")", "placeholders", "=", "{", "\"value\"", ":", "self", ".", "hidden_value", "if", "self", ".", "hidden", "else", "value", "}", "placeholders", ".", "update", "(", "kwargs", ")", "placeholders", ".", "update", "(", "self", ".", "message_values", ")", "self", ".", "messages", "[", "code", "]", "=", "message", ".", "safe_substitute", "(", "placeholders", ")" ]
95af84fb8e6452c8a6d88af496cbdb31bca7a608
valid
copy
File copy that support compress and decompress of zip files
lrcloud/util.py
def copy(src, dst): """File copy that support compress and decompress of zip files""" (szip, dzip) = (src.endswith(".zip"), dst.endswith(".zip")) logging.info("Copy: %s => %s"%(src, dst)) if szip and dzip:#If both zipped, we can simply use copy shutil.copy2(src, dst) elif szip: with zipfile.ZipFile(src, mode='r') as z: tmpdir = tempfile.mkdtemp() try: z.extractall(tmpdir) if len(z.namelist()) != 1: raise RuntimeError("The zip file '%s' should only have one "\ "compressed file"%src) tmpfile = join(tmpdir,z.namelist()[0]) try: os.remove(dst) except OSError: pass shutil.move(tmpfile, dst) finally: shutil.rmtree(tmpdir, ignore_errors=True) elif dzip: with zipfile.ZipFile(dst, mode='w', compression=ZIP_DEFLATED) as z: z.write(src, arcname=basename(src)) else:#None of them are zipped shutil.copy2(src, dst)
def copy(src, dst): """File copy that support compress and decompress of zip files""" (szip, dzip) = (src.endswith(".zip"), dst.endswith(".zip")) logging.info("Copy: %s => %s"%(src, dst)) if szip and dzip:#If both zipped, we can simply use copy shutil.copy2(src, dst) elif szip: with zipfile.ZipFile(src, mode='r') as z: tmpdir = tempfile.mkdtemp() try: z.extractall(tmpdir) if len(z.namelist()) != 1: raise RuntimeError("The zip file '%s' should only have one "\ "compressed file"%src) tmpfile = join(tmpdir,z.namelist()[0]) try: os.remove(dst) except OSError: pass shutil.move(tmpfile, dst) finally: shutil.rmtree(tmpdir, ignore_errors=True) elif dzip: with zipfile.ZipFile(dst, mode='w', compression=ZIP_DEFLATED) as z: z.write(src, arcname=basename(src)) else:#None of them are zipped shutil.copy2(src, dst)
[ "File", "copy", "that", "support", "compress", "and", "decompress", "of", "zip", "files" ]
madsbk/lrcloud
python
https://github.com/madsbk/lrcloud/blob/8d99be3e1abdf941642e9a1c86b7d775dc373c0b/lrcloud/util.py#L16-L44
[ "def", "copy", "(", "src", ",", "dst", ")", ":", "(", "szip", ",", "dzip", ")", "=", "(", "src", ".", "endswith", "(", "\".zip\"", ")", ",", "dst", ".", "endswith", "(", "\".zip\"", ")", ")", "logging", ".", "info", "(", "\"Copy: %s => %s\"", "%", "(", "src", ",", "dst", ")", ")", "if", "szip", "and", "dzip", ":", "#If both zipped, we can simply use copy", "shutil", ".", "copy2", "(", "src", ",", "dst", ")", "elif", "szip", ":", "with", "zipfile", ".", "ZipFile", "(", "src", ",", "mode", "=", "'r'", ")", "as", "z", ":", "tmpdir", "=", "tempfile", ".", "mkdtemp", "(", ")", "try", ":", "z", ".", "extractall", "(", "tmpdir", ")", "if", "len", "(", "z", ".", "namelist", "(", ")", ")", "!=", "1", ":", "raise", "RuntimeError", "(", "\"The zip file '%s' should only have one \"", "\"compressed file\"", "%", "src", ")", "tmpfile", "=", "join", "(", "tmpdir", ",", "z", ".", "namelist", "(", ")", "[", "0", "]", ")", "try", ":", "os", ".", "remove", "(", "dst", ")", "except", "OSError", ":", "pass", "shutil", ".", "move", "(", "tmpfile", ",", "dst", ")", "finally", ":", "shutil", ".", "rmtree", "(", "tmpdir", ",", "ignore_errors", "=", "True", ")", "elif", "dzip", ":", "with", "zipfile", ".", "ZipFile", "(", "dst", ",", "mode", "=", "'w'", ",", "compression", "=", "ZIP_DEFLATED", ")", "as", "z", ":", "z", ".", "write", "(", "src", ",", "arcname", "=", "basename", "(", "src", ")", ")", "else", ":", "#None of them are zipped", "shutil", ".", "copy2", "(", "src", ",", "dst", ")" ]
8d99be3e1abdf941642e9a1c86b7d775dc373c0b
valid
apply_changesets
Apply to the 'catalog' the changesets in the metafile list 'changesets
lrcloud/util.py
def apply_changesets(args, changesets, catalog): """Apply to the 'catalog' the changesets in the metafile list 'changesets'""" tmpdir = tempfile.mkdtemp() tmp_patch = join(tmpdir, "tmp.patch") tmp_lcat = join(tmpdir, "tmp.lcat") for node in changesets: remove(tmp_patch) copy(node.mfile['changeset']['filename'], tmp_patch) logging.info("mv %s %s"%(catalog, tmp_lcat)) shutil.move(catalog, tmp_lcat) cmd = args.patch_cmd.replace("$in1", tmp_lcat)\ .replace("$patch", tmp_patch)\ .replace("$out", catalog) logging.info("Patch: %s"%cmd) subprocess.check_call(cmd, shell=True) shutil.rmtree(tmpdir, ignore_errors=True)
def apply_changesets(args, changesets, catalog): """Apply to the 'catalog' the changesets in the metafile list 'changesets'""" tmpdir = tempfile.mkdtemp() tmp_patch = join(tmpdir, "tmp.patch") tmp_lcat = join(tmpdir, "tmp.lcat") for node in changesets: remove(tmp_patch) copy(node.mfile['changeset']['filename'], tmp_patch) logging.info("mv %s %s"%(catalog, tmp_lcat)) shutil.move(catalog, tmp_lcat) cmd = args.patch_cmd.replace("$in1", tmp_lcat)\ .replace("$patch", tmp_patch)\ .replace("$out", catalog) logging.info("Patch: %s"%cmd) subprocess.check_call(cmd, shell=True) shutil.rmtree(tmpdir, ignore_errors=True)
[ "Apply", "to", "the", "catalog", "the", "changesets", "in", "the", "metafile", "list", "changesets" ]
madsbk/lrcloud
python
https://github.com/madsbk/lrcloud/blob/8d99be3e1abdf941642e9a1c86b7d775dc373c0b/lrcloud/util.py#L56-L75
[ "def", "apply_changesets", "(", "args", ",", "changesets", ",", "catalog", ")", ":", "tmpdir", "=", "tempfile", ".", "mkdtemp", "(", ")", "tmp_patch", "=", "join", "(", "tmpdir", ",", "\"tmp.patch\"", ")", "tmp_lcat", "=", "join", "(", "tmpdir", ",", "\"tmp.lcat\"", ")", "for", "node", "in", "changesets", ":", "remove", "(", "tmp_patch", ")", "copy", "(", "node", ".", "mfile", "[", "'changeset'", "]", "[", "'filename'", "]", ",", "tmp_patch", ")", "logging", ".", "info", "(", "\"mv %s %s\"", "%", "(", "catalog", ",", "tmp_lcat", ")", ")", "shutil", ".", "move", "(", "catalog", ",", "tmp_lcat", ")", "cmd", "=", "args", ".", "patch_cmd", ".", "replace", "(", "\"$in1\"", ",", "tmp_lcat", ")", ".", "replace", "(", "\"$patch\"", ",", "tmp_patch", ")", ".", "replace", "(", "\"$out\"", ",", "catalog", ")", "logging", ".", "info", "(", "\"Patch: %s\"", "%", "cmd", ")", "subprocess", ".", "check_call", "(", "cmd", ",", "shell", "=", "True", ")", "shutil", ".", "rmtree", "(", "tmpdir", ",", "ignore_errors", "=", "True", ")" ]
8d99be3e1abdf941642e9a1c86b7d775dc373c0b
valid
AddEventForm.clean
Validate that an event with this name on this date does not exist.
build/lib/happenings/forms.py
def clean(self): """ Validate that an event with this name on this date does not exist. """ cleaned = super(EventForm, self).clean() if Event.objects.filter(name=cleaned['name'], start_date=cleaned['start_date']).count(): raise forms.ValidationError(u'This event appears to be in the database already.') return cleaned
def clean(self): """ Validate that an event with this name on this date does not exist. """ cleaned = super(EventForm, self).clean() if Event.objects.filter(name=cleaned['name'], start_date=cleaned['start_date']).count(): raise forms.ValidationError(u'This event appears to be in the database already.') return cleaned
[ "Validate", "that", "an", "event", "with", "this", "name", "on", "this", "date", "does", "not", "exist", "." ]
tBaxter/tango-happenings
python
https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/forms.py#L37-L44
[ "def", "clean", "(", "self", ")", ":", "cleaned", "=", "super", "(", "EventForm", ",", "self", ")", ".", "clean", "(", ")", "if", "Event", ".", "objects", ".", "filter", "(", "name", "=", "cleaned", "[", "'name'", "]", ",", "start_date", "=", "cleaned", "[", "'start_date'", "]", ")", ".", "count", "(", ")", ":", "raise", "forms", ".", "ValidationError", "(", "u'This event appears to be in the database already.'", ")", "return", "cleaned" ]
cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2
valid
loop_in_background
When entering the context, spawns a greenlet that sleeps for `interval` seconds between `callback` executions. When leaving the context stops the greenlet. The yielded object is the `GeventLoop` object so the loop can be stopped from within the context. For example: ``` with loop_in_background(60.0, purge_cache) as purge_cache_job: ... ... if should_stop_cache(): purge_cache_job.stop() ```
src/infi/gevent_utils/gevent_loop.py
def loop_in_background(interval, callback): """ When entering the context, spawns a greenlet that sleeps for `interval` seconds between `callback` executions. When leaving the context stops the greenlet. The yielded object is the `GeventLoop` object so the loop can be stopped from within the context. For example: ``` with loop_in_background(60.0, purge_cache) as purge_cache_job: ... ... if should_stop_cache(): purge_cache_job.stop() ``` """ loop = GeventLoop(interval, callback) loop.start() try: yield loop finally: if loop.has_started(): loop.stop()
def loop_in_background(interval, callback): """ When entering the context, spawns a greenlet that sleeps for `interval` seconds between `callback` executions. When leaving the context stops the greenlet. The yielded object is the `GeventLoop` object so the loop can be stopped from within the context. For example: ``` with loop_in_background(60.0, purge_cache) as purge_cache_job: ... ... if should_stop_cache(): purge_cache_job.stop() ``` """ loop = GeventLoop(interval, callback) loop.start() try: yield loop finally: if loop.has_started(): loop.stop()
[ "When", "entering", "the", "context", "spawns", "a", "greenlet", "that", "sleeps", "for", "interval", "seconds", "between", "callback", "executions", ".", "When", "leaving", "the", "context", "stops", "the", "greenlet", ".", "The", "yielded", "object", "is", "the", "GeventLoop", "object", "so", "the", "loop", "can", "be", "stopped", "from", "within", "the", "context", "." ]
Infinidat/infi.gevent_utils
python
https://github.com/Infinidat/infi.gevent_utils/blob/7eb3c1601b8f2c9aaa3a83154ee7dfce8e5e5a5a/src/infi/gevent_utils/gevent_loop.py#L101-L122
[ "def", "loop_in_background", "(", "interval", ",", "callback", ")", ":", "loop", "=", "GeventLoop", "(", "interval", ",", "callback", ")", "loop", ".", "start", "(", ")", "try", ":", "yield", "loop", "finally", ":", "if", "loop", ".", "has_started", "(", ")", ":", "loop", ".", "stop", "(", ")" ]
7eb3c1601b8f2c9aaa3a83154ee7dfce8e5e5a5a
valid
GeventLoopBase._loop
Main loop - used internally.
src/infi/gevent_utils/gevent_loop.py
def _loop(self): """Main loop - used internally.""" while True: try: with uncaught_greenlet_exception_context(): self._loop_callback() except gevent.GreenletExit: break if self._stop_event.wait(self._interval): break self._clear()
def _loop(self): """Main loop - used internally.""" while True: try: with uncaught_greenlet_exception_context(): self._loop_callback() except gevent.GreenletExit: break if self._stop_event.wait(self._interval): break self._clear()
[ "Main", "loop", "-", "used", "internally", "." ]
Infinidat/infi.gevent_utils
python
https://github.com/Infinidat/infi.gevent_utils/blob/7eb3c1601b8f2c9aaa3a83154ee7dfce8e5e5a5a/src/infi/gevent_utils/gevent_loop.py#L16-L26
[ "def", "_loop", "(", "self", ")", ":", "while", "True", ":", "try", ":", "with", "uncaught_greenlet_exception_context", "(", ")", ":", "self", ".", "_loop_callback", "(", ")", "except", "gevent", ".", "GreenletExit", ":", "break", "if", "self", ".", "_stop_event", ".", "wait", "(", "self", ".", "_interval", ")", ":", "break", "self", ".", "_clear", "(", ")" ]
7eb3c1601b8f2c9aaa3a83154ee7dfce8e5e5a5a
valid
GeventLoopBase.start
Starts the loop. Calling a running loop is an error.
src/infi/gevent_utils/gevent_loop.py
def start(self): """ Starts the loop. Calling a running loop is an error. """ assert not self.has_started(), "called start() on an active GeventLoop" self._stop_event = Event() # note that we don't use safe_greenlets.spawn because we take care of it in _loop by ourselves self._greenlet = gevent.spawn(self._loop)
def start(self): """ Starts the loop. Calling a running loop is an error. """ assert not self.has_started(), "called start() on an active GeventLoop" self._stop_event = Event() # note that we don't use safe_greenlets.spawn because we take care of it in _loop by ourselves self._greenlet = gevent.spawn(self._loop)
[ "Starts", "the", "loop", ".", "Calling", "a", "running", "loop", "is", "an", "error", "." ]
Infinidat/infi.gevent_utils
python
https://github.com/Infinidat/infi.gevent_utils/blob/7eb3c1601b8f2c9aaa3a83154ee7dfce8e5e5a5a/src/infi/gevent_utils/gevent_loop.py#L32-L39
[ "def", "start", "(", "self", ")", ":", "assert", "not", "self", ".", "has_started", "(", ")", ",", "\"called start() on an active GeventLoop\"", "self", ".", "_stop_event", "=", "Event", "(", ")", "# note that we don't use safe_greenlets.spawn because we take care of it in _loop by ourselves", "self", ".", "_greenlet", "=", "gevent", ".", "spawn", "(", "self", ".", "_loop", ")" ]
7eb3c1601b8f2c9aaa3a83154ee7dfce8e5e5a5a
valid
GeventLoopBase.stop
Stops a running loop and waits for it to end if timeout is set. Calling a non-running loop is an error. :param timeout: time (in seconds) to wait for the loop to end after signalling it. ``None`` is to block till it ends. :return: True if the loop stopped, False if still stopping.
src/infi/gevent_utils/gevent_loop.py
def stop(self, timeout=None): """ Stops a running loop and waits for it to end if timeout is set. Calling a non-running loop is an error. :param timeout: time (in seconds) to wait for the loop to end after signalling it. ``None`` is to block till it ends. :return: True if the loop stopped, False if still stopping. """ assert self.has_started(), "called stop() on a non-active GeventLoop" greenlet = self._greenlet if gevent.getcurrent() != self._greenlet else None self._stop_event.set() if greenlet is not None and timeout is not None: greenlet.join(timeout) return greenlet.ready else: return True
def stop(self, timeout=None): """ Stops a running loop and waits for it to end if timeout is set. Calling a non-running loop is an error. :param timeout: time (in seconds) to wait for the loop to end after signalling it. ``None`` is to block till it ends. :return: True if the loop stopped, False if still stopping. """ assert self.has_started(), "called stop() on a non-active GeventLoop" greenlet = self._greenlet if gevent.getcurrent() != self._greenlet else None self._stop_event.set() if greenlet is not None and timeout is not None: greenlet.join(timeout) return greenlet.ready else: return True
[ "Stops", "a", "running", "loop", "and", "waits", "for", "it", "to", "end", "if", "timeout", "is", "set", ".", "Calling", "a", "non", "-", "running", "loop", "is", "an", "error", ".", ":", "param", "timeout", ":", "time", "(", "in", "seconds", ")", "to", "wait", "for", "the", "loop", "to", "end", "after", "signalling", "it", ".", "None", "is", "to", "block", "till", "it", "ends", ".", ":", "return", ":", "True", "if", "the", "loop", "stopped", "False", "if", "still", "stopping", "." ]
Infinidat/infi.gevent_utils
python
https://github.com/Infinidat/infi.gevent_utils/blob/7eb3c1601b8f2c9aaa3a83154ee7dfce8e5e5a5a/src/infi/gevent_utils/gevent_loop.py#L41-L55
[ "def", "stop", "(", "self", ",", "timeout", "=", "None", ")", ":", "assert", "self", ".", "has_started", "(", ")", ",", "\"called stop() on a non-active GeventLoop\"", "greenlet", "=", "self", ".", "_greenlet", "if", "gevent", ".", "getcurrent", "(", ")", "!=", "self", ".", "_greenlet", "else", "None", "self", ".", "_stop_event", ".", "set", "(", ")", "if", "greenlet", "is", "not", "None", "and", "timeout", "is", "not", "None", ":", "greenlet", ".", "join", "(", "timeout", ")", "return", "greenlet", ".", "ready", "else", ":", "return", "True" ]
7eb3c1601b8f2c9aaa3a83154ee7dfce8e5e5a5a
valid
GeventLoopBase.kill
Kills the running loop and waits till it gets killed.
src/infi/gevent_utils/gevent_loop.py
def kill(self): """Kills the running loop and waits till it gets killed.""" assert self.has_started(), "called kill() on a non-active GeventLoop" self._stop_event.set() self._greenlet.kill() self._clear()
def kill(self): """Kills the running loop and waits till it gets killed.""" assert self.has_started(), "called kill() on a non-active GeventLoop" self._stop_event.set() self._greenlet.kill() self._clear()
[ "Kills", "the", "running", "loop", "and", "waits", "till", "it", "gets", "killed", "." ]
Infinidat/infi.gevent_utils
python
https://github.com/Infinidat/infi.gevent_utils/blob/7eb3c1601b8f2c9aaa3a83154ee7dfce8e5e5a5a/src/infi/gevent_utils/gevent_loop.py#L57-L62
[ "def", "kill", "(", "self", ")", ":", "assert", "self", ".", "has_started", "(", ")", ",", "\"called kill() on a non-active GeventLoop\"", "self", ".", "_stop_event", ".", "set", "(", ")", "self", ".", "_greenlet", ".", "kill", "(", ")", "self", ".", "_clear", "(", ")" ]
7eb3c1601b8f2c9aaa3a83154ee7dfce8e5e5a5a
valid
NonUniformImage
Used to plot a set of coordinates. Parameters ---------- x, y : :class:`numpy.ndarray` 1-D ndarrays of lengths N and M, respectively, specifying pixel centers z : :class:`numpy.ndarray` An (M, N) ndarray or masked array of values to be colormapped, or a (M, N, 3) RGB array, or a (M, N, 4) RGBA array. ax : :class:`matplotlib.axes.Axes`, optional The axis to plot to. fig : :class:`matplotlib.figure.Figure`, optional The figure to plot to. cmap : :class:`matplotlib.colors.Colormap`, optional The colormap to use. alpha : float, optional The transparency to use. scalex : bool, optional To set the x limits to available data scaley : bool, optional To set the y limits to available data add_cbar : bool, optional Whether ot add a colorbar or not. Returns ------- img : :class:`matplotlib.image.NonUniformImage` Object representing the :class:`matplotlib.image.NonUniformImage`.
scisalt/matplotlib/NonUniformImage.py
def NonUniformImage(x, y, z, ax=None, fig=None, cmap=None, alpha=None, scalex=True, scaley=True, add_cbar=True, **kwargs): """ Used to plot a set of coordinates. Parameters ---------- x, y : :class:`numpy.ndarray` 1-D ndarrays of lengths N and M, respectively, specifying pixel centers z : :class:`numpy.ndarray` An (M, N) ndarray or masked array of values to be colormapped, or a (M, N, 3) RGB array, or a (M, N, 4) RGBA array. ax : :class:`matplotlib.axes.Axes`, optional The axis to plot to. fig : :class:`matplotlib.figure.Figure`, optional The figure to plot to. cmap : :class:`matplotlib.colors.Colormap`, optional The colormap to use. alpha : float, optional The transparency to use. scalex : bool, optional To set the x limits to available data scaley : bool, optional To set the y limits to available data add_cbar : bool, optional Whether ot add a colorbar or not. Returns ------- img : :class:`matplotlib.image.NonUniformImage` Object representing the :class:`matplotlib.image.NonUniformImage`. """ if ax is None and fig is None: fig, ax = _setup_axes() elif ax is None: ax = fig.gca() elif fig is None: fig = ax.get_figure() norm = kwargs.get('norm', None) im = _mplim.NonUniformImage(ax, **kwargs) vmin = kwargs.pop('vmin', _np.min(z)) vmax = kwargs.pop('vmax', _np.max(z)) # im.set_clim(vmin=vmin, vmax=vmax) if cmap is not None: im.set_cmap(cmap) m = _cm.ScalarMappable(cmap=im.get_cmap(), norm=norm) m.set_array(z) if add_cbar: cax, cb = _cb(ax=ax, im=m, fig=fig) if alpha is not None: im.set_alpha(alpha) im.set_data(x, y, z) ax.images.append(im) if scalex: xmin = min(x) xmax = max(x) ax.set_xlim(xmin, xmax) if scaley: ymin = min(y) ymax = max(y) ax.set_ylim(ymin, ymax) return _SI(im=im, cb=cb, cax=cax)
def NonUniformImage(x, y, z, ax=None, fig=None, cmap=None, alpha=None, scalex=True, scaley=True, add_cbar=True, **kwargs): """ Used to plot a set of coordinates. Parameters ---------- x, y : :class:`numpy.ndarray` 1-D ndarrays of lengths N and M, respectively, specifying pixel centers z : :class:`numpy.ndarray` An (M, N) ndarray or masked array of values to be colormapped, or a (M, N, 3) RGB array, or a (M, N, 4) RGBA array. ax : :class:`matplotlib.axes.Axes`, optional The axis to plot to. fig : :class:`matplotlib.figure.Figure`, optional The figure to plot to. cmap : :class:`matplotlib.colors.Colormap`, optional The colormap to use. alpha : float, optional The transparency to use. scalex : bool, optional To set the x limits to available data scaley : bool, optional To set the y limits to available data add_cbar : bool, optional Whether ot add a colorbar or not. Returns ------- img : :class:`matplotlib.image.NonUniformImage` Object representing the :class:`matplotlib.image.NonUniformImage`. """ if ax is None and fig is None: fig, ax = _setup_axes() elif ax is None: ax = fig.gca() elif fig is None: fig = ax.get_figure() norm = kwargs.get('norm', None) im = _mplim.NonUniformImage(ax, **kwargs) vmin = kwargs.pop('vmin', _np.min(z)) vmax = kwargs.pop('vmax', _np.max(z)) # im.set_clim(vmin=vmin, vmax=vmax) if cmap is not None: im.set_cmap(cmap) m = _cm.ScalarMappable(cmap=im.get_cmap(), norm=norm) m.set_array(z) if add_cbar: cax, cb = _cb(ax=ax, im=m, fig=fig) if alpha is not None: im.set_alpha(alpha) im.set_data(x, y, z) ax.images.append(im) if scalex: xmin = min(x) xmax = max(x) ax.set_xlim(xmin, xmax) if scaley: ymin = min(y) ymax = max(y) ax.set_ylim(ymin, ymax) return _SI(im=im, cb=cb, cax=cax)
[ "Used", "to", "plot", "a", "set", "of", "coordinates", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/matplotlib/NonUniformImage.py#L13-L84
[ "def", "NonUniformImage", "(", "x", ",", "y", ",", "z", ",", "ax", "=", "None", ",", "fig", "=", "None", ",", "cmap", "=", "None", ",", "alpha", "=", "None", ",", "scalex", "=", "True", ",", "scaley", "=", "True", ",", "add_cbar", "=", "True", ",", "*", "*", "kwargs", ")", ":", "if", "ax", "is", "None", "and", "fig", "is", "None", ":", "fig", ",", "ax", "=", "_setup_axes", "(", ")", "elif", "ax", "is", "None", ":", "ax", "=", "fig", ".", "gca", "(", ")", "elif", "fig", "is", "None", ":", "fig", "=", "ax", ".", "get_figure", "(", ")", "norm", "=", "kwargs", ".", "get", "(", "'norm'", ",", "None", ")", "im", "=", "_mplim", ".", "NonUniformImage", "(", "ax", ",", "*", "*", "kwargs", ")", "vmin", "=", "kwargs", ".", "pop", "(", "'vmin'", ",", "_np", ".", "min", "(", "z", ")", ")", "vmax", "=", "kwargs", ".", "pop", "(", "'vmax'", ",", "_np", ".", "max", "(", "z", ")", ")", "# im.set_clim(vmin=vmin, vmax=vmax)", "if", "cmap", "is", "not", "None", ":", "im", ".", "set_cmap", "(", "cmap", ")", "m", "=", "_cm", ".", "ScalarMappable", "(", "cmap", "=", "im", ".", "get_cmap", "(", ")", ",", "norm", "=", "norm", ")", "m", ".", "set_array", "(", "z", ")", "if", "add_cbar", ":", "cax", ",", "cb", "=", "_cb", "(", "ax", "=", "ax", ",", "im", "=", "m", ",", "fig", "=", "fig", ")", "if", "alpha", "is", "not", "None", ":", "im", ".", "set_alpha", "(", "alpha", ")", "im", ".", "set_data", "(", "x", ",", "y", ",", "z", ")", "ax", ".", "images", ".", "append", "(", "im", ")", "if", "scalex", ":", "xmin", "=", "min", "(", "x", ")", "xmax", "=", "max", "(", "x", ")", "ax", ".", "set_xlim", "(", "xmin", ",", "xmax", ")", "if", "scaley", ":", "ymin", "=", "min", "(", "y", ")", "ymax", "=", "max", "(", "y", ")", "ax", ".", "set_ylim", "(", "ymin", ",", "ymax", ")", "return", "_SI", "(", "im", "=", "im", ",", "cb", "=", "cb", ",", "cax", "=", "cax", ")" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
LatexFixer._sentence_to_interstitial_spacing
Fix common spacing errors caused by LaTeX's habit of using an inter-sentence space after any full stop.
latexfixer/fix.py
def _sentence_to_interstitial_spacing(self): """Fix common spacing errors caused by LaTeX's habit of using an inter-sentence space after any full stop.""" not_sentence_end_chars = [' '] abbreviations = ['i.e.', 'e.g.', ' v.', ' w.', ' wh.'] titles = ['Prof.', 'Mr.', 'Mrs.', 'Messrs.', 'Mmes.', 'Msgr.', 'Ms.', 'Fr.', 'Rev.', 'St.', 'Dr.', 'Lieut.', 'Lt.', 'Capt.', 'Cptn.', 'Sgt.', 'Sjt.', 'Gen.', 'Hon.', 'Cpl.', 'L-Cpl.', 'Pvt.', 'Dvr.', 'Gnr.', 'Spr.', 'Col.', 'Lt-Col', 'Lt-Gen.', 'Mx.'] for abbrev in abbreviations: for x in not_sentence_end_chars: self._str_replacement(abbrev + x, abbrev + '\ ') for title in titles: for x in not_sentence_end_chars: self._str_replacement(title + x, title + '~')
def _sentence_to_interstitial_spacing(self): """Fix common spacing errors caused by LaTeX's habit of using an inter-sentence space after any full stop.""" not_sentence_end_chars = [' '] abbreviations = ['i.e.', 'e.g.', ' v.', ' w.', ' wh.'] titles = ['Prof.', 'Mr.', 'Mrs.', 'Messrs.', 'Mmes.', 'Msgr.', 'Ms.', 'Fr.', 'Rev.', 'St.', 'Dr.', 'Lieut.', 'Lt.', 'Capt.', 'Cptn.', 'Sgt.', 'Sjt.', 'Gen.', 'Hon.', 'Cpl.', 'L-Cpl.', 'Pvt.', 'Dvr.', 'Gnr.', 'Spr.', 'Col.', 'Lt-Col', 'Lt-Gen.', 'Mx.'] for abbrev in abbreviations: for x in not_sentence_end_chars: self._str_replacement(abbrev + x, abbrev + '\ ') for title in titles: for x in not_sentence_end_chars: self._str_replacement(title + x, title + '~')
[ "Fix", "common", "spacing", "errors", "caused", "by", "LaTeX", "s", "habit", "of", "using", "an", "inter", "-", "sentence", "space", "after", "any", "full", "stop", "." ]
fizzbucket/latexfixer
python
https://github.com/fizzbucket/latexfixer/blob/1b127e866fbca9764e638fb05fdd43da9dd1a97b/latexfixer/fix.py#L26-L46
[ "def", "_sentence_to_interstitial_spacing", "(", "self", ")", ":", "not_sentence_end_chars", "=", "[", "' '", "]", "abbreviations", "=", "[", "'i.e.'", ",", "'e.g.'", ",", "' v.'", ",", "' w.'", ",", "' wh.'", "]", "titles", "=", "[", "'Prof.'", ",", "'Mr.'", ",", "'Mrs.'", ",", "'Messrs.'", ",", "'Mmes.'", ",", "'Msgr.'", ",", "'Ms.'", ",", "'Fr.'", ",", "'Rev.'", ",", "'St.'", ",", "'Dr.'", ",", "'Lieut.'", ",", "'Lt.'", ",", "'Capt.'", ",", "'Cptn.'", ",", "'Sgt.'", ",", "'Sjt.'", ",", "'Gen.'", ",", "'Hon.'", ",", "'Cpl.'", ",", "'L-Cpl.'", ",", "'Pvt.'", ",", "'Dvr.'", ",", "'Gnr.'", ",", "'Spr.'", ",", "'Col.'", ",", "'Lt-Col'", ",", "'Lt-Gen.'", ",", "'Mx.'", "]", "for", "abbrev", "in", "abbreviations", ":", "for", "x", "in", "not_sentence_end_chars", ":", "self", ".", "_str_replacement", "(", "abbrev", "+", "x", ",", "abbrev", "+", "'\\ '", ")", "for", "title", "in", "titles", ":", "for", "x", "in", "not_sentence_end_chars", ":", "self", ".", "_str_replacement", "(", "title", "+", "x", ",", "title", "+", "'~'", ")" ]
1b127e866fbca9764e638fb05fdd43da9dd1a97b
valid
LatexFixer._hyphens_to_dashes
Transform hyphens to various kinds of dashes
latexfixer/fix.py
def _hyphens_to_dashes(self): """Transform hyphens to various kinds of dashes""" problematic_hyphens = [(r'-([.,!)])', r'---\1'), (r'(?<=\d)-(?=\d)', '--'), (r'(?<=\s)-(?=\s)', '---')] for problem_case in problematic_hyphens: self._regex_replacement(*problem_case)
def _hyphens_to_dashes(self): """Transform hyphens to various kinds of dashes""" problematic_hyphens = [(r'-([.,!)])', r'---\1'), (r'(?<=\d)-(?=\d)', '--'), (r'(?<=\s)-(?=\s)', '---')] for problem_case in problematic_hyphens: self._regex_replacement(*problem_case)
[ "Transform", "hyphens", "to", "various", "kinds", "of", "dashes" ]
fizzbucket/latexfixer
python
https://github.com/fizzbucket/latexfixer/blob/1b127e866fbca9764e638fb05fdd43da9dd1a97b/latexfixer/fix.py#L64-L72
[ "def", "_hyphens_to_dashes", "(", "self", ")", ":", "problematic_hyphens", "=", "[", "(", "r'-([.,!)])'", ",", "r'---\\1'", ")", ",", "(", "r'(?<=\\d)-(?=\\d)'", ",", "'--'", ")", ",", "(", "r'(?<=\\s)-(?=\\s)'", ",", "'---'", ")", "]", "for", "problem_case", "in", "problematic_hyphens", ":", "self", ".", "_regex_replacement", "(", "*", "problem_case", ")" ]
1b127e866fbca9764e638fb05fdd43da9dd1a97b
valid
LatexFixer._str_replacement
Replace target with replacement
latexfixer/fix.py
def _str_replacement(self, target, replacement): """Replace target with replacement""" self.data = self.data.replace(target, replacement)
def _str_replacement(self, target, replacement): """Replace target with replacement""" self.data = self.data.replace(target, replacement)
[ "Replace", "target", "with", "replacement" ]
fizzbucket/latexfixer
python
https://github.com/fizzbucket/latexfixer/blob/1b127e866fbca9764e638fb05fdd43da9dd1a97b/latexfixer/fix.py#L75-L77
[ "def", "_str_replacement", "(", "self", ",", "target", ",", "replacement", ")", ":", "self", ".", "data", "=", "self", ".", "data", ".", "replace", "(", "target", ",", "replacement", ")" ]
1b127e866fbca9764e638fb05fdd43da9dd1a97b
valid
LatexFixer._regex_replacement
Regex substitute target with replacement
latexfixer/fix.py
def _regex_replacement(self, target, replacement): """Regex substitute target with replacement""" match = re.compile(target) self.data = match.sub(replacement, self.data)
def _regex_replacement(self, target, replacement): """Regex substitute target with replacement""" match = re.compile(target) self.data = match.sub(replacement, self.data)
[ "Regex", "substitute", "target", "with", "replacement" ]
fizzbucket/latexfixer
python
https://github.com/fizzbucket/latexfixer/blob/1b127e866fbca9764e638fb05fdd43da9dd1a97b/latexfixer/fix.py#L79-L82
[ "def", "_regex_replacement", "(", "self", ",", "target", ",", "replacement", ")", ":", "match", "=", "re", ".", "compile", "(", "target", ")", "self", ".", "data", "=", "match", ".", "sub", "(", "replacement", ",", "self", ".", "data", ")" ]
1b127e866fbca9764e638fb05fdd43da9dd1a97b
valid
sphinx_make
Call the Sphinx Makefile with the specified targets. `options.paved.docs.path`: the path to the Sphinx folder (where the Makefile resides).
paved/docs.py
def sphinx_make(*targets): """Call the Sphinx Makefile with the specified targets. `options.paved.docs.path`: the path to the Sphinx folder (where the Makefile resides). """ sh('make %s' % ' '.join(targets), cwd=options.paved.docs.path)
def sphinx_make(*targets): """Call the Sphinx Makefile with the specified targets. `options.paved.docs.path`: the path to the Sphinx folder (where the Makefile resides). """ sh('make %s' % ' '.join(targets), cwd=options.paved.docs.path)
[ "Call", "the", "Sphinx", "Makefile", "with", "the", "specified", "targets", "." ]
eykd/paved
python
https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/docs.py#L24-L29
[ "def", "sphinx_make", "(", "*", "targets", ")", ":", "sh", "(", "'make %s'", "%", "' '", ".", "join", "(", "targets", ")", ",", "cwd", "=", "options", ".", "paved", ".", "docs", ".", "path", ")" ]
f04f8a4248c571f3d5ce882b325884a3e5d80203
valid
rsync_docs
Upload the docs to a remote location via rsync. `options.paved.docs.rsync_location`: the target location to rsync files to. `options.paved.docs.path`: the path to the Sphinx folder (where the Makefile resides). `options.paved.docs.build_rel`: the path of the documentation build folder, relative to `options.paved.docs.path`.
paved/docs.py
def rsync_docs(): """Upload the docs to a remote location via rsync. `options.paved.docs.rsync_location`: the target location to rsync files to. `options.paved.docs.path`: the path to the Sphinx folder (where the Makefile resides). `options.paved.docs.build_rel`: the path of the documentation build folder, relative to `options.paved.docs.path`. """ assert options.paved.docs.rsync_location, "Please specify an rsync location in options.paved.docs.rsync_location." sh('rsync -ravz %s/ %s/' % (path(options.paved.docs.path) / options.paved.docs.build_rel, options.paved.docs.rsync_location))
def rsync_docs(): """Upload the docs to a remote location via rsync. `options.paved.docs.rsync_location`: the target location to rsync files to. `options.paved.docs.path`: the path to the Sphinx folder (where the Makefile resides). `options.paved.docs.build_rel`: the path of the documentation build folder, relative to `options.paved.docs.path`. """ assert options.paved.docs.rsync_location, "Please specify an rsync location in options.paved.docs.rsync_location." sh('rsync -ravz %s/ %s/' % (path(options.paved.docs.path) / options.paved.docs.build_rel, options.paved.docs.rsync_location))
[ "Upload", "the", "docs", "to", "a", "remote", "location", "via", "rsync", "." ]
eykd/paved
python
https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/docs.py#L54-L66
[ "def", "rsync_docs", "(", ")", ":", "assert", "options", ".", "paved", ".", "docs", ".", "rsync_location", ",", "\"Please specify an rsync location in options.paved.docs.rsync_location.\"", "sh", "(", "'rsync -ravz %s/ %s/'", "%", "(", "path", "(", "options", ".", "paved", ".", "docs", ".", "path", ")", "/", "options", ".", "paved", ".", "docs", ".", "build_rel", ",", "options", ".", "paved", ".", "docs", ".", "rsync_location", ")", ")" ]
f04f8a4248c571f3d5ce882b325884a3e5d80203
valid
ghpages
Push Sphinx docs to github_ gh-pages branch. 1. Create file .nojekyll 2. Push the branch to origin/gh-pages after committing using ghp-import_ Requirements: - easy_install ghp-import Options: - `options.paved.docs.*` is not used - `options.sphinx.docroot` is used (default=docs) - `options.sphinx.builddir` is used (default=.build) .. warning:: This will DESTROY your gh-pages branch. If you love it, you'll want to take backups before playing with this. This script assumes that gh-pages is 100% derivative. You should never edit files in your gh-pages branch by hand if you're using this script because you will lose your work. .. _github: https://github.com .. _ghp-import: https://github.com/davisp/ghp-import
paved/docs.py
def ghpages(): '''Push Sphinx docs to github_ gh-pages branch. 1. Create file .nojekyll 2. Push the branch to origin/gh-pages after committing using ghp-import_ Requirements: - easy_install ghp-import Options: - `options.paved.docs.*` is not used - `options.sphinx.docroot` is used (default=docs) - `options.sphinx.builddir` is used (default=.build) .. warning:: This will DESTROY your gh-pages branch. If you love it, you'll want to take backups before playing with this. This script assumes that gh-pages is 100% derivative. You should never edit files in your gh-pages branch by hand if you're using this script because you will lose your work. .. _github: https://github.com .. _ghp-import: https://github.com/davisp/ghp-import ''' # copy from paver opts = options docroot = path(opts.get('docroot', 'docs')) if not docroot.exists(): raise BuildFailure("Sphinx documentation root (%s) does not exist." % docroot) builddir = docroot / opts.get("builddir", ".build") # end of copy builddir=builddir / 'html' if not builddir.exists(): raise BuildFailure("Sphinx build directory (%s) does not exist." % builddir) nojekyll = path(builddir) / '.nojekyll' nojekyll.touch() sh('ghp-import -p %s' % (builddir))
def ghpages(): '''Push Sphinx docs to github_ gh-pages branch. 1. Create file .nojekyll 2. Push the branch to origin/gh-pages after committing using ghp-import_ Requirements: - easy_install ghp-import Options: - `options.paved.docs.*` is not used - `options.sphinx.docroot` is used (default=docs) - `options.sphinx.builddir` is used (default=.build) .. warning:: This will DESTROY your gh-pages branch. If you love it, you'll want to take backups before playing with this. This script assumes that gh-pages is 100% derivative. You should never edit files in your gh-pages branch by hand if you're using this script because you will lose your work. .. _github: https://github.com .. _ghp-import: https://github.com/davisp/ghp-import ''' # copy from paver opts = options docroot = path(opts.get('docroot', 'docs')) if not docroot.exists(): raise BuildFailure("Sphinx documentation root (%s) does not exist." % docroot) builddir = docroot / opts.get("builddir", ".build") # end of copy builddir=builddir / 'html' if not builddir.exists(): raise BuildFailure("Sphinx build directory (%s) does not exist." % builddir) nojekyll = path(builddir) / '.nojekyll' nojekyll.touch() sh('ghp-import -p %s' % (builddir))
[ "Push", "Sphinx", "docs", "to", "github_", "gh", "-", "pages", "branch", "." ]
eykd/paved
python
https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/docs.py#L69-L114
[ "def", "ghpages", "(", ")", ":", "# copy from paver", "opts", "=", "options", "docroot", "=", "path", "(", "opts", ".", "get", "(", "'docroot'", ",", "'docs'", ")", ")", "if", "not", "docroot", ".", "exists", "(", ")", ":", "raise", "BuildFailure", "(", "\"Sphinx documentation root (%s) does not exist.\"", "%", "docroot", ")", "builddir", "=", "docroot", "/", "opts", ".", "get", "(", "\"builddir\"", ",", "\".build\"", ")", "# end of copy", "builddir", "=", "builddir", "/", "'html'", "if", "not", "builddir", ".", "exists", "(", ")", ":", "raise", "BuildFailure", "(", "\"Sphinx build directory (%s) does not exist.\"", "%", "builddir", ")", "nojekyll", "=", "path", "(", "builddir", ")", "/", "'.nojekyll'", "nojekyll", ".", "touch", "(", ")", "sh", "(", "'ghp-import -p %s'", "%", "(", "builddir", ")", ")" ]
f04f8a4248c571f3d5ce882b325884a3e5d80203
valid
showhtml
Open your web browser and display the generated html documentation.
paved/docs.py
def showhtml(): """Open your web browser and display the generated html documentation. """ import webbrowser # copy from paver opts = options docroot = path(opts.get('docroot', 'docs')) if not docroot.exists(): raise BuildFailure("Sphinx documentation root (%s) does not exist." % docroot) builddir = docroot / opts.get("builddir", ".build") # end of copy builddir=builddir / 'html' if not builddir.exists(): raise BuildFailure("Sphinx build directory (%s) does not exist." % builddir) webbrowser.open(builddir / 'index.html')
def showhtml(): """Open your web browser and display the generated html documentation. """ import webbrowser # copy from paver opts = options docroot = path(opts.get('docroot', 'docs')) if not docroot.exists(): raise BuildFailure("Sphinx documentation root (%s) does not exist." % docroot) builddir = docroot / opts.get("builddir", ".build") # end of copy builddir=builddir / 'html' if not builddir.exists(): raise BuildFailure("Sphinx build directory (%s) does not exist." % builddir) webbrowser.open(builddir / 'index.html')
[ "Open", "your", "web", "browser", "and", "display", "the", "generated", "html", "documentation", "." ]
eykd/paved
python
https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/docs.py#L119-L138
[ "def", "showhtml", "(", ")", ":", "import", "webbrowser", "# copy from paver", "opts", "=", "options", "docroot", "=", "path", "(", "opts", ".", "get", "(", "'docroot'", ",", "'docs'", ")", ")", "if", "not", "docroot", ".", "exists", "(", ")", ":", "raise", "BuildFailure", "(", "\"Sphinx documentation root (%s) does not exist.\"", "%", "docroot", ")", "builddir", "=", "docroot", "/", "opts", ".", "get", "(", "\"builddir\"", ",", "\".build\"", ")", "# end of copy", "builddir", "=", "builddir", "/", "'html'", "if", "not", "builddir", ".", "exists", "(", ")", ":", "raise", "BuildFailure", "(", "\"Sphinx build directory (%s) does not exist.\"", "%", "builddir", ")", "webbrowser", ".", "open", "(", "builddir", "/", "'index.html'", ")" ]
f04f8a4248c571f3d5ce882b325884a3e5d80203
valid
setup_figure
Sets up a figure with a number of rows (*rows*) and columns (*cols*), *\*\*kwargs* passes through to :class:`matplotlib.figure.Figure`. .. versionchanged:: 1.3 Supports *\*\*kwargs* pass-through to :class:`matplotlib.figure.Figure`. .. versionchanged:: 1.2 Changed *gridspec_x* to *rows*, *gridspec_y* to *cols*, added *figsize* control. Parameters ---------- rows : int Number of rows to create. cols : int Number of columns to create. Returns ------- fig : :class:`matplotlib.figure.Figure` The figure. gs : :class:`matplotlib.gridspec.GridSpec` Instance with *gridspec_x* rows and *gridspec_y* columns
scisalt/matplotlib/setup_figure.py
def setup_figure(rows=1, cols=1, **kwargs): """ Sets up a figure with a number of rows (*rows*) and columns (*cols*), *\*\*kwargs* passes through to :class:`matplotlib.figure.Figure`. .. versionchanged:: 1.3 Supports *\*\*kwargs* pass-through to :class:`matplotlib.figure.Figure`. .. versionchanged:: 1.2 Changed *gridspec_x* to *rows*, *gridspec_y* to *cols*, added *figsize* control. Parameters ---------- rows : int Number of rows to create. cols : int Number of columns to create. Returns ------- fig : :class:`matplotlib.figure.Figure` The figure. gs : :class:`matplotlib.gridspec.GridSpec` Instance with *gridspec_x* rows and *gridspec_y* columns """ fig = _plt.figure(**kwargs) gs = _gridspec.GridSpec(rows, cols) return fig, gs
def setup_figure(rows=1, cols=1, **kwargs): """ Sets up a figure with a number of rows (*rows*) and columns (*cols*), *\*\*kwargs* passes through to :class:`matplotlib.figure.Figure`. .. versionchanged:: 1.3 Supports *\*\*kwargs* pass-through to :class:`matplotlib.figure.Figure`. .. versionchanged:: 1.2 Changed *gridspec_x* to *rows*, *gridspec_y* to *cols*, added *figsize* control. Parameters ---------- rows : int Number of rows to create. cols : int Number of columns to create. Returns ------- fig : :class:`matplotlib.figure.Figure` The figure. gs : :class:`matplotlib.gridspec.GridSpec` Instance with *gridspec_x* rows and *gridspec_y* columns """ fig = _plt.figure(**kwargs) gs = _gridspec.GridSpec(rows, cols) return fig, gs
[ "Sets", "up", "a", "figure", "with", "a", "number", "of", "rows", "(", "*", "rows", "*", ")", "and", "columns", "(", "*", "cols", "*", ")", "*", "\\", "*", "\\", "*", "kwargs", "*", "passes", "through", "to", ":", "class", ":", "matplotlib", ".", "figure", ".", "Figure", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/matplotlib/setup_figure.py#L8-L37
[ "def", "setup_figure", "(", "rows", "=", "1", ",", "cols", "=", "1", ",", "*", "*", "kwargs", ")", ":", "fig", "=", "_plt", ".", "figure", "(", "*", "*", "kwargs", ")", "gs", "=", "_gridspec", ".", "GridSpec", "(", "rows", ",", "cols", ")", "return", "fig", ",", "gs" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
GameController.guess
guess() allows a guess to be made. Before the guess is made, the method checks to see if the game has been won, lost, or there are no tries remaining. It then creates a return object stating the number of bulls (direct matches), cows (indirect matches), an analysis of the guess (a list of analysis objects), and a status. :param args: any number of integers (or string representations of integers) to the number of Digits in the answer; i.e. in normal mode, there would be a DigitWord to guess of 4 digits, so guess would expect guess(1, 2, 3, 4) and a shorter (guess(1, 2)) or longer (guess(1, 2, 3, 4, 5)) sequence will raise an exception. :return: a JSON object containing the analysis of the guess: { "cows": {"type": "integer"}, "bulls": {"type": "integer"}, "analysis": {"type": "array of DigitWordAnalysis"}, "status": {"type": "string"} }
python_cowbull_game/v2_deprecated/GameController.py
def guess(self, *args): self._validate() """ guess() allows a guess to be made. Before the guess is made, the method checks to see if the game has been won, lost, or there are no tries remaining. It then creates a return object stating the number of bulls (direct matches), cows (indirect matches), an analysis of the guess (a list of analysis objects), and a status. :param args: any number of integers (or string representations of integers) to the number of Digits in the answer; i.e. in normal mode, there would be a DigitWord to guess of 4 digits, so guess would expect guess(1, 2, 3, 4) and a shorter (guess(1, 2)) or longer (guess(1, 2, 3, 4, 5)) sequence will raise an exception. :return: a JSON object containing the analysis of the guess: { "cows": {"type": "integer"}, "bulls": {"type": "integer"}, "analysis": {"type": "array of DigitWordAnalysis"}, "status": {"type": "string"} } """ logging.debug("guess called.") logging.debug("Validating game object") self._validate(op="guess") logging.debug("Building return object") _return_results = { "cows": None, "bulls": None, "analysis": [], "status": "" } logging.debug("Check if game already won, lost, or too many tries.") if self._game.status == GameObject.GAME_WON: _return_results["message"] = self._start_again("You already won!") elif self._game.status == GameObject.GAME_LOST: _return_results["message"] = self._start_again("You have made too many guesses, you lost!") elif self._game.guesses_remaining < 1: _return_results["message"] = self._start_again("You have run out of tries, sorry!") else: logging.debug("Creating a DigitWord for the guess.") _mode = self._load_mode(self._game.mode) guess = DigitWord(*args, wordtype=_mode.digit_type) logging.debug("Validating guess.") self._game.guesses_remaining -= 1 self._game.guesses_made += 1 logging.debug("Initializing return object.") _return_results["analysis"] = [] _return_results["cows"] = 0 _return_results["bulls"] = 0 logging.debug("Asking the underlying GameObject to compare itself to the guess.") for i in self._game.answer.compare(guess): logging.debug("Iteration of guesses. Processing guess {}".format(i.index)) if i.match is True: logging.debug("Bull found. +1") _return_results["bulls"] += 1 elif i.in_word is True: logging.debug("Cow found. +1") _return_results["cows"] += 1 logging.debug("Add analysis to return object") _return_results["analysis"].append(i.get_object()) logging.debug("Checking if game won or lost.") if _return_results["bulls"] == len(self._game.answer.word): logging.debug("Game was won.") self._game.status = GameObject.GAME_WON self._game.guesses_remaining = 0 _return_results["message"] = "Well done! You won the game with your " \ "answers {}".format(self._game.answer_str) elif self._game.guesses_remaining < 1: logging.debug("Game was lost.") self._game.status = GameObject.GAME_LOST _return_results["message"] = "Sorry, you lost! The correct answer was " \ "{}".format(self._game.answer_str) _return_results["status"] = self._game.status logging.debug("Returning results.") return _return_results
def guess(self, *args): self._validate() """ guess() allows a guess to be made. Before the guess is made, the method checks to see if the game has been won, lost, or there are no tries remaining. It then creates a return object stating the number of bulls (direct matches), cows (indirect matches), an analysis of the guess (a list of analysis objects), and a status. :param args: any number of integers (or string representations of integers) to the number of Digits in the answer; i.e. in normal mode, there would be a DigitWord to guess of 4 digits, so guess would expect guess(1, 2, 3, 4) and a shorter (guess(1, 2)) or longer (guess(1, 2, 3, 4, 5)) sequence will raise an exception. :return: a JSON object containing the analysis of the guess: { "cows": {"type": "integer"}, "bulls": {"type": "integer"}, "analysis": {"type": "array of DigitWordAnalysis"}, "status": {"type": "string"} } """ logging.debug("guess called.") logging.debug("Validating game object") self._validate(op="guess") logging.debug("Building return object") _return_results = { "cows": None, "bulls": None, "analysis": [], "status": "" } logging.debug("Check if game already won, lost, or too many tries.") if self._game.status == GameObject.GAME_WON: _return_results["message"] = self._start_again("You already won!") elif self._game.status == GameObject.GAME_LOST: _return_results["message"] = self._start_again("You have made too many guesses, you lost!") elif self._game.guesses_remaining < 1: _return_results["message"] = self._start_again("You have run out of tries, sorry!") else: logging.debug("Creating a DigitWord for the guess.") _mode = self._load_mode(self._game.mode) guess = DigitWord(*args, wordtype=_mode.digit_type) logging.debug("Validating guess.") self._game.guesses_remaining -= 1 self._game.guesses_made += 1 logging.debug("Initializing return object.") _return_results["analysis"] = [] _return_results["cows"] = 0 _return_results["bulls"] = 0 logging.debug("Asking the underlying GameObject to compare itself to the guess.") for i in self._game.answer.compare(guess): logging.debug("Iteration of guesses. Processing guess {}".format(i.index)) if i.match is True: logging.debug("Bull found. +1") _return_results["bulls"] += 1 elif i.in_word is True: logging.debug("Cow found. +1") _return_results["cows"] += 1 logging.debug("Add analysis to return object") _return_results["analysis"].append(i.get_object()) logging.debug("Checking if game won or lost.") if _return_results["bulls"] == len(self._game.answer.word): logging.debug("Game was won.") self._game.status = GameObject.GAME_WON self._game.guesses_remaining = 0 _return_results["message"] = "Well done! You won the game with your " \ "answers {}".format(self._game.answer_str) elif self._game.guesses_remaining < 1: logging.debug("Game was lost.") self._game.status = GameObject.GAME_LOST _return_results["message"] = "Sorry, you lost! The correct answer was " \ "{}".format(self._game.answer_str) _return_results["status"] = self._game.status logging.debug("Returning results.") return _return_results
[ "guess", "()", "allows", "a", "guess", "to", "be", "made", ".", "Before", "the", "guess", "is", "made", "the", "method", "checks", "to", "see", "if", "the", "game", "has", "been", "won", "lost", "or", "there", "are", "no", "tries", "remaining", ".", "It", "then", "creates", "a", "return", "object", "stating", "the", "number", "of", "bulls", "(", "direct", "matches", ")", "cows", "(", "indirect", "matches", ")", "an", "analysis", "of", "the", "guess", "(", "a", "list", "of", "analysis", "objects", ")", "and", "a", "status", "." ]
dsandersAzure/python_cowbull_game
python
https://github.com/dsandersAzure/python_cowbull_game/blob/82a0d8ee127869123d4fad51a8cd1707879e368f/python_cowbull_game/v2_deprecated/GameController.py#L173-L261
[ "def", "guess", "(", "self", ",", "*", "args", ")", ":", "self", ".", "_validate", "(", ")", "logging", ".", "debug", "(", "\"guess called.\"", ")", "logging", ".", "debug", "(", "\"Validating game object\"", ")", "self", ".", "_validate", "(", "op", "=", "\"guess\"", ")", "logging", ".", "debug", "(", "\"Building return object\"", ")", "_return_results", "=", "{", "\"cows\"", ":", "None", ",", "\"bulls\"", ":", "None", ",", "\"analysis\"", ":", "[", "]", ",", "\"status\"", ":", "\"\"", "}", "logging", ".", "debug", "(", "\"Check if game already won, lost, or too many tries.\"", ")", "if", "self", ".", "_game", ".", "status", "==", "GameObject", ".", "GAME_WON", ":", "_return_results", "[", "\"message\"", "]", "=", "self", ".", "_start_again", "(", "\"You already won!\"", ")", "elif", "self", ".", "_game", ".", "status", "==", "GameObject", ".", "GAME_LOST", ":", "_return_results", "[", "\"message\"", "]", "=", "self", ".", "_start_again", "(", "\"You have made too many guesses, you lost!\"", ")", "elif", "self", ".", "_game", ".", "guesses_remaining", "<", "1", ":", "_return_results", "[", "\"message\"", "]", "=", "self", ".", "_start_again", "(", "\"You have run out of tries, sorry!\"", ")", "else", ":", "logging", ".", "debug", "(", "\"Creating a DigitWord for the guess.\"", ")", "_mode", "=", "self", ".", "_load_mode", "(", "self", ".", "_game", ".", "mode", ")", "guess", "=", "DigitWord", "(", "*", "args", ",", "wordtype", "=", "_mode", ".", "digit_type", ")", "logging", ".", "debug", "(", "\"Validating guess.\"", ")", "self", ".", "_game", ".", "guesses_remaining", "-=", "1", "self", ".", "_game", ".", "guesses_made", "+=", "1", "logging", ".", "debug", "(", "\"Initializing return object.\"", ")", "_return_results", "[", "\"analysis\"", "]", "=", "[", "]", "_return_results", "[", "\"cows\"", "]", "=", "0", "_return_results", "[", "\"bulls\"", "]", "=", "0", "logging", ".", "debug", "(", "\"Asking the underlying GameObject to compare itself to the guess.\"", ")", "for", "i", "in", "self", ".", "_game", ".", "answer", ".", "compare", "(", "guess", ")", ":", "logging", ".", "debug", "(", "\"Iteration of guesses. Processing guess {}\"", ".", "format", "(", "i", ".", "index", ")", ")", "if", "i", ".", "match", "is", "True", ":", "logging", ".", "debug", "(", "\"Bull found. +1\"", ")", "_return_results", "[", "\"bulls\"", "]", "+=", "1", "elif", "i", ".", "in_word", "is", "True", ":", "logging", ".", "debug", "(", "\"Cow found. +1\"", ")", "_return_results", "[", "\"cows\"", "]", "+=", "1", "logging", ".", "debug", "(", "\"Add analysis to return object\"", ")", "_return_results", "[", "\"analysis\"", "]", ".", "append", "(", "i", ".", "get_object", "(", ")", ")", "logging", ".", "debug", "(", "\"Checking if game won or lost.\"", ")", "if", "_return_results", "[", "\"bulls\"", "]", "==", "len", "(", "self", ".", "_game", ".", "answer", ".", "word", ")", ":", "logging", ".", "debug", "(", "\"Game was won.\"", ")", "self", ".", "_game", ".", "status", "=", "GameObject", ".", "GAME_WON", "self", ".", "_game", ".", "guesses_remaining", "=", "0", "_return_results", "[", "\"message\"", "]", "=", "\"Well done! You won the game with your \"", "\"answers {}\"", ".", "format", "(", "self", ".", "_game", ".", "answer_str", ")", "elif", "self", ".", "_game", ".", "guesses_remaining", "<", "1", ":", "logging", ".", "debug", "(", "\"Game was lost.\"", ")", "self", ".", "_game", ".", "status", "=", "GameObject", ".", "GAME_LOST", "_return_results", "[", "\"message\"", "]", "=", "\"Sorry, you lost! The correct answer was \"", "\"{}\"", ".", "format", "(", "self", ".", "_game", ".", "answer_str", ")", "_return_results", "[", "\"status\"", "]", "=", "self", ".", "_game", ".", "status", "logging", ".", "debug", "(", "\"Returning results.\"", ")", "return", "_return_results" ]
82a0d8ee127869123d4fad51a8cd1707879e368f
valid
GameController._start_again
Simple method to form a start again message and give the answer in readable form.
python_cowbull_game/v2_deprecated/GameController.py
def _start_again(self, message=None): """Simple method to form a start again message and give the answer in readable form.""" logging.debug("Start again message delivered: {}".format(message)) the_answer = self._game.answer_str return "{0} The correct answer was {1}. Please start a new game.".format( message, the_answer )
def _start_again(self, message=None): """Simple method to form a start again message and give the answer in readable form.""" logging.debug("Start again message delivered: {}".format(message)) the_answer = self._game.answer_str return "{0} The correct answer was {1}. Please start a new game.".format( message, the_answer )
[ "Simple", "method", "to", "form", "a", "start", "again", "message", "and", "give", "the", "answer", "in", "readable", "form", "." ]
dsandersAzure/python_cowbull_game
python
https://github.com/dsandersAzure/python_cowbull_game/blob/82a0d8ee127869123d4fad51a8cd1707879e368f/python_cowbull_game/v2_deprecated/GameController.py#L266-L274
[ "def", "_start_again", "(", "self", ",", "message", "=", "None", ")", ":", "logging", ".", "debug", "(", "\"Start again message delivered: {}\"", ".", "format", "(", "message", ")", ")", "the_answer", "=", "self", ".", "_game", ".", "answer_str", "return", "\"{0} The correct answer was {1}. Please start a new game.\"", ".", "format", "(", "message", ",", "the_answer", ")" ]
82a0d8ee127869123d4fad51a8cd1707879e368f
valid
attachments
Parse the copy inside ``value`` and look for shortcodes in this format:: <p>Here's an attachment</p> <p>[attachment 1]</p> Replace the shortcode with a full image, video or audio element, or download link :param obj: The object against which attachments are saved :param width: The width of images or audio/video tags (defaults to the ``ATTACHMENT_WIDTH`` SETTING)
bambu_attachments/templatetags/attachments.py
def attachments(value, obj, width = WIDTH): """ Parse the copy inside ``value`` and look for shortcodes in this format:: <p>Here's an attachment</p> <p>[attachment 1]</p> Replace the shortcode with a full image, video or audio element, or download link :param obj: The object against which attachments are saved :param width: The width of images or audio/video tags (defaults to the ``ATTACHMENT_WIDTH`` SETTING) """ match = ATTACHMENT_REGEX.search(value) safe = isinstance(value, (SafeString, SafeUnicode)) while not match is None and match.end() <= len(value): start = match.start() end = match.end() groups = match.groups() if len(groups) > 0: index = groups[0] options = None if len(groups) > 1: options = groups[1] if options: options = options.strip() if options: try: options = split(smart_str(options)) except: options = None args = [] kwargs = { 'width': width } if options: for option in options: key, equals, val = option.partition('=') if equals != '=': if key and not val: args.append(key) continue kwargs[key] = val try: if isinstance(obj, dict): inner = Attachment( **obj['attachments__attachment'][int(index) - 1] ).render(*args, **kwargs) else: inner = obj.attachments.all()[int(index) - 1].render(*args, **kwargs) except: inner = '' else: inner = '' value = value[:start] + inner + value[end:] match = ATTACHMENT_REGEX.search(value, start + len(inner)) if safe: return mark_safe(value) else: return value
def attachments(value, obj, width = WIDTH): """ Parse the copy inside ``value`` and look for shortcodes in this format:: <p>Here's an attachment</p> <p>[attachment 1]</p> Replace the shortcode with a full image, video or audio element, or download link :param obj: The object against which attachments are saved :param width: The width of images or audio/video tags (defaults to the ``ATTACHMENT_WIDTH`` SETTING) """ match = ATTACHMENT_REGEX.search(value) safe = isinstance(value, (SafeString, SafeUnicode)) while not match is None and match.end() <= len(value): start = match.start() end = match.end() groups = match.groups() if len(groups) > 0: index = groups[0] options = None if len(groups) > 1: options = groups[1] if options: options = options.strip() if options: try: options = split(smart_str(options)) except: options = None args = [] kwargs = { 'width': width } if options: for option in options: key, equals, val = option.partition('=') if equals != '=': if key and not val: args.append(key) continue kwargs[key] = val try: if isinstance(obj, dict): inner = Attachment( **obj['attachments__attachment'][int(index) - 1] ).render(*args, **kwargs) else: inner = obj.attachments.all()[int(index) - 1].render(*args, **kwargs) except: inner = '' else: inner = '' value = value[:start] + inner + value[end:] match = ATTACHMENT_REGEX.search(value, start + len(inner)) if safe: return mark_safe(value) else: return value
[ "Parse", "the", "copy", "inside", "value", "and", "look", "for", "shortcodes", "in", "this", "format", "::", "<p", ">", "Here", "s", "an", "attachment<", "/", "p", ">", "<p", ">", "[", "attachment", "1", "]", "<", "/", "p", ">", "Replace", "the", "shortcode", "with", "a", "full", "image", "video", "or", "audio", "element", "or", "download", "link", ":", "param", "obj", ":", "The", "object", "against", "which", "attachments", "are", "saved", ":", "param", "width", ":", "The", "width", "of", "images", "or", "audio", "/", "video", "tags", "(", "defaults", "to", "the", "ATTACHMENT_WIDTH", "SETTING", ")" ]
iamsteadman/bambu-attachments
python
https://github.com/iamsteadman/bambu-attachments/blob/cc846dc8545c0b1795afff5d41f2f3def56b6603/bambu_attachments/templatetags/attachments.py#L14-L82
[ "def", "attachments", "(", "value", ",", "obj", ",", "width", "=", "WIDTH", ")", ":", "match", "=", "ATTACHMENT_REGEX", ".", "search", "(", "value", ")", "safe", "=", "isinstance", "(", "value", ",", "(", "SafeString", ",", "SafeUnicode", ")", ")", "while", "not", "match", "is", "None", "and", "match", ".", "end", "(", ")", "<=", "len", "(", "value", ")", ":", "start", "=", "match", ".", "start", "(", ")", "end", "=", "match", ".", "end", "(", ")", "groups", "=", "match", ".", "groups", "(", ")", "if", "len", "(", "groups", ")", ">", "0", ":", "index", "=", "groups", "[", "0", "]", "options", "=", "None", "if", "len", "(", "groups", ")", ">", "1", ":", "options", "=", "groups", "[", "1", "]", "if", "options", ":", "options", "=", "options", ".", "strip", "(", ")", "if", "options", ":", "try", ":", "options", "=", "split", "(", "smart_str", "(", "options", ")", ")", "except", ":", "options", "=", "None", "args", "=", "[", "]", "kwargs", "=", "{", "'width'", ":", "width", "}", "if", "options", ":", "for", "option", "in", "options", ":", "key", ",", "equals", ",", "val", "=", "option", ".", "partition", "(", "'='", ")", "if", "equals", "!=", "'='", ":", "if", "key", "and", "not", "val", ":", "args", ".", "append", "(", "key", ")", "continue", "kwargs", "[", "key", "]", "=", "val", "try", ":", "if", "isinstance", "(", "obj", ",", "dict", ")", ":", "inner", "=", "Attachment", "(", "*", "*", "obj", "[", "'attachments__attachment'", "]", "[", "int", "(", "index", ")", "-", "1", "]", ")", ".", "render", "(", "*", "args", ",", "*", "*", "kwargs", ")", "else", ":", "inner", "=", "obj", ".", "attachments", ".", "all", "(", ")", "[", "int", "(", "index", ")", "-", "1", "]", ".", "render", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", ":", "inner", "=", "''", "else", ":", "inner", "=", "''", "value", "=", "value", "[", ":", "start", "]", "+", "inner", "+", "value", "[", "end", ":", "]", "match", "=", "ATTACHMENT_REGEX", ".", "search", "(", "value", ",", "start", "+", "len", "(", "inner", ")", ")", "if", "safe", ":", "return", "mark_safe", "(", "value", ")", "else", ":", "return", "value" ]
cc846dc8545c0b1795afff5d41f2f3def56b6603
valid
CssMinifier.minify
Tries to minimize the length of CSS code passed as parameter. Returns string.
compressor/minifier/css.py
def minify(self, css): """Tries to minimize the length of CSS code passed as parameter. Returns string.""" css = css.replace("\r\n", "\n") # get rid of Windows line endings, if they exist for rule in _REPLACERS[self.level]: css = re.compile(rule[0], re.MULTILINE|re.UNICODE|re.DOTALL).sub(rule[1], css) return css
def minify(self, css): """Tries to minimize the length of CSS code passed as parameter. Returns string.""" css = css.replace("\r\n", "\n") # get rid of Windows line endings, if they exist for rule in _REPLACERS[self.level]: css = re.compile(rule[0], re.MULTILINE|re.UNICODE|re.DOTALL).sub(rule[1], css) return css
[ "Tries", "to", "minimize", "the", "length", "of", "CSS", "code", "passed", "as", "parameter", ".", "Returns", "string", "." ]
marcelnicolay/pycompressor
python
https://github.com/marcelnicolay/pycompressor/blob/ded6b16c58c9f2a7446014b171fd409a22b561e4/compressor/minifier/css.py#L40-L45
[ "def", "minify", "(", "self", ",", "css", ")", ":", "css", "=", "css", ".", "replace", "(", "\"\\r\\n\"", ",", "\"\\n\"", ")", "# get rid of Windows line endings, if they exist", "for", "rule", "in", "_REPLACERS", "[", "self", ".", "level", "]", ":", "css", "=", "re", ".", "compile", "(", "rule", "[", "0", "]", ",", "re", ".", "MULTILINE", "|", "re", ".", "UNICODE", "|", "re", ".", "DOTALL", ")", ".", "sub", "(", "rule", "[", "1", "]", ",", "css", ")", "return", "css" ]
ded6b16c58c9f2a7446014b171fd409a22b561e4
valid
colorbar
Adds a polite colorbar that steals space so :func:`matplotlib.pyplot.tight_layout` works nicely. .. versionadded:: 1.3 Parameters ---------- ax : :class:`matplotlib.axis.Axis` The axis to plot to. im : :class:`matplotlib.image.AxesImage` The plotted image to use for the colorbar. fig : :class:`matplotlib.figure.Figure`, optional The figure to plot to. loc : str, optional The location to place the axes. size : str, optional The size to allocate for the colorbar. pad : str, optional The amount to pad the colorbar.
scisalt/matplotlib/colorbar.py
def colorbar(ax, im, fig=None, loc="right", size="5%", pad="3%"): """ Adds a polite colorbar that steals space so :func:`matplotlib.pyplot.tight_layout` works nicely. .. versionadded:: 1.3 Parameters ---------- ax : :class:`matplotlib.axis.Axis` The axis to plot to. im : :class:`matplotlib.image.AxesImage` The plotted image to use for the colorbar. fig : :class:`matplotlib.figure.Figure`, optional The figure to plot to. loc : str, optional The location to place the axes. size : str, optional The size to allocate for the colorbar. pad : str, optional The amount to pad the colorbar. """ if fig is None: fig = ax.get_figure() # _pdb.set_trace() if loc == "left" or loc == "right": width = fig.get_figwidth() new = width * (1 + _pc2f(size) + _pc2f(pad)) _logger.debug('Setting new figure width: {}'.format(new)) # fig.set_size_inches(new, fig.get_figheight(), forward=True) elif loc == "top" or loc == "bottom": height = fig.get_figheight() new = height * (1 + _pc2f(size) + _pc2f(pad)) _logger.debug('Setting new figure height: {}'.format(new)) # fig.set_figheight(fig.get_figwidth(), new, forward=True) divider = _ag1.make_axes_locatable(ax) cax = divider.append_axes(loc, size=size, pad=pad) return cax, _plt.colorbar(im, cax=cax)
def colorbar(ax, im, fig=None, loc="right", size="5%", pad="3%"): """ Adds a polite colorbar that steals space so :func:`matplotlib.pyplot.tight_layout` works nicely. .. versionadded:: 1.3 Parameters ---------- ax : :class:`matplotlib.axis.Axis` The axis to plot to. im : :class:`matplotlib.image.AxesImage` The plotted image to use for the colorbar. fig : :class:`matplotlib.figure.Figure`, optional The figure to plot to. loc : str, optional The location to place the axes. size : str, optional The size to allocate for the colorbar. pad : str, optional The amount to pad the colorbar. """ if fig is None: fig = ax.get_figure() # _pdb.set_trace() if loc == "left" or loc == "right": width = fig.get_figwidth() new = width * (1 + _pc2f(size) + _pc2f(pad)) _logger.debug('Setting new figure width: {}'.format(new)) # fig.set_size_inches(new, fig.get_figheight(), forward=True) elif loc == "top" or loc == "bottom": height = fig.get_figheight() new = height * (1 + _pc2f(size) + _pc2f(pad)) _logger.debug('Setting new figure height: {}'.format(new)) # fig.set_figheight(fig.get_figwidth(), new, forward=True) divider = _ag1.make_axes_locatable(ax) cax = divider.append_axes(loc, size=size, pad=pad) return cax, _plt.colorbar(im, cax=cax)
[ "Adds", "a", "polite", "colorbar", "that", "steals", "space", "so", ":", "func", ":", "matplotlib", ".", "pyplot", ".", "tight_layout", "works", "nicely", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/matplotlib/colorbar.py#L13-L53
[ "def", "colorbar", "(", "ax", ",", "im", ",", "fig", "=", "None", ",", "loc", "=", "\"right\"", ",", "size", "=", "\"5%\"", ",", "pad", "=", "\"3%\"", ")", ":", "if", "fig", "is", "None", ":", "fig", "=", "ax", ".", "get_figure", "(", ")", "# _pdb.set_trace()", "if", "loc", "==", "\"left\"", "or", "loc", "==", "\"right\"", ":", "width", "=", "fig", ".", "get_figwidth", "(", ")", "new", "=", "width", "*", "(", "1", "+", "_pc2f", "(", "size", ")", "+", "_pc2f", "(", "pad", ")", ")", "_logger", ".", "debug", "(", "'Setting new figure width: {}'", ".", "format", "(", "new", ")", ")", "# fig.set_size_inches(new, fig.get_figheight(), forward=True)", "elif", "loc", "==", "\"top\"", "or", "loc", "==", "\"bottom\"", ":", "height", "=", "fig", ".", "get_figheight", "(", ")", "new", "=", "height", "*", "(", "1", "+", "_pc2f", "(", "size", ")", "+", "_pc2f", "(", "pad", ")", ")", "_logger", ".", "debug", "(", "'Setting new figure height: {}'", ".", "format", "(", "new", ")", ")", "# fig.set_figheight(fig.get_figwidth(), new, forward=True)", "divider", "=", "_ag1", ".", "make_axes_locatable", "(", "ax", ")", "cax", "=", "divider", ".", "append_axes", "(", "loc", ",", "size", "=", "size", ",", "pad", "=", "pad", ")", "return", "cax", ",", "_plt", ".", "colorbar", "(", "im", ",", "cax", "=", "cax", ")" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
BDES2K
Converts a quadrupole :math:`B_des` into a geometric focusing strength :math:`K`. Parameters ---------- bdes : float The magnet value of :math:`B_des`. quad_length : float The length of the quadrupole in meters. energy : float The design energy of the beam in GeV. Returns ------- K : float The geometric focusing strength :math:`K`.
scisalt/accelphys/BDES2K.py
def BDES2K(bdes, quad_length, energy): """ Converts a quadrupole :math:`B_des` into a geometric focusing strength :math:`K`. Parameters ---------- bdes : float The magnet value of :math:`B_des`. quad_length : float The length of the quadrupole in meters. energy : float The design energy of the beam in GeV. Returns ------- K : float The geometric focusing strength :math:`K`. """ # Make sure everything is float bdes = _np.float_(bdes) quad_length = _np.float_(quad_length) energy = _np.float_(energy) Brho = energy/_np.float_(0.029979) K = bdes/(Brho*quad_length) logger.log(level=loggerlevel, msg='Converted BDES: {bdes}, quad length: {quad_length}, energy: {energy} to K: {K}'.format( bdes = bdes , quad_length = quad_length , energy = energy , K = K ) ) return K
def BDES2K(bdes, quad_length, energy): """ Converts a quadrupole :math:`B_des` into a geometric focusing strength :math:`K`. Parameters ---------- bdes : float The magnet value of :math:`B_des`. quad_length : float The length of the quadrupole in meters. energy : float The design energy of the beam in GeV. Returns ------- K : float The geometric focusing strength :math:`K`. """ # Make sure everything is float bdes = _np.float_(bdes) quad_length = _np.float_(quad_length) energy = _np.float_(energy) Brho = energy/_np.float_(0.029979) K = bdes/(Brho*quad_length) logger.log(level=loggerlevel, msg='Converted BDES: {bdes}, quad length: {quad_length}, energy: {energy} to K: {K}'.format( bdes = bdes , quad_length = quad_length , energy = energy , K = K ) ) return K
[ "Converts", "a", "quadrupole", ":", "math", ":", "B_des", "into", "a", "geometric", "focusing", "strength", ":", "math", ":", "K", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/accelphys/BDES2K.py#L13-L47
[ "def", "BDES2K", "(", "bdes", ",", "quad_length", ",", "energy", ")", ":", "# Make sure everything is float", "bdes", "=", "_np", ".", "float_", "(", "bdes", ")", "quad_length", "=", "_np", ".", "float_", "(", "quad_length", ")", "energy", "=", "_np", ".", "float_", "(", "energy", ")", "Brho", "=", "energy", "/", "_np", ".", "float_", "(", "0.029979", ")", "K", "=", "bdes", "/", "(", "Brho", "*", "quad_length", ")", "logger", ".", "log", "(", "level", "=", "loggerlevel", ",", "msg", "=", "'Converted BDES: {bdes}, quad length: {quad_length}, energy: {energy} to K: {K}'", ".", "format", "(", "bdes", "=", "bdes", ",", "quad_length", "=", "quad_length", ",", "energy", "=", "energy", ",", "K", "=", "K", ")", ")", "return", "K" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
IndexedOpen.get_or_create_index
Return an open file-object to the index file
randomlineaccess/index.py
def get_or_create_index(self, index_ratio, index_width): """Return an open file-object to the index file""" if not self.index_path.exists() or not self.filepath.stat().st_mtime == self.index_path.stat().st_mtime: create_index(self.filepath, self.index_path, index_ratio=index_ratio, index_width=index_width) return IndexFile(str(self.index_path))
def get_or_create_index(self, index_ratio, index_width): """Return an open file-object to the index file""" if not self.index_path.exists() or not self.filepath.stat().st_mtime == self.index_path.stat().st_mtime: create_index(self.filepath, self.index_path, index_ratio=index_ratio, index_width=index_width) return IndexFile(str(self.index_path))
[ "Return", "an", "open", "file", "-", "object", "to", "the", "index", "file" ]
brycedrennan/random-line-access
python
https://github.com/brycedrennan/random-line-access/blob/ad46749252ffbe5885f2f001f5abb5a180939268/randomlineaccess/index.py#L94-L98
[ "def", "get_or_create_index", "(", "self", ",", "index_ratio", ",", "index_width", ")", ":", "if", "not", "self", ".", "index_path", ".", "exists", "(", ")", "or", "not", "self", ".", "filepath", ".", "stat", "(", ")", ".", "st_mtime", "==", "self", ".", "index_path", ".", "stat", "(", ")", ".", "st_mtime", ":", "create_index", "(", "self", ".", "filepath", ",", "self", ".", "index_path", ",", "index_ratio", "=", "index_ratio", ",", "index_width", "=", "index_width", ")", "return", "IndexFile", "(", "str", "(", "self", ".", "index_path", ")", ")" ]
ad46749252ffbe5885f2f001f5abb5a180939268
valid
MapRouletteTaskCollection.create
Create the tasks on the server
maproulette/taskcollection.py
def create(self, server): """Create the tasks on the server""" for chunk in self.__cut_to_size(): server.post( 'tasks_admin', chunk.as_payload(), replacements={ 'slug': chunk.challenge.slug})
def create(self, server): """Create the tasks on the server""" for chunk in self.__cut_to_size(): server.post( 'tasks_admin', chunk.as_payload(), replacements={ 'slug': chunk.challenge.slug})
[ "Create", "the", "tasks", "on", "the", "server" ]
mvexel/maproulette-api-wrapper
python
https://github.com/mvexel/maproulette-api-wrapper/blob/835278111afefed2beecf9716a033529304c548f/maproulette/taskcollection.py#L42-L49
[ "def", "create", "(", "self", ",", "server", ")", ":", "for", "chunk", "in", "self", ".", "__cut_to_size", "(", ")", ":", "server", ".", "post", "(", "'tasks_admin'", ",", "chunk", ".", "as_payload", "(", ")", ",", "replacements", "=", "{", "'slug'", ":", "chunk", ".", "challenge", ".", "slug", "}", ")" ]
835278111afefed2beecf9716a033529304c548f
valid
MapRouletteTaskCollection.update
Update existing tasks on the server
maproulette/taskcollection.py
def update(self, server): """Update existing tasks on the server""" for chunk in self.__cut_to_size(): server.put( 'tasks_admin', chunk.as_payload(), replacements={ 'slug': chunk.challenge.slug})
def update(self, server): """Update existing tasks on the server""" for chunk in self.__cut_to_size(): server.put( 'tasks_admin', chunk.as_payload(), replacements={ 'slug': chunk.challenge.slug})
[ "Update", "existing", "tasks", "on", "the", "server" ]
mvexel/maproulette-api-wrapper
python
https://github.com/mvexel/maproulette-api-wrapper/blob/835278111afefed2beecf9716a033529304c548f/maproulette/taskcollection.py#L51-L58
[ "def", "update", "(", "self", ",", "server", ")", ":", "for", "chunk", "in", "self", ".", "__cut_to_size", "(", ")", ":", "server", ".", "put", "(", "'tasks_admin'", ",", "chunk", ".", "as_payload", "(", ")", ",", "replacements", "=", "{", "'slug'", ":", "chunk", ".", "challenge", ".", "slug", "}", ")" ]
835278111afefed2beecf9716a033529304c548f
valid
MapRouletteTaskCollection.reconcile
Reconcile this collection with the server.
maproulette/taskcollection.py
def reconcile(self, server): """ Reconcile this collection with the server. """ if not self.challenge.exists(server): raise Exception('Challenge does not exist on server') existing = MapRouletteTaskCollection.from_server(server, self.challenge) same = [] new = [] changed = [] deleted = [] # reconcile the new tasks with the existing tasks: for task in self.tasks: # if the task exists on the server... if task.identifier in [existing_task.identifier for existing_task in existing.tasks]: # and they are equal... if task == existing.get_by_identifier(task.identifier): # add to 'same' list same.append(task) # if they are not equal, add to 'changed' list else: changed.append(task) # if the task does not exist on the server, add to 'new' list else: new.append(task) # next, check for tasks on the server that don't exist in the new collection... for task in existing.tasks: if task.identifier not in [task.identifier for task in self.tasks]: # ... and add those to the 'deleted' list. deleted.append(task) # update the server with new, changed, and deleted tasks if new: newCollection = MapRouletteTaskCollection(self.challenge, tasks=new) newCollection.create(server) if changed: changedCollection = MapRouletteTaskCollection(self.challenge, tasks=changed) changedCollection.update(server) if deleted: deletedCollection = MapRouletteTaskCollection(self.challenge, tasks=deleted) for task in deletedCollection.tasks: task.status = 'deleted' deletedCollection.update(server) # return same, new, changed and deleted tasks return {'same': same, 'new': new, 'changed': changed, 'deleted': deleted}
def reconcile(self, server): """ Reconcile this collection with the server. """ if not self.challenge.exists(server): raise Exception('Challenge does not exist on server') existing = MapRouletteTaskCollection.from_server(server, self.challenge) same = [] new = [] changed = [] deleted = [] # reconcile the new tasks with the existing tasks: for task in self.tasks: # if the task exists on the server... if task.identifier in [existing_task.identifier for existing_task in existing.tasks]: # and they are equal... if task == existing.get_by_identifier(task.identifier): # add to 'same' list same.append(task) # if they are not equal, add to 'changed' list else: changed.append(task) # if the task does not exist on the server, add to 'new' list else: new.append(task) # next, check for tasks on the server that don't exist in the new collection... for task in existing.tasks: if task.identifier not in [task.identifier for task in self.tasks]: # ... and add those to the 'deleted' list. deleted.append(task) # update the server with new, changed, and deleted tasks if new: newCollection = MapRouletteTaskCollection(self.challenge, tasks=new) newCollection.create(server) if changed: changedCollection = MapRouletteTaskCollection(self.challenge, tasks=changed) changedCollection.update(server) if deleted: deletedCollection = MapRouletteTaskCollection(self.challenge, tasks=deleted) for task in deletedCollection.tasks: task.status = 'deleted' deletedCollection.update(server) # return same, new, changed and deleted tasks return {'same': same, 'new': new, 'changed': changed, 'deleted': deleted}
[ "Reconcile", "this", "collection", "with", "the", "server", "." ]
mvexel/maproulette-api-wrapper
python
https://github.com/mvexel/maproulette-api-wrapper/blob/835278111afefed2beecf9716a033529304c548f/maproulette/taskcollection.py#L60-L108
[ "def", "reconcile", "(", "self", ",", "server", ")", ":", "if", "not", "self", ".", "challenge", ".", "exists", "(", "server", ")", ":", "raise", "Exception", "(", "'Challenge does not exist on server'", ")", "existing", "=", "MapRouletteTaskCollection", ".", "from_server", "(", "server", ",", "self", ".", "challenge", ")", "same", "=", "[", "]", "new", "=", "[", "]", "changed", "=", "[", "]", "deleted", "=", "[", "]", "# reconcile the new tasks with the existing tasks:", "for", "task", "in", "self", ".", "tasks", ":", "# if the task exists on the server...", "if", "task", ".", "identifier", "in", "[", "existing_task", ".", "identifier", "for", "existing_task", "in", "existing", ".", "tasks", "]", ":", "# and they are equal...", "if", "task", "==", "existing", ".", "get_by_identifier", "(", "task", ".", "identifier", ")", ":", "# add to 'same' list", "same", ".", "append", "(", "task", ")", "# if they are not equal, add to 'changed' list", "else", ":", "changed", ".", "append", "(", "task", ")", "# if the task does not exist on the server, add to 'new' list", "else", ":", "new", ".", "append", "(", "task", ")", "# next, check for tasks on the server that don't exist in the new collection...", "for", "task", "in", "existing", ".", "tasks", ":", "if", "task", ".", "identifier", "not", "in", "[", "task", ".", "identifier", "for", "task", "in", "self", ".", "tasks", "]", ":", "# ... and add those to the 'deleted' list.", "deleted", ".", "append", "(", "task", ")", "# update the server with new, changed, and deleted tasks", "if", "new", ":", "newCollection", "=", "MapRouletteTaskCollection", "(", "self", ".", "challenge", ",", "tasks", "=", "new", ")", "newCollection", ".", "create", "(", "server", ")", "if", "changed", ":", "changedCollection", "=", "MapRouletteTaskCollection", "(", "self", ".", "challenge", ",", "tasks", "=", "changed", ")", "changedCollection", ".", "update", "(", "server", ")", "if", "deleted", ":", "deletedCollection", "=", "MapRouletteTaskCollection", "(", "self", ".", "challenge", ",", "tasks", "=", "deleted", ")", "for", "task", "in", "deletedCollection", ".", "tasks", ":", "task", ".", "status", "=", "'deleted'", "deletedCollection", ".", "update", "(", "server", ")", "# return same, new, changed and deleted tasks", "return", "{", "'same'", ":", "same", ",", "'new'", ":", "new", ",", "'changed'", ":", "changed", ",", "'deleted'", ":", "deleted", "}" ]
835278111afefed2beecf9716a033529304c548f
valid
yn_prompt
Prompts the user for yes or no.
tmc/ui/prompt.py
def yn_prompt(msg, default=True): """ Prompts the user for yes or no. """ ret = custom_prompt(msg, ["y", "n"], "y" if default else "n") if ret == "y": return True return False
def yn_prompt(msg, default=True): """ Prompts the user for yes or no. """ ret = custom_prompt(msg, ["y", "n"], "y" if default else "n") if ret == "y": return True return False
[ "Prompts", "the", "user", "for", "yes", "or", "no", "." ]
minttu/tmc.py
python
https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/ui/prompt.py#L1-L8
[ "def", "yn_prompt", "(", "msg", ",", "default", "=", "True", ")", ":", "ret", "=", "custom_prompt", "(", "msg", ",", "[", "\"y\"", ",", "\"n\"", "]", ",", "\"y\"", "if", "default", "else", "\"n\"", ")", "if", "ret", "==", "\"y\"", ":", "return", "True", "return", "False" ]
212cfe1791a4aab4783f99b665cc32da6437f419
valid
custom_prompt
Prompts the user with custom options.
tmc/ui/prompt.py
def custom_prompt(msg, options, default): """ Prompts the user with custom options. """ formatted_options = [ x.upper() if x == default else x.lower() for x in options ] sure = input("{0} [{1}]: ".format(msg, "/".join(formatted_options))) if len(sure) == 0: return default for option in options: if sure.upper() == option.upper(): return option return default
def custom_prompt(msg, options, default): """ Prompts the user with custom options. """ formatted_options = [ x.upper() if x == default else x.lower() for x in options ] sure = input("{0} [{1}]: ".format(msg, "/".join(formatted_options))) if len(sure) == 0: return default for option in options: if sure.upper() == option.upper(): return option return default
[ "Prompts", "the", "user", "with", "custom", "options", "." ]
minttu/tmc.py
python
https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/ui/prompt.py#L11-L24
[ "def", "custom_prompt", "(", "msg", ",", "options", ",", "default", ")", ":", "formatted_options", "=", "[", "x", ".", "upper", "(", ")", "if", "x", "==", "default", "else", "x", ".", "lower", "(", ")", "for", "x", "in", "options", "]", "sure", "=", "input", "(", "\"{0} [{1}]: \"", ".", "format", "(", "msg", ",", "\"/\"", ".", "join", "(", "formatted_options", ")", ")", ")", "if", "len", "(", "sure", ")", "==", "0", ":", "return", "default", "for", "option", "in", "options", ":", "if", "sure", ".", "upper", "(", ")", "==", "option", ".", "upper", "(", ")", ":", "return", "option", "return", "default" ]
212cfe1791a4aab4783f99b665cc32da6437f419
valid
read
Reading the configure file and adds non-existing attributes to 'args
lrcloud/config_parser.py
def read(args): """Reading the configure file and adds non-existing attributes to 'args'""" if args.config_file is None or not isfile(args.config_file): return logging.info("Reading configure file: %s"%args.config_file) config = cparser.ConfigParser() config.read(args.config_file) if not config.has_section('lrcloud'): raise RuntimeError("Configure file has no [lrcloud] section!") for (name, value) in config.items('lrcloud'): if value == "True": value = True elif value == "False": value = False if getattr(args, name) is None: setattr(args, name, value)
def read(args): """Reading the configure file and adds non-existing attributes to 'args'""" if args.config_file is None or not isfile(args.config_file): return logging.info("Reading configure file: %s"%args.config_file) config = cparser.ConfigParser() config.read(args.config_file) if not config.has_section('lrcloud'): raise RuntimeError("Configure file has no [lrcloud] section!") for (name, value) in config.items('lrcloud'): if value == "True": value = True elif value == "False": value = False if getattr(args, name) is None: setattr(args, name, value)
[ "Reading", "the", "configure", "file", "and", "adds", "non", "-", "existing", "attributes", "to", "args" ]
madsbk/lrcloud
python
https://github.com/madsbk/lrcloud/blob/8d99be3e1abdf941642e9a1c86b7d775dc373c0b/lrcloud/config_parser.py#L22-L41
[ "def", "read", "(", "args", ")", ":", "if", "args", ".", "config_file", "is", "None", "or", "not", "isfile", "(", "args", ".", "config_file", ")", ":", "return", "logging", ".", "info", "(", "\"Reading configure file: %s\"", "%", "args", ".", "config_file", ")", "config", "=", "cparser", ".", "ConfigParser", "(", ")", "config", ".", "read", "(", "args", ".", "config_file", ")", "if", "not", "config", ".", "has_section", "(", "'lrcloud'", ")", ":", "raise", "RuntimeError", "(", "\"Configure file has no [lrcloud] section!\"", ")", "for", "(", "name", ",", "value", ")", "in", "config", ".", "items", "(", "'lrcloud'", ")", ":", "if", "value", "==", "\"True\"", ":", "value", "=", "True", "elif", "value", "==", "\"False\"", ":", "value", "=", "False", "if", "getattr", "(", "args", ",", "name", ")", "is", "None", ":", "setattr", "(", "args", ",", "name", ",", "value", ")" ]
8d99be3e1abdf941642e9a1c86b7d775dc373c0b
valid
write
Writing the configure file with the attributes in 'args
lrcloud/config_parser.py
def write(args): """Writing the configure file with the attributes in 'args'""" logging.info("Writing configure file: %s"%args.config_file) if args.config_file is None: return #Let's add each attribute of 'args' to the configure file config = cparser.ConfigParser() config.add_section("lrcloud") for p in [x for x in dir(args) if not x.startswith("_")]: if p in IGNORE_ARGS: continue#We ignore some attributes value = getattr(args, p) if value is not None: config.set('lrcloud', p, str(value)) with open(args.config_file, 'w') as f: config.write(f)
def write(args): """Writing the configure file with the attributes in 'args'""" logging.info("Writing configure file: %s"%args.config_file) if args.config_file is None: return #Let's add each attribute of 'args' to the configure file config = cparser.ConfigParser() config.add_section("lrcloud") for p in [x for x in dir(args) if not x.startswith("_")]: if p in IGNORE_ARGS: continue#We ignore some attributes value = getattr(args, p) if value is not None: config.set('lrcloud', p, str(value)) with open(args.config_file, 'w') as f: config.write(f)
[ "Writing", "the", "configure", "file", "with", "the", "attributes", "in", "args" ]
madsbk/lrcloud
python
https://github.com/madsbk/lrcloud/blob/8d99be3e1abdf941642e9a1c86b7d775dc373c0b/lrcloud/config_parser.py#L44-L62
[ "def", "write", "(", "args", ")", ":", "logging", ".", "info", "(", "\"Writing configure file: %s\"", "%", "args", ".", "config_file", ")", "if", "args", ".", "config_file", "is", "None", ":", "return", "#Let's add each attribute of 'args' to the configure file", "config", "=", "cparser", ".", "ConfigParser", "(", ")", "config", ".", "add_section", "(", "\"lrcloud\"", ")", "for", "p", "in", "[", "x", "for", "x", "in", "dir", "(", "args", ")", "if", "not", "x", ".", "startswith", "(", "\"_\"", ")", "]", ":", "if", "p", "in", "IGNORE_ARGS", ":", "continue", "#We ignore some attributes", "value", "=", "getattr", "(", "args", ",", "p", ")", "if", "value", "is", "not", "None", ":", "config", ".", "set", "(", "'lrcloud'", ",", "p", ",", "str", "(", "value", ")", ")", "with", "open", "(", "args", ".", "config_file", ",", "'w'", ")", "as", "f", ":", "config", ".", "write", "(", "f", ")" ]
8d99be3e1abdf941642e9a1c86b7d775dc373c0b
valid
_spawn_memcached
Helper function for tests. Spawns a memcached process attached to sock. Returns Popen instance. Terminate with p.terminate(). Note: sock parameter is not checked, and command is executed as shell. Use only if you trust that sock parameter. You've been warned.
memcachemap.py
def _spawn_memcached(sock): """Helper function for tests. Spawns a memcached process attached to sock. Returns Popen instance. Terminate with p.terminate(). Note: sock parameter is not checked, and command is executed as shell. Use only if you trust that sock parameter. You've been warned. """ p = subprocess.Popen('memcached -s ' + sock, shell=True) time.sleep(0.2) # memcached needs to initialize assert p.poll() is None # make sure it's running return p
def _spawn_memcached(sock): """Helper function for tests. Spawns a memcached process attached to sock. Returns Popen instance. Terminate with p.terminate(). Note: sock parameter is not checked, and command is executed as shell. Use only if you trust that sock parameter. You've been warned. """ p = subprocess.Popen('memcached -s ' + sock, shell=True) time.sleep(0.2) # memcached needs to initialize assert p.poll() is None # make sure it's running return p
[ "Helper", "function", "for", "tests", ".", "Spawns", "a", "memcached", "process", "attached", "to", "sock", ".", "Returns", "Popen", "instance", ".", "Terminate", "with", "p", ".", "terminate", "()", ".", "Note", ":", "sock", "parameter", "is", "not", "checked", "and", "command", "is", "executed", "as", "shell", ".", "Use", "only", "if", "you", "trust", "that", "sock", "parameter", ".", "You", "ve", "been", "warned", "." ]
langloisjp/pysvccache
python
https://github.com/langloisjp/pysvccache/blob/c4b95f1982f3a99e1f63341d15173099361e549b/memcachemap.py#L54-L63
[ "def", "_spawn_memcached", "(", "sock", ")", ":", "p", "=", "subprocess", ".", "Popen", "(", "'memcached -s '", "+", "sock", ",", "shell", "=", "True", ")", "time", ".", "sleep", "(", "0.2", ")", "# memcached needs to initialize", "assert", "p", ".", "poll", "(", ")", "is", "None", "# make sure it's running", "return", "p" ]
c4b95f1982f3a99e1f63341d15173099361e549b
valid
GameObject.dump
Dump (return) a dict representation of the GameObject. This is a Python dict and is NOT serialized. NB: the answer (a DigitWord object) and the mode (a GameMode object) are converted to python objects of a list and dict respectively. :return: python <dict> of the GameObject as detailed above.
python_cowbull_game/GameObject.py
def dump(self): """ Dump (return) a dict representation of the GameObject. This is a Python dict and is NOT serialized. NB: the answer (a DigitWord object) and the mode (a GameMode object) are converted to python objects of a list and dict respectively. :return: python <dict> of the GameObject as detailed above. """ return { "key": self._key, "status": self._status, "ttl": self._ttl, "answer": self._answer.word, "mode": self._mode.dump(), "guesses_made": self._guesses_made }
def dump(self): """ Dump (return) a dict representation of the GameObject. This is a Python dict and is NOT serialized. NB: the answer (a DigitWord object) and the mode (a GameMode object) are converted to python objects of a list and dict respectively. :return: python <dict> of the GameObject as detailed above. """ return { "key": self._key, "status": self._status, "ttl": self._ttl, "answer": self._answer.word, "mode": self._mode.dump(), "guesses_made": self._guesses_made }
[ "Dump", "(", "return", ")", "a", "dict", "representation", "of", "the", "GameObject", ".", "This", "is", "a", "Python", "dict", "and", "is", "NOT", "serialized", ".", "NB", ":", "the", "answer", "(", "a", "DigitWord", "object", ")", "and", "the", "mode", "(", "a", "GameMode", "object", ")", "are", "converted", "to", "python", "objects", "of", "a", "list", "and", "dict", "respectively", "." ]
dsandersAzure/python_cowbull_game
python
https://github.com/dsandersAzure/python_cowbull_game/blob/82a0d8ee127869123d4fad51a8cd1707879e368f/python_cowbull_game/GameObject.py#L123-L140
[ "def", "dump", "(", "self", ")", ":", "return", "{", "\"key\"", ":", "self", ".", "_key", ",", "\"status\"", ":", "self", ".", "_status", ",", "\"ttl\"", ":", "self", ".", "_ttl", ",", "\"answer\"", ":", "self", ".", "_answer", ".", "word", ",", "\"mode\"", ":", "self", ".", "_mode", ".", "dump", "(", ")", ",", "\"guesses_made\"", ":", "self", ".", "_guesses_made", "}" ]
82a0d8ee127869123d4fad51a8cd1707879e368f
valid
GameObject.load
Load the representation of a GameObject from a Python <dict> representing the game object. :param source: a Python <dict> as detailed above. :return:
python_cowbull_game/GameObject.py
def load(self, source=None): """ Load the representation of a GameObject from a Python <dict> representing the game object. :param source: a Python <dict> as detailed above. :return: """ if not source: raise ValueError("A valid dictionary must be passed as the source_dict") if not isinstance(source, dict): raise TypeError("A valid dictionary must be passed as the source_dict. {} given.".format(type(source))) required_keys = ( "key", "status", "ttl", "answer", "mode", "guesses_made") if not all(key in source for key in required_keys): raise ValueError("The dictionary passed is malformed: {}".format(source)) _mode = GameMode(**source["mode"]) self._key = source["key"] self._status = source["status"] self._ttl = source["ttl"] self._answer = DigitWord(*source["answer"], wordtype=_mode.digit_type) self._mode = _mode self._guesses_made = source["guesses_made"]
def load(self, source=None): """ Load the representation of a GameObject from a Python <dict> representing the game object. :param source: a Python <dict> as detailed above. :return: """ if not source: raise ValueError("A valid dictionary must be passed as the source_dict") if not isinstance(source, dict): raise TypeError("A valid dictionary must be passed as the source_dict. {} given.".format(type(source))) required_keys = ( "key", "status", "ttl", "answer", "mode", "guesses_made") if not all(key in source for key in required_keys): raise ValueError("The dictionary passed is malformed: {}".format(source)) _mode = GameMode(**source["mode"]) self._key = source["key"] self._status = source["status"] self._ttl = source["ttl"] self._answer = DigitWord(*source["answer"], wordtype=_mode.digit_type) self._mode = _mode self._guesses_made = source["guesses_made"]
[ "Load", "the", "representation", "of", "a", "GameObject", "from", "a", "Python", "<dict", ">", "representing", "the", "game", "object", "." ]
dsandersAzure/python_cowbull_game
python
https://github.com/dsandersAzure/python_cowbull_game/blob/82a0d8ee127869123d4fad51a8cd1707879e368f/python_cowbull_game/GameObject.py#L142-L172
[ "def", "load", "(", "self", ",", "source", "=", "None", ")", ":", "if", "not", "source", ":", "raise", "ValueError", "(", "\"A valid dictionary must be passed as the source_dict\"", ")", "if", "not", "isinstance", "(", "source", ",", "dict", ")", ":", "raise", "TypeError", "(", "\"A valid dictionary must be passed as the source_dict. {} given.\"", ".", "format", "(", "type", "(", "source", ")", ")", ")", "required_keys", "=", "(", "\"key\"", ",", "\"status\"", ",", "\"ttl\"", ",", "\"answer\"", ",", "\"mode\"", ",", "\"guesses_made\"", ")", "if", "not", "all", "(", "key", "in", "source", "for", "key", "in", "required_keys", ")", ":", "raise", "ValueError", "(", "\"The dictionary passed is malformed: {}\"", ".", "format", "(", "source", ")", ")", "_mode", "=", "GameMode", "(", "*", "*", "source", "[", "\"mode\"", "]", ")", "self", ".", "_key", "=", "source", "[", "\"key\"", "]", "self", ".", "_status", "=", "source", "[", "\"status\"", "]", "self", ".", "_ttl", "=", "source", "[", "\"ttl\"", "]", "self", ".", "_answer", "=", "DigitWord", "(", "*", "source", "[", "\"answer\"", "]", ",", "wordtype", "=", "_mode", ".", "digit_type", ")", "self", ".", "_mode", "=", "_mode", "self", ".", "_guesses_made", "=", "source", "[", "\"guesses_made\"", "]" ]
82a0d8ee127869123d4fad51a8cd1707879e368f
valid
GameObject.new
Create a new instance of a game. Note, a mode MUST be provided and MUST be of type GameMode. :param mode: <required>
python_cowbull_game/GameObject.py
def new(self, mode): """ Create a new instance of a game. Note, a mode MUST be provided and MUST be of type GameMode. :param mode: <required> """ dw = DigitWord(wordtype=mode.digit_type) dw.random(mode.digits) self._key = str(uuid.uuid4()) self._status = "" self._ttl = 3600 self._answer = dw self._mode = mode self._guesses_remaining = mode.guesses_allowed self._guesses_made = 0
def new(self, mode): """ Create a new instance of a game. Note, a mode MUST be provided and MUST be of type GameMode. :param mode: <required> """ dw = DigitWord(wordtype=mode.digit_type) dw.random(mode.digits) self._key = str(uuid.uuid4()) self._status = "" self._ttl = 3600 self._answer = dw self._mode = mode self._guesses_remaining = mode.guesses_allowed self._guesses_made = 0
[ "Create", "a", "new", "instance", "of", "a", "game", ".", "Note", "a", "mode", "MUST", "be", "provided", "and", "MUST", "be", "of", "type", "GameMode", "." ]
dsandersAzure/python_cowbull_game
python
https://github.com/dsandersAzure/python_cowbull_game/blob/82a0d8ee127869123d4fad51a8cd1707879e368f/python_cowbull_game/GameObject.py#L174-L191
[ "def", "new", "(", "self", ",", "mode", ")", ":", "dw", "=", "DigitWord", "(", "wordtype", "=", "mode", ".", "digit_type", ")", "dw", ".", "random", "(", "mode", ".", "digits", ")", "self", ".", "_key", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "self", ".", "_status", "=", "\"\"", "self", ".", "_ttl", "=", "3600", "self", ".", "_answer", "=", "dw", "self", ".", "_mode", "=", "mode", "self", ".", "_guesses_remaining", "=", "mode", ".", "guesses_allowed", "self", ".", "_guesses_made", "=", "0" ]
82a0d8ee127869123d4fad51a8cd1707879e368f
valid
SimBeam.emit_measured
The beam emittance :math:`\\langle x x' \\rangle`.
scisalt/PWFA/sim.py
def emit_measured(self): """ The beam emittance :math:`\\langle x x' \\rangle`. """ return _np.sqrt(self.spotsq*self.divsq-self.xxp**2)
def emit_measured(self): """ The beam emittance :math:`\\langle x x' \\rangle`. """ return _np.sqrt(self.spotsq*self.divsq-self.xxp**2)
[ "The", "beam", "emittance", ":", "math", ":", "\\\\", "langle", "x", "x", "\\\\", "rangle", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/PWFA/sim.py#L160-L164
[ "def", "emit_measured", "(", "self", ")", ":", "return", "_np", ".", "sqrt", "(", "self", ".", "spotsq", "*", "self", ".", "divsq", "-", "self", ".", "xxp", "**", "2", ")" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
Version.bump
Bumps the Version given a target The target can be either MAJOR, MINOR or PATCH
yld/tag.py
def bump(self, target): """ Bumps the Version given a target The target can be either MAJOR, MINOR or PATCH """ if target == 'patch': return Version(self.major, self.minor, self.patch + 1) if target == 'minor': return Version(self.major, self.minor + 1, 0) if target == 'major': return Version(self.major + 1, 0, 0) return self.clone()
def bump(self, target): """ Bumps the Version given a target The target can be either MAJOR, MINOR or PATCH """ if target == 'patch': return Version(self.major, self.minor, self.patch + 1) if target == 'minor': return Version(self.major, self.minor + 1, 0) if target == 'major': return Version(self.major + 1, 0, 0) return self.clone()
[ "Bumps", "the", "Version", "given", "a", "target" ]
ewilazarus/yld
python
https://github.com/ewilazarus/yld/blob/157e474d1055f14ffdfd7e99da6c77d5f17d4307/yld/tag.py#L51-L63
[ "def", "bump", "(", "self", ",", "target", ")", ":", "if", "target", "==", "'patch'", ":", "return", "Version", "(", "self", ".", "major", ",", "self", ".", "minor", ",", "self", ".", "patch", "+", "1", ")", "if", "target", "==", "'minor'", ":", "return", "Version", "(", "self", ".", "major", ",", "self", ".", "minor", "+", "1", ",", "0", ")", "if", "target", "==", "'major'", ":", "return", "Version", "(", "self", ".", "major", "+", "1", ",", "0", ",", "0", ")", "return", "self", ".", "clone", "(", ")" ]
157e474d1055f14ffdfd7e99da6c77d5f17d4307
valid
Tag.clone
Returns a copy of this object
yld/tag.py
def clone(self): """ Returns a copy of this object """ t = Tag(self.version.major, self.version.minor, self.version.patch) if self.revision is not None: t.revision = self.revision.clone() return t
def clone(self): """ Returns a copy of this object """ t = Tag(self.version.major, self.version.minor, self.version.patch) if self.revision is not None: t.revision = self.revision.clone() return t
[ "Returns", "a", "copy", "of", "this", "object" ]
ewilazarus/yld
python
https://github.com/ewilazarus/yld/blob/157e474d1055f14ffdfd7e99da6c77d5f17d4307/yld/tag.py#L142-L149
[ "def", "clone", "(", "self", ")", ":", "t", "=", "Tag", "(", "self", ".", "version", ".", "major", ",", "self", ".", "version", ".", "minor", ",", "self", ".", "version", ".", "patch", ")", "if", "self", ".", "revision", "is", "not", "None", ":", "t", ".", "revision", "=", "self", ".", "revision", ".", "clone", "(", ")", "return", "t" ]
157e474d1055f14ffdfd7e99da6c77d5f17d4307
valid
Tag.with_revision
Returns a Tag with a given revision
yld/tag.py
def with_revision(self, label, number): """ Returns a Tag with a given revision """ t = self.clone() t.revision = Revision(label, number) return t
def with_revision(self, label, number): """ Returns a Tag with a given revision """ t = self.clone() t.revision = Revision(label, number) return t
[ "Returns", "a", "Tag", "with", "a", "given", "revision" ]
ewilazarus/yld
python
https://github.com/ewilazarus/yld/blob/157e474d1055f14ffdfd7e99da6c77d5f17d4307/yld/tag.py#L151-L157
[ "def", "with_revision", "(", "self", ",", "label", ",", "number", ")", ":", "t", "=", "self", ".", "clone", "(", ")", "t", ".", "revision", "=", "Revision", "(", "label", ",", "number", ")", "return", "t" ]
157e474d1055f14ffdfd7e99da6c77d5f17d4307
valid
Tag.parse
Parses a string into a Tag
yld/tag.py
def parse(s): """ Parses a string into a Tag """ try: m = _regex.match(s) t = Tag(int(m.group('major')), int(m.group('minor')), int(m.group('patch'))) return t \ if m.group('label') is None \ else t.with_revision(m.group('label'), int(m.group('number'))) except AttributeError: return None
def parse(s): """ Parses a string into a Tag """ try: m = _regex.match(s) t = Tag(int(m.group('major')), int(m.group('minor')), int(m.group('patch'))) return t \ if m.group('label') is None \ else t.with_revision(m.group('label'), int(m.group('number'))) except AttributeError: return None
[ "Parses", "a", "string", "into", "a", "Tag" ]
ewilazarus/yld
python
https://github.com/ewilazarus/yld/blob/157e474d1055f14ffdfd7e99da6c77d5f17d4307/yld/tag.py#L174-L187
[ "def", "parse", "(", "s", ")", ":", "try", ":", "m", "=", "_regex", ".", "match", "(", "s", ")", "t", "=", "Tag", "(", "int", "(", "m", ".", "group", "(", "'major'", ")", ")", ",", "int", "(", "m", ".", "group", "(", "'minor'", ")", ")", ",", "int", "(", "m", ".", "group", "(", "'patch'", ")", ")", ")", "return", "t", "if", "m", ".", "group", "(", "'label'", ")", "is", "None", "else", "t", ".", "with_revision", "(", "m", ".", "group", "(", "'label'", ")", ",", "int", "(", "m", ".", "group", "(", "'number'", ")", ")", ")", "except", "AttributeError", ":", "return", "None" ]
157e474d1055f14ffdfd7e99da6c77d5f17d4307
valid
TagHandler.yield_tag
Returns a new Tag containing the bumped target and/or the bumped label
yld/tag.py
def yield_tag(self, target=None, label=None): """ Returns a new Tag containing the bumped target and/or the bumped label """ if target is None and label is None: raise ValueError('`target` and/or `label` must be specified') if label is None: return self._yield_from_target(target) if target is None: return self._yield_from_label(label) return self._yield_from_target_and_label(target, label)
def yield_tag(self, target=None, label=None): """ Returns a new Tag containing the bumped target and/or the bumped label """ if target is None and label is None: raise ValueError('`target` and/or `label` must be specified') if label is None: return self._yield_from_target(target) if target is None: return self._yield_from_label(label) return self._yield_from_target_and_label(target, label)
[ "Returns", "a", "new", "Tag", "containing", "the", "bumped", "target", "and", "/", "or", "the", "bumped", "label" ]
ewilazarus/yld
python
https://github.com/ewilazarus/yld/blob/157e474d1055f14ffdfd7e99da6c77d5f17d4307/yld/tag.py#L226-L236
[ "def", "yield_tag", "(", "self", ",", "target", "=", "None", ",", "label", "=", "None", ")", ":", "if", "target", "is", "None", "and", "label", "is", "None", ":", "raise", "ValueError", "(", "'`target` and/or `label` must be specified'", ")", "if", "label", "is", "None", ":", "return", "self", ".", "_yield_from_target", "(", "target", ")", "if", "target", "is", "None", ":", "return", "self", ".", "_yield_from_label", "(", "label", ")", "return", "self", ".", "_yield_from_target_and_label", "(", "target", ",", "label", ")" ]
157e474d1055f14ffdfd7e99da6c77d5f17d4307
valid
tile
Tiles open figures.
scisalt/matplotlib/tile.py
def tile(): """Tiles open figures.""" figs = plt.get_fignums() # Keep track of x, y, size for figures x = 0 y = 0 # maxy = 0 toppad = 21 size = np.array([0, 0]) if ( len(figs) != 0 ): fig = plt.figure(figs[0]) screen = fig.canvas.window.get_screen() screenx = screen.get_monitor_geometry(screen.get_primary_monitor()) screenx = screenx[2] fig = plt.figure(figs[0]) fig.canvas.manager.window.move(x, y) maxy = np.array(fig.canvas.manager.window.get_position())[1] size = np.array(fig.canvas.manager.window.get_size()) y = maxy x += size[0]+1 for fig in figs[1:]: fig = plt.figure(fig) size = np.array(fig.canvas.manager.window.get_size()) if ( x+size[0] > screenx ): x = 0 y = maxy maxy = y+size[1]+toppad else: maxy = max(maxy, y+size[1]+toppad) fig.canvas.manager.window.move(x, y) x += size[0] + 1
def tile(): """Tiles open figures.""" figs = plt.get_fignums() # Keep track of x, y, size for figures x = 0 y = 0 # maxy = 0 toppad = 21 size = np.array([0, 0]) if ( len(figs) != 0 ): fig = plt.figure(figs[0]) screen = fig.canvas.window.get_screen() screenx = screen.get_monitor_geometry(screen.get_primary_monitor()) screenx = screenx[2] fig = plt.figure(figs[0]) fig.canvas.manager.window.move(x, y) maxy = np.array(fig.canvas.manager.window.get_position())[1] size = np.array(fig.canvas.manager.window.get_size()) y = maxy x += size[0]+1 for fig in figs[1:]: fig = plt.figure(fig) size = np.array(fig.canvas.manager.window.get_size()) if ( x+size[0] > screenx ): x = 0 y = maxy maxy = y+size[1]+toppad else: maxy = max(maxy, y+size[1]+toppad) fig.canvas.manager.window.move(x, y) x += size[0] + 1
[ "Tiles", "open", "figures", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/matplotlib/tile.py#L9-L45
[ "def", "tile", "(", ")", ":", "figs", "=", "plt", ".", "get_fignums", "(", ")", "# Keep track of x, y, size for figures", "x", "=", "0", "y", "=", "0", "# maxy = 0", "toppad", "=", "21", "size", "=", "np", ".", "array", "(", "[", "0", ",", "0", "]", ")", "if", "(", "len", "(", "figs", ")", "!=", "0", ")", ":", "fig", "=", "plt", ".", "figure", "(", "figs", "[", "0", "]", ")", "screen", "=", "fig", ".", "canvas", ".", "window", ".", "get_screen", "(", ")", "screenx", "=", "screen", ".", "get_monitor_geometry", "(", "screen", ".", "get_primary_monitor", "(", ")", ")", "screenx", "=", "screenx", "[", "2", "]", "fig", "=", "plt", ".", "figure", "(", "figs", "[", "0", "]", ")", "fig", ".", "canvas", ".", "manager", ".", "window", ".", "move", "(", "x", ",", "y", ")", "maxy", "=", "np", ".", "array", "(", "fig", ".", "canvas", ".", "manager", ".", "window", ".", "get_position", "(", ")", ")", "[", "1", "]", "size", "=", "np", ".", "array", "(", "fig", ".", "canvas", ".", "manager", ".", "window", ".", "get_size", "(", ")", ")", "y", "=", "maxy", "x", "+=", "size", "[", "0", "]", "+", "1", "for", "fig", "in", "figs", "[", "1", ":", "]", ":", "fig", "=", "plt", ".", "figure", "(", "fig", ")", "size", "=", "np", ".", "array", "(", "fig", ".", "canvas", ".", "manager", ".", "window", ".", "get_size", "(", ")", ")", "if", "(", "x", "+", "size", "[", "0", "]", ">", "screenx", ")", ":", "x", "=", "0", "y", "=", "maxy", "maxy", "=", "y", "+", "size", "[", "1", "]", "+", "toppad", "else", ":", "maxy", "=", "max", "(", "maxy", ",", "y", "+", "size", "[", "1", "]", "+", "toppad", ")", "fig", ".", "canvas", ".", "manager", ".", "window", ".", "move", "(", "x", ",", "y", ")", "x", "+=", "size", "[", "0", "]", "+", "1" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
linspaceborders
Generate a new array with numbers interpolated between the numbers of the input array. Extrapolates elements to the left and right sides to get the exterior border as well. Parameters ---------- array : :class:`numpy.ndarray` The original array. Returns ------- array : :class:`numpy.ndarray` The interpolated/extrapolated array.
scisalt/numpy/linspaceborders.py
def linspaceborders(array): """ Generate a new array with numbers interpolated between the numbers of the input array. Extrapolates elements to the left and right sides to get the exterior border as well. Parameters ---------- array : :class:`numpy.ndarray` The original array. Returns ------- array : :class:`numpy.ndarray` The interpolated/extrapolated array. """ # Get and set left side dela = array[1] - array[0] new_arr = _np.array([array[0] - dela / 2]) # Add a point to the right side so the for loop works delb = array[-1] - array[-2] array = _np.append(array, array[-1] + delb) for i, val in enumerate(array): try: avg = (array[i] + array[i + 1]) / 2 new_arr = _np.append(new_arr, avg) except: pass # start = array[0] - dela / 2 # end = array[-1] + dela / 2 # return _linspacestep(start, end, dela) return new_arr
def linspaceborders(array): """ Generate a new array with numbers interpolated between the numbers of the input array. Extrapolates elements to the left and right sides to get the exterior border as well. Parameters ---------- array : :class:`numpy.ndarray` The original array. Returns ------- array : :class:`numpy.ndarray` The interpolated/extrapolated array. """ # Get and set left side dela = array[1] - array[0] new_arr = _np.array([array[0] - dela / 2]) # Add a point to the right side so the for loop works delb = array[-1] - array[-2] array = _np.append(array, array[-1] + delb) for i, val in enumerate(array): try: avg = (array[i] + array[i + 1]) / 2 new_arr = _np.append(new_arr, avg) except: pass # start = array[0] - dela / 2 # end = array[-1] + dela / 2 # return _linspacestep(start, end, dela) return new_arr
[ "Generate", "a", "new", "array", "with", "numbers", "interpolated", "between", "the", "numbers", "of", "the", "input", "array", ".", "Extrapolates", "elements", "to", "the", "left", "and", "right", "sides", "to", "get", "the", "exterior", "border", "as", "well", ".", "Parameters", "----------" ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/numpy/linspaceborders.py#L8-L40
[ "def", "linspaceborders", "(", "array", ")", ":", "# Get and set left side", "dela", "=", "array", "[", "1", "]", "-", "array", "[", "0", "]", "new_arr", "=", "_np", ".", "array", "(", "[", "array", "[", "0", "]", "-", "dela", "/", "2", "]", ")", "# Add a point to the right side so the for loop works", "delb", "=", "array", "[", "-", "1", "]", "-", "array", "[", "-", "2", "]", "array", "=", "_np", ".", "append", "(", "array", ",", "array", "[", "-", "1", "]", "+", "delb", ")", "for", "i", ",", "val", "in", "enumerate", "(", "array", ")", ":", "try", ":", "avg", "=", "(", "array", "[", "i", "]", "+", "array", "[", "i", "+", "1", "]", ")", "/", "2", "new_arr", "=", "_np", ".", "append", "(", "new_arr", ",", "avg", ")", "except", ":", "pass", "# start = array[0] - dela / 2", "# end = array[-1] + dela / 2", "# return _linspacestep(start, end, dela)", "return", "new_arr" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
Ions1D.nb0
On-axis beam density :math:`n_{b,0}`.
scisalt/PWFA/ions1d.py
def nb0(self): """ On-axis beam density :math:`n_{b,0}`. """ return self.N_e / (4*_np.sqrt(3) * _np.pi * self.sig_x * self.sig_y * self.sig_xi)
def nb0(self): """ On-axis beam density :math:`n_{b,0}`. """ return self.N_e / (4*_np.sqrt(3) * _np.pi * self.sig_x * self.sig_y * self.sig_xi)
[ "On", "-", "axis", "beam", "density", ":", "math", ":", "n_", "{", "b", "0", "}", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/PWFA/ions1d.py#L73-L77
[ "def", "nb0", "(", "self", ")", ":", "return", "self", ".", "N_e", "/", "(", "4", "*", "_np", ".", "sqrt", "(", "3", ")", "*", "_np", ".", "pi", "*", "self", ".", "sig_x", "*", "self", ".", "sig_y", "*", "self", ".", "sig_xi", ")" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
Ions1D.k
Driving force term: :math:`r'' = -k \\left( \\frac{1-e^{-r^2/2{\\sigma_r}^2}}{r} \\right)`
scisalt/PWFA/ions1d.py
def k(self): """ Driving force term: :math:`r'' = -k \\left( \\frac{1-e^{-r^2/2{\\sigma_r}^2}}{r} \\right)` """ try: return self._k except AttributeError: self._k = _np.sqrt(_np.pi/8) * e**2 * self.nb0 * self.sig_y / ( e0 * self.m * c**2) return self._k
def k(self): """ Driving force term: :math:`r'' = -k \\left( \\frac{1-e^{-r^2/2{\\sigma_r}^2}}{r} \\right)` """ try: return self._k except AttributeError: self._k = _np.sqrt(_np.pi/8) * e**2 * self.nb0 * self.sig_y / ( e0 * self.m * c**2) return self._k
[ "Driving", "force", "term", ":", ":", "math", ":", "r", "=", "-", "k", "\\\\", "left", "(", "\\\\", "frac", "{", "1", "-", "e^", "{", "-", "r^2", "/", "2", "{", "\\\\", "sigma_r", "}", "^2", "}}", "{", "r", "}", "\\\\", "right", ")" ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/PWFA/ions1d.py#L80-L88
[ "def", "k", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_k", "except", "AttributeError", ":", "self", ".", "_k", "=", "_np", ".", "sqrt", "(", "_np", ".", "pi", "/", "8", ")", "*", "e", "**", "2", "*", "self", ".", "nb0", "*", "self", ".", "sig_y", "/", "(", "e0", "*", "self", ".", "m", "*", "c", "**", "2", ")", "return", "self", ".", "_k" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
Ions1D.k_small
Small-angle driving force term: :math:`r'' = -k_{small} r`. Note: :math:`k_{small} = \\frac{k}{2{\\sigma_r^2}}`
scisalt/PWFA/ions1d.py
def k_small(self): """ Small-angle driving force term: :math:`r'' = -k_{small} r`. Note: :math:`k_{small} = \\frac{k}{2{\\sigma_r^2}}` """ return self.k * _np.sqrt(2/_np.pi) / self.sig_y
def k_small(self): """ Small-angle driving force term: :math:`r'' = -k_{small} r`. Note: :math:`k_{small} = \\frac{k}{2{\\sigma_r^2}}` """ return self.k * _np.sqrt(2/_np.pi) / self.sig_y
[ "Small", "-", "angle", "driving", "force", "term", ":", ":", "math", ":", "r", "=", "-", "k_", "{", "small", "}", "r", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/PWFA/ions1d.py#L91-L97
[ "def", "k_small", "(", "self", ")", ":", "return", "self", ".", "k", "*", "_np", ".", "sqrt", "(", "2", "/", "_np", ".", "pi", ")", "/", "self", ".", "sig_y" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
update_time
When a Comment is added, updates the Update to set "last_updated" time
build/lib/happenings/signals.py
def update_time(sender, **kwargs): """ When a Comment is added, updates the Update to set "last_updated" time """ comment = kwargs['instance'] if comment.content_type.app_label == "happenings" and comment.content_type.name == "Update": from .models import Update item = Update.objects.get(id=comment.object_pk) item.save()
def update_time(sender, **kwargs): """ When a Comment is added, updates the Update to set "last_updated" time """ comment = kwargs['instance'] if comment.content_type.app_label == "happenings" and comment.content_type.name == "Update": from .models import Update item = Update.objects.get(id=comment.object_pk) item.save()
[ "When", "a", "Comment", "is", "added", "updates", "the", "Update", "to", "set", "last_updated", "time" ]
tBaxter/tango-happenings
python
https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/signals.py#L2-L10
[ "def", "update_time", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "comment", "=", "kwargs", "[", "'instance'", "]", "if", "comment", ".", "content_type", ".", "app_label", "==", "\"happenings\"", "and", "comment", ".", "content_type", ".", "name", "==", "\"Update\"", ":", "from", ".", "models", "import", "Update", "item", "=", "Update", ".", "objects", ".", "get", "(", "id", "=", "comment", ".", "object_pk", ")", "item", ".", "save", "(", ")" ]
cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2
valid
Game.new_game
new_game() creates a new game. Docs TBC. :return: JSON String containing the game object.
python_cowbull_game/v1_deprecated/Game.py
def new_game(self, mode=None): """ new_game() creates a new game. Docs TBC. :return: JSON String containing the game object. """ # Create a placeholder Game object self._g = GameObject() # Validate game mode _mode = mode or "normal" logging.debug("new_game: requesting mode {}".format(_mode)) mode_info = self._g.get_game_type(gametype=_mode) logging.debug("mode_info: {} (Type: {})".format(mode_info, type(mode_info))) if not mode_info: self._g = None raise ValueError('The mode passed ({}) is not supported.'.format(_mode)) logging.debug("Creating a DigitWord (type {})".format(mode_info.digitType)) dw = DigitWord(wordtype=mode_info.digitType) dw.random(mode_info.digits) logging.debug("Randomized DigitWord. Value is {}.".format(dw.word)) _game = { "key": str(uuid.uuid4()), "status": "playing", "ttl": int(time()) + 3600, "answer": dw.word, "mode": _mode, "guesses_remaining": mode_info.guesses_allowed, "guesses_made": 0 } logging.debug("Game being created: {}".format(_game)) self._g.from_json(jsonstr=json.dumps(_game)) return self._g.to_json()
def new_game(self, mode=None): """ new_game() creates a new game. Docs TBC. :return: JSON String containing the game object. """ # Create a placeholder Game object self._g = GameObject() # Validate game mode _mode = mode or "normal" logging.debug("new_game: requesting mode {}".format(_mode)) mode_info = self._g.get_game_type(gametype=_mode) logging.debug("mode_info: {} (Type: {})".format(mode_info, type(mode_info))) if not mode_info: self._g = None raise ValueError('The mode passed ({}) is not supported.'.format(_mode)) logging.debug("Creating a DigitWord (type {})".format(mode_info.digitType)) dw = DigitWord(wordtype=mode_info.digitType) dw.random(mode_info.digits) logging.debug("Randomized DigitWord. Value is {}.".format(dw.word)) _game = { "key": str(uuid.uuid4()), "status": "playing", "ttl": int(time()) + 3600, "answer": dw.word, "mode": _mode, "guesses_remaining": mode_info.guesses_allowed, "guesses_made": 0 } logging.debug("Game being created: {}".format(_game)) self._g.from_json(jsonstr=json.dumps(_game)) return self._g.to_json()
[ "new_game", "()", "creates", "a", "new", "game", ".", "Docs", "TBC", "." ]
dsandersAzure/python_cowbull_game
python
https://github.com/dsandersAzure/python_cowbull_game/blob/82a0d8ee127869123d4fad51a8cd1707879e368f/python_cowbull_game/v1_deprecated/Game.py#L53-L93
[ "def", "new_game", "(", "self", ",", "mode", "=", "None", ")", ":", "# Create a placeholder Game object", "self", ".", "_g", "=", "GameObject", "(", ")", "# Validate game mode", "_mode", "=", "mode", "or", "\"normal\"", "logging", ".", "debug", "(", "\"new_game: requesting mode {}\"", ".", "format", "(", "_mode", ")", ")", "mode_info", "=", "self", ".", "_g", ".", "get_game_type", "(", "gametype", "=", "_mode", ")", "logging", ".", "debug", "(", "\"mode_info: {} (Type: {})\"", ".", "format", "(", "mode_info", ",", "type", "(", "mode_info", ")", ")", ")", "if", "not", "mode_info", ":", "self", ".", "_g", "=", "None", "raise", "ValueError", "(", "'The mode passed ({}) is not supported.'", ".", "format", "(", "_mode", ")", ")", "logging", ".", "debug", "(", "\"Creating a DigitWord (type {})\"", ".", "format", "(", "mode_info", ".", "digitType", ")", ")", "dw", "=", "DigitWord", "(", "wordtype", "=", "mode_info", ".", "digitType", ")", "dw", ".", "random", "(", "mode_info", ".", "digits", ")", "logging", ".", "debug", "(", "\"Randomized DigitWord. Value is {}.\"", ".", "format", "(", "dw", ".", "word", ")", ")", "_game", "=", "{", "\"key\"", ":", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", ",", "\"status\"", ":", "\"playing\"", ",", "\"ttl\"", ":", "int", "(", "time", "(", ")", ")", "+", "3600", ",", "\"answer\"", ":", "dw", ".", "word", ",", "\"mode\"", ":", "_mode", ",", "\"guesses_remaining\"", ":", "mode_info", ".", "guesses_allowed", ",", "\"guesses_made\"", ":", "0", "}", "logging", ".", "debug", "(", "\"Game being created: {}\"", ".", "format", "(", "_game", ")", ")", "self", ".", "_g", ".", "from_json", "(", "jsonstr", "=", "json", ".", "dumps", "(", "_game", ")", ")", "return", "self", ".", "_g", ".", "to_json", "(", ")" ]
82a0d8ee127869123d4fad51a8cd1707879e368f
valid
Game.load_game
load_game() takes a JSON string representing a game object and calls the underlying game object (_g) to load the JSON. The underlying object will handle schema validation and transformation. :param jsonstr: A valid JSON string representing a GameObject (see above) :return: None
python_cowbull_game/v1_deprecated/Game.py
def load_game(self, jsonstr): """ load_game() takes a JSON string representing a game object and calls the underlying game object (_g) to load the JSON. The underlying object will handle schema validation and transformation. :param jsonstr: A valid JSON string representing a GameObject (see above) :return: None """ logging.debug("load_game called.") logging.debug("Creating empty GameObject.") self._g = GameObject() logging.debug("Calling from_json with {}.".format(jsonstr)) self._g.from_json(jsonstr=jsonstr)
def load_game(self, jsonstr): """ load_game() takes a JSON string representing a game object and calls the underlying game object (_g) to load the JSON. The underlying object will handle schema validation and transformation. :param jsonstr: A valid JSON string representing a GameObject (see above) :return: None """ logging.debug("load_game called.") logging.debug("Creating empty GameObject.") self._g = GameObject() logging.debug("Calling from_json with {}.".format(jsonstr)) self._g.from_json(jsonstr=jsonstr)
[ "load_game", "()", "takes", "a", "JSON", "string", "representing", "a", "game", "object", "and", "calls", "the", "underlying", "game", "object", "(", "_g", ")", "to", "load", "the", "JSON", ".", "The", "underlying", "object", "will", "handle", "schema", "validation", "and", "transformation", "." ]
dsandersAzure/python_cowbull_game
python
https://github.com/dsandersAzure/python_cowbull_game/blob/82a0d8ee127869123d4fad51a8cd1707879e368f/python_cowbull_game/v1_deprecated/Game.py#L95-L111
[ "def", "load_game", "(", "self", ",", "jsonstr", ")", ":", "logging", ".", "debug", "(", "\"load_game called.\"", ")", "logging", ".", "debug", "(", "\"Creating empty GameObject.\"", ")", "self", ".", "_g", "=", "GameObject", "(", ")", "logging", ".", "debug", "(", "\"Calling from_json with {}.\"", ".", "format", "(", "jsonstr", ")", ")", "self", ".", "_g", ".", "from_json", "(", "jsonstr", "=", "jsonstr", ")" ]
82a0d8ee127869123d4fad51a8cd1707879e368f