repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
thespacedoctor/qubits
qubits/results.py
calculate_fraction_of_sn_discovered
def calculate_fraction_of_sn_discovered( log, surveyCadenceSettings, snSurveyDiscoveryTimes, redshifts, peakAppMagList, snCampaignLengthList, extraSurveyConstraints, zmin, zmax): """ *Given a list of the snSurveyDiscoveryTimes calculate the...
python
def calculate_fraction_of_sn_discovered( log, surveyCadenceSettings, snSurveyDiscoveryTimes, redshifts, peakAppMagList, snCampaignLengthList, extraSurveyConstraints, zmin, zmax): """ *Given a list of the snSurveyDiscoveryTimes calculate the...
[ "def", "calculate_fraction_of_sn_discovered", "(", "log", ",", "surveyCadenceSettings", ",", "snSurveyDiscoveryTimes", ",", "redshifts", ",", "peakAppMagList", ",", "snCampaignLengthList", ",", "extraSurveyConstraints", ",", "zmin", ",", "zmax", ")", ":", "###############...
*Given a list of the snSurveyDiscoveryTimes calculate the discovery/non-discovery ratio for a given redshift range* **Key Arguments:** - ``log`` -- logger - ``surveyCadenceSettings`` -- the cadence settings for the survey - ``snSurveyDiscoveryTimes`` -- the discovery times of the SN relativ...
[ "*", "Given", "a", "list", "of", "the", "snSurveyDiscoveryTimes", "calculate", "the", "discovery", "/", "non", "-", "discovery", "ratio", "for", "a", "given", "redshift", "range", "*" ]
train
https://github.com/thespacedoctor/qubits/blob/3c02ace7226389841c6bb838d045c11bed61a3c2/qubits/results.py#L954-L1079
ulf1/oxyba
oxyba/linreg_ols_pinv.py
linreg_ols_pinv
def linreg_ols_pinv(y, X, rcond=1e-15): """Linear Regression, OLS, by multiplying with Pseudoinverse""" import numpy as np try: # multiply with inverse to compute coefficients return np.dot(np.linalg.pinv( np.dot(X.T, X), rcond=rcond), np.dot(X.T, y)) except np.linalg.LinAlgError: ...
python
def linreg_ols_pinv(y, X, rcond=1e-15): """Linear Regression, OLS, by multiplying with Pseudoinverse""" import numpy as np try: # multiply with inverse to compute coefficients return np.dot(np.linalg.pinv( np.dot(X.T, X), rcond=rcond), np.dot(X.T, y)) except np.linalg.LinAlgError: ...
[ "def", "linreg_ols_pinv", "(", "y", ",", "X", ",", "rcond", "=", "1e-15", ")", ":", "import", "numpy", "as", "np", "try", ":", "# multiply with inverse to compute coefficients", "return", "np", ".", "dot", "(", "np", ".", "linalg", ".", "pinv", "(", "np", ...
Linear Regression, OLS, by multiplying with Pseudoinverse
[ "Linear", "Regression", "OLS", "by", "multiplying", "with", "Pseudoinverse" ]
train
https://github.com/ulf1/oxyba/blob/b3043116050de275124365cb11e7df91fb40169d/oxyba/linreg_ols_pinv.py#L2-L10
xethorn/oto
oto/response.py
create_error_response
def create_error_response(code, message, status=status.BAD_REQUEST): """Create a fail response. Args: code (str): the code of the error. The title should be lowercase and underscore separated. message (dict, list, str): the message of the error. This can be a list, dicti...
python
def create_error_response(code, message, status=status.BAD_REQUEST): """Create a fail response. Args: code (str): the code of the error. The title should be lowercase and underscore separated. message (dict, list, str): the message of the error. This can be a list, dicti...
[ "def", "create_error_response", "(", "code", ",", "message", ",", "status", "=", "status", ".", "BAD_REQUEST", ")", ":", "errors", "=", "dict", "(", "code", "=", "code", ",", "message", "=", "message", ")", "return", "Response", "(", "errors", "=", "erro...
Create a fail response. Args: code (str): the code of the error. The title should be lowercase and underscore separated. message (dict, list, str): the message of the error. This can be a list, dictionary or simple string. status (int): the status code. Defaults to 4...
[ "Create", "a", "fail", "response", "." ]
train
https://github.com/xethorn/oto/blob/2a76d374ccc4c85fdf81ae1c43698a94c0594d7b/oto/response.py#L71-L89
kervi/kervi-core
kervi/values/__init__.py
NumberValue.display_unit
def display_unit(self): """ Display unit of value. :type: ``str`` """ if self._display_unit: return self._display_unit elif self._Q: config = Configuration.display.unit_systems default_system = Configuration.unit_system uni...
python
def display_unit(self): """ Display unit of value. :type: ``str`` """ if self._display_unit: return self._display_unit elif self._Q: config = Configuration.display.unit_systems default_system = Configuration.unit_system uni...
[ "def", "display_unit", "(", "self", ")", ":", "if", "self", ".", "_display_unit", ":", "return", "self", ".", "_display_unit", "elif", "self", ".", "_Q", ":", "config", "=", "Configuration", ".", "display", ".", "unit_systems", "default_system", "=", "Config...
Display unit of value. :type: ``str``
[ "Display", "unit", "of", "value", "." ]
train
https://github.com/kervi/kervi-core/blob/3c1e3c8a17a7b4d085d8a28b99180ff2a96b0e23/kervi/values/__init__.py#L129-L156
kervi/kervi-core
kervi/values/__init__.py
DateTimeValue.value
def value(self, new_value): """ Updates the value. If the change exceeds the change delta observers and linked values are notified. """ datetime_value = None if new_value: datetime_value = new_value.strftime("%Y-%M-%dT%H:%M:%SZ") self._set_value(date...
python
def value(self, new_value): """ Updates the value. If the change exceeds the change delta observers and linked values are notified. """ datetime_value = None if new_value: datetime_value = new_value.strftime("%Y-%M-%dT%H:%M:%SZ") self._set_value(date...
[ "def", "value", "(", "self", ",", "new_value", ")", ":", "datetime_value", "=", "None", "if", "new_value", ":", "datetime_value", "=", "new_value", ".", "strftime", "(", "\"%Y-%M-%dT%H:%M:%SZ\"", ")", "self", ".", "_set_value", "(", "datetime_value", ")" ]
Updates the value. If the change exceeds the change delta observers and linked values are notified.
[ "Updates", "the", "value", ".", "If", "the", "change", "exceeds", "the", "change", "delta", "observers", "and", "linked", "values", "are", "notified", "." ]
train
https://github.com/kervi/kervi-core/blob/3c1e3c8a17a7b4d085d8a28b99180ff2a96b0e23/kervi/values/__init__.py#L401-L409
kervi/kervi-core
kervi/values/__init__.py
EnumValue.add_option
def add_option(self, value, text, selected=False): """ Add option to select :param value: The value that the option represent. :param text: The text that should be displayer in dropdown :param selected: True if the option should be the default value. """ option...
python
def add_option(self, value, text, selected=False): """ Add option to select :param value: The value that the option represent. :param text: The text that should be displayer in dropdown :param selected: True if the option should be the default value. """ option...
[ "def", "add_option", "(", "self", ",", "value", ",", "text", ",", "selected", "=", "False", ")", ":", "option", "=", "{", "\"value\"", ":", "value", ",", "\"text\"", ":", "text", ",", "\"selected\"", ":", "selected", "}", "self", ".", "options", "+=", ...
Add option to select :param value: The value that the option represent. :param text: The text that should be displayer in dropdown :param selected: True if the option should be the default value.
[ "Add", "option", "to", "select" ]
train
https://github.com/kervi/kervi-core/blob/3c1e3c8a17a7b4d085d8a28b99180ff2a96b0e23/kervi/values/__init__.py#L503-L519
StanfordBioinformatics/scgpm_seqresults_dnanexus
scgpm_seqresults_dnanexus/log.py
get_logfile_name
def get_logfile_name(tags): """Formulates a log file name that incorporates the provided tags. The log file will be located in ``scgpm_seqresults_dnanexus.LOG_DIR``. Args: tags: `list` of tags to append to the log file name. Each tag will be '_' delimited. Each tag will be added in the same or...
python
def get_logfile_name(tags): """Formulates a log file name that incorporates the provided tags. The log file will be located in ``scgpm_seqresults_dnanexus.LOG_DIR``. Args: tags: `list` of tags to append to the log file name. Each tag will be '_' delimited. Each tag will be added in the same or...
[ "def", "get_logfile_name", "(", "tags", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "sd", ".", "LOG_DIR", ")", ":", "os", ".", "mkdir", "(", "sd", ".", "LOG_DIR", ")", "filename", "=", "\"log\"", "for", "tag", "in", "tags", ":", ...
Formulates a log file name that incorporates the provided tags. The log file will be located in ``scgpm_seqresults_dnanexus.LOG_DIR``. Args: tags: `list` of tags to append to the log file name. Each tag will be '_' delimited. Each tag will be added in the same order as provided.
[ "Formulates", "a", "log", "file", "name", "that", "incorporates", "the", "provided", "tags", "." ]
train
https://github.com/StanfordBioinformatics/scgpm_seqresults_dnanexus/blob/2bdaae5ec5d38a07fec99e0c5379074a591d77b6/scgpm_seqresults_dnanexus/log.py#L14-L30
StanfordBioinformatics/scgpm_seqresults_dnanexus
scgpm_seqresults_dnanexus/log.py
add_file_handler
def add_file_handler(logger,level,tags): """Creates and Adds a file handler (`logging.FileHandler` instance) to the specified logger. Args: logger: The `logging.Logger` instance to add the new file handler to. level: `str`. The logging level for which the handler accepts messages, i.e. `logging.INFO`....
python
def add_file_handler(logger,level,tags): """Creates and Adds a file handler (`logging.FileHandler` instance) to the specified logger. Args: logger: The `logging.Logger` instance to add the new file handler to. level: `str`. The logging level for which the handler accepts messages, i.e. `logging.INFO`....
[ "def", "add_file_handler", "(", "logger", ",", "level", ",", "tags", ")", ":", "f_formatter", "=", "logging", ".", "Formatter", "(", "'%(asctime)s:%(name)s:\\t%(message)s'", ")", "filename", "=", "get_logfile_name", "(", "tags", ")", "handler", "=", "logging", "...
Creates and Adds a file handler (`logging.FileHandler` instance) to the specified logger. Args: logger: The `logging.Logger` instance to add the new file handler to. level: `str`. The logging level for which the handler accepts messages, i.e. `logging.INFO`. tags: `list` of tags to append to the l...
[ "Creates", "and", "Adds", "a", "file", "handler", "(", "logging", ".", "FileHandler", "instance", ")", "to", "the", "specified", "logger", "." ]
train
https://github.com/StanfordBioinformatics/scgpm_seqresults_dnanexus/blob/2bdaae5ec5d38a07fec99e0c5379074a591d77b6/scgpm_seqresults_dnanexus/log.py#L32-L46
paul-butcher/nose_enhanced_descriptions
nose_enhanced_descriptions/__init__.py
get_id
def get_id(test): """ Return the id of the given test, formatted as expected by nose. :param test: a nose.case.Test instance :return: """ test_id = test.id() module_length = len(test.test.__module__) return test_id[:module_length] + ":" + test_id[module_length + 1:]
python
def get_id(test): """ Return the id of the given test, formatted as expected by nose. :param test: a nose.case.Test instance :return: """ test_id = test.id() module_length = len(test.test.__module__) return test_id[:module_length] + ":" + test_id[module_length + 1:]
[ "def", "get_id", "(", "test", ")", ":", "test_id", "=", "test", ".", "id", "(", ")", "module_length", "=", "len", "(", "test", ".", "test", ".", "__module__", ")", "return", "test_id", "[", ":", "module_length", "]", "+", "\":\"", "+", "test_id", "["...
Return the id of the given test, formatted as expected by nose. :param test: a nose.case.Test instance :return:
[ "Return", "the", "id", "of", "the", "given", "test", "formatted", "as", "expected", "by", "nose", ".", ":", "param", "test", ":", "a", "nose", ".", "case", ".", "Test", "instance", ":", "return", ":" ]
train
https://github.com/paul-butcher/nose_enhanced_descriptions/blob/3381af0407cbcf26ae85ffffa21846b3a822c3f6/nose_enhanced_descriptions/__init__.py#L33-L41
dossier/dossier.web
dossier/web/filters.py
get_string_counter
def get_string_counter(fc, feature_name): '''Find and return a :class:`~dossier.fc.StringCounter` at `feature_name` or at `DISPLAY_PREFIX` + `feature_name` in the `fc`, or return None. ''' if feature_name not in fc: feature = fc.get(FC.DISPLAY_PREFIX + feature_name) else: featur...
python
def get_string_counter(fc, feature_name): '''Find and return a :class:`~dossier.fc.StringCounter` at `feature_name` or at `DISPLAY_PREFIX` + `feature_name` in the `fc`, or return None. ''' if feature_name not in fc: feature = fc.get(FC.DISPLAY_PREFIX + feature_name) else: featur...
[ "def", "get_string_counter", "(", "fc", ",", "feature_name", ")", ":", "if", "feature_name", "not", "in", "fc", ":", "feature", "=", "fc", ".", "get", "(", "FC", ".", "DISPLAY_PREFIX", "+", "feature_name", ")", "else", ":", "feature", "=", "fc", ".", "...
Find and return a :class:`~dossier.fc.StringCounter` at `feature_name` or at `DISPLAY_PREFIX` + `feature_name` in the `fc`, or return None.
[ "Find", "and", "return", "a", ":", "class", ":", "~dossier", ".", "fc", ".", "StringCounter", "at", "feature_name", "or", "at", "DISPLAY_PREFIX", "+", "feature_name", "in", "the", "fc", "or", "return", "None", "." ]
train
https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/web/filters.py#L174-L187
Othernet-Project/conz
conz/utils.py
rewrap
def rewrap(s, width=COLS): """ Join all lines from input string and wrap it at specified width """ s = ' '.join([l.strip() for l in s.strip().split('\n')]) return '\n'.join(textwrap.wrap(s, width))
python
def rewrap(s, width=COLS): """ Join all lines from input string and wrap it at specified width """ s = ' '.join([l.strip() for l in s.strip().split('\n')]) return '\n'.join(textwrap.wrap(s, width))
[ "def", "rewrap", "(", "s", ",", "width", "=", "COLS", ")", ":", "s", "=", "' '", ".", "join", "(", "[", "l", ".", "strip", "(", ")", "for", "l", "in", "s", ".", "strip", "(", ")", ".", "split", "(", "'\\n'", ")", "]", ")", "return", "'\\n'"...
Join all lines from input string and wrap it at specified width
[ "Join", "all", "lines", "from", "input", "string", "and", "wrap", "it", "at", "specified", "width" ]
train
https://github.com/Othernet-Project/conz/blob/051214fa95a837c21595b03426a2c54c522d07a0/conz/utils.py#L17-L20
Othernet-Project/conz
conz/utils.py
rewrap_long
def rewrap_long(s, width=COLS): """ Rewrap longer texts with paragraph breaks (two consecutive LF) """ paras = s.split('\n\n') return '\n\n'.join(rewrap(p) for p in paras)
python
def rewrap_long(s, width=COLS): """ Rewrap longer texts with paragraph breaks (two consecutive LF) """ paras = s.split('\n\n') return '\n\n'.join(rewrap(p) for p in paras)
[ "def", "rewrap_long", "(", "s", ",", "width", "=", "COLS", ")", ":", "paras", "=", "s", ".", "split", "(", "'\\n\\n'", ")", "return", "'\\n\\n'", ".", "join", "(", "rewrap", "(", "p", ")", "for", "p", "in", "paras", ")" ]
Rewrap longer texts with paragraph breaks (two consecutive LF)
[ "Rewrap", "longer", "texts", "with", "paragraph", "breaks", "(", "two", "consecutive", "LF", ")" ]
train
https://github.com/Othernet-Project/conz/blob/051214fa95a837c21595b03426a2c54c522d07a0/conz/utils.py#L23-L26
jut-io/jut-python-tools
jut/commands/configs.py
add_configuration
def add_configuration(options): """ interactively add a new configuration """ if options.username != None: username = options.username else: username = prompt('Username: ') if options.password != None: password = options.password else: password = prompt('Pas...
python
def add_configuration(options): """ interactively add a new configuration """ if options.username != None: username = options.username else: username = prompt('Username: ') if options.password != None: password = options.password else: password = prompt('Pas...
[ "def", "add_configuration", "(", "options", ")", ":", "if", "options", ".", "username", "!=", "None", ":", "username", "=", "options", ".", "username", "else", ":", "username", "=", "prompt", "(", "'Username: '", ")", "if", "options", ".", "password", "!="...
interactively add a new configuration
[ "interactively", "add", "a", "new", "configuration" ]
train
https://github.com/jut-io/jut-python-tools/blob/65574d23f51a7bbced9bb25010d02da5ca5d906f/jut/commands/configs.py#L58-L110
jamieleshaw/lurklib
lurklib/uqueries.py
_UserQueries.who
def who(self, target): """ Runs a WHO on a target Required arguments: * target - /WHO <target> Returns a dictionary, with a nick as the key and - the value is a list in the form of; [0] - Username [1] - Priv level [2] - Real name ...
python
def who(self, target): """ Runs a WHO on a target Required arguments: * target - /WHO <target> Returns a dictionary, with a nick as the key and - the value is a list in the form of; [0] - Username [1] - Priv level [2] - Real name ...
[ "def", "who", "(", "self", ",", "target", ")", ":", "with", "self", ".", "lock", ":", "self", ".", "send", "(", "'WHO %s'", "%", "target", ")", "who_lst", "=", "{", "}", "while", "self", ".", "readable", "(", ")", ":", "msg", "=", "self", ".", ...
Runs a WHO on a target Required arguments: * target - /WHO <target> Returns a dictionary, with a nick as the key and - the value is a list in the form of; [0] - Username [1] - Priv level [2] - Real name [3] - Hostname
[ "Runs", "a", "WHO", "on", "a", "target", "Required", "arguments", ":", "*", "target", "-", "/", "WHO", "<target", ">", "Returns", "a", "dictionary", "with", "a", "nick", "as", "the", "key", "and", "-", "the", "value", "is", "a", "list", "in", "the", ...
train
https://github.com/jamieleshaw/lurklib/blob/a861f35d880140422103dd78ec3239814e85fd7e/lurklib/uqueries.py#L23-L67
jamieleshaw/lurklib
lurklib/uqueries.py
_UserQueries.whois
def whois(self, nick): """ Runs a WHOIS on someone. Required arguments: * nick - Nick to whois. Returns a dictionary: IDENT == The user's ident. HOST == The user's host. NAME == The user's real name. SERVER == The server the user is...
python
def whois(self, nick): """ Runs a WHOIS on someone. Required arguments: * nick - Nick to whois. Returns a dictionary: IDENT == The user's ident. HOST == The user's host. NAME == The user's real name. SERVER == The server the user is...
[ "def", "whois", "(", "self", ",", "nick", ")", ":", "with", "self", ".", "lock", ":", "self", ".", "send", "(", "'WHOIS %s'", "%", "nick", ")", "whois_r", "=", "{", "'CHANNELS'", ":", "[", "]", "}", "while", "self", ".", "readable", "(", ")", ":"...
Runs a WHOIS on someone. Required arguments: * nick - Nick to whois. Returns a dictionary: IDENT == The user's ident. HOST == The user's host. NAME == The user's real name. SERVER == The server the user is on. SERVER_INFO == The name of...
[ "Runs", "a", "WHOIS", "on", "someone", ".", "Required", "arguments", ":", "*", "nick", "-", "Nick", "to", "whois", ".", "Returns", "a", "dictionary", ":", "IDENT", "==", "The", "user", "s", "ident", ".", "HOST", "==", "The", "user", "s", "host", ".",...
train
https://github.com/jamieleshaw/lurklib/blob/a861f35d880140422103dd78ec3239814e85fd7e/lurklib/uqueries.py#L69-L117
jamieleshaw/lurklib
lurklib/uqueries.py
_UserQueries.whowas
def whowas(self, nick): """ Runs a WHOWAS on someone. Required arguments: * nick - Nick to run a WHOWAS on. Returns a list: [0] The user's nick. [1] The user's ident. [2] The user's host. [3] The user's real name. """ wi...
python
def whowas(self, nick): """ Runs a WHOWAS on someone. Required arguments: * nick - Nick to run a WHOWAS on. Returns a list: [0] The user's nick. [1] The user's ident. [2] The user's host. [3] The user's real name. """ wi...
[ "def", "whowas", "(", "self", ",", "nick", ")", ":", "with", "self", ".", "lock", ":", "self", ".", "send", "(", "'WHOWAS %s'", "%", "nick", ")", "rwhowas", "=", "[", "]", "while", "self", ".", "readable", "(", ")", ":", "msg", "=", "self", ".", ...
Runs a WHOWAS on someone. Required arguments: * nick - Nick to run a WHOWAS on. Returns a list: [0] The user's nick. [1] The user's ident. [2] The user's host. [3] The user's real name.
[ "Runs", "a", "WHOWAS", "on", "someone", ".", "Required", "arguments", ":", "*", "nick", "-", "Nick", "to", "run", "a", "WHOWAS", "on", ".", "Returns", "a", "list", ":", "[", "0", "]", "The", "user", "s", "nick", ".", "[", "1", "]", "The", "user",...
train
https://github.com/jamieleshaw/lurklib/blob/a861f35d880140422103dd78ec3239814e85fd7e/lurklib/uqueries.py#L119-L143
insilicolife/micti
build/lib/MICTI/Kmeans.py
Kmeans.get_initial_centroids
def get_initial_centroids(self): '''Randomly choose k data points as initial centroids''' if self.seed is not None: # useful for obtaining consistent results np.random.seed(self.seed) n = self.data.shape[0] # number of data points # Pick K indices from range [0, N). ...
python
def get_initial_centroids(self): '''Randomly choose k data points as initial centroids''' if self.seed is not None: # useful for obtaining consistent results np.random.seed(self.seed) n = self.data.shape[0] # number of data points # Pick K indices from range [0, N). ...
[ "def", "get_initial_centroids", "(", "self", ")", ":", "if", "self", ".", "seed", "is", "not", "None", ":", "# useful for obtaining consistent results", "np", ".", "random", ".", "seed", "(", "self", ".", "seed", ")", "n", "=", "self", ".", "data", ".", ...
Randomly choose k data points as initial centroids
[ "Randomly", "choose", "k", "data", "points", "as", "initial", "centroids" ]
train
https://github.com/insilicolife/micti/blob/f12f46724295b57c4859e6acf7eab580fc355eb1/build/lib/MICTI/Kmeans.py#L34-L48
insilicolife/micti
build/lib/MICTI/Kmeans.py
Kmeans.smart_initialize
def smart_initialize(self): '''Use k-means++ to initialize a good set of centroids''' if self.seed is not None: # useful for obtaining consistent results np.random.seed(self.seed) centroids = np.zeros((self.k, self.data.shape[1])) # Randomly choose the first centroid. ...
python
def smart_initialize(self): '''Use k-means++ to initialize a good set of centroids''' if self.seed is not None: # useful for obtaining consistent results np.random.seed(self.seed) centroids = np.zeros((self.k, self.data.shape[1])) # Randomly choose the first centroid. ...
[ "def", "smart_initialize", "(", "self", ")", ":", "if", "self", ".", "seed", "is", "not", "None", ":", "# useful for obtaining consistent results", "np", ".", "random", ".", "seed", "(", "self", ".", "seed", ")", "centroids", "=", "np", ".", "zeros", "(", ...
Use k-means++ to initialize a good set of centroids
[ "Use", "k", "-", "means", "++", "to", "initialize", "a", "good", "set", "of", "centroids" ]
train
https://github.com/insilicolife/micti/blob/f12f46724295b57c4859e6acf7eab580fc355eb1/build/lib/MICTI/Kmeans.py#L50-L70
insilicolife/micti
build/lib/MICTI/Kmeans.py
Kmeans.kmeans
def kmeans(self, maxiter, record_heterogeneity=None, verbose=False): '''This function runs k-means on given data and initial set of centroids. maxiter: maximum number of iterations to run. record_heterogeneity: (optional) a list, to store the history of heterogeneity as function of iterati...
python
def kmeans(self, maxiter, record_heterogeneity=None, verbose=False): '''This function runs k-means on given data and initial set of centroids. maxiter: maximum number of iterations to run. record_heterogeneity: (optional) a list, to store the history of heterogeneity as function of iterati...
[ "def", "kmeans", "(", "self", ",", "maxiter", ",", "record_heterogeneity", "=", "None", ",", "verbose", "=", "False", ")", ":", "centroids", "=", "self", ".", "centroids", "[", ":", "]", "prev_cluster_assignment", "=", "None", "for", "itr", "in", "range", ...
This function runs k-means on given data and initial set of centroids. maxiter: maximum number of iterations to run. record_heterogeneity: (optional) a list, to store the history of heterogeneity as function of iterations if None, do not store the history. v...
[ "This", "function", "runs", "k", "-", "means", "on", "given", "data", "and", "initial", "set", "of", "centroids", ".", "maxiter", ":", "maximum", "number", "of", "iterations", "to", "run", ".", "record_heterogeneity", ":", "(", "optional", ")", "a", "list"...
train
https://github.com/insilicolife/micti/blob/f12f46724295b57c4859e6acf7eab580fc355eb1/build/lib/MICTI/Kmeans.py#L100-L134
mrcagney/gtfsrtk
gtfsrtk/main.py
read_gtfsr
def read_gtfsr(path, *, from_json=False): """ Given a path (string or Path object) to a GTFSR feed file, return the corresponding GTFS feed (FeedMessage instance). If ``from_json``, then assume the feed file is in JSON format; otherwise, assume the feed file is in Protocol Buffer format. """ ...
python
def read_gtfsr(path, *, from_json=False): """ Given a path (string or Path object) to a GTFSR feed file, return the corresponding GTFS feed (FeedMessage instance). If ``from_json``, then assume the feed file is in JSON format; otherwise, assume the feed file is in Protocol Buffer format. """ ...
[ "def", "read_gtfsr", "(", "path", ",", "*", ",", "from_json", "=", "False", ")", ":", "path", "=", "Path", "(", "path", ")", "feed", "=", "gtfs_realtime_pb2", ".", "FeedMessage", "(", ")", "with", "path", ".", "open", "(", "'rb'", ")", "as", "src", ...
Given a path (string or Path object) to a GTFSR feed file, return the corresponding GTFS feed (FeedMessage instance). If ``from_json``, then assume the feed file is in JSON format; otherwise, assume the feed file is in Protocol Buffer format.
[ "Given", "a", "path", "(", "string", "or", "Path", "object", ")", "to", "a", "GTFSR", "feed", "file", "return", "the", "corresponding", "GTFS", "feed", "(", "FeedMessage", "instance", ")", ".", "If", "from_json", "then", "assume", "the", "feed", "file", ...
train
https://github.com/mrcagney/gtfsrtk/blob/16517b4f2a4a1f51d37e691ce3159a8d637e5389/gtfsrtk/main.py#L18-L34
mrcagney/gtfsrtk
gtfsrtk/main.py
write_gtfsr
def write_gtfsr(feed, path, *, to_json=False): """ Given a GTFSR feed (FeedMessage instance), write it to the given file path (string or Path object). If ``to_json``, then save the file as JSON; otherwise save it as Protocol Buffer. """ path = Path(path) if to_json: with path.op...
python
def write_gtfsr(feed, path, *, to_json=False): """ Given a GTFSR feed (FeedMessage instance), write it to the given file path (string or Path object). If ``to_json``, then save the file as JSON; otherwise save it as Protocol Buffer. """ path = Path(path) if to_json: with path.op...
[ "def", "write_gtfsr", "(", "feed", ",", "path", ",", "*", ",", "to_json", "=", "False", ")", ":", "path", "=", "Path", "(", "path", ")", "if", "to_json", ":", "with", "path", ".", "open", "(", "'w'", ")", "as", "tgt", ":", "tgt", ".", "write", ...
Given a GTFSR feed (FeedMessage instance), write it to the given file path (string or Path object). If ``to_json``, then save the file as JSON; otherwise save it as Protocol Buffer.
[ "Given", "a", "GTFSR", "feed", "(", "FeedMessage", "instance", ")", "write", "it", "to", "the", "given", "file", "path", "(", "string", "or", "Path", "object", ")", ".", "If", "to_json", "then", "save", "the", "file", "as", "JSON", ";", "otherwise", "s...
train
https://github.com/mrcagney/gtfsrtk/blob/16517b4f2a4a1f51d37e691ce3159a8d637e5389/gtfsrtk/main.py#L36-L50
mrcagney/gtfsrtk
gtfsrtk/main.py
timestamp_to_str
def timestamp_to_str(t, datetime_format=DATETIME_FORMAT, *, inverse=False): """ Given a POSIX timestamp (integer) ``t``, format it as a datetime string in the given format. If ``inverse``, then do the inverse, that is, assume ``t`` is a datetime string in the given format and return its correspondin...
python
def timestamp_to_str(t, datetime_format=DATETIME_FORMAT, *, inverse=False): """ Given a POSIX timestamp (integer) ``t``, format it as a datetime string in the given format. If ``inverse``, then do the inverse, that is, assume ``t`` is a datetime string in the given format and return its correspondin...
[ "def", "timestamp_to_str", "(", "t", ",", "datetime_format", "=", "DATETIME_FORMAT", ",", "*", ",", "inverse", "=", "False", ")", ":", "if", "not", "inverse", ":", "if", "datetime_format", "is", "None", ":", "result", "=", "str", "(", "t", ")", "else", ...
Given a POSIX timestamp (integer) ``t``, format it as a datetime string in the given format. If ``inverse``, then do the inverse, that is, assume ``t`` is a datetime string in the given format and return its corresponding timestamp. If ``format is None``, then return ``t`` as a string (if not ``...
[ "Given", "a", "POSIX", "timestamp", "(", "integer", ")", "t", "format", "it", "as", "a", "datetime", "string", "in", "the", "given", "format", ".", "If", "inverse", "then", "do", "the", "inverse", "that", "is", "assume", "t", "is", "a", "datetime", "st...
train
https://github.com/mrcagney/gtfsrtk/blob/16517b4f2a4a1f51d37e691ce3159a8d637e5389/gtfsrtk/main.py#L65-L85
mrcagney/gtfsrtk
gtfsrtk/main.py
extract_delays
def extract_delays(feed): """ Given a GTFSR feed (FeedMessage instance), extract the delays from the feed and return a DataFrame with the columns: - route_id - trip_id - stop_id - stop_sequence - arrival_delay - departure_delay If the feed has no trip updates, then return an em...
python
def extract_delays(feed): """ Given a GTFSR feed (FeedMessage instance), extract the delays from the feed and return a DataFrame with the columns: - route_id - trip_id - stop_id - stop_sequence - arrival_delay - departure_delay If the feed has no trip updates, then return an em...
[ "def", "extract_delays", "(", "feed", ")", ":", "rows", "=", "[", "]", "for", "e", "in", "feed", ".", "entity", ":", "if", "not", "e", ".", "HasField", "(", "'trip_update'", ")", ":", "continue", "tu", "=", "e", ".", "trip_update", "rid", "=", "tu"...
Given a GTFSR feed (FeedMessage instance), extract the delays from the feed and return a DataFrame with the columns: - route_id - trip_id - stop_id - stop_sequence - arrival_delay - departure_delay If the feed has no trip updates, then return an empty DataFrame.
[ "Given", "a", "GTFSR", "feed", "(", "FeedMessage", "instance", ")", "extract", "the", "delays", "from", "the", "feed", "and", "return", "a", "DataFrame", "with", "the", "columns", ":" ]
train
https://github.com/mrcagney/gtfsrtk/blob/16517b4f2a4a1f51d37e691ce3159a8d637e5389/gtfsrtk/main.py#L95-L134
mrcagney/gtfsrtk
gtfsrtk/main.py
combine_delays
def combine_delays(delays_list): """ Given a list of DataFrames of the form output by the function :func:`extract_delays`, combine them into a single DataFrame as follows and return the result. Concatenate ``delays_list`` and remove duplicate [route_id, trip_id, stop_sequence] entries by com...
python
def combine_delays(delays_list): """ Given a list of DataFrames of the form output by the function :func:`extract_delays`, combine them into a single DataFrame as follows and return the result. Concatenate ``delays_list`` and remove duplicate [route_id, trip_id, stop_sequence] entries by com...
[ "def", "combine_delays", "(", "delays_list", ")", ":", "if", "not", "delays_list", ":", "return", "pd", ".", "DataFrame", "(", ")", "f", "=", "pd", ".", "concat", "(", "delays_list", ")", "f", "=", "f", ".", "drop_duplicates", "(", ")", "f", "=", "f"...
Given a list of DataFrames of the form output by the function :func:`extract_delays`, combine them into a single DataFrame as follows and return the result. Concatenate ``delays_list`` and remove duplicate [route_id, trip_id, stop_sequence] entries by combining their non-null delay values into one e...
[ "Given", "a", "list", "of", "DataFrames", "of", "the", "form", "output", "by", "the", "function", ":", "func", ":", "extract_delays", "combine", "them", "into", "a", "single", "DataFrame", "as", "follows", "and", "return", "the", "result", ".", "Concatenate"...
train
https://github.com/mrcagney/gtfsrtk/blob/16517b4f2a4a1f51d37e691ce3159a8d637e5389/gtfsrtk/main.py#L136-L181
mrcagney/gtfsrtk
gtfsrtk/main.py
build_augmented_stop_times
def build_augmented_stop_times(gtfsr_feeds, gtfs_feed, date): """ Given a list of GTFSR feeds (FeedMessage instances), a GTFS feed (GTFSTK Feed instance), and a date (YYYYMMDD string), return a DataFrame of GTFS stop times for trips scheduled on the given date and containing two extra columns, ``'ar...
python
def build_augmented_stop_times(gtfsr_feeds, gtfs_feed, date): """ Given a list of GTFSR feeds (FeedMessage instances), a GTFS feed (GTFSTK Feed instance), and a date (YYYYMMDD string), return a DataFrame of GTFS stop times for trips scheduled on the given date and containing two extra columns, ``'ar...
[ "def", "build_augmented_stop_times", "(", "gtfsr_feeds", ",", "gtfs_feed", ",", "date", ")", ":", "# Get scheduled stop times for date", "st", "=", "gt", ".", "get_stop_times", "(", "gtfs_feed", ",", "date", ")", "# Get GTFSR timestamps pertinent to date.", "# Use datetim...
Given a list of GTFSR feeds (FeedMessage instances), a GTFS feed (GTFSTK Feed instance), and a date (YYYYMMDD string), return a DataFrame of GTFS stop times for trips scheduled on the given date and containing two extra columns, ``'arrival_delay'`` and ``'departure_delay'``, which are delay values in se...
[ "Given", "a", "list", "of", "GTFSR", "feeds", "(", "FeedMessage", "instances", ")", "a", "GTFS", "feed", "(", "GTFSTK", "Feed", "instance", ")", "and", "a", "date", "(", "YYYYMMDD", "string", ")", "return", "a", "DataFrame", "of", "GTFS", "stop", "times"...
train
https://github.com/mrcagney/gtfsrtk/blob/16517b4f2a4a1f51d37e691ce3159a8d637e5389/gtfsrtk/main.py#L183-L235
mrcagney/gtfsrtk
gtfsrtk/main.py
interpolate_delays
def interpolate_delays(augmented_stop_times, dist_threshold, delay_threshold=3600, delay_cols=None): """ Given an augment stop times DataFrame as output by the function :func:`build_augmented_stop_times`, a distance threshold (float) in the same units as the ``'shape_dist_traveled'`` column of ``a...
python
def interpolate_delays(augmented_stop_times, dist_threshold, delay_threshold=3600, delay_cols=None): """ Given an augment stop times DataFrame as output by the function :func:`build_augmented_stop_times`, a distance threshold (float) in the same units as the ``'shape_dist_traveled'`` column of ``a...
[ "def", "interpolate_delays", "(", "augmented_stop_times", ",", "dist_threshold", ",", "delay_threshold", "=", "3600", ",", "delay_cols", "=", "None", ")", ":", "f", "=", "augmented_stop_times", ".", "copy", "(", ")", "if", "delay_cols", "is", "None", "or", "no...
Given an augment stop times DataFrame as output by the function :func:`build_augmented_stop_times`, a distance threshold (float) in the same units as the ``'shape_dist_traveled'`` column of ``augmented_stop_times``, if that column is present, and a delay threshold (integer number of seconds), alter the ...
[ "Given", "an", "augment", "stop", "times", "DataFrame", "as", "output", "by", "the", "function", ":", "func", ":", "build_augmented_stop_times", "a", "distance", "threshold", "(", "float", ")", "in", "the", "same", "units", "as", "the", "shape_dist_traveled", ...
train
https://github.com/mrcagney/gtfsrtk/blob/16517b4f2a4a1f51d37e691ce3159a8d637e5389/gtfsrtk/main.py#L237-L318
etcher-be/elib_run
elib_run/_run/_capture_output.py
filter_line
def filter_line(line: str, context: RunContext) -> typing.Optional[str]: """ Filters out lines that match a given regex :param line: line to filter :type line: str :param context: run context :type context: _RunContext :return: line if it doesn't match the filter :rtype: optional str ...
python
def filter_line(line: str, context: RunContext) -> typing.Optional[str]: """ Filters out lines that match a given regex :param line: line to filter :type line: str :param context: run context :type context: _RunContext :return: line if it doesn't match the filter :rtype: optional str ...
[ "def", "filter_line", "(", "line", ":", "str", ",", "context", ":", "RunContext", ")", "->", "typing", ".", "Optional", "[", "str", "]", ":", "if", "context", ".", "filters", "is", "not", "None", ":", "for", "filter_", "in", "context", ".", "filters", ...
Filters out lines that match a given regex :param line: line to filter :type line: str :param context: run context :type context: _RunContext :return: line if it doesn't match the filter :rtype: optional str
[ "Filters", "out", "lines", "that", "match", "a", "given", "regex" ]
train
https://github.com/etcher-be/elib_run/blob/c9d8ba9f067ab90c5baa27375a92b23f1b97cdde/elib_run/_run/_capture_output.py#L15-L30
etcher-be/elib_run
elib_run/_run/_capture_output.py
decode_and_filter
def decode_and_filter(line: bytes, context: RunContext) -> typing.Optional[str]: """ Decodes a line that was captured from the running process using a given encoding (defaults to UTF8) Runs that line into the filters, and output the decoded line back if no filter catches it. :param line: line to parse...
python
def decode_and_filter(line: bytes, context: RunContext) -> typing.Optional[str]: """ Decodes a line that was captured from the running process using a given encoding (defaults to UTF8) Runs that line into the filters, and output the decoded line back if no filter catches it. :param line: line to parse...
[ "def", "decode_and_filter", "(", "line", ":", "bytes", ",", "context", ":", "RunContext", ")", "->", "typing", ".", "Optional", "[", "str", "]", ":", "line_str", ":", "str", "=", "line", ".", "decode", "(", "context", ".", "console_encoding", ",", "error...
Decodes a line that was captured from the running process using a given encoding (defaults to UTF8) Runs that line into the filters, and output the decoded line back if no filter catches it. :param line: line to parse :type line: str :param context: run context :type context: RunContext :retur...
[ "Decodes", "a", "line", "that", "was", "captured", "from", "the", "running", "process", "using", "a", "given", "encoding", "(", "defaults", "to", "UTF8", ")" ]
train
https://github.com/etcher-be/elib_run/blob/c9d8ba9f067ab90c5baa27375a92b23f1b97cdde/elib_run/_run/_capture_output.py#L33-L51
etcher-be/elib_run
elib_run/_run/_capture_output.py
capture_output_from_running_process
def capture_output_from_running_process(context: RunContext) -> None: """ Parses output from a running sub-process Decodes and filters the process output line by line, buffering it If "mute" is False, sends the output back in real time :param context: run context :type context: _RunContext ...
python
def capture_output_from_running_process(context: RunContext) -> None: """ Parses output from a running sub-process Decodes and filters the process output line by line, buffering it If "mute" is False, sends the output back in real time :param context: run context :type context: _RunContext ...
[ "def", "capture_output_from_running_process", "(", "context", ":", "RunContext", ")", "->", "None", ":", "# Get the raw output one line at a time", "_output", "=", "context", ".", "capture", ".", "readline", "(", "block", "=", "False", ")", "if", "_output", ":", "...
Parses output from a running sub-process Decodes and filters the process output line by line, buffering it If "mute" is False, sends the output back in real time :param context: run context :type context: _RunContext
[ "Parses", "output", "from", "a", "running", "sub", "-", "process" ]
train
https://github.com/etcher-be/elib_run/blob/c9d8ba9f067ab90c5baa27375a92b23f1b97cdde/elib_run/_run/_capture_output.py#L54-L84
awacha/credolib
credolib/atsas.py
autorg
def autorg(filename, mininterval=None, qminrg=None, qmaxrg=None, noprint=True): """Execute autorg. Inputs: filename: either a name of an ascii file, or an instance of Curve. mininterval: the minimum number of points in the Guinier range qminrg: the maximum value of qmin*Rg. Default of a...
python
def autorg(filename, mininterval=None, qminrg=None, qmaxrg=None, noprint=True): """Execute autorg. Inputs: filename: either a name of an ascii file, or an instance of Curve. mininterval: the minimum number of points in the Guinier range qminrg: the maximum value of qmin*Rg. Default of a...
[ "def", "autorg", "(", "filename", ",", "mininterval", "=", "None", ",", "qminrg", "=", "None", ",", "qmaxrg", "=", "None", ",", "noprint", "=", "True", ")", ":", "if", "isinstance", "(", "filename", ",", "Curve", ")", ":", "curve", "=", "filename", "...
Execute autorg. Inputs: filename: either a name of an ascii file, or an instance of Curve. mininterval: the minimum number of points in the Guinier range qminrg: the maximum value of qmin*Rg. Default of autorg is 1.0 qmaxrg: the maximum value of qmax*Rg. Default of autorg is 1.3 ...
[ "Execute", "autorg", "." ]
train
https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/atsas.py#L156-L197
awacha/credolib
credolib/atsas.py
shanum
def shanum(filename, dmax=None, noprint=True): """Execute the shanum program to determine the optimum qmax according to an estimation of the optimum number of Shannon channels. Inputs: filename: either a name of an ascii file, or an instance of Curve dmax: the cut-off of...
python
def shanum(filename, dmax=None, noprint=True): """Execute the shanum program to determine the optimum qmax according to an estimation of the optimum number of Shannon channels. Inputs: filename: either a name of an ascii file, or an instance of Curve dmax: the cut-off of...
[ "def", "shanum", "(", "filename", ",", "dmax", "=", "None", ",", "noprint", "=", "True", ")", ":", "if", "isinstance", "(", "filename", ",", "Curve", ")", ":", "curve", "=", "filename", "with", "tempfile", ".", "NamedTemporaryFile", "(", "'w+b'", ",", ...
Execute the shanum program to determine the optimum qmax according to an estimation of the optimum number of Shannon channels. Inputs: filename: either a name of an ascii file, or an instance of Curve dmax: the cut-off of the P(r) function, if known. If None, thi...
[ "Execute", "the", "shanum", "program", "to", "determine", "the", "optimum", "qmax", "according", "to", "an", "estimation", "of", "the", "optimum", "number", "of", "Shannon", "channels", ".", "Inputs", ":", "filename", ":", "either", "a", "name", "of", "an", ...
train
https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/atsas.py#L231-L271
awacha/credolib
credolib/atsas.py
datcmp
def datcmp(*curves, alpha=None, adjust=None, test='CORMAP'): """Run datcmp on the scattering curves. Inputs: *curves: scattering curves as positional arguments alpha: confidence parameter adjust: adjustment type (string), see the help of datcmp for details test: test (string), s...
python
def datcmp(*curves, alpha=None, adjust=None, test='CORMAP'): """Run datcmp on the scattering curves. Inputs: *curves: scattering curves as positional arguments alpha: confidence parameter adjust: adjustment type (string), see the help of datcmp for details test: test (string), s...
[ "def", "datcmp", "(", "*", "curves", ",", "alpha", "=", "None", ",", "adjust", "=", "None", ",", "test", "=", "'CORMAP'", ")", ":", "if", "len", "(", "{", "len", "(", "c", ")", "for", "c", "in", "curves", "}", ")", "!=", "1", ":", "raise", "V...
Run datcmp on the scattering curves. Inputs: *curves: scattering curves as positional arguments alpha: confidence parameter adjust: adjustment type (string), see the help of datcmp for details test: test (string), see the help of datcmp for details Outputs: matC: the C ...
[ "Run", "datcmp", "on", "the", "scattering", "curves", "." ]
train
https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/atsas.py#L371-L428
awacha/credolib
credolib/atsas.py
datporod
def datporod(gnomoutfile): """Run datporod and return the estimated Porod volume. Returns: Radius of gyration found in the input file I0 found in the input file Vporod: the estimated Porod volume """ results = subprocess.check_output(['datporod', gnomoutfile]).decode('utf-8')...
python
def datporod(gnomoutfile): """Run datporod and return the estimated Porod volume. Returns: Radius of gyration found in the input file I0 found in the input file Vporod: the estimated Porod volume """ results = subprocess.check_output(['datporod', gnomoutfile]).decode('utf-8')...
[ "def", "datporod", "(", "gnomoutfile", ")", ":", "results", "=", "subprocess", ".", "check_output", "(", "[", "'datporod'", ",", "gnomoutfile", "]", ")", ".", "decode", "(", "'utf-8'", ")", ".", "strip", "(", ")", ".", "split", "(", ")", "return", "flo...
Run datporod and return the estimated Porod volume. Returns: Radius of gyration found in the input file I0 found in the input file Vporod: the estimated Porod volume
[ "Run", "datporod", "and", "return", "the", "estimated", "Porod", "volume", "." ]
train
https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/atsas.py#L431-L440
awacha/credolib
credolib/atsas.py
gnom
def gnom(curve, Rmax, outputfilename=None, Npoints_realspace=None, initial_alpha=None): """Run GNOM on the dataset. Inputs: curve: an instance of sastool.classes2.Curve or anything which has a save() method, saving the scattering curve to a given .dat file, in q=4*pi*sin(theta)/...
python
def gnom(curve, Rmax, outputfilename=None, Npoints_realspace=None, initial_alpha=None): """Run GNOM on the dataset. Inputs: curve: an instance of sastool.classes2.Curve or anything which has a save() method, saving the scattering curve to a given .dat file, in q=4*pi*sin(theta)/...
[ "def", "gnom", "(", "curve", ",", "Rmax", ",", "outputfilename", "=", "None", ",", "Npoints_realspace", "=", "None", ",", "initial_alpha", "=", "None", ")", ":", "with", "tempfile", ".", "TemporaryDirectory", "(", "prefix", "=", "'credolib_gnom'", ")", "as",...
Run GNOM on the dataset. Inputs: curve: an instance of sastool.classes2.Curve or anything which has a save() method, saving the scattering curve to a given .dat file, in q=4*pi*sin(theta)/lambda [1/nm] units Rmax: the estimated maximum extent of the scattering object, in nm....
[ "Run", "GNOM", "on", "the", "dataset", "." ]
train
https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/atsas.py#L443-L518
uw-it-aca/uw-restclients-libraries
uw_libraries/mylib.py
get_account
def get_account(netid, timestamp=None): """ The Libraries object has a method for getting information about a user's library account """ response = _get_account(netid, timestamp=timestamp) return _account_from_json(response)
python
def get_account(netid, timestamp=None): """ The Libraries object has a method for getting information about a user's library account """ response = _get_account(netid, timestamp=timestamp) return _account_from_json(response)
[ "def", "get_account", "(", "netid", ",", "timestamp", "=", "None", ")", ":", "response", "=", "_get_account", "(", "netid", ",", "timestamp", "=", "timestamp", ")", "return", "_account_from_json", "(", "response", ")" ]
The Libraries object has a method for getting information about a user's library account
[ "The", "Libraries", "object", "has", "a", "method", "for", "getting", "information", "about", "a", "user", "s", "library", "account" ]
train
https://github.com/uw-it-aca/uw-restclients-libraries/blob/2fa2e38be4516d7853c2802e2f23b17fbf4bac3d/uw_libraries/mylib.py#L45-L51
fred49/linshare-api
linshareapi/user/contactslistcontact.py
ContactsListContact.delete
def delete(self, list_uuid, uuid): """ Delete one list.""" res = self.get(list_uuid, uuid) url = "%(base)s/%(list_uuid)s/contacts/%(uuid)s" % { 'base': self.local_base_url, 'list_uuid': list_uuid, 'uuid': uuid } self.core.delete(url) re...
python
def delete(self, list_uuid, uuid): """ Delete one list.""" res = self.get(list_uuid, uuid) url = "%(base)s/%(list_uuid)s/contacts/%(uuid)s" % { 'base': self.local_base_url, 'list_uuid': list_uuid, 'uuid': uuid } self.core.delete(url) re...
[ "def", "delete", "(", "self", ",", "list_uuid", ",", "uuid", ")", ":", "res", "=", "self", ".", "get", "(", "list_uuid", ",", "uuid", ")", "url", "=", "\"%(base)s/%(list_uuid)s/contacts/%(uuid)s\"", "%", "{", "'base'", ":", "self", ".", "local_base_url", "...
Delete one list.
[ "Delete", "one", "list", "." ]
train
https://github.com/fred49/linshare-api/blob/be646c25aa8ba3718abb6869c620b157d53d6e41/linshareapi/user/contactslistcontact.py#L99-L108
fred49/linshare-api
linshareapi/user/contactslistcontact.py
ContactsListContact.update
def update(self, data): """ Update a list.""" self.debug(data) url = "%(base)s/%(list_uuid)s/contacts/%(uuid)s" % { 'base': self.local_base_url, 'list_uuid': data.get('mailingListUuid'), 'uuid': data.get('uuid') } return self.core.update(url, d...
python
def update(self, data): """ Update a list.""" self.debug(data) url = "%(base)s/%(list_uuid)s/contacts/%(uuid)s" % { 'base': self.local_base_url, 'list_uuid': data.get('mailingListUuid'), 'uuid': data.get('uuid') } return self.core.update(url, d...
[ "def", "update", "(", "self", ",", "data", ")", ":", "self", ".", "debug", "(", "data", ")", "url", "=", "\"%(base)s/%(list_uuid)s/contacts/%(uuid)s\"", "%", "{", "'base'", ":", "self", ".", "local_base_url", ",", "'list_uuid'", ":", "data", ".", "get", "(...
Update a list.
[ "Update", "a", "list", "." ]
train
https://github.com/fred49/linshare-api/blob/be646c25aa8ba3718abb6869c620b157d53d6e41/linshareapi/user/contactslistcontact.py#L112-L120
willcrichton/cmu_auth
cmu_auth/auth.py
authenticate
def authenticate(url, username, password): ''' Queries an asset behind CMU's WebISO wall. It uses Shibboleth authentication (see: http://dev.e-taxonomy.eu/trac/wiki/ShibbolethProtocol) Note that you can use this to authenticate stuff beyond just grades! (any CMU service) Sample usage: s = authen...
python
def authenticate(url, username, password): ''' Queries an asset behind CMU's WebISO wall. It uses Shibboleth authentication (see: http://dev.e-taxonomy.eu/trac/wiki/ShibbolethProtocol) Note that you can use this to authenticate stuff beyond just grades! (any CMU service) Sample usage: s = authen...
[ "def", "authenticate", "(", "url", ",", "username", ",", "password", ")", ":", "# We're using a Requests (http://www.python-requests.org/en/latest/) session", "s", "=", "requests", ".", "Session", "(", ")", "# 1. Initiate sequence by querying the protected asset", "data", "="...
Queries an asset behind CMU's WebISO wall. It uses Shibboleth authentication (see: http://dev.e-taxonomy.eu/trac/wiki/ShibbolethProtocol) Note that you can use this to authenticate stuff beyond just grades! (any CMU service) Sample usage: s = authenticate('https://enr-apps.as.cmu.edu/audit/audit', '...
[ "Queries", "an", "asset", "behind", "CMU", "s", "WebISO", "wall", ".", "It", "uses", "Shibboleth", "authentication", "(", "see", ":", "http", ":", "//", "dev", ".", "e", "-", "taxonomy", ".", "eu", "/", "trac", "/", "wiki", "/", "ShibbolethProtocol", "...
train
https://github.com/willcrichton/cmu_auth/blob/6d05f80b4863b14d59946734dce3b8f8a66380b8/cmu_auth/auth.py#L9-L73
ramrod-project/database-brain
schema/brain/controller/plugins.py
find_plugin
def find_plugin(value, key=DEFAULT_LOOKUP_KEY, conn=None): """ get's the plugin matching the key and value example: find_plugin("plugin1", "ServiceName") => list of 0 or 1 item example: find_plugin("plugin1", "Name") => list of 0-to-many items :param value: :par...
python
def find_plugin(value, key=DEFAULT_LOOKUP_KEY, conn=None): """ get's the plugin matching the key and value example: find_plugin("plugin1", "ServiceName") => list of 0 or 1 item example: find_plugin("plugin1", "Name") => list of 0-to-many items :param value: :par...
[ "def", "find_plugin", "(", "value", ",", "key", "=", "DEFAULT_LOOKUP_KEY", ",", "conn", "=", "None", ")", ":", "# cast to list to hide rethink internals from caller", "result", "=", "list", "(", "RPC", ".", "filter", "(", "{", "key", ":", "value", "}", ")", ...
get's the plugin matching the key and value example: find_plugin("plugin1", "ServiceName") => list of 0 or 1 item example: find_plugin("plugin1", "Name") => list of 0-to-many items :param value: :param key: <str> (default "Name") :param conn: :return:
[ "get", "s", "the", "plugin", "matching", "the", "key", "and", "value" ]
train
https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/controller/plugins.py#L57-L75
ramrod-project/database-brain
schema/brain/controller/plugins.py
create_plugin
def create_plugin(plugin_data, verify_plugin=True, conn=None): """ :param plugin_data: <dict> dict matching Plugin() :param verify_plugin: <bool> :param conn: <rethinkdb.DefaultConnection> :return: <dict> rethinkdb insert response value """ assert isinstan...
python
def create_plugin(plugin_data, verify_plugin=True, conn=None): """ :param plugin_data: <dict> dict matching Plugin() :param verify_plugin: <bool> :param conn: <rethinkdb.DefaultConnection> :return: <dict> rethinkdb insert response value """ assert isinstan...
[ "def", "create_plugin", "(", "plugin_data", ",", "verify_plugin", "=", "True", ",", "conn", "=", "None", ")", ":", "assert", "isinstance", "(", "plugin_data", ",", "dict", ")", "if", "verify_plugin", "and", "not", "verify", "(", "plugin_data", ",", "Plugin",...
:param plugin_data: <dict> dict matching Plugin() :param verify_plugin: <bool> :param conn: <rethinkdb.DefaultConnection> :return: <dict> rethinkdb insert response value
[ ":", "param", "plugin_data", ":", "<dict", ">", "dict", "matching", "Plugin", "()", ":", "param", "verify_plugin", ":", "<bool", ">", ":", "param", "conn", ":", "<rethinkdb", ".", "DefaultConnection", ">", ":", "return", ":", "<dict", ">", "rethinkdb", "in...
train
https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/controller/plugins.py#L99-L119
ramrod-project/database-brain
schema/brain/controller/plugins.py
record_state
def record_state(serv_name, state, conn=None): """ MAKE A DOCSTRING :param serv_name: <str> service name of plugin instance :param state: <dictionary> plugin state :param conn: <rethinkdb.DefaultConnection> :return: """ serv_filter = {SERVICE_KEY:serv_name} updated = {PLUGIN_STATE_K...
python
def record_state(serv_name, state, conn=None): """ MAKE A DOCSTRING :param serv_name: <str> service name of plugin instance :param state: <dictionary> plugin state :param conn: <rethinkdb.DefaultConnection> :return: """ serv_filter = {SERVICE_KEY:serv_name} updated = {PLUGIN_STATE_K...
[ "def", "record_state", "(", "serv_name", ",", "state", ",", "conn", "=", "None", ")", ":", "serv_filter", "=", "{", "SERVICE_KEY", ":", "serv_name", "}", "updated", "=", "{", "PLUGIN_STATE_KEY", ":", "state", "}", "return", "RPC", ".", "filter", "(", "se...
MAKE A DOCSTRING :param serv_name: <str> service name of plugin instance :param state: <dictionary> plugin state :param conn: <rethinkdb.DefaultConnection> :return:
[ "MAKE", "A", "DOCSTRING", ":", "param", "serv_name", ":", "<str", ">", "service", "name", "of", "plugin", "instance", ":", "param", "state", ":", "<dictionary", ">", "plugin", "state", ":", "param", "conn", ":", "<rethinkdb", ".", "DefaultConnection", ">", ...
train
https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/controller/plugins.py#L240-L250
OpenVolunteeringPlatform/django-ovp-projects
ovp_projects/emails.py
ApplyMail.sendAppliedToOwner
def sendAppliedToOwner(self, context={}): """ Sent to project owner when user applies to a project """ super(ApplyMail, self).__init__(self.apply.project.owner.email, self.async, self.apply.project.owner.locale) return self.sendEmail('volunteerApplied-ToOwner', 'New volunteer', context)
python
def sendAppliedToOwner(self, context={}): """ Sent to project owner when user applies to a project """ super(ApplyMail, self).__init__(self.apply.project.owner.email, self.async, self.apply.project.owner.locale) return self.sendEmail('volunteerApplied-ToOwner', 'New volunteer', context)
[ "def", "sendAppliedToOwner", "(", "self", ",", "context", "=", "{", "}", ")", ":", "super", "(", "ApplyMail", ",", "self", ")", ".", "__init__", "(", "self", ".", "apply", ".", "project", ".", "owner", ".", "email", ",", "self", ".", "async", ",", ...
Sent to project owner when user applies to a project
[ "Sent", "to", "project", "owner", "when", "user", "applies", "to", "a", "project" ]
train
https://github.com/OpenVolunteeringPlatform/django-ovp-projects/blob/239e27027ca99c7b44ee4f30bf55d06439d49251/ovp_projects/emails.py#L53-L58
rosscdh/hellosign
hellosign/hellosign.py
HelloSignSignature.add_signer
def add_signer(self, signer): """ Simple dict of {'name': 'John Doe', 'email': 'name@example.com'}""" if isinstance(signer, HelloSigner) and signer.validate(): self.signers.append(signer) else: if not signer.validate(): raise Exception("HelloSigner Errors ...
python
def add_signer(self, signer): """ Simple dict of {'name': 'John Doe', 'email': 'name@example.com'}""" if isinstance(signer, HelloSigner) and signer.validate(): self.signers.append(signer) else: if not signer.validate(): raise Exception("HelloSigner Errors ...
[ "def", "add_signer", "(", "self", ",", "signer", ")", ":", "if", "isinstance", "(", "signer", ",", "HelloSigner", ")", "and", "signer", ".", "validate", "(", ")", ":", "self", ".", "signers", ".", "append", "(", "signer", ")", "else", ":", "if", "not...
Simple dict of {'name': 'John Doe', 'email': 'name@example.com'}
[ "Simple", "dict", "of", "{", "name", ":", "John", "Doe", "email", ":", "name" ]
train
https://github.com/rosscdh/hellosign/blob/4061c2733fa9f1b6ebefa99bed69df8373eb93b3/hellosign/hellosign.py#L33-L41
rosscdh/hellosign
hellosign/hellosign.py
HelloSignSignature.add_doc
def add_doc(self, doc): """ Simple dict of {'name': '@filename.pdf'}""" if isinstance(doc, HelloDoc) and doc.validate(): self.docs.append(doc) else: if not doc.validate(): raise Exception("HelloDoc Errors %s" % (doc.errors,)) else: ...
python
def add_doc(self, doc): """ Simple dict of {'name': '@filename.pdf'}""" if isinstance(doc, HelloDoc) and doc.validate(): self.docs.append(doc) else: if not doc.validate(): raise Exception("HelloDoc Errors %s" % (doc.errors,)) else: ...
[ "def", "add_doc", "(", "self", ",", "doc", ")", ":", "if", "isinstance", "(", "doc", ",", "HelloDoc", ")", "and", "doc", ".", "validate", "(", ")", ":", "self", ".", "docs", ".", "append", "(", "doc", ")", "else", ":", "if", "not", "doc", ".", ...
Simple dict of {'name': '@filename.pdf'}
[ "Simple", "dict", "of", "{", "name", ":" ]
train
https://github.com/rosscdh/hellosign/blob/4061c2733fa9f1b6ebefa99bed69df8373eb93b3/hellosign/hellosign.py#L43-L51
rosscdh/hellosign
hellosign/hellosign.py
HelloSignEmbeddedDocumentSigningUrl.create
def create(self, **kwargs): """ returns the JSON object {'embedded': { 'sign_url': 'https://www.hellosign.com/editor/embeddedSign?signature_id={signature_id}&token={token}', 'expires_at': {timestamp} }} """ auth = None if 'auth' in kwar...
python
def create(self, **kwargs): """ returns the JSON object {'embedded': { 'sign_url': 'https://www.hellosign.com/editor/embeddedSign?signature_id={signature_id}&token={token}', 'expires_at': {timestamp} }} """ auth = None if 'auth' in kwar...
[ "def", "create", "(", "self", ",", "*", "*", "kwargs", ")", ":", "auth", "=", "None", "if", "'auth'", "in", "kwargs", ":", "auth", "=", "kwargs", "[", "'auth'", "]", "del", "(", "kwargs", "[", "'auth'", "]", ")", "self", ".", "_url", "=", "'%s%s%...
returns the JSON object {'embedded': { 'sign_url': 'https://www.hellosign.com/editor/embeddedSign?signature_id={signature_id}&token={token}', 'expires_at': {timestamp} }}
[ "returns", "the", "JSON", "object", "{", "embedded", ":", "{", "sign_url", ":", "https", ":", "//", "www", ".", "hellosign", ".", "com", "/", "editor", "/", "embeddedSign?signature_id", "=", "{", "signature_id", "}", "&token", "=", "{", "token", "}", "ex...
train
https://github.com/rosscdh/hellosign/blob/4061c2733fa9f1b6ebefa99bed69df8373eb93b3/hellosign/hellosign.py#L159-L174
mbarakaja/braulio
braulio/git.py
commit_analyzer
def commit_analyzer(commits, label_pattern, label_position="footer"): """Analyzes a list of :class:`~braulio.git.Commit` objects searching for messages that match a given message convention and extract metadata from them. A message convention is determined by ``label_pattern``, which is not a regul...
python
def commit_analyzer(commits, label_pattern, label_position="footer"): """Analyzes a list of :class:`~braulio.git.Commit` objects searching for messages that match a given message convention and extract metadata from them. A message convention is determined by ``label_pattern``, which is not a regul...
[ "def", "commit_analyzer", "(", "commits", ",", "label_pattern", ",", "label_position", "=", "\"footer\"", ")", ":", "# Internally, a real regular expression pattern is used", "pattern_string", "=", "re", ".", "escape", "(", "label_pattern", ")", "# Capturing group patterns"...
Analyzes a list of :class:`~braulio.git.Commit` objects searching for messages that match a given message convention and extract metadata from them. A message convention is determined by ``label_pattern``, which is not a regular expression pattern. Instead it must be a string literals with placehol...
[ "Analyzes", "a", "list", "of", ":", "class", ":", "~braulio", ".", "git", ".", "Commit", "objects", "searching", "for", "messages", "that", "match", "a", "given", "message", "convention", "and", "extract", "metadata", "from", "them", "." ]
train
https://github.com/mbarakaja/braulio/blob/70ab6f0dd631ef78c4da1b39d1c6fb6f9a995d2b/braulio/git.py#L148-L221
mbarakaja/braulio
braulio/git.py
Git.add
def add(self, *files): """Add one or more files to the index running git-add.""" try: _run_command(("git", "add") + files) except CalledProcessError: # Only if the command fails we check if the files # exist, because git-add most of the time fails when ...
python
def add(self, *files): """Add one or more files to the index running git-add.""" try: _run_command(("git", "add") + files) except CalledProcessError: # Only if the command fails we check if the files # exist, because git-add most of the time fails when ...
[ "def", "add", "(", "self", ",", "*", "files", ")", ":", "try", ":", "_run_command", "(", "(", "\"git\"", ",", "\"add\"", ")", "+", "files", ")", "except", "CalledProcessError", ":", "# Only if the command fails we check if the files", "# exist, because git-add most ...
Add one or more files to the index running git-add.
[ "Add", "one", "or", "more", "files", "to", "the", "index", "running", "git", "-", "add", "." ]
train
https://github.com/mbarakaja/braulio/blob/70ab6f0dd631ef78c4da1b39d1c6fb6f9a995d2b/braulio/git.py#L71-L82
mbarakaja/braulio
braulio/git.py
Git.commit
def commit(self, message, files=None): """Run git-commit.""" if files: self.add(*files) return _run_command(["git", "commit", "-m", f'"{message}"'])
python
def commit(self, message, files=None): """Run git-commit.""" if files: self.add(*files) return _run_command(["git", "commit", "-m", f'"{message}"'])
[ "def", "commit", "(", "self", ",", "message", ",", "files", "=", "None", ")", ":", "if", "files", ":", "self", ".", "add", "(", "*", "files", ")", "return", "_run_command", "(", "[", "\"git\"", ",", "\"commit\"", ",", "\"-m\"", ",", "f'\"{message}\"'",...
Run git-commit.
[ "Run", "git", "-", "commit", "." ]
train
https://github.com/mbarakaja/braulio/blob/70ab6f0dd631ef78c4da1b39d1c6fb6f9a995d2b/braulio/git.py#L84-L90
mbarakaja/braulio
braulio/git.py
Git.log
def log(self, _from=None, to=None): """Run git-log.""" command = ["git", "log"] if _from: to = "HEAD" if not to else to revision_range = f"{_from}..{to}" command.append(revision_range) git_log_text = _run_command(command) commit_text_lst = _...
python
def log(self, _from=None, to=None): """Run git-log.""" command = ["git", "log"] if _from: to = "HEAD" if not to else to revision_range = f"{_from}..{to}" command.append(revision_range) git_log_text = _run_command(command) commit_text_lst = _...
[ "def", "log", "(", "self", ",", "_from", "=", "None", ",", "to", "=", "None", ")", ":", "command", "=", "[", "\"git\"", ",", "\"log\"", "]", "if", "_from", ":", "to", "=", "\"HEAD\"", "if", "not", "to", "else", "to", "revision_range", "=", "f\"{_fr...
Run git-log.
[ "Run", "git", "-", "log", "." ]
train
https://github.com/mbarakaja/braulio/blob/70ab6f0dd631ef78c4da1b39d1c6fb6f9a995d2b/braulio/git.py#L92-L105
mbarakaja/braulio
braulio/git.py
Git.tag
def tag(self, name=None): """Create and list tag objects running git-tag command""" command = ["git", "tag"] if not name: command.extend( [ "-l", "--sort=creatordate", "--format=%(creatordate:short)%09%(ref...
python
def tag(self, name=None): """Create and list tag objects running git-tag command""" command = ["git", "tag"] if not name: command.extend( [ "-l", "--sort=creatordate", "--format=%(creatordate:short)%09%(ref...
[ "def", "tag", "(", "self", ",", "name", "=", "None", ")", ":", "command", "=", "[", "\"git\"", ",", "\"tag\"", "]", "if", "not", "name", ":", "command", ".", "extend", "(", "[", "\"-l\"", ",", "\"--sort=creatordate\"", ",", "\"--format=%(creatordate:short)...
Create and list tag objects running git-tag command
[ "Create", "and", "list", "tag", "objects", "running", "git", "-", "tag", "command" ]
train
https://github.com/mbarakaja/braulio/blob/70ab6f0dd631ef78c4da1b39d1c6fb6f9a995d2b/braulio/git.py#L107-L132
devricks/soft_drf
soft_drf/api/routers/__init__.py
DefaultRouter.register
def register(self, prefix, viewset, base_name=None, router_class=None): """ Append the given viewset to the proper registry. """ if base_name is None: base_name = self.get_default_base_name(viewset) if router_class is not None: kwargs = {'trailing_slash':...
python
def register(self, prefix, viewset, base_name=None, router_class=None): """ Append the given viewset to the proper registry. """ if base_name is None: base_name = self.get_default_base_name(viewset) if router_class is not None: kwargs = {'trailing_slash':...
[ "def", "register", "(", "self", ",", "prefix", ",", "viewset", ",", "base_name", "=", "None", ",", "router_class", "=", "None", ")", ":", "if", "base_name", "is", "None", ":", "base_name", "=", "self", ".", "get_default_base_name", "(", "viewset", ")", "...
Append the given viewset to the proper registry.
[ "Append", "the", "given", "viewset", "to", "the", "proper", "registry", "." ]
train
https://github.com/devricks/soft_drf/blob/1869b13f9341bfcebd931059e93de2bc38570da3/soft_drf/api/routers/__init__.py#L16-L34
devricks/soft_drf
soft_drf/api/routers/__init__.py
DefaultRouter.register_nested
def register_nested( self, parent_prefix, prefix, viewset, base_name=None, parent_lookup_name=None, depth_level=1 ): """ Register a nested viewset wihtout worrying of instantiate a nested router for registry. """ kwargs = { 'trailing_slash'...
python
def register_nested( self, parent_prefix, prefix, viewset, base_name=None, parent_lookup_name=None, depth_level=1 ): """ Register a nested viewset wihtout worrying of instantiate a nested router for registry. """ kwargs = { 'trailing_slash'...
[ "def", "register_nested", "(", "self", ",", "parent_prefix", ",", "prefix", ",", "viewset", ",", "base_name", "=", "None", ",", "parent_lookup_name", "=", "None", ",", "depth_level", "=", "1", ")", ":", "kwargs", "=", "{", "'trailing_slash'", ":", "bool", ...
Register a nested viewset wihtout worrying of instantiate a nested router for registry.
[ "Register", "a", "nested", "viewset", "wihtout", "worrying", "of", "instantiate", "a", "nested", "router", "for", "registry", "." ]
train
https://github.com/devricks/soft_drf/blob/1869b13f9341bfcebd931059e93de2bc38570da3/soft_drf/api/routers/__init__.py#L36-L78
devricks/soft_drf
soft_drf/api/routers/__init__.py
DefaultRouter.get_urls
def get_urls(self): """ Generate the list of URL patterns including the registered single object routers urls. """ base_urls = super(SimpleRouter, self).get_urls() single_urls = sum([r.urls for r in self._single_object_registry], []) nested_urls = sum([r.urls for ...
python
def get_urls(self): """ Generate the list of URL patterns including the registered single object routers urls. """ base_urls = super(SimpleRouter, self).get_urls() single_urls = sum([r.urls for r in self._single_object_registry], []) nested_urls = sum([r.urls for ...
[ "def", "get_urls", "(", "self", ")", ":", "base_urls", "=", "super", "(", "SimpleRouter", ",", "self", ")", ".", "get_urls", "(", ")", "single_urls", "=", "sum", "(", "[", "r", ".", "urls", "for", "r", "in", "self", ".", "_single_object_registry", "]",...
Generate the list of URL patterns including the registered single object routers urls.
[ "Generate", "the", "list", "of", "URL", "patterns", "including", "the", "registered", "single", "object", "routers", "urls", "." ]
train
https://github.com/devricks/soft_drf/blob/1869b13f9341bfcebd931059e93de2bc38570da3/soft_drf/api/routers/__init__.py#L80-L89
DoWhileGeek/authentise-services
authentise_services/config.py
Config.parse_config
def parse_config(path): """parse either the config file we found, or use some canned defaults""" config = configparser.ConfigParser() if path: # if user has config with user creds in it, this will grab it config.read(path) try: return {k: v for k, v in config["...
python
def parse_config(path): """parse either the config file we found, or use some canned defaults""" config = configparser.ConfigParser() if path: # if user has config with user creds in it, this will grab it config.read(path) try: return {k: v for k, v in config["...
[ "def", "parse_config", "(", "path", ")", ":", "config", "=", "configparser", ".", "ConfigParser", "(", ")", "if", "path", ":", "# if user has config with user creds in it, this will grab it", "config", ".", "read", "(", "path", ")", "try", ":", "return", "{", "k...
parse either the config file we found, or use some canned defaults
[ "parse", "either", "the", "config", "file", "we", "found", "or", "use", "some", "canned", "defaults" ]
train
https://github.com/DoWhileGeek/authentise-services/blob/ee32bd7f7de15d3fb24c0a6374640d3a1ec8096d/authentise_services/config.py#L25-L35
b3j0f/utils
b3j0f/utils/path.py
lookup
def lookup(path, cache=True, scope=None, safe=False): """Get element reference from input element. The element can be a builtin/globals/scope object or is resolved from the current execution stack. :limitations: it does not resolve class methods or static values such as True, False, numbers, s...
python
def lookup(path, cache=True, scope=None, safe=False): """Get element reference from input element. The element can be a builtin/globals/scope object or is resolved from the current execution stack. :limitations: it does not resolve class methods or static values such as True, False, numbers, s...
[ "def", "lookup", "(", "path", ",", "cache", "=", "True", ",", "scope", "=", "None", ",", "safe", "=", "False", ")", ":", "result", "=", "None", "found", "=", "path", "and", "cache", "and", "path", "in", "__LOOKUP_CACHE", "if", "found", ":", "result",...
Get element reference from input element. The element can be a builtin/globals/scope object or is resolved from the current execution stack. :limitations: it does not resolve class methods or static values such as True, False, numbers, string and keywords. :param str path: full path to a pytho...
[ "Get", "element", "reference", "from", "input", "element", "." ]
train
https://github.com/b3j0f/utils/blob/793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff/b3j0f/utils/path.py#L100-L211
b3j0f/utils
b3j0f/utils/path.py
getpath
def getpath(element): """Get full path of a given element such as the opposite of the resolve_path behaviour. :param element: must be directly defined into a module or a package and has the attribute '__name__'. :return: element absolute path. :rtype: str :raises AttributeError: if el...
python
def getpath(element): """Get full path of a given element such as the opposite of the resolve_path behaviour. :param element: must be directly defined into a module or a package and has the attribute '__name__'. :return: element absolute path. :rtype: str :raises AttributeError: if el...
[ "def", "getpath", "(", "element", ")", ":", "if", "not", "hasattr", "(", "element", ",", "'__name__'", ")", ":", "raise", "AttributeError", "(", "'element {0} must have the attribute __name__'", ".", "format", "(", "element", ")", ")", "result", "=", "element", ...
Get full path of a given element such as the opposite of the resolve_path behaviour. :param element: must be directly defined into a module or a package and has the attribute '__name__'. :return: element absolute path. :rtype: str :raises AttributeError: if element has not the attribute _...
[ "Get", "full", "path", "of", "a", "given", "element", "such", "as", "the", "opposite", "of", "the", "resolve_path", "behaviour", "." ]
train
https://github.com/b3j0f/utils/blob/793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff/b3j0f/utils/path.py#L214-L240
bbiskup/purkinje-messages
purkinje_messages/message.py
register_eventclass
def register_eventclass(event_id): """Decorator for registering event classes for parsing """ def register(cls): if not issubclass(cls, Event): raise MessageException(('Cannot register a class that' ' is not a subclass of Event')) EVENT_REGISTR...
python
def register_eventclass(event_id): """Decorator for registering event classes for parsing """ def register(cls): if not issubclass(cls, Event): raise MessageException(('Cannot register a class that' ' is not a subclass of Event')) EVENT_REGISTR...
[ "def", "register_eventclass", "(", "event_id", ")", ":", "def", "register", "(", "cls", ")", ":", "if", "not", "issubclass", "(", "cls", ",", "Event", ")", ":", "raise", "MessageException", "(", "(", "'Cannot register a class that'", "' is not a subclass of Event'...
Decorator for registering event classes for parsing
[ "Decorator", "for", "registering", "event", "classes", "for", "parsing" ]
train
https://github.com/bbiskup/purkinje-messages/blob/ba4217d993a86fd882bcf73d206d2910e65316dd/purkinje_messages/message.py#L141-L152
stevepeak/inquiry
inquiry/helpers.py
unique
def unique(lst): """Unique with keeping sort/order ["a", "c", "b", "c", "c", ["d", "e"]] Results in ["a", "c", "b", "d", "e"] """ nl = [] [(nl.append(e) if type(e) is not list else nl.extend(e)) \ for e in lst if e not in nl] return nl
python
def unique(lst): """Unique with keeping sort/order ["a", "c", "b", "c", "c", ["d", "e"]] Results in ["a", "c", "b", "d", "e"] """ nl = [] [(nl.append(e) if type(e) is not list else nl.extend(e)) \ for e in lst if e not in nl] return nl
[ "def", "unique", "(", "lst", ")", ":", "nl", "=", "[", "]", "[", "(", "nl", ".", "append", "(", "e", ")", "if", "type", "(", "e", ")", "is", "not", "list", "else", "nl", ".", "extend", "(", "e", ")", ")", "for", "e", "in", "lst", "if", "e...
Unique with keeping sort/order ["a", "c", "b", "c", "c", ["d", "e"]] Results in ["a", "c", "b", "d", "e"]
[ "Unique", "with", "keeping", "sort", "/", "order", "[", "a", "c", "b", "c", "c", "[", "d", "e", "]]" ]
train
https://github.com/stevepeak/inquiry/blob/f6ea435c302560ba19985b5d4ce2c97e2f321508/inquiry/helpers.py#L5-L15
stevepeak/inquiry
inquiry/helpers.py
_merge_fix
def _merge_fix(d): """Fixes keys that start with "&" and "-" d = { "&steve": 10, "-gary": 4 } result = { "steve": 10, "gary": 4 } """ if type(d) is dict: for key in d.keys(): if key[0] in ('&', '-'): ...
python
def _merge_fix(d): """Fixes keys that start with "&" and "-" d = { "&steve": 10, "-gary": 4 } result = { "steve": 10, "gary": 4 } """ if type(d) is dict: for key in d.keys(): if key[0] in ('&', '-'): ...
[ "def", "_merge_fix", "(", "d", ")", ":", "if", "type", "(", "d", ")", "is", "dict", ":", "for", "key", "in", "d", ".", "keys", "(", ")", ":", "if", "key", "[", "0", "]", "in", "(", "'&'", ",", "'-'", ")", ":", "d", "[", "key", "[", "1", ...
Fixes keys that start with "&" and "-" d = { "&steve": 10, "-gary": 4 } result = { "steve": 10, "gary": 4 }
[ "Fixes", "keys", "that", "start", "with", "&", "and", "-", "d", "=", "{", "&steve", ":", "10", "-", "gary", ":", "4", "}", "result", "=", "{", "steve", ":", "10", "gary", ":", "4", "}" ]
train
https://github.com/stevepeak/inquiry/blob/f6ea435c302560ba19985b5d4ce2c97e2f321508/inquiry/helpers.py#L18-L33
stevepeak/inquiry
inquiry/helpers.py
merge
def merge(d1, d2): """This method does cool stuff like append and replace for dicts d1 = { "steve": 10, "gary": 4 } d2 = { "&steve": 11, "-gary": null } result = { "steve": [10, 11] } """ d1, d2 = deepcopy(d1),...
python
def merge(d1, d2): """This method does cool stuff like append and replace for dicts d1 = { "steve": 10, "gary": 4 } d2 = { "&steve": 11, "-gary": null } result = { "steve": [10, 11] } """ d1, d2 = deepcopy(d1),...
[ "def", "merge", "(", "d1", ",", "d2", ")", ":", "d1", ",", "d2", "=", "deepcopy", "(", "d1", ")", ",", "deepcopy", "(", "d2", ")", "if", "d1", "==", "{", "}", "or", "type", "(", "d1", ")", "is", "not", "dict", ":", "return", "_merge_fix", "("...
This method does cool stuff like append and replace for dicts d1 = { "steve": 10, "gary": 4 } d2 = { "&steve": 11, "-gary": null } result = { "steve": [10, 11] }
[ "This", "method", "does", "cool", "stuff", "like", "append", "and", "replace", "for", "dicts", "d1", "=", "{", "steve", ":", "10", "gary", ":", "4", "}", "d2", "=", "{", "&steve", ":", "11", "-", "gary", ":", "null", "}", "result", "=", "{", "ste...
train
https://github.com/stevepeak/inquiry/blob/f6ea435c302560ba19985b5d4ce2c97e2f321508/inquiry/helpers.py#L36-L85
stevepeak/inquiry
inquiry/helpers.py
json_minify
def json_minify(string, strip_space=True): # pragma: no cover """Removes whitespace from json strings, returning the string """ in_string = False in_multi = False in_single = False new_str = [] index = 0 for match in re.finditer(TOKENIZER, string): if not (in_multi or in_singl...
python
def json_minify(string, strip_space=True): # pragma: no cover """Removes whitespace from json strings, returning the string """ in_string = False in_multi = False in_single = False new_str = [] index = 0 for match in re.finditer(TOKENIZER, string): if not (in_multi or in_singl...
[ "def", "json_minify", "(", "string", ",", "strip_space", "=", "True", ")", ":", "# pragma: no cover", "in_string", "=", "False", "in_multi", "=", "False", "in_single", "=", "False", "new_str", "=", "[", "]", "index", "=", "0", "for", "match", "in", "re", ...
Removes whitespace from json strings, returning the string
[ "Removes", "whitespace", "from", "json", "strings", "returning", "the", "string" ]
train
https://github.com/stevepeak/inquiry/blob/f6ea435c302560ba19985b5d4ce2c97e2f321508/inquiry/helpers.py#L110-L152
alexlovelltroy/django-classy-mail
classy_mail/mixins/base.py
resolve_template
def resolve_template(template): "Accepts a template object, path-to-template or list of paths" if isinstance(template, (list, tuple)): return loader.select_template(template) elif isinstance(template, basestring): try: return loader.get_template(template) except TemplateD...
python
def resolve_template(template): "Accepts a template object, path-to-template or list of paths" if isinstance(template, (list, tuple)): return loader.select_template(template) elif isinstance(template, basestring): try: return loader.get_template(template) except TemplateD...
[ "def", "resolve_template", "(", "template", ")", ":", "if", "isinstance", "(", "template", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "loader", ".", "select_template", "(", "template", ")", "elif", "isinstance", "(", "template", ",", "basestr...
Accepts a template object, path-to-template or list of paths
[ "Accepts", "a", "template", "object", "path", "-", "to", "-", "template", "or", "list", "of", "paths" ]
train
https://github.com/alexlovelltroy/django-classy-mail/blob/1f225555bce44d8dbc4c695a4b7ffc71ac500168/classy_mail/mixins/base.py#L6-L16
brentpayne/kennyg
kennyg/element.py
Collector.update
def update(self, obj=None, **kwargs): # known special case of dict.update """ dict.update is special cased and does not end up calling __setitem___ overriding to ensure it gets called. Below is the dict.update description: D.update([E, ]**F) -> None. Update D from dict/iterable ...
python
def update(self, obj=None, **kwargs): # known special case of dict.update """ dict.update is special cased and does not end up calling __setitem___ overriding to ensure it gets called. Below is the dict.update description: D.update([E, ]**F) -> None. Update D from dict/iterable ...
[ "def", "update", "(", "self", ",", "obj", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# known special case of dict.update", "if", "obj", "is", "None", ":", "pass", "elif", "hasattr", "(", "obj", ",", "'iteritems'", ")", ":", "# iteritems saves memory an...
dict.update is special cased and does not end up calling __setitem___ overriding to ensure it gets called. Below is the dict.update description: D.update([E, ]**F) -> None. Update D from dict/iterable E and F. If E present and has a .keys() method, does: for k in E: D[k] = E[k] ...
[ "dict", ".", "update", "is", "special", "cased", "and", "does", "not", "end", "up", "calling", "__setitem___", "overriding", "to", "ensure", "it", "gets", "called", ".", "Below", "is", "the", "dict", ".", "update", "description", ":", "D", ".", "update", ...
train
https://github.com/brentpayne/kennyg/blob/c688dd6d270bb7dcdcce7f08c54eafb1bf3232f2/kennyg/element.py#L25-L48
brentpayne/kennyg
kennyg/element.py
DateValue.value
def value(self, value, *args, **kwargs): """ Takes a string value and returns the Date based on the format """ from datetime import datetime value = self.obj.value(value, *args, **kwargs) try: rv = datetime.strptime(value, self.format) except ValueErro...
python
def value(self, value, *args, **kwargs): """ Takes a string value and returns the Date based on the format """ from datetime import datetime value = self.obj.value(value, *args, **kwargs) try: rv = datetime.strptime(value, self.format) except ValueErro...
[ "def", "value", "(", "self", ",", "value", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "datetime", "import", "datetime", "value", "=", "self", ".", "obj", ".", "value", "(", "value", ",", "*", "args", ",", "*", "*", "kwargs", ")"...
Takes a string value and returns the Date based on the format
[ "Takes", "a", "string", "value", "and", "returns", "the", "Date", "based", "on", "the", "format" ]
train
https://github.com/brentpayne/kennyg/blob/c688dd6d270bb7dcdcce7f08c54eafb1bf3232f2/kennyg/element.py#L123-L133
klmitch/framer
framer/transport.py
FramerAdaptor.factory
def factory(cls, client, *args, **kwargs): """ Generates and returns a callable suitable for passing as the ``protocol_factory`` parameter of the ``create_connection()`` or ``create_server()`` loop methods. This class method performs some sanity checks on the arguments, and is p...
python
def factory(cls, client, *args, **kwargs): """ Generates and returns a callable suitable for passing as the ``protocol_factory`` parameter of the ``create_connection()`` or ``create_server()`` loop methods. This class method performs some sanity checks on the arguments, and is p...
[ "def", "factory", "(", "cls", ",", "client", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Some basic sanity checks", "if", "not", "six", ".", "callable", "(", "client", ")", ":", "raise", "exc", ".", "FramerException", "(", "\"Protocol factory i...
Generates and returns a callable suitable for passing as the ``protocol_factory`` parameter of the ``create_connection()`` or ``create_server()`` loop methods. This class method performs some sanity checks on the arguments, and is preferred over using a manually constructed ``lambda``. ...
[ "Generates", "and", "returns", "a", "callable", "suitable", "for", "passing", "as", "the", "protocol_factory", "parameter", "of", "the", "create_connection", "()", "or", "create_server", "()", "loop", "methods", ".", "This", "class", "method", "performs", "some", ...
train
https://github.com/klmitch/framer/blob/bd34cee9737793dab61d1d8973930b64bd08acb4/framer/transport.py#L52-L88
klmitch/framer
framer/transport.py
FramerAdaptor._interpret_framer
def _interpret_framer(self, args, kwargs): """ Interprets positional and keyword arguments related to framers. :param args: A tuple of positional arguments. The first such argument will be interpreted as a framer object, and the second will be ...
python
def _interpret_framer(self, args, kwargs): """ Interprets positional and keyword arguments related to framers. :param args: A tuple of positional arguments. The first such argument will be interpreted as a framer object, and the second will be ...
[ "def", "_interpret_framer", "(", "self", ",", "args", ",", "kwargs", ")", ":", "# Cannot specify both positional and keyword arguments, but", "# must provide one or the other", "if", "not", "args", "and", "not", "kwargs", ":", "raise", "exc", ".", "InvalidFramerSpecificat...
Interprets positional and keyword arguments related to framers. :param args: A tuple of positional arguments. The first such argument will be interpreted as a framer object, and the second will be interpreted as a framer state. :pa...
[ "Interprets", "positional", "and", "keyword", "arguments", "related", "to", "framers", "." ]
train
https://github.com/klmitch/framer/blob/bd34cee9737793dab61d1d8973930b64bd08acb4/framer/transport.py#L131-L210
klmitch/framer
framer/transport.py
FramerAdaptor.connection_made
def connection_made(self, transport): """ Called by the underlying transport when a connection is made. :param transport: The transport representing the connection. """ # Save the underlying transport self._transport = transport # Call connection_made() on the ...
python
def connection_made(self, transport): """ Called by the underlying transport when a connection is made. :param transport: The transport representing the connection. """ # Save the underlying transport self._transport = transport # Call connection_made() on the ...
[ "def", "connection_made", "(", "self", ",", "transport", ")", ":", "# Save the underlying transport", "self", ".", "_transport", "=", "transport", "# Call connection_made() on the client protocol, passing", "# ourself as the transport", "self", ".", "_client", ".", "connectio...
Called by the underlying transport when a connection is made. :param transport: The transport representing the connection.
[ "Called", "by", "the", "underlying", "transport", "when", "a", "connection", "is", "made", "." ]
train
https://github.com/klmitch/framer/blob/bd34cee9737793dab61d1d8973930b64bd08acb4/framer/transport.py#L212-L224
klmitch/framer
framer/transport.py
FramerAdaptor.data_received
def data_received(self, data): """ Called by the underlying transport when data is received. :param data: The data received on the connection. """ # First, add the data to the receive buffer self._recv_buf += data # Now, pass all frames we can find to the clien...
python
def data_received(self, data): """ Called by the underlying transport when data is received. :param data: The data received on the connection. """ # First, add the data to the receive buffer self._recv_buf += data # Now, pass all frames we can find to the clien...
[ "def", "data_received", "(", "self", ",", "data", ")", ":", "# First, add the data to the receive buffer", "self", ".", "_recv_buf", "+=", "data", "# Now, pass all frames we can find to the client protocol", "while", "self", ".", "_recv_buf", "and", "not", "self", ".", ...
Called by the underlying transport when data is received. :param data: The data received on the connection.
[ "Called", "by", "the", "underlying", "transport", "when", "data", "is", "received", "." ]
train
https://github.com/klmitch/framer/blob/bd34cee9737793dab61d1d8973930b64bd08acb4/framer/transport.py#L257-L278
klmitch/framer
framer/transport.py
FramerAdaptor.get_extra_info
def get_extra_info(self, name, default=None): """ Called by the client protocol to return optional transport information. Information requests not recognized by the ``FramerProtocol`` are passed on to the underlying transport. The values of ``name`` recognized directly by ...
python
def get_extra_info(self, name, default=None): """ Called by the client protocol to return optional transport information. Information requests not recognized by the ``FramerProtocol`` are passed on to the underlying transport. The values of ``name`` recognized directly by ...
[ "def", "get_extra_info", "(", "self", ",", "name", ",", "default", "=", "None", ")", ":", "# Handle data we know about", "if", "name", "in", "self", ".", "_handlers", ":", "return", "self", ".", "_handlers", "[", "name", "]", "(", "self", ")", "# Call get_...
Called by the client protocol to return optional transport information. Information requests not recognized by the ``FramerProtocol`` are passed on to the underlying transport. The values of ``name`` recognized directly by ``FramerProtocol`` are: =============== =============...
[ "Called", "by", "the", "client", "protocol", "to", "return", "optional", "transport", "information", ".", "Information", "requests", "not", "recognized", "by", "the", "FramerProtocol", "are", "passed", "on", "to", "the", "underlying", "transport", "." ]
train
https://github.com/klmitch/framer/blob/bd34cee9737793dab61d1d8973930b64bd08acb4/framer/transport.py#L307-L342
klmitch/framer
framer/transport.py
FramerAdaptor.resume_reading
def resume_reading(self): """ Called by the client protocol to resume the receiving end. The protocol's ``frame_received()`` method will be called once again if some data is available for reading. """ # Clear the read pause status self._recv_paused = False ...
python
def resume_reading(self): """ Called by the client protocol to resume the receiving end. The protocol's ``frame_received()`` method will be called once again if some data is available for reading. """ # Clear the read pause status self._recv_paused = False ...
[ "def", "resume_reading", "(", "self", ")", ":", "# Clear the read pause status", "self", ".", "_recv_paused", "=", "False", "# Call resume_reading() on the transport", "self", ".", "_transport", ".", "resume_reading", "(", ")", "# If there's data in the receive buffer, pass i...
Called by the client protocol to resume the receiving end. The protocol's ``frame_received()`` method will be called once again if some data is available for reading.
[ "Called", "by", "the", "client", "protocol", "to", "resume", "the", "receiving", "end", ".", "The", "protocol", "s", "frame_received", "()", "method", "will", "be", "called", "once", "again", "if", "some", "data", "is", "available", "for", "reading", "." ]
train
https://github.com/klmitch/framer/blob/bd34cee9737793dab61d1d8973930b64bd08acb4/framer/transport.py#L358-L374
klmitch/framer
framer/transport.py
FramerAdaptor.set_write_buffer_limits
def set_write_buffer_limits(self, high=None, low=None): """ Called by the client protocol to set the high- and low-water limits for write flow control. These two values control when call the protocol's ``pause_writing()`` and ``resume_writing()`` methods are called. ...
python
def set_write_buffer_limits(self, high=None, low=None): """ Called by the client protocol to set the high- and low-water limits for write flow control. These two values control when call the protocol's ``pause_writing()`` and ``resume_writing()`` methods are called. ...
[ "def", "set_write_buffer_limits", "(", "self", ",", "high", "=", "None", ",", "low", "=", "None", ")", ":", "# Call set_write_buffer_limits() on the transport", "self", ".", "_transport", ".", "set_write_buffer_limits", "(", "high", "=", "high", ",", "low", "=", ...
Called by the client protocol to set the high- and low-water limits for write flow control. These two values control when call the protocol's ``pause_writing()`` and ``resume_writing()`` methods are called. :param high: The high-water limit. Must be a non-negative ...
[ "Called", "by", "the", "client", "protocol", "to", "set", "the", "high", "-", "and", "low", "-", "water", "limits", "for", "write", "flow", "control", "." ]
train
https://github.com/klmitch/framer/blob/bd34cee9737793dab61d1d8973930b64bd08acb4/framer/transport.py#L413-L433
klmitch/framer
framer/transport.py
FramerAdaptor.send_frame
def send_frame(self, frame): """ Called by the client protocol to send a frame to the remote peer. This method does not block; it buffers the data and arranges for it to be sent out asynchronously. :param frame: The frame to send to the peer. Must be in the ...
python
def send_frame(self, frame): """ Called by the client protocol to send a frame to the remote peer. This method does not block; it buffers the data and arranges for it to be sent out asynchronously. :param frame: The frame to send to the peer. Must be in the ...
[ "def", "send_frame", "(", "self", ",", "frame", ")", ":", "# Convert the frame to bytes and write them to the connection", "data", "=", "self", ".", "_send_framer", ".", "to_bytes", "(", "frame", ",", "self", ".", "_send_state", ")", "self", ".", "_transport", "."...
Called by the client protocol to send a frame to the remote peer. This method does not block; it buffers the data and arranges for it to be sent out asynchronously. :param frame: The frame to send to the peer. Must be in the format expected by the currently active send ...
[ "Called", "by", "the", "client", "protocol", "to", "send", "a", "frame", "to", "the", "remote", "peer", ".", "This", "method", "does", "not", "block", ";", "it", "buffers", "the", "data", "and", "arranges", "for", "it", "to", "be", "sent", "out", "asyn...
train
https://github.com/klmitch/framer/blob/bd34cee9737793dab61d1d8973930b64bd08acb4/framer/transport.py#L447-L460
klmitch/framer
framer/transport.py
FramerAdaptor.push_framer
def push_framer(self, *args, **kwargs): """ Called by the client protocol to temporarily switch to a new send framer, receive framer, or both. Can be called multiple times. Each call to ``push_framer()`` must be paired with a call to ``pop_framer()``, which restores to the prev...
python
def push_framer(self, *args, **kwargs): """ Called by the client protocol to temporarily switch to a new send framer, receive framer, or both. Can be called multiple times. Each call to ``push_framer()`` must be paired with a call to ``pop_framer()``, which restores to the prev...
[ "def", "push_framer", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# First, interpret the arguments", "elem", "=", "self", ".", "_interpret_framer", "(", "args", ",", "kwargs", ")", "# Append the element to the framer stack", "self", ".", "...
Called by the client protocol to temporarily switch to a new send framer, receive framer, or both. Can be called multiple times. Each call to ``push_framer()`` must be paired with a call to ``pop_framer()``, which restores to the previously set framer. When called with positio...
[ "Called", "by", "the", "client", "protocol", "to", "temporarily", "switch", "to", "a", "new", "send", "framer", "receive", "framer", "or", "both", ".", "Can", "be", "called", "multiple", "times", ".", "Each", "call", "to", "push_framer", "()", "must", "be"...
train
https://github.com/klmitch/framer/blob/bd34cee9737793dab61d1d8973930b64bd08acb4/framer/transport.py#L462-L492
klmitch/framer
framer/transport.py
FramerAdaptor.set_framer
def set_framer(self, *args, **kwargs): """ Called by the client protocol to replace the current send framer, receive framer, or both. This does not alter the stack maintained by ``push_framer()`` and ``pop_framer()``; if this method is called after ``push_framer()``, then ...
python
def set_framer(self, *args, **kwargs): """ Called by the client protocol to replace the current send framer, receive framer, or both. This does not alter the stack maintained by ``push_framer()`` and ``pop_framer()``; if this method is called after ``push_framer()``, then ...
[ "def", "set_framer", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# First, interpret the arguments", "elem", "=", "self", ".", "_interpret_framer", "(", "args", ",", "kwargs", ")", "# Now, replace the current top of the framer stack", "self", ...
Called by the client protocol to replace the current send framer, receive framer, or both. This does not alter the stack maintained by ``push_framer()`` and ``pop_framer()``; if this method is called after ``push_framer()``, then ``pop_framer()`` is called, the framers in force at the t...
[ "Called", "by", "the", "client", "protocol", "to", "replace", "the", "current", "send", "framer", "receive", "framer", "or", "both", ".", "This", "does", "not", "alter", "the", "stack", "maintained", "by", "push_framer", "()", "and", "pop_framer", "()", ";",...
train
https://github.com/klmitch/framer/blob/bd34cee9737793dab61d1d8973930b64bd08acb4/framer/transport.py#L509-L540
exekias/droplet
droplet/web/menus.py
menu
def menu(): """ Return global menu composed from all modules menu. This method will compose the global menu by calling menu() function for module, it should be located under module_path.menu module """ root = MenuItem('') for mod in droplet.modules(): if mod.installed: ...
python
def menu(): """ Return global menu composed from all modules menu. This method will compose the global menu by calling menu() function for module, it should be located under module_path.menu module """ root = MenuItem('') for mod in droplet.modules(): if mod.installed: ...
[ "def", "menu", "(", ")", ":", "root", "=", "MenuItem", "(", "''", ")", "for", "mod", "in", "droplet", ".", "modules", "(", ")", ":", "if", "mod", ".", "installed", ":", "module_path", "=", "mod", ".", "__class__", ".", "__module__", ".", "rsplit", ...
Return global menu composed from all modules menu. This method will compose the global menu by calling menu() function for module, it should be located under module_path.menu module
[ "Return", "global", "menu", "composed", "from", "all", "modules", "menu", "." ]
train
https://github.com/exekias/droplet/blob/aeac573a2c1c4b774e99d5414a1c79b1bb734941/droplet/web/menus.py#L56-L72
exekias/droplet
droplet/web/menus.py
MenuItem.append
def append(self, item): """ Add the given item as children """ if self.url: raise TypeError('Menu items with URL cannot have childrens') # Look for already present common node if not item.is_leaf(): for current_item in self.items: ...
python
def append(self, item): """ Add the given item as children """ if self.url: raise TypeError('Menu items with URL cannot have childrens') # Look for already present common node if not item.is_leaf(): for current_item in self.items: ...
[ "def", "append", "(", "self", ",", "item", ")", ":", "if", "self", ".", "url", ":", "raise", "TypeError", "(", "'Menu items with URL cannot have childrens'", ")", "# Look for already present common node", "if", "not", "item", ".", "is_leaf", "(", ")", ":", "for"...
Add the given item as children
[ "Add", "the", "given", "item", "as", "children" ]
train
https://github.com/exekias/droplet/blob/aeac573a2c1c4b774e99d5414a1c79b1bb734941/droplet/web/menus.py#L34-L50
rbarrois/confutils
confutils/configreader.py
ConfigReader.parse_file
def parse_file(self, filename, skip_unreadable=False): """Parse a file from its name (instead of fds). If skip_unreadable is False and the file can't be read, will raise a ConfigReadingError. """ if not os.access(filename, os.R_OK): if skip_unreadable: ...
python
def parse_file(self, filename, skip_unreadable=False): """Parse a file from its name (instead of fds). If skip_unreadable is False and the file can't be read, will raise a ConfigReadingError. """ if not os.access(filename, os.R_OK): if skip_unreadable: ...
[ "def", "parse_file", "(", "self", ",", "filename", ",", "skip_unreadable", "=", "False", ")", ":", "if", "not", "os", ".", "access", "(", "filename", ",", "os", ".", "R_OK", ")", ":", "if", "skip_unreadable", ":", "return", "raise", "ConfigReadingError", ...
Parse a file from its name (instead of fds). If skip_unreadable is False and the file can't be read, will raise a ConfigReadingError.
[ "Parse", "a", "file", "from", "its", "name", "(", "instead", "of", "fds", ")", "." ]
train
https://github.com/rbarrois/confutils/blob/26bbb3f31c09a99ee2104263a9e97d6d3fc8e4f4/confutils/configreader.py#L127-L138
ardydedase/pycouchbase
pycouchbase/document.py
Document.doc_id
def doc_id(self): """Returns the couchbase document's id, object property. :returns: The document id (that is created from :attr:'doc_type' and :attr:'__key_field__' value, or auto-hashed document id at first saving). :rtype: unicode """ if self.id: ...
python
def doc_id(self): """Returns the couchbase document's id, object property. :returns: The document id (that is created from :attr:'doc_type' and :attr:'__key_field__' value, or auto-hashed document id at first saving). :rtype: unicode """ if self.id: ...
[ "def", "doc_id", "(", "self", ")", ":", "if", "self", ".", "id", ":", "return", "'%s_%s'", "%", "(", "self", ".", "doc_type", ",", "self", ".", "id", ".", "lower", "(", ")", ")", "return", "self", ".", "_hashed_key" ]
Returns the couchbase document's id, object property. :returns: The document id (that is created from :attr:'doc_type' and :attr:'__key_field__' value, or auto-hashed document id at first saving). :rtype: unicode
[ "Returns", "the", "couchbase", "document", "s", "id", "object", "property", "." ]
train
https://github.com/ardydedase/pycouchbase/blob/6f010b4d2ef41aead2366878d0cf0b1284c0db0e/pycouchbase/document.py#L97-L107
ardydedase/pycouchbase
pycouchbase/document.py
Document.touch
def touch(self, expiration): """Updates the current document's expiration value. :param expiration: Expiration in seconds for the document to be removed by couchbase server, defaults to 0 - will never expire. :type expiration: int :returns: Response from CouchbaseClient. ...
python
def touch(self, expiration): """Updates the current document's expiration value. :param expiration: Expiration in seconds for the document to be removed by couchbase server, defaults to 0 - will never expire. :type expiration: int :returns: Response from CouchbaseClient. ...
[ "def", "touch", "(", "self", ",", "expiration", ")", ":", "if", "not", "self", ".", "cas_value", "or", "not", "self", ".", "doc_id", ":", "raise", "self", ".", "DoesNotExist", "(", "self", ")", "return", "self", ".", "bucket", ".", "touch", "(", "sel...
Updates the current document's expiration value. :param expiration: Expiration in seconds for the document to be removed by couchbase server, defaults to 0 - will never expire. :type expiration: int :returns: Response from CouchbaseClient. :rtype: unicode :raises: :e...
[ "Updates", "the", "current", "document", "s", "expiration", "value", "." ]
train
https://github.com/ardydedase/pycouchbase/blob/6f010b4d2ef41aead2366878d0cf0b1284c0db0e/pycouchbase/document.py#L245-L258
limpyd/redis-limpyd-extensions
limpyd_extensions/dynamic/collection.py
CollectionManagerForModelWithDynamicFieldMixin.dynamic_filter
def dynamic_filter(self, field_name, dynamic_part, value, index_suffix=''): """ Add a filter to the collection, using a dynamic field. The key part of the filter is composed using the field_name, which must be the field name of a dynamic field on the attached model, and a dynamic part. ...
python
def dynamic_filter(self, field_name, dynamic_part, value, index_suffix=''): """ Add a filter to the collection, using a dynamic field. The key part of the filter is composed using the field_name, which must be the field name of a dynamic field on the attached model, and a dynamic part. ...
[ "def", "dynamic_filter", "(", "self", ",", "field_name", ",", "dynamic_part", ",", "value", ",", "index_suffix", "=", "''", ")", ":", "field_name_parts", "=", "field_name", ".", "split", "(", "'__'", ")", "real_field_name", "=", "field_name_parts", ".", "pop",...
Add a filter to the collection, using a dynamic field. The key part of the filter is composed using the field_name, which must be the field name of a dynamic field on the attached model, and a dynamic part. The index_suffix allow to specify which index to use. It's an empty string by def...
[ "Add", "a", "filter", "to", "the", "collection", "using", "a", "dynamic", "field", ".", "The", "key", "part", "of", "the", "filter", "is", "composed", "using", "the", "field_name", "which", "must", "be", "the", "field", "name", "of", "a", "dynamic", "fie...
train
https://github.com/limpyd/redis-limpyd-extensions/blob/13f34e39efd2f802761457da30ab2a4213b63934/limpyd_extensions/dynamic/collection.py#L9-L28
emencia/emencia-django-forum
forum/admin.py
ThreadAdmin.save_model
def save_model(self, request, obj, form, change): """ Surclasse la méthode de sauvegarde de l'admin du modèle pour y rajouter automatiquement l'auteur qui créé l'objet """ instance = form.save(commit=False) if not(instance.created): instance.author = request....
python
def save_model(self, request, obj, form, change): """ Surclasse la méthode de sauvegarde de l'admin du modèle pour y rajouter automatiquement l'auteur qui créé l'objet """ instance = form.save(commit=False) if not(instance.created): instance.author = request....
[ "def", "save_model", "(", "self", ",", "request", ",", "obj", ",", "form", ",", "change", ")", ":", "instance", "=", "form", ".", "save", "(", "commit", "=", "False", ")", "if", "not", "(", "instance", ".", "created", ")", ":", "instance", ".", "au...
Surclasse la méthode de sauvegarde de l'admin du modèle pour y rajouter automatiquement l'auteur qui créé l'objet
[ "Surclasse", "la", "méthode", "de", "sauvegarde", "de", "l", "admin", "du", "modèle", "pour", "y", "rajouter", "automatiquement", "l", "auteur", "qui", "créé", "l", "objet" ]
train
https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/admin.py#L9-L20
vecnet/vecnet.simulation
vecnet/simulation/sim_status.py
get_description
def get_description(status_code): """ Get the description for a status code. """ description = _descriptions.get(status_code) if description is None: description = 'code = %s (no description)' % str(status_code) return description
python
def get_description(status_code): """ Get the description for a status code. """ description = _descriptions.get(status_code) if description is None: description = 'code = %s (no description)' % str(status_code) return description
[ "def", "get_description", "(", "status_code", ")", ":", "description", "=", "_descriptions", ".", "get", "(", "status_code", ")", "if", "description", "is", "None", ":", "description", "=", "'code = %s (no description)'", "%", "str", "(", "status_code", ")", "re...
Get the description for a status code.
[ "Get", "the", "description", "for", "a", "status", "code", "." ]
train
https://github.com/vecnet/vecnet.simulation/blob/3a4b3df7b12418c6fa8a7d9cd49656a1c031fc0e/vecnet/simulation/sim_status.py#L47-L54
emilssolmanis/tapes
tapes/meta.py
metered_meta
def metered_meta(metrics, base=type): """Creates a metaclass that will add the specified metrics at a path parametrized on the dynamic class name. Prime use case is for base classes if all subclasses need separate metrics and / or the metrics need to be used in base class methods, e.g., Tornado's ``Request...
python
def metered_meta(metrics, base=type): """Creates a metaclass that will add the specified metrics at a path parametrized on the dynamic class name. Prime use case is for base classes if all subclasses need separate metrics and / or the metrics need to be used in base class methods, e.g., Tornado's ``Request...
[ "def", "metered_meta", "(", "metrics", ",", "base", "=", "type", ")", ":", "class", "_MeteredMeta", "(", "base", ")", ":", "def", "__new__", "(", "meta", ",", "name", ",", "bases", ",", "dict_", ")", ":", "new_dict", "=", "dict", "(", "*", "*", "di...
Creates a metaclass that will add the specified metrics at a path parametrized on the dynamic class name. Prime use case is for base classes if all subclasses need separate metrics and / or the metrics need to be used in base class methods, e.g., Tornado's ``RequestHandler`` like:: import tapes ...
[ "Creates", "a", "metaclass", "that", "will", "add", "the", "specified", "metrics", "at", "a", "path", "parametrized", "on", "the", "dynamic", "class", "name", "." ]
train
https://github.com/emilssolmanis/tapes/blob/7797fc9ebcb359cb1ba5085570e3cab5ebcd1d3c/tapes/meta.py#L1-L57
KnowledgeLinks/rdfframework
rdfframework/search/elasticsearchbase.py
EsBase.make_action_list
def make_action_list(self, item_list, **kwargs): ''' Generates a list of actions for sending to Elasticsearch ''' action_list = [] es_index = get2(kwargs, "es_index", self.es_index) action_type = kwargs.get("action_type","index") action_settings = {'_op_type': action_type,...
python
def make_action_list(self, item_list, **kwargs): ''' Generates a list of actions for sending to Elasticsearch ''' action_list = [] es_index = get2(kwargs, "es_index", self.es_index) action_type = kwargs.get("action_type","index") action_settings = {'_op_type': action_type,...
[ "def", "make_action_list", "(", "self", ",", "item_list", ",", "*", "*", "kwargs", ")", ":", "action_list", "=", "[", "]", "es_index", "=", "get2", "(", "kwargs", ",", "\"es_index\"", ",", "self", ".", "es_index", ")", "action_type", "=", "kwargs", ".", ...
Generates a list of actions for sending to Elasticsearch
[ "Generates", "a", "list", "of", "actions", "for", "sending", "to", "Elasticsearch" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/search/elasticsearchbase.py#L45-L63
KnowledgeLinks/rdfframework
rdfframework/search/elasticsearchbase.py
EsBase.bulk_save
def bulk_save(self, action_list, **kwargs): ''' sends a passed in action_list to elasticsearch ''' lg = logging.getLogger("%s.%s" % (self.ln, inspect.stack()[0][3])) lg.setLevel(self.log_level) err_log = logging.getLogger("index.errors") es = self.es es_index = ge...
python
def bulk_save(self, action_list, **kwargs): ''' sends a passed in action_list to elasticsearch ''' lg = logging.getLogger("%s.%s" % (self.ln, inspect.stack()[0][3])) lg.setLevel(self.log_level) err_log = logging.getLogger("index.errors") es = self.es es_index = ge...
[ "def", "bulk_save", "(", "self", ",", "action_list", ",", "*", "*", "kwargs", ")", ":", "lg", "=", "logging", ".", "getLogger", "(", "\"%s.%s\"", "%", "(", "self", ".", "ln", ",", "inspect", ".", "stack", "(", ")", "[", "0", "]", "[", "3", "]", ...
sends a passed in action_list to elasticsearch
[ "sends", "a", "passed", "in", "action_list", "to", "elasticsearch" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/search/elasticsearchbase.py#L65-L101
KnowledgeLinks/rdfframework
rdfframework/search/elasticsearchbase.py
EsBase.save
def save(self, data, **kwargs): """ sends a passed in action_list to elasticsearch args: data: that data dictionary to save kwargs: id: es id to use / None = auto """ lg = logging.getLogger("%s.%s" % (self.ln, inspect.stack()[0][3])) ...
python
def save(self, data, **kwargs): """ sends a passed in action_list to elasticsearch args: data: that data dictionary to save kwargs: id: es id to use / None = auto """ lg = logging.getLogger("%s.%s" % (self.ln, inspect.stack()[0][3])) ...
[ "def", "save", "(", "self", ",", "data", ",", "*", "*", "kwargs", ")", ":", "lg", "=", "logging", ".", "getLogger", "(", "\"%s.%s\"", "%", "(", "self", ".", "ln", ",", "inspect", ".", "stack", "(", ")", "[", "0", "]", "[", "3", "]", ")", ")",...
sends a passed in action_list to elasticsearch args: data: that data dictionary to save kwargs: id: es id to use / None = auto
[ "sends", "a", "passed", "in", "action_list", "to", "elasticsearch", "args", ":", "data", ":", "that", "data", "dictionary", "to", "save", "kwargs", ":", "id", ":", "es", "id", "to", "use", "/", "None", "=", "auto" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/search/elasticsearchbase.py#L103-L137
KnowledgeLinks/rdfframework
rdfframework/search/elasticsearchbase.py
EsBase._find_ids
def _find_ids(self, data_list, prop, lookup_index, lookup_doc_type, lookup_field): """ Reads a list of data and replaces the ids with es id of the item args: data_list: list of items to find i...
python
def _find_ids(self, data_list, prop, lookup_index, lookup_doc_type, lookup_field): """ Reads a list of data and replaces the ids with es id of the item args: data_list: list of items to find i...
[ "def", "_find_ids", "(", "self", ",", "data_list", ",", "prop", ",", "lookup_index", ",", "lookup_doc_type", ",", "lookup_field", ")", ":", "lg", "=", "logging", ".", "getLogger", "(", "\"%s.%s\"", "%", "(", "self", ".", "ln", ",", "inspect", ".", "stack...
Reads a list of data and replaces the ids with es id of the item args: data_list: list of items to find in replace prop: full prop name in es format i.e. make.id lookup_src: dictionary with index doc_type ie. {"es_index": "reference", "doc_type": "devic...
[ "Reads", "a", "list", "of", "data", "and", "replaces", "the", "ids", "with", "es", "id", "of", "the", "item", "args", ":", "data_list", ":", "list", "of", "items", "to", "find", "in", "replace", "prop", ":", "full", "prop", "name", "in", "es", "forma...
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/search/elasticsearchbase.py#L139-L171
KnowledgeLinks/rdfframework
rdfframework/search/elasticsearchbase.py
EsBase.get_doc
def get_doc(self, item_id, id_field="_id", **kwargs): """ returns a single item data record/document based on specified criteria args: item_id: the id value of the desired item. Can be used in combination with the id_field for a paired lookup. ...
python
def get_doc(self, item_id, id_field="_id", **kwargs): """ returns a single item data record/document based on specified criteria args: item_id: the id value of the desired item. Can be used in combination with the id_field for a paired lookup. ...
[ "def", "get_doc", "(", "self", ",", "item_id", ",", "id_field", "=", "\"_id\"", ",", "*", "*", "kwargs", ")", ":", "lg", "=", "logging", ".", "getLogger", "(", "\"%s.%s\"", "%", "(", "self", ".", "ln", ",", "inspect", ".", "stack", "(", ")", "[", ...
returns a single item data record/document based on specified criteria args: item_id: the id value of the desired item. Can be used in combination with the id_field for a paired lookup. id_field: the field that is related to the item_id; default = '_id...
[ "returns", "a", "single", "item", "data", "record", "/", "document", "based", "on", "specified", "criteria", "args", ":", "item_id", ":", "the", "id", "value", "of", "the", "desired", "item", ".", "Can", "be", "used", "in", "combination", "with", "the", ...
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/search/elasticsearchbase.py#L173-L225
KnowledgeLinks/rdfframework
rdfframework/search/elasticsearchbase.py
EsBase.get_list
def get_list(self, method="list", **kwargs): """ returns a key value list of items based on the specfied criteria """ lg = logging.getLogger("%s.%s" % (self.ln, inspect.stack()[0][3])) lg.setLevel(self.log_level) args = inspect.getargvalues(inspect.currentframe())[3] ...
python
def get_list(self, method="list", **kwargs): """ returns a key value list of items based on the specfied criteria """ lg = logging.getLogger("%s.%s" % (self.ln, inspect.stack()[0][3])) lg.setLevel(self.log_level) args = inspect.getargvalues(inspect.currentframe())[3] ...
[ "def", "get_list", "(", "self", ",", "method", "=", "\"list\"", ",", "*", "*", "kwargs", ")", ":", "lg", "=", "logging", ".", "getLogger", "(", "\"%s.%s\"", "%", "(", "self", ".", "ln", ",", "inspect", ".", "stack", "(", ")", "[", "0", "]", "[", ...
returns a key value list of items based on the specfied criteria
[ "returns", "a", "key", "value", "list", "of", "items", "based", "on", "the", "specfied", "criteria" ]
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/search/elasticsearchbase.py#L227-L311
KnowledgeLinks/rdfframework
rdfframework/search/elasticsearchbase.py
EsBase._calc_result
def _calc_result(self, results, calc): """ parses the calc string and then reads the results and returns the new value Elasticsearch no longer allow dynamic in scripting args: results: the list of results from Elasticsearch calc: the calculation sting re...
python
def _calc_result(self, results, calc): """ parses the calc string and then reads the results and returns the new value Elasticsearch no longer allow dynamic in scripting args: results: the list of results from Elasticsearch calc: the calculation sting re...
[ "def", "_calc_result", "(", "self", ",", "results", ",", "calc", ")", ":", "lg", "=", "logging", ".", "getLogger", "(", "\"%s.%s\"", "%", "(", "self", ".", "ln", ",", "inspect", ".", "stack", "(", ")", "[", "0", "]", "[", "3", "]", ")", ")", "l...
parses the calc string and then reads the results and returns the new value Elasticsearch no longer allow dynamic in scripting args: results: the list of results from Elasticsearch calc: the calculation sting returns: refomated results list with calc...
[ "parses", "the", "calc", "string", "and", "then", "reads", "the", "results", "and", "returns", "the", "new", "value", "Elasticsearch", "no", "longer", "allow", "dynamic", "in", "scripting", "args", ":", "results", ":", "the", "list", "of", "results", "from",...
train
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/search/elasticsearchbase.py#L313-L353
cirruscluster/cirruscluster
cirruscluster/cluster/ec2cluster.py
Ec2Cluster.authorize_role
def authorize_role(self, role, protocol, from_port, to_port, cidr_ip): """ Authorize access to machines in a given role from a given network. """ if (protocol != 'tcp' and protocol != 'udp'): raise RuntimeError('error: expected protocol to be tcp or udp '\ 'but got %s' % (...
python
def authorize_role(self, role, protocol, from_port, to_port, cidr_ip): """ Authorize access to machines in a given role from a given network. """ if (protocol != 'tcp' and protocol != 'udp'): raise RuntimeError('error: expected protocol to be tcp or udp '\ 'but got %s' % (...
[ "def", "authorize_role", "(", "self", ",", "role", ",", "protocol", ",", "from_port", ",", "to_port", ",", "cidr_ip", ")", ":", "if", "(", "protocol", "!=", "'tcp'", "and", "protocol", "!=", "'udp'", ")", ":", "raise", "RuntimeError", "(", "'error: expecte...
Authorize access to machines in a given role from a given network.
[ "Authorize", "access", "to", "machines", "in", "a", "given", "role", "from", "a", "given", "network", "." ]
train
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/cluster/ec2cluster.py#L83-L102
cirruscluster/cirruscluster
cirruscluster/cluster/ec2cluster.py
Ec2Cluster.check_running
def check_running(self, role, number): """ Check that a certain number of instances in a role are running. """ instances = self.get_instances_in_role(role, "running") if len(instances) != number: print "Expected %s instances in role %s, but was %s %s" % \ (number, role, len(instances),...
python
def check_running(self, role, number): """ Check that a certain number of instances in a role are running. """ instances = self.get_instances_in_role(role, "running") if len(instances) != number: print "Expected %s instances in role %s, but was %s %s" % \ (number, role, len(instances),...
[ "def", "check_running", "(", "self", ",", "role", ",", "number", ")", ":", "instances", "=", "self", ".", "get_instances_in_role", "(", "role", ",", "\"running\"", ")", "if", "len", "(", "instances", ")", "!=", "number", ":", "print", "\"Expected %s instance...
Check that a certain number of instances in a role are running.
[ "Check", "that", "a", "certain", "number", "of", "instances", "in", "a", "role", "are", "running", "." ]
train
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/cluster/ec2cluster.py#L104-L114
cirruscluster/cirruscluster
cirruscluster/cluster/ec2cluster.py
Ec2Cluster.get_instances_in_role
def get_instances_in_role(self, role, state_filter=None): """ Get all the instances in a role, filtered by state. @param role: the name of the role @param state_filter: the state that the instance should be in (e.g. "running"), or None for all states """ self._check_role_name(role) in...
python
def get_instances_in_role(self, role, state_filter=None): """ Get all the instances in a role, filtered by state. @param role: the name of the role @param state_filter: the state that the instance should be in (e.g. "running"), or None for all states """ self._check_role_name(role) in...
[ "def", "get_instances_in_role", "(", "self", ",", "role", ",", "state_filter", "=", "None", ")", ":", "self", ".", "_check_role_name", "(", "role", ")", "instances", "=", "[", "]", "for", "instance", "in", "self", ".", "_get_instances", "(", "self", ".", ...
Get all the instances in a role, filtered by state. @param role: the name of the role @param state_filter: the state that the instance should be in (e.g. "running"), or None for all states
[ "Get", "all", "the", "instances", "in", "a", "role", "filtered", "by", "state", "." ]
train
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/cluster/ec2cluster.py#L116-L133
cirruscluster/cirruscluster
cirruscluster/cluster/ec2cluster.py
Ec2Cluster.get_instances
def get_instances(self, state_filter=None): """ Get all the instances filtered by state. @param state_filter: the state that the instance should be in (e.g. "running"), or None for all states """ instances = [] for instance in self._get_instances(self._get_cluster_group_name(), ...
python
def get_instances(self, state_filter=None): """ Get all the instances filtered by state. @param state_filter: the state that the instance should be in (e.g. "running"), or None for all states """ instances = [] for instance in self._get_instances(self._get_cluster_group_name(), ...
[ "def", "get_instances", "(", "self", ",", "state_filter", "=", "None", ")", ":", "instances", "=", "[", "]", "for", "instance", "in", "self", ".", "_get_instances", "(", "self", ".", "_get_cluster_group_name", "(", ")", ",", "state_filter", ")", ":", "inst...
Get all the instances filtered by state. @param state_filter: the state that the instance should be in (e.g. "running"), or None for all states
[ "Get", "all", "the", "instances", "filtered", "by", "state", "." ]
train
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/cluster/ec2cluster.py#L135-L149
cirruscluster/cirruscluster
cirruscluster/cluster/ec2cluster.py
Ec2Cluster.print_status
def print_status(self, roles=None, state_filter="running"): """ Print the status of instances in the given roles, filtered by state. """ if not roles: for instance in self._get_instances(self._get_cluster_group_name(), state_filter): self._print_in...
python
def print_status(self, roles=None, state_filter="running"): """ Print the status of instances in the given roles, filtered by state. """ if not roles: for instance in self._get_instances(self._get_cluster_group_name(), state_filter): self._print_in...
[ "def", "print_status", "(", "self", ",", "roles", "=", "None", ",", "state_filter", "=", "\"running\"", ")", ":", "if", "not", "roles", ":", "for", "instance", "in", "self", ".", "_get_instances", "(", "self", ".", "_get_cluster_group_name", "(", ")", ",",...
Print the status of instances in the given roles, filtered by state.
[ "Print", "the", "status", "of", "instances", "in", "the", "given", "roles", "filtered", "by", "state", "." ]
train
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/cluster/ec2cluster.py#L151-L163
cirruscluster/cirruscluster
cirruscluster/cluster/ec2cluster.py
Ec2Cluster.CreateBlockDeviceMap
def CreateBlockDeviceMap(self, image_id, instance_type): """ If you launch without specifying a manual device block mapping, you may not get all the ephemeral devices available to the given instance type. This will build one that ensures all available ephemeral devices are mapped. ...
python
def CreateBlockDeviceMap(self, image_id, instance_type): """ If you launch without specifying a manual device block mapping, you may not get all the ephemeral devices available to the given instance type. This will build one that ensures all available ephemeral devices are mapped. ...
[ "def", "CreateBlockDeviceMap", "(", "self", ",", "image_id", ",", "instance_type", ")", ":", "# get the block device mapping stored with the image", "image", "=", "self", ".", "ec2", ".", "get_image", "(", "image_id", ")", "block_device_map", "=", "image", ".", "blo...
If you launch without specifying a manual device block mapping, you may not get all the ephemeral devices available to the given instance type. This will build one that ensures all available ephemeral devices are mapped.
[ "If", "you", "launch", "without", "specifying", "a", "manual", "device", "block", "mapping", "you", "may", "not", "get", "all", "the", "ephemeral", "devices", "available", "to", "the", "given", "instance", "type", ".", "This", "will", "build", "one", "that",...
train
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/cluster/ec2cluster.py#L213-L233
cirruscluster/cirruscluster
cirruscluster/cluster/ec2cluster.py
Ec2Cluster.get_cluster_placement_group
def get_cluster_placement_group(self): """ Return the placement group, create it if it doesn't yet exist. (needed for cluster type instances). """ placement_group_name = 'pg-%s' % (self._name) try: self.ec2.create_placement_group(placement_group_name, ...
python
def get_cluster_placement_group(self): """ Return the placement group, create it if it doesn't yet exist. (needed for cluster type instances). """ placement_group_name = 'pg-%s' % (self._name) try: self.ec2.create_placement_group(placement_group_name, ...
[ "def", "get_cluster_placement_group", "(", "self", ")", ":", "placement_group_name", "=", "'pg-%s'", "%", "(", "self", ".", "_name", ")", "try", ":", "self", ".", "ec2", ".", "create_placement_group", "(", "placement_group_name", ",", "strategy", "=", "'cluster'...
Return the placement group, create it if it doesn't yet exist. (needed for cluster type instances).
[ "Return", "the", "placement", "group", "create", "it", "if", "it", "doesn", "t", "yet", "exist", ".", "(", "needed", "for", "cluster", "type", "instances", ")", "." ]
train
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/cluster/ec2cluster.py#L415-L426
cirruscluster/cirruscluster
cirruscluster/cluster/ec2cluster.py
Ec2Cluster._create_security_groups
def _create_security_groups(self, role): """ Create the security groups for a given role, including a group for the cluster if it doesn't exist. """ self._check_role_name(role) security_group_names = self._get_all_group_names() cluster_group_name = self._get_cluster_group_name() if not ...
python
def _create_security_groups(self, role): """ Create the security groups for a given role, including a group for the cluster if it doesn't exist. """ self._check_role_name(role) security_group_names = self._get_all_group_names() cluster_group_name = self._get_cluster_group_name() if not ...
[ "def", "_create_security_groups", "(", "self", ",", "role", ")", ":", "self", ".", "_check_role_name", "(", "role", ")", "security_group_names", "=", "self", ".", "_get_all_group_names", "(", ")", "cluster_group_name", "=", "self", ".", "_get_cluster_group_name", ...
Create the security groups for a given role, including a group for the cluster if it doesn't exist.
[ "Create", "the", "security", "groups", "for", "a", "given", "role", "including", "a", "group", "for", "the", "cluster", "if", "it", "doesn", "t", "exist", "." ]
train
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/cluster/ec2cluster.py#L468-L492
cirruscluster/cirruscluster
cirruscluster/cluster/ec2cluster.py
Ec2Cluster._delete_security_groups
def _delete_security_groups(self): """ Delete the security groups for each role in the cluster, and the group for the cluster. """ group_names = self._get_all_group_names_for_cluster() for group in group_names: self.ec2.delete_security_group(group)
python
def _delete_security_groups(self): """ Delete the security groups for each role in the cluster, and the group for the cluster. """ group_names = self._get_all_group_names_for_cluster() for group in group_names: self.ec2.delete_security_group(group)
[ "def", "_delete_security_groups", "(", "self", ")", ":", "group_names", "=", "self", ".", "_get_all_group_names_for_cluster", "(", ")", "for", "group", "in", "group_names", ":", "self", ".", "ec2", ".", "delete_security_group", "(", "group", ")" ]
Delete the security groups for each role in the cluster, and the group for the cluster.
[ "Delete", "the", "security", "groups", "for", "each", "role", "in", "the", "cluster", "and", "the", "group", "for", "the", "cluster", "." ]
train
https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/cluster/ec2cluster.py#L494-L501
kodexlab/reliure
reliure/utils/cli.py
argument_from_option
def argument_from_option(parser, component, opt_name, prefix=""): """ Add an argparse argument to a parse from one option of one :class:`Optionable` >>> comp = Optionable() >>> comp.add_option("num", Numeric(default=1, max=12, help="An exemple of option")) >>> parser = argparse.ArgumentParser(prog="PRO...
python
def argument_from_option(parser, component, opt_name, prefix=""): """ Add an argparse argument to a parse from one option of one :class:`Optionable` >>> comp = Optionable() >>> comp.add_option("num", Numeric(default=1, max=12, help="An exemple of option")) >>> parser = argparse.ArgumentParser(prog="PRO...
[ "def", "argument_from_option", "(", "parser", ",", "component", ",", "opt_name", ",", "prefix", "=", "\"\"", ")", ":", "assert", "component", ".", "has_option", "(", "opt_name", ")", ",", "\"'%s' is not an option of the given component\"", "%", "opt_name", "option",...
Add an argparse argument to a parse from one option of one :class:`Optionable` >>> comp = Optionable() >>> comp.add_option("num", Numeric(default=1, max=12, help="An exemple of option")) >>> parser = argparse.ArgumentParser(prog="PROG") >>> argument_from_option(parser, comp, "num") >>> parser.print...
[ "Add", "an", "argparse", "argument", "to", "a", "parse", "from", "one", "option", "of", "one", ":", "class", ":", "Optionable" ]
train
https://github.com/kodexlab/reliure/blob/0450c7a9254c5c003162738458bbe0c49e777ba5/reliure/utils/cli.py#L19-L71