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
Game.save_game
save_game() asks the underlying game object (_g) to dump the contents of itself as JSON and then returns the JSON to :return: A JSON representation of the game object
python_cowbull_game/v1_deprecated/Game.py
def save_game(self): """ save_game() asks the underlying game object (_g) to dump the contents of itself as JSON and then returns the JSON to :return: A JSON representation of the game object """ logging.debug("save_game called.") logging.debug("Validating game object") self._validate_game_object(op="save_game") logging.debug("Dumping JSON from GameObject") return self._g.to_json()
def save_game(self): """ save_game() asks the underlying game object (_g) to dump the contents of itself as JSON and then returns the JSON to :return: A JSON representation of the game object """ logging.debug("save_game called.") logging.debug("Validating game object") self._validate_game_object(op="save_game") logging.debug("Dumping JSON from GameObject") return self._g.to_json()
[ "save_game", "()", "asks", "the", "underlying", "game", "object", "(", "_g", ")", "to", "dump", "the", "contents", "of", "itself", "as", "JSON", "and", "then", "returns", "the", "JSON", "to" ]
dsandersAzure/python_cowbull_game
python
https://github.com/dsandersAzure/python_cowbull_game/blob/82a0d8ee127869123d4fad51a8cd1707879e368f/python_cowbull_game/v1_deprecated/Game.py#L113-L126
[ "def", "save_game", "(", "self", ")", ":", "logging", ".", "debug", "(", "\"save_game called.\"", ")", "logging", ".", "debug", "(", "\"Validating game object\"", ")", "self", ".", "_validate_game_object", "(", "op", "=", "\"save_game\"", ")", "logging", ".", "debug", "(", "\"Dumping JSON from GameObject\"", ")", "return", "self", ".", "_g", ".", "to_json", "(", ")" ]
82a0d8ee127869123d4fad51a8cd1707879e368f
valid
Game.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/v1_deprecated/Game.py
def guess(self, *args): """ 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_game_object(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._g.status.lower() == "won": _return_results["message"] = self._start_again("You already won!") elif self._g.status.lower() == "lost": _return_results["message"] = self._start_again("You have made too many guesses_allowed, you lost!") elif self._g.guesses_remaining < 1: _return_results["message"] = self._start_again("You have run out of tries, sorry!") elif self._g.ttl < time(): _return_results["message"] = self._start_again("Sorry, you ran out of time to complete the puzzle!") else: logging.debug("Creating a DigitWord for the guess.") _wordtype = DigitWord.HEXDIGIT if self._g.mode.lower() == 'hex' else DigitWord.DIGIT guess = DigitWord(*args, wordtype=_wordtype) logging.debug("Validating guess.") self._g.guesses_remaining -= 1 self._g.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._g.answer.compare(guess): logging.debug("Iteration of guesses_allowed. 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._g.answer.word): logging.debug("Game was won.") self._g.status = "won" self._g.guesses_remaining = 0 _return_results["message"] = "Well done! You won the game with your " \ "answers {}".format(self._get_text_answer()) elif self._g.guesses_remaining < 1: logging.debug("Game was lost.") self._g.status = "lost" _return_results["message"] = "Sorry, you lost! The correct answer was " \ "{}".format(self._get_text_answer()) _return_results["status"] = self._g.status logging.debug("Returning results.") return _return_results
def guess(self, *args): """ 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_game_object(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._g.status.lower() == "won": _return_results["message"] = self._start_again("You already won!") elif self._g.status.lower() == "lost": _return_results["message"] = self._start_again("You have made too many guesses_allowed, you lost!") elif self._g.guesses_remaining < 1: _return_results["message"] = self._start_again("You have run out of tries, sorry!") elif self._g.ttl < time(): _return_results["message"] = self._start_again("Sorry, you ran out of time to complete the puzzle!") else: logging.debug("Creating a DigitWord for the guess.") _wordtype = DigitWord.HEXDIGIT if self._g.mode.lower() == 'hex' else DigitWord.DIGIT guess = DigitWord(*args, wordtype=_wordtype) logging.debug("Validating guess.") self._g.guesses_remaining -= 1 self._g.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._g.answer.compare(guess): logging.debug("Iteration of guesses_allowed. 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._g.answer.word): logging.debug("Game was won.") self._g.status = "won" self._g.guesses_remaining = 0 _return_results["message"] = "Well done! You won the game with your " \ "answers {}".format(self._get_text_answer()) elif self._g.guesses_remaining < 1: logging.debug("Game was lost.") self._g.status = "lost" _return_results["message"] = "Sorry, you lost! The correct answer was " \ "{}".format(self._get_text_answer()) _return_results["status"] = self._g.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/v1_deprecated/Game.py#L128-L217
[ "def", "guess", "(", "self", ",", "*", "args", ")", ":", "logging", ".", "debug", "(", "\"guess called.\"", ")", "logging", ".", "debug", "(", "\"Validating game object\"", ")", "self", ".", "_validate_game_object", "(", "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", ".", "_g", ".", "status", ".", "lower", "(", ")", "==", "\"won\"", ":", "_return_results", "[", "\"message\"", "]", "=", "self", ".", "_start_again", "(", "\"You already won!\"", ")", "elif", "self", ".", "_g", ".", "status", ".", "lower", "(", ")", "==", "\"lost\"", ":", "_return_results", "[", "\"message\"", "]", "=", "self", ".", "_start_again", "(", "\"You have made too many guesses_allowed, you lost!\"", ")", "elif", "self", ".", "_g", ".", "guesses_remaining", "<", "1", ":", "_return_results", "[", "\"message\"", "]", "=", "self", ".", "_start_again", "(", "\"You have run out of tries, sorry!\"", ")", "elif", "self", ".", "_g", ".", "ttl", "<", "time", "(", ")", ":", "_return_results", "[", "\"message\"", "]", "=", "self", ".", "_start_again", "(", "\"Sorry, you ran out of time to complete the puzzle!\"", ")", "else", ":", "logging", ".", "debug", "(", "\"Creating a DigitWord for the guess.\"", ")", "_wordtype", "=", "DigitWord", ".", "HEXDIGIT", "if", "self", ".", "_g", ".", "mode", ".", "lower", "(", ")", "==", "'hex'", "else", "DigitWord", ".", "DIGIT", "guess", "=", "DigitWord", "(", "*", "args", ",", "wordtype", "=", "_wordtype", ")", "logging", ".", "debug", "(", "\"Validating guess.\"", ")", "self", ".", "_g", ".", "guesses_remaining", "-=", "1", "self", ".", "_g", ".", "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", ".", "_g", ".", "answer", ".", "compare", "(", "guess", ")", ":", "logging", ".", "debug", "(", "\"Iteration of guesses_allowed. 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", ".", "_g", ".", "answer", ".", "word", ")", ":", "logging", ".", "debug", "(", "\"Game was won.\"", ")", "self", ".", "_g", ".", "status", "=", "\"won\"", "self", ".", "_g", ".", "guesses_remaining", "=", "0", "_return_results", "[", "\"message\"", "]", "=", "\"Well done! You won the game with your \"", "\"answers {}\"", ".", "format", "(", "self", ".", "_get_text_answer", "(", ")", ")", "elif", "self", ".", "_g", ".", "guesses_remaining", "<", "1", ":", "logging", ".", "debug", "(", "\"Game was lost.\"", ")", "self", ".", "_g", ".", "status", "=", "\"lost\"", "_return_results", "[", "\"message\"", "]", "=", "\"Sorry, you lost! The correct answer was \"", "\"{}\"", ".", "format", "(", "self", ".", "_get_text_answer", "(", ")", ")", "_return_results", "[", "\"status\"", "]", "=", "self", ".", "_g", ".", "status", "logging", ".", "debug", "(", "\"Returning results.\"", ")", "return", "_return_results" ]
82a0d8ee127869123d4fad51a8cd1707879e368f
valid
Game._start_again
Simple method to form a start again message and give the answer in readable form.
python_cowbull_game/v1_deprecated/Game.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._get_text_answer() 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._get_text_answer() 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/v1_deprecated/Game.py#L223-L231
[ "def", "_start_again", "(", "self", ",", "message", "=", "None", ")", ":", "logging", ".", "debug", "(", "\"Start again message delivered: {}\"", ".", "format", "(", "message", ")", ")", "the_answer", "=", "self", ".", "_get_text_answer", "(", ")", "return", "\"{0} The correct answer was {1}. Please start a new game.\"", ".", "format", "(", "message", ",", "the_answer", ")" ]
82a0d8ee127869123d4fad51a8cd1707879e368f
valid
Game._validate_game_object
A helper method to provide validation of the game object (_g). If the game object does not exist or if (for any reason) the object is not a GameObject, then an exception will be raised. :param op: A string describing the operation (e.g. guess, save, etc.) taking place :return: Nothing
python_cowbull_game/v1_deprecated/Game.py
def _validate_game_object(self, op="unknown"): """ A helper method to provide validation of the game object (_g). If the game object does not exist or if (for any reason) the object is not a GameObject, then an exception will be raised. :param op: A string describing the operation (e.g. guess, save, etc.) taking place :return: Nothing """ if self._g is None: raise ValueError( "Game must be instantiated properly before using - call new_game() " "or load_game(jsonstr='{...}')" ) if not isinstance(self._g, GameObject): raise TypeError( "Unexpected error during {0}! GameObject (_g) is not a GameObject!".format(op) )
def _validate_game_object(self, op="unknown"): """ A helper method to provide validation of the game object (_g). If the game object does not exist or if (for any reason) the object is not a GameObject, then an exception will be raised. :param op: A string describing the operation (e.g. guess, save, etc.) taking place :return: Nothing """ if self._g is None: raise ValueError( "Game must be instantiated properly before using - call new_game() " "or load_game(jsonstr='{...}')" ) if not isinstance(self._g, GameObject): raise TypeError( "Unexpected error during {0}! GameObject (_g) is not a GameObject!".format(op) )
[ "A", "helper", "method", "to", "provide", "validation", "of", "the", "game", "object", "(", "_g", ")", ".", "If", "the", "game", "object", "does", "not", "exist", "or", "if", "(", "for", "any", "reason", ")", "the", "object", "is", "not", "a", "GameObject", "then", "an", "exception", "will", "be", "raised", "." ]
dsandersAzure/python_cowbull_game
python
https://github.com/dsandersAzure/python_cowbull_game/blob/82a0d8ee127869123d4fad51a8cd1707879e368f/python_cowbull_game/v1_deprecated/Game.py#L236-L253
[ "def", "_validate_game_object", "(", "self", ",", "op", "=", "\"unknown\"", ")", ":", "if", "self", ".", "_g", "is", "None", ":", "raise", "ValueError", "(", "\"Game must be instantiated properly before using - call new_game() \"", "\"or load_game(jsonstr='{...}')\"", ")", "if", "not", "isinstance", "(", "self", ".", "_g", ",", "GameObject", ")", ":", "raise", "TypeError", "(", "\"Unexpected error during {0}! GameObject (_g) is not a GameObject!\"", ".", "format", "(", "op", ")", ")" ]
82a0d8ee127869123d4fad51a8cd1707879e368f
valid
extra_context
Adds useful global items to the context for use in templates. * *request*: the request object * *HOST*: host name of server * *IN_ADMIN*: True if you are in the django admin area
awl/context_processors.py
def extra_context(request): """Adds useful global items to the context for use in templates. * *request*: the request object * *HOST*: host name of server * *IN_ADMIN*: True if you are in the django admin area """ host = os.environ.get('DJANGO_LIVE_TEST_SERVER_ADDRESS', None) \ or request.get_host() d = { 'request':request, 'HOST':host, 'IN_ADMIN':request.path.startswith('/admin/'), } return d
def extra_context(request): """Adds useful global items to the context for use in templates. * *request*: the request object * *HOST*: host name of server * *IN_ADMIN*: True if you are in the django admin area """ host = os.environ.get('DJANGO_LIVE_TEST_SERVER_ADDRESS', None) \ or request.get_host() d = { 'request':request, 'HOST':host, 'IN_ADMIN':request.path.startswith('/admin/'), } return d
[ "Adds", "useful", "global", "items", "to", "the", "context", "for", "use", "in", "templates", "." ]
cltrudeau/django-awl
python
https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/context_processors.py#L4-L19
[ "def", "extra_context", "(", "request", ")", ":", "host", "=", "os", ".", "environ", ".", "get", "(", "'DJANGO_LIVE_TEST_SERVER_ADDRESS'", ",", "None", ")", "or", "request", ".", "get_host", "(", ")", "d", "=", "{", "'request'", ":", "request", ",", "'HOST'", ":", "host", ",", "'IN_ADMIN'", ":", "request", ".", "path", ".", "startswith", "(", "'/admin/'", ")", ",", "}", "return", "d" ]
70d469ef9a161c1170b53aa017cf02d7c15eb90c
valid
fft
Adds options to :func:`scipy.fftpack.rfft`: * *freq* is the frequency the samples were taken at * *timestamps* is the time the samples were taken, to help with filling in missing data if *fill_missing* is true
scisalt/scipy/fft.py
def fft(values, freq=None, timestamps=None, fill_missing=False): """ Adds options to :func:`scipy.fftpack.rfft`: * *freq* is the frequency the samples were taken at * *timestamps* is the time the samples were taken, to help with filling in missing data if *fill_missing* is true """ # ====================================== # Get frequency # ====================================== if freq is None: from .. import qt freq = qt.getDouble(title='Fourier Analysis', text='Frequency samples taken at:', min=0, decimals=2, value=1.0) freq = freq.input if fill_missing: (t_x, x_filled) = fill_missing_timestamps(timestamps, values) else: x_filled = values num_samples = _np.size(x_filled) xfft = _sp.fftpack.rfft(x_filled) factor = freq/num_samples num_fft = _np.size(xfft) f = factor * _np.linspace(1, num_fft, num_fft) xpow = _np.abs(xfft*_np.conj(xfft)) # ====================================== # No DC term # ====================================== xpow = xpow[1:] f = f[1:] return (f, xpow)
def fft(values, freq=None, timestamps=None, fill_missing=False): """ Adds options to :func:`scipy.fftpack.rfft`: * *freq* is the frequency the samples were taken at * *timestamps* is the time the samples were taken, to help with filling in missing data if *fill_missing* is true """ # ====================================== # Get frequency # ====================================== if freq is None: from .. import qt freq = qt.getDouble(title='Fourier Analysis', text='Frequency samples taken at:', min=0, decimals=2, value=1.0) freq = freq.input if fill_missing: (t_x, x_filled) = fill_missing_timestamps(timestamps, values) else: x_filled = values num_samples = _np.size(x_filled) xfft = _sp.fftpack.rfft(x_filled) factor = freq/num_samples num_fft = _np.size(xfft) f = factor * _np.linspace(1, num_fft, num_fft) xpow = _np.abs(xfft*_np.conj(xfft)) # ====================================== # No DC term # ====================================== xpow = xpow[1:] f = f[1:] return (f, xpow)
[ "Adds", "options", "to", ":", "func", ":", "scipy", ".", "fftpack", ".", "rfft", ":" ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/scipy/fft.py#L11-L46
[ "def", "fft", "(", "values", ",", "freq", "=", "None", ",", "timestamps", "=", "None", ",", "fill_missing", "=", "False", ")", ":", "# ======================================", "# Get frequency", "# ======================================", "if", "freq", "is", "None", ":", "from", ".", ".", "import", "qt", "freq", "=", "qt", ".", "getDouble", "(", "title", "=", "'Fourier Analysis'", ",", "text", "=", "'Frequency samples taken at:'", ",", "min", "=", "0", ",", "decimals", "=", "2", ",", "value", "=", "1.0", ")", "freq", "=", "freq", ".", "input", "if", "fill_missing", ":", "(", "t_x", ",", "x_filled", ")", "=", "fill_missing_timestamps", "(", "timestamps", ",", "values", ")", "else", ":", "x_filled", "=", "values", "num_samples", "=", "_np", ".", "size", "(", "x_filled", ")", "xfft", "=", "_sp", ".", "fftpack", ".", "rfft", "(", "x_filled", ")", "factor", "=", "freq", "/", "num_samples", "num_fft", "=", "_np", ".", "size", "(", "xfft", ")", "f", "=", "factor", "*", "_np", ".", "linspace", "(", "1", ",", "num_fft", ",", "num_fft", ")", "xpow", "=", "_np", ".", "abs", "(", "xfft", "*", "_np", ".", "conj", "(", "xfft", ")", ")", "# ======================================", "# No DC term", "# ======================================", "xpow", "=", "xpow", "[", "1", ":", "]", "f", "=", "f", "[", "1", ":", "]", "return", "(", "f", ",", "xpow", ")" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
MapRouletteChallenge.create
Create the challenge on the server
maproulette/challenge.py
def create(self, server): """Create the challenge on the server""" return server.post( 'challenge_admin', self.as_payload(), replacements={'slug': self.slug})
def create(self, server): """Create the challenge on the server""" return server.post( 'challenge_admin', self.as_payload(), replacements={'slug': self.slug})
[ "Create", "the", "challenge", "on", "the", "server" ]
mvexel/maproulette-api-wrapper
python
https://github.com/mvexel/maproulette-api-wrapper/blob/835278111afefed2beecf9716a033529304c548f/maproulette/challenge.py#L59-L65
[ "def", "create", "(", "self", ",", "server", ")", ":", "return", "server", ".", "post", "(", "'challenge_admin'", ",", "self", ".", "as_payload", "(", ")", ",", "replacements", "=", "{", "'slug'", ":", "self", ".", "slug", "}", ")" ]
835278111afefed2beecf9716a033529304c548f
valid
MapRouletteChallenge.update
Update existing challenge on the server
maproulette/challenge.py
def update(self, server): """Update existing challenge on the server""" return server.put( 'challenge_admin', self.as_payload(), replacements={'slug': self.slug})
def update(self, server): """Update existing challenge on the server""" return server.put( 'challenge_admin', self.as_payload(), replacements={'slug': self.slug})
[ "Update", "existing", "challenge", "on", "the", "server" ]
mvexel/maproulette-api-wrapper
python
https://github.com/mvexel/maproulette-api-wrapper/blob/835278111afefed2beecf9716a033529304c548f/maproulette/challenge.py#L67-L73
[ "def", "update", "(", "self", ",", "server", ")", ":", "return", "server", ".", "put", "(", "'challenge_admin'", ",", "self", ".", "as_payload", "(", ")", ",", "replacements", "=", "{", "'slug'", ":", "self", ".", "slug", "}", ")" ]
835278111afefed2beecf9716a033529304c548f
valid
MapRouletteChallenge.exists
Check if a challenge exists on the server
maproulette/challenge.py
def exists(self, server): """Check if a challenge exists on the server""" try: server.get( 'challenge', replacements={'slug': self.slug}) except Exception: return False return True
def exists(self, server): """Check if a challenge exists on the server""" try: server.get( 'challenge', replacements={'slug': self.slug}) except Exception: return False return True
[ "Check", "if", "a", "challenge", "exists", "on", "the", "server" ]
mvexel/maproulette-api-wrapper
python
https://github.com/mvexel/maproulette-api-wrapper/blob/835278111afefed2beecf9716a033529304c548f/maproulette/challenge.py#L81-L90
[ "def", "exists", "(", "self", ",", "server", ")", ":", "try", ":", "server", ".", "get", "(", "'challenge'", ",", "replacements", "=", "{", "'slug'", ":", "self", ".", "slug", "}", ")", "except", "Exception", ":", "return", "False", "return", "True" ]
835278111afefed2beecf9716a033529304c548f
valid
MapRouletteChallenge.from_server
Retrieve a challenge from the MapRoulette server :type server
maproulette/challenge.py
def from_server(cls, server, slug): """Retrieve a challenge from the MapRoulette server :type server """ challenge = server.get( 'challenge', replacements={'slug': slug}) return cls( **challenge)
def from_server(cls, server, slug): """Retrieve a challenge from the MapRoulette server :type server """ challenge = server.get( 'challenge', replacements={'slug': slug}) return cls( **challenge)
[ "Retrieve", "a", "challenge", "from", "the", "MapRoulette", "server", ":", "type", "server" ]
mvexel/maproulette-api-wrapper
python
https://github.com/mvexel/maproulette-api-wrapper/blob/835278111afefed2beecf9716a033529304c548f/maproulette/challenge.py#L100-L109
[ "def", "from_server", "(", "cls", ",", "server", ",", "slug", ")", ":", "challenge", "=", "server", ".", "get", "(", "'challenge'", ",", "replacements", "=", "{", "'slug'", ":", "slug", "}", ")", "return", "cls", "(", "*", "*", "challenge", ")" ]
835278111afefed2beecf9716a033529304c548f
valid
django_logging_dict
Extends :func:`logthing.utils.default_logging_dict` with django specific values.
awl/logtools.py
def django_logging_dict(log_dir, handlers=['file'], filename='debug.log'): """Extends :func:`logthing.utils.default_logging_dict` with django specific values. """ d = default_logging_dict(log_dir, handlers, filename) d['handlers'].update({ 'mail_admins':{ 'level':'ERROR', 'class':'django.utils.log.AdminEmailHandler', } }) d['loggers'].update({ 'django.db.backends': { # stop SQL debug from going to main logger 'handlers': ['file', 'mail_admins'], 'level': 'ERROR', 'propagate': False, }, 'django.request': { 'handlers': ['file', 'mail_admins'], 'level': 'ERROR', 'propagate': False, }, }) return d
def django_logging_dict(log_dir, handlers=['file'], filename='debug.log'): """Extends :func:`logthing.utils.default_logging_dict` with django specific values. """ d = default_logging_dict(log_dir, handlers, filename) d['handlers'].update({ 'mail_admins':{ 'level':'ERROR', 'class':'django.utils.log.AdminEmailHandler', } }) d['loggers'].update({ 'django.db.backends': { # stop SQL debug from going to main logger 'handlers': ['file', 'mail_admins'], 'level': 'ERROR', 'propagate': False, }, 'django.request': { 'handlers': ['file', 'mail_admins'], 'level': 'ERROR', 'propagate': False, }, }) return d
[ "Extends", ":", "func", ":", "logthing", ".", "utils", ".", "default_logging_dict", "with", "django", "specific", "values", "." ]
cltrudeau/django-awl
python
https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/logtools.py#L7-L30
[ "def", "django_logging_dict", "(", "log_dir", ",", "handlers", "=", "[", "'file'", "]", ",", "filename", "=", "'debug.log'", ")", ":", "d", "=", "default_logging_dict", "(", "log_dir", ",", "handlers", ",", "filename", ")", "d", "[", "'handlers'", "]", ".", "update", "(", "{", "'mail_admins'", ":", "{", "'level'", ":", "'ERROR'", ",", "'class'", ":", "'django.utils.log.AdminEmailHandler'", ",", "}", "}", ")", "d", "[", "'loggers'", "]", ".", "update", "(", "{", "'django.db.backends'", ":", "{", "# stop SQL debug from going to main logger", "'handlers'", ":", "[", "'file'", ",", "'mail_admins'", "]", ",", "'level'", ":", "'ERROR'", ",", "'propagate'", ":", "False", ",", "}", ",", "'django.request'", ":", "{", "'handlers'", ":", "[", "'file'", ",", "'mail_admins'", "]", ",", "'level'", ":", "'ERROR'", ",", "'propagate'", ":", "False", ",", "}", ",", "}", ")", "return", "d" ]
70d469ef9a161c1170b53aa017cf02d7c15eb90c
valid
Positions.get_position
Returns position data. http://dev.wheniwork.com/#get-existing-position
uw_wheniwork/positions.py
def get_position(self, position_id): """ Returns position data. http://dev.wheniwork.com/#get-existing-position """ url = "/2/positions/%s" % position_id return self.position_from_json(self._get_resource(url)["position"])
def get_position(self, position_id): """ Returns position data. http://dev.wheniwork.com/#get-existing-position """ url = "/2/positions/%s" % position_id return self.position_from_json(self._get_resource(url)["position"])
[ "Returns", "position", "data", "." ]
uw-it-cte/uw-restclients-wheniwork
python
https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/positions.py#L6-L14
[ "def", "get_position", "(", "self", ",", "position_id", ")", ":", "url", "=", "\"/2/positions/%s\"", "%", "position_id", "return", "self", ".", "position_from_json", "(", "self", ".", "_get_resource", "(", "url", ")", "[", "\"position\"", "]", ")" ]
0d3ca09d5bbe808fec12e5f943596570d33a1731
valid
Positions.get_positions
Returns a list of positions. http://dev.wheniwork.com/#listing-positions
uw_wheniwork/positions.py
def get_positions(self): """ Returns a list of positions. http://dev.wheniwork.com/#listing-positions """ url = "/2/positions" data = self._get_resource(url) positions = [] for entry in data['positions']: positions.append(self.position_from_json(entry)) return positions
def get_positions(self): """ Returns a list of positions. http://dev.wheniwork.com/#listing-positions """ url = "/2/positions" data = self._get_resource(url) positions = [] for entry in data['positions']: positions.append(self.position_from_json(entry)) return positions
[ "Returns", "a", "list", "of", "positions", "." ]
uw-it-cte/uw-restclients-wheniwork
python
https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/positions.py#L16-L29
[ "def", "get_positions", "(", "self", ")", ":", "url", "=", "\"/2/positions\"", "data", "=", "self", ".", "_get_resource", "(", "url", ")", "positions", "=", "[", "]", "for", "entry", "in", "data", "[", "'positions'", "]", ":", "positions", ".", "append", "(", "self", ".", "position_from_json", "(", "entry", ")", ")", "return", "positions" ]
0d3ca09d5bbe808fec12e5f943596570d33a1731
valid
Positions.create_position
Creates a position http://dev.wheniwork.com/#create-update-position
uw_wheniwork/positions.py
def create_position(self, params={}): """ Creates a position http://dev.wheniwork.com/#create-update-position """ url = "/2/positions/" body = params data = self._post_resource(url, body) return self.position_from_json(data["position"])
def create_position(self, params={}): """ Creates a position http://dev.wheniwork.com/#create-update-position """ url = "/2/positions/" body = params data = self._post_resource(url, body) return self.position_from_json(data["position"])
[ "Creates", "a", "position" ]
uw-it-cte/uw-restclients-wheniwork
python
https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/positions.py#L31-L41
[ "def", "create_position", "(", "self", ",", "params", "=", "{", "}", ")", ":", "url", "=", "\"/2/positions/\"", "body", "=", "params", "data", "=", "self", ".", "_post_resource", "(", "url", ",", "body", ")", "return", "self", ".", "position_from_json", "(", "data", "[", "\"position\"", "]", ")" ]
0d3ca09d5bbe808fec12e5f943596570d33a1731
valid
print2elog
Prints to the elog. Parameters ---------- author : str, optional Author of the elog. title : str, optional Title of the elog. link : str, optional Path to a thumbnail. file : str, optional Path to a file. now : :class:`datetime.datetime` Time of the elog.
scisalt/facettools/print2elog.py
def print2elog(author='', title='', text='', link=None, file=None, now=None): """ Prints to the elog. Parameters ---------- author : str, optional Author of the elog. title : str, optional Title of the elog. link : str, optional Path to a thumbnail. file : str, optional Path to a file. now : :class:`datetime.datetime` Time of the elog. """ # ============================ # Get current time # ============================ if now is None: now = _dt.datetime.now() fulltime = now.strftime('%Y-%m-%dT%H:%M:%S-00') # ============================ # Copy files # ============================ if not ((link is None) ^ (file is None)): link_copied = _copy_file(link, fulltime) file_copied = _copy_file(file, fulltime) else: raise ValueError('Need both file and its thumbnail!') # ============================ # Jinja templating # ============================ loader = _jj.PackageLoader('pytools.facettools', 'resources/templates') env = _jj.Environment(loader=loader, trim_blocks=True) template = env.get_template('facetelog.xml') stream = template.stream(author=author, title=title, text=text, link=link_copied, file=file_copied, now=now) # ============================ # Write xml # ============================ with _tempfile.TemporaryDirectory() as dirname: filename = '{}.xml'.format(fulltime) filepath = _os.path.join(dirname, filename) with open(filepath, 'w+') as fid: # stream.disable_buffering() stream.dump(fid) finalpath = _os.path.join(basedir, filename) # _shutil.copyfile(filepath, 'new.xml') _shutil.copyfile(filepath, finalpath)
def print2elog(author='', title='', text='', link=None, file=None, now=None): """ Prints to the elog. Parameters ---------- author : str, optional Author of the elog. title : str, optional Title of the elog. link : str, optional Path to a thumbnail. file : str, optional Path to a file. now : :class:`datetime.datetime` Time of the elog. """ # ============================ # Get current time # ============================ if now is None: now = _dt.datetime.now() fulltime = now.strftime('%Y-%m-%dT%H:%M:%S-00') # ============================ # Copy files # ============================ if not ((link is None) ^ (file is None)): link_copied = _copy_file(link, fulltime) file_copied = _copy_file(file, fulltime) else: raise ValueError('Need both file and its thumbnail!') # ============================ # Jinja templating # ============================ loader = _jj.PackageLoader('pytools.facettools', 'resources/templates') env = _jj.Environment(loader=loader, trim_blocks=True) template = env.get_template('facetelog.xml') stream = template.stream(author=author, title=title, text=text, link=link_copied, file=file_copied, now=now) # ============================ # Write xml # ============================ with _tempfile.TemporaryDirectory() as dirname: filename = '{}.xml'.format(fulltime) filepath = _os.path.join(dirname, filename) with open(filepath, 'w+') as fid: # stream.disable_buffering() stream.dump(fid) finalpath = _os.path.join(basedir, filename) # _shutil.copyfile(filepath, 'new.xml') _shutil.copyfile(filepath, finalpath)
[ "Prints", "to", "the", "elog", ".", "Parameters", "----------" ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/facettools/print2elog.py#L26-L81
[ "def", "print2elog", "(", "author", "=", "''", ",", "title", "=", "''", ",", "text", "=", "''", ",", "link", "=", "None", ",", "file", "=", "None", ",", "now", "=", "None", ")", ":", "# ============================", "# Get current time", "# ============================", "if", "now", "is", "None", ":", "now", "=", "_dt", ".", "datetime", ".", "now", "(", ")", "fulltime", "=", "now", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%S-00'", ")", "# ============================", "# Copy files", "# ============================", "if", "not", "(", "(", "link", "is", "None", ")", "^", "(", "file", "is", "None", ")", ")", ":", "link_copied", "=", "_copy_file", "(", "link", ",", "fulltime", ")", "file_copied", "=", "_copy_file", "(", "file", ",", "fulltime", ")", "else", ":", "raise", "ValueError", "(", "'Need both file and its thumbnail!'", ")", "# ============================", "# Jinja templating", "# ============================", "loader", "=", "_jj", ".", "PackageLoader", "(", "'pytools.facettools'", ",", "'resources/templates'", ")", "env", "=", "_jj", ".", "Environment", "(", "loader", "=", "loader", ",", "trim_blocks", "=", "True", ")", "template", "=", "env", ".", "get_template", "(", "'facetelog.xml'", ")", "stream", "=", "template", ".", "stream", "(", "author", "=", "author", ",", "title", "=", "title", ",", "text", "=", "text", ",", "link", "=", "link_copied", ",", "file", "=", "file_copied", ",", "now", "=", "now", ")", "# ============================", "# Write xml", "# ============================", "with", "_tempfile", ".", "TemporaryDirectory", "(", ")", "as", "dirname", ":", "filename", "=", "'{}.xml'", ".", "format", "(", "fulltime", ")", "filepath", "=", "_os", ".", "path", ".", "join", "(", "dirname", ",", "filename", ")", "with", "open", "(", "filepath", ",", "'w+'", ")", "as", "fid", ":", "# stream.disable_buffering()", "stream", ".", "dump", "(", "fid", ")", "finalpath", "=", "_os", ".", "path", ".", "join", "(", "basedir", ",", "filename", ")", "# _shutil.copyfile(filepath, 'new.xml')", "_shutil", ".", "copyfile", "(", "filepath", ",", "finalpath", ")" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
fopen
Similar to Python's built-in `open()` function.
src/infi/gevent_utils/os/__init__.py
def fopen(name, mode='r', buffering=-1): """Similar to Python's built-in `open()` function.""" f = _fopen(name, mode, buffering) return _FileObjectThreadWithContext(f, mode, buffering)
def fopen(name, mode='r', buffering=-1): """Similar to Python's built-in `open()` function.""" f = _fopen(name, mode, buffering) return _FileObjectThreadWithContext(f, mode, buffering)
[ "Similar", "to", "Python", "s", "built", "-", "in", "open", "()", "function", "." ]
Infinidat/infi.gevent_utils
python
https://github.com/Infinidat/infi.gevent_utils/blob/7eb3c1601b8f2c9aaa3a83154ee7dfce8e5e5a5a/src/infi/gevent_utils/os/__init__.py#L87-L90
[ "def", "fopen", "(", "name", ",", "mode", "=", "'r'", ",", "buffering", "=", "-", "1", ")", ":", "f", "=", "_fopen", "(", "name", ",", "mode", ",", "buffering", ")", "return", "_FileObjectThreadWithContext", "(", "f", ",", "mode", ",", "buffering", ")" ]
7eb3c1601b8f2c9aaa3a83154ee7dfce8e5e5a5a
valid
sloccount
Print "Source Lines of Code" and export to file. Export is hudson_ plugin_ compatible: sloccount.sc requirements: - sloccount_ should be installed. - tee and pipes are used options.paved.pycheck.sloccount.param .. _sloccount: http://www.dwheeler.com/sloccount/ .. _hudson: http://hudson-ci.org/ .. _plugin: http://wiki.hudson-ci.org/display/HUDSON/SLOCCount+Plugin
paved/pycheck.py
def sloccount(): '''Print "Source Lines of Code" and export to file. Export is hudson_ plugin_ compatible: sloccount.sc requirements: - sloccount_ should be installed. - tee and pipes are used options.paved.pycheck.sloccount.param .. _sloccount: http://www.dwheeler.com/sloccount/ .. _hudson: http://hudson-ci.org/ .. _plugin: http://wiki.hudson-ci.org/display/HUDSON/SLOCCount+Plugin ''' # filter out subpackages setup = options.get('setup') packages = options.get('packages') if setup else None if packages: dirs = [x for x in packages if '.' not in x] else: dirs = ['.'] # sloccount has strange behaviour with directories, # can cause exception in hudson sloccount plugin. # Better to call it with file list ls=[] for d in dirs: ls += list(path(d).walkfiles()) #ls=list(set(ls)) files=' '.join(ls) param=options.paved.pycheck.sloccount.param sh('sloccount {param} {files} | tee sloccount.sc'.format(param=param, files=files))
def sloccount(): '''Print "Source Lines of Code" and export to file. Export is hudson_ plugin_ compatible: sloccount.sc requirements: - sloccount_ should be installed. - tee and pipes are used options.paved.pycheck.sloccount.param .. _sloccount: http://www.dwheeler.com/sloccount/ .. _hudson: http://hudson-ci.org/ .. _plugin: http://wiki.hudson-ci.org/display/HUDSON/SLOCCount+Plugin ''' # filter out subpackages setup = options.get('setup') packages = options.get('packages') if setup else None if packages: dirs = [x for x in packages if '.' not in x] else: dirs = ['.'] # sloccount has strange behaviour with directories, # can cause exception in hudson sloccount plugin. # Better to call it with file list ls=[] for d in dirs: ls += list(path(d).walkfiles()) #ls=list(set(ls)) files=' '.join(ls) param=options.paved.pycheck.sloccount.param sh('sloccount {param} {files} | tee sloccount.sc'.format(param=param, files=files))
[ "Print", "Source", "Lines", "of", "Code", "and", "export", "to", "file", "." ]
eykd/paved
python
https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/pycheck.py#L37-L71
[ "def", "sloccount", "(", ")", ":", "# filter out subpackages", "setup", "=", "options", ".", "get", "(", "'setup'", ")", "packages", "=", "options", ".", "get", "(", "'packages'", ")", "if", "setup", "else", "None", "if", "packages", ":", "dirs", "=", "[", "x", "for", "x", "in", "packages", "if", "'.'", "not", "in", "x", "]", "else", ":", "dirs", "=", "[", "'.'", "]", "# sloccount has strange behaviour with directories,", "# can cause exception in hudson sloccount plugin.", "# Better to call it with file list", "ls", "=", "[", "]", "for", "d", "in", "dirs", ":", "ls", "+=", "list", "(", "path", "(", "d", ")", ".", "walkfiles", "(", ")", ")", "#ls=list(set(ls))", "files", "=", "' '", ".", "join", "(", "ls", ")", "param", "=", "options", ".", "paved", ".", "pycheck", ".", "sloccount", ".", "param", "sh", "(", "'sloccount {param} {files} | tee sloccount.sc'", ".", "format", "(", "param", "=", "param", ",", "files", "=", "files", ")", ")" ]
f04f8a4248c571f3d5ce882b325884a3e5d80203
valid
pyflakes
passive check of python programs by pyflakes. requirements: - pyflakes_ should be installed. ``easy_install pyflakes`` options.paved.pycheck.pyflakes.param .. _pyflakes: http://pypi.python.org/pypi/pyflakes
paved/pycheck.py
def pyflakes(): '''passive check of python programs by pyflakes. requirements: - pyflakes_ should be installed. ``easy_install pyflakes`` options.paved.pycheck.pyflakes.param .. _pyflakes: http://pypi.python.org/pypi/pyflakes ''' # filter out subpackages packages = [x for x in options.setup.packages if '.' not in x] sh('pyflakes {param} {files}'.format(param=options.paved.pycheck.pyflakes.param, files=' '.join(packages)))
def pyflakes(): '''passive check of python programs by pyflakes. requirements: - pyflakes_ should be installed. ``easy_install pyflakes`` options.paved.pycheck.pyflakes.param .. _pyflakes: http://pypi.python.org/pypi/pyflakes ''' # filter out subpackages packages = [x for x in options.setup.packages if '.' not in x] sh('pyflakes {param} {files}'.format(param=options.paved.pycheck.pyflakes.param, files=' '.join(packages)))
[ "passive", "check", "of", "python", "programs", "by", "pyflakes", "." ]
eykd/paved
python
https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/pycheck.py#L91-L105
[ "def", "pyflakes", "(", ")", ":", "# filter out subpackages", "packages", "=", "[", "x", "for", "x", "in", "options", ".", "setup", ".", "packages", "if", "'.'", "not", "in", "x", "]", "sh", "(", "'pyflakes {param} {files}'", ".", "format", "(", "param", "=", "options", ".", "paved", ".", "pycheck", ".", "pyflakes", ".", "param", ",", "files", "=", "' '", ".", "join", "(", "packages", ")", ")", ")" ]
f04f8a4248c571f3d5ce882b325884a3e5d80203
valid
gaussian
Gaussian function of the form :math:`\\frac{1}{\\sqrt{2 \\pi}\\sigma} e^{-\\frac{(x-\\mu)^2}{2\\sigma^2}}`. .. versionadded:: 1.5 Parameters ---------- x : float Function variable :math:`x`. mu : float Mean of the Gaussian function. sigma : float Standard deviation of the Gaussian function.
scisalt/numpy/functions.py
def gaussian(x, mu, sigma): """ Gaussian function of the form :math:`\\frac{1}{\\sqrt{2 \\pi}\\sigma} e^{-\\frac{(x-\\mu)^2}{2\\sigma^2}}`. .. versionadded:: 1.5 Parameters ---------- x : float Function variable :math:`x`. mu : float Mean of the Gaussian function. sigma : float Standard deviation of the Gaussian function. """ return _np.exp(-(x-mu)**2/(2*sigma**2)) / (_np.sqrt(2*_np.pi) * sigma)
def gaussian(x, mu, sigma): """ Gaussian function of the form :math:`\\frac{1}{\\sqrt{2 \\pi}\\sigma} e^{-\\frac{(x-\\mu)^2}{2\\sigma^2}}`. .. versionadded:: 1.5 Parameters ---------- x : float Function variable :math:`x`. mu : float Mean of the Gaussian function. sigma : float Standard deviation of the Gaussian function. """ return _np.exp(-(x-mu)**2/(2*sigma**2)) / (_np.sqrt(2*_np.pi) * sigma)
[ "Gaussian", "function", "of", "the", "form", ":", "math", ":", "\\\\", "frac", "{", "1", "}", "{", "\\\\", "sqrt", "{", "2", "\\\\", "pi", "}", "\\\\", "sigma", "}", "e^", "{", "-", "\\\\", "frac", "{", "(", "x", "-", "\\\\", "mu", ")", "^2", "}", "{", "2", "\\\\", "sigma^2", "}}", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/numpy/functions.py#L7-L22
[ "def", "gaussian", "(", "x", ",", "mu", ",", "sigma", ")", ":", "return", "_np", ".", "exp", "(", "-", "(", "x", "-", "mu", ")", "**", "2", "/", "(", "2", "*", "sigma", "**", "2", ")", ")", "/", "(", "_np", ".", "sqrt", "(", "2", "*", "_np", ".", "pi", ")", "*", "sigma", ")" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
http_exception_error_handler
Handle HTTP exception :param werkzeug.exceptions.HTTPException exception: Raised exception A response is returned, as formatted by the :py:func:`response` function.
starling/flask/error_handler/json.py
def http_exception_error_handler( exception): """ Handle HTTP exception :param werkzeug.exceptions.HTTPException exception: Raised exception A response is returned, as formatted by the :py:func:`response` function. """ assert issubclass(type(exception), HTTPException), type(exception) assert hasattr(exception, "code") assert hasattr(exception, "description") return response(exception.code, exception.description)
def http_exception_error_handler( exception): """ Handle HTTP exception :param werkzeug.exceptions.HTTPException exception: Raised exception A response is returned, as formatted by the :py:func:`response` function. """ assert issubclass(type(exception), HTTPException), type(exception) assert hasattr(exception, "code") assert hasattr(exception, "description") return response(exception.code, exception.description)
[ "Handle", "HTTP", "exception" ]
geoneric/starling
python
https://github.com/geoneric/starling/blob/a8e1324c4d6e8b063a0d353bcd03bb8e57edd888/starling/flask/error_handler/json.py#L36-L50
[ "def", "http_exception_error_handler", "(", "exception", ")", ":", "assert", "issubclass", "(", "type", "(", "exception", ")", ",", "HTTPException", ")", ",", "type", "(", "exception", ")", "assert", "hasattr", "(", "exception", ",", "\"code\"", ")", "assert", "hasattr", "(", "exception", ",", "\"description\"", ")", "return", "response", "(", "exception", ".", "code", ",", "exception", ".", "description", ")" ]
a8e1324c4d6e8b063a0d353bcd03bb8e57edd888
valid
is_colour
Returns True if the value given is a valid CSS colour, i.e. matches one of the regular expressions in the module or is in the list of predetefined values by the browser.
awl/css_colours.py
def is_colour(value): """Returns True if the value given is a valid CSS colour, i.e. matches one of the regular expressions in the module or is in the list of predetefined values by the browser. """ global PREDEFINED, HEX_MATCH, RGB_MATCH, RGBA_MATCH, HSL_MATCH, HSLA_MATCH value = value.strip() # hex match if HEX_MATCH.match(value) or RGB_MATCH.match(value) or \ RGBA_MATCH.match(value) or HSL_MATCH.match(value) or \ HSLA_MATCH.match(value) or value in PREDEFINED: return True return False
def is_colour(value): """Returns True if the value given is a valid CSS colour, i.e. matches one of the regular expressions in the module or is in the list of predetefined values by the browser. """ global PREDEFINED, HEX_MATCH, RGB_MATCH, RGBA_MATCH, HSL_MATCH, HSLA_MATCH value = value.strip() # hex match if HEX_MATCH.match(value) or RGB_MATCH.match(value) or \ RGBA_MATCH.match(value) or HSL_MATCH.match(value) or \ HSLA_MATCH.match(value) or value in PREDEFINED: return True return False
[ "Returns", "True", "if", "the", "value", "given", "is", "a", "valid", "CSS", "colour", "i", ".", "e", ".", "matches", "one", "of", "the", "regular", "expressions", "in", "the", "module", "or", "is", "in", "the", "list", "of", "predetefined", "values", "by", "the", "browser", "." ]
cltrudeau/django-awl
python
https://github.com/cltrudeau/django-awl/blob/70d469ef9a161c1170b53aa017cf02d7c15eb90c/awl/css_colours.py#L103-L117
[ "def", "is_colour", "(", "value", ")", ":", "global", "PREDEFINED", ",", "HEX_MATCH", ",", "RGB_MATCH", ",", "RGBA_MATCH", ",", "HSL_MATCH", ",", "HSLA_MATCH", "value", "=", "value", ".", "strip", "(", ")", "# hex match", "if", "HEX_MATCH", ".", "match", "(", "value", ")", "or", "RGB_MATCH", ".", "match", "(", "value", ")", "or", "RGBA_MATCH", ".", "match", "(", "value", ")", "or", "HSL_MATCH", ".", "match", "(", "value", ")", "or", "HSLA_MATCH", ".", "match", "(", "value", ")", "or", "value", "in", "PREDEFINED", ":", "return", "True", "return", "False" ]
70d469ef9a161c1170b53aa017cf02d7c15eb90c
valid
CompactETA.format_time
Formats time as the string "HH:MM:SS".
hibget/widgets.py
def format_time(seconds): """Formats time as the string "HH:MM:SS".""" timedelta = datetime.timedelta(seconds=int(seconds)) mm, ss = divmod(timedelta.seconds, 60) if mm < 60: return "%02d:%02d" % (mm, ss) hh, mm = divmod(mm, 60) if hh < 24: return "%02d:%02d:%02d" % (hh, mm, ss) dd, hh = divmod(mm, 24) return "%d days %02d:%02d:%02d" % (dd, hh, mm, ss)
def format_time(seconds): """Formats time as the string "HH:MM:SS".""" timedelta = datetime.timedelta(seconds=int(seconds)) mm, ss = divmod(timedelta.seconds, 60) if mm < 60: return "%02d:%02d" % (mm, ss) hh, mm = divmod(mm, 60) if hh < 24: return "%02d:%02d:%02d" % (hh, mm, ss) dd, hh = divmod(mm, 24) return "%d days %02d:%02d:%02d" % (dd, hh, mm, ss)
[ "Formats", "time", "as", "the", "string", "HH", ":", "MM", ":", "SS", "." ]
saik0/hibget
python
https://github.com/saik0/hibget/blob/90b42c915bffb2151aa01e3e3d9826dd78ca6a87/hibget/widgets.py#L43-L55
[ "def", "format_time", "(", "seconds", ")", ":", "timedelta", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "int", "(", "seconds", ")", ")", "mm", ",", "ss", "=", "divmod", "(", "timedelta", ".", "seconds", ",", "60", ")", "if", "mm", "<", "60", ":", "return", "\"%02d:%02d\"", "%", "(", "mm", ",", "ss", ")", "hh", ",", "mm", "=", "divmod", "(", "mm", ",", "60", ")", "if", "hh", "<", "24", ":", "return", "\"%02d:%02d:%02d\"", "%", "(", "hh", ",", "mm", ",", "ss", ")", "dd", ",", "hh", "=", "divmod", "(", "mm", ",", "24", ")", "return", "\"%d days %02d:%02d:%02d\"", "%", "(", "dd", ",", "hh", ",", "mm", ",", "ss", ")" ]
90b42c915bffb2151aa01e3e3d9826dd78ca6a87
valid
frictional_resistance_coef
Flat plate frictional resistance of the ship according to ITTC formula. ref: https://ittc.info/media/2021/75-02-02-02.pdf :param length: metres length of the vehicle :param speed: m/s speed of the vehicle :param kwargs: optional could take in temperature to take account change of water property :return: Frictional resistance coefficient of the vehicle
PyResis/propulsion_power.py
def frictional_resistance_coef(length, speed, **kwargs): """ Flat plate frictional resistance of the ship according to ITTC formula. ref: https://ittc.info/media/2021/75-02-02-02.pdf :param length: metres length of the vehicle :param speed: m/s speed of the vehicle :param kwargs: optional could take in temperature to take account change of water property :return: Frictional resistance coefficient of the vehicle """ Cf = 0.075 / (np.log10(reynolds_number(length, speed, **kwargs)) - 2) ** 2 return Cf
def frictional_resistance_coef(length, speed, **kwargs): """ Flat plate frictional resistance of the ship according to ITTC formula. ref: https://ittc.info/media/2021/75-02-02-02.pdf :param length: metres length of the vehicle :param speed: m/s speed of the vehicle :param kwargs: optional could take in temperature to take account change of water property :return: Frictional resistance coefficient of the vehicle """ Cf = 0.075 / (np.log10(reynolds_number(length, speed, **kwargs)) - 2) ** 2 return Cf
[ "Flat", "plate", "frictional", "resistance", "of", "the", "ship", "according", "to", "ITTC", "formula", ".", "ref", ":", "https", ":", "//", "ittc", ".", "info", "/", "media", "/", "2021", "/", "75", "-", "02", "-", "02", "-", "02", ".", "pdf" ]
MaritimeRenewable/PyResis
python
https://github.com/MaritimeRenewable/PyResis/blob/c53f83598c8760d532c44036ea3ecd0c84eada95/PyResis/propulsion_power.py#L13-L24
[ "def", "frictional_resistance_coef", "(", "length", ",", "speed", ",", "*", "*", "kwargs", ")", ":", "Cf", "=", "0.075", "/", "(", "np", ".", "log10", "(", "reynolds_number", "(", "length", ",", "speed", ",", "*", "*", "kwargs", ")", ")", "-", "2", ")", "**", "2", "return", "Cf" ]
c53f83598c8760d532c44036ea3ecd0c84eada95
valid
reynolds_number
Reynold number utility function that return Reynold number for vehicle at specific length and speed. Optionally, it can also take account of temperature effect of sea water. Kinematic viscosity from: http://web.mit.edu/seawater/2017_MIT_Seawater_Property_Tables_r2.pdf :param length: metres length of the vehicle :param speed: m/s speed of the vehicle :param temperature: degree C :return: Reynolds number of the vehicle (dimensionless)
PyResis/propulsion_power.py
def reynolds_number(length, speed, temperature=25): """ Reynold number utility function that return Reynold number for vehicle at specific length and speed. Optionally, it can also take account of temperature effect of sea water. Kinematic viscosity from: http://web.mit.edu/seawater/2017_MIT_Seawater_Property_Tables_r2.pdf :param length: metres length of the vehicle :param speed: m/s speed of the vehicle :param temperature: degree C :return: Reynolds number of the vehicle (dimensionless) """ kinematic_viscosity = interpolate.interp1d([0, 10, 20, 25, 30, 40], np.array([18.54, 13.60, 10.50, 9.37, 8.42, 6.95]) / 10 ** 7) # Data from http://web.mit.edu/seawater/2017_MIT_Seawater_Property_Tables_r2.pdf Re = length * speed / kinematic_viscosity(temperature) return Re
def reynolds_number(length, speed, temperature=25): """ Reynold number utility function that return Reynold number for vehicle at specific length and speed. Optionally, it can also take account of temperature effect of sea water. Kinematic viscosity from: http://web.mit.edu/seawater/2017_MIT_Seawater_Property_Tables_r2.pdf :param length: metres length of the vehicle :param speed: m/s speed of the vehicle :param temperature: degree C :return: Reynolds number of the vehicle (dimensionless) """ kinematic_viscosity = interpolate.interp1d([0, 10, 20, 25, 30, 40], np.array([18.54, 13.60, 10.50, 9.37, 8.42, 6.95]) / 10 ** 7) # Data from http://web.mit.edu/seawater/2017_MIT_Seawater_Property_Tables_r2.pdf Re = length * speed / kinematic_viscosity(temperature) return Re
[ "Reynold", "number", "utility", "function", "that", "return", "Reynold", "number", "for", "vehicle", "at", "specific", "length", "and", "speed", ".", "Optionally", "it", "can", "also", "take", "account", "of", "temperature", "effect", "of", "sea", "water", "." ]
MaritimeRenewable/PyResis
python
https://github.com/MaritimeRenewable/PyResis/blob/c53f83598c8760d532c44036ea3ecd0c84eada95/PyResis/propulsion_power.py#L27-L43
[ "def", "reynolds_number", "(", "length", ",", "speed", ",", "temperature", "=", "25", ")", ":", "kinematic_viscosity", "=", "interpolate", ".", "interp1d", "(", "[", "0", ",", "10", ",", "20", ",", "25", ",", "30", ",", "40", "]", ",", "np", ".", "array", "(", "[", "18.54", ",", "13.60", ",", "10.50", ",", "9.37", ",", "8.42", ",", "6.95", "]", ")", "/", "10", "**", "7", ")", "# Data from http://web.mit.edu/seawater/2017_MIT_Seawater_Property_Tables_r2.pdf", "Re", "=", "length", "*", "speed", "/", "kinematic_viscosity", "(", "temperature", ")", "return", "Re" ]
c53f83598c8760d532c44036ea3ecd0c84eada95
valid
froude_number
Froude number utility function that return Froude number for vehicle at specific length and speed. :param speed: m/s speed of the vehicle :param length: metres length of the vehicle :return: Froude number of the vehicle (dimensionless)
PyResis/propulsion_power.py
def froude_number(speed, length): """ Froude number utility function that return Froude number for vehicle at specific length and speed. :param speed: m/s speed of the vehicle :param length: metres length of the vehicle :return: Froude number of the vehicle (dimensionless) """ g = 9.80665 # conventional standard value m/s^2 Fr = speed / np.sqrt(g * length) return Fr
def froude_number(speed, length): """ Froude number utility function that return Froude number for vehicle at specific length and speed. :param speed: m/s speed of the vehicle :param length: metres length of the vehicle :return: Froude number of the vehicle (dimensionless) """ g = 9.80665 # conventional standard value m/s^2 Fr = speed / np.sqrt(g * length) return Fr
[ "Froude", "number", "utility", "function", "that", "return", "Froude", "number", "for", "vehicle", "at", "specific", "length", "and", "speed", "." ]
MaritimeRenewable/PyResis
python
https://github.com/MaritimeRenewable/PyResis/blob/c53f83598c8760d532c44036ea3ecd0c84eada95/PyResis/propulsion_power.py#L46-L56
[ "def", "froude_number", "(", "speed", ",", "length", ")", ":", "g", "=", "9.80665", "# conventional standard value m/s^2", "Fr", "=", "speed", "/", "np", ".", "sqrt", "(", "g", "*", "length", ")", "return", "Fr" ]
c53f83598c8760d532c44036ea3ecd0c84eada95
valid
residual_resistance_coef
Residual resistance coefficient estimation from slenderness function, prismatic coefficient and Froude number. :param slenderness: Slenderness coefficient dimensionless :math:`L/(∇^{1/3})` where L is length of ship, ∇ is displacement :param prismatic_coef: Prismatic coefficient dimensionless :math:`∇/(L\cdot A_m)` where L is length of ship, ∇ is displacement Am is midsection area of the ship :param froude_number: Froude number of the ship dimensionless :return: Residual resistance of the ship
PyResis/propulsion_power.py
def residual_resistance_coef(slenderness, prismatic_coef, froude_number): """ Residual resistance coefficient estimation from slenderness function, prismatic coefficient and Froude number. :param slenderness: Slenderness coefficient dimensionless :math:`L/(∇^{1/3})` where L is length of ship, ∇ is displacement :param prismatic_coef: Prismatic coefficient dimensionless :math:`∇/(L\cdot A_m)` where L is length of ship, ∇ is displacement Am is midsection area of the ship :param froude_number: Froude number of the ship dimensionless :return: Residual resistance of the ship """ Cr = cr(slenderness, prismatic_coef, froude_number) if math.isnan(Cr): Cr = cr_nearest(slenderness, prismatic_coef, froude_number) # if Froude number is out of interpolation range, nearest extrapolation is used return Cr
def residual_resistance_coef(slenderness, prismatic_coef, froude_number): """ Residual resistance coefficient estimation from slenderness function, prismatic coefficient and Froude number. :param slenderness: Slenderness coefficient dimensionless :math:`L/(∇^{1/3})` where L is length of ship, ∇ is displacement :param prismatic_coef: Prismatic coefficient dimensionless :math:`∇/(L\cdot A_m)` where L is length of ship, ∇ is displacement Am is midsection area of the ship :param froude_number: Froude number of the ship dimensionless :return: Residual resistance of the ship """ Cr = cr(slenderness, prismatic_coef, froude_number) if math.isnan(Cr): Cr = cr_nearest(slenderness, prismatic_coef, froude_number) # if Froude number is out of interpolation range, nearest extrapolation is used return Cr
[ "Residual", "resistance", "coefficient", "estimation", "from", "slenderness", "function", "prismatic", "coefficient", "and", "Froude", "number", "." ]
MaritimeRenewable/PyResis
python
https://github.com/MaritimeRenewable/PyResis/blob/c53f83598c8760d532c44036ea3ecd0c84eada95/PyResis/propulsion_power.py#L60-L74
[ "def", "residual_resistance_coef", "(", "slenderness", ",", "prismatic_coef", ",", "froude_number", ")", ":", "Cr", "=", "cr", "(", "slenderness", ",", "prismatic_coef", ",", "froude_number", ")", "if", "math", ".", "isnan", "(", "Cr", ")", ":", "Cr", "=", "cr_nearest", "(", "slenderness", ",", "prismatic_coef", ",", "froude_number", ")", "# if Froude number is out of interpolation range, nearest extrapolation is used", "return", "Cr" ]
c53f83598c8760d532c44036ea3ecd0c84eada95
valid
Ship.dimension
Assign values for the main dimension of a ship. :param length: metres length of the vehicle :param draught: metres draught of the vehicle :param beam: metres beam of the vehicle :param speed: m/s speed of the vehicle :param slenderness_coefficient: Slenderness coefficient dimensionless :math:`L/(∇^{1/3})` where L is length of ship, ∇ is displacement :param prismatic_coefficient: Prismatic coefficient dimensionless :math:`∇/(L\cdot A_m)` where L is length of ship, ∇ is displacement Am is midsection area of the ship
PyResis/propulsion_power.py
def dimension(self, length, draught, beam, speed, slenderness_coefficient, prismatic_coefficient): """ Assign values for the main dimension of a ship. :param length: metres length of the vehicle :param draught: metres draught of the vehicle :param beam: metres beam of the vehicle :param speed: m/s speed of the vehicle :param slenderness_coefficient: Slenderness coefficient dimensionless :math:`L/(∇^{1/3})` where L is length of ship, ∇ is displacement :param prismatic_coefficient: Prismatic coefficient dimensionless :math:`∇/(L\cdot A_m)` where L is length of ship, ∇ is displacement Am is midsection area of the ship """ self.length = length self.draught = draught self.beam = beam self.speed = speed self.slenderness_coefficient = slenderness_coefficient self.prismatic_coefficient = prismatic_coefficient self.displacement = (self.length / self.slenderness_coefficient) ** 3 self.surface_area = 1.025 * (1.7 * self.length * self.draught + self.displacement / self.draught)
def dimension(self, length, draught, beam, speed, slenderness_coefficient, prismatic_coefficient): """ Assign values for the main dimension of a ship. :param length: metres length of the vehicle :param draught: metres draught of the vehicle :param beam: metres beam of the vehicle :param speed: m/s speed of the vehicle :param slenderness_coefficient: Slenderness coefficient dimensionless :math:`L/(∇^{1/3})` where L is length of ship, ∇ is displacement :param prismatic_coefficient: Prismatic coefficient dimensionless :math:`∇/(L\cdot A_m)` where L is length of ship, ∇ is displacement Am is midsection area of the ship """ self.length = length self.draught = draught self.beam = beam self.speed = speed self.slenderness_coefficient = slenderness_coefficient self.prismatic_coefficient = prismatic_coefficient self.displacement = (self.length / self.slenderness_coefficient) ** 3 self.surface_area = 1.025 * (1.7 * self.length * self.draught + self.displacement / self.draught)
[ "Assign", "values", "for", "the", "main", "dimension", "of", "a", "ship", "." ]
MaritimeRenewable/PyResis
python
https://github.com/MaritimeRenewable/PyResis/blob/c53f83598c8760d532c44036ea3ecd0c84eada95/PyResis/propulsion_power.py#L84-L106
[ "def", "dimension", "(", "self", ",", "length", ",", "draught", ",", "beam", ",", "speed", ",", "slenderness_coefficient", ",", "prismatic_coefficient", ")", ":", "self", ".", "length", "=", "length", "self", ".", "draught", "=", "draught", "self", ".", "beam", "=", "beam", "self", ".", "speed", "=", "speed", "self", ".", "slenderness_coefficient", "=", "slenderness_coefficient", "self", ".", "prismatic_coefficient", "=", "prismatic_coefficient", "self", ".", "displacement", "=", "(", "self", ".", "length", "/", "self", ".", "slenderness_coefficient", ")", "**", "3", "self", ".", "surface_area", "=", "1.025", "*", "(", "1.7", "*", "self", ".", "length", "*", "self", ".", "draught", "+", "self", ".", "displacement", "/", "self", ".", "draught", ")" ]
c53f83598c8760d532c44036ea3ecd0c84eada95
valid
Ship.resistance
Return resistance of the vehicle. :return: newton the resistance of the ship
PyResis/propulsion_power.py
def resistance(self): """ Return resistance of the vehicle. :return: newton the resistance of the ship """ self.total_resistance_coef = frictional_resistance_coef(self.length, self.speed) + \ residual_resistance_coef(self.slenderness_coefficient, self.prismatic_coefficient, froude_number(self.speed, self.length)) RT = 1 / 2 * self.total_resistance_coef * 1025 * self.surface_area * self.speed ** 2 return RT
def resistance(self): """ Return resistance of the vehicle. :return: newton the resistance of the ship """ self.total_resistance_coef = frictional_resistance_coef(self.length, self.speed) + \ residual_resistance_coef(self.slenderness_coefficient, self.prismatic_coefficient, froude_number(self.speed, self.length)) RT = 1 / 2 * self.total_resistance_coef * 1025 * self.surface_area * self.speed ** 2 return RT
[ "Return", "resistance", "of", "the", "vehicle", "." ]
MaritimeRenewable/PyResis
python
https://github.com/MaritimeRenewable/PyResis/blob/c53f83598c8760d532c44036ea3ecd0c84eada95/PyResis/propulsion_power.py#L108-L119
[ "def", "resistance", "(", "self", ")", ":", "self", ".", "total_resistance_coef", "=", "frictional_resistance_coef", "(", "self", ".", "length", ",", "self", ".", "speed", ")", "+", "residual_resistance_coef", "(", "self", ".", "slenderness_coefficient", ",", "self", ".", "prismatic_coefficient", ",", "froude_number", "(", "self", ".", "speed", ",", "self", ".", "length", ")", ")", "RT", "=", "1", "/", "2", "*", "self", ".", "total_resistance_coef", "*", "1025", "*", "self", ".", "surface_area", "*", "self", ".", "speed", "**", "2", "return", "RT" ]
c53f83598c8760d532c44036ea3ecd0c84eada95
valid
Ship.maximum_deck_area
Return the maximum deck area of the ship :param water_plane_coef: optional water plane coefficient :return: Area of the deck
PyResis/propulsion_power.py
def maximum_deck_area(self, water_plane_coef=0.88): """ Return the maximum deck area of the ship :param water_plane_coef: optional water plane coefficient :return: Area of the deck """ AD = self.beam * self.length * water_plane_coef return AD
def maximum_deck_area(self, water_plane_coef=0.88): """ Return the maximum deck area of the ship :param water_plane_coef: optional water plane coefficient :return: Area of the deck """ AD = self.beam * self.length * water_plane_coef return AD
[ "Return", "the", "maximum", "deck", "area", "of", "the", "ship" ]
MaritimeRenewable/PyResis
python
https://github.com/MaritimeRenewable/PyResis/blob/c53f83598c8760d532c44036ea3ecd0c84eada95/PyResis/propulsion_power.py#L121-L129
[ "def", "maximum_deck_area", "(", "self", ",", "water_plane_coef", "=", "0.88", ")", ":", "AD", "=", "self", ".", "beam", "*", "self", ".", "length", "*", "water_plane_coef", "return", "AD" ]
c53f83598c8760d532c44036ea3ecd0c84eada95
valid
Ship.prop_power
Total propulsion power of the ship. :param propulsion_eff: Shaft efficiency of the ship :param sea_margin: Sea margin take account of interaction between ship and the sea, e.g. wave :return: Watts shaft propulsion power of the ship
PyResis/propulsion_power.py
def prop_power(self, propulsion_eff=0.7, sea_margin=0.2): """ Total propulsion power of the ship. :param propulsion_eff: Shaft efficiency of the ship :param sea_margin: Sea margin take account of interaction between ship and the sea, e.g. wave :return: Watts shaft propulsion power of the ship """ PP = (1 + sea_margin) * self.resistance() * self.speed/propulsion_eff return PP
def prop_power(self, propulsion_eff=0.7, sea_margin=0.2): """ Total propulsion power of the ship. :param propulsion_eff: Shaft efficiency of the ship :param sea_margin: Sea margin take account of interaction between ship and the sea, e.g. wave :return: Watts shaft propulsion power of the ship """ PP = (1 + sea_margin) * self.resistance() * self.speed/propulsion_eff return PP
[ "Total", "propulsion", "power", "of", "the", "ship", "." ]
MaritimeRenewable/PyResis
python
https://github.com/MaritimeRenewable/PyResis/blob/c53f83598c8760d532c44036ea3ecd0c84eada95/PyResis/propulsion_power.py#L139-L148
[ "def", "prop_power", "(", "self", ",", "propulsion_eff", "=", "0.7", ",", "sea_margin", "=", "0.2", ")", ":", "PP", "=", "(", "1", "+", "sea_margin", ")", "*", "self", ".", "resistance", "(", ")", "*", "self", ".", "speed", "/", "propulsion_eff", "return", "PP" ]
c53f83598c8760d532c44036ea3ecd0c84eada95
valid
axesfontsize
Change the font size for the title, x and y labels, and x and y tick labels for axis *ax* to *fontsize*.
scisalt/matplotlib/axesfontsize.py
def axesfontsize(ax, fontsize): """ Change the font size for the title, x and y labels, and x and y tick labels for axis *ax* to *fontsize*. """ items = ([ax.title, ax.xaxis.label, ax.yaxis.label] + ax.get_xticklabels() + ax.get_yticklabels()) for item in items: item.set_fontsize(fontsize)
def axesfontsize(ax, fontsize): """ Change the font size for the title, x and y labels, and x and y tick labels for axis *ax* to *fontsize*. """ items = ([ax.title, ax.xaxis.label, ax.yaxis.label] + ax.get_xticklabels() + ax.get_yticklabels()) for item in items: item.set_fontsize(fontsize)
[ "Change", "the", "font", "size", "for", "the", "title", "x", "and", "y", "labels", "and", "x", "and", "y", "tick", "labels", "for", "axis", "*", "ax", "*", "to", "*", "fontsize", "*", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/matplotlib/axesfontsize.py#L1-L7
[ "def", "axesfontsize", "(", "ax", ",", "fontsize", ")", ":", "items", "=", "(", "[", "ax", ".", "title", ",", "ax", ".", "xaxis", ".", "label", ",", "ax", ".", "yaxis", ".", "label", "]", "+", "ax", ".", "get_xticklabels", "(", ")", "+", "ax", ".", "get_yticklabels", "(", ")", ")", "for", "item", "in", "items", ":", "item", ".", "set_fontsize", "(", "fontsize", ")" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
less_labels
Scale the number of tick labels in x and y by *x_fraction* and *y_fraction* respectively.
scisalt/matplotlib/less_labels.py
def less_labels(ax, x_fraction=0.5, y_fraction=0.5): """ Scale the number of tick labels in x and y by *x_fraction* and *y_fraction* respectively. """ nbins = _np.size(ax.get_xticklabels()) ax.locator_params(nbins=_np.floor(nbins*x_fraction), axis='x') nbins = _np.size(ax.get_yticklabels()) ax.locator_params(nbins=_np.floor(nbins*y_fraction), axis='y')
def less_labels(ax, x_fraction=0.5, y_fraction=0.5): """ Scale the number of tick labels in x and y by *x_fraction* and *y_fraction* respectively. """ nbins = _np.size(ax.get_xticklabels()) ax.locator_params(nbins=_np.floor(nbins*x_fraction), axis='x') nbins = _np.size(ax.get_yticklabels()) ax.locator_params(nbins=_np.floor(nbins*y_fraction), axis='y')
[ "Scale", "the", "number", "of", "tick", "labels", "in", "x", "and", "y", "by", "*", "x_fraction", "*", "and", "*", "y_fraction", "*", "respectively", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/matplotlib/less_labels.py#L7-L15
[ "def", "less_labels", "(", "ax", ",", "x_fraction", "=", "0.5", ",", "y_fraction", "=", "0.5", ")", ":", "nbins", "=", "_np", ".", "size", "(", "ax", ".", "get_xticklabels", "(", ")", ")", "ax", ".", "locator_params", "(", "nbins", "=", "_np", ".", "floor", "(", "nbins", "*", "x_fraction", ")", ",", "axis", "=", "'x'", ")", "nbins", "=", "_np", ".", "size", "(", "ax", ".", "get_yticklabels", "(", ")", ")", "ax", ".", "locator_params", "(", "nbins", "=", "_np", ".", "floor", "(", "nbins", "*", "y_fraction", ")", ",", "axis", "=", "'y'", ")" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
API.configure
Configure the api to use given url and token or to get them from the Config.
tmc/api.py
def configure(self, url=None, token=None, test=False): """ Configure the api to use given url and token or to get them from the Config. """ if url is None: url = Config.get_value("url") if token is None: token = Config.get_value("token") self.server_url = url self.auth_header = {"Authorization": "Basic {0}".format(token)} self.configured = True if test: self.test_connection() Config.set("url", url) Config.set("token", token)
def configure(self, url=None, token=None, test=False): """ Configure the api to use given url and token or to get them from the Config. """ if url is None: url = Config.get_value("url") if token is None: token = Config.get_value("token") self.server_url = url self.auth_header = {"Authorization": "Basic {0}".format(token)} self.configured = True if test: self.test_connection() Config.set("url", url) Config.set("token", token)
[ "Configure", "the", "api", "to", "use", "given", "url", "and", "token", "or", "to", "get", "them", "from", "the", "Config", "." ]
minttu/tmc.py
python
https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/api.py#L38-L57
[ "def", "configure", "(", "self", ",", "url", "=", "None", ",", "token", "=", "None", ",", "test", "=", "False", ")", ":", "if", "url", "is", "None", ":", "url", "=", "Config", ".", "get_value", "(", "\"url\"", ")", "if", "token", "is", "None", ":", "token", "=", "Config", ".", "get_value", "(", "\"token\"", ")", "self", ".", "server_url", "=", "url", "self", ".", "auth_header", "=", "{", "\"Authorization\"", ":", "\"Basic {0}\"", ".", "format", "(", "token", ")", "}", "self", ".", "configured", "=", "True", "if", "test", ":", "self", ".", "test_connection", "(", ")", "Config", ".", "set", "(", "\"url\"", ",", "url", ")", "Config", ".", "set", "(", "\"token\"", ",", "token", ")" ]
212cfe1791a4aab4783f99b665cc32da6437f419
valid
API.send_zip
Send zipfile to TMC for given exercise
tmc/api.py
def send_zip(self, exercise, file, params): """ Send zipfile to TMC for given exercise """ resp = self.post( exercise.return_url, params=params, files={ "submission[file]": ('submission.zip', file) }, data={ "commit": "Submit" } ) return self._to_json(resp)
def send_zip(self, exercise, file, params): """ Send zipfile to TMC for given exercise """ resp = self.post( exercise.return_url, params=params, files={ "submission[file]": ('submission.zip', file) }, data={ "commit": "Submit" } ) return self._to_json(resp)
[ "Send", "zipfile", "to", "TMC", "for", "given", "exercise" ]
minttu/tmc.py
python
https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/api.py#L83-L98
[ "def", "send_zip", "(", "self", ",", "exercise", ",", "file", ",", "params", ")", ":", "resp", "=", "self", ".", "post", "(", "exercise", ".", "return_url", ",", "params", "=", "params", ",", "files", "=", "{", "\"submission[file]\"", ":", "(", "'submission.zip'", ",", "file", ")", "}", ",", "data", "=", "{", "\"commit\"", ":", "\"Submit\"", "}", ")", "return", "self", ".", "_to_json", "(", "resp", ")" ]
212cfe1791a4aab4783f99b665cc32da6437f419
valid
API._make_url
Ensures that the request url is valid. Sometimes we have URLs that the server gives that are preformatted, sometimes we need to form our own.
tmc/api.py
def _make_url(self, slug): """ Ensures that the request url is valid. Sometimes we have URLs that the server gives that are preformatted, sometimes we need to form our own. """ if slug.startswith("http"): return slug return "{0}{1}".format(self.server_url, slug)
def _make_url(self, slug): """ Ensures that the request url is valid. Sometimes we have URLs that the server gives that are preformatted, sometimes we need to form our own. """ if slug.startswith("http"): return slug return "{0}{1}".format(self.server_url, slug)
[ "Ensures", "that", "the", "request", "url", "is", "valid", ".", "Sometimes", "we", "have", "URLs", "that", "the", "server", "gives", "that", "are", "preformatted", "sometimes", "we", "need", "to", "form", "our", "own", "." ]
minttu/tmc.py
python
https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/api.py#L106-L114
[ "def", "_make_url", "(", "self", ",", "slug", ")", ":", "if", "slug", ".", "startswith", "(", "\"http\"", ")", ":", "return", "slug", "return", "\"{0}{1}\"", ".", "format", "(", "self", ".", "server_url", ",", "slug", ")" ]
212cfe1791a4aab4783f99b665cc32da6437f419
valid
API._do_request
Does HTTP request sending / response validation. Prevents RequestExceptions from propagating
tmc/api.py
def _do_request(self, method, slug, **kwargs): """ Does HTTP request sending / response validation. Prevents RequestExceptions from propagating """ # ensure we are configured if not self.configured: self.configure() url = self._make_url(slug) # 'defaults' are values associated with every request. # following will make values in kwargs override them. defaults = {"headers": self.auth_header, "params": self.params} for item in defaults.keys(): # override default's value with kwargs's one if existing. kwargs[item] = dict(defaults[item], **(kwargs.get(item, {}))) # request() can raise connectivity related exceptions. # raise_for_status raises an exception ONLY if the response # status_code is "not-OK" i.e 4XX, 5XX.. # # All of these inherit from RequestException # which is "translated" into an APIError. try: resp = request(method, url, **kwargs) resp.raise_for_status() except RequestException as e: reason = "HTTP {0} request to {1} failed: {2}" raise APIError(reason.format(method, url, repr(e))) return resp
def _do_request(self, method, slug, **kwargs): """ Does HTTP request sending / response validation. Prevents RequestExceptions from propagating """ # ensure we are configured if not self.configured: self.configure() url = self._make_url(slug) # 'defaults' are values associated with every request. # following will make values in kwargs override them. defaults = {"headers": self.auth_header, "params": self.params} for item in defaults.keys(): # override default's value with kwargs's one if existing. kwargs[item] = dict(defaults[item], **(kwargs.get(item, {}))) # request() can raise connectivity related exceptions. # raise_for_status raises an exception ONLY if the response # status_code is "not-OK" i.e 4XX, 5XX.. # # All of these inherit from RequestException # which is "translated" into an APIError. try: resp = request(method, url, **kwargs) resp.raise_for_status() except RequestException as e: reason = "HTTP {0} request to {1} failed: {2}" raise APIError(reason.format(method, url, repr(e))) return resp
[ "Does", "HTTP", "request", "sending", "/", "response", "validation", ".", "Prevents", "RequestExceptions", "from", "propagating" ]
minttu/tmc.py
python
https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/api.py#L116-L146
[ "def", "_do_request", "(", "self", ",", "method", ",", "slug", ",", "*", "*", "kwargs", ")", ":", "# ensure we are configured", "if", "not", "self", ".", "configured", ":", "self", ".", "configure", "(", ")", "url", "=", "self", ".", "_make_url", "(", "slug", ")", "# 'defaults' are values associated with every request.", "# following will make values in kwargs override them.", "defaults", "=", "{", "\"headers\"", ":", "self", ".", "auth_header", ",", "\"params\"", ":", "self", ".", "params", "}", "for", "item", "in", "defaults", ".", "keys", "(", ")", ":", "# override default's value with kwargs's one if existing.", "kwargs", "[", "item", "]", "=", "dict", "(", "defaults", "[", "item", "]", ",", "*", "*", "(", "kwargs", ".", "get", "(", "item", ",", "{", "}", ")", ")", ")", "# request() can raise connectivity related exceptions.", "# raise_for_status raises an exception ONLY if the response", "# status_code is \"not-OK\" i.e 4XX, 5XX..", "#", "# All of these inherit from RequestException", "# which is \"translated\" into an APIError.", "try", ":", "resp", "=", "request", "(", "method", ",", "url", ",", "*", "*", "kwargs", ")", "resp", ".", "raise_for_status", "(", ")", "except", "RequestException", "as", "e", ":", "reason", "=", "\"HTTP {0} request to {1} failed: {2}\"", "raise", "APIError", "(", "reason", ".", "format", "(", "method", ",", "url", ",", "repr", "(", "e", ")", ")", ")", "return", "resp" ]
212cfe1791a4aab4783f99b665cc32da6437f419
valid
API._to_json
Extract json from a response. Assumes response is valid otherwise. Internal use only.
tmc/api.py
def _to_json(self, resp): """ Extract json from a response. Assumes response is valid otherwise. Internal use only. """ try: json = resp.json() except ValueError as e: reason = "TMC Server did not send valid JSON: {0}" raise APIError(reason.format(repr(e))) return json
def _to_json(self, resp): """ Extract json from a response. Assumes response is valid otherwise. Internal use only. """ try: json = resp.json() except ValueError as e: reason = "TMC Server did not send valid JSON: {0}" raise APIError(reason.format(repr(e))) return json
[ "Extract", "json", "from", "a", "response", ".", "Assumes", "response", "is", "valid", "otherwise", ".", "Internal", "use", "only", "." ]
minttu/tmc.py
python
https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/api.py#L148-L160
[ "def", "_to_json", "(", "self", ",", "resp", ")", ":", "try", ":", "json", "=", "resp", ".", "json", "(", ")", "except", "ValueError", "as", "e", ":", "reason", "=", "\"TMC Server did not send valid JSON: {0}\"", "raise", "APIError", "(", "reason", ".", "format", "(", "repr", "(", "e", ")", ")", ")", "return", "json" ]
212cfe1791a4aab4783f99b665cc32da6437f419
valid
_normalize_instancemethod
wraps(instancemethod) returns a function, not an instancemethod so its repr() is all messed up; we want the original repr to show up in the logs, therefore we do this trick
src/infi/gevent_utils/safe_greenlets.py
def _normalize_instancemethod(instance_method): """ wraps(instancemethod) returns a function, not an instancemethod so its repr() is all messed up; we want the original repr to show up in the logs, therefore we do this trick """ if not hasattr(instance_method, 'im_self'): return instance_method def _func(*args, **kwargs): return instance_method(*args, **kwargs) _func.__name__ = repr(instance_method) return _func
def _normalize_instancemethod(instance_method): """ wraps(instancemethod) returns a function, not an instancemethod so its repr() is all messed up; we want the original repr to show up in the logs, therefore we do this trick """ if not hasattr(instance_method, 'im_self'): return instance_method def _func(*args, **kwargs): return instance_method(*args, **kwargs) _func.__name__ = repr(instance_method) return _func
[ "wraps", "(", "instancemethod", ")", "returns", "a", "function", "not", "an", "instancemethod", "so", "its", "repr", "()", "is", "all", "messed", "up", ";", "we", "want", "the", "original", "repr", "to", "show", "up", "in", "the", "logs", "therefore", "we", "do", "this", "trick" ]
Infinidat/infi.gevent_utils
python
https://github.com/Infinidat/infi.gevent_utils/blob/7eb3c1601b8f2c9aaa3a83154ee7dfce8e5e5a5a/src/infi/gevent_utils/safe_greenlets.py#L53-L65
[ "def", "_normalize_instancemethod", "(", "instance_method", ")", ":", "if", "not", "hasattr", "(", "instance_method", ",", "'im_self'", ")", ":", "return", "instance_method", "def", "_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "instance_method", "(", "*", "args", ",", "*", "*", "kwargs", ")", "_func", ".", "__name__", "=", "repr", "(", "instance_method", ")", "return", "_func" ]
7eb3c1601b8f2c9aaa3a83154ee7dfce8e5e5a5a
valid
safe_joinall
Wrapper for gevent.joinall if the greenlet that waits for the joins is killed, it kills all the greenlets it joins for.
src/infi/gevent_utils/safe_greenlets.py
def safe_joinall(greenlets, timeout=None, raise_error=False): """ Wrapper for gevent.joinall if the greenlet that waits for the joins is killed, it kills all the greenlets it joins for. """ greenlets = list(greenlets) try: gevent.joinall(greenlets, timeout=timeout, raise_error=raise_error) except gevent.GreenletExit: [greenlet.kill() for greenlet in greenlets if not greenlet.ready()] raise return greenlets
def safe_joinall(greenlets, timeout=None, raise_error=False): """ Wrapper for gevent.joinall if the greenlet that waits for the joins is killed, it kills all the greenlets it joins for. """ greenlets = list(greenlets) try: gevent.joinall(greenlets, timeout=timeout, raise_error=raise_error) except gevent.GreenletExit: [greenlet.kill() for greenlet in greenlets if not greenlet.ready()] raise return greenlets
[ "Wrapper", "for", "gevent", ".", "joinall", "if", "the", "greenlet", "that", "waits", "for", "the", "joins", "is", "killed", "it", "kills", "all", "the", "greenlets", "it", "joins", "for", "." ]
Infinidat/infi.gevent_utils
python
https://github.com/Infinidat/infi.gevent_utils/blob/7eb3c1601b8f2c9aaa3a83154ee7dfce8e5e5a5a/src/infi/gevent_utils/safe_greenlets.py#L111-L122
[ "def", "safe_joinall", "(", "greenlets", ",", "timeout", "=", "None", ",", "raise_error", "=", "False", ")", ":", "greenlets", "=", "list", "(", "greenlets", ")", "try", ":", "gevent", ".", "joinall", "(", "greenlets", ",", "timeout", "=", "timeout", ",", "raise_error", "=", "raise_error", ")", "except", "gevent", ".", "GreenletExit", ":", "[", "greenlet", ".", "kill", "(", ")", "for", "greenlet", "in", "greenlets", "if", "not", "greenlet", ".", "ready", "(", ")", "]", "raise", "return", "greenlets" ]
7eb3c1601b8f2c9aaa3a83154ee7dfce8e5e5a5a
valid
imshow_batch
Plots an array of *images* to a single window of size *figsize* with *rows* and *columns*. * *cmap*: Specifies color map * *cbar*: Add color bars * *show*: If false, dismisses each window after it is created and optionally saved * *pdf*: Save to a pdf of filename *pdf* * *\*\*kwargs* passed to :class:`matplotlib.axis.imshow`
scisalt/matplotlib/imshow_batch.py
def imshow_batch(images, cbar=True, show=True, pdf=None, figsize=(16, 12), rows=2, columns=2, cmap=None, **kwargs): """ Plots an array of *images* to a single window of size *figsize* with *rows* and *columns*. * *cmap*: Specifies color map * *cbar*: Add color bars * *show*: If false, dismisses each window after it is created and optionally saved * *pdf*: Save to a pdf of filename *pdf* * *\*\*kwargs* passed to :class:`matplotlib.axis.imshow` """ # ====================================== # Set up grid # ====================================== images = _np.array(images) gs = _gridspec.GridSpec(rows, columns) num_imgs = images.shape[0] max_ind = num_imgs-1 # ====================================== # Split into pages # ====================================== per_page = rows*columns num_pages = _np.int(_np.ceil(num_imgs/per_page)) fig_array = _np.empty(shape=num_pages, dtype=object) if num_pages > 1: logger.info('Multiple pages necessary') if pdf is not None: f = _PdfPages(pdf) for p in range(num_pages): # ====================================== # Make figure # ====================================== fig_array[p] = _plt.figure(figsize=figsize) # ====================================== # Get number of rows on page # ====================================== pg_max_ind = _np.min( [(p+1) * per_page - 1, max_ind] ) num_rows = _np.int(_np.ceil((pg_max_ind+1 - p * per_page) / columns)) for i in range(num_rows): # ====================================== # Get images for column # ====================================== i_min_ind = p * per_page + i * columns col_max_ind = _np.min([i_min_ind + columns - 1, max_ind]) for j, image in enumerate(images[i_min_ind:col_max_ind+1]): ax = fig_array[p].add_subplot(gs[i, j]) try: if _np.issubdtype(image.dtype, _np.integer): image = _np.array(image, dtype=float) except: pass plot = ax.imshow(image, **kwargs) if cmap is not None: plot.set_cmap(cmap) if cbar: fig_array[p].colorbar(plot) fig_array[p].tight_layout() if pdf is not None: f.savefig(fig_array[p]) if not show: _plt.close(fig_array[p]) if pdf is not None: f.close() return fig_array
def imshow_batch(images, cbar=True, show=True, pdf=None, figsize=(16, 12), rows=2, columns=2, cmap=None, **kwargs): """ Plots an array of *images* to a single window of size *figsize* with *rows* and *columns*. * *cmap*: Specifies color map * *cbar*: Add color bars * *show*: If false, dismisses each window after it is created and optionally saved * *pdf*: Save to a pdf of filename *pdf* * *\*\*kwargs* passed to :class:`matplotlib.axis.imshow` """ # ====================================== # Set up grid # ====================================== images = _np.array(images) gs = _gridspec.GridSpec(rows, columns) num_imgs = images.shape[0] max_ind = num_imgs-1 # ====================================== # Split into pages # ====================================== per_page = rows*columns num_pages = _np.int(_np.ceil(num_imgs/per_page)) fig_array = _np.empty(shape=num_pages, dtype=object) if num_pages > 1: logger.info('Multiple pages necessary') if pdf is not None: f = _PdfPages(pdf) for p in range(num_pages): # ====================================== # Make figure # ====================================== fig_array[p] = _plt.figure(figsize=figsize) # ====================================== # Get number of rows on page # ====================================== pg_max_ind = _np.min( [(p+1) * per_page - 1, max_ind] ) num_rows = _np.int(_np.ceil((pg_max_ind+1 - p * per_page) / columns)) for i in range(num_rows): # ====================================== # Get images for column # ====================================== i_min_ind = p * per_page + i * columns col_max_ind = _np.min([i_min_ind + columns - 1, max_ind]) for j, image in enumerate(images[i_min_ind:col_max_ind+1]): ax = fig_array[p].add_subplot(gs[i, j]) try: if _np.issubdtype(image.dtype, _np.integer): image = _np.array(image, dtype=float) except: pass plot = ax.imshow(image, **kwargs) if cmap is not None: plot.set_cmap(cmap) if cbar: fig_array[p].colorbar(plot) fig_array[p].tight_layout() if pdf is not None: f.savefig(fig_array[p]) if not show: _plt.close(fig_array[p]) if pdf is not None: f.close() return fig_array
[ "Plots", "an", "array", "of", "*", "images", "*", "to", "a", "single", "window", "of", "size", "*", "figsize", "*", "with", "*", "rows", "*", "and", "*", "columns", "*", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/matplotlib/imshow_batch.py#L15-L92
[ "def", "imshow_batch", "(", "images", ",", "cbar", "=", "True", ",", "show", "=", "True", ",", "pdf", "=", "None", ",", "figsize", "=", "(", "16", ",", "12", ")", ",", "rows", "=", "2", ",", "columns", "=", "2", ",", "cmap", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# ======================================", "# Set up grid", "# ======================================", "images", "=", "_np", ".", "array", "(", "images", ")", "gs", "=", "_gridspec", ".", "GridSpec", "(", "rows", ",", "columns", ")", "num_imgs", "=", "images", ".", "shape", "[", "0", "]", "max_ind", "=", "num_imgs", "-", "1", "# ======================================", "# Split into pages", "# ======================================", "per_page", "=", "rows", "*", "columns", "num_pages", "=", "_np", ".", "int", "(", "_np", ".", "ceil", "(", "num_imgs", "/", "per_page", ")", ")", "fig_array", "=", "_np", ".", "empty", "(", "shape", "=", "num_pages", ",", "dtype", "=", "object", ")", "if", "num_pages", ">", "1", ":", "logger", ".", "info", "(", "'Multiple pages necessary'", ")", "if", "pdf", "is", "not", "None", ":", "f", "=", "_PdfPages", "(", "pdf", ")", "for", "p", "in", "range", "(", "num_pages", ")", ":", "# ======================================", "# Make figure", "# ======================================", "fig_array", "[", "p", "]", "=", "_plt", ".", "figure", "(", "figsize", "=", "figsize", ")", "# ======================================", "# Get number of rows on page", "# ======================================", "pg_max_ind", "=", "_np", ".", "min", "(", "[", "(", "p", "+", "1", ")", "*", "per_page", "-", "1", ",", "max_ind", "]", ")", "num_rows", "=", "_np", ".", "int", "(", "_np", ".", "ceil", "(", "(", "pg_max_ind", "+", "1", "-", "p", "*", "per_page", ")", "/", "columns", ")", ")", "for", "i", "in", "range", "(", "num_rows", ")", ":", "# ======================================", "# Get images for column", "# ======================================", "i_min_ind", "=", "p", "*", "per_page", "+", "i", "*", "columns", "col_max_ind", "=", "_np", ".", "min", "(", "[", "i_min_ind", "+", "columns", "-", "1", ",", "max_ind", "]", ")", "for", "j", ",", "image", "in", "enumerate", "(", "images", "[", "i_min_ind", ":", "col_max_ind", "+", "1", "]", ")", ":", "ax", "=", "fig_array", "[", "p", "]", ".", "add_subplot", "(", "gs", "[", "i", ",", "j", "]", ")", "try", ":", "if", "_np", ".", "issubdtype", "(", "image", ".", "dtype", ",", "_np", ".", "integer", ")", ":", "image", "=", "_np", ".", "array", "(", "image", ",", "dtype", "=", "float", ")", "except", ":", "pass", "plot", "=", "ax", ".", "imshow", "(", "image", ",", "*", "*", "kwargs", ")", "if", "cmap", "is", "not", "None", ":", "plot", ".", "set_cmap", "(", "cmap", ")", "if", "cbar", ":", "fig_array", "[", "p", "]", ".", "colorbar", "(", "plot", ")", "fig_array", "[", "p", "]", ".", "tight_layout", "(", ")", "if", "pdf", "is", "not", "None", ":", "f", ".", "savefig", "(", "fig_array", "[", "p", "]", ")", "if", "not", "show", ":", "_plt", ".", "close", "(", "fig_array", "[", "p", "]", ")", "if", "pdf", "is", "not", "None", ":", "f", ".", "close", "(", ")", "return", "fig_array" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
error
Creates an error from the given code, and args and kwargs. :param code: The acknowledgement code :param args: Exception args :param kwargs: Exception kwargs :return: the error for the given acknowledgement code
hedgehog/protocol/errors.py
def error(code: int, *args, **kwargs) -> HedgehogCommandError: """ Creates an error from the given code, and args and kwargs. :param code: The acknowledgement code :param args: Exception args :param kwargs: Exception kwargs :return: the error for the given acknowledgement code """ # TODO add proper error code if code == FAILED_COMMAND and len(args) >= 1 and args[0] == "Emergency Shutdown activated": return EmergencyShutdown(*args, **kwargs) return _errors[code](*args, **kwargs)
def error(code: int, *args, **kwargs) -> HedgehogCommandError: """ Creates an error from the given code, and args and kwargs. :param code: The acknowledgement code :param args: Exception args :param kwargs: Exception kwargs :return: the error for the given acknowledgement code """ # TODO add proper error code if code == FAILED_COMMAND and len(args) >= 1 and args[0] == "Emergency Shutdown activated": return EmergencyShutdown(*args, **kwargs) return _errors[code](*args, **kwargs)
[ "Creates", "an", "error", "from", "the", "given", "code", "and", "args", "and", "kwargs", "." ]
PRIArobotics/HedgehogProtocol
python
https://github.com/PRIArobotics/HedgehogProtocol/blob/140df1ade46fbfee7eea7a6c0b35cbc7ffbf89fe/hedgehog/protocol/errors.py#L62-L74
[ "def", "error", "(", "code", ":", "int", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "HedgehogCommandError", ":", "# TODO add proper error code", "if", "code", "==", "FAILED_COMMAND", "and", "len", "(", "args", ")", ">=", "1", "and", "args", "[", "0", "]", "==", "\"Emergency Shutdown activated\"", ":", "return", "EmergencyShutdown", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "_errors", "[", "code", "]", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
140df1ade46fbfee7eea7a6c0b35cbc7ffbf89fe
valid
HedgehogCommandError.to_message
Creates an error Acknowledgement message. The message's code and message are taken from this exception. :return: the message representing this exception
hedgehog/protocol/errors.py
def to_message(self): """ Creates an error Acknowledgement message. The message's code and message are taken from this exception. :return: the message representing this exception """ from .messages import ack return ack.Acknowledgement(self.code, self.args[0] if len(self.args) > 0 else '')
def to_message(self): """ Creates an error Acknowledgement message. The message's code and message are taken from this exception. :return: the message representing this exception """ from .messages import ack return ack.Acknowledgement(self.code, self.args[0] if len(self.args) > 0 else '')
[ "Creates", "an", "error", "Acknowledgement", "message", ".", "The", "message", "s", "code", "and", "message", "are", "taken", "from", "this", "exception", "." ]
PRIArobotics/HedgehogProtocol
python
https://github.com/PRIArobotics/HedgehogProtocol/blob/140df1ade46fbfee7eea7a6c0b35cbc7ffbf89fe/hedgehog/protocol/errors.py#L23-L31
[ "def", "to_message", "(", "self", ")", ":", "from", ".", "messages", "import", "ack", "return", "ack", ".", "Acknowledgement", "(", "self", ".", "code", ",", "self", ".", "args", "[", "0", "]", "if", "len", "(", "self", ".", "args", ")", ">", "0", "else", "''", ")" ]
140df1ade46fbfee7eea7a6c0b35cbc7ffbf89fe
valid
clean
Clean up extra files littering the source tree. options.paved.clean.dirs: directories to search recursively options.paved.clean.patterns: patterns to search for and remove
paved/paved.py
def clean(options, info): """Clean up extra files littering the source tree. options.paved.clean.dirs: directories to search recursively options.paved.clean.patterns: patterns to search for and remove """ info("Cleaning patterns %s", options.paved.clean.patterns) for wd in options.paved.clean.dirs: info("Cleaning in %s", wd) for p in options.paved.clean.patterns: for f in wd.walkfiles(p): f.remove()
def clean(options, info): """Clean up extra files littering the source tree. options.paved.clean.dirs: directories to search recursively options.paved.clean.patterns: patterns to search for and remove """ info("Cleaning patterns %s", options.paved.clean.patterns) for wd in options.paved.clean.dirs: info("Cleaning in %s", wd) for p in options.paved.clean.patterns: for f in wd.walkfiles(p): f.remove()
[ "Clean", "up", "extra", "files", "littering", "the", "source", "tree", "." ]
eykd/paved
python
https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/paved.py#L28-L39
[ "def", "clean", "(", "options", ",", "info", ")", ":", "info", "(", "\"Cleaning patterns %s\"", ",", "options", ".", "paved", ".", "clean", ".", "patterns", ")", "for", "wd", "in", "options", ".", "paved", ".", "clean", ".", "dirs", ":", "info", "(", "\"Cleaning in %s\"", ",", "wd", ")", "for", "p", "in", "options", ".", "paved", ".", "clean", ".", "patterns", ":", "for", "f", "in", "wd", ".", "walkfiles", "(", "p", ")", ":", "f", ".", "remove", "(", ")" ]
f04f8a4248c571f3d5ce882b325884a3e5d80203
valid
printoptions
print paver options. Prettified by json. `long_description` is removed
paved/paved.py
def printoptions(): '''print paver options. Prettified by json. `long_description` is removed ''' x = json.dumps(environment.options, indent=4, sort_keys=True, skipkeys=True, cls=MyEncoder) print(x)
def printoptions(): '''print paver options. Prettified by json. `long_description` is removed ''' x = json.dumps(environment.options, indent=4, sort_keys=True, skipkeys=True, cls=MyEncoder) print(x)
[ "print", "paver", "options", "." ]
eykd/paved
python
https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/paved.py#L56-L67
[ "def", "printoptions", "(", ")", ":", "x", "=", "json", ".", "dumps", "(", "environment", ".", "options", ",", "indent", "=", "4", ",", "sort_keys", "=", "True", ",", "skipkeys", "=", "True", ",", "cls", "=", "MyEncoder", ")", "print", "(", "x", ")" ]
f04f8a4248c571f3d5ce882b325884a3e5d80203
valid
CommSide.parse
\ Parses a binary protobuf message into a Message object.
hedgehog/protocol/__init__.py
def parse(self, data: RawMessage) -> Message: """\ Parses a binary protobuf message into a Message object. """ try: return self.receiver.parse(data) except KeyError as err: raise UnknownCommandError from err except DecodeError as err: raise UnknownCommandError(f"{err}") from err
def parse(self, data: RawMessage) -> Message: """\ Parses a binary protobuf message into a Message object. """ try: return self.receiver.parse(data) except KeyError as err: raise UnknownCommandError from err except DecodeError as err: raise UnknownCommandError(f"{err}") from err
[ "\\", "Parses", "a", "binary", "protobuf", "message", "into", "a", "Message", "object", "." ]
PRIArobotics/HedgehogProtocol
python
https://github.com/PRIArobotics/HedgehogProtocol/blob/140df1ade46fbfee7eea7a6c0b35cbc7ffbf89fe/hedgehog/protocol/__init__.py#L44-L53
[ "def", "parse", "(", "self", ",", "data", ":", "RawMessage", ")", "->", "Message", ":", "try", ":", "return", "self", ".", "receiver", ".", "parse", "(", "data", ")", "except", "KeyError", "as", "err", ":", "raise", "UnknownCommandError", "from", "err", "except", "DecodeError", "as", "err", ":", "raise", "UnknownCommandError", "(", "f\"{err}\"", ")", "from", "err" ]
140df1ade46fbfee7eea7a6c0b35cbc7ffbf89fe
valid
setup_axes
Sets up a figure of size *figsize* with a number of rows (*rows*) and columns (*cols*). \*\*kwargs passed through to :meth:`matplotlib.figure.Figure.add_subplot`. .. versionadded:: 1.2 Parameters ---------- rows : int Number of rows to create. cols : int Number of columns to create. figsize : tuple Size of figure to create. expand : bool Make the entire figure with size `figsize`. Returns ------- fig : :class:`matplotlib.figure.Figure` The figure. axes : :class:`numpy.ndarray` An array of all of the axes. (Unless there's only one axis, in which case it returns an object instance :class:`matplotlib.axis.Axis`.)
scisalt/matplotlib/setup_axes.py
def setup_axes(rows=1, cols=1, figsize=(8, 6), expand=True, tight_layout=None, **kwargs): """ Sets up a figure of size *figsize* with a number of rows (*rows*) and columns (*cols*). \*\*kwargs passed through to :meth:`matplotlib.figure.Figure.add_subplot`. .. versionadded:: 1.2 Parameters ---------- rows : int Number of rows to create. cols : int Number of columns to create. figsize : tuple Size of figure to create. expand : bool Make the entire figure with size `figsize`. Returns ------- fig : :class:`matplotlib.figure.Figure` The figure. axes : :class:`numpy.ndarray` An array of all of the axes. (Unless there's only one axis, in which case it returns an object instance :class:`matplotlib.axis.Axis`.) """ if expand: figsize = (figsize[0]*cols, figsize[1]*rows) figargs = {} if isinstance(tight_layout, dict): figargs["tight_layout"] = tight_layout elif tight_layout == "pdf": figargs["tight_layout"] = {"rect": (0, 0, 1, 0.95)} dpi = kwargs.pop('dpi', None) fig, gs = _setup_figure(rows=rows, cols=cols, figsize=figsize, dpi=dpi, **figargs) axes = _np.empty(shape=(rows, cols), dtype=object) for i in range(rows): for j in range(cols): axes[i, j] = fig.add_subplot(gs[i, j], **kwargs) if axes.shape == (1, 1): return fig, axes[0, 0] else: return fig, axes
def setup_axes(rows=1, cols=1, figsize=(8, 6), expand=True, tight_layout=None, **kwargs): """ Sets up a figure of size *figsize* with a number of rows (*rows*) and columns (*cols*). \*\*kwargs passed through to :meth:`matplotlib.figure.Figure.add_subplot`. .. versionadded:: 1.2 Parameters ---------- rows : int Number of rows to create. cols : int Number of columns to create. figsize : tuple Size of figure to create. expand : bool Make the entire figure with size `figsize`. Returns ------- fig : :class:`matplotlib.figure.Figure` The figure. axes : :class:`numpy.ndarray` An array of all of the axes. (Unless there's only one axis, in which case it returns an object instance :class:`matplotlib.axis.Axis`.) """ if expand: figsize = (figsize[0]*cols, figsize[1]*rows) figargs = {} if isinstance(tight_layout, dict): figargs["tight_layout"] = tight_layout elif tight_layout == "pdf": figargs["tight_layout"] = {"rect": (0, 0, 1, 0.95)} dpi = kwargs.pop('dpi', None) fig, gs = _setup_figure(rows=rows, cols=cols, figsize=figsize, dpi=dpi, **figargs) axes = _np.empty(shape=(rows, cols), dtype=object) for i in range(rows): for j in range(cols): axes[i, j] = fig.add_subplot(gs[i, j], **kwargs) if axes.shape == (1, 1): return fig, axes[0, 0] else: return fig, axes
[ "Sets", "up", "a", "figure", "of", "size", "*", "figsize", "*", "with", "a", "number", "of", "rows", "(", "*", "rows", "*", ")", "and", "columns", "(", "*", "cols", "*", ")", ".", "\\", "*", "\\", "*", "kwargs", "passed", "through", "to", ":", "meth", ":", "matplotlib", ".", "figure", ".", "Figure", ".", "add_subplot", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/matplotlib/setup_axes.py#L8-L57
[ "def", "setup_axes", "(", "rows", "=", "1", ",", "cols", "=", "1", ",", "figsize", "=", "(", "8", ",", "6", ")", ",", "expand", "=", "True", ",", "tight_layout", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "expand", ":", "figsize", "=", "(", "figsize", "[", "0", "]", "*", "cols", ",", "figsize", "[", "1", "]", "*", "rows", ")", "figargs", "=", "{", "}", "if", "isinstance", "(", "tight_layout", ",", "dict", ")", ":", "figargs", "[", "\"tight_layout\"", "]", "=", "tight_layout", "elif", "tight_layout", "==", "\"pdf\"", ":", "figargs", "[", "\"tight_layout\"", "]", "=", "{", "\"rect\"", ":", "(", "0", ",", "0", ",", "1", ",", "0.95", ")", "}", "dpi", "=", "kwargs", ".", "pop", "(", "'dpi'", ",", "None", ")", "fig", ",", "gs", "=", "_setup_figure", "(", "rows", "=", "rows", ",", "cols", "=", "cols", ",", "figsize", "=", "figsize", ",", "dpi", "=", "dpi", ",", "*", "*", "figargs", ")", "axes", "=", "_np", ".", "empty", "(", "shape", "=", "(", "rows", ",", "cols", ")", ",", "dtype", "=", "object", ")", "for", "i", "in", "range", "(", "rows", ")", ":", "for", "j", "in", "range", "(", "cols", ")", ":", "axes", "[", "i", ",", "j", "]", "=", "fig", ".", "add_subplot", "(", "gs", "[", "i", ",", "j", "]", ",", "*", "*", "kwargs", ")", "if", "axes", ".", "shape", "==", "(", "1", ",", "1", ")", ":", "return", "fig", ",", "axes", "[", "0", ",", "0", "]", "else", ":", "return", "fig", ",", "axes" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
DCCGraph.factory
Creates a ``DCCGraph``, a root :class:`Node`: and the node's associated data class instance. This factory is used to get around the chicken-and-egg problem of the ``DCCGraph`` and ``Nodes`` within it having pointers to each other. :param data_class: django model class that extends :class:`BaseNodeData` and is used to associate information with the nodes in this graph :param kwargs: arguments to pass to constructor of the data class instance that is to be created for the root node :returns: instance of the newly created ``DCCGraph``
flowr/models.py
def factory(cls, data_class, **kwargs): """Creates a ``DCCGraph``, a root :class:`Node`: and the node's associated data class instance. This factory is used to get around the chicken-and-egg problem of the ``DCCGraph`` and ``Nodes`` within it having pointers to each other. :param data_class: django model class that extends :class:`BaseNodeData` and is used to associate information with the nodes in this graph :param kwargs: arguments to pass to constructor of the data class instance that is to be created for the root node :returns: instance of the newly created ``DCCGraph`` """ if not issubclass(data_class, BaseNodeData): raise AttributeError('data_class must be a BaseNodeData extender') content_type = ContentType.objects.get_for_model(data_class) graph = DCCGraph.objects.create(data_content_type=content_type) node = Node.objects.create(graph=graph) data_class.objects.create(node=node, **kwargs) graph.root = node graph.save() return graph
def factory(cls, data_class, **kwargs): """Creates a ``DCCGraph``, a root :class:`Node`: and the node's associated data class instance. This factory is used to get around the chicken-and-egg problem of the ``DCCGraph`` and ``Nodes`` within it having pointers to each other. :param data_class: django model class that extends :class:`BaseNodeData` and is used to associate information with the nodes in this graph :param kwargs: arguments to pass to constructor of the data class instance that is to be created for the root node :returns: instance of the newly created ``DCCGraph`` """ if not issubclass(data_class, BaseNodeData): raise AttributeError('data_class must be a BaseNodeData extender') content_type = ContentType.objects.get_for_model(data_class) graph = DCCGraph.objects.create(data_content_type=content_type) node = Node.objects.create(graph=graph) data_class.objects.create(node=node, **kwargs) graph.root = node graph.save() return graph
[ "Creates", "a", "DCCGraph", "a", "root", ":", "class", ":", "Node", ":", "and", "the", "node", "s", "associated", "data", "class", "instance", ".", "This", "factory", "is", "used", "to", "get", "around", "the", "chicken", "-", "and", "-", "egg", "problem", "of", "the", "DCCGraph", "and", "Nodes", "within", "it", "having", "pointers", "to", "each", "other", "." ]
cltrudeau/django-flowr
python
https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L37-L61
[ "def", "factory", "(", "cls", ",", "data_class", ",", "*", "*", "kwargs", ")", ":", "if", "not", "issubclass", "(", "data_class", ",", "BaseNodeData", ")", ":", "raise", "AttributeError", "(", "'data_class must be a BaseNodeData extender'", ")", "content_type", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "data_class", ")", "graph", "=", "DCCGraph", ".", "objects", ".", "create", "(", "data_content_type", "=", "content_type", ")", "node", "=", "Node", ".", "objects", ".", "create", "(", "graph", "=", "graph", ")", "data_class", ".", "objects", ".", "create", "(", "node", "=", "node", ",", "*", "*", "kwargs", ")", "graph", ".", "root", "=", "node", "graph", ".", "save", "(", ")", "return", "graph" ]
d077b90376ede33721db55ff29e08b8a16ed17ae
valid
DCCGraph.factory_from_graph
Creates a ``DCCGraph`` and corresponding nodes. The root_args parm is a dictionary specifying the parameters for creating a :class:`Node` and its corresponding :class:`BaseNodeData` subclass from the data_class specified. The children parm is an iterable containing pairs of dictionaries and iterables, where the dictionaries specify the parameters for a :class:`BaseNodeData` subclass and the iterable the list of children. Example:: DCCGraph.factory_from_graph(Label, {'name':'A'}, [ ({'name':'B', []), ({'name':'C', []) ]) creates the graph:: A / \ B C :param data_class: django model class that extends :class:`BaseNodeData` and is used to associate information with the Nodes in this graph :param root_args: dictionary of arguments to pass to constructor of the data class instance that is to be created for the root node :param children: iterable with a list of dictionary and iterable pairs :returns: instance of the newly created ``DCCGraph``
flowr/models.py
def factory_from_graph(cls, data_class, root_args, children): """Creates a ``DCCGraph`` and corresponding nodes. The root_args parm is a dictionary specifying the parameters for creating a :class:`Node` and its corresponding :class:`BaseNodeData` subclass from the data_class specified. The children parm is an iterable containing pairs of dictionaries and iterables, where the dictionaries specify the parameters for a :class:`BaseNodeData` subclass and the iterable the list of children. Example:: DCCGraph.factory_from_graph(Label, {'name':'A'}, [ ({'name':'B', []), ({'name':'C', []) ]) creates the graph:: A / \ B C :param data_class: django model class that extends :class:`BaseNodeData` and is used to associate information with the Nodes in this graph :param root_args: dictionary of arguments to pass to constructor of the data class instance that is to be created for the root node :param children: iterable with a list of dictionary and iterable pairs :returns: instance of the newly created ``DCCGraph`` """ graph = cls.factory(data_class, **root_args) for child in children: cls._depth_create(graph.root, child[0], child[1]) return graph
def factory_from_graph(cls, data_class, root_args, children): """Creates a ``DCCGraph`` and corresponding nodes. The root_args parm is a dictionary specifying the parameters for creating a :class:`Node` and its corresponding :class:`BaseNodeData` subclass from the data_class specified. The children parm is an iterable containing pairs of dictionaries and iterables, where the dictionaries specify the parameters for a :class:`BaseNodeData` subclass and the iterable the list of children. Example:: DCCGraph.factory_from_graph(Label, {'name':'A'}, [ ({'name':'B', []), ({'name':'C', []) ]) creates the graph:: A / \ B C :param data_class: django model class that extends :class:`BaseNodeData` and is used to associate information with the Nodes in this graph :param root_args: dictionary of arguments to pass to constructor of the data class instance that is to be created for the root node :param children: iterable with a list of dictionary and iterable pairs :returns: instance of the newly created ``DCCGraph`` """ graph = cls.factory(data_class, **root_args) for child in children: cls._depth_create(graph.root, child[0], child[1]) return graph
[ "Creates", "a", "DCCGraph", "and", "corresponding", "nodes", ".", "The", "root_args", "parm", "is", "a", "dictionary", "specifying", "the", "parameters", "for", "creating", "a", ":", "class", ":", "Node", "and", "its", "corresponding", ":", "class", ":", "BaseNodeData", "subclass", "from", "the", "data_class", "specified", ".", "The", "children", "parm", "is", "an", "iterable", "containing", "pairs", "of", "dictionaries", "and", "iterables", "where", "the", "dictionaries", "specify", "the", "parameters", "for", "a", ":", "class", ":", "BaseNodeData", "subclass", "and", "the", "iterable", "the", "list", "of", "children", "." ]
cltrudeau/django-flowr
python
https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L71-L109
[ "def", "factory_from_graph", "(", "cls", ",", "data_class", ",", "root_args", ",", "children", ")", ":", "graph", "=", "cls", ".", "factory", "(", "data_class", ",", "*", "*", "root_args", ")", "for", "child", "in", "children", ":", "cls", ".", "_depth_create", "(", "graph", ".", "root", ",", "child", "[", "0", "]", ",", "child", "[", "1", "]", ")", "return", "graph" ]
d077b90376ede33721db55ff29e08b8a16ed17ae
valid
DCCGraph.find_nodes
Searches the data nodes that are associated with this graph using the key word arguments as a filter and returns a :class:`django.db.models.query.QuerySet`` of the attached :class:`Node` objects. :param kwargs: filter arguments applied to searching the :class:`BaseNodeData` subclass associated with this graph. :returns: ``QuerySet`` of :class:`Node` objects
flowr/models.py
def find_nodes(self, **kwargs): """Searches the data nodes that are associated with this graph using the key word arguments as a filter and returns a :class:`django.db.models.query.QuerySet`` of the attached :class:`Node` objects. :param kwargs: filter arguments applied to searching the :class:`BaseNodeData` subclass associated with this graph. :returns: ``QuerySet`` of :class:`Node` objects """ filter_args = {} classname = self.data_content_type.model_class().__name__.lower() for key, value in kwargs.items(): filter_args['%s__%s' % (classname, key)] = value return Node.objects.filter(**filter_args)
def find_nodes(self, **kwargs): """Searches the data nodes that are associated with this graph using the key word arguments as a filter and returns a :class:`django.db.models.query.QuerySet`` of the attached :class:`Node` objects. :param kwargs: filter arguments applied to searching the :class:`BaseNodeData` subclass associated with this graph. :returns: ``QuerySet`` of :class:`Node` objects """ filter_args = {} classname = self.data_content_type.model_class().__name__.lower() for key, value in kwargs.items(): filter_args['%s__%s' % (classname, key)] = value return Node.objects.filter(**filter_args)
[ "Searches", "the", "data", "nodes", "that", "are", "associated", "with", "this", "graph", "using", "the", "key", "word", "arguments", "as", "a", "filter", "and", "returns", "a", ":", "class", ":", "django", ".", "db", ".", "models", ".", "query", ".", "QuerySet", "of", "the", "attached", ":", "class", ":", "Node", "objects", "." ]
cltrudeau/django-flowr
python
https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L111-L128
[ "def", "find_nodes", "(", "self", ",", "*", "*", "kwargs", ")", ":", "filter_args", "=", "{", "}", "classname", "=", "self", ".", "data_content_type", ".", "model_class", "(", ")", ".", "__name__", ".", "lower", "(", ")", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "filter_args", "[", "'%s__%s'", "%", "(", "classname", ",", "key", ")", "]", "=", "value", "return", "Node", ".", "objects", ".", "filter", "(", "*", "*", "filter_args", ")" ]
d077b90376ede33721db55ff29e08b8a16ed17ae
valid
Node.add_child
Creates a new ``Node`` based on the extending class and adds it as a child to this ``Node``. :param kwargs: arguments for constructing the data object associated with this ``Node`` :returns: extender of the ``Node`` class
flowr/models.py
def add_child(self, **kwargs): """Creates a new ``Node`` based on the extending class and adds it as a child to this ``Node``. :param kwargs: arguments for constructing the data object associated with this ``Node`` :returns: extender of the ``Node`` class """ data_class = self.graph.data_content_type.model_class() node = Node.objects.create(graph=self.graph) data_class.objects.create(node=node, **kwargs) node.parents.add(self) self.children.add(node) return node
def add_child(self, **kwargs): """Creates a new ``Node`` based on the extending class and adds it as a child to this ``Node``. :param kwargs: arguments for constructing the data object associated with this ``Node`` :returns: extender of the ``Node`` class """ data_class = self.graph.data_content_type.model_class() node = Node.objects.create(graph=self.graph) data_class.objects.create(node=node, **kwargs) node.parents.add(self) self.children.add(node) return node
[ "Creates", "a", "new", "Node", "based", "on", "the", "extending", "class", "and", "adds", "it", "as", "a", "child", "to", "this", "Node", "." ]
cltrudeau/django-flowr
python
https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L187-L202
[ "def", "add_child", "(", "self", ",", "*", "*", "kwargs", ")", ":", "data_class", "=", "self", ".", "graph", ".", "data_content_type", ".", "model_class", "(", ")", "node", "=", "Node", ".", "objects", ".", "create", "(", "graph", "=", "self", ".", "graph", ")", "data_class", ".", "objects", ".", "create", "(", "node", "=", "node", ",", "*", "*", "kwargs", ")", "node", ".", "parents", ".", "add", "(", "self", ")", "self", ".", "children", ".", "add", "(", "node", ")", "return", "node" ]
d077b90376ede33721db55ff29e08b8a16ed17ae
valid
Node.connect_child
Adds the given node as a child to this one. No new nodes are created, only connections are made. :param node: a ``Node`` object to connect
flowr/models.py
def connect_child(self, node): """Adds the given node as a child to this one. No new nodes are created, only connections are made. :param node: a ``Node`` object to connect """ if node.graph != self.graph: raise AttributeError('cannot connect nodes from different graphs') node.parents.add(self) self.children.add(node)
def connect_child(self, node): """Adds the given node as a child to this one. No new nodes are created, only connections are made. :param node: a ``Node`` object to connect """ if node.graph != self.graph: raise AttributeError('cannot connect nodes from different graphs') node.parents.add(self) self.children.add(node)
[ "Adds", "the", "given", "node", "as", "a", "child", "to", "this", "one", ".", "No", "new", "nodes", "are", "created", "only", "connections", "are", "made", ".", ":", "param", "node", ":", "a", "Node", "object", "to", "connect" ]
cltrudeau/django-flowr
python
https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L204-L215
[ "def", "connect_child", "(", "self", ",", "node", ")", ":", "if", "node", ".", "graph", "!=", "self", ".", "graph", ":", "raise", "AttributeError", "(", "'cannot connect nodes from different graphs'", ")", "node", ".", "parents", ".", "add", "(", "self", ")", "self", ".", "children", ".", "add", "(", "node", ")" ]
d077b90376ede33721db55ff29e08b8a16ed17ae
valid
Node.ancestors
Returns a list of the ancestors of this node.
flowr/models.py
def ancestors(self): """Returns a list of the ancestors of this node.""" ancestors = set([]) self._depth_ascend(self, ancestors) try: ancestors.remove(self) except KeyError: # we weren't ancestor of ourself, that's ok pass return list(ancestors)
def ancestors(self): """Returns a list of the ancestors of this node.""" ancestors = set([]) self._depth_ascend(self, ancestors) try: ancestors.remove(self) except KeyError: # we weren't ancestor of ourself, that's ok pass return list(ancestors)
[ "Returns", "a", "list", "of", "the", "ancestors", "of", "this", "node", "." ]
cltrudeau/django-flowr
python
https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L226-L236
[ "def", "ancestors", "(", "self", ")", ":", "ancestors", "=", "set", "(", "[", "]", ")", "self", ".", "_depth_ascend", "(", "self", ",", "ancestors", ")", "try", ":", "ancestors", ".", "remove", "(", "self", ")", "except", "KeyError", ":", "# we weren't ancestor of ourself, that's ok", "pass", "return", "list", "(", "ancestors", ")" ]
d077b90376ede33721db55ff29e08b8a16ed17ae
valid
Node.ancestors_root
Returns a list of the ancestors of this node but does not pass the root node, even if the root has parents due to cycles.
flowr/models.py
def ancestors_root(self): """Returns a list of the ancestors of this node but does not pass the root node, even if the root has parents due to cycles.""" if self.is_root(): return [] ancestors = set([]) self._depth_ascend(self, ancestors, True) try: ancestors.remove(self) except KeyError: # we weren't ancestor of ourself, that's ok pass return list(ancestors)
def ancestors_root(self): """Returns a list of the ancestors of this node but does not pass the root node, even if the root has parents due to cycles.""" if self.is_root(): return [] ancestors = set([]) self._depth_ascend(self, ancestors, True) try: ancestors.remove(self) except KeyError: # we weren't ancestor of ourself, that's ok pass return list(ancestors)
[ "Returns", "a", "list", "of", "the", "ancestors", "of", "this", "node", "but", "does", "not", "pass", "the", "root", "node", "even", "if", "the", "root", "has", "parents", "due", "to", "cycles", "." ]
cltrudeau/django-flowr
python
https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L238-L252
[ "def", "ancestors_root", "(", "self", ")", ":", "if", "self", ".", "is_root", "(", ")", ":", "return", "[", "]", "ancestors", "=", "set", "(", "[", "]", ")", "self", ".", "_depth_ascend", "(", "self", ",", "ancestors", ",", "True", ")", "try", ":", "ancestors", ".", "remove", "(", "self", ")", "except", "KeyError", ":", "# we weren't ancestor of ourself, that's ok", "pass", "return", "list", "(", "ancestors", ")" ]
d077b90376ede33721db55ff29e08b8a16ed17ae
valid
Node.descendents
Returns a list of descendents of this node.
flowr/models.py
def descendents(self): """Returns a list of descendents of this node.""" visited = set([]) self._depth_descend(self, visited) try: visited.remove(self) except KeyError: # we weren't descendent of ourself, that's ok pass return list(visited)
def descendents(self): """Returns a list of descendents of this node.""" visited = set([]) self._depth_descend(self, visited) try: visited.remove(self) except KeyError: # we weren't descendent of ourself, that's ok pass return list(visited)
[ "Returns", "a", "list", "of", "descendents", "of", "this", "node", "." ]
cltrudeau/django-flowr
python
https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L263-L273
[ "def", "descendents", "(", "self", ")", ":", "visited", "=", "set", "(", "[", "]", ")", "self", ".", "_depth_descend", "(", "self", ",", "visited", ")", "try", ":", "visited", ".", "remove", "(", "self", ")", "except", "KeyError", ":", "# we weren't descendent of ourself, that's ok", "pass", "return", "list", "(", "visited", ")" ]
d077b90376ede33721db55ff29e08b8a16ed17ae
valid
Node.descendents_root
Returns a list of descendents of this node, if the root node is in the list (due to a cycle) it will be included but will not pass through it.
flowr/models.py
def descendents_root(self): """Returns a list of descendents of this node, if the root node is in the list (due to a cycle) it will be included but will not pass through it. """ visited = set([]) self._depth_descend(self, visited, True) try: visited.remove(self) except KeyError: # we weren't descendent of ourself, that's ok pass return list(visited)
def descendents_root(self): """Returns a list of descendents of this node, if the root node is in the list (due to a cycle) it will be included but will not pass through it. """ visited = set([]) self._depth_descend(self, visited, True) try: visited.remove(self) except KeyError: # we weren't descendent of ourself, that's ok pass return list(visited)
[ "Returns", "a", "list", "of", "descendents", "of", "this", "node", "if", "the", "root", "node", "is", "in", "the", "list", "(", "due", "to", "a", "cycle", ")", "it", "will", "be", "included", "but", "will", "not", "pass", "through", "it", "." ]
cltrudeau/django-flowr
python
https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L275-L288
[ "def", "descendents_root", "(", "self", ")", ":", "visited", "=", "set", "(", "[", "]", ")", "self", ".", "_depth_descend", "(", "self", ",", "visited", ",", "True", ")", "try", ":", "visited", ".", "remove", "(", "self", ")", "except", "KeyError", ":", "# we weren't descendent of ourself, that's ok", "pass", "return", "list", "(", "visited", ")" ]
d077b90376ede33721db55ff29e08b8a16ed17ae
valid
Node.can_remove
Returns True if it is legal to remove this node and still leave the graph as a single connected entity, not splitting it into a forest. Only nodes with no children or those who cause a cycle can be deleted.
flowr/models.py
def can_remove(self): """Returns True if it is legal to remove this node and still leave the graph as a single connected entity, not splitting it into a forest. Only nodes with no children or those who cause a cycle can be deleted. """ if self.children.count() == 0: return True ancestors = set(self.ancestors_root()) children = set(self.children.all()) return children.issubset(ancestors)
def can_remove(self): """Returns True if it is legal to remove this node and still leave the graph as a single connected entity, not splitting it into a forest. Only nodes with no children or those who cause a cycle can be deleted. """ if self.children.count() == 0: return True ancestors = set(self.ancestors_root()) children = set(self.children.all()) return children.issubset(ancestors)
[ "Returns", "True", "if", "it", "is", "legal", "to", "remove", "this", "node", "and", "still", "leave", "the", "graph", "as", "a", "single", "connected", "entity", "not", "splitting", "it", "into", "a", "forest", ".", "Only", "nodes", "with", "no", "children", "or", "those", "who", "cause", "a", "cycle", "can", "be", "deleted", "." ]
cltrudeau/django-flowr
python
https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L290-L300
[ "def", "can_remove", "(", "self", ")", ":", "if", "self", ".", "children", ".", "count", "(", ")", "==", "0", ":", "return", "True", "ancestors", "=", "set", "(", "self", ".", "ancestors_root", "(", ")", ")", "children", "=", "set", "(", "self", ".", "children", ".", "all", "(", ")", ")", "return", "children", ".", "issubset", "(", "ancestors", ")" ]
d077b90376ede33721db55ff29e08b8a16ed17ae
valid
Node.remove
Removes the node from the graph. Note this does not remove the associated data object. See :func:`Node.can_remove` for limitations on what can be deleted. :returns: :class:`BaseNodeData` subclass associated with the deleted Node :raises AttributeError: if called on a ``Node`` that cannot be deleted
flowr/models.py
def remove(self): """Removes the node from the graph. Note this does not remove the associated data object. See :func:`Node.can_remove` for limitations on what can be deleted. :returns: :class:`BaseNodeData` subclass associated with the deleted Node :raises AttributeError: if called on a ``Node`` that cannot be deleted """ if not self.can_remove(): raise AttributeError('this node cannot be deleted') data = self.data self.parents.remove(self) self.delete() return data
def remove(self): """Removes the node from the graph. Note this does not remove the associated data object. See :func:`Node.can_remove` for limitations on what can be deleted. :returns: :class:`BaseNodeData` subclass associated with the deleted Node :raises AttributeError: if called on a ``Node`` that cannot be deleted """ if not self.can_remove(): raise AttributeError('this node cannot be deleted') data = self.data self.parents.remove(self) self.delete() return data
[ "Removes", "the", "node", "from", "the", "graph", ".", "Note", "this", "does", "not", "remove", "the", "associated", "data", "object", ".", "See", ":", "func", ":", "Node", ".", "can_remove", "for", "limitations", "on", "what", "can", "be", "deleted", "." ]
cltrudeau/django-flowr
python
https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L302-L319
[ "def", "remove", "(", "self", ")", ":", "if", "not", "self", ".", "can_remove", "(", ")", ":", "raise", "AttributeError", "(", "'this node cannot be deleted'", ")", "data", "=", "self", ".", "data", "self", ".", "parents", ".", "remove", "(", "self", ")", "self", ".", "delete", "(", ")", "return", "data" ]
d077b90376ede33721db55ff29e08b8a16ed17ae
valid
Node.prune
Removes the node and all descendents without looping back past the root. Note this does not remove the associated data objects. :returns: list of :class:`BaseDataNode` subclassers associated with the removed ``Node`` objects.
flowr/models.py
def prune(self): """Removes the node and all descendents without looping back past the root. Note this does not remove the associated data objects. :returns: list of :class:`BaseDataNode` subclassers associated with the removed ``Node`` objects. """ targets = self.descendents_root() try: targets.remove(self.graph.root) except ValueError: # root wasn't in the target list, no problem pass results = [n.data for n in targets] results.append(self.data) for node in targets: node.delete() for parent in self.parents.all(): parent.children.remove(self) self.delete() return results
def prune(self): """Removes the node and all descendents without looping back past the root. Note this does not remove the associated data objects. :returns: list of :class:`BaseDataNode` subclassers associated with the removed ``Node`` objects. """ targets = self.descendents_root() try: targets.remove(self.graph.root) except ValueError: # root wasn't in the target list, no problem pass results = [n.data for n in targets] results.append(self.data) for node in targets: node.delete() for parent in self.parents.all(): parent.children.remove(self) self.delete() return results
[ "Removes", "the", "node", "and", "all", "descendents", "without", "looping", "back", "past", "the", "root", ".", "Note", "this", "does", "not", "remove", "the", "associated", "data", "objects", "." ]
cltrudeau/django-flowr
python
https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L321-L345
[ "def", "prune", "(", "self", ")", ":", "targets", "=", "self", ".", "descendents_root", "(", ")", "try", ":", "targets", ".", "remove", "(", "self", ".", "graph", ".", "root", ")", "except", "ValueError", ":", "# root wasn't in the target list, no problem", "pass", "results", "=", "[", "n", ".", "data", "for", "n", "in", "targets", "]", "results", ".", "append", "(", "self", ".", "data", ")", "for", "node", "in", "targets", ":", "node", ".", "delete", "(", ")", "for", "parent", "in", "self", ".", "parents", ".", "all", "(", ")", ":", "parent", ".", "children", ".", "remove", "(", "self", ")", "self", ".", "delete", "(", ")", "return", "results" ]
d077b90376ede33721db55ff29e08b8a16ed17ae
valid
Node.prune_list
Returns a list of nodes that would be removed if prune were called on this element.
flowr/models.py
def prune_list(self): """Returns a list of nodes that would be removed if prune were called on this element. """ targets = self.descendents_root() try: targets.remove(self.graph.root) except ValueError: # root wasn't in the target list, no problem pass targets.append(self) return targets
def prune_list(self): """Returns a list of nodes that would be removed if prune were called on this element. """ targets = self.descendents_root() try: targets.remove(self.graph.root) except ValueError: # root wasn't in the target list, no problem pass targets.append(self) return targets
[ "Returns", "a", "list", "of", "nodes", "that", "would", "be", "removed", "if", "prune", "were", "called", "on", "this", "element", "." ]
cltrudeau/django-flowr
python
https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L347-L359
[ "def", "prune_list", "(", "self", ")", ":", "targets", "=", "self", ".", "descendents_root", "(", ")", "try", ":", "targets", ".", "remove", "(", "self", ".", "graph", ".", "root", ")", "except", "ValueError", ":", "# root wasn't in the target list, no problem", "pass", "targets", ".", "append", "(", "self", ")", "return", "targets" ]
d077b90376ede33721db55ff29e08b8a16ed17ae
valid
FlowNodeData._child_allowed
Called to verify that the given rule can become a child of the current node. :raises AttributeError: if the child is not allowed
flowr/models.py
def _child_allowed(self, child_rule): """Called to verify that the given rule can become a child of the current node. :raises AttributeError: if the child is not allowed """ num_kids = self.node.children.count() num_kids_allowed = len(self.rule.children) if not self.rule.multiple_paths: num_kids_allowed = 1 if num_kids >= num_kids_allowed: raise AttributeError('Rule %s only allows %s children' % ( self.rule_name, self.num_kids_allowed)) # verify not a duplicate for node in self.node.children.all(): if node.data.rule_label == child_rule.class_label: raise AttributeError('Child rule already exists') # check if the given rule is allowed as a child if child_rule not in self.rule.children: raise AttributeError('Rule %s is not a valid child of Rule %s' % ( child_rule.__name__, self.rule_name))
def _child_allowed(self, child_rule): """Called to verify that the given rule can become a child of the current node. :raises AttributeError: if the child is not allowed """ num_kids = self.node.children.count() num_kids_allowed = len(self.rule.children) if not self.rule.multiple_paths: num_kids_allowed = 1 if num_kids >= num_kids_allowed: raise AttributeError('Rule %s only allows %s children' % ( self.rule_name, self.num_kids_allowed)) # verify not a duplicate for node in self.node.children.all(): if node.data.rule_label == child_rule.class_label: raise AttributeError('Child rule already exists') # check if the given rule is allowed as a child if child_rule not in self.rule.children: raise AttributeError('Rule %s is not a valid child of Rule %s' % ( child_rule.__name__, self.rule_name))
[ "Called", "to", "verify", "that", "the", "given", "rule", "can", "become", "a", "child", "of", "the", "current", "node", "." ]
cltrudeau/django-flowr
python
https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L540-L564
[ "def", "_child_allowed", "(", "self", ",", "child_rule", ")", ":", "num_kids", "=", "self", ".", "node", ".", "children", ".", "count", "(", ")", "num_kids_allowed", "=", "len", "(", "self", ".", "rule", ".", "children", ")", "if", "not", "self", ".", "rule", ".", "multiple_paths", ":", "num_kids_allowed", "=", "1", "if", "num_kids", ">=", "num_kids_allowed", ":", "raise", "AttributeError", "(", "'Rule %s only allows %s children'", "%", "(", "self", ".", "rule_name", ",", "self", ".", "num_kids_allowed", ")", ")", "# verify not a duplicate", "for", "node", "in", "self", ".", "node", ".", "children", ".", "all", "(", ")", ":", "if", "node", ".", "data", ".", "rule_label", "==", "child_rule", ".", "class_label", ":", "raise", "AttributeError", "(", "'Child rule already exists'", ")", "# check if the given rule is allowed as a child", "if", "child_rule", "not", "in", "self", ".", "rule", ".", "children", ":", "raise", "AttributeError", "(", "'Rule %s is not a valid child of Rule %s'", "%", "(", "child_rule", ".", "__name__", ",", "self", ".", "rule_name", ")", ")" ]
d077b90376ede33721db55ff29e08b8a16ed17ae
valid
FlowNodeData.add_child_rule
Add a child path in the :class:`Flow` graph using the given :class:`Rule` subclass. This will create a new child :class:`Node` in the associated :class:`Flow` object's state graph with a new :class:`FlowNodeData` instance attached. The :class:`Rule` must be allowed at this stage of the flow according to the hierarchy of rules. :param child_rule: :class:`Rule` class to add to the flow as a child of :class:`Node` that this object owns :returns: ``FlowNodeData`` that was added
flowr/models.py
def add_child_rule(self, child_rule): """Add a child path in the :class:`Flow` graph using the given :class:`Rule` subclass. This will create a new child :class:`Node` in the associated :class:`Flow` object's state graph with a new :class:`FlowNodeData` instance attached. The :class:`Rule` must be allowed at this stage of the flow according to the hierarchy of rules. :param child_rule: :class:`Rule` class to add to the flow as a child of :class:`Node` that this object owns :returns: ``FlowNodeData`` that was added """ self._child_allowed(child_rule) child_node = self.node.add_child(rule_label=child_rule.class_label) return child_node.data
def add_child_rule(self, child_rule): """Add a child path in the :class:`Flow` graph using the given :class:`Rule` subclass. This will create a new child :class:`Node` in the associated :class:`Flow` object's state graph with a new :class:`FlowNodeData` instance attached. The :class:`Rule` must be allowed at this stage of the flow according to the hierarchy of rules. :param child_rule: :class:`Rule` class to add to the flow as a child of :class:`Node` that this object owns :returns: ``FlowNodeData`` that was added """ self._child_allowed(child_rule) child_node = self.node.add_child(rule_label=child_rule.class_label) return child_node.data
[ "Add", "a", "child", "path", "in", "the", ":", "class", ":", "Flow", "graph", "using", "the", "given", ":", "class", ":", "Rule", "subclass", ".", "This", "will", "create", "a", "new", "child", ":", "class", ":", "Node", "in", "the", "associated", ":", "class", ":", "Flow", "object", "s", "state", "graph", "with", "a", "new", ":", "class", ":", "FlowNodeData", "instance", "attached", ".", "The", ":", "class", ":", "Rule", "must", "be", "allowed", "at", "this", "stage", "of", "the", "flow", "according", "to", "the", "hierarchy", "of", "rules", "." ]
cltrudeau/django-flowr
python
https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L566-L583
[ "def", "add_child_rule", "(", "self", ",", "child_rule", ")", ":", "self", ".", "_child_allowed", "(", "child_rule", ")", "child_node", "=", "self", ".", "node", ".", "add_child", "(", "rule_label", "=", "child_rule", ".", "class_label", ")", "return", "child_node", ".", "data" ]
d077b90376ede33721db55ff29e08b8a16ed17ae
valid
FlowNodeData.connect_child
Adds a connection to an existing rule in the :class`Flow` graph. The given :class`Rule` subclass must be allowed to be connected at this stage of the flow according to the hierarchy of rules. :param child_node: ``FlowNodeData`` to attach as a child
flowr/models.py
def connect_child(self, child_node): """Adds a connection to an existing rule in the :class`Flow` graph. The given :class`Rule` subclass must be allowed to be connected at this stage of the flow according to the hierarchy of rules. :param child_node: ``FlowNodeData`` to attach as a child """ self._child_allowed(child_node.rule) self.node.connect_child(child_node.node)
def connect_child(self, child_node): """Adds a connection to an existing rule in the :class`Flow` graph. The given :class`Rule` subclass must be allowed to be connected at this stage of the flow according to the hierarchy of rules. :param child_node: ``FlowNodeData`` to attach as a child """ self._child_allowed(child_node.rule) self.node.connect_child(child_node.node)
[ "Adds", "a", "connection", "to", "an", "existing", "rule", "in", "the", ":", "class", "Flow", "graph", ".", "The", "given", ":", "class", "Rule", "subclass", "must", "be", "allowed", "to", "be", "connected", "at", "this", "stage", "of", "the", "flow", "according", "to", "the", "hierarchy", "of", "rules", "." ]
cltrudeau/django-flowr
python
https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L585-L594
[ "def", "connect_child", "(", "self", ",", "child_node", ")", ":", "self", ".", "_child_allowed", "(", "child_node", ".", "rule", ")", "self", ".", "node", ".", "connect_child", "(", "child_node", ".", "node", ")" ]
d077b90376ede33721db55ff29e08b8a16ed17ae
valid
Flow.in_use
Returns True if there is a :class:`State` object that uses this ``Flow``
flowr/models.py
def in_use(self): """Returns True if there is a :class:`State` object that uses this ``Flow``""" state = State.objects.filter(flow=self).first() return bool(state)
def in_use(self): """Returns True if there is a :class:`State` object that uses this ``Flow``""" state = State.objects.filter(flow=self).first() return bool(state)
[ "Returns", "True", "if", "there", "is", "a", ":", "class", ":", "State", "object", "that", "uses", "this", "Flow" ]
cltrudeau/django-flowr
python
https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L613-L617
[ "def", "in_use", "(", "self", ")", ":", "state", "=", "State", ".", "objects", ".", "filter", "(", "flow", "=", "self", ")", ".", "first", "(", ")", "return", "bool", "(", "state", ")" ]
d077b90376ede33721db55ff29e08b8a16ed17ae
valid
State.start
Factory method for a running state based on a flow. Creates and returns a ``State`` object and calls the associated :func:`Rule.on_enter` method. :param flow: :class:`Flow` which defines this state machine :returns: newly created instance
flowr/models.py
def start(self, flow): """Factory method for a running state based on a flow. Creates and returns a ``State`` object and calls the associated :func:`Rule.on_enter` method. :param flow: :class:`Flow` which defines this state machine :returns: newly created instance """ state = State.objects.create(flow=flow, current_node=flow.state_graph.root) flow.state_graph.root.data.rule.on_enter(state) return state
def start(self, flow): """Factory method for a running state based on a flow. Creates and returns a ``State`` object and calls the associated :func:`Rule.on_enter` method. :param flow: :class:`Flow` which defines this state machine :returns: newly created instance """ state = State.objects.create(flow=flow, current_node=flow.state_graph.root) flow.state_graph.root.data.rule.on_enter(state) return state
[ "Factory", "method", "for", "a", "running", "state", "based", "on", "a", "flow", ".", "Creates", "and", "returns", "a", "State", "object", "and", "calls", "the", "associated", ":", "func", ":", "Rule", ".", "on_enter", "method", "." ]
cltrudeau/django-flowr
python
https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L638-L651
[ "def", "start", "(", "self", ",", "flow", ")", ":", "state", "=", "State", ".", "objects", ".", "create", "(", "flow", "=", "flow", ",", "current_node", "=", "flow", ".", "state_graph", ".", "root", ")", "flow", ".", "state_graph", ".", "root", ".", "data", ".", "rule", ".", "on_enter", "(", "state", ")", "return", "state" ]
d077b90376ede33721db55ff29e08b8a16ed17ae
valid
State.next_state
Proceeds to the next step in the flow. Calls the associated :func:`Rule.on_leave` method for the for the current rule and the :func:`Rule.on_enter` for the rule being entered. If the current step in the flow is multipath then a valid :class:`Rule` subclass must be passed into this call. If there is only one possible path in the flow and a :class:`Rule` is given it will be ignored. :param rule: if the current :class:`Rule` in the :class:`Flow` is multipath then the next :class:`Rule` in the flow must be provided.
flowr/models.py
def next_state(self, rule=None): """Proceeds to the next step in the flow. Calls the associated :func:`Rule.on_leave` method for the for the current rule and the :func:`Rule.on_enter` for the rule being entered. If the current step in the flow is multipath then a valid :class:`Rule` subclass must be passed into this call. If there is only one possible path in the flow and a :class:`Rule` is given it will be ignored. :param rule: if the current :class:`Rule` in the :class:`Flow` is multipath then the next :class:`Rule` in the flow must be provided. """ num_kids = self.current_node.children.count() next_node = None if num_kids == 0: raise AttributeError('No next state in this Flow id=%s' % ( self.flow.id)) elif num_kids == 1: next_node = self.current_node.children.first() else: if not rule: raise AttributeError(('Current Rule %s is multipath but no ' 'choice was passed in') % self.current_node.data.rule_name) for node in self.current_node.children.all(): if node.data.rule_label == rule.class_label: next_node = node break if not next_node: raise AttributeError(('Current Rule %s is multipath and the ' 'Rule choice passed in was not in the Flow') % ( self.current_node.data.rule_name)) self.current_node.data.rule.on_leave(self) next_node.data.rule.on_enter(self) self.current_node = next_node self.save()
def next_state(self, rule=None): """Proceeds to the next step in the flow. Calls the associated :func:`Rule.on_leave` method for the for the current rule and the :func:`Rule.on_enter` for the rule being entered. If the current step in the flow is multipath then a valid :class:`Rule` subclass must be passed into this call. If there is only one possible path in the flow and a :class:`Rule` is given it will be ignored. :param rule: if the current :class:`Rule` in the :class:`Flow` is multipath then the next :class:`Rule` in the flow must be provided. """ num_kids = self.current_node.children.count() next_node = None if num_kids == 0: raise AttributeError('No next state in this Flow id=%s' % ( self.flow.id)) elif num_kids == 1: next_node = self.current_node.children.first() else: if not rule: raise AttributeError(('Current Rule %s is multipath but no ' 'choice was passed in') % self.current_node.data.rule_name) for node in self.current_node.children.all(): if node.data.rule_label == rule.class_label: next_node = node break if not next_node: raise AttributeError(('Current Rule %s is multipath and the ' 'Rule choice passed in was not in the Flow') % ( self.current_node.data.rule_name)) self.current_node.data.rule.on_leave(self) next_node.data.rule.on_enter(self) self.current_node = next_node self.save()
[ "Proceeds", "to", "the", "next", "step", "in", "the", "flow", ".", "Calls", "the", "associated", ":", "func", ":", "Rule", ".", "on_leave", "method", "for", "the", "for", "the", "current", "rule", "and", "the", ":", "func", ":", "Rule", ".", "on_enter", "for", "the", "rule", "being", "entered", ".", "If", "the", "current", "step", "in", "the", "flow", "is", "multipath", "then", "a", "valid", ":", "class", ":", "Rule", "subclass", "must", "be", "passed", "into", "this", "call", "." ]
cltrudeau/django-flowr
python
https://github.com/cltrudeau/django-flowr/blob/d077b90376ede33721db55ff29e08b8a16ed17ae/flowr/models.py#L657-L696
[ "def", "next_state", "(", "self", ",", "rule", "=", "None", ")", ":", "num_kids", "=", "self", ".", "current_node", ".", "children", ".", "count", "(", ")", "next_node", "=", "None", "if", "num_kids", "==", "0", ":", "raise", "AttributeError", "(", "'No next state in this Flow id=%s'", "%", "(", "self", ".", "flow", ".", "id", ")", ")", "elif", "num_kids", "==", "1", ":", "next_node", "=", "self", ".", "current_node", ".", "children", ".", "first", "(", ")", "else", ":", "if", "not", "rule", ":", "raise", "AttributeError", "(", "(", "'Current Rule %s is multipath but no '", "'choice was passed in'", ")", "%", "self", ".", "current_node", ".", "data", ".", "rule_name", ")", "for", "node", "in", "self", ".", "current_node", ".", "children", ".", "all", "(", ")", ":", "if", "node", ".", "data", ".", "rule_label", "==", "rule", ".", "class_label", ":", "next_node", "=", "node", "break", "if", "not", "next_node", ":", "raise", "AttributeError", "(", "(", "'Current Rule %s is multipath and the '", "'Rule choice passed in was not in the Flow'", ")", "%", "(", "self", ".", "current_node", ".", "data", ".", "rule_name", ")", ")", "self", ".", "current_node", ".", "data", ".", "rule", ".", "on_leave", "(", "self", ")", "next_node", ".", "data", ".", "rule", ".", "on_enter", "(", "self", ")", "self", ".", "current_node", "=", "next_node", "self", ".", "save", "(", ")" ]
d077b90376ede33721db55ff29e08b8a16ed17ae
valid
Locations.get_location
Returns location data. http://dev.wheniwork.com/#get-existing-location
uw_wheniwork/locations.py
def get_location(self, location_id): """ Returns location data. http://dev.wheniwork.com/#get-existing-location """ url = "/2/locations/%s" % location_id return self.location_from_json(self._get_resource(url)["location"])
def get_location(self, location_id): """ Returns location data. http://dev.wheniwork.com/#get-existing-location """ url = "/2/locations/%s" % location_id return self.location_from_json(self._get_resource(url)["location"])
[ "Returns", "location", "data", "." ]
uw-it-cte/uw-restclients-wheniwork
python
https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/locations.py#L6-L14
[ "def", "get_location", "(", "self", ",", "location_id", ")", ":", "url", "=", "\"/2/locations/%s\"", "%", "location_id", "return", "self", ".", "location_from_json", "(", "self", ".", "_get_resource", "(", "url", ")", "[", "\"location\"", "]", ")" ]
0d3ca09d5bbe808fec12e5f943596570d33a1731
valid
Locations.get_locations
Returns a list of locations. http://dev.wheniwork.com/#listing-locations
uw_wheniwork/locations.py
def get_locations(self): """ Returns a list of locations. http://dev.wheniwork.com/#listing-locations """ url = "/2/locations" data = self._get_resource(url) locations = [] for entry in data['locations']: locations.append(self.location_from_json(entry)) return locations
def get_locations(self): """ Returns a list of locations. http://dev.wheniwork.com/#listing-locations """ url = "/2/locations" data = self._get_resource(url) locations = [] for entry in data['locations']: locations.append(self.location_from_json(entry)) return locations
[ "Returns", "a", "list", "of", "locations", "." ]
uw-it-cte/uw-restclients-wheniwork
python
https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/locations.py#L16-L29
[ "def", "get_locations", "(", "self", ")", ":", "url", "=", "\"/2/locations\"", "data", "=", "self", ".", "_get_resource", "(", "url", ")", "locations", "=", "[", "]", "for", "entry", "in", "data", "[", "'locations'", "]", ":", "locations", ".", "append", "(", "self", ".", "location_from_json", "(", "entry", ")", ")", "return", "locations" ]
0d3ca09d5bbe808fec12e5f943596570d33a1731
valid
LinLsqFit.X
The :math:`X` weighted properly by the errors from *y_error*
scisalt/scipy/LinLsqFit_mod.py
def X(self): """ The :math:`X` weighted properly by the errors from *y_error* """ if self._X is None: X = _copy.deepcopy(self.X_unweighted) # print 'X shape is {}'.format(X.shape) for i, el in enumerate(X): X[i, :] = el/self.y_error[i] # print 'New X shape is {}'.format(X.shape) self._X = X return self._X
def X(self): """ The :math:`X` weighted properly by the errors from *y_error* """ if self._X is None: X = _copy.deepcopy(self.X_unweighted) # print 'X shape is {}'.format(X.shape) for i, el in enumerate(X): X[i, :] = el/self.y_error[i] # print 'New X shape is {}'.format(X.shape) self._X = X return self._X
[ "The", ":", "math", ":", "X", "weighted", "properly", "by", "the", "errors", "from", "*", "y_error", "*" ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/scipy/LinLsqFit_mod.py#L91-L102
[ "def", "X", "(", "self", ")", ":", "if", "self", ".", "_X", "is", "None", ":", "X", "=", "_copy", ".", "deepcopy", "(", "self", ".", "X_unweighted", ")", "# print 'X shape is {}'.format(X.shape)", "for", "i", ",", "el", "in", "enumerate", "(", "X", ")", ":", "X", "[", "i", ",", ":", "]", "=", "el", "/", "self", ".", "y_error", "[", "i", "]", "# print 'New X shape is {}'.format(X.shape)", "self", ".", "_X", "=", "X", "return", "self", ".", "_X" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
LinLsqFit.y
The :math:`X` weighted properly by the errors from *y_error*
scisalt/scipy/LinLsqFit_mod.py
def y(self): """ The :math:`X` weighted properly by the errors from *y_error* """ if self._y is None: self._y = self.y_unweighted/self.y_error return self._y
def y(self): """ The :math:`X` weighted properly by the errors from *y_error* """ if self._y is None: self._y = self.y_unweighted/self.y_error return self._y
[ "The", ":", "math", ":", "X", "weighted", "properly", "by", "the", "errors", "from", "*", "y_error", "*" ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/scipy/LinLsqFit_mod.py#L108-L114
[ "def", "y", "(", "self", ")", ":", "if", "self", ".", "_y", "is", "None", ":", "self", ".", "_y", "=", "self", ".", "y_unweighted", "/", "self", ".", "y_error", "return", "self", ".", "_y" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
LinLsqFit.y_fit
Using the result of the linear least squares, the result of :math:`X_{ij}\\beta_i`
scisalt/scipy/LinLsqFit_mod.py
def y_fit(self): """ Using the result of the linear least squares, the result of :math:`X_{ij}\\beta_i` """ if self._y_fit is None: self._y_fit = _np.dot(self.X_unweighted, self.beta) return self._y_fit
def y_fit(self): """ Using the result of the linear least squares, the result of :math:`X_{ij}\\beta_i` """ if self._y_fit is None: self._y_fit = _np.dot(self.X_unweighted, self.beta) return self._y_fit
[ "Using", "the", "result", "of", "the", "linear", "least", "squares", "the", "result", "of", ":", "math", ":", "X_", "{", "ij", "}", "\\\\", "beta_i" ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/scipy/LinLsqFit_mod.py#L120-L126
[ "def", "y_fit", "(", "self", ")", ":", "if", "self", ".", "_y_fit", "is", "None", ":", "self", ".", "_y_fit", "=", "_np", ".", "dot", "(", "self", ".", "X_unweighted", ",", "self", ".", "beta", ")", "return", "self", ".", "_y_fit" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
LinLsqFit.beta
The result :math:`\\beta` of the linear least squares
scisalt/scipy/LinLsqFit_mod.py
def beta(self): """ The result :math:`\\beta` of the linear least squares """ if self._beta is None: # This is the linear least squares matrix formalism self._beta = _np.dot(_np.linalg.pinv(self.X) , self.y) return self._beta
def beta(self): """ The result :math:`\\beta` of the linear least squares """ if self._beta is None: # This is the linear least squares matrix formalism self._beta = _np.dot(_np.linalg.pinv(self.X) , self.y) return self._beta
[ "The", "result", ":", "math", ":", "\\\\", "beta", "of", "the", "linear", "least", "squares" ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/scipy/LinLsqFit_mod.py#L132-L139
[ "def", "beta", "(", "self", ")", ":", "if", "self", ".", "_beta", "is", "None", ":", "# This is the linear least squares matrix formalism", "self", ".", "_beta", "=", "_np", ".", "dot", "(", "_np", ".", "linalg", ".", "pinv", "(", "self", ".", "X", ")", ",", "self", ".", "y", ")", "return", "self", ".", "_beta" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
LinLsqFit.covar
The covariance matrix for the result :math:`\\beta`
scisalt/scipy/LinLsqFit_mod.py
def covar(self): """ The covariance matrix for the result :math:`\\beta` """ if self._covar is None: self._covar = _np.linalg.inv(_np.dot(_np.transpose(self.X), self.X)) return self._covar
def covar(self): """ The covariance matrix for the result :math:`\\beta` """ if self._covar is None: self._covar = _np.linalg.inv(_np.dot(_np.transpose(self.X), self.X)) return self._covar
[ "The", "covariance", "matrix", "for", "the", "result", ":", "math", ":", "\\\\", "beta" ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/scipy/LinLsqFit_mod.py#L145-L151
[ "def", "covar", "(", "self", ")", ":", "if", "self", ".", "_covar", "is", "None", ":", "self", ".", "_covar", "=", "_np", ".", "linalg", ".", "inv", "(", "_np", ".", "dot", "(", "_np", ".", "transpose", "(", "self", ".", "X", ")", ",", "self", ".", "X", ")", ")", "return", "self", ".", "_covar" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
LinLsqFit.chisq_red
The reduced chi-square of the linear least squares
scisalt/scipy/LinLsqFit_mod.py
def chisq_red(self): """ The reduced chi-square of the linear least squares """ if self._chisq_red is None: self._chisq_red = chisquare(self.y_unweighted.transpose(), _np.dot(self.X_unweighted, self.beta), self.y_error, ddof=3, verbose=False) return self._chisq_red
def chisq_red(self): """ The reduced chi-square of the linear least squares """ if self._chisq_red is None: self._chisq_red = chisquare(self.y_unweighted.transpose(), _np.dot(self.X_unweighted, self.beta), self.y_error, ddof=3, verbose=False) return self._chisq_red
[ "The", "reduced", "chi", "-", "square", "of", "the", "linear", "least", "squares" ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/scipy/LinLsqFit_mod.py#L157-L163
[ "def", "chisq_red", "(", "self", ")", ":", "if", "self", ".", "_chisq_red", "is", "None", ":", "self", ".", "_chisq_red", "=", "chisquare", "(", "self", ".", "y_unweighted", ".", "transpose", "(", ")", ",", "_np", ".", "dot", "(", "self", ".", "X_unweighted", ",", "self", ".", "beta", ")", ",", "self", ".", "y_error", ",", "ddof", "=", "3", ",", "verbose", "=", "False", ")", "return", "self", ".", "_chisq_red" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
MapRouletteTask.create
Create the task on the server
maproulette/task.py
def create(self, server): """Create the task on the server""" if len(self.geometries) == 0: raise Exception('no geometries') return server.post( 'task_admin', self.as_payload(), replacements={ 'slug': self.__challenge__.slug, 'identifier': self.identifier})
def create(self, server): """Create the task on the server""" if len(self.geometries) == 0: raise Exception('no geometries') return server.post( 'task_admin', self.as_payload(), replacements={ 'slug': self.__challenge__.slug, 'identifier': self.identifier})
[ "Create", "the", "task", "on", "the", "server" ]
mvexel/maproulette-api-wrapper
python
https://github.com/mvexel/maproulette-api-wrapper/blob/835278111afefed2beecf9716a033529304c548f/maproulette/task.py#L45-L54
[ "def", "create", "(", "self", ",", "server", ")", ":", "if", "len", "(", "self", ".", "geometries", ")", "==", "0", ":", "raise", "Exception", "(", "'no geometries'", ")", "return", "server", ".", "post", "(", "'task_admin'", ",", "self", ".", "as_payload", "(", ")", ",", "replacements", "=", "{", "'slug'", ":", "self", ".", "__challenge__", ".", "slug", ",", "'identifier'", ":", "self", ".", "identifier", "}", ")" ]
835278111afefed2beecf9716a033529304c548f
valid
MapRouletteTask.update
Update existing task on the server
maproulette/task.py
def update(self, server): """Update existing task on the server""" return server.put( 'task_admin', self.as_payload(), replacements={ 'slug': self.__challenge__.slug, 'identifier': self.identifier})
def update(self, server): """Update existing task on the server""" return server.put( 'task_admin', self.as_payload(), replacements={ 'slug': self.__challenge__.slug, 'identifier': self.identifier})
[ "Update", "existing", "task", "on", "the", "server" ]
mvexel/maproulette-api-wrapper
python
https://github.com/mvexel/maproulette-api-wrapper/blob/835278111afefed2beecf9716a033529304c548f/maproulette/task.py#L56-L63
[ "def", "update", "(", "self", ",", "server", ")", ":", "return", "server", ".", "put", "(", "'task_admin'", ",", "self", ".", "as_payload", "(", ")", ",", "replacements", "=", "{", "'slug'", ":", "self", ".", "__challenge__", ".", "slug", ",", "'identifier'", ":", "self", ".", "identifier", "}", ")" ]
835278111afefed2beecf9716a033529304c548f
valid
MapRouletteTask.from_server
Retrieve a task from the server
maproulette/task.py
def from_server(cls, server, slug, identifier): """Retrieve a task from the server""" task = server.get( 'task', replacements={ 'slug': slug, 'identifier': identifier}) return cls(**task)
def from_server(cls, server, slug, identifier): """Retrieve a task from the server""" task = server.get( 'task', replacements={ 'slug': slug, 'identifier': identifier}) return cls(**task)
[ "Retrieve", "a", "task", "from", "the", "server" ]
mvexel/maproulette-api-wrapper
python
https://github.com/mvexel/maproulette-api-wrapper/blob/835278111afefed2beecf9716a033529304c548f/maproulette/task.py#L92-L99
[ "def", "from_server", "(", "cls", ",", "server", ",", "slug", ",", "identifier", ")", ":", "task", "=", "server", ".", "get", "(", "'task'", ",", "replacements", "=", "{", "'slug'", ":", "slug", ",", "'identifier'", ":", "identifier", "}", ")", "return", "cls", "(", "*", "*", "task", ")" ]
835278111afefed2beecf9716a033529304c548f
valid
formatter
Formats a string with color
tmc/coloring.py
def formatter(color, s): """ Formats a string with color """ if no_coloring: return s return "{begin}{s}{reset}".format(begin=color, s=s, reset=Colors.RESET)
def formatter(color, s): """ Formats a string with color """ if no_coloring: return s return "{begin}{s}{reset}".format(begin=color, s=s, reset=Colors.RESET)
[ "Formats", "a", "string", "with", "color" ]
minttu/tmc.py
python
https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/coloring.py#L42-L46
[ "def", "formatter", "(", "color", ",", "s", ")", ":", "if", "no_coloring", ":", "return", "s", "return", "\"{begin}{s}{reset}\"", ".", "format", "(", "begin", "=", "color", ",", "s", "=", "s", ",", "reset", "=", "Colors", ".", "RESET", ")" ]
212cfe1791a4aab4783f99b665cc32da6437f419
valid
Document.reload
Reloads all attributes from the database. :param fields: (optional) args list of fields to reload :param max_depth: (optional) depth of dereferencing to follow .. versionadded:: 0.1.2 .. versionchanged:: 0.6 Now chainable .. versionchanged:: 0.9 Can provide specific fields to reload
frasco_models/backends/mongoengine.py
def reload(self, *fields, **kwargs): """Reloads all attributes from the database. :param fields: (optional) args list of fields to reload :param max_depth: (optional) depth of dereferencing to follow .. versionadded:: 0.1.2 .. versionchanged:: 0.6 Now chainable .. versionchanged:: 0.9 Can provide specific fields to reload """ max_depth = 1 if fields and isinstance(fields[0], int): max_depth = fields[0] fields = fields[1:] elif "max_depth" in kwargs: max_depth = kwargs["max_depth"] if not self.pk: raise self.DoesNotExist("Document does not exist") obj = self._qs.read_preference(ReadPreference.PRIMARY).filter( **self._object_key).only(*fields).limit(1 ).select_related(max_depth=max_depth) if obj: obj = obj[0] else: raise self.DoesNotExist("Document does not exist") for field in self._fields_ordered: if not fields or field in fields: try: setattr(self, field, self._reload(field, obj[field])) except KeyError: # If field is removed from the database while the object # is in memory, a reload would cause a KeyError # i.e. obj.update(unset__field=1) followed by obj.reload() delattr(self, field) # BUG FIX BY US HERE: if not fields: self._changed_fields = obj._changed_fields else: for field in fields: field = self._db_field_map.get(field, field) if field in self._changed_fields: self._changed_fields.remove(field) self._created = False return self
def reload(self, *fields, **kwargs): """Reloads all attributes from the database. :param fields: (optional) args list of fields to reload :param max_depth: (optional) depth of dereferencing to follow .. versionadded:: 0.1.2 .. versionchanged:: 0.6 Now chainable .. versionchanged:: 0.9 Can provide specific fields to reload """ max_depth = 1 if fields and isinstance(fields[0], int): max_depth = fields[0] fields = fields[1:] elif "max_depth" in kwargs: max_depth = kwargs["max_depth"] if not self.pk: raise self.DoesNotExist("Document does not exist") obj = self._qs.read_preference(ReadPreference.PRIMARY).filter( **self._object_key).only(*fields).limit(1 ).select_related(max_depth=max_depth) if obj: obj = obj[0] else: raise self.DoesNotExist("Document does not exist") for field in self._fields_ordered: if not fields or field in fields: try: setattr(self, field, self._reload(field, obj[field])) except KeyError: # If field is removed from the database while the object # is in memory, a reload would cause a KeyError # i.e. obj.update(unset__field=1) followed by obj.reload() delattr(self, field) # BUG FIX BY US HERE: if not fields: self._changed_fields = obj._changed_fields else: for field in fields: field = self._db_field_map.get(field, field) if field in self._changed_fields: self._changed_fields.remove(field) self._created = False return self
[ "Reloads", "all", "attributes", "from", "the", "database", ".", ":", "param", "fields", ":", "(", "optional", ")", "args", "list", "of", "fields", "to", "reload", ":", "param", "max_depth", ":", "(", "optional", ")", "depth", "of", "dereferencing", "to", "follow", "..", "versionadded", "::", "0", ".", "1", ".", "2", "..", "versionchanged", "::", "0", ".", "6", "Now", "chainable", "..", "versionchanged", "::", "0", ".", "9", "Can", "provide", "specific", "fields", "to", "reload" ]
frascoweb/frasco-models
python
https://github.com/frascoweb/frasco-models/blob/f7c1e14424cadf3dc07c2bd81cc32b0fd046ccba/frasco_models/backends/mongoengine.py#L45-L90
[ "def", "reload", "(", "self", ",", "*", "fields", ",", "*", "*", "kwargs", ")", ":", "max_depth", "=", "1", "if", "fields", "and", "isinstance", "(", "fields", "[", "0", "]", ",", "int", ")", ":", "max_depth", "=", "fields", "[", "0", "]", "fields", "=", "fields", "[", "1", ":", "]", "elif", "\"max_depth\"", "in", "kwargs", ":", "max_depth", "=", "kwargs", "[", "\"max_depth\"", "]", "if", "not", "self", ".", "pk", ":", "raise", "self", ".", "DoesNotExist", "(", "\"Document does not exist\"", ")", "obj", "=", "self", ".", "_qs", ".", "read_preference", "(", "ReadPreference", ".", "PRIMARY", ")", ".", "filter", "(", "*", "*", "self", ".", "_object_key", ")", ".", "only", "(", "*", "fields", ")", ".", "limit", "(", "1", ")", ".", "select_related", "(", "max_depth", "=", "max_depth", ")", "if", "obj", ":", "obj", "=", "obj", "[", "0", "]", "else", ":", "raise", "self", ".", "DoesNotExist", "(", "\"Document does not exist\"", ")", "for", "field", "in", "self", ".", "_fields_ordered", ":", "if", "not", "fields", "or", "field", "in", "fields", ":", "try", ":", "setattr", "(", "self", ",", "field", ",", "self", ".", "_reload", "(", "field", ",", "obj", "[", "field", "]", ")", ")", "except", "KeyError", ":", "# If field is removed from the database while the object", "# is in memory, a reload would cause a KeyError", "# i.e. obj.update(unset__field=1) followed by obj.reload()", "delattr", "(", "self", ",", "field", ")", "# BUG FIX BY US HERE:", "if", "not", "fields", ":", "self", ".", "_changed_fields", "=", "obj", ".", "_changed_fields", "else", ":", "for", "field", "in", "fields", ":", "field", "=", "self", ".", "_db_field_map", ".", "get", "(", "field", ",", "field", ")", "if", "field", "in", "self", ".", "_changed_fields", ":", "self", ".", "_changed_fields", ".", "remove", "(", "field", ")", "self", ".", "_created", "=", "False", "return", "self" ]
f7c1e14424cadf3dc07c2bd81cc32b0fd046ccba
valid
pdf2png
Uses `ImageMagick <http://www.imagemagick.org/>`_ to convert an input *file_in* pdf to a *file_out* png. (Untested with other formats.) Parameters ---------- file_in : str The path to the pdf file to be converted. file_out : str The path to the png file to be written.
scisalt/imageprocess/pdf2png.py
def pdf2png(file_in, file_out): """ Uses `ImageMagick <http://www.imagemagick.org/>`_ to convert an input *file_in* pdf to a *file_out* png. (Untested with other formats.) Parameters ---------- file_in : str The path to the pdf file to be converted. file_out : str The path to the png file to be written. """ command = 'convert -display 37.5 {} -resize 600 -append {}'.format(file_in, file_out) _subprocess.call(_shlex.split(command))
def pdf2png(file_in, file_out): """ Uses `ImageMagick <http://www.imagemagick.org/>`_ to convert an input *file_in* pdf to a *file_out* png. (Untested with other formats.) Parameters ---------- file_in : str The path to the pdf file to be converted. file_out : str The path to the png file to be written. """ command = 'convert -display 37.5 {} -resize 600 -append {}'.format(file_in, file_out) _subprocess.call(_shlex.split(command))
[ "Uses", "ImageMagick", "<http", ":", "//", "www", ".", "imagemagick", ".", "org", "/", ">", "_", "to", "convert", "an", "input", "*", "file_in", "*", "pdf", "to", "a", "*", "file_out", "*", "png", ".", "(", "Untested", "with", "other", "formats", ".", ")" ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/imageprocess/pdf2png.py#L6-L19
[ "def", "pdf2png", "(", "file_in", ",", "file_out", ")", ":", "command", "=", "'convert -display 37.5 {} -resize 600 -append {}'", ".", "format", "(", "file_in", ",", "file_out", ")", "_subprocess", ".", "call", "(", "_shlex", ".", "split", "(", "command", ")", ")" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
Users.get_user
Returns user profile data. http://dev.wheniwork.com/#get-existing-user
uw_wheniwork/users.py
def get_user(self, user_id): """ Returns user profile data. http://dev.wheniwork.com/#get-existing-user """ url = "/2/users/%s" % user_id return self.user_from_json(self._get_resource(url)["user"])
def get_user(self, user_id): """ Returns user profile data. http://dev.wheniwork.com/#get-existing-user """ url = "/2/users/%s" % user_id return self.user_from_json(self._get_resource(url)["user"])
[ "Returns", "user", "profile", "data", "." ]
uw-it-cte/uw-restclients-wheniwork
python
https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/users.py#L8-L16
[ "def", "get_user", "(", "self", ",", "user_id", ")", ":", "url", "=", "\"/2/users/%s\"", "%", "user_id", "return", "self", ".", "user_from_json", "(", "self", ".", "_get_resource", "(", "url", ")", "[", "\"user\"", "]", ")" ]
0d3ca09d5bbe808fec12e5f943596570d33a1731
valid
Users.get_users
Returns a list of users. http://dev.wheniwork.com/#listing-users
uw_wheniwork/users.py
def get_users(self, params={}): """ Returns a list of users. http://dev.wheniwork.com/#listing-users """ param_list = [(k, params[k]) for k in sorted(params)] url = "/2/users/?%s" % urlencode(param_list) data = self._get_resource(url) users = [] for entry in data["users"]: users.append(self.user_from_json(entry)) return users
def get_users(self, params={}): """ Returns a list of users. http://dev.wheniwork.com/#listing-users """ param_list = [(k, params[k]) for k in sorted(params)] url = "/2/users/?%s" % urlencode(param_list) data = self._get_resource(url) users = [] for entry in data["users"]: users.append(self.user_from_json(entry)) return users
[ "Returns", "a", "list", "of", "users", "." ]
uw-it-cte/uw-restclients-wheniwork
python
https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/users.py#L18-L32
[ "def", "get_users", "(", "self", ",", "params", "=", "{", "}", ")", ":", "param_list", "=", "[", "(", "k", ",", "params", "[", "k", "]", ")", "for", "k", "in", "sorted", "(", "params", ")", "]", "url", "=", "\"/2/users/?%s\"", "%", "urlencode", "(", "param_list", ")", "data", "=", "self", ".", "_get_resource", "(", "url", ")", "users", "=", "[", "]", "for", "entry", "in", "data", "[", "\"users\"", "]", ":", "users", ".", "append", "(", "self", ".", "user_from_json", "(", "entry", ")", ")", "return", "users" ]
0d3ca09d5bbe808fec12e5f943596570d33a1731
valid
_setVirtualEnv
Attempt to set the virtualenv activate command, if it hasn't been specified.
paved/util.py
def _setVirtualEnv(): """Attempt to set the virtualenv activate command, if it hasn't been specified. """ try: activate = options.virtualenv.activate_cmd except AttributeError: activate = None if activate is None: virtualenv = path(os.environ.get('VIRTUAL_ENV', '')) if not virtualenv: virtualenv = options.paved.cwd else: virtualenv = path(virtualenv) activate = virtualenv / 'bin' / 'activate' if activate.exists(): info('Using default virtualenv at %s' % activate) options.setdotted('virtualenv.activate_cmd', 'source %s' % activate)
def _setVirtualEnv(): """Attempt to set the virtualenv activate command, if it hasn't been specified. """ try: activate = options.virtualenv.activate_cmd except AttributeError: activate = None if activate is None: virtualenv = path(os.environ.get('VIRTUAL_ENV', '')) if not virtualenv: virtualenv = options.paved.cwd else: virtualenv = path(virtualenv) activate = virtualenv / 'bin' / 'activate' if activate.exists(): info('Using default virtualenv at %s' % activate) options.setdotted('virtualenv.activate_cmd', 'source %s' % activate)
[ "Attempt", "to", "set", "the", "virtualenv", "activate", "command", "if", "it", "hasn", "t", "been", "specified", "." ]
eykd/paved
python
https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/util.py#L14-L33
[ "def", "_setVirtualEnv", "(", ")", ":", "try", ":", "activate", "=", "options", ".", "virtualenv", ".", "activate_cmd", "except", "AttributeError", ":", "activate", "=", "None", "if", "activate", "is", "None", ":", "virtualenv", "=", "path", "(", "os", ".", "environ", ".", "get", "(", "'VIRTUAL_ENV'", ",", "''", ")", ")", "if", "not", "virtualenv", ":", "virtualenv", "=", "options", ".", "paved", ".", "cwd", "else", ":", "virtualenv", "=", "path", "(", "virtualenv", ")", "activate", "=", "virtualenv", "/", "'bin'", "/", "'activate'", "if", "activate", ".", "exists", "(", ")", ":", "info", "(", "'Using default virtualenv at %s'", "%", "activate", ")", "options", ".", "setdotted", "(", "'virtualenv.activate_cmd'", ",", "'source %s'", "%", "activate", ")" ]
f04f8a4248c571f3d5ce882b325884a3e5d80203
valid
shv
Run the given command inside the virtual environment, if available:
paved/util.py
def shv(command, capture=False, ignore_error=False, cwd=None): """Run the given command inside the virtual environment, if available: """ _setVirtualEnv() try: command = "%s; %s" % (options.virtualenv.activate_cmd, command) except AttributeError: pass return bash(command, capture=capture, ignore_error=ignore_error, cwd=cwd)
def shv(command, capture=False, ignore_error=False, cwd=None): """Run the given command inside the virtual environment, if available: """ _setVirtualEnv() try: command = "%s; %s" % (options.virtualenv.activate_cmd, command) except AttributeError: pass return bash(command, capture=capture, ignore_error=ignore_error, cwd=cwd)
[ "Run", "the", "given", "command", "inside", "the", "virtual", "environment", "if", "available", ":" ]
eykd/paved
python
https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/util.py#L85-L93
[ "def", "shv", "(", "command", ",", "capture", "=", "False", ",", "ignore_error", "=", "False", ",", "cwd", "=", "None", ")", ":", "_setVirtualEnv", "(", ")", "try", ":", "command", "=", "\"%s; %s\"", "%", "(", "options", ".", "virtualenv", ".", "activate_cmd", ",", "command", ")", "except", "AttributeError", ":", "pass", "return", "bash", "(", "command", ",", "capture", "=", "capture", ",", "ignore_error", "=", "ignore_error", ",", "cwd", "=", "cwd", ")" ]
f04f8a4248c571f3d5ce882b325884a3e5d80203
valid
update
Recursively update the destination dict-like object with the source dict-like object. Useful for merging options and Bunches together! Based on: http://code.activestate.com/recipes/499335-recursively-update-a-dictionary-without-hitting-py/#c1
paved/util.py
def update(dst, src): """Recursively update the destination dict-like object with the source dict-like object. Useful for merging options and Bunches together! Based on: http://code.activestate.com/recipes/499335-recursively-update-a-dictionary-without-hitting-py/#c1 """ stack = [(dst, src)] def isdict(o): return hasattr(o, 'keys') while stack: current_dst, current_src = stack.pop() for key in current_src: if key not in current_dst: current_dst[key] = current_src[key] else: if isdict(current_src[key]) and isdict(current_dst[key]): stack.append((current_dst[key], current_src[key])) else: current_dst[key] = current_src[key] return dst
def update(dst, src): """Recursively update the destination dict-like object with the source dict-like object. Useful for merging options and Bunches together! Based on: http://code.activestate.com/recipes/499335-recursively-update-a-dictionary-without-hitting-py/#c1 """ stack = [(dst, src)] def isdict(o): return hasattr(o, 'keys') while stack: current_dst, current_src = stack.pop() for key in current_src: if key not in current_dst: current_dst[key] = current_src[key] else: if isdict(current_src[key]) and isdict(current_dst[key]): stack.append((current_dst[key], current_src[key])) else: current_dst[key] = current_src[key] return dst
[ "Recursively", "update", "the", "destination", "dict", "-", "like", "object", "with", "the", "source", "dict", "-", "like", "object", "." ]
eykd/paved
python
https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/util.py#L96-L119
[ "def", "update", "(", "dst", ",", "src", ")", ":", "stack", "=", "[", "(", "dst", ",", "src", ")", "]", "def", "isdict", "(", "o", ")", ":", "return", "hasattr", "(", "o", ",", "'keys'", ")", "while", "stack", ":", "current_dst", ",", "current_src", "=", "stack", ".", "pop", "(", ")", "for", "key", "in", "current_src", ":", "if", "key", "not", "in", "current_dst", ":", "current_dst", "[", "key", "]", "=", "current_src", "[", "key", "]", "else", ":", "if", "isdict", "(", "current_src", "[", "key", "]", ")", "and", "isdict", "(", "current_dst", "[", "key", "]", ")", ":", "stack", ".", "append", "(", "(", "current_dst", "[", "key", "]", ",", "current_src", "[", "key", "]", ")", ")", "else", ":", "current_dst", "[", "key", "]", "=", "current_src", "[", "key", "]", "return", "dst" ]
f04f8a4248c571f3d5ce882b325884a3e5d80203
valid
pip_install
Send the given arguments to `pip install`.
paved/util.py
def pip_install(*args): """Send the given arguments to `pip install`. """ download_cache = ('--download-cache=%s ' % options.paved.pip.download_cache) if options.paved.pip.download_cache else '' shv('pip install %s%s' % (download_cache, ' '.join(args)))
def pip_install(*args): """Send the given arguments to `pip install`. """ download_cache = ('--download-cache=%s ' % options.paved.pip.download_cache) if options.paved.pip.download_cache else '' shv('pip install %s%s' % (download_cache, ' '.join(args)))
[ "Send", "the", "given", "arguments", "to", "pip", "install", "." ]
eykd/paved
python
https://github.com/eykd/paved/blob/f04f8a4248c571f3d5ce882b325884a3e5d80203/paved/util.py#L132-L136
[ "def", "pip_install", "(", "*", "args", ")", ":", "download_cache", "=", "(", "'--download-cache=%s '", "%", "options", ".", "paved", ".", "pip", ".", "download_cache", ")", "if", "options", ".", "paved", ".", "pip", ".", "download_cache", "else", "''", "shv", "(", "'pip install %s%s'", "%", "(", "download_cache", ",", "' '", ".", "join", "(", "args", ")", ")", ")" ]
f04f8a4248c571f3d5ce882b325884a3e5d80203
valid
WhenIWork._get_resource
When I Work GET method. Return representation of the requested resource.
uw_wheniwork/__init__.py
def _get_resource(self, url, data_key=None): """ When I Work GET method. Return representation of the requested resource. """ headers = {"Accept": "application/json"} if self.token: headers["W-Token"] = "%s" % self.token response = WhenIWork_DAO().getURL(url, headers) if response.status != 200: raise DataFailureException(url, response.status, response.data) return json.loads(response.data)
def _get_resource(self, url, data_key=None): """ When I Work GET method. Return representation of the requested resource. """ headers = {"Accept": "application/json"} if self.token: headers["W-Token"] = "%s" % self.token response = WhenIWork_DAO().getURL(url, headers) if response.status != 200: raise DataFailureException(url, response.status, response.data) return json.loads(response.data)
[ "When", "I", "Work", "GET", "method", ".", "Return", "representation", "of", "the", "requested", "resource", "." ]
uw-it-cte/uw-restclients-wheniwork
python
https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/__init__.py#L26-L39
[ "def", "_get_resource", "(", "self", ",", "url", ",", "data_key", "=", "None", ")", ":", "headers", "=", "{", "\"Accept\"", ":", "\"application/json\"", "}", "if", "self", ".", "token", ":", "headers", "[", "\"W-Token\"", "]", "=", "\"%s\"", "%", "self", ".", "token", "response", "=", "WhenIWork_DAO", "(", ")", ".", "getURL", "(", "url", ",", "headers", ")", "if", "response", ".", "status", "!=", "200", ":", "raise", "DataFailureException", "(", "url", ",", "response", ".", "status", ",", "response", ".", "data", ")", "return", "json", ".", "loads", "(", "response", ".", "data", ")" ]
0d3ca09d5bbe808fec12e5f943596570d33a1731
valid
WhenIWork._put_resource
When I Work PUT method.
uw_wheniwork/__init__.py
def _put_resource(self, url, body): """ When I Work PUT method. """ headers = {"Content-Type": "application/json", "Accept": "application/json"} if self.token: headers["W-Token"] = "%s" % self.token response = WhenIWork_DAO().putURL(url, headers, json.dumps(body)) if not (response.status == 200 or response.status == 201 or response.status == 204): raise DataFailureException(url, response.status, response.data) return json.loads(response.data)
def _put_resource(self, url, body): """ When I Work PUT method. """ headers = {"Content-Type": "application/json", "Accept": "application/json"} if self.token: headers["W-Token"] = "%s" % self.token response = WhenIWork_DAO().putURL(url, headers, json.dumps(body)) if not (response.status == 200 or response.status == 201 or response.status == 204): raise DataFailureException(url, response.status, response.data) return json.loads(response.data)
[ "When", "I", "Work", "PUT", "method", "." ]
uw-it-cte/uw-restclients-wheniwork
python
https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/__init__.py#L41-L55
[ "def", "_put_resource", "(", "self", ",", "url", ",", "body", ")", ":", "headers", "=", "{", "\"Content-Type\"", ":", "\"application/json\"", ",", "\"Accept\"", ":", "\"application/json\"", "}", "if", "self", ".", "token", ":", "headers", "[", "\"W-Token\"", "]", "=", "\"%s\"", "%", "self", ".", "token", "response", "=", "WhenIWork_DAO", "(", ")", ".", "putURL", "(", "url", ",", "headers", ",", "json", ".", "dumps", "(", "body", ")", ")", "if", "not", "(", "response", ".", "status", "==", "200", "or", "response", ".", "status", "==", "201", "or", "response", ".", "status", "==", "204", ")", ":", "raise", "DataFailureException", "(", "url", ",", "response", ".", "status", ",", "response", ".", "data", ")", "return", "json", ".", "loads", "(", "response", ".", "data", ")" ]
0d3ca09d5bbe808fec12e5f943596570d33a1731
valid
WhenIWork._post_resource
When I Work POST method.
uw_wheniwork/__init__.py
def _post_resource(self, url, body): """ When I Work POST method. """ headers = {"Content-Type": "application/json", "Accept": "application/json"} if self.token: headers["W-Token"] = "%s" % self.token response = WhenIWork_DAO().postURL(url, headers, json.dumps(body)) if not (response.status == 200 or response.status == 204): raise DataFailureException(url, response.status, response.data) return json.loads(response.data)
def _post_resource(self, url, body): """ When I Work POST method. """ headers = {"Content-Type": "application/json", "Accept": "application/json"} if self.token: headers["W-Token"] = "%s" % self.token response = WhenIWork_DAO().postURL(url, headers, json.dumps(body)) if not (response.status == 200 or response.status == 204): raise DataFailureException(url, response.status, response.data) return json.loads(response.data)
[ "When", "I", "Work", "POST", "method", "." ]
uw-it-cte/uw-restclients-wheniwork
python
https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/__init__.py#L57-L70
[ "def", "_post_resource", "(", "self", ",", "url", ",", "body", ")", ":", "headers", "=", "{", "\"Content-Type\"", ":", "\"application/json\"", ",", "\"Accept\"", ":", "\"application/json\"", "}", "if", "self", ".", "token", ":", "headers", "[", "\"W-Token\"", "]", "=", "\"%s\"", "%", "self", ".", "token", "response", "=", "WhenIWork_DAO", "(", ")", ".", "postURL", "(", "url", ",", "headers", ",", "json", ".", "dumps", "(", "body", ")", ")", "if", "not", "(", "response", ".", "status", "==", "200", "or", "response", ".", "status", "==", "204", ")", ":", "raise", "DataFailureException", "(", "url", ",", "response", ".", "status", ",", "response", ".", "data", ")", "return", "json", ".", "loads", "(", "response", ".", "data", ")" ]
0d3ca09d5bbe808fec12e5f943596570d33a1731
valid
WhenIWork._delete_resource
When I Work DELETE method.
uw_wheniwork/__init__.py
def _delete_resource(self, url): """ When I Work DELETE method. """ headers = {"Content-Type": "application/json", "Accept": "application/json"} if self.token: headers["W-Token"] = "%s" % self.token response = WhenIWork_DAO().deleteURL(url, headers) if not (response.status == 200 or response.status == 201 or response.status == 204): raise DataFailureException(url, response.status, response.data) return json.loads(response.data)
def _delete_resource(self, url): """ When I Work DELETE method. """ headers = {"Content-Type": "application/json", "Accept": "application/json"} if self.token: headers["W-Token"] = "%s" % self.token response = WhenIWork_DAO().deleteURL(url, headers) if not (response.status == 200 or response.status == 201 or response.status == 204): raise DataFailureException(url, response.status, response.data) return json.loads(response.data)
[ "When", "I", "Work", "DELETE", "method", "." ]
uw-it-cte/uw-restclients-wheniwork
python
https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/__init__.py#L72-L86
[ "def", "_delete_resource", "(", "self", ",", "url", ")", ":", "headers", "=", "{", "\"Content-Type\"", ":", "\"application/json\"", ",", "\"Accept\"", ":", "\"application/json\"", "}", "if", "self", ".", "token", ":", "headers", "[", "\"W-Token\"", "]", "=", "\"%s\"", "%", "self", ".", "token", "response", "=", "WhenIWork_DAO", "(", ")", ".", "deleteURL", "(", "url", ",", "headers", ")", "if", "not", "(", "response", ".", "status", "==", "200", "or", "response", ".", "status", "==", "201", "or", "response", ".", "status", "==", "204", ")", ":", "raise", "DataFailureException", "(", "url", ",", "response", ".", "status", ",", "response", ".", "data", ")", "return", "json", ".", "loads", "(", "response", ".", "data", ")" ]
0d3ca09d5bbe808fec12e5f943596570d33a1731
valid
Shifts.get_shifts
List shifts http://dev.wheniwork.com/#listing-shifts
uw_wheniwork/shifts.py
def get_shifts(self, params={}): """ List shifts http://dev.wheniwork.com/#listing-shifts """ param_list = [(k, params[k]) for k in sorted(params)] url = "/2/shifts/?%s" % urlencode(param_list) data = self._get_resource(url) shifts = [] locations = {} sites = {} positions = {} users = {} for entry in data.get("locations", []): location = Locations.location_from_json(entry) locations[location.location_id] = location for entry in data.get("sites", []): site = Sites.site_from_json(entry) sites[site.site_id] = site for entry in data.get("positions", []): position = Positions.position_from_json(entry) positions[position.position_id] = position for entry in data.get("users", []): user = Users.user_from_json(entry) users[user.user_id] = user for entry in data["shifts"]: shift = self.shift_from_json(entry) shifts.append(shift) for shift in shifts: shift.location = locations.get(shift.location_id, None) shift.site = sites.get(shift.site_id, None) shift.position = positions.get(shift.position_id, None) shift.user = users.get(shift.user_id, None) return shifts
def get_shifts(self, params={}): """ List shifts http://dev.wheniwork.com/#listing-shifts """ param_list = [(k, params[k]) for k in sorted(params)] url = "/2/shifts/?%s" % urlencode(param_list) data = self._get_resource(url) shifts = [] locations = {} sites = {} positions = {} users = {} for entry in data.get("locations", []): location = Locations.location_from_json(entry) locations[location.location_id] = location for entry in data.get("sites", []): site = Sites.site_from_json(entry) sites[site.site_id] = site for entry in data.get("positions", []): position = Positions.position_from_json(entry) positions[position.position_id] = position for entry in data.get("users", []): user = Users.user_from_json(entry) users[user.user_id] = user for entry in data["shifts"]: shift = self.shift_from_json(entry) shifts.append(shift) for shift in shifts: shift.location = locations.get(shift.location_id, None) shift.site = sites.get(shift.site_id, None) shift.position = positions.get(shift.position_id, None) shift.user = users.get(shift.user_id, None) return shifts
[ "List", "shifts" ]
uw-it-cte/uw-restclients-wheniwork
python
https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/shifts.py#L13-L50
[ "def", "get_shifts", "(", "self", ",", "params", "=", "{", "}", ")", ":", "param_list", "=", "[", "(", "k", ",", "params", "[", "k", "]", ")", "for", "k", "in", "sorted", "(", "params", ")", "]", "url", "=", "\"/2/shifts/?%s\"", "%", "urlencode", "(", "param_list", ")", "data", "=", "self", ".", "_get_resource", "(", "url", ")", "shifts", "=", "[", "]", "locations", "=", "{", "}", "sites", "=", "{", "}", "positions", "=", "{", "}", "users", "=", "{", "}", "for", "entry", "in", "data", ".", "get", "(", "\"locations\"", ",", "[", "]", ")", ":", "location", "=", "Locations", ".", "location_from_json", "(", "entry", ")", "locations", "[", "location", ".", "location_id", "]", "=", "location", "for", "entry", "in", "data", ".", "get", "(", "\"sites\"", ",", "[", "]", ")", ":", "site", "=", "Sites", ".", "site_from_json", "(", "entry", ")", "sites", "[", "site", ".", "site_id", "]", "=", "site", "for", "entry", "in", "data", ".", "get", "(", "\"positions\"", ",", "[", "]", ")", ":", "position", "=", "Positions", ".", "position_from_json", "(", "entry", ")", "positions", "[", "position", ".", "position_id", "]", "=", "position", "for", "entry", "in", "data", ".", "get", "(", "\"users\"", ",", "[", "]", ")", ":", "user", "=", "Users", ".", "user_from_json", "(", "entry", ")", "users", "[", "user", ".", "user_id", "]", "=", "user", "for", "entry", "in", "data", "[", "\"shifts\"", "]", ":", "shift", "=", "self", ".", "shift_from_json", "(", "entry", ")", "shifts", ".", "append", "(", "shift", ")", "for", "shift", "in", "shifts", ":", "shift", ".", "location", "=", "locations", ".", "get", "(", "shift", ".", "location_id", ",", "None", ")", "shift", ".", "site", "=", "sites", ".", "get", "(", "shift", ".", "site_id", ",", "None", ")", "shift", ".", "position", "=", "positions", ".", "get", "(", "shift", ".", "position_id", ",", "None", ")", "shift", ".", "user", "=", "users", ".", "get", "(", "shift", ".", "user_id", ",", "None", ")", "return", "shifts" ]
0d3ca09d5bbe808fec12e5f943596570d33a1731
valid
Shifts.create_shift
Creates a shift http://dev.wheniwork.com/#create/update-shift
uw_wheniwork/shifts.py
def create_shift(self, params={}): """ Creates a shift http://dev.wheniwork.com/#create/update-shift """ url = "/2/shifts/" body = params data = self._post_resource(url, body) shift = self.shift_from_json(data["shift"]) return shift
def create_shift(self, params={}): """ Creates a shift http://dev.wheniwork.com/#create/update-shift """ url = "/2/shifts/" body = params data = self._post_resource(url, body) shift = self.shift_from_json(data["shift"]) return shift
[ "Creates", "a", "shift" ]
uw-it-cte/uw-restclients-wheniwork
python
https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/shifts.py#L52-L64
[ "def", "create_shift", "(", "self", ",", "params", "=", "{", "}", ")", ":", "url", "=", "\"/2/shifts/\"", "body", "=", "params", "data", "=", "self", ".", "_post_resource", "(", "url", ",", "body", ")", "shift", "=", "self", ".", "shift_from_json", "(", "data", "[", "\"shift\"", "]", ")", "return", "shift" ]
0d3ca09d5bbe808fec12e5f943596570d33a1731
valid
Shifts.delete_shifts
Delete existing shifts. http://dev.wheniwork.com/#delete-shift
uw_wheniwork/shifts.py
def delete_shifts(self, shifts): """ Delete existing shifts. http://dev.wheniwork.com/#delete-shift """ url = "/2/shifts/?%s" % urlencode( {'ids': ",".join(str(s) for s in shifts)}) data = self._delete_resource(url) return data
def delete_shifts(self, shifts): """ Delete existing shifts. http://dev.wheniwork.com/#delete-shift """ url = "/2/shifts/?%s" % urlencode( {'ids': ",".join(str(s) for s in shifts)}) data = self._delete_resource(url) return data
[ "Delete", "existing", "shifts", "." ]
uw-it-cte/uw-restclients-wheniwork
python
https://github.com/uw-it-cte/uw-restclients-wheniwork/blob/0d3ca09d5bbe808fec12e5f943596570d33a1731/uw_wheniwork/shifts.py#L66-L77
[ "def", "delete_shifts", "(", "self", ",", "shifts", ")", ":", "url", "=", "\"/2/shifts/?%s\"", "%", "urlencode", "(", "{", "'ids'", ":", "\",\"", ".", "join", "(", "str", "(", "s", ")", "for", "s", "in", "shifts", ")", "}", ")", "data", "=", "self", ".", "_delete_resource", "(", "url", ")", "return", "data" ]
0d3ca09d5bbe808fec12e5f943596570d33a1731
valid
EventManager.delete_past_events
Removes old events. This is provided largely as a convenience for maintenance purposes (daily_cleanup). if an Event has passed by more than X days as defined by Lapsed and has no related special events it will be deleted to free up the event name and remove clutter. For best results, set this up to run regularly as a cron job.
build/lib/happenings/models.py
def delete_past_events(self): """ Removes old events. This is provided largely as a convenience for maintenance purposes (daily_cleanup). if an Event has passed by more than X days as defined by Lapsed and has no related special events it will be deleted to free up the event name and remove clutter. For best results, set this up to run regularly as a cron job. """ lapsed = datetime.datetime.now() - datetime.timedelta(days=90) for event in self.filter(start_date__lte=lapsed, featured=0, recap=''): event.delete()
def delete_past_events(self): """ Removes old events. This is provided largely as a convenience for maintenance purposes (daily_cleanup). if an Event has passed by more than X days as defined by Lapsed and has no related special events it will be deleted to free up the event name and remove clutter. For best results, set this up to run regularly as a cron job. """ lapsed = datetime.datetime.now() - datetime.timedelta(days=90) for event in self.filter(start_date__lte=lapsed, featured=0, recap=''): event.delete()
[ "Removes", "old", "events", ".", "This", "is", "provided", "largely", "as", "a", "convenience", "for", "maintenance", "purposes", "(", "daily_cleanup", ")", ".", "if", "an", "Event", "has", "passed", "by", "more", "than", "X", "days", "as", "defined", "by", "Lapsed", "and", "has", "no", "related", "special", "events", "it", "will", "be", "deleted", "to", "free", "up", "the", "event", "name", "and", "remove", "clutter", ".", "For", "best", "results", "set", "this", "up", "to", "run", "regularly", "as", "a", "cron", "job", "." ]
tBaxter/tango-happenings
python
https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/models.py#L56-L66
[ "def", "delete_past_events", "(", "self", ")", ":", "lapsed", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "-", "datetime", ".", "timedelta", "(", "days", "=", "90", ")", "for", "event", "in", "self", ".", "filter", "(", "start_date__lte", "=", "lapsed", ",", "featured", "=", "0", ",", "recap", "=", "''", ")", ":", "event", ".", "delete", "(", ")" ]
cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2
valid
Event.recently_ended
Determines if event ended recently (within 5 days). Useful for attending list.
build/lib/happenings/models.py
def recently_ended(self): """ Determines if event ended recently (within 5 days). Useful for attending list. """ if self.ended(): end_date = self.end_date if self.end_date else self.start_date if end_date >= offset.date(): return True
def recently_ended(self): """ Determines if event ended recently (within 5 days). Useful for attending list. """ if self.ended(): end_date = self.end_date if self.end_date else self.start_date if end_date >= offset.date(): return True
[ "Determines", "if", "event", "ended", "recently", "(", "within", "5", "days", ")", ".", "Useful", "for", "attending", "list", "." ]
tBaxter/tango-happenings
python
https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/models.py#L159-L167
[ "def", "recently_ended", "(", "self", ")", ":", "if", "self", ".", "ended", "(", ")", ":", "end_date", "=", "self", ".", "end_date", "if", "self", ".", "end_date", "else", "self", ".", "start_date", "if", "end_date", ">=", "offset", ".", "date", "(", ")", ":", "return", "True" ]
cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2
valid
Event.all_comments
Returns combined list of event and update comments.
build/lib/happenings/models.py
def all_comments(self): """ Returns combined list of event and update comments. """ ctype = ContentType.objects.get(app_label__exact="happenings", model__exact='event') update_ctype = ContentType.objects.get(app_label__exact="happenings", model__exact='update') update_ids = self.update_set.values_list('id', flat=True) return Comment.objects.filter( Q(content_type=ctype.id, object_pk=self.id) | Q(content_type=update_ctype.id, object_pk__in=update_ids) )
def all_comments(self): """ Returns combined list of event and update comments. """ ctype = ContentType.objects.get(app_label__exact="happenings", model__exact='event') update_ctype = ContentType.objects.get(app_label__exact="happenings", model__exact='update') update_ids = self.update_set.values_list('id', flat=True) return Comment.objects.filter( Q(content_type=ctype.id, object_pk=self.id) | Q(content_type=update_ctype.id, object_pk__in=update_ids) )
[ "Returns", "combined", "list", "of", "event", "and", "update", "comments", "." ]
tBaxter/tango-happenings
python
https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/models.py#L186-L197
[ "def", "all_comments", "(", "self", ")", ":", "ctype", "=", "ContentType", ".", "objects", ".", "get", "(", "app_label__exact", "=", "\"happenings\"", ",", "model__exact", "=", "'event'", ")", "update_ctype", "=", "ContentType", ".", "objects", ".", "get", "(", "app_label__exact", "=", "\"happenings\"", ",", "model__exact", "=", "'update'", ")", "update_ids", "=", "self", ".", "update_set", ".", "values_list", "(", "'id'", ",", "flat", "=", "True", ")", "return", "Comment", ".", "objects", ".", "filter", "(", "Q", "(", "content_type", "=", "ctype", ".", "id", ",", "object_pk", "=", "self", ".", "id", ")", "|", "Q", "(", "content_type", "=", "update_ctype", ".", "id", ",", "object_pk__in", "=", "update_ids", ")", ")" ]
cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2
valid
Event.get_all_images
Returns chained list of event and update images.
build/lib/happenings/models.py
def get_all_images(self): """ Returns chained list of event and update images. """ self_imgs = self.image_set.all() update_ids = self.update_set.values_list('id', flat=True) u_images = UpdateImage.objects.filter(update__id__in=update_ids) return list(chain(self_imgs, u_images))
def get_all_images(self): """ Returns chained list of event and update images. """ self_imgs = self.image_set.all() update_ids = self.update_set.values_list('id', flat=True) u_images = UpdateImage.objects.filter(update__id__in=update_ids) return list(chain(self_imgs, u_images))
[ "Returns", "chained", "list", "of", "event", "and", "update", "images", "." ]
tBaxter/tango-happenings
python
https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/models.py#L217-L225
[ "def", "get_all_images", "(", "self", ")", ":", "self_imgs", "=", "self", ".", "image_set", ".", "all", "(", ")", "update_ids", "=", "self", ".", "update_set", ".", "values_list", "(", "'id'", ",", "flat", "=", "True", ")", "u_images", "=", "UpdateImage", ".", "objects", ".", "filter", "(", "update__id__in", "=", "update_ids", ")", "return", "list", "(", "chain", "(", "self_imgs", ",", "u_images", ")", ")" ]
cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2
valid
Event.get_all_images_count
Gets count of all images from both event and updates.
build/lib/happenings/models.py
def get_all_images_count(self): """ Gets count of all images from both event and updates. """ self_imgs = self.image_set.count() update_ids = self.update_set.values_list('id', flat=True) u_images = UpdateImage.objects.filter(update__id__in=update_ids).count() count = self_imgs + u_images return count
def get_all_images_count(self): """ Gets count of all images from both event and updates. """ self_imgs = self.image_set.count() update_ids = self.update_set.values_list('id', flat=True) u_images = UpdateImage.objects.filter(update__id__in=update_ids).count() count = self_imgs + u_images return count
[ "Gets", "count", "of", "all", "images", "from", "both", "event", "and", "updates", "." ]
tBaxter/tango-happenings
python
https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/models.py#L227-L236
[ "def", "get_all_images_count", "(", "self", ")", ":", "self_imgs", "=", "self", ".", "image_set", ".", "count", "(", ")", "update_ids", "=", "self", ".", "update_set", ".", "values_list", "(", "'id'", ",", "flat", "=", "True", ")", "u_images", "=", "UpdateImage", ".", "objects", ".", "filter", "(", "update__id__in", "=", "update_ids", ")", ".", "count", "(", ")", "count", "=", "self_imgs", "+", "u_images", "return", "count" ]
cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2
valid
Event.get_top_assets
Gets images and videos to populate top assets. Map is built separately.
build/lib/happenings/models.py
def get_top_assets(self): """ Gets images and videos to populate top assets. Map is built separately. """ images = self.get_all_images()[0:14] video = [] if supports_video: video = self.eventvideo_set.all()[0:10] return list(chain(images, video))[0:15]
def get_top_assets(self): """ Gets images and videos to populate top assets. Map is built separately. """ images = self.get_all_images()[0:14] video = [] if supports_video: video = self.eventvideo_set.all()[0:10] return list(chain(images, video))[0:15]
[ "Gets", "images", "and", "videos", "to", "populate", "top", "assets", "." ]
tBaxter/tango-happenings
python
https://github.com/tBaxter/tango-happenings/blob/cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2/build/lib/happenings/models.py#L238-L249
[ "def", "get_top_assets", "(", "self", ")", ":", "images", "=", "self", ".", "get_all_images", "(", ")", "[", "0", ":", "14", "]", "video", "=", "[", "]", "if", "supports_video", ":", "video", "=", "self", ".", "eventvideo_set", ".", "all", "(", ")", "[", "0", ":", "10", "]", "return", "list", "(", "chain", "(", "images", ",", "video", ")", ")", "[", "0", ":", "15", "]" ]
cb3c49ea39e0a6cef9c6ffb534c2fbf401139ba2
valid
plot_featured
Wrapper for matplotlib.pyplot.plot() / errorbar(). Takes options: * 'error': if true, use :func:`matplotlib.pyplot.errorbar` instead of :func:`matplotlib.pyplot.plot`. *\*args* and *\*\*kwargs* passed through here. * 'fig': figure to use. * 'figlabel': figure label. * 'legend': legend location. * 'toplabel': top label of plot. * 'xlabel': x-label of plot. * 'ylabel': y-label of plot.
scisalt/matplotlib/plot_featured.py
def plot_featured(*args, **kwargs): """ Wrapper for matplotlib.pyplot.plot() / errorbar(). Takes options: * 'error': if true, use :func:`matplotlib.pyplot.errorbar` instead of :func:`matplotlib.pyplot.plot`. *\*args* and *\*\*kwargs* passed through here. * 'fig': figure to use. * 'figlabel': figure label. * 'legend': legend location. * 'toplabel': top label of plot. * 'xlabel': x-label of plot. * 'ylabel': y-label of plot. """ # Strip off options specific to plot_featured toplabel = kwargs.pop('toplabel', None) xlabel = kwargs.pop('xlabel', None) ylabel = kwargs.pop('ylabel', None) legend = kwargs.pop('legend', None) error = kwargs.pop('error', None) # save = kwargs.pop('save', False) figlabel = kwargs.pop('figlabel', None) fig = kwargs.pop('fig', None) if figlabel is not None: fig = _figure(figlabel) elif fig is None: try: fig = _plt.gcf() except: fig = _plt.fig() # Pass everything else to plot if error is None: _plt.plot(*args, **kwargs) else: _plt.errorbar(*args, **kwargs) # Format plot as desired _addlabel(toplabel, xlabel, ylabel, fig=fig) if legend is not None: _plt.legend(legend) return fig
def plot_featured(*args, **kwargs): """ Wrapper for matplotlib.pyplot.plot() / errorbar(). Takes options: * 'error': if true, use :func:`matplotlib.pyplot.errorbar` instead of :func:`matplotlib.pyplot.plot`. *\*args* and *\*\*kwargs* passed through here. * 'fig': figure to use. * 'figlabel': figure label. * 'legend': legend location. * 'toplabel': top label of plot. * 'xlabel': x-label of plot. * 'ylabel': y-label of plot. """ # Strip off options specific to plot_featured toplabel = kwargs.pop('toplabel', None) xlabel = kwargs.pop('xlabel', None) ylabel = kwargs.pop('ylabel', None) legend = kwargs.pop('legend', None) error = kwargs.pop('error', None) # save = kwargs.pop('save', False) figlabel = kwargs.pop('figlabel', None) fig = kwargs.pop('fig', None) if figlabel is not None: fig = _figure(figlabel) elif fig is None: try: fig = _plt.gcf() except: fig = _plt.fig() # Pass everything else to plot if error is None: _plt.plot(*args, **kwargs) else: _plt.errorbar(*args, **kwargs) # Format plot as desired _addlabel(toplabel, xlabel, ylabel, fig=fig) if legend is not None: _plt.legend(legend) return fig
[ "Wrapper", "for", "matplotlib", ".", "pyplot", ".", "plot", "()", "/", "errorbar", "()", "." ]
joelfrederico/SciSalt
python
https://github.com/joelfrederico/SciSalt/blob/7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f/scisalt/matplotlib/plot_featured.py#L11-L55
[ "def", "plot_featured", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Strip off options specific to plot_featured", "toplabel", "=", "kwargs", ".", "pop", "(", "'toplabel'", ",", "None", ")", "xlabel", "=", "kwargs", ".", "pop", "(", "'xlabel'", ",", "None", ")", "ylabel", "=", "kwargs", ".", "pop", "(", "'ylabel'", ",", "None", ")", "legend", "=", "kwargs", ".", "pop", "(", "'legend'", ",", "None", ")", "error", "=", "kwargs", ".", "pop", "(", "'error'", ",", "None", ")", "# save = kwargs.pop('save', False)", "figlabel", "=", "kwargs", ".", "pop", "(", "'figlabel'", ",", "None", ")", "fig", "=", "kwargs", ".", "pop", "(", "'fig'", ",", "None", ")", "if", "figlabel", "is", "not", "None", ":", "fig", "=", "_figure", "(", "figlabel", ")", "elif", "fig", "is", "None", ":", "try", ":", "fig", "=", "_plt", ".", "gcf", "(", ")", "except", ":", "fig", "=", "_plt", ".", "fig", "(", ")", "# Pass everything else to plot", "if", "error", "is", "None", ":", "_plt", ".", "plot", "(", "*", "args", ",", "*", "*", "kwargs", ")", "else", ":", "_plt", ".", "errorbar", "(", "*", "args", ",", "*", "*", "kwargs", ")", "# Format plot as desired", "_addlabel", "(", "toplabel", ",", "xlabel", ",", "ylabel", ",", "fig", "=", "fig", ")", "if", "legend", "is", "not", "None", ":", "_plt", ".", "legend", "(", "legend", ")", "return", "fig" ]
7bf57c49c7dde0a8b0aa337fbd2fbd527ce7a67f
valid
Spinner.decorate
Decorated methods progress will be displayed to the user as a spinner. Mostly for slower functions that do some network IO.
tmc/ui/spinner.py
def decorate(msg="", waitmsg="Please wait"): """ Decorated methods progress will be displayed to the user as a spinner. Mostly for slower functions that do some network IO. """ def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): spin = Spinner(msg=msg, waitmsg=waitmsg) spin.start() a = None try: a = func(*args, **kwargs) except Exception as e: spin.msg = "Something went wrong: " spin.stop_spinning() spin.join() raise e spin.stop_spinning() spin.join() return a return wrapper return decorator
def decorate(msg="", waitmsg="Please wait"): """ Decorated methods progress will be displayed to the user as a spinner. Mostly for slower functions that do some network IO. """ def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): spin = Spinner(msg=msg, waitmsg=waitmsg) spin.start() a = None try: a = func(*args, **kwargs) except Exception as e: spin.msg = "Something went wrong: " spin.stop_spinning() spin.join() raise e spin.stop_spinning() spin.join() return a return wrapper return decorator
[ "Decorated", "methods", "progress", "will", "be", "displayed", "to", "the", "user", "as", "a", "spinner", ".", "Mostly", "for", "slower", "functions", "that", "do", "some", "network", "IO", "." ]
minttu/tmc.py
python
https://github.com/minttu/tmc.py/blob/212cfe1791a4aab4783f99b665cc32da6437f419/tmc/ui/spinner.py#L54-L78
[ "def", "decorate", "(", "msg", "=", "\"\"", ",", "waitmsg", "=", "\"Please wait\"", ")", ":", "def", "decorator", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "spin", "=", "Spinner", "(", "msg", "=", "msg", ",", "waitmsg", "=", "waitmsg", ")", "spin", ".", "start", "(", ")", "a", "=", "None", "try", ":", "a", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Exception", "as", "e", ":", "spin", ".", "msg", "=", "\"Something went wrong: \"", "spin", ".", "stop_spinning", "(", ")", "spin", ".", "join", "(", ")", "raise", "e", "spin", ".", "stop_spinning", "(", ")", "spin", ".", "join", "(", ")", "return", "a", "return", "wrapper", "return", "decorator" ]
212cfe1791a4aab4783f99b665cc32da6437f419