repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
3 values
summary
stringlengths
4
350
samghelms/mathviz
mathviz_hopper/src/indices.py
GensimMathIndex._get_next_token
def _get_next_token(self, string): """ "eats" up the string until it hits an ending character to get valid leaf expressions. For example, given \\Phi_{z}(L) = \\sum_{i=1}^{N} \\frac{1}{C_{i} \\times V_{\\rm max, i}}, this function would pull out \\Phi, stopping at _ @ string: str...
python
def _get_next_token(self, string): """ "eats" up the string until it hits an ending character to get valid leaf expressions. For example, given \\Phi_{z}(L) = \\sum_{i=1}^{N} \\frac{1}{C_{i} \\times V_{\\rm max, i}}, this function would pull out \\Phi, stopping at _ @ string: str...
[ "def", "_get_next_token", "(", "self", ",", "string", ")", ":", "STOP_CHARS", "=", "\"_ {}^ \\n ,()=\"", "UNARY_CHARS", "=", "\"^_\"", "# ^ and _ are valid leaf expressions--just ones that should be handled on their own", "if", "string", "[", "0", "]", "in", "STOP_CHARS", ...
"eats" up the string until it hits an ending character to get valid leaf expressions. For example, given \\Phi_{z}(L) = \\sum_{i=1}^{N} \\frac{1}{C_{i} \\times V_{\\rm max, i}}, this function would pull out \\Phi, stopping at _ @ string: str returns a tuple of (expression [ex: \\Phi], re...
[ "eats", "up", "the", "string", "until", "it", "hits", "an", "ending", "character", "to", "get", "valid", "leaf", "expressions", ".", "For", "example", "given", "\\\\", "Phi_", "{", "z", "}", "(", "L", ")", "=", "\\\\", "sum_", "{", "i", "=", "1", "...
30fe89537379faea4de8c8b568ac6e52e4d15353
https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/indices.py#L72-L93
train
This function returns the next token in the string that is valid leaf expressions.
samghelms/mathviz
mathviz_hopper/src/indices.py
GensimMathIndex._tokenize_latex
def _tokenize_latex(self, exp): """ Internal method to tokenize latex """ tokens = [] prevexp = "" while exp: t, exp = self._get_next_token(exp) if t.strip() != "": tokens.append(t) if prevexp == exp: bre...
python
def _tokenize_latex(self, exp): """ Internal method to tokenize latex """ tokens = [] prevexp = "" while exp: t, exp = self._get_next_token(exp) if t.strip() != "": tokens.append(t) if prevexp == exp: bre...
[ "def", "_tokenize_latex", "(", "self", ",", "exp", ")", ":", "tokens", "=", "[", "]", "prevexp", "=", "\"\"", "while", "exp", ":", "t", ",", "exp", "=", "self", ".", "_get_next_token", "(", "exp", ")", "if", "t", ".", "strip", "(", ")", "!=", "\"...
Internal method to tokenize latex
[ "Internal", "method", "to", "tokenize", "latex" ]
30fe89537379faea4de8c8b568ac6e52e4d15353
https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/indices.py#L95-L108
train
Internal method to tokenize latex tokens
samghelms/mathviz
mathviz_hopper/src/indices.py
GensimMathIndex._convert_query
def _convert_query(self, query): """ Convert query into an indexable string. """ query = self.dictionary.doc2bow(self._tokenize_latex(query)) sims = self.index[query] neighbors = sorted(sims, key=lambda item: -item[1]) neighbors = {"neighbors":[{self.columns[0]: {...
python
def _convert_query(self, query): """ Convert query into an indexable string. """ query = self.dictionary.doc2bow(self._tokenize_latex(query)) sims = self.index[query] neighbors = sorted(sims, key=lambda item: -item[1]) neighbors = {"neighbors":[{self.columns[0]: {...
[ "def", "_convert_query", "(", "self", ",", "query", ")", ":", "query", "=", "self", ".", "dictionary", ".", "doc2bow", "(", "self", ".", "_tokenize_latex", "(", "query", ")", ")", "sims", "=", "self", ".", "index", "[", "query", "]", "neighbors", "=", ...
Convert query into an indexable string.
[ "Convert", "query", "into", "an", "indexable", "string", "." ]
30fe89537379faea4de8c8b568ac6e52e4d15353
https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/indices.py#L110-L118
train
Convert a query into an indexable string.
jasonrbriggs/proton
python/proton/utils.py
join
def join(path1, path2): ''' nicely join two path elements together ''' if path1.endswith('/') and path2.startswith('/'): return ''.join([path1, path2[1:]]) elif path1.endswith('/') or path2.startswith('/'): return ''.join([path1, path2]) else: return ''.join([path1, '/', ...
python
def join(path1, path2): ''' nicely join two path elements together ''' if path1.endswith('/') and path2.startswith('/'): return ''.join([path1, path2[1:]]) elif path1.endswith('/') or path2.startswith('/'): return ''.join([path1, path2]) else: return ''.join([path1, '/', ...
[ "def", "join", "(", "path1", ",", "path2", ")", ":", "if", "path1", ".", "endswith", "(", "'/'", ")", "and", "path2", ".", "startswith", "(", "'/'", ")", ":", "return", "''", ".", "join", "(", "[", "path1", ",", "path2", "[", "1", ":", "]", "]"...
nicely join two path elements together
[ "nicely", "join", "two", "path", "elements", "together" ]
e734734750797ef0caaa1680379e07b86d7a53e3
https://github.com/jasonrbriggs/proton/blob/e734734750797ef0caaa1680379e07b86d7a53e3/python/proton/utils.py#L24-L33
train
nicely join two path elements together
samghelms/mathviz
mathviz_hopper/src/print_math.py
print_math
def print_math(math_expression_lst, name = "math.html", out='html', formatter = lambda x: x): """ Converts LaTeX math expressions into an html layout. Creates a html file in the directory where print_math is called by default. Displays math to jupyter notebook if "notebook" argument is specified. ...
python
def print_math(math_expression_lst, name = "math.html", out='html', formatter = lambda x: x): """ Converts LaTeX math expressions into an html layout. Creates a html file in the directory where print_math is called by default. Displays math to jupyter notebook if "notebook" argument is specified. ...
[ "def", "print_math", "(", "math_expression_lst", ",", "name", "=", "\"math.html\"", ",", "out", "=", "'html'", ",", "formatter", "=", "lambda", "x", ":", "x", ")", ":", "try", ":", "shutil", ".", "rmtree", "(", "'viz'", ")", "except", ":", "pass", "pth...
Converts LaTeX math expressions into an html layout. Creates a html file in the directory where print_math is called by default. Displays math to jupyter notebook if "notebook" argument is specified. Args: math_expression_lst (list): A list of LaTeX math (string) to be rendered by KaTeX ...
[ "Converts", "LaTeX", "math", "expressions", "into", "an", "html", "layout", ".", "Creates", "a", "html", "file", "in", "the", "directory", "where", "print_math", "is", "called", "by", "default", ".", "Displays", "math", "to", "jupyter", "notebook", "if", "no...
30fe89537379faea4de8c8b568ac6e52e4d15353
https://github.com/samghelms/mathviz/blob/30fe89537379faea4de8c8b568ac6e52e4d15353/mathviz_hopper/src/print_math.py#L17-L53
train
Print LaTeX math expressions into an HTML file.
azogue/i2csense
i2csense/__init__.py
I2cBaseClass.log_error
def log_error(self, msg, *args): """Log an error or print in stdout if no logger.""" if self._logger is not None: self._logger.error(msg, *args) else: print(msg % args)
python
def log_error(self, msg, *args): """Log an error or print in stdout if no logger.""" if self._logger is not None: self._logger.error(msg, *args) else: print(msg % args)
[ "def", "log_error", "(", "self", ",", "msg", ",", "*", "args", ")", ":", "if", "self", ".", "_logger", "is", "not", "None", ":", "self", ".", "_logger", ".", "error", "(", "msg", ",", "*", "args", ")", "else", ":", "print", "(", "msg", "%", "ar...
Log an error or print in stdout if no logger.
[ "Log", "an", "error", "or", "print", "in", "stdout", "if", "no", "logger", "." ]
ecc6806dcee9de827a5414a9e836d271fedca9b9
https://github.com/azogue/i2csense/blob/ecc6806dcee9de827a5414a9e836d271fedca9b9/i2csense/__init__.py#L55-L60
train
Log an error or print in stdout if no logger.
azogue/i2csense
i2csense/__init__.py
I2cBaseClass._get_value_opc_attr
def _get_value_opc_attr(self, attr_name, prec_decimals=2): """Return sensor attribute with precission, or None if not present.""" try: value = getattr(self, attr_name) if value is not None: return round(value, prec_decimals) except I2cVariableNotImplemente...
python
def _get_value_opc_attr(self, attr_name, prec_decimals=2): """Return sensor attribute with precission, or None if not present.""" try: value = getattr(self, attr_name) if value is not None: return round(value, prec_decimals) except I2cVariableNotImplemente...
[ "def", "_get_value_opc_attr", "(", "self", ",", "attr_name", ",", "prec_decimals", "=", "2", ")", ":", "try", ":", "value", "=", "getattr", "(", "self", ",", "attr_name", ")", "if", "value", "is", "not", "None", ":", "return", "round", "(", "value", ",...
Return sensor attribute with precission, or None if not present.
[ "Return", "sensor", "attribute", "with", "precission", "or", "None", "if", "not", "present", "." ]
ecc6806dcee9de827a5414a9e836d271fedca9b9
https://github.com/azogue/i2csense/blob/ecc6806dcee9de827a5414a9e836d271fedca9b9/i2csense/__init__.py#L91-L99
train
Return sensor attribute with precission or None.
azogue/i2csense
i2csense/__init__.py
I2cBaseClass.current_state_str
def current_state_str(self): """Return string representation of the current state of the sensor.""" if self.sample_ok: msg = '' temperature = self._get_value_opc_attr('temperature') if temperature is not None: msg += 'Temp: %s ºC, ' % temperature ...
python
def current_state_str(self): """Return string representation of the current state of the sensor.""" if self.sample_ok: msg = '' temperature = self._get_value_opc_attr('temperature') if temperature is not None: msg += 'Temp: %s ºC, ' % temperature ...
[ "def", "current_state_str", "(", "self", ")", ":", "if", "self", ".", "sample_ok", ":", "msg", "=", "''", "temperature", "=", "self", ".", "_get_value_opc_attr", "(", "'temperature'", ")", "if", "temperature", "is", "not", "None", ":", "msg", "+=", "'Temp:...
Return string representation of the current state of the sensor.
[ "Return", "string", "representation", "of", "the", "current", "state", "of", "the", "sensor", "." ]
ecc6806dcee9de827a5414a9e836d271fedca9b9
https://github.com/azogue/i2csense/blob/ecc6806dcee9de827a5414a9e836d271fedca9b9/i2csense/__init__.py#L102-L120
train
Return string representation of the current state of the sensor.
azogue/i2csense
i2csense/__init__.py
I2cBaseClass.dew_point_temperature
def dew_point_temperature(self): """Return the dew point temperature in ºC for the last measurement. For sensors implementing temperature and humidity values. Extracted from the HTU21D sensor spec sheet.""" if self.sample_ok: temperature = self._get_value_opc_attr('temperatu...
python
def dew_point_temperature(self): """Return the dew point temperature in ºC for the last measurement. For sensors implementing temperature and humidity values. Extracted from the HTU21D sensor spec sheet.""" if self.sample_ok: temperature = self._get_value_opc_attr('temperatu...
[ "def", "dew_point_temperature", "(", "self", ")", ":", "if", "self", ".", "sample_ok", ":", "temperature", "=", "self", ".", "_get_value_opc_attr", "(", "'temperature'", ",", "3", ")", "humidity", "=", "self", ".", "_get_value_opc_attr", "(", "'humidity'", ","...
Return the dew point temperature in ºC for the last measurement. For sensors implementing temperature and humidity values. Extracted from the HTU21D sensor spec sheet.
[ "Return", "the", "dew", "point", "temperature", "in", "ºC", "for", "the", "last", "measurement", "." ]
ecc6806dcee9de827a5414a9e836d271fedca9b9
https://github.com/azogue/i2csense/blob/ecc6806dcee9de827a5414a9e836d271fedca9b9/i2csense/__init__.py#L123-L138
train
Return the dew point temperature in ºC for the last measurement.
gesellkammer/sndfileio
sndfileio/resampling.py
_applyMultichan
def _applyMultichan(samples, func): # type: (np.ndarray, Callable[[np.ndarray], np.ndarray]) -> np.ndarray """ Apply func to each channel of audio data in samples """ if len(samples.shape) == 1 or samples.shape[1] == 1: newsamples = func(samples) else: y = np.array([]) fo...
python
def _applyMultichan(samples, func): # type: (np.ndarray, Callable[[np.ndarray], np.ndarray]) -> np.ndarray """ Apply func to each channel of audio data in samples """ if len(samples.shape) == 1 or samples.shape[1] == 1: newsamples = func(samples) else: y = np.array([]) fo...
[ "def", "_applyMultichan", "(", "samples", ",", "func", ")", ":", "# type: (np.ndarray, Callable[[np.ndarray], np.ndarray]) -> np.ndarray", "if", "len", "(", "samples", ".", "shape", ")", "==", "1", "or", "samples", ".", "shape", "[", "1", "]", "==", "1", ":", ...
Apply func to each channel of audio data in samples
[ "Apply", "func", "to", "each", "channel", "of", "audio", "data", "in", "samples" ]
8e2b264cadb652f09d2e775f54090c0a3cb2ced2
https://github.com/gesellkammer/sndfileio/blob/8e2b264cadb652f09d2e775f54090c0a3cb2ced2/sndfileio/resampling.py#L17-L29
train
Apply func to each channel of audio data in samples
gesellkammer/sndfileio
sndfileio/resampling.py
_resample_samplerate
def _resample_samplerate(samples, sr, newsr): # type: (np.ndarray, int, int, str) -> np.ndarray """ Uses https://github.com/tuxu/python-samplerate """ try: from samplerate import resample except ImportError: return None ratio = newsr/sr return _applyMultichan(samples, ...
python
def _resample_samplerate(samples, sr, newsr): # type: (np.ndarray, int, int, str) -> np.ndarray """ Uses https://github.com/tuxu/python-samplerate """ try: from samplerate import resample except ImportError: return None ratio = newsr/sr return _applyMultichan(samples, ...
[ "def", "_resample_samplerate", "(", "samples", ",", "sr", ",", "newsr", ")", ":", "# type: (np.ndarray, int, int, str) -> np.ndarray", "try", ":", "from", "samplerate", "import", "resample", "except", "ImportError", ":", "return", "None", "ratio", "=", "newsr", "/",...
Uses https://github.com/tuxu/python-samplerate
[ "Uses", "https", ":", "//", "github", ".", "com", "/", "tuxu", "/", "python", "-", "samplerate" ]
8e2b264cadb652f09d2e775f54090c0a3cb2ced2
https://github.com/gesellkammer/sndfileio/blob/8e2b264cadb652f09d2e775f54090c0a3cb2ced2/sndfileio/resampling.py#L46-L58
train
Resample the samples according to the samplerate sr.
gesellkammer/sndfileio
sndfileio/resampling.py
_nnresample_compute_filt
def _nnresample_compute_filt(up, down, beta=5.0, L=32001): r""" Computes a filter to resample a signal from rate "down" to rate "up" Parameters ---------- up : int The upsampling factor. down : int The downsampling factor. beta : float Beta factor for Kaiser wind...
python
def _nnresample_compute_filt(up, down, beta=5.0, L=32001): r""" Computes a filter to resample a signal from rate "down" to rate "up" Parameters ---------- up : int The upsampling factor. down : int The downsampling factor. beta : float Beta factor for Kaiser wind...
[ "def", "_nnresample_compute_filt", "(", "up", ",", "down", ",", "beta", "=", "5.0", ",", "L", "=", "32001", ")", ":", "# Determine our up and down factors", "g", "=", "gcd", "(", "up", ",", "down", ")", "up", "=", "up", "//", "g", "down", "=", "down", ...
r""" Computes a filter to resample a signal from rate "down" to rate "up" Parameters ---------- up : int The upsampling factor. down : int The downsampling factor. beta : float Beta factor for Kaiser window. Determines tradeoff between stopband attenuation a...
[ "r", "Computes", "a", "filter", "to", "resample", "a", "signal", "from", "rate", "down", "to", "rate", "up", "Parameters", "----------", "up", ":", "int", "The", "upsampling", "factor", ".", "down", ":", "int", "The", "downsampling", "factor", ".", "beta",...
8e2b264cadb652f09d2e775f54090c0a3cb2ced2
https://github.com/gesellkammer/sndfileio/blob/8e2b264cadb652f09d2e775f54090c0a3cb2ced2/sndfileio/resampling.py#L66-L122
train
r Computes a filter to resample a signal from rate up to rate down.
gesellkammer/sndfileio
sndfileio/resampling.py
_resample_nnresample2
def _resample_nnresample2(s, up, down, beta=5.0, L=16001, axis=0): # type: (np.ndarray, float, float, float, int, int) -> np.ndarray """ Taken from https://github.com/jthiem/nnresample Resample a signal from rate "down" to rate "up" Parameters ---------- x : array_like The data...
python
def _resample_nnresample2(s, up, down, beta=5.0, L=16001, axis=0): # type: (np.ndarray, float, float, float, int, int) -> np.ndarray """ Taken from https://github.com/jthiem/nnresample Resample a signal from rate "down" to rate "up" Parameters ---------- x : array_like The data...
[ "def", "_resample_nnresample2", "(", "s", ",", "up", ",", "down", ",", "beta", "=", "5.0", ",", "L", "=", "16001", ",", "axis", "=", "0", ")", ":", "# type: (np.ndarray, float, float, float, int, int) -> np.ndarray", "# check if a resampling filter with the chosen param...
Taken from https://github.com/jthiem/nnresample Resample a signal from rate "down" to rate "up" Parameters ---------- x : array_like The data to be resampled. up : int The upsampling factor. down : int The downsampling factor. beta : float Beta factor fo...
[ "Taken", "from", "https", ":", "//", "github", ".", "com", "/", "jthiem", "/", "nnresample" ]
8e2b264cadb652f09d2e775f54090c0a3cb2ced2
https://github.com/gesellkammer/sndfileio/blob/8e2b264cadb652f09d2e775f54090c0a3cb2ced2/sndfileio/resampling.py#L131-L176
train
Resample a signal from rate down to rate up.
gesellkammer/sndfileio
sndfileio/resampling.py
_resample_obspy
def _resample_obspy(samples, sr, newsr, window='hanning', lowpass=True): # type: (np.ndarray, int, int, str, bool) -> np.ndarray """ Resample using Fourier method. The same as resample_scipy but with low-pass filtering for upsampling """ from scipy.signal import resample from math import ce...
python
def _resample_obspy(samples, sr, newsr, window='hanning', lowpass=True): # type: (np.ndarray, int, int, str, bool) -> np.ndarray """ Resample using Fourier method. The same as resample_scipy but with low-pass filtering for upsampling """ from scipy.signal import resample from math import ce...
[ "def", "_resample_obspy", "(", "samples", ",", "sr", ",", "newsr", ",", "window", "=", "'hanning'", ",", "lowpass", "=", "True", ")", ":", "# type: (np.ndarray, int, int, str, bool) -> np.ndarray", "from", "scipy", ".", "signal", "import", "resample", "from", "mat...
Resample using Fourier method. The same as resample_scipy but with low-pass filtering for upsampling
[ "Resample", "using", "Fourier", "method", ".", "The", "same", "as", "resample_scipy", "but", "with", "low", "-", "pass", "filtering", "for", "upsampling" ]
8e2b264cadb652f09d2e775f54090c0a3cb2ced2
https://github.com/gesellkammer/sndfileio/blob/8e2b264cadb652f09d2e775f54090c0a3cb2ced2/sndfileio/resampling.py#L191-L213
train
Resample using Fourier method.
gesellkammer/sndfileio
sndfileio/resampling.py
resample
def resample(samples, oldsr, newsr): # type: (np.ndarray, int, int) -> np.ndarray """ Resample `samples` with given samplerate `sr` to new samplerate `newsr` samples: mono or multichannel frames oldsr : original samplerate newsr : new sample rate Returns: the new samples """ back...
python
def resample(samples, oldsr, newsr): # type: (np.ndarray, int, int) -> np.ndarray """ Resample `samples` with given samplerate `sr` to new samplerate `newsr` samples: mono or multichannel frames oldsr : original samplerate newsr : new sample rate Returns: the new samples """ back...
[ "def", "resample", "(", "samples", ",", "oldsr", ",", "newsr", ")", ":", "# type: (np.ndarray, int, int) -> np.ndarray", "backends", "=", "[", "_resample_samplerate", ",", "# turns the samples into float32, which is ok for audio ", "_resample_scikits", ",", "_resample_nnresampl...
Resample `samples` with given samplerate `sr` to new samplerate `newsr` samples: mono or multichannel frames oldsr : original samplerate newsr : new sample rate Returns: the new samples
[ "Resample", "samples", "with", "given", "samplerate", "sr", "to", "new", "samplerate", "newsr" ]
8e2b264cadb652f09d2e775f54090c0a3cb2ced2
https://github.com/gesellkammer/sndfileio/blob/8e2b264cadb652f09d2e775f54090c0a3cb2ced2/sndfileio/resampling.py#L216-L238
train
Resample samples with given samplerate sr to new samplerate newsr
garenchan/policy
setup.py
get_package_version
def get_package_version(): """return package version without importing it""" base = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(base, 'policy', '__init__.py'), mode='rt', encoding='utf-8') as initf: for line in initf: m = version.match(li...
python
def get_package_version(): """return package version without importing it""" base = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(base, 'policy', '__init__.py'), mode='rt', encoding='utf-8') as initf: for line in initf: m = version.match(li...
[ "def", "get_package_version", "(", ")", ":", "base", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "base", ",", "'policy'", ",", ...
return package version without importing it
[ "return", "package", "version", "without", "importing", "it" ]
7709ae5f371146f8c90380d0877a5e59d731f644
https://github.com/garenchan/policy/blob/7709ae5f371146f8c90380d0877a5e59d731f644/setup.py#L24-L34
train
return package version without importing it
garenchan/policy
setup.py
get_long_description
def get_long_description(): """return package's long description""" base = os.path.abspath(os.path.dirname(__file__)) readme_file = os.path.join(base, 'README.md') with open(readme_file, mode='rt', encoding='utf-8') as readme: return readme.read()
python
def get_long_description(): """return package's long description""" base = os.path.abspath(os.path.dirname(__file__)) readme_file = os.path.join(base, 'README.md') with open(readme_file, mode='rt', encoding='utf-8') as readme: return readme.read()
[ "def", "get_long_description", "(", ")", ":", "base", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", "readme_file", "=", "os", ".", "path", ".", "join", "(", "base", ",", "'README.md'", ")",...
return package's long description
[ "return", "package", "s", "long", "description" ]
7709ae5f371146f8c90380d0877a5e59d731f644
https://github.com/garenchan/policy/blob/7709ae5f371146f8c90380d0877a5e59d731f644/setup.py#L37-L42
train
return package s long description
garenchan/policy
setup.py
get_install_requires
def get_install_requires(): """return package's install requires""" base = os.path.abspath(os.path.dirname(__file__)) requirements_file = os.path.join(base, 'requirements.txt') if not os.path.exists(requirements_file): return [] with open(requirements_file, mode='rt', encoding='utf-8') as f:...
python
def get_install_requires(): """return package's install requires""" base = os.path.abspath(os.path.dirname(__file__)) requirements_file = os.path.join(base, 'requirements.txt') if not os.path.exists(requirements_file): return [] with open(requirements_file, mode='rt', encoding='utf-8') as f:...
[ "def", "get_install_requires", "(", ")", ":", "base", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", "requirements_file", "=", "os", ".", "path", ".", "join", "(", "base", ",", "'requirements....
return package's install requires
[ "return", "package", "s", "install", "requires" ]
7709ae5f371146f8c90380d0877a5e59d731f644
https://github.com/garenchan/policy/blob/7709ae5f371146f8c90380d0877a5e59d731f644/setup.py#L61-L68
train
return package s install requires
BernardFW/bernard
src/bernard/misc/sheet_sync/_base.py
main
def main(flags): """ Download all sheets as configured. """ dl = SheetDownloader(flags) dl.init() for file_info in settings.GOOGLE_SHEET_SYNC['files']: print('Downloading {}'.format(file_info['path'])) dl.download_sheet( file_info['path'], file_info['she...
python
def main(flags): """ Download all sheets as configured. """ dl = SheetDownloader(flags) dl.init() for file_info in settings.GOOGLE_SHEET_SYNC['files']: print('Downloading {}'.format(file_info['path'])) dl.download_sheet( file_info['path'], file_info['she...
[ "def", "main", "(", "flags", ")", ":", "dl", "=", "SheetDownloader", "(", "flags", ")", "dl", ".", "init", "(", ")", "for", "file_info", "in", "settings", ".", "GOOGLE_SHEET_SYNC", "[", "'files'", "]", ":", "print", "(", "'Downloading {}'", ".", "format"...
Download all sheets as configured.
[ "Download", "all", "sheets", "as", "configured", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/misc/sheet_sync/_base.py#L122-L136
train
Download all sheets as configured.
BernardFW/bernard
src/bernard/misc/sheet_sync/_base.py
SheetDownloader.init
def init(self): """ Fetch the credentials (and cache them on disk). """ self.credentials = self._get_credentials() self.http = self.credentials.authorize(httplib2.Http()) self.service = discovery.build( 'sheets', 'v4', http=self.http, ...
python
def init(self): """ Fetch the credentials (and cache them on disk). """ self.credentials = self._get_credentials() self.http = self.credentials.authorize(httplib2.Http()) self.service = discovery.build( 'sheets', 'v4', http=self.http, ...
[ "def", "init", "(", "self", ")", ":", "self", ".", "credentials", "=", "self", ".", "_get_credentials", "(", ")", "self", ".", "http", "=", "self", ".", "credentials", ".", "authorize", "(", "httplib2", ".", "Http", "(", ")", ")", "self", ".", "servi...
Fetch the credentials (and cache them on disk).
[ "Fetch", "the", "credentials", "(", "and", "cache", "them", "on", "disk", ")", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/misc/sheet_sync/_base.py#L50-L62
train
Initialize the object.
BernardFW/bernard
src/bernard/misc/sheet_sync/_base.py
SheetDownloader._get_credentials
def _get_credentials(self): """ Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential. """ ...
python
def _get_credentials(self): """ Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential. """ ...
[ "def", "_get_credentials", "(", "self", ")", ":", "home_dir", "=", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", "credential_dir", "=", "os", ".", "path", ".", "join", "(", "home_dir", ",", "'.credentials'", ")", "if", "not", "os", ".", "path"...
Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential.
[ "Gets", "valid", "user", "credentials", "from", "storage", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/misc/sheet_sync/_base.py#L64-L100
train
Gets valid user credentials from storage.
BernardFW/bernard
src/bernard/misc/sheet_sync/_base.py
SheetDownloader.download_sheet
def download_sheet(self, file_path, sheet_id, cell_range): """ Download the cell range from the sheet and store it as CSV in the `file_path` file. """ result = self.service.spreadsheets().values().get( spreadsheetId=sheet_id, range=cell_range, ).e...
python
def download_sheet(self, file_path, sheet_id, cell_range): """ Download the cell range from the sheet and store it as CSV in the `file_path` file. """ result = self.service.spreadsheets().values().get( spreadsheetId=sheet_id, range=cell_range, ).e...
[ "def", "download_sheet", "(", "self", ",", "file_path", ",", "sheet_id", ",", "cell_range", ")", ":", "result", "=", "self", ".", "service", ".", "spreadsheets", "(", ")", ".", "values", "(", ")", ".", "get", "(", "spreadsheetId", "=", "sheet_id", ",", ...
Download the cell range from the sheet and store it as CSV in the `file_path` file.
[ "Download", "the", "cell", "range", "from", "the", "sheet", "and", "store", "it", "as", "CSV", "in", "the", "file_path", "file", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/misc/sheet_sync/_base.py#L102-L119
train
Download the cell range from the sheet and store it in the file_path file.
coogger/steem-connect
steemconnect/client.py
Client.get_refresh_token
def get_refresh_token(code, app_secret): "tokens = get_refresh_token(code:str,app_secret:str)" "tokens['access_token']" "tokens['username']" "tokens['refresh_token']" token_api = "https://steemconnect.com/api/oauth2/token?code={}&client_secret={}".format(code, app_secret) ...
python
def get_refresh_token(code, app_secret): "tokens = get_refresh_token(code:str,app_secret:str)" "tokens['access_token']" "tokens['username']" "tokens['refresh_token']" token_api = "https://steemconnect.com/api/oauth2/token?code={}&client_secret={}".format(code, app_secret) ...
[ "def", "get_refresh_token", "(", "code", ",", "app_secret", ")", ":", "\"tokens['access_token']\"", "\"tokens['username']\"", "\"tokens['refresh_token']\"", "token_api", "=", "\"https://steemconnect.com/api/oauth2/token?code={}&client_secret={}\"", ".", "format", "(", "code", ","...
tokens = get_refresh_token(code:str,app_secret:str)
[ "tokens", "=", "get_refresh_token", "(", "code", ":", "str", "app_secret", ":", "str", ")" ]
7f3bcc40a4447bfd86de697a75b076d0b5e398d2
https://github.com/coogger/steem-connect/blob/7f3bcc40a4447bfd86de697a75b076d0b5e398d2/steemconnect/client.py#L26-L32
train
Get a refresh token for the user.
giancosta86/Iris
info/gianlucacosta/iris/versioning.py
Version.getFriendlyString
def getFriendlyString(self): """ Returns the version, printed in a friendly way. More precisely, it trims trailing zero components. """ if self._friendlyString is not None: return self._friendlyString resultComponents = [ self.getIntMajor(), ...
python
def getFriendlyString(self): """ Returns the version, printed in a friendly way. More precisely, it trims trailing zero components. """ if self._friendlyString is not None: return self._friendlyString resultComponents = [ self.getIntMajor(), ...
[ "def", "getFriendlyString", "(", "self", ")", ":", "if", "self", ".", "_friendlyString", "is", "not", "None", ":", "return", "self", ".", "_friendlyString", "resultComponents", "=", "[", "self", ".", "getIntMajor", "(", ")", ",", "self", ".", "getIntMinor", ...
Returns the version, printed in a friendly way. More precisely, it trims trailing zero components.
[ "Returns", "the", "version", "printed", "in", "a", "friendly", "way", "." ]
b3d92cca5cce3653519bd032346b211c46a57d05
https://github.com/giancosta86/Iris/blob/b3d92cca5cce3653519bd032346b211c46a57d05/info/gianlucacosta/iris/versioning.py#L117-L143
train
Returns the version printed in a friendly way.
giancosta86/Iris
info/gianlucacosta/iris/versioning.py
VersionDirectory.getVersions
def getVersions(self): """ Returns the versions of the suitable entries available in the directory - an empty list if no such entry is available """ if not os.path.exists(self._path): return [] result = [] for entryName in os.listdir(self._pa...
python
def getVersions(self): """ Returns the versions of the suitable entries available in the directory - an empty list if no such entry is available """ if not os.path.exists(self._path): return [] result = [] for entryName in os.listdir(self._pa...
[ "def", "getVersions", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "_path", ")", ":", "return", "[", "]", "result", "=", "[", "]", "for", "entryName", "in", "os", ".", "listdir", "(", "self", ".", "_path...
Returns the versions of the suitable entries available in the directory - an empty list if no such entry is available
[ "Returns", "the", "versions", "of", "the", "suitable", "entries", "available", "in", "the", "directory", "-", "an", "empty", "list", "if", "no", "such", "entry", "is", "available" ]
b3d92cca5cce3653519bd032346b211c46a57d05
https://github.com/giancosta86/Iris/blob/b3d92cca5cce3653519bd032346b211c46a57d05/info/gianlucacosta/iris/versioning.py#L167-L185
train
Returns the versions of the suitable entries available in the directory.
jstitch/MambuPy
MambuPy/rest/mambubranch.py
MambuBranch.setUsers
def setUsers(self, *args, **kwargs): """Adds the active users for this branch to a 'users' field. Returns the number of requests done to Mambu. .. todo:: since pagination logic was added, is not always true that just 1 request was done. It may be more! But since request counter sin...
python
def setUsers(self, *args, **kwargs): """Adds the active users for this branch to a 'users' field. Returns the number of requests done to Mambu. .. todo:: since pagination logic was added, is not always true that just 1 request was done. It may be more! But since request counter sin...
[ "def", "setUsers", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "usrs", "=", "[", "us", "for", "us", "in", "self", ".", "mambuusersclass", "(", "branchId", "=", "self", "[", "'id'", "]", ",", "*", "args", ",", "...
Adds the active users for this branch to a 'users' field. Returns the number of requests done to Mambu. .. todo:: since pagination logic was added, is not always true that just 1 request was done. It may be more! But since request counter singleton holds true information about how many req...
[ "Adds", "the", "active", "users", "for", "this", "branch", "to", "a", "users", "field", "." ]
2af98cc12e7ed5ec183b3e97644e880e70b79ee8
https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambubranch.py#L39-L57
train
Adds the active users for this branch to a users field. Returns the number of requests done to Mambu.
jstitch/MambuPy
MambuPy/rest/mambubranch.py
MambuBranches.convertDict2Attrs
def convertDict2Attrs(self, *args, **kwargs): """The trick for iterable Mambu Objects comes here: You iterate over each element of the responded List from Mambu, and create a Mambu Branch object for each one, initializing them one at a time, and changing the attrs attribute (which just ...
python
def convertDict2Attrs(self, *args, **kwargs): """The trick for iterable Mambu Objects comes here: You iterate over each element of the responded List from Mambu, and create a Mambu Branch object for each one, initializing them one at a time, and changing the attrs attribute (which just ...
[ "def", "convertDict2Attrs", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "n", ",", "b", "in", "enumerate", "(", "self", ".", "attrs", ")", ":", "# ok ok, I'm modifying elements of a list while iterating it. BAD PRACTICE!", "try", ":",...
The trick for iterable Mambu Objects comes here: You iterate over each element of the responded List from Mambu, and create a Mambu Branch object for each one, initializing them one at a time, and changing the attrs attribute (which just holds a list of plain dictionaries) with a MambuB...
[ "The", "trick", "for", "iterable", "Mambu", "Objects", "comes", "here", ":" ]
2af98cc12e7ed5ec183b3e97644e880e70b79ee8
https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambubranch.py#L78-L106
train
This function converts a dictionary of plain dictionaries into a list of Mambu Branch objects.
cloudmesh-cmd3/cmd3
cmd3/plugins-example/graphviz.py
graphviz.do_graphviz
def do_graphviz(self, args, arguments): """ :: Usage: graphviz FILENAME Export the data in cvs format to a file. Former cvs command Arguments: FILENAME The filename """ filename = arguments['FILENAME'] ...
python
def do_graphviz(self, args, arguments): """ :: Usage: graphviz FILENAME Export the data in cvs format to a file. Former cvs command Arguments: FILENAME The filename """ filename = arguments['FILENAME'] ...
[ "def", "do_graphviz", "(", "self", ",", "args", ",", "arguments", ")", ":", "filename", "=", "arguments", "[", "'FILENAME'", "]", "if", "platform", ".", "system", "(", ")", "==", "'Darwin'", ":", "if", "os", ".", "path", ".", "isfile", "(", "filename",...
:: Usage: graphviz FILENAME Export the data in cvs format to a file. Former cvs command Arguments: FILENAME The filename
[ "::", "Usage", ":", "graphviz", "FILENAME" ]
92e33c96032fd3921f159198a0e57917c4dc34ed
https://github.com/cloudmesh-cmd3/cmd3/blob/92e33c96032fd3921f159198a0e57917c4dc34ed/cmd3/plugins-example/graphviz.py#L14-L30
train
\ ~english Graphviz export the data in cvs format to a file.
cloudmesh-cmd3/cmd3
cmd3/plugins-example/graphviz.py
graphviz.do_dot2
def do_dot2(self, args, arguments): """ :: Usage: dot2 FILENAME FORMAT Export the data in cvs format to a file. Former cvs command Arguments: FILENAME The filename FORMAT the export format, pdf, png, ... ...
python
def do_dot2(self, args, arguments): """ :: Usage: dot2 FILENAME FORMAT Export the data in cvs format to a file. Former cvs command Arguments: FILENAME The filename FORMAT the export format, pdf, png, ... ...
[ "def", "do_dot2", "(", "self", ",", "args", ",", "arguments", ")", ":", "filename", "=", "arguments", "[", "'FILENAME'", "]", "output_format", "=", "arguments", "[", "'FORMAT'", "]", "base", "=", "filename", ".", "replace", "(", "\".dot\"", ",", "\"\"", ...
:: Usage: dot2 FILENAME FORMAT Export the data in cvs format to a file. Former cvs command Arguments: FILENAME The filename FORMAT the export format, pdf, png, ...
[ "::" ]
92e33c96032fd3921f159198a0e57917c4dc34ed
https://github.com/cloudmesh-cmd3/cmd3/blob/92e33c96032fd3921f159198a0e57917c4dc34ed/cmd3/plugins-example/graphviz.py#L33-L56
train
This command is used to export the data in cvs format to a file.
pyQode/pyqode.cobol
pyqode/cobol/modes/indenter.py
IndenterMode.unindent_selection
def unindent_selection(self, cursor): """ Un-indents selected text :param cursor: QTextCursor """ doc = self.editor.document() tab_len = self.editor.tab_length nb_lines = len(cursor.selection().toPlainText().splitlines()) if nb_lines == 0: nb_...
python
def unindent_selection(self, cursor): """ Un-indents selected text :param cursor: QTextCursor """ doc = self.editor.document() tab_len = self.editor.tab_length nb_lines = len(cursor.selection().toPlainText().splitlines()) if nb_lines == 0: nb_...
[ "def", "unindent_selection", "(", "self", ",", "cursor", ")", ":", "doc", "=", "self", ".", "editor", ".", "document", "(", ")", "tab_len", "=", "self", ".", "editor", ".", "tab_length", "nb_lines", "=", "len", "(", "cursor", ".", "selection", "(", ")"...
Un-indents selected text :param cursor: QTextCursor
[ "Un", "-", "indents", "selected", "text" ]
eedae4e320a4b2d0c44abb2c3061091321648fb7
https://github.com/pyQode/pyqode.cobol/blob/eedae4e320a4b2d0c44abb2c3061091321648fb7/pyqode/cobol/modes/indenter.py#L70-L107
train
Un - indents selected text.
pyQode/pyqode.cobol
pyqode/cobol/modes/indenter.py
IndenterMode.indent
def indent(self): """ Indents text at cursor position. """ cursor = self.editor.textCursor() assert isinstance(cursor, QtGui.QTextCursor) if cursor.hasSelection(): self.indent_selection(cursor) else: # simply insert indentation at the curso...
python
def indent(self): """ Indents text at cursor position. """ cursor = self.editor.textCursor() assert isinstance(cursor, QtGui.QTextCursor) if cursor.hasSelection(): self.indent_selection(cursor) else: # simply insert indentation at the curso...
[ "def", "indent", "(", "self", ")", ":", "cursor", "=", "self", ".", "editor", ".", "textCursor", "(", ")", "assert", "isinstance", "(", "cursor", ",", "QtGui", ".", "QTextCursor", ")", "if", "cursor", ".", "hasSelection", "(", ")", ":", "self", ".", ...
Indents text at cursor position.
[ "Indents", "text", "at", "cursor", "position", "." ]
eedae4e320a4b2d0c44abb2c3061091321648fb7
https://github.com/pyQode/pyqode.cobol/blob/eedae4e320a4b2d0c44abb2c3061091321648fb7/pyqode/cobol/modes/indenter.py#L109-L129
train
Indents text at cursor position.
pyQode/pyqode.cobol
pyqode/cobol/modes/indenter.py
IndenterMode.unindent
def unindent(self): """ Un-indents text at cursor position. """ _logger().debug('unindent') cursor = self.editor.textCursor() _logger().debug('cursor has selection %r', cursor.hasSelection()) if cursor.hasSelection(): cursor.beginEditBlock() ...
python
def unindent(self): """ Un-indents text at cursor position. """ _logger().debug('unindent') cursor = self.editor.textCursor() _logger().debug('cursor has selection %r', cursor.hasSelection()) if cursor.hasSelection(): cursor.beginEditBlock() ...
[ "def", "unindent", "(", "self", ")", ":", "_logger", "(", ")", ".", "debug", "(", "'unindent'", ")", "cursor", "=", "self", ".", "editor", ".", "textCursor", "(", ")", "_logger", "(", ")", ".", "debug", "(", "'cursor has selection %r'", ",", "cursor", ...
Un-indents text at cursor position.
[ "Un", "-", "indents", "text", "at", "cursor", "position", "." ]
eedae4e320a4b2d0c44abb2c3061091321648fb7
https://github.com/pyQode/pyqode.cobol/blob/eedae4e320a4b2d0c44abb2c3061091321648fb7/pyqode/cobol/modes/indenter.py#L149-L178
train
Un - indents the current line of text at the current cursor position.
inveniosoftware-contrib/invenio-workflows
invenio_workflows/engine.py
WorkflowEngine.with_name
def with_name(cls, name, id_user=0, **extra_data): """Instantiate a WorkflowEngine given a name or UUID. :param name: name of workflow to run. :type name: str :param id_user: id of user to associate with workflow :type id_user: int :param module_name: label used to que...
python
def with_name(cls, name, id_user=0, **extra_data): """Instantiate a WorkflowEngine given a name or UUID. :param name: name of workflow to run. :type name: str :param id_user: id of user to associate with workflow :type id_user: int :param module_name: label used to que...
[ "def", "with_name", "(", "cls", ",", "name", ",", "id_user", "=", "0", ",", "*", "*", "extra_data", ")", ":", "return", "cls", "(", "name", "=", "name", ",", "id_user", "=", "0", ",", "*", "*", "extra_data", ")" ]
Instantiate a WorkflowEngine given a name or UUID. :param name: name of workflow to run. :type name: str :param id_user: id of user to associate with workflow :type id_user: int :param module_name: label used to query groups of workflows. :type module_name: str
[ "Instantiate", "a", "WorkflowEngine", "given", "a", "name", "or", "UUID", "." ]
9c09fd29509a3db975ac2aba337e6760d8cfd3c2
https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L65-L77
train
Instantiate a WorkflowEngine given a name or UUID.
inveniosoftware-contrib/invenio-workflows
invenio_workflows/engine.py
WorkflowEngine.from_uuid
def from_uuid(cls, uuid, **extra_data): """Load an existing workflow from the database given a UUID. :param uuid: pass a uuid to an existing workflow. :type uuid: str """ model = Workflow.query.get(uuid) if model is None: raise LookupError( "N...
python
def from_uuid(cls, uuid, **extra_data): """Load an existing workflow from the database given a UUID. :param uuid: pass a uuid to an existing workflow. :type uuid: str """ model = Workflow.query.get(uuid) if model is None: raise LookupError( "N...
[ "def", "from_uuid", "(", "cls", ",", "uuid", ",", "*", "*", "extra_data", ")", ":", "model", "=", "Workflow", ".", "query", ".", "get", "(", "uuid", ")", "if", "model", "is", "None", ":", "raise", "LookupError", "(", "\"No workflow with UUID {} was found\"...
Load an existing workflow from the database given a UUID. :param uuid: pass a uuid to an existing workflow. :type uuid: str
[ "Load", "an", "existing", "workflow", "from", "the", "database", "given", "a", "UUID", "." ]
9c09fd29509a3db975ac2aba337e6760d8cfd3c2
https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L80-L96
train
Load an existing workflow from the database given a UUID.
inveniosoftware-contrib/invenio-workflows
invenio_workflows/engine.py
WorkflowEngine.final_objects
def final_objects(self): """Return the objects associated with this workflow.""" return [obj for obj in self.database_objects if obj.status in [obj.known_statuses.COMPLETED]]
python
def final_objects(self): """Return the objects associated with this workflow.""" return [obj for obj in self.database_objects if obj.status in [obj.known_statuses.COMPLETED]]
[ "def", "final_objects", "(", "self", ")", ":", "return", "[", "obj", "for", "obj", "in", "self", ".", "database_objects", "if", "obj", ".", "status", "in", "[", "obj", ".", "known_statuses", ".", "COMPLETED", "]", "]" ]
Return the objects associated with this workflow.
[ "Return", "the", "objects", "associated", "with", "this", "workflow", "." ]
9c09fd29509a3db975ac2aba337e6760d8cfd3c2
https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L149-L152
train
Return the objects associated with this workflow.
inveniosoftware-contrib/invenio-workflows
invenio_workflows/engine.py
WorkflowEngine.halted_objects
def halted_objects(self): """Return the objects associated with this workflow.""" return [obj for obj in self.database_objects if obj.status in [obj.known_statuses.HALTED]]
python
def halted_objects(self): """Return the objects associated with this workflow.""" return [obj for obj in self.database_objects if obj.status in [obj.known_statuses.HALTED]]
[ "def", "halted_objects", "(", "self", ")", ":", "return", "[", "obj", "for", "obj", "in", "self", ".", "database_objects", "if", "obj", ".", "status", "in", "[", "obj", ".", "known_statuses", ".", "HALTED", "]", "]" ]
Return the objects associated with this workflow.
[ "Return", "the", "objects", "associated", "with", "this", "workflow", "." ]
9c09fd29509a3db975ac2aba337e6760d8cfd3c2
https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L155-L158
train
Return the objects associated with this workflow.
inveniosoftware-contrib/invenio-workflows
invenio_workflows/engine.py
WorkflowEngine.running_objects
def running_objects(self): """Return the objects associated with this workflow.""" return [obj for obj in self.database_objects if obj.status in [obj.known_statuses.RUNNING]]
python
def running_objects(self): """Return the objects associated with this workflow.""" return [obj for obj in self.database_objects if obj.status in [obj.known_statuses.RUNNING]]
[ "def", "running_objects", "(", "self", ")", ":", "return", "[", "obj", "for", "obj", "in", "self", ".", "database_objects", "if", "obj", ".", "status", "in", "[", "obj", ".", "known_statuses", ".", "RUNNING", "]", "]" ]
Return the objects associated with this workflow.
[ "Return", "the", "objects", "associated", "with", "this", "workflow", "." ]
9c09fd29509a3db975ac2aba337e6760d8cfd3c2
https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L161-L164
train
Return the objects associated with this workflow.
inveniosoftware-contrib/invenio-workflows
invenio_workflows/engine.py
WorkflowEngine.save
def save(self, status=None): """Save object to persistent storage.""" if self.model is None: raise WorkflowsMissingModel() with db.session.begin_nested(): self.model.modified = datetime.now() if status is not None: self.model.status = status ...
python
def save(self, status=None): """Save object to persistent storage.""" if self.model is None: raise WorkflowsMissingModel() with db.session.begin_nested(): self.model.modified = datetime.now() if status is not None: self.model.status = status ...
[ "def", "save", "(", "self", ",", "status", "=", "None", ")", ":", "if", "self", ".", "model", "is", "None", ":", "raise", "WorkflowsMissingModel", "(", ")", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "self", ".", "model", ".", ...
Save object to persistent storage.
[ "Save", "object", "to", "persistent", "storage", "." ]
9c09fd29509a3db975ac2aba337e6760d8cfd3c2
https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L166-L179
train
Save object to persistent storage.
inveniosoftware-contrib/invenio-workflows
invenio_workflows/engine.py
WorkflowEngine.continue_object
def continue_object(self, workflow_object, restart_point='restart_task', task_offset=1, stop_on_halt=False): """Continue workflow for one given object from "restart_point". :param object: :param stop_on_halt: :param restart_point: can be one of: * res...
python
def continue_object(self, workflow_object, restart_point='restart_task', task_offset=1, stop_on_halt=False): """Continue workflow for one given object from "restart_point". :param object: :param stop_on_halt: :param restart_point: can be one of: * res...
[ "def", "continue_object", "(", "self", ",", "workflow_object", ",", "restart_point", "=", "'restart_task'", ",", "task_offset", "=", "1", ",", "stop_on_halt", "=", "False", ")", ":", "translate", "=", "{", "'restart_task'", ":", "'current'", ",", "'continue_next...
Continue workflow for one given object from "restart_point". :param object: :param stop_on_halt: :param restart_point: can be one of: * restart_prev: will restart from the previous task * continue_next: will continue to the next task * restart_task: will rest...
[ "Continue", "workflow", "for", "one", "given", "object", "from", "restart_point", "." ]
9c09fd29509a3db975ac2aba337e6760d8cfd3c2
https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L193-L215
train
Continue the workflow for one given object from restart_point.
inveniosoftware-contrib/invenio-workflows
invenio_workflows/engine.py
WorkflowEngine.has_completed
def has_completed(self): """Return True if workflow is fully completed.""" objects_in_db = WorkflowObjectModel.query.filter( WorkflowObjectModel.id_workflow == self.uuid, WorkflowObjectModel.id_parent == None, # noqa ).filter(WorkflowObjectModel.status.in_([ ...
python
def has_completed(self): """Return True if workflow is fully completed.""" objects_in_db = WorkflowObjectModel.query.filter( WorkflowObjectModel.id_workflow == self.uuid, WorkflowObjectModel.id_parent == None, # noqa ).filter(WorkflowObjectModel.status.in_([ ...
[ "def", "has_completed", "(", "self", ")", ":", "objects_in_db", "=", "WorkflowObjectModel", ".", "query", ".", "filter", "(", "WorkflowObjectModel", ".", "id_workflow", "==", "self", ".", "uuid", ",", "WorkflowObjectModel", ".", "id_parent", "==", "None", ",", ...
Return True if workflow is fully completed.
[ "Return", "True", "if", "workflow", "is", "fully", "completed", "." ]
9c09fd29509a3db975ac2aba337e6760d8cfd3c2
https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L222-L230
train
Return True if the workflow has completed.
inveniosoftware-contrib/invenio-workflows
invenio_workflows/engine.py
WorkflowEngine.set_workflow_by_name
def set_workflow_by_name(self, workflow_name): """Configure the workflow to run by the name of this one. Allows the modification of the workflow that the engine will run by looking in the registry the name passed in parameter. :param workflow_name: name of the workflow. :type w...
python
def set_workflow_by_name(self, workflow_name): """Configure the workflow to run by the name of this one. Allows the modification of the workflow that the engine will run by looking in the registry the name passed in parameter. :param workflow_name: name of the workflow. :type w...
[ "def", "set_workflow_by_name", "(", "self", ",", "workflow_name", ")", ":", "from", ".", "proxies", "import", "workflows", "if", "workflow_name", "not", "in", "workflows", ":", "# No workflow with that name exists", "raise", "WorkflowDefinitionError", "(", "\"Workflow '...
Configure the workflow to run by the name of this one. Allows the modification of the workflow that the engine will run by looking in the registry the name passed in parameter. :param workflow_name: name of the workflow. :type workflow_name: str
[ "Configure", "the", "workflow", "to", "run", "by", "the", "name", "of", "this", "one", "." ]
9c09fd29509a3db975ac2aba337e6760d8cfd3c2
https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L232-L249
train
Configure the workflow to run by the name passed in.
inveniosoftware-contrib/invenio-workflows
invenio_workflows/engine.py
InvenioActionMapper.after_each_callback
def after_each_callback(eng, callback_func, obj): """Take action after every WF callback.""" obj.callback_pos = eng.state.callback_pos obj.extra_data["_last_task_name"] = callback_func.__name__ task_history = get_task_history(callback_func) if "_task_history" not in obj.extra_dat...
python
def after_each_callback(eng, callback_func, obj): """Take action after every WF callback.""" obj.callback_pos = eng.state.callback_pos obj.extra_data["_last_task_name"] = callback_func.__name__ task_history = get_task_history(callback_func) if "_task_history" not in obj.extra_dat...
[ "def", "after_each_callback", "(", "eng", ",", "callback_func", ",", "obj", ")", ":", "obj", ".", "callback_pos", "=", "eng", ".", "state", ".", "callback_pos", "obj", ".", "extra_data", "[", "\"_last_task_name\"", "]", "=", "callback_func", ".", "__name__", ...
Take action after every WF callback.
[ "Take", "action", "after", "every", "WF", "callback", "." ]
9c09fd29509a3db975ac2aba337e6760d8cfd3c2
https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L275-L283
train
Take action after every WF callback.
inveniosoftware-contrib/invenio-workflows
invenio_workflows/engine.py
InvenioProcessingFactory.before_object
def before_object(eng, objects, obj): """Take action before the processing of an object begins.""" super(InvenioProcessingFactory, InvenioProcessingFactory)\ .before_object( eng, objects, obj ) if "_error_msg" in obj.extra_data: del obj.extra_data["_er...
python
def before_object(eng, objects, obj): """Take action before the processing of an object begins.""" super(InvenioProcessingFactory, InvenioProcessingFactory)\ .before_object( eng, objects, obj ) if "_error_msg" in obj.extra_data: del obj.extra_data["_er...
[ "def", "before_object", "(", "eng", ",", "objects", ",", "obj", ")", ":", "super", "(", "InvenioProcessingFactory", ",", "InvenioProcessingFactory", ")", ".", "before_object", "(", "eng", ",", "objects", ",", "obj", ")", "if", "\"_error_msg\"", "in", "obj", ...
Take action before the processing of an object begins.
[ "Take", "action", "before", "the", "processing", "of", "an", "object", "begins", "." ]
9c09fd29509a3db975ac2aba337e6760d8cfd3c2
https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L300-L308
train
Take action before the processing of an object begins.
inveniosoftware-contrib/invenio-workflows
invenio_workflows/engine.py
InvenioProcessingFactory.after_object
def after_object(eng, objects, obj): """Take action once the proccessing of an object completes.""" # We save each object once it is fully run through super(InvenioProcessingFactory, InvenioProcessingFactory)\ .after_object(eng, objects, obj) obj.save( status=obj....
python
def after_object(eng, objects, obj): """Take action once the proccessing of an object completes.""" # We save each object once it is fully run through super(InvenioProcessingFactory, InvenioProcessingFactory)\ .after_object(eng, objects, obj) obj.save( status=obj....
[ "def", "after_object", "(", "eng", ",", "objects", ",", "obj", ")", ":", "# We save each object once it is fully run through", "super", "(", "InvenioProcessingFactory", ",", "InvenioProcessingFactory", ")", ".", "after_object", "(", "eng", ",", "objects", ",", "obj", ...
Take action once the proccessing of an object completes.
[ "Take", "action", "once", "the", "proccessing", "of", "an", "object", "completes", "." ]
9c09fd29509a3db975ac2aba337e6760d8cfd3c2
https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L311-L320
train
Take action once the proccessing of an object completes.
inveniosoftware-contrib/invenio-workflows
invenio_workflows/engine.py
InvenioProcessingFactory.before_processing
def before_processing(eng, objects): """Execute before processing the workflow.""" super(InvenioProcessingFactory, InvenioProcessingFactory)\ .before_processing(eng, objects) eng.save(WorkflowStatus.RUNNING) db.session.commit()
python
def before_processing(eng, objects): """Execute before processing the workflow.""" super(InvenioProcessingFactory, InvenioProcessingFactory)\ .before_processing(eng, objects) eng.save(WorkflowStatus.RUNNING) db.session.commit()
[ "def", "before_processing", "(", "eng", ",", "objects", ")", ":", "super", "(", "InvenioProcessingFactory", ",", "InvenioProcessingFactory", ")", ".", "before_processing", "(", "eng", ",", "objects", ")", "eng", ".", "save", "(", "WorkflowStatus", ".", "RUNNING"...
Execute before processing the workflow.
[ "Execute", "before", "processing", "the", "workflow", "." ]
9c09fd29509a3db975ac2aba337e6760d8cfd3c2
https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L323-L328
train
Execute before processing the workflow.
inveniosoftware-contrib/invenio-workflows
invenio_workflows/engine.py
InvenioProcessingFactory.after_processing
def after_processing(eng, objects): """Process to update status.""" super(InvenioProcessingFactory, InvenioProcessingFactory)\ .after_processing(eng, objects) if eng.has_completed: eng.save(WorkflowStatus.COMPLETED) else: eng.save(WorkflowStatus.HALTED...
python
def after_processing(eng, objects): """Process to update status.""" super(InvenioProcessingFactory, InvenioProcessingFactory)\ .after_processing(eng, objects) if eng.has_completed: eng.save(WorkflowStatus.COMPLETED) else: eng.save(WorkflowStatus.HALTED...
[ "def", "after_processing", "(", "eng", ",", "objects", ")", ":", "super", "(", "InvenioProcessingFactory", ",", "InvenioProcessingFactory", ")", ".", "after_processing", "(", "eng", ",", "objects", ")", "if", "eng", ".", "has_completed", ":", "eng", ".", "save...
Process to update status.
[ "Process", "to", "update", "status", "." ]
9c09fd29509a3db975ac2aba337e6760d8cfd3c2
https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L331-L339
train
Process to update status.
inveniosoftware-contrib/invenio-workflows
invenio_workflows/engine.py
InvenioTransitionAction.Exception
def Exception(obj, eng, callbacks, exc_info): """Handle general exceptions in workflow, saving states.""" exception_repr = ''.join(traceback.format_exception(*exc_info)) msg = "Error:\n%s" % (exception_repr) eng.log.error(msg) if obj: # Sets an error message as a tupl...
python
def Exception(obj, eng, callbacks, exc_info): """Handle general exceptions in workflow, saving states.""" exception_repr = ''.join(traceback.format_exception(*exc_info)) msg = "Error:\n%s" % (exception_repr) eng.log.error(msg) if obj: # Sets an error message as a tupl...
[ "def", "Exception", "(", "obj", ",", "eng", ",", "callbacks", ",", "exc_info", ")", ":", "exception_repr", "=", "''", ".", "join", "(", "traceback", ".", "format_exception", "(", "*", "exc_info", ")", ")", "msg", "=", "\"Error:\\n%s\"", "%", "(", "except...
Handle general exceptions in workflow, saving states.
[ "Handle", "general", "exceptions", "in", "workflow", "saving", "states", "." ]
9c09fd29509a3db975ac2aba337e6760d8cfd3c2
https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L346-L365
train
Handle general exceptions in workflow saving states.
inveniosoftware-contrib/invenio-workflows
invenio_workflows/engine.py
InvenioTransitionAction.WaitProcessing
def WaitProcessing(obj, eng, callbacks, exc_info): """Take actions when WaitProcessing is raised. ..note:: We're essentially doing HaltProcessing, plus `obj.set_action` and object status `WAITING` instead of `HALTED`. This is not present in TransitionActions so that...
python
def WaitProcessing(obj, eng, callbacks, exc_info): """Take actions when WaitProcessing is raised. ..note:: We're essentially doing HaltProcessing, plus `obj.set_action` and object status `WAITING` instead of `HALTED`. This is not present in TransitionActions so that...
[ "def", "WaitProcessing", "(", "obj", ",", "eng", ",", "callbacks", ",", "exc_info", ")", ":", "e", "=", "exc_info", "[", "1", "]", "obj", ".", "set_action", "(", "e", ".", "action", ",", "e", ".", "message", ")", "obj", ".", "save", "(", "status", ...
Take actions when WaitProcessing is raised. ..note:: We're essentially doing HaltProcessing, plus `obj.set_action` and object status `WAITING` instead of `HALTED`. This is not present in TransitionActions so that's why it is not calling super in this case.
[ "Take", "actions", "when", "WaitProcessing", "is", "raised", "." ]
9c09fd29509a3db975ac2aba337e6760d8cfd3c2
https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L368-L391
train
Take actions when WaitProcessing is raised.
inveniosoftware-contrib/invenio-workflows
invenio_workflows/engine.py
InvenioTransitionAction.StopProcessing
def StopProcessing(obj, eng, callbacks, exc_info): """Stop the engne and mark the workflow as completed.""" e = exc_info[1] obj.save(status=eng.object_status.COMPLETED, id_workflow=eng.uuid) eng.save(WorkflowStatus.COMPLETED) obj.log.warning( "Workflo...
python
def StopProcessing(obj, eng, callbacks, exc_info): """Stop the engne and mark the workflow as completed.""" e = exc_info[1] obj.save(status=eng.object_status.COMPLETED, id_workflow=eng.uuid) eng.save(WorkflowStatus.COMPLETED) obj.log.warning( "Workflo...
[ "def", "StopProcessing", "(", "obj", ",", "eng", ",", "callbacks", ",", "exc_info", ")", ":", "e", "=", "exc_info", "[", "1", "]", "obj", ".", "save", "(", "status", "=", "eng", ".", "object_status", ".", "COMPLETED", ",", "id_workflow", "=", "eng", ...
Stop the engne and mark the workflow as completed.
[ "Stop", "the", "engne", "and", "mark", "the", "workflow", "as", "completed", "." ]
9c09fd29509a3db975ac2aba337e6760d8cfd3c2
https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L419-L433
train
Stop the engne and mark the workflow as completed.
inveniosoftware-contrib/invenio-workflows
invenio_workflows/engine.py
InvenioTransitionAction.SkipToken
def SkipToken(obj, eng, callbacks, exc_info): """Take action when SkipToken is raised.""" msg = "Skipped running this object: {0}".format(obj.id) eng.log.debug(msg) raise Continue
python
def SkipToken(obj, eng, callbacks, exc_info): """Take action when SkipToken is raised.""" msg = "Skipped running this object: {0}".format(obj.id) eng.log.debug(msg) raise Continue
[ "def", "SkipToken", "(", "obj", ",", "eng", ",", "callbacks", ",", "exc_info", ")", ":", "msg", "=", "\"Skipped running this object: {0}\"", ".", "format", "(", "obj", ".", "id", ")", "eng", ".", "log", ".", "debug", "(", "msg", ")", "raise", "Continue" ...
Take action when SkipToken is raised.
[ "Take", "action", "when", "SkipToken", "is", "raised", "." ]
9c09fd29509a3db975ac2aba337e6760d8cfd3c2
https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L436-L440
train
Take action when SkipToken is raised.
inveniosoftware-contrib/invenio-workflows
invenio_workflows/engine.py
InvenioTransitionAction.AbortProcessing
def AbortProcessing(obj, eng, callbacks, exc_info): """Take action when AbortProcessing is raised.""" msg = "Processing was aborted for object: {0}".format(obj.id) eng.log.debug(msg) raise Break
python
def AbortProcessing(obj, eng, callbacks, exc_info): """Take action when AbortProcessing is raised.""" msg = "Processing was aborted for object: {0}".format(obj.id) eng.log.debug(msg) raise Break
[ "def", "AbortProcessing", "(", "obj", ",", "eng", ",", "callbacks", ",", "exc_info", ")", ":", "msg", "=", "\"Processing was aborted for object: {0}\"", ".", "format", "(", "obj", ".", "id", ")", "eng", ".", "log", ".", "debug", "(", "msg", ")", "raise", ...
Take action when AbortProcessing is raised.
[ "Take", "action", "when", "AbortProcessing", "is", "raised", "." ]
9c09fd29509a3db975ac2aba337e6760d8cfd3c2
https://github.com/inveniosoftware-contrib/invenio-workflows/blob/9c09fd29509a3db975ac2aba337e6760d8cfd3c2/invenio_workflows/engine.py#L443-L447
train
Take action when AbortProcessing is raised.
xypnox/email_purifier
epurifier/tezt.py
edits1
def edits1(word): "All edits that are one edit away from `word`." letters = 'qwertyuiopasdfghjklzxcvbnm' splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] print('splits = ', splits) deletes = [L + R[1:] for L, R in splits if R] print('deletes = ', deletes) transposes = [L + R[1] ...
python
def edits1(word): "All edits that are one edit away from `word`." letters = 'qwertyuiopasdfghjklzxcvbnm' splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] print('splits = ', splits) deletes = [L + R[1:] for L, R in splits if R] print('deletes = ', deletes) transposes = [L + R[1] ...
[ "def", "edits1", "(", "word", ")", ":", "letters", "=", "'qwertyuiopasdfghjklzxcvbnm'", "splits", "=", "[", "(", "word", "[", ":", "i", "]", ",", "word", "[", "i", ":", "]", ")", "for", "i", "in", "range", "(", "len", "(", "word", ")", "+", "1", ...
All edits that are one edit away from `word`.
[ "All", "edits", "that", "are", "one", "edit", "away", "from", "word", "." ]
a9ecde9c5293b5c283e0c5b4cf8744c76418fb6f
https://github.com/xypnox/email_purifier/blob/a9ecde9c5293b5c283e0c5b4cf8744c76418fb6f/epurifier/tezt.py#L1-L16
train
All edits that are one edit away from word.
openvax/varlens
varlens/read_evidence/pileup_collection.py
to_locus
def to_locus(variant_or_locus): """ Return a Locus object for a Variant instance. This is necessary since the read evidence module expects Variant instances to have a locus attribute st to a varcode.Locus instance of interbase genomic coordinates. The rest of varcode uses a different Variant class...
python
def to_locus(variant_or_locus): """ Return a Locus object for a Variant instance. This is necessary since the read evidence module expects Variant instances to have a locus attribute st to a varcode.Locus instance of interbase genomic coordinates. The rest of varcode uses a different Variant class...
[ "def", "to_locus", "(", "variant_or_locus", ")", ":", "if", "isinstance", "(", "variant_or_locus", ",", "Locus", ")", ":", "return", "variant_or_locus", "try", ":", "return", "variant_or_locus", ".", "locus", "except", "AttributeError", ":", "# IMPORTANT: if varcode...
Return a Locus object for a Variant instance. This is necessary since the read evidence module expects Variant instances to have a locus attribute st to a varcode.Locus instance of interbase genomic coordinates. The rest of varcode uses a different Variant class, but will eventually be transitioned to...
[ "Return", "a", "Locus", "object", "for", "a", "Variant", "instance", "." ]
715d3ede5893757b2fcba4117515621bca7b1e5d
https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/read_evidence/pileup_collection.py#L605-L634
train
Converts a Variant instance to a Locus object.
openvax/varlens
varlens/read_evidence/pileup_collection.py
PileupCollection.pileup
def pileup(self, locus): ''' Given a 1-base locus, return the Pileup at that locus. Raises a KeyError if this PileupCollection does not have a Pileup at the specified locus. ''' locus = to_locus(locus) if len(locus.positions) != 1: raise ValueError("N...
python
def pileup(self, locus): ''' Given a 1-base locus, return the Pileup at that locus. Raises a KeyError if this PileupCollection does not have a Pileup at the specified locus. ''' locus = to_locus(locus) if len(locus.positions) != 1: raise ValueError("N...
[ "def", "pileup", "(", "self", ",", "locus", ")", ":", "locus", "=", "to_locus", "(", "locus", ")", "if", "len", "(", "locus", ".", "positions", ")", "!=", "1", ":", "raise", "ValueError", "(", "\"Not a single-base locus: %s\"", "%", "locus", ")", "return...
Given a 1-base locus, return the Pileup at that locus. Raises a KeyError if this PileupCollection does not have a Pileup at the specified locus.
[ "Given", "a", "1", "-", "base", "locus", "return", "the", "Pileup", "at", "that", "locus", "." ]
715d3ede5893757b2fcba4117515621bca7b1e5d
https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/read_evidence/pileup_collection.py#L54-L64
train
Given a 1 - base locus return the Pileup at that locus. Raises a KeyError if this PileupCollection does not have a Pileup at that locus.
openvax/varlens
varlens/read_evidence/pileup_collection.py
PileupCollection.at
def at(self, *loci): ''' Return a new PileupCollection instance including only pileups for the specified loci. ''' loci = [to_locus(obj) for obj in loci] single_position_loci = [] for locus in loci: for position in locus.positions: sin...
python
def at(self, *loci): ''' Return a new PileupCollection instance including only pileups for the specified loci. ''' loci = [to_locus(obj) for obj in loci] single_position_loci = [] for locus in loci: for position in locus.positions: sin...
[ "def", "at", "(", "self", ",", "*", "loci", ")", ":", "loci", "=", "[", "to_locus", "(", "obj", ")", "for", "obj", "in", "loci", "]", "single_position_loci", "=", "[", "]", "for", "locus", "in", "loci", ":", "for", "position", "in", "locus", ".", ...
Return a new PileupCollection instance including only pileups for the specified loci.
[ "Return", "a", "new", "PileupCollection", "instance", "including", "only", "pileups", "for", "the", "specified", "loci", "." ]
715d3ede5893757b2fcba4117515621bca7b1e5d
https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/read_evidence/pileup_collection.py#L66-L79
train
Return a new PileupCollection instance including only pileups for the specified loci.
openvax/varlens
varlens/read_evidence/pileup_collection.py
PileupCollection.reads
def reads(self): ''' The reads in this PileupCollection. All reads will have an alignment that overlaps at least one of the included loci. Since SAM (and pysam) have no real notion of a "read", the returned instances are actually pysam.AlignedSegment instances, (i.e. al...
python
def reads(self): ''' The reads in this PileupCollection. All reads will have an alignment that overlaps at least one of the included loci. Since SAM (and pysam) have no real notion of a "read", the returned instances are actually pysam.AlignedSegment instances, (i.e. al...
[ "def", "reads", "(", "self", ")", ":", "# TODO: Optimize this.", "def", "alignment_precedence", "(", "pysam_alignment_record", ")", ":", "return", "pysam_alignment_record", ".", "mapping_quality", "result", "=", "{", "}", "for", "pileup", "in", "self", ".", "pileu...
The reads in this PileupCollection. All reads will have an alignment that overlaps at least one of the included loci. Since SAM (and pysam) have no real notion of a "read", the returned instances are actually pysam.AlignedSegment instances, (i.e. alignments). However, only one alignmen...
[ "The", "reads", "in", "this", "PileupCollection", ".", "All", "reads", "will", "have", "an", "alignment", "that", "overlaps", "at", "least", "one", "of", "the", "included", "loci", "." ]
715d3ede5893757b2fcba4117515621bca7b1e5d
https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/read_evidence/pileup_collection.py#L87-L117
train
Returns a list of pysam. AlignedSegment instances for all reads in this PileupCollection.
openvax/varlens
varlens/read_evidence/pileup_collection.py
PileupCollection.read_attributes
def read_attributes(self, attributes=None): ''' Collect read attributes across reads in this PileupCollection into a pandas.DataFrame. Valid attributes are the following properties of a pysam.AlignedSegment instance. See: http://pysam.readthedocs.org/en/latest/api.ht...
python
def read_attributes(self, attributes=None): ''' Collect read attributes across reads in this PileupCollection into a pandas.DataFrame. Valid attributes are the following properties of a pysam.AlignedSegment instance. See: http://pysam.readthedocs.org/en/latest/api.ht...
[ "def", "read_attributes", "(", "self", ",", "attributes", "=", "None", ")", ":", "def", "include", "(", "attribute", ")", ":", "return", "attributes", "is", "None", "or", "attribute", "in", "attributes", "reads", "=", "self", ".", "reads", "(", ")", "pos...
Collect read attributes across reads in this PileupCollection into a pandas.DataFrame. Valid attributes are the following properties of a pysam.AlignedSegment instance. See: http://pysam.readthedocs.org/en/latest/api.html#pysam.AlignedSegment for the meaning of these attribu...
[ "Collect", "read", "attributes", "across", "reads", "in", "this", "PileupCollection", "into", "a", "pandas", ".", "DataFrame", "." ]
715d3ede5893757b2fcba4117515621bca7b1e5d
https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/read_evidence/pileup_collection.py#L143-L240
train
Returns a pandas. DataFrame containing the read attributes across the reads in this PileupCollection.
openvax/varlens
varlens/read_evidence/pileup_collection.py
PileupCollection.group_by_allele
def group_by_allele(self, locus): ''' Split the PileupCollection by the alleles suggested by the reads at the specified locus. If a read has an insertion immediately following the locus, then the insertion is included in the allele. For example, if locus is the 1-base ra...
python
def group_by_allele(self, locus): ''' Split the PileupCollection by the alleles suggested by the reads at the specified locus. If a read has an insertion immediately following the locus, then the insertion is included in the allele. For example, if locus is the 1-base ra...
[ "def", "group_by_allele", "(", "self", ",", "locus", ")", ":", "locus", "=", "to_locus", "(", "locus", ")", "read_to_allele", "=", "None", "loci", "=", "[", "]", "if", "locus", ".", "positions", ":", "# Our locus includes at least one reference base.", "for", ...
Split the PileupCollection by the alleles suggested by the reads at the specified locus. If a read has an insertion immediately following the locus, then the insertion is included in the allele. For example, if locus is the 1-base range [5,6), one allele might be "AGA", indicating that ...
[ "Split", "the", "PileupCollection", "by", "the", "alleles", "suggested", "by", "the", "reads", "at", "the", "specified", "locus", "." ]
715d3ede5893757b2fcba4117515621bca7b1e5d
https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/read_evidence/pileup_collection.py#L249-L336
train
Split the PileupCollection by the alleles suggested by reads at the specified locus.
openvax/varlens
varlens/read_evidence/pileup_collection.py
PileupCollection.allele_summary
def allele_summary(self, locus, score=lambda x: x.num_reads()): ''' Convenience method to summarize the evidence for each of the alleles present at a locus. Applies a score function to the PileupCollection associated with each allele. See also `PileupCollection.group_by_allele`....
python
def allele_summary(self, locus, score=lambda x: x.num_reads()): ''' Convenience method to summarize the evidence for each of the alleles present at a locus. Applies a score function to the PileupCollection associated with each allele. See also `PileupCollection.group_by_allele`....
[ "def", "allele_summary", "(", "self", ",", "locus", ",", "score", "=", "lambda", "x", ":", "x", ".", "num_reads", "(", ")", ")", ":", "locus", "=", "to_locus", "(", "locus", ")", "return", "[", "(", "allele", ",", "score", "(", "x", ")", ")", "fo...
Convenience method to summarize the evidence for each of the alleles present at a locus. Applies a score function to the PileupCollection associated with each allele. See also `PileupCollection.group_by_allele`. Parameters ---------- locus : Locus The refere...
[ "Convenience", "method", "to", "summarize", "the", "evidence", "for", "each", "of", "the", "alleles", "present", "at", "a", "locus", ".", "Applies", "a", "score", "function", "to", "the", "PileupCollection", "associated", "with", "each", "allele", "." ]
715d3ede5893757b2fcba4117515621bca7b1e5d
https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/read_evidence/pileup_collection.py#L338-L363
train
Convenience method to summarize the evidence for each allele in a locus.
openvax/varlens
varlens/read_evidence/pileup_collection.py
PileupCollection.group_by_match
def group_by_match(self, variant): ''' Given a variant, split the PileupCollection based on whether it the data supports the reference allele, the alternate allele, or neither. Parameters ---------- variant : Variant The variant. Must have fields 'locus', 're...
python
def group_by_match(self, variant): ''' Given a variant, split the PileupCollection based on whether it the data supports the reference allele, the alternate allele, or neither. Parameters ---------- variant : Variant The variant. Must have fields 'locus', 're...
[ "def", "group_by_match", "(", "self", ",", "variant", ")", ":", "locus", "=", "to_locus", "(", "variant", ")", "if", "len", "(", "variant", ".", "ref", ")", "!=", "len", "(", "locus", ".", "positions", ")", ":", "logging", ".", "warning", "(", "\"Ref...
Given a variant, split the PileupCollection based on whether it the data supports the reference allele, the alternate allele, or neither. Parameters ---------- variant : Variant The variant. Must have fields 'locus', 'ref', and 'alt'. Returns ---------- ...
[ "Given", "a", "variant", "split", "the", "PileupCollection", "based", "on", "whether", "it", "the", "data", "supports", "the", "reference", "allele", "the", "alternate", "allele", "or", "neither", "." ]
715d3ede5893757b2fcba4117515621bca7b1e5d
https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/read_evidence/pileup_collection.py#L365-L402
train
Given a variant split the PileupCollection based on whether it the PileupCollection supports the reference allele and the alternate allele or neither.
openvax/varlens
varlens/read_evidence/pileup_collection.py
PileupCollection.match_summary
def match_summary(self, variant, score=lambda x: x.num_reads()): ''' Convenience method to summarize the evidence for and against a variant using a user-specified score function. See also `PileupCollection.group_by_match`. Parameters ---------- variant : Variant...
python
def match_summary(self, variant, score=lambda x: x.num_reads()): ''' Convenience method to summarize the evidence for and against a variant using a user-specified score function. See also `PileupCollection.group_by_match`. Parameters ---------- variant : Variant...
[ "def", "match_summary", "(", "self", ",", "variant", ",", "score", "=", "lambda", "x", ":", "x", ".", "num_reads", "(", ")", ")", ":", "split", "=", "self", ".", "group_by_match", "(", "variant", ")", "def", "name", "(", "allele_to_pileup_collection", ")...
Convenience method to summarize the evidence for and against a variant using a user-specified score function. See also `PileupCollection.group_by_match`. Parameters ---------- variant : Variant The variant. Must have fields 'locus', 'ref', and 'alt'. score ...
[ "Convenience", "method", "to", "summarize", "the", "evidence", "for", "and", "against", "a", "variant", "using", "a", "user", "-", "specified", "score", "function", "." ]
715d3ede5893757b2fcba4117515621bca7b1e5d
https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/read_evidence/pileup_collection.py#L404-L443
train
Returns a summary of the evidence for and against a variant.
openvax/varlens
varlens/read_evidence/pileup_collection.py
PileupCollection.filter
def filter(self, drop_duplicates=False, drop_improper_mate_pairs=False, min_mapping_quality=None, min_base_quality=None, filters=None): ''' Return a new PileupCollection that includes only pileup elements satisfying the specified criter...
python
def filter(self, drop_duplicates=False, drop_improper_mate_pairs=False, min_mapping_quality=None, min_base_quality=None, filters=None): ''' Return a new PileupCollection that includes only pileup elements satisfying the specified criter...
[ "def", "filter", "(", "self", ",", "drop_duplicates", "=", "False", ",", "drop_improper_mate_pairs", "=", "False", ",", "min_mapping_quality", "=", "None", ",", "min_base_quality", "=", "None", ",", "filters", "=", "None", ")", ":", "if", "filters", "is", "N...
Return a new PileupCollection that includes only pileup elements satisfying the specified criteria. Parameters ---------- drop_duplicates (optional, default False) : boolean Remove alignments with the is_duplicate flag. drop_improper_mate_pairs (optional, default Fa...
[ "Return", "a", "new", "PileupCollection", "that", "includes", "only", "pileup", "elements", "satisfying", "the", "specified", "criteria", "." ]
715d3ede5893757b2fcba4117515621bca7b1e5d
https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/read_evidence/pileup_collection.py#L445-L501
train
Returns a new PileupCollection containing only the subset of the specified pileup elements.
openvax/varlens
varlens/read_evidence/pileup_collection.py
PileupCollection.merge
def merge(self, *others): ''' Return a new PileupCollection that is the union of self and the other specified collections. ''' new_pileups = {} for collection in (self,) + others: for (locus, pileup) in collection.pileups.items(): if locus in n...
python
def merge(self, *others): ''' Return a new PileupCollection that is the union of self and the other specified collections. ''' new_pileups = {} for collection in (self,) + others: for (locus, pileup) in collection.pileups.items(): if locus in n...
[ "def", "merge", "(", "self", ",", "*", "others", ")", ":", "new_pileups", "=", "{", "}", "for", "collection", "in", "(", "self", ",", ")", "+", "others", ":", "for", "(", "locus", ",", "pileup", ")", "in", "collection", ".", "pileups", ".", "items"...
Return a new PileupCollection that is the union of self and the other specified collections.
[ "Return", "a", "new", "PileupCollection", "that", "is", "the", "union", "of", "self", "and", "the", "other", "specified", "collections", "." ]
715d3ede5893757b2fcba4117515621bca7b1e5d
https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/read_evidence/pileup_collection.py#L503-L515
train
Return a new PileupCollection that is the union of self and the other PileupCollections.
openvax/varlens
varlens/read_evidence/pileup_collection.py
PileupCollection.from_bam
def from_bam(pysam_samfile, loci, normalized_contig_names=True): ''' Create a PileupCollection for a set of loci from a BAM file. Parameters ---------- pysam_samfile : `pysam.Samfile` instance, or filename string to a BAM file. The BAM file must be indexed. ...
python
def from_bam(pysam_samfile, loci, normalized_contig_names=True): ''' Create a PileupCollection for a set of loci from a BAM file. Parameters ---------- pysam_samfile : `pysam.Samfile` instance, or filename string to a BAM file. The BAM file must be indexed. ...
[ "def", "from_bam", "(", "pysam_samfile", ",", "loci", ",", "normalized_contig_names", "=", "True", ")", ":", "loci", "=", "[", "to_locus", "(", "obj", ")", "for", "obj", "in", "loci", "]", "close_on_completion", "=", "False", "if", "typechecks", ".", "is_s...
Create a PileupCollection for a set of loci from a BAM file. Parameters ---------- pysam_samfile : `pysam.Samfile` instance, or filename string to a BAM file. The BAM file must be indexed. loci : list of Locus instances Loci to collect pileups for. norm...
[ "Create", "a", "PileupCollection", "for", "a", "set", "of", "loci", "from", "a", "BAM", "file", "." ]
715d3ede5893757b2fcba4117515621bca7b1e5d
https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/read_evidence/pileup_collection.py#L518-L603
train
Create a PileupCollection instance for a set of loci from a BAM file.
inveniosoftware/invenio-query-parser
invenio_query_parser/contrib/elasticsearch/__init__.py
invenio_query_factory
def invenio_query_factory(parser=None, walkers=None): """Create a parser returning Elastic Search DSL query instance.""" parser = parser or Main walkers = walkers or [PypegConverter()] walkers.append(ElasticSearchDSL()) def invenio_query(pattern): query = pypeg2.parse(pattern, parser, white...
python
def invenio_query_factory(parser=None, walkers=None): """Create a parser returning Elastic Search DSL query instance.""" parser = parser or Main walkers = walkers or [PypegConverter()] walkers.append(ElasticSearchDSL()) def invenio_query(pattern): query = pypeg2.parse(pattern, parser, white...
[ "def", "invenio_query_factory", "(", "parser", "=", "None", ",", "walkers", "=", "None", ")", ":", "parser", "=", "parser", "or", "Main", "walkers", "=", "walkers", "or", "[", "PypegConverter", "(", ")", "]", "walkers", ".", "append", "(", "ElasticSearchDS...
Create a parser returning Elastic Search DSL query instance.
[ "Create", "a", "parser", "returning", "Elastic", "Search", "DSL", "query", "instance", "." ]
21a2c36318003ff52d2e18e7196bb420db8ecb4b
https://github.com/inveniosoftware/invenio-query-parser/blob/21a2c36318003ff52d2e18e7196bb420db8ecb4b/invenio_query_parser/contrib/elasticsearch/__init__.py#L34-L45
train
Create a parser returning Elastic Search DSL query instance.
ioos/cc-plugin-ncei
cc_plugin_ncei/ncei_timeseries_profile.py
NCEITimeSeriesProfileOrthogonalBase.check_dimensions
def check_dimensions(self, dataset): ''' Checks that the feature types of this dataset are consistent with a timeseries-profile-orthogonal dataset. :param netCDF4.Dataset dataset: An open netCDF dataset ''' results = [] required_ctx = TestCtx(BaseCheck.HIGH, 'All geophys...
python
def check_dimensions(self, dataset): ''' Checks that the feature types of this dataset are consistent with a timeseries-profile-orthogonal dataset. :param netCDF4.Dataset dataset: An open netCDF dataset ''' results = [] required_ctx = TestCtx(BaseCheck.HIGH, 'All geophys...
[ "def", "check_dimensions", "(", "self", ",", "dataset", ")", ":", "results", "=", "[", "]", "required_ctx", "=", "TestCtx", "(", "BaseCheck", ".", "HIGH", ",", "'All geophysical variables are timeseries-profile-orthogonal feature types'", ")", "message", "=", "'{} mus...
Checks that the feature types of this dataset are consistent with a timeseries-profile-orthogonal dataset. :param netCDF4.Dataset dataset: An open netCDF dataset
[ "Checks", "that", "the", "feature", "types", "of", "this", "dataset", "are", "consistent", "with", "a", "timeseries", "-", "profile", "-", "orthogonal", "dataset", "." ]
963fefd7fa43afd32657ac4c36aad4ddb4c25acf
https://github.com/ioos/cc-plugin-ncei/blob/963fefd7fa43afd32657ac4c36aad4ddb4c25acf/cc_plugin_ncei/ncei_timeseries_profile.py#L21-L43
train
Checks that the feature types of this dataset are consistent with a timeseries - profile - orthogonal dataset.
cloudmesh-cmd3/cmd3
fabfile/doc.py
theme
def theme(name='readthedocs'): """set name to 'bootstrap' in case you want to use bootstrap. This also requires the template sto be in the main dir""" os.environ['SPHINX_THEME'] = name if os.environ['SPHINX_THEME'] == 'bootstrap': local('cp docs/source/_templates/layout_bootstrap.html docs/...
python
def theme(name='readthedocs'): """set name to 'bootstrap' in case you want to use bootstrap. This also requires the template sto be in the main dir""" os.environ['SPHINX_THEME'] = name if os.environ['SPHINX_THEME'] == 'bootstrap': local('cp docs/source/_templates/layout_bootstrap.html docs/...
[ "def", "theme", "(", "name", "=", "'readthedocs'", ")", ":", "os", ".", "environ", "[", "'SPHINX_THEME'", "]", "=", "name", "if", "os", ".", "environ", "[", "'SPHINX_THEME'", "]", "==", "'bootstrap'", ":", "local", "(", "'cp docs/source/_templates/layout_boots...
set name to 'bootstrap' in case you want to use bootstrap. This also requires the template sto be in the main dir
[ "set", "name", "to", "bootstrap", "in", "case", "you", "want", "to", "use", "bootstrap", ".", "This", "also", "requires", "the", "template", "sto", "be", "in", "the", "main", "dir" ]
92e33c96032fd3921f159198a0e57917c4dc34ed
https://github.com/cloudmesh-cmd3/cmd3/blob/92e33c96032fd3921f159198a0e57917c4dc34ed/fabfile/doc.py#L57-L67
train
set the name of the theme
cloudmesh-cmd3/cmd3
fabfile/doc.py
html
def html(theme_name='readthedocs'): # disable Flask RSTPAGES due to sphinx incompatibility os.environ['RSTPAGES'] = 'FALSE' theme(theme_name) api() man() """build the doc locally and view""" clean() local("cd docs; make html") local("fab security.check") local("touch docs/build/h...
python
def html(theme_name='readthedocs'): # disable Flask RSTPAGES due to sphinx incompatibility os.environ['RSTPAGES'] = 'FALSE' theme(theme_name) api() man() """build the doc locally and view""" clean() local("cd docs; make html") local("fab security.check") local("touch docs/build/h...
[ "def", "html", "(", "theme_name", "=", "'readthedocs'", ")", ":", "# disable Flask RSTPAGES due to sphinx incompatibility", "os", ".", "environ", "[", "'RSTPAGES'", "]", "=", "'FALSE'", "theme", "(", "theme_name", ")", "api", "(", ")", "man", "(", ")", "clean", ...
build the doc locally and view
[ "build", "the", "doc", "locally", "and", "view" ]
92e33c96032fd3921f159198a0e57917c4dc34ed
https://github.com/cloudmesh-cmd3/cmd3/blob/92e33c96032fd3921f159198a0e57917c4dc34ed/fabfile/doc.py#L70-L80
train
Build the html file locally and view
BernardFW/bernard
src/bernard/platforms/facebook/platform.py
sign_message
def sign_message(body: ByteString, secret: Text) -> Text: """ Compute a message's signature. """ return 'sha1={}'.format( hmac.new(secret.encode(), body, sha1).hexdigest() )
python
def sign_message(body: ByteString, secret: Text) -> Text: """ Compute a message's signature. """ return 'sha1={}'.format( hmac.new(secret.encode(), body, sha1).hexdigest() )
[ "def", "sign_message", "(", "body", ":", "ByteString", ",", "secret", ":", "Text", ")", "->", "Text", ":", "return", "'sha1={}'", ".", "format", "(", "hmac", ".", "new", "(", "secret", ".", "encode", "(", ")", ",", "body", ",", "sha1", ")", ".", "h...
Compute a message's signature.
[ "Compute", "a", "message", "s", "signature", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L112-L119
train
Compute a message s signature.
BernardFW/bernard
src/bernard/platforms/facebook/platform.py
FacebookUser._get_user
async def _get_user(self): """ Get the user dict from cache or query it from the platform if missing. """ if self._cache is None: try: self._cache = \ await self.facebook.get_user(self.fbid, self.page_id) except PlatformOperati...
python
async def _get_user(self): """ Get the user dict from cache or query it from the platform if missing. """ if self._cache is None: try: self._cache = \ await self.facebook.get_user(self.fbid, self.page_id) except PlatformOperati...
[ "async", "def", "_get_user", "(", "self", ")", ":", "if", "self", ".", "_cache", "is", "None", ":", "try", ":", "self", ".", "_cache", "=", "await", "self", ".", "facebook", ".", "get_user", "(", "self", ".", "fbid", ",", "self", ".", "page_id", ")...
Get the user dict from cache or query it from the platform if missing.
[ "Get", "the", "user", "dict", "from", "cache", "or", "query", "it", "from", "the", "platform", "if", "missing", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L146-L157
train
Get the user dict from the cache or query it from the platform
BernardFW/bernard
src/bernard/platforms/facebook/platform.py
FacebookUser.get_friendly_name
async def get_friendly_name(self) -> Text: """ The friendly name is mapped to Facebook's first name. If the first name is missing, use the last name. """ u = await self._get_user() f = u.get('first_name', '').strip() l = u.get('last_name', '').strip() ret...
python
async def get_friendly_name(self) -> Text: """ The friendly name is mapped to Facebook's first name. If the first name is missing, use the last name. """ u = await self._get_user() f = u.get('first_name', '').strip() l = u.get('last_name', '').strip() ret...
[ "async", "def", "get_friendly_name", "(", "self", ")", "->", "Text", ":", "u", "=", "await", "self", ".", "_get_user", "(", ")", "f", "=", "u", ".", "get", "(", "'first_name'", ",", "''", ")", ".", "strip", "(", ")", "l", "=", "u", ".", "get", ...
The friendly name is mapped to Facebook's first name. If the first name is missing, use the last name.
[ "The", "friendly", "name", "is", "mapped", "to", "Facebook", "s", "first", "name", ".", "If", "the", "first", "name", "is", "missing", "use", "the", "last", "name", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L171-L180
train
Get the friendly name of the user.
BernardFW/bernard
src/bernard/platforms/facebook/platform.py
FacebookUser.get_gender
async def get_gender(self) -> User.Gender: """ Get the gender from Facebook. """ u = await self._get_user() try: return User.Gender(u.get('gender')) except ValueError: return User.Gender.unknown
python
async def get_gender(self) -> User.Gender: """ Get the gender from Facebook. """ u = await self._get_user() try: return User.Gender(u.get('gender')) except ValueError: return User.Gender.unknown
[ "async", "def", "get_gender", "(", "self", ")", "->", "User", ".", "Gender", ":", "u", "=", "await", "self", ".", "_get_user", "(", ")", "try", ":", "return", "User", ".", "Gender", "(", "u", ".", "get", "(", "'gender'", ")", ")", "except", "ValueE...
Get the gender from Facebook.
[ "Get", "the", "gender", "from", "Facebook", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L182-L191
train
Get the gender from Facebook.
BernardFW/bernard
src/bernard/platforms/facebook/platform.py
FacebookUser.get_timezone
async def get_timezone(self) -> Optional[tzinfo]: """ We can't exactly know the time zone of the user from what Facebook gives (fucking morons) but we can still give something that'll work until next DST. """ u = await self._get_user() diff = float(u.get('timezon...
python
async def get_timezone(self) -> Optional[tzinfo]: """ We can't exactly know the time zone of the user from what Facebook gives (fucking morons) but we can still give something that'll work until next DST. """ u = await self._get_user() diff = float(u.get('timezon...
[ "async", "def", "get_timezone", "(", "self", ")", "->", "Optional", "[", "tzinfo", "]", ":", "u", "=", "await", "self", ".", "_get_user", "(", ")", "diff", "=", "float", "(", "u", ".", "get", "(", "'timezone'", ",", "0", ")", ")", "*", "3600.0", ...
We can't exactly know the time zone of the user from what Facebook gives (fucking morons) but we can still give something that'll work until next DST.
[ "We", "can", "t", "exactly", "know", "the", "time", "zone", "of", "the", "user", "from", "what", "Facebook", "gives", "(", "fucking", "morons", ")", "but", "we", "can", "still", "give", "something", "that", "ll", "work", "until", "next", "DST", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L193-L203
train
Get the time zone of the user s Facebook entry.
BernardFW/bernard
src/bernard/platforms/facebook/platform.py
FacebookMessage.get_user
def get_user(self) -> FacebookUser: """ Generate a Facebook user instance """ return FacebookUser( self._event['sender']['id'], self.get_page_id(), self._facebook, self, )
python
def get_user(self) -> FacebookUser: """ Generate a Facebook user instance """ return FacebookUser( self._event['sender']['id'], self.get_page_id(), self._facebook, self, )
[ "def", "get_user", "(", "self", ")", "->", "FacebookUser", ":", "return", "FacebookUser", "(", "self", ".", "_event", "[", "'sender'", "]", "[", "'id'", "]", ",", "self", ".", "get_page_id", "(", ")", ",", "self", ".", "_facebook", ",", "self", ",", ...
Generate a Facebook user instance
[ "Generate", "a", "Facebook", "user", "instance" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L244-L253
train
Generate a Facebook user instance
BernardFW/bernard
src/bernard/platforms/facebook/platform.py
FacebookMessage.get_layers
def get_layers(self) -> List[BaseLayer]: """ Return all layers that can be found in the message. """ out = [] msg = self._event.get('message', {}) if 'text' in msg: out.append(lyr.RawText(msg['text'])) for attachment in msg.get('attachments') or []: ...
python
def get_layers(self) -> List[BaseLayer]: """ Return all layers that can be found in the message. """ out = [] msg = self._event.get('message', {}) if 'text' in msg: out.append(lyr.RawText(msg['text'])) for attachment in msg.get('attachments') or []: ...
[ "def", "get_layers", "(", "self", ")", "->", "List", "[", "BaseLayer", "]", ":", "out", "=", "[", "]", "msg", "=", "self", ".", "_event", ".", "get", "(", "'message'", ",", "{", "}", ")", "if", "'text'", "in", "msg", ":", "out", ".", "append", ...
Return all layers that can be found in the message.
[ "Return", "all", "layers", "that", "can", "be", "found", "in", "the", "message", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L261-L297
train
Returns all layers that can be found in the message.
BernardFW/bernard
src/bernard/platforms/facebook/platform.py
Facebook.self_check
async def self_check(cls): """ Check that the configuration is correct - Presence of "BERNARD_BASE_URL" in the global configuration - Presence of a "WEBVIEW_SECRET_KEY" """ async for check in super().self_check(): yield check s = cls.settings() ...
python
async def self_check(cls): """ Check that the configuration is correct - Presence of "BERNARD_BASE_URL" in the global configuration - Presence of a "WEBVIEW_SECRET_KEY" """ async for check in super().self_check(): yield check s = cls.settings() ...
[ "async", "def", "self_check", "(", "cls", ")", ":", "async", "for", "check", "in", "super", "(", ")", ".", "self_check", "(", ")", ":", "yield", "check", "s", "=", "cls", ".", "settings", "(", ")", "if", "not", "hasattr", "(", "settings", ",", "'BE...
Check that the configuration is correct - Presence of "BERNARD_BASE_URL" in the global configuration - Presence of a "WEBVIEW_SECRET_KEY"
[ "Check", "that", "the", "configuration", "is", "correct" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L346-L373
train
Check that the configuration is correct.
BernardFW/bernard
src/bernard/platforms/facebook/platform.py
Facebook.verify_token
def verify_token(self): """ Automatically generated secure verify token """ h = sha256() h.update(self.app_access_token.encode()) return h.hexdigest()
python
def verify_token(self): """ Automatically generated secure verify token """ h = sha256() h.update(self.app_access_token.encode()) return h.hexdigest()
[ "def", "verify_token", "(", "self", ")", ":", "h", "=", "sha256", "(", ")", "h", ".", "update", "(", "self", ".", "app_access_token", ".", "encode", "(", ")", ")", "return", "h", ".", "hexdigest", "(", ")" ]
Automatically generated secure verify token
[ "Automatically", "generated", "secure", "verify", "token" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L385-L392
train
Automatically generated secure verify token
BernardFW/bernard
src/bernard/platforms/facebook/platform.py
Facebook.hook_up
def hook_up(self, router: UrlDispatcher): """ Dynamically hooks the right webhook paths """ router.add_get(self.webhook_path, self.check_hook) router.add_post(self.webhook_path, self.receive_events)
python
def hook_up(self, router: UrlDispatcher): """ Dynamically hooks the right webhook paths """ router.add_get(self.webhook_path, self.check_hook) router.add_post(self.webhook_path, self.receive_events)
[ "def", "hook_up", "(", "self", ",", "router", ":", "UrlDispatcher", ")", ":", "router", ".", "add_get", "(", "self", ".", "webhook_path", ",", "self", ".", "check_hook", ")", "router", ".", "add_post", "(", "self", ".", "webhook_path", ",", "self", ".", ...
Dynamically hooks the right webhook paths
[ "Dynamically", "hooks", "the", "right", "webhook", "paths" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L410-L416
train
Dynamically hooks the right webhook paths
BernardFW/bernard
src/bernard/platforms/facebook/platform.py
Facebook.check_hook
async def check_hook(self, request: HttpRequest): """ Called when Facebook checks the hook """ verify_token = request.query.get('hub.verify_token') if not verify_token: return json_response({ 'error': 'No verification token was provided', ...
python
async def check_hook(self, request: HttpRequest): """ Called when Facebook checks the hook """ verify_token = request.query.get('hub.verify_token') if not verify_token: return json_response({ 'error': 'No verification token was provided', ...
[ "async", "def", "check_hook", "(", "self", ",", "request", ":", "HttpRequest", ")", ":", "verify_token", "=", "request", ".", "query", ".", "get", "(", "'hub.verify_token'", ")", "if", "not", "verify_token", ":", "return", "json_response", "(", "{", "'error'...
Called when Facebook checks the hook
[ "Called", "when", "Facebook", "checks", "the", "hook" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L418-L435
train
Called when Facebook checks the hook
BernardFW/bernard
src/bernard/platforms/facebook/platform.py
Facebook.receive_events
async def receive_events(self, request: HttpRequest): """ Events received from Facebook """ body = await request.read() s = self.settings() try: content = ujson.loads(body) except ValueError: return json_response({ 'error'...
python
async def receive_events(self, request: HttpRequest): """ Events received from Facebook """ body = await request.read() s = self.settings() try: content = ujson.loads(body) except ValueError: return json_response({ 'error'...
[ "async", "def", "receive_events", "(", "self", ",", "request", ":", "HttpRequest", ")", ":", "body", "=", "await", "request", ".", "read", "(", ")", "s", "=", "self", ".", "settings", "(", ")", "try", ":", "content", "=", "ujson", ".", "loads", "(", ...
Events received from Facebook
[ "Events", "received", "from", "Facebook" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L437-L470
train
Handles events received from Facebook.
BernardFW/bernard
src/bernard/platforms/facebook/platform.py
Facebook._deferred_init
async def _deferred_init(self): """ Run those things in a sepearate tasks as they are not required for the bot to work and they take a lot of time to run. """ await self._check_subscriptions() await self._set_whitelist() await self._set_get_started() awai...
python
async def _deferred_init(self): """ Run those things in a sepearate tasks as they are not required for the bot to work and they take a lot of time to run. """ await self._check_subscriptions() await self._set_whitelist() await self._set_get_started() awai...
[ "async", "def", "_deferred_init", "(", "self", ")", ":", "await", "self", ".", "_check_subscriptions", "(", ")", "await", "self", ".", "_set_whitelist", "(", ")", "await", "self", ".", "_set_get_started", "(", ")", "await", "self", ".", "_set_greeting_text", ...
Run those things in a sepearate tasks as they are not required for the bot to work and they take a lot of time to run.
[ "Run", "those", "things", "in", "a", "sepearate", "tasks", "as", "they", "are", "not", "required", "for", "the", "bot", "to", "work", "and", "they", "take", "a", "lot", "of", "time", "to", "run", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L472-L482
train
Called by the bot when the bot is not ready to run.
BernardFW/bernard
src/bernard/platforms/facebook/platform.py
Facebook._get_messenger_profile
async def _get_messenger_profile(self, page, fields: List[Text]): """ Fetch the value of specified fields in order to avoid setting the same field twice at the same value (since Facebook engineers are not able to make menus that keep on working if set again). """ params ...
python
async def _get_messenger_profile(self, page, fields: List[Text]): """ Fetch the value of specified fields in order to avoid setting the same field twice at the same value (since Facebook engineers are not able to make menus that keep on working if set again). """ params ...
[ "async", "def", "_get_messenger_profile", "(", "self", ",", "page", ",", "fields", ":", "List", "[", "Text", "]", ")", ":", "params", "=", "{", "'access_token'", ":", "page", "[", "'page_token'", "]", ",", "'fields'", ":", "','", ".", "join", "(", "fie...
Fetch the value of specified fields in order to avoid setting the same field twice at the same value (since Facebook engineers are not able to make menus that keep on working if set again).
[ "Fetch", "the", "value", "of", "specified", "fields", "in", "order", "to", "avoid", "setting", "the", "same", "field", "twice", "at", "the", "same", "value", "(", "since", "Facebook", "engineers", "are", "not", "able", "to", "make", "menus", "that", "keep"...
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L484-L505
train
Get the value of specified fields from the messenger profile endpoint.
BernardFW/bernard
src/bernard/platforms/facebook/platform.py
Facebook._send_to_messenger_profile
async def _send_to_messenger_profile(self, page, content): """ The messenger profile API handles all meta-information about the bot, like the menu. This allows to submit data to this API endpoint. :param page: page dict from the configuration :param content: content to be sent t...
python
async def _send_to_messenger_profile(self, page, content): """ The messenger profile API handles all meta-information about the bot, like the menu. This allows to submit data to this API endpoint. :param page: page dict from the configuration :param content: content to be sent t...
[ "async", "def", "_send_to_messenger_profile", "(", "self", ",", "page", ",", "content", ")", ":", "log_name", "=", "', '", ".", "join", "(", "repr", "(", "x", ")", "for", "x", "in", "content", ".", "keys", "(", ")", ")", "page_id", "=", "page", "[", ...
The messenger profile API handles all meta-information about the bot, like the menu. This allows to submit data to this API endpoint. :param page: page dict from the configuration :param content: content to be sent to Facebook (as dict)
[ "The", "messenger", "profile", "API", "handles", "all", "meta", "-", "information", "about", "the", "bot", "like", "the", "menu", ".", "This", "allows", "to", "submit", "data", "to", "this", "API", "endpoint", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L507-L548
train
Send content to the messenger profile API.
BernardFW/bernard
src/bernard/platforms/facebook/platform.py
Facebook._set_get_started
async def _set_get_started(self): """ Set the "get started" action for all configured pages. """ page = self.settings() if 'get_started' in page: payload = page['get_started'] else: payload = {'action': 'get_started'} await self._send_to...
python
async def _set_get_started(self): """ Set the "get started" action for all configured pages. """ page = self.settings() if 'get_started' in page: payload = page['get_started'] else: payload = {'action': 'get_started'} await self._send_to...
[ "async", "def", "_set_get_started", "(", "self", ")", ":", "page", "=", "self", ".", "settings", "(", ")", "if", "'get_started'", "in", "page", ":", "payload", "=", "page", "[", "'get_started'", "]", "else", ":", "payload", "=", "{", "'action'", ":", "...
Set the "get started" action for all configured pages.
[ "Set", "the", "get", "started", "action", "for", "all", "configured", "pages", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L550-L568
train
Set the get started action for all configured pages.
BernardFW/bernard
src/bernard/platforms/facebook/platform.py
Facebook._set_greeting_text
async def _set_greeting_text(self): """ Set the greeting text of the page """ page = self.settings() if 'greeting' in page: await self._send_to_messenger_profile(page, { 'greeting': page['greeting'], }) logger.info('Greeting ...
python
async def _set_greeting_text(self): """ Set the greeting text of the page """ page = self.settings() if 'greeting' in page: await self._send_to_messenger_profile(page, { 'greeting': page['greeting'], }) logger.info('Greeting ...
[ "async", "def", "_set_greeting_text", "(", "self", ")", ":", "page", "=", "self", ".", "settings", "(", ")", "if", "'greeting'", "in", "page", ":", "await", "self", ".", "_send_to_messenger_profile", "(", "page", ",", "{", "'greeting'", ":", "page", "[", ...
Set the greeting text of the page
[ "Set", "the", "greeting", "text", "of", "the", "page" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L570-L582
train
Set the greeting text of the page.
BernardFW/bernard
src/bernard/platforms/facebook/platform.py
Facebook._set_persistent_menu
async def _set_persistent_menu(self): """ Define the persistent menu for all pages """ page = self.settings() if 'menu' in page: await self._send_to_messenger_profile(page, { 'persistent_menu': page['menu'], }) logger.info('S...
python
async def _set_persistent_menu(self): """ Define the persistent menu for all pages """ page = self.settings() if 'menu' in page: await self._send_to_messenger_profile(page, { 'persistent_menu': page['menu'], }) logger.info('S...
[ "async", "def", "_set_persistent_menu", "(", "self", ")", ":", "page", "=", "self", ".", "settings", "(", ")", "if", "'menu'", "in", "page", ":", "await", "self", ".", "_send_to_messenger_profile", "(", "page", ",", "{", "'persistent_menu'", ":", "page", "...
Define the persistent menu for all pages
[ "Define", "the", "persistent", "menu", "for", "all", "pages" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L584-L596
train
Define the persistent menu for all pages
BernardFW/bernard
src/bernard/platforms/facebook/platform.py
Facebook._set_whitelist
async def _set_whitelist(self): """ Whitelist domains for the messenger extensions """ page = self.settings() if 'whitelist' in page: await self._send_to_messenger_profile(page, { 'whitelisted_domains': page['whitelist'], }) ...
python
async def _set_whitelist(self): """ Whitelist domains for the messenger extensions """ page = self.settings() if 'whitelist' in page: await self._send_to_messenger_profile(page, { 'whitelisted_domains': page['whitelist'], }) ...
[ "async", "def", "_set_whitelist", "(", "self", ")", ":", "page", "=", "self", ".", "settings", "(", ")", "if", "'whitelist'", "in", "page", ":", "await", "self", ".", "_send_to_messenger_profile", "(", "page", ",", "{", "'whitelisted_domains'", ":", "page", ...
Whitelist domains for the messenger extensions
[ "Whitelist", "domains", "for", "the", "messenger", "extensions" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L598-L612
train
Set the whitelisted domains for the messenger extensions
BernardFW/bernard
src/bernard/platforms/facebook/platform.py
Facebook._get_subscriptions_endpoint
def _get_subscriptions_endpoint(self): """ Generates the URL and tokens for the subscriptions endpoint """ s = self.settings() params = { 'access_token': self.app_access_token, } return ( GRAPH_ENDPOINT.format(f'{s["app_id"]}/subscriptio...
python
def _get_subscriptions_endpoint(self): """ Generates the URL and tokens for the subscriptions endpoint """ s = self.settings() params = { 'access_token': self.app_access_token, } return ( GRAPH_ENDPOINT.format(f'{s["app_id"]}/subscriptio...
[ "def", "_get_subscriptions_endpoint", "(", "self", ")", ":", "s", "=", "self", ".", "settings", "(", ")", "params", "=", "{", "'access_token'", ":", "self", ".", "app_access_token", ",", "}", "return", "(", "GRAPH_ENDPOINT", ".", "format", "(", "f'{s[\"app_i...
Generates the URL and tokens for the subscriptions endpoint
[ "Generates", "the", "URL", "and", "tokens", "for", "the", "subscriptions", "endpoint" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L614-L628
train
Generates the URL and tokens for the subscriptions endpoint
BernardFW/bernard
src/bernard/platforms/facebook/platform.py
Facebook._get_subscriptions
async def _get_subscriptions(self) -> Tuple[Set[Text], Text]: """ List the subscriptions currently active """ url, params = self._get_subscriptions_endpoint() get = self.session.get(url, params=params) async with get as r: await self._handle_fb_response(r) ...
python
async def _get_subscriptions(self) -> Tuple[Set[Text], Text]: """ List the subscriptions currently active """ url, params = self._get_subscriptions_endpoint() get = self.session.get(url, params=params) async with get as r: await self._handle_fb_response(r) ...
[ "async", "def", "_get_subscriptions", "(", "self", ")", "->", "Tuple", "[", "Set", "[", "Text", "]", ",", "Text", "]", ":", "url", ",", "params", "=", "self", ".", "_get_subscriptions_endpoint", "(", ")", "get", "=", "self", ".", "session", ".", "get",...
List the subscriptions currently active
[ "List", "the", "subscriptions", "currently", "active" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L630-L650
train
List the currently active subscriptions
BernardFW/bernard
src/bernard/platforms/facebook/platform.py
Facebook._set_subscriptions
async def _set_subscriptions(self, subscriptions): """ Set the subscriptions to a specific list of values """ url, params = self._get_subscriptions_endpoint() data = { 'object': 'page', 'callback_url': self.webhook_url, 'fields': ', '.join(su...
python
async def _set_subscriptions(self, subscriptions): """ Set the subscriptions to a specific list of values """ url, params = self._get_subscriptions_endpoint() data = { 'object': 'page', 'callback_url': self.webhook_url, 'fields': ', '.join(su...
[ "async", "def", "_set_subscriptions", "(", "self", ",", "subscriptions", ")", ":", "url", ",", "params", "=", "self", ".", "_get_subscriptions_endpoint", "(", ")", "data", "=", "{", "'object'", ":", "'page'", ",", "'callback_url'", ":", "self", ".", "webhook...
Set the subscriptions to a specific list of values
[ "Set", "the", "subscriptions", "to", "a", "specific", "list", "of", "values" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L652-L679
train
Set the subscriptions to a specific list of values
BernardFW/bernard
src/bernard/platforms/facebook/platform.py
Facebook._check_subscriptions
async def _check_subscriptions(self): """ Checks that all subscriptions are subscribed """ subscribed, url = await self._get_subscriptions() expect = set(settings.FACEBOOK_SUBSCRIPTIONS) if (expect - subscribed) or url != self.webhook_url: await self._set_su...
python
async def _check_subscriptions(self): """ Checks that all subscriptions are subscribed """ subscribed, url = await self._get_subscriptions() expect = set(settings.FACEBOOK_SUBSCRIPTIONS) if (expect - subscribed) or url != self.webhook_url: await self._set_su...
[ "async", "def", "_check_subscriptions", "(", "self", ")", ":", "subscribed", ",", "url", "=", "await", "self", ".", "_get_subscriptions", "(", ")", "expect", "=", "set", "(", "settings", ".", "FACEBOOK_SUBSCRIPTIONS", ")", "if", "(", "expect", "-", "subscrib...
Checks that all subscriptions are subscribed
[ "Checks", "that", "all", "subscriptions", "are", "subscribed" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L681-L693
train
Checks that all subscriptions are subscribed and update the webhook url if needed
BernardFW/bernard
src/bernard/platforms/facebook/platform.py
Facebook.handle_event
async def handle_event(self, event: FacebookMessage): """ Handle an incoming message from Facebook. """ responder = FacebookResponder(self) await self._notify(event, responder)
python
async def handle_event(self, event: FacebookMessage): """ Handle an incoming message from Facebook. """ responder = FacebookResponder(self) await self._notify(event, responder)
[ "async", "def", "handle_event", "(", "self", ",", "event", ":", "FacebookMessage", ")", ":", "responder", "=", "FacebookResponder", "(", "self", ")", "await", "self", ".", "_notify", "(", "event", ",", "responder", ")" ]
Handle an incoming message from Facebook.
[ "Handle", "an", "incoming", "message", "from", "Facebook", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L695-L700
train
Handle an incoming message from Facebook.
BernardFW/bernard
src/bernard/platforms/facebook/platform.py
Facebook._access_token
def _access_token(self, request: Request=None, page_id: Text=''): """ Guess the access token for that specific request. """ if not page_id: msg = request.message # type: FacebookMessage page_id = msg.get_page_id() page = self.settings() if page...
python
def _access_token(self, request: Request=None, page_id: Text=''): """ Guess the access token for that specific request. """ if not page_id: msg = request.message # type: FacebookMessage page_id = msg.get_page_id() page = self.settings() if page...
[ "def", "_access_token", "(", "self", ",", "request", ":", "Request", "=", "None", ",", "page_id", ":", "Text", "=", "''", ")", ":", "if", "not", "page_id", ":", "msg", "=", "request", ".", "message", "# type: FacebookMessage", "page_id", "=", "msg", ".",...
Guess the access token for that specific request.
[ "Guess", "the", "access", "token", "for", "that", "specific", "request", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L702-L718
train
Guess the access token for a specific request.
BernardFW/bernard
src/bernard/platforms/facebook/platform.py
Facebook._make_qr
async def _make_qr(self, qr: QuickRepliesList.BaseOption, request: Request): """ Generate a single quick reply's content. """ if isinstance(qr, QuickRepliesList.TextOption): return { 'content_type': 'text', ...
python
async def _make_qr(self, qr: QuickRepliesList.BaseOption, request: Request): """ Generate a single quick reply's content. """ if isinstance(qr, QuickRepliesList.TextOption): return { 'content_type': 'text', ...
[ "async", "def", "_make_qr", "(", "self", ",", "qr", ":", "QuickRepliesList", ".", "BaseOption", ",", "request", ":", "Request", ")", ":", "if", "isinstance", "(", "qr", ",", "QuickRepliesList", ".", "TextOption", ")", ":", "return", "{", "'content_type'", ...
Generate a single quick reply's content.
[ "Generate", "a", "single", "quick", "reply", "s", "content", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L720-L736
train
Generate a single quick reply s content.
BernardFW/bernard
src/bernard/platforms/facebook/platform.py
Facebook._send_text
async def _send_text(self, request: Request, stack: Stack): """ Send text layers to the user. Each layer will go in its own bubble. Also, Facebook limits messages to 320 chars, so if any message is longer than that it will be split into as many messages as needed to be accepted ...
python
async def _send_text(self, request: Request, stack: Stack): """ Send text layers to the user. Each layer will go in its own bubble. Also, Facebook limits messages to 320 chars, so if any message is longer than that it will be split into as many messages as needed to be accepted ...
[ "async", "def", "_send_text", "(", "self", ",", "request", ":", "Request", ",", "stack", ":", "Stack", ")", ":", "parts", "=", "[", "]", "for", "layer", "in", "stack", ".", "layers", ":", "if", "isinstance", "(", "layer", ",", "lyr", ".", "MultiText"...
Send text layers to the user. Each layer will go in its own bubble. Also, Facebook limits messages to 320 chars, so if any message is longer than that it will be split into as many messages as needed to be accepted by Facebook.
[ "Send", "text", "layers", "to", "the", "user", ".", "Each", "layer", "will", "go", "in", "its", "own", "bubble", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L749-L783
train
Send text layers to the user.
BernardFW/bernard
src/bernard/platforms/facebook/platform.py
Facebook._send_generic_template
async def _send_generic_template(self, request: Request, stack: Stack): """ Generates and send a generic template. """ gt = stack.get_layer(GenericTemplate) payload = await gt.serialize(request) msg = { 'attachment': { 'type': 'template', ...
python
async def _send_generic_template(self, request: Request, stack: Stack): """ Generates and send a generic template. """ gt = stack.get_layer(GenericTemplate) payload = await gt.serialize(request) msg = { 'attachment': { 'type': 'template', ...
[ "async", "def", "_send_generic_template", "(", "self", ",", "request", ":", "Request", ",", "stack", ":", "Stack", ")", ":", "gt", "=", "stack", ".", "get_layer", "(", "GenericTemplate", ")", "payload", "=", "await", "gt", ".", "serialize", "(", "request",...
Generates and send a generic template.
[ "Generates", "and", "send", "a", "generic", "template", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L785-L801
train
Generates and sends a generic template.
BernardFW/bernard
src/bernard/platforms/facebook/platform.py
Facebook._send_button_template
async def _send_button_template(self, request: Request, stack: Stack): """ Generates and send a button template. """ gt = stack.get_layer(ButtonTemplate) payload = { 'template_type': 'button', 'text': await render(gt.text, request), 'buttons'...
python
async def _send_button_template(self, request: Request, stack: Stack): """ Generates and send a button template. """ gt = stack.get_layer(ButtonTemplate) payload = { 'template_type': 'button', 'text': await render(gt.text, request), 'buttons'...
[ "async", "def", "_send_button_template", "(", "self", ",", "request", ":", "Request", ",", "stack", ":", "Stack", ")", ":", "gt", "=", "stack", ".", "get_layer", "(", "ButtonTemplate", ")", "payload", "=", "{", "'template_type'", ":", "'button'", ",", "'te...
Generates and send a button template.
[ "Generates", "and", "send", "a", "button", "template", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L803-L824
train
Generates and sends a button template.
BernardFW/bernard
src/bernard/platforms/facebook/platform.py
Facebook._send_typing
async def _send_typing(self, request: Request, stack: Stack): """ Send to Facebook typing indications """ active = stack.get_layer(lyr.Typing).active msg = ujson.dumps({ 'recipient': { 'id': request.conversation.fbid, }, 'send...
python
async def _send_typing(self, request: Request, stack: Stack): """ Send to Facebook typing indications """ active = stack.get_layer(lyr.Typing).active msg = ujson.dumps({ 'recipient': { 'id': request.conversation.fbid, }, 'send...
[ "async", "def", "_send_typing", "(", "self", ",", "request", ":", "Request", ",", "stack", ":", "Stack", ")", ":", "active", "=", "stack", ".", "get_layer", "(", "lyr", ".", "Typing", ")", ".", "active", "msg", "=", "ujson", ".", "dumps", "(", "{", ...
Send to Facebook typing indications
[ "Send", "to", "Facebook", "typing", "indications" ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L858-L890
train
Send to Facebook typing indications
BernardFW/bernard
src/bernard/platforms/facebook/platform.py
Facebook._handle_fb_response
async def _handle_fb_response(self, response: aiohttp.ClientResponse): """ Check that Facebook was OK with the API call we just made and raise an exception if it failed. """ ok = response.status == 200 if not ok: # noinspection PyBroadException t...
python
async def _handle_fb_response(self, response: aiohttp.ClientResponse): """ Check that Facebook was OK with the API call we just made and raise an exception if it failed. """ ok = response.status == 200 if not ok: # noinspection PyBroadException t...
[ "async", "def", "_handle_fb_response", "(", "self", ",", "response", ":", "aiohttp", ".", "ClientResponse", ")", ":", "ok", "=", "response", ".", "status", "==", "200", "if", "not", "ok", ":", "# noinspection PyBroadException", "try", ":", "error", "=", "(",...
Check that Facebook was OK with the API call we just made and raise an exception if it failed.
[ "Check", "that", "Facebook", "was", "OK", "with", "the", "API", "call", "we", "just", "made", "and", "raise", "an", "exception", "if", "it", "failed", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L892-L908
train
Check if Facebook was OK and raise an exception if it failed.
BernardFW/bernard
src/bernard/platforms/facebook/platform.py
Facebook._send
async def _send(self, request: Request, content: Dict[Text, Any], stack: Stack): """ Actually proceed to sending the message to the Facebook API. """ msg = { 'recipient': { 'id': request.conversation...
python
async def _send(self, request: Request, content: Dict[Text, Any], stack: Stack): """ Actually proceed to sending the message to the Facebook API. """ msg = { 'recipient': { 'id': request.conversation...
[ "async", "def", "_send", "(", "self", ",", "request", ":", "Request", ",", "content", ":", "Dict", "[", "Text", ",", "Any", "]", ",", "stack", ":", "Stack", ")", ":", "msg", "=", "{", "'recipient'", ":", "{", "'id'", ":", "request", ".", "conversat...
Actually proceed to sending the message to the Facebook API.
[ "Actually", "proceed", "to", "sending", "the", "message", "to", "the", "Facebook", "API", "." ]
9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/facebook/platform.py#L910-L951
train
Send the message to Facebook API.