repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
mixmastamyk/console
console/detection.py
parse_vtrgb
def parse_vtrgb(path='/etc/vtrgb'): ''' Parse the color table for the Linux console. ''' palette = () table = [] try: with open(path) as infile: for i, line in enumerate(infile): row = tuple(int(val) for val in line.split(',')) table.append(row) ...
python
def parse_vtrgb(path='/etc/vtrgb'): ''' Parse the color table for the Linux console. ''' palette = () table = [] try: with open(path) as infile: for i, line in enumerate(infile): row = tuple(int(val) for val in line.split(',')) table.append(row) ...
[ "def", "parse_vtrgb", "(", "path", "=", "'/etc/vtrgb'", ")", ":", "palette", "=", "(", ")", "table", "=", "[", "]", "try", ":", "with", "open", "(", "path", ")", "as", "infile", ":", "for", "i", ",", "line", "in", "enumerate", "(", "infile", ")", ...
Parse the color table for the Linux console.
[ "Parse", "the", "color", "table", "for", "the", "Linux", "console", "." ]
afe6c95d5a7b83d85376f450454e3769e4a5c3d0
https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/detection.py#L378-L395
train
64,700
mixmastamyk/console
console/detection.py
_read_until
def _read_until(infile=sys.stdin, maxchars=20, end=RS): ''' Read a terminal response of up to a few characters from stdin. ''' chars = [] read = infile.read if not isinstance(end, tuple): end = (end,) # count down, stopping at 0 while maxchars: char = read(1) if char in...
python
def _read_until(infile=sys.stdin, maxchars=20, end=RS): ''' Read a terminal response of up to a few characters from stdin. ''' chars = [] read = infile.read if not isinstance(end, tuple): end = (end,) # count down, stopping at 0 while maxchars: char = read(1) if char in...
[ "def", "_read_until", "(", "infile", "=", "sys", ".", "stdin", ",", "maxchars", "=", "20", ",", "end", "=", "RS", ")", ":", "chars", "=", "[", "]", "read", "=", "infile", ".", "read", "if", "not", "isinstance", "(", "end", ",", "tuple", ")", ":",...
Read a terminal response of up to a few characters from stdin.
[ "Read", "a", "terminal", "response", "of", "up", "to", "a", "few", "characters", "from", "stdin", "." ]
afe6c95d5a7b83d85376f450454e3769e4a5c3d0
https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/detection.py#L409-L424
train
64,701
mixmastamyk/console
console/detection.py
get_color
def get_color(name, number=None): ''' Query the default terminal, for colors, etc. Direct queries supported on xterm, iTerm, perhaps others. Arguments: str: name, one of ('foreground', 'fg', 'background', 'bg', or 'index') # index grabs a palette ind...
python
def get_color(name, number=None): ''' Query the default terminal, for colors, etc. Direct queries supported on xterm, iTerm, perhaps others. Arguments: str: name, one of ('foreground', 'fg', 'background', 'bg', or 'index') # index grabs a palette ind...
[ "def", "get_color", "(", "name", ",", "number", "=", "None", ")", ":", "colors", "=", "(", ")", "if", "is_a_tty", "(", ")", "and", "not", "env", ".", "SSH_CLIENT", ":", "if", "not", "'index'", "in", "_color_code_map", ":", "_color_code_map", "[", "'ind...
Query the default terminal, for colors, etc. Direct queries supported on xterm, iTerm, perhaps others. Arguments: str: name, one of ('foreground', 'fg', 'background', 'bg', or 'index') # index grabs a palette index int: or a "dynamic color n...
[ "Query", "the", "default", "terminal", "for", "colors", "etc", "." ]
afe6c95d5a7b83d85376f450454e3769e4a5c3d0
https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/detection.py#L452-L525
train
64,702
mixmastamyk/console
console/detection.py
get_position
def get_position(fallback=CURSOR_POS_FALLBACK): ''' Return the current column number of the terminal cursor. Used to figure out if we need to print an extra newline. Returns: tuple(int): (x, y), (,) - empty, if an error occurred. TODO: needs non-ansi mode for Windows N...
python
def get_position(fallback=CURSOR_POS_FALLBACK): ''' Return the current column number of the terminal cursor. Used to figure out if we need to print an extra newline. Returns: tuple(int): (x, y), (,) - empty, if an error occurred. TODO: needs non-ansi mode for Windows N...
[ "def", "get_position", "(", "fallback", "=", "CURSOR_POS_FALLBACK", ")", ":", "values", "=", "fallback", "if", "is_a_tty", "(", ")", ":", "import", "tty", ",", "termios", "try", ":", "with", "TermStack", "(", ")", "as", "fd", ":", "tty", ".", "setcbreak"...
Return the current column number of the terminal cursor. Used to figure out if we need to print an extra newline. Returns: tuple(int): (x, y), (,) - empty, if an error occurred. TODO: needs non-ansi mode for Windows Note: Checks is_a_tty() first, since function...
[ "Return", "the", "current", "column", "number", "of", "the", "terminal", "cursor", ".", "Used", "to", "figure", "out", "if", "we", "need", "to", "print", "an", "extra", "newline", "." ]
afe6c95d5a7b83d85376f450454e3769e4a5c3d0
https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/detection.py#L528-L559
train
64,703
mixmastamyk/console
console/detection.py
get_theme
def get_theme(): ''' Checks system for theme information. First checks for the environment variable COLORFGBG. Next, queries terminal, supported on Windows and xterm, perhaps others. See notes on get_color(). Returns: str, None: 'dark', 'light', None if no information. ...
python
def get_theme(): ''' Checks system for theme information. First checks for the environment variable COLORFGBG. Next, queries terminal, supported on Windows and xterm, perhaps others. See notes on get_color(). Returns: str, None: 'dark', 'light', None if no information. ...
[ "def", "get_theme", "(", ")", ":", "theme", "=", "None", "log", ".", "debug", "(", "'COLORFGBG: %s'", ",", "env", ".", "COLORFGBG", ")", "if", "env", ".", "COLORFGBG", ":", "FG", ",", "_", ",", "BG", "=", "env", ".", "COLORFGBG", ".", "partition", ...
Checks system for theme information. First checks for the environment variable COLORFGBG. Next, queries terminal, supported on Windows and xterm, perhaps others. See notes on get_color(). Returns: str, None: 'dark', 'light', None if no information.
[ "Checks", "system", "for", "theme", "information", "." ]
afe6c95d5a7b83d85376f450454e3769e4a5c3d0
https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/detection.py#L631-L665
train
64,704
justanr/Flask-Transfer
examples/allotr/allotr/transfer.py
really_bad_du
def really_bad_du(path): "Don't actually use this, it's just an example." return sum([os.path.getsize(fp) for fp in list_files(path)])
python
def really_bad_du(path): "Don't actually use this, it's just an example." return sum([os.path.getsize(fp) for fp in list_files(path)])
[ "def", "really_bad_du", "(", "path", ")", ":", "return", "sum", "(", "[", "os", ".", "path", ".", "getsize", "(", "fp", ")", "for", "fp", "in", "list_files", "(", "path", ")", "]", ")" ]
Don't actually use this, it's just an example.
[ "Don", "t", "actually", "use", "this", "it", "s", "just", "an", "example", "." ]
075ba9edb8c8d0ea47619cc763394bbb717c2ead
https://github.com/justanr/Flask-Transfer/blob/075ba9edb8c8d0ea47619cc763394bbb717c2ead/examples/allotr/allotr/transfer.py#L18-L20
train
64,705
justanr/Flask-Transfer
examples/allotr/allotr/transfer.py
check_disk_usage
def check_disk_usage(filehandle, meta): """Checks the upload directory to see if the uploaded file would exceed the total disk allotment. Meant as a quick and dirty example. """ # limit it at twenty kilobytes if no default is provided MAX_DISK_USAGE = current_app.config.get('MAX_DISK_USAGE', 20 * 10...
python
def check_disk_usage(filehandle, meta): """Checks the upload directory to see if the uploaded file would exceed the total disk allotment. Meant as a quick and dirty example. """ # limit it at twenty kilobytes if no default is provided MAX_DISK_USAGE = current_app.config.get('MAX_DISK_USAGE', 20 * 10...
[ "def", "check_disk_usage", "(", "filehandle", ",", "meta", ")", ":", "# limit it at twenty kilobytes if no default is provided", "MAX_DISK_USAGE", "=", "current_app", ".", "config", ".", "get", "(", "'MAX_DISK_USAGE'", ",", "20", "*", "1024", ")", "CURRENT_USAGE", "="...
Checks the upload directory to see if the uploaded file would exceed the total disk allotment. Meant as a quick and dirty example.
[ "Checks", "the", "upload", "directory", "to", "see", "if", "the", "uploaded", "file", "would", "exceed", "the", "total", "disk", "allotment", ".", "Meant", "as", "a", "quick", "and", "dirty", "example", "." ]
075ba9edb8c8d0ea47619cc763394bbb717c2ead
https://github.com/justanr/Flask-Transfer/blob/075ba9edb8c8d0ea47619cc763394bbb717c2ead/examples/allotr/allotr/transfer.py#L24-L37
train
64,706
mixmastamyk/console
setup.py
get_version
def get_version(filename, version='1.00'): ''' Read version as text to avoid machinations at import time. ''' with open(filename) as infile: for line in infile: if line.startswith('__version__'): try: version = line.split("'")[1] except Ind...
python
def get_version(filename, version='1.00'): ''' Read version as text to avoid machinations at import time. ''' with open(filename) as infile: for line in infile: if line.startswith('__version__'): try: version = line.split("'")[1] except Ind...
[ "def", "get_version", "(", "filename", ",", "version", "=", "'1.00'", ")", ":", "with", "open", "(", "filename", ")", "as", "infile", ":", "for", "line", "in", "infile", ":", "if", "line", ".", "startswith", "(", "'__version__'", ")", ":", "try", ":", ...
Read version as text to avoid machinations at import time.
[ "Read", "version", "as", "text", "to", "avoid", "machinations", "at", "import", "time", "." ]
afe6c95d5a7b83d85376f450454e3769e4a5c3d0
https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/setup.py#L25-L35
train
64,707
mixmastamyk/console
console/proximity.py
find_nearest_color_index
def find_nearest_color_index(r, g, b, color_table=None, method='euclid'): ''' Given three integers representing R, G, and B, return the nearest color index. Arguments: r: int - of range 0…255 g: int - of range 0…255 b: int - of range 0…255 Retur...
python
def find_nearest_color_index(r, g, b, color_table=None, method='euclid'): ''' Given three integers representing R, G, and B, return the nearest color index. Arguments: r: int - of range 0…255 g: int - of range 0…255 b: int - of range 0…255 Retur...
[ "def", "find_nearest_color_index", "(", "r", ",", "g", ",", "b", ",", "color_table", "=", "None", ",", "method", "=", "'euclid'", ")", ":", "shortest_distance", "=", "257", "*", "257", "*", "3", "# max eucl. distance from #000000 to #ffffff", "index", "=", "0"...
Given three integers representing R, G, and B, return the nearest color index. Arguments: r: int - of range 0…255 g: int - of range 0…255 b: int - of range 0…255 Returns: int, None: index, or None on error.
[ "Given", "three", "integers", "representing", "R", "G", "and", "B", "return", "the", "nearest", "color", "index", "." ]
afe6c95d5a7b83d85376f450454e3769e4a5c3d0
https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/proximity.py#L77-L107
train
64,708
mixmastamyk/console
console/proximity.py
find_nearest_color_hexstr
def find_nearest_color_hexstr(hexdigits, color_table=None, method='euclid'): ''' Given a three or six-character hex digit string, return the nearest color index. Arguments: hexdigits: a three/6 digit hex string, e.g. 'b0b', '123456' Returns: int, None: index, or No...
python
def find_nearest_color_hexstr(hexdigits, color_table=None, method='euclid'): ''' Given a three or six-character hex digit string, return the nearest color index. Arguments: hexdigits: a three/6 digit hex string, e.g. 'b0b', '123456' Returns: int, None: index, or No...
[ "def", "find_nearest_color_hexstr", "(", "hexdigits", ",", "color_table", "=", "None", ",", "method", "=", "'euclid'", ")", ":", "triplet", "=", "[", "]", "try", ":", "if", "len", "(", "hexdigits", ")", "==", "3", ":", "for", "digit", "in", "hexdigits", ...
Given a three or six-character hex digit string, return the nearest color index. Arguments: hexdigits: a three/6 digit hex string, e.g. 'b0b', '123456' Returns: int, None: index, or None on error.
[ "Given", "a", "three", "or", "six", "-", "character", "hex", "digit", "string", "return", "the", "nearest", "color", "index", "." ]
afe6c95d5a7b83d85376f450454e3769e4a5c3d0
https://github.com/mixmastamyk/console/blob/afe6c95d5a7b83d85376f450454e3769e4a5c3d0/console/proximity.py#L110-L135
train
64,709
konstantint/pyliftover
pyliftover/intervaltree.py
IntervalTree.add_interval
def add_interval(self, start, end, data=None): ''' Inserts an interval to the tree. Note that when inserting we do not maintain appropriate sorting of the "mid" data structure. This should be done after all intervals are inserted. ''' # Ignore intervals of 0 or negative ...
python
def add_interval(self, start, end, data=None): ''' Inserts an interval to the tree. Note that when inserting we do not maintain appropriate sorting of the "mid" data structure. This should be done after all intervals are inserted. ''' # Ignore intervals of 0 or negative ...
[ "def", "add_interval", "(", "self", ",", "start", ",", "end", ",", "data", "=", "None", ")", ":", "# Ignore intervals of 0 or negative length", "if", "(", "end", "-", "start", ")", "<=", "0", ":", "return", "if", "self", ".", "single_interval", "is", "None...
Inserts an interval to the tree. Note that when inserting we do not maintain appropriate sorting of the "mid" data structure. This should be done after all intervals are inserted.
[ "Inserts", "an", "interval", "to", "the", "tree", ".", "Note", "that", "when", "inserting", "we", "do", "not", "maintain", "appropriate", "sorting", "of", "the", "mid", "data", "structure", ".", "This", "should", "be", "done", "after", "all", "intervals", ...
5164eed9ae678ad0ddc164df8c2c5767e6a4b39f
https://github.com/konstantint/pyliftover/blob/5164eed9ae678ad0ddc164df8c2c5767e6a4b39f/pyliftover/intervaltree.py#L55-L74
train
64,710
konstantint/pyliftover
pyliftover/intervaltree.py
IntervalTree._query
def _query(self, x, result): ''' Same as self.query, but uses a provided list to accumulate results into. ''' if self.single_interval is None: # Empty return elif self.single_interval != 0: # Single interval, just check whether x is in it if self.single_i...
python
def _query(self, x, result): ''' Same as self.query, but uses a provided list to accumulate results into. ''' if self.single_interval is None: # Empty return elif self.single_interval != 0: # Single interval, just check whether x is in it if self.single_i...
[ "def", "_query", "(", "self", ",", "x", ",", "result", ")", ":", "if", "self", ".", "single_interval", "is", "None", ":", "# Empty", "return", "elif", "self", ".", "single_interval", "!=", "0", ":", "# Single interval, just check whether x is in it", "if", "se...
Same as self.query, but uses a provided list to accumulate results into.
[ "Same", "as", "self", ".", "query", "but", "uses", "a", "provided", "list", "to", "accumulate", "results", "into", "." ]
5164eed9ae678ad0ddc164df8c2c5767e6a4b39f
https://github.com/konstantint/pyliftover/blob/5164eed9ae678ad0ddc164df8c2c5767e6a4b39f/pyliftover/intervaltree.py#L111-L135
train
64,711
Oneiroe/PySimpleAutomata
PySimpleAutomata/DFA.py
dfa_complementation
def dfa_complementation(dfa: dict) -> dict: """ Returns a DFA that accepts any word but he ones accepted by the input DFA. Let A be a completed DFA, :math:`Ā = (Σ, S, s_0 , ρ, S − F )` is the DFA that runs A but accepts whatever word A does not. :param dict dfa: input DFA. :return: *(dict)* re...
python
def dfa_complementation(dfa: dict) -> dict: """ Returns a DFA that accepts any word but he ones accepted by the input DFA. Let A be a completed DFA, :math:`Ā = (Σ, S, s_0 , ρ, S − F )` is the DFA that runs A but accepts whatever word A does not. :param dict dfa: input DFA. :return: *(dict)* re...
[ "def", "dfa_complementation", "(", "dfa", ":", "dict", ")", "->", "dict", ":", "dfa_complement", "=", "dfa_completion", "(", "deepcopy", "(", "dfa", ")", ")", "dfa_complement", "[", "'accepting_states'", "]", "=", "dfa_complement", "[", "'states'", "]", ".", ...
Returns a DFA that accepts any word but he ones accepted by the input DFA. Let A be a completed DFA, :math:`Ā = (Σ, S, s_0 , ρ, S − F )` is the DFA that runs A but accepts whatever word A does not. :param dict dfa: input DFA. :return: *(dict)* representing the complement of the input DFA.
[ "Returns", "a", "DFA", "that", "accepts", "any", "word", "but", "he", "ones", "accepted", "by", "the", "input", "DFA", "." ]
0f9f2705fd8ddd5d8118bc31552a640f5d00c359
https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/DFA.py#L89-L102
train
64,712
Oneiroe/PySimpleAutomata
PySimpleAutomata/DFA.py
dfa_intersection
def dfa_intersection(dfa_1: dict, dfa_2: dict) -> dict: """ Returns a DFA accepting the intersection of the DFAs in input. Let :math:`A_1 = (Σ, S_1 , s_{01} , ρ_1 , F_1 )` and :math:`A_2 = (Σ, S_2 , s_{02} , ρ_2 , F_2 )` be two DFAs. Then there is a DFA :math:`A_∧` that runs simultaneously both ...
python
def dfa_intersection(dfa_1: dict, dfa_2: dict) -> dict: """ Returns a DFA accepting the intersection of the DFAs in input. Let :math:`A_1 = (Σ, S_1 , s_{01} , ρ_1 , F_1 )` and :math:`A_2 = (Σ, S_2 , s_{02} , ρ_2 , F_2 )` be two DFAs. Then there is a DFA :math:`A_∧` that runs simultaneously both ...
[ "def", "dfa_intersection", "(", "dfa_1", ":", "dict", ",", "dfa_2", ":", "dict", ")", "->", "dict", ":", "intersection", "=", "{", "'alphabet'", ":", "dfa_1", "[", "'alphabet'", "]", ".", "intersection", "(", "dfa_2", "[", "'alphabet'", "]", ")", ",", ...
Returns a DFA accepting the intersection of the DFAs in input. Let :math:`A_1 = (Σ, S_1 , s_{01} , ρ_1 , F_1 )` and :math:`A_2 = (Σ, S_2 , s_{02} , ρ_2 , F_2 )` be two DFAs. Then there is a DFA :math:`A_∧` that runs simultaneously both :math:`A_1` and :math:`A_2` on the input word and accepts w...
[ "Returns", "a", "DFA", "accepting", "the", "intersection", "of", "the", "DFAs", "in", "input", "." ]
0f9f2705fd8ddd5d8118bc31552a640f5d00c359
https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/DFA.py#L105-L157
train
64,713
Oneiroe/PySimpleAutomata
PySimpleAutomata/DFA.py
dfa_union
def dfa_union(dfa_1: dict, dfa_2: dict) -> dict: """ Returns a DFA accepting the union of the input DFAs. Let :math:`A_1 = (Σ, S_1 , s_{01} , ρ_1 , F_1 )` and :math:`A_2 = (Σ, S_2 , s_{02} , ρ_2 , F_2 )` be two completed DFAs. Then there is a DFA :math:`A_∨` that runs simultaneously both :math:...
python
def dfa_union(dfa_1: dict, dfa_2: dict) -> dict: """ Returns a DFA accepting the union of the input DFAs. Let :math:`A_1 = (Σ, S_1 , s_{01} , ρ_1 , F_1 )` and :math:`A_2 = (Σ, S_2 , s_{02} , ρ_2 , F_2 )` be two completed DFAs. Then there is a DFA :math:`A_∨` that runs simultaneously both :math:...
[ "def", "dfa_union", "(", "dfa_1", ":", "dict", ",", "dfa_2", ":", "dict", ")", "->", "dict", ":", "dfa_1", "=", "deepcopy", "(", "dfa_1", ")", "dfa_2", "=", "deepcopy", "(", "dfa_2", ")", "dfa_1", "[", "'alphabet'", "]", "=", "dfa_2", "[", "'alphabet...
Returns a DFA accepting the union of the input DFAs. Let :math:`A_1 = (Σ, S_1 , s_{01} , ρ_1 , F_1 )` and :math:`A_2 = (Σ, S_2 , s_{02} , ρ_2 , F_2 )` be two completed DFAs. Then there is a DFA :math:`A_∨` that runs simultaneously both :math:`A_1` and :math:`A_2` on the input word and accepts w...
[ "Returns", "a", "DFA", "accepting", "the", "union", "of", "the", "input", "DFAs", "." ]
0f9f2705fd8ddd5d8118bc31552a640f5d00c359
https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/DFA.py#L160-L218
train
64,714
Oneiroe/PySimpleAutomata
PySimpleAutomata/DFA.py
dfa_minimization
def dfa_minimization(dfa: dict) -> dict: """ Returns the minimization of the DFA in input through a greatest fix-point method. Given a completed DFA :math:`A = (Σ, S, s_0 , ρ, F )` there exists a single minimal DFA :math:`A_m` which is equivalent to A, i.e. reads the same language :math:`L(A) =...
python
def dfa_minimization(dfa: dict) -> dict: """ Returns the minimization of the DFA in input through a greatest fix-point method. Given a completed DFA :math:`A = (Σ, S, s_0 , ρ, F )` there exists a single minimal DFA :math:`A_m` which is equivalent to A, i.e. reads the same language :math:`L(A) =...
[ "def", "dfa_minimization", "(", "dfa", ":", "dict", ")", "->", "dict", ":", "dfa", "=", "dfa_completion", "(", "deepcopy", "(", "dfa", ")", ")", "################################################################", "### Greatest-fixpoint", "z_current", "=", "set", "(", ...
Returns the minimization of the DFA in input through a greatest fix-point method. Given a completed DFA :math:`A = (Σ, S, s_0 , ρ, F )` there exists a single minimal DFA :math:`A_m` which is equivalent to A, i.e. reads the same language :math:`L(A) = L(A_m)` and with a minimal number of states. ...
[ "Returns", "the", "minimization", "of", "the", "DFA", "in", "input", "through", "a", "greatest", "fix", "-", "point", "method", "." ]
0f9f2705fd8ddd5d8118bc31552a640f5d00c359
https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/DFA.py#L221-L326
train
64,715
Oneiroe/PySimpleAutomata
PySimpleAutomata/DFA.py
dfa_reachable
def dfa_reachable(dfa: dict) -> dict: """ Side effects on input! Removes unreachable states from a DFA and returns the pruned DFA. It is possible to remove from a DFA A all unreachable states from the initial state without altering the language. The reachable DFA :math:`A_R` corresponding to A is d...
python
def dfa_reachable(dfa: dict) -> dict: """ Side effects on input! Removes unreachable states from a DFA and returns the pruned DFA. It is possible to remove from a DFA A all unreachable states from the initial state without altering the language. The reachable DFA :math:`A_R` corresponding to A is d...
[ "def", "dfa_reachable", "(", "dfa", ":", "dict", ")", "->", "dict", ":", "reachable_states", "=", "set", "(", ")", "# set of reachable states from root", "boundary", "=", "set", "(", ")", "reachable_states", ".", "add", "(", "dfa", "[", "'initial_state'", "]",...
Side effects on input! Removes unreachable states from a DFA and returns the pruned DFA. It is possible to remove from a DFA A all unreachable states from the initial state without altering the language. The reachable DFA :math:`A_R` corresponding to A is defined as: :math:`A_R = (Σ, S_R , s_0 , ρ...
[ "Side", "effects", "on", "input!", "Removes", "unreachable", "states", "from", "a", "DFA", "and", "returns", "the", "pruned", "DFA", "." ]
0f9f2705fd8ddd5d8118bc31552a640f5d00c359
https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/DFA.py#L330-L373
train
64,716
Oneiroe/PySimpleAutomata
PySimpleAutomata/DFA.py
dfa_co_reachable
def dfa_co_reachable(dfa: dict) -> dict: """ Side effects on input! Removes from the DFA all states that do not reach a final state and returns the pruned DFA. It is possible to remove from a DFA A all states that do not reach a final state without altering the language. The co-reachable dfa :math:...
python
def dfa_co_reachable(dfa: dict) -> dict: """ Side effects on input! Removes from the DFA all states that do not reach a final state and returns the pruned DFA. It is possible to remove from a DFA A all states that do not reach a final state without altering the language. The co-reachable dfa :math:...
[ "def", "dfa_co_reachable", "(", "dfa", ":", "dict", ")", "->", "dict", ":", "co_reachable_states", "=", "dfa", "[", "'accepting_states'", "]", ".", "copy", "(", ")", "boundary", "=", "co_reachable_states", ".", "copy", "(", ")", "# inverse transition function", ...
Side effects on input! Removes from the DFA all states that do not reach a final state and returns the pruned DFA. It is possible to remove from a DFA A all states that do not reach a final state without altering the language. The co-reachable dfa :math:`A_F` corresponding to A is defined as: ...
[ "Side", "effects", "on", "input!", "Removes", "from", "the", "DFA", "all", "states", "that", "do", "not", "reach", "a", "final", "state", "and", "returns", "the", "pruned", "DFA", "." ]
0f9f2705fd8ddd5d8118bc31552a640f5d00c359
https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/DFA.py#L377-L433
train
64,717
Oneiroe/PySimpleAutomata
PySimpleAutomata/DFA.py
dfa_trimming
def dfa_trimming(dfa: dict) -> dict: """ Side effects on input! Returns the DFA in input trimmed, so both reachable and co-reachable. Given a DFA A, the corresponding trimmed DFA contains only those states that are reachable from the initial state and that lead to a final state. The trimmed dfa...
python
def dfa_trimming(dfa: dict) -> dict: """ Side effects on input! Returns the DFA in input trimmed, so both reachable and co-reachable. Given a DFA A, the corresponding trimmed DFA contains only those states that are reachable from the initial state and that lead to a final state. The trimmed dfa...
[ "def", "dfa_trimming", "(", "dfa", ":", "dict", ")", "->", "dict", ":", "# Reachable DFA", "dfa", "=", "dfa_reachable", "(", "dfa", ")", "# Co-reachable DFA", "dfa", "=", "dfa_co_reachable", "(", "dfa", ")", "# trimmed DFA", "return", "dfa" ]
Side effects on input! Returns the DFA in input trimmed, so both reachable and co-reachable. Given a DFA A, the corresponding trimmed DFA contains only those states that are reachable from the initial state and that lead to a final state. The trimmed dfa :math:`A_{RF}` corresponding to A is defined...
[ "Side", "effects", "on", "input!", "Returns", "the", "DFA", "in", "input", "trimmed", "so", "both", "reachable", "and", "co", "-", "reachable", "." ]
0f9f2705fd8ddd5d8118bc31552a640f5d00c359
https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/DFA.py#L437-L463
train
64,718
konstantint/pyliftover
pyliftover/chainfile.py
LiftOverChainFile._load_chains
def _load_chains(f): ''' Loads all LiftOverChain objects from a file into an array. Returns the result. ''' chains = [] while True: line = f.readline() if not line: break if line.startswith(b'#') or line.startswith(b'\n') or lin...
python
def _load_chains(f): ''' Loads all LiftOverChain objects from a file into an array. Returns the result. ''' chains = [] while True: line = f.readline() if not line: break if line.startswith(b'#') or line.startswith(b'\n') or lin...
[ "def", "_load_chains", "(", "f", ")", ":", "chains", "=", "[", "]", "while", "True", ":", "line", "=", "f", ".", "readline", "(", ")", "if", "not", "line", ":", "break", "if", "line", ".", "startswith", "(", "b'#'", ")", "or", "line", ".", "start...
Loads all LiftOverChain objects from a file into an array. Returns the result.
[ "Loads", "all", "LiftOverChain", "objects", "from", "a", "file", "into", "an", "array", ".", "Returns", "the", "result", "." ]
5164eed9ae678ad0ddc164df8c2c5767e6a4b39f
https://github.com/konstantint/pyliftover/blob/5164eed9ae678ad0ddc164df8c2c5767e6a4b39f/pyliftover/chainfile.py#L106-L121
train
64,719
mmcloughlin/luhn
luhn.py
checksum
def checksum(string): """ Compute the Luhn checksum for the provided string of digits. Note this assumes the check digit is in place. """ digits = list(map(int, string)) odd_sum = sum(digits[-1::-2]) even_sum = sum([sum(divmod(2 * d, 10)) for d in digits[-2::-2]]) return (odd_sum + even_...
python
def checksum(string): """ Compute the Luhn checksum for the provided string of digits. Note this assumes the check digit is in place. """ digits = list(map(int, string)) odd_sum = sum(digits[-1::-2]) even_sum = sum([sum(divmod(2 * d, 10)) for d in digits[-2::-2]]) return (odd_sum + even_...
[ "def", "checksum", "(", "string", ")", ":", "digits", "=", "list", "(", "map", "(", "int", ",", "string", ")", ")", "odd_sum", "=", "sum", "(", "digits", "[", "-", "1", ":", ":", "-", "2", "]", ")", "even_sum", "=", "sum", "(", "[", "sum", "(...
Compute the Luhn checksum for the provided string of digits. Note this assumes the check digit is in place.
[ "Compute", "the", "Luhn", "checksum", "for", "the", "provided", "string", "of", "digits", ".", "Note", "this", "assumes", "the", "check", "digit", "is", "in", "place", "." ]
d6f3fa71072f99334a4c1d2a3f062fa93982797f
https://github.com/mmcloughlin/luhn/blob/d6f3fa71072f99334a4c1d2a3f062fa93982797f/luhn.py#L3-L11
train
64,720
sdonk/django-admin-ip-restrictor
admin_ip_restrictor/middleware.py
AdminIPRestrictorMiddleware.is_blocked
def is_blocked(self, ip): """Determine if an IP address should be considered blocked.""" blocked = True if ip in self.allowed_admin_ips: blocked = False for allowed_range in self.allowed_admin_ip_ranges: if ipaddress.ip_address(ip) in ipaddress.ip_network(allowe...
python
def is_blocked(self, ip): """Determine if an IP address should be considered blocked.""" blocked = True if ip in self.allowed_admin_ips: blocked = False for allowed_range in self.allowed_admin_ip_ranges: if ipaddress.ip_address(ip) in ipaddress.ip_network(allowe...
[ "def", "is_blocked", "(", "self", ",", "ip", ")", ":", "blocked", "=", "True", "if", "ip", "in", "self", ".", "allowed_admin_ips", ":", "blocked", "=", "False", "for", "allowed_range", "in", "self", ".", "allowed_admin_ip_ranges", ":", "if", "ipaddress", "...
Determine if an IP address should be considered blocked.
[ "Determine", "if", "an", "IP", "address", "should", "be", "considered", "blocked", "." ]
29c948677e52bc416d44fff0f013d1f4ba2cb782
https://github.com/sdonk/django-admin-ip-restrictor/blob/29c948677e52bc416d44fff0f013d1f4ba2cb782/admin_ip_restrictor/middleware.py#L60-L71
train
64,721
entrepreneur-interet-general/mkinx
mkinx/commands.py
serve
def serve(args): """Start a server which will watch .md and .rst files for changes. If a md file changes, the Home Documentation is rebuilt. If a .rst file changes, the updated sphinx project is rebuilt Args: args (ArgumentParser): flags from the CLI """ # Sever's parameters port = ...
python
def serve(args): """Start a server which will watch .md and .rst files for changes. If a md file changes, the Home Documentation is rebuilt. If a .rst file changes, the updated sphinx project is rebuilt Args: args (ArgumentParser): flags from the CLI """ # Sever's parameters port = ...
[ "def", "serve", "(", "args", ")", ":", "# Sever's parameters", "port", "=", "args", ".", "serve_port", "or", "PORT", "host", "=", "\"0.0.0.0\"", "# Current working directory", "dir_path", "=", "Path", "(", ")", ".", "absolute", "(", ")", "web_dir", "=", "dir...
Start a server which will watch .md and .rst files for changes. If a md file changes, the Home Documentation is rebuilt. If a .rst file changes, the updated sphinx project is rebuilt Args: args (ArgumentParser): flags from the CLI
[ "Start", "a", "server", "which", "will", "watch", ".", "md", "and", ".", "rst", "files", "for", "changes", ".", "If", "a", "md", "file", "changes", "the", "Home", "Documentation", "is", "rebuilt", ".", "If", "a", ".", "rst", "file", "changes", "the", ...
70ccf81d3fad974283829ca4ec069a873341461d
https://github.com/entrepreneur-interet-general/mkinx/blob/70ccf81d3fad974283829ca4ec069a873341461d/mkinx/commands.py#L45-L138
train
64,722
entrepreneur-interet-general/mkinx
mkinx/include/example_project/classif/models.py
LogisticRegressor.train
def train(self, X_train, Y_train, X_test, Y_test): """Train and validate the LR on a train and test dataset Args: X_train (np.array): Training data Y_train (np.array): Training labels X_test (np.array): Test data Y_test (np.array): Test labels """...
python
def train(self, X_train, Y_train, X_test, Y_test): """Train and validate the LR on a train and test dataset Args: X_train (np.array): Training data Y_train (np.array): Training labels X_test (np.array): Test data Y_test (np.array): Test labels """...
[ "def", "train", "(", "self", ",", "X_train", ",", "Y_train", ",", "X_test", ",", "Y_test", ")", ":", "while", "True", ":", "print", "(", "1", ")", "time", ".", "sleep", "(", "1", ")", "if", "random", ".", "randint", "(", "0", ",", "9", ")", ">=...
Train and validate the LR on a train and test dataset Args: X_train (np.array): Training data Y_train (np.array): Training labels X_test (np.array): Test data Y_test (np.array): Test labels
[ "Train", "and", "validate", "the", "LR", "on", "a", "train", "and", "test", "dataset" ]
70ccf81d3fad974283829ca4ec069a873341461d
https://github.com/entrepreneur-interet-general/mkinx/blob/70ccf81d3fad974283829ca4ec069a873341461d/mkinx/include/example_project/classif/models.py#L24-L38
train
64,723
choldgraf/download
download/download.py
download
def download(url, path, kind='file', progressbar=True, replace=False, timeout=10., verbose=True): """Download a URL. This will download a file and store it in a '~/data/` folder, creating directories if need be. It will also work for zip files, in which case it will unzip all of the files ...
python
def download(url, path, kind='file', progressbar=True, replace=False, timeout=10., verbose=True): """Download a URL. This will download a file and store it in a '~/data/` folder, creating directories if need be. It will also work for zip files, in which case it will unzip all of the files ...
[ "def", "download", "(", "url", ",", "path", ",", "kind", "=", "'file'", ",", "progressbar", "=", "True", ",", "replace", "=", "False", ",", "timeout", "=", "10.", ",", "verbose", "=", "True", ")", ":", "if", "kind", "not", "in", "ALLOWED_KINDS", ":",...
Download a URL. This will download a file and store it in a '~/data/` folder, creating directories if need be. It will also work for zip files, in which case it will unzip all of the files to the desired location. Parameters ---------- url : string The url of the file to download. ...
[ "Download", "a", "URL", "." ]
26007bb87751ee35791e30e4dfc54dd088bf15e6
https://github.com/choldgraf/download/blob/26007bb87751ee35791e30e4dfc54dd088bf15e6/download/download.py#L27-L113
train
64,724
choldgraf/download
download/download.py
_convert_url_to_downloadable
def _convert_url_to_downloadable(url): """Convert a url to the proper style depending on its website.""" if 'drive.google.com' in url: # For future support of google drive file_id = url.split('d/')[1].split('/')[0] base_url = 'https://drive.google.com/uc?export=download&id=' out...
python
def _convert_url_to_downloadable(url): """Convert a url to the proper style depending on its website.""" if 'drive.google.com' in url: # For future support of google drive file_id = url.split('d/')[1].split('/')[0] base_url = 'https://drive.google.com/uc?export=download&id=' out...
[ "def", "_convert_url_to_downloadable", "(", "url", ")", ":", "if", "'drive.google.com'", "in", "url", ":", "# For future support of google drive", "file_id", "=", "url", ".", "split", "(", "'d/'", ")", "[", "1", "]", ".", "split", "(", "'/'", ")", "[", "0", ...
Convert a url to the proper style depending on its website.
[ "Convert", "a", "url", "to", "the", "proper", "style", "depending", "on", "its", "website", "." ]
26007bb87751ee35791e30e4dfc54dd088bf15e6
https://github.com/choldgraf/download/blob/26007bb87751ee35791e30e4dfc54dd088bf15e6/download/download.py#L116-L134
train
64,725
choldgraf/download
download/download.py
md5sum
def md5sum(fname, block_size=1048576): # 2 ** 20 """Calculate the md5sum for a file. Parameters ---------- fname : str Filename. block_size : int Block size to use when reading. Returns ------- hash_ : str The hexadecimal digest of the hash. """ md5 = h...
python
def md5sum(fname, block_size=1048576): # 2 ** 20 """Calculate the md5sum for a file. Parameters ---------- fname : str Filename. block_size : int Block size to use when reading. Returns ------- hash_ : str The hexadecimal digest of the hash. """ md5 = h...
[ "def", "md5sum", "(", "fname", ",", "block_size", "=", "1048576", ")", ":", "# 2 ** 20", "md5", "=", "hashlib", ".", "md5", "(", ")", "with", "open", "(", "fname", ",", "'rb'", ")", "as", "fid", ":", "while", "True", ":", "data", "=", "fid", ".", ...
Calculate the md5sum for a file. Parameters ---------- fname : str Filename. block_size : int Block size to use when reading. Returns ------- hash_ : str The hexadecimal digest of the hash.
[ "Calculate", "the", "md5sum", "for", "a", "file", "." ]
26007bb87751ee35791e30e4dfc54dd088bf15e6
https://github.com/choldgraf/download/blob/26007bb87751ee35791e30e4dfc54dd088bf15e6/download/download.py#L322-L344
train
64,726
choldgraf/download
download/download.py
_chunk_write
def _chunk_write(chunk, local_file, progress): """Write a chunk to file and update the progress bar.""" local_file.write(chunk) if progress is not None: progress.update(len(chunk))
python
def _chunk_write(chunk, local_file, progress): """Write a chunk to file and update the progress bar.""" local_file.write(chunk) if progress is not None: progress.update(len(chunk))
[ "def", "_chunk_write", "(", "chunk", ",", "local_file", ",", "progress", ")", ":", "local_file", ".", "write", "(", "chunk", ")", "if", "progress", "is", "not", "None", ":", "progress", ".", "update", "(", "len", "(", "chunk", ")", ")" ]
Write a chunk to file and update the progress bar.
[ "Write", "a", "chunk", "to", "file", "and", "update", "the", "progress", "bar", "." ]
26007bb87751ee35791e30e4dfc54dd088bf15e6
https://github.com/choldgraf/download/blob/26007bb87751ee35791e30e4dfc54dd088bf15e6/download/download.py#L347-L351
train
64,727
choldgraf/download
download/download.py
sizeof_fmt
def sizeof_fmt(num): """Turn number of bytes into human-readable str. Parameters ---------- num : int The number of bytes. Returns ------- size : str The size in human-readable format. """ units = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'] decimals = [0, 0, 1, 2, 2...
python
def sizeof_fmt(num): """Turn number of bytes into human-readable str. Parameters ---------- num : int The number of bytes. Returns ------- size : str The size in human-readable format. """ units = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'] decimals = [0, 0, 1, 2, 2...
[ "def", "sizeof_fmt", "(", "num", ")", ":", "units", "=", "[", "'bytes'", ",", "'kB'", ",", "'MB'", ",", "'GB'", ",", "'TB'", ",", "'PB'", "]", "decimals", "=", "[", "0", ",", "0", ",", "1", ",", "2", ",", "2", ",", "2", "]", "if", "num", ">...
Turn number of bytes into human-readable str. Parameters ---------- num : int The number of bytes. Returns ------- size : str The size in human-readable format.
[ "Turn", "number", "of", "bytes", "into", "human", "-", "readable", "str", "." ]
26007bb87751ee35791e30e4dfc54dd088bf15e6
https://github.com/choldgraf/download/blob/26007bb87751ee35791e30e4dfc54dd088bf15e6/download/download.py#L354-L379
train
64,728
rasky/geventconnpool
src/geventconnpool/pool.py
retry
def retry(f, exc_classes=DEFAULT_EXC_CLASSES, logger=None, retry_log_level=logging.INFO, retry_log_message="Connection broken in '{f}' (error: '{e}'); " "retrying with new connection.", max_failures=None, interval=0, max_failure_log_level=logging.ERROR...
python
def retry(f, exc_classes=DEFAULT_EXC_CLASSES, logger=None, retry_log_level=logging.INFO, retry_log_message="Connection broken in '{f}' (error: '{e}'); " "retrying with new connection.", max_failures=None, interval=0, max_failure_log_level=logging.ERROR...
[ "def", "retry", "(", "f", ",", "exc_classes", "=", "DEFAULT_EXC_CLASSES", ",", "logger", "=", "None", ",", "retry_log_level", "=", "logging", ".", "INFO", ",", "retry_log_message", "=", "\"Connection broken in '{f}' (error: '{e}'); \"", "\"retrying with new connection.\""...
Decorator to automatically reexecute a function if the connection is broken for any reason.
[ "Decorator", "to", "automatically", "reexecute", "a", "function", "if", "the", "connection", "is", "broken", "for", "any", "reason", "." ]
47c65c64e051cb62061f3ed072991d6b0a83bbf5
https://github.com/rasky/geventconnpool/blob/47c65c64e051cb62061f3ed072991d6b0a83bbf5/src/geventconnpool/pool.py#L112-L144
train
64,729
rasky/geventconnpool
src/geventconnpool/pool.py
ConnectionPool.get
def get(self): """ Get a connection from the pool, to make and receive traffic. If the connection fails for any reason (socket.error), it is dropped and a new one is scheduled. Please use @retry as a way to automatically retry whatever operation you were performing. """ ...
python
def get(self): """ Get a connection from the pool, to make and receive traffic. If the connection fails for any reason (socket.error), it is dropped and a new one is scheduled. Please use @retry as a way to automatically retry whatever operation you were performing. """ ...
[ "def", "get", "(", "self", ")", ":", "self", ".", "lock", ".", "acquire", "(", ")", "try", ":", "c", "=", "self", ".", "conn", ".", "popleft", "(", ")", "yield", "c", "except", "self", ".", "exc_classes", ":", "# The current connection has failed, drop i...
Get a connection from the pool, to make and receive traffic. If the connection fails for any reason (socket.error), it is dropped and a new one is scheduled. Please use @retry as a way to automatically retry whatever operation you were performing.
[ "Get", "a", "connection", "from", "the", "pool", "to", "make", "and", "receive", "traffic", "." ]
47c65c64e051cb62061f3ed072991d6b0a83bbf5
https://github.com/rasky/geventconnpool/blob/47c65c64e051cb62061f3ed072991d6b0a83bbf5/src/geventconnpool/pool.py#L85-L109
train
64,730
alimanfoo/vcfnp
vcfnp/eff.py
eff_default_transformer
def eff_default_transformer(fills=EFF_DEFAULT_FILLS): """ Return a simple transformer function for parsing EFF annotations. N.B., ignores all but the first effect. """ def _transformer(vals): if len(vals) == 0: return fills else: # ignore all but first effect...
python
def eff_default_transformer(fills=EFF_DEFAULT_FILLS): """ Return a simple transformer function for parsing EFF annotations. N.B., ignores all but the first effect. """ def _transformer(vals): if len(vals) == 0: return fills else: # ignore all but first effect...
[ "def", "eff_default_transformer", "(", "fills", "=", "EFF_DEFAULT_FILLS", ")", ":", "def", "_transformer", "(", "vals", ")", ":", "if", "len", "(", "vals", ")", "==", "0", ":", "return", "fills", "else", ":", "# ignore all but first effect", "match_eff_main", ...
Return a simple transformer function for parsing EFF annotations. N.B., ignores all but the first effect.
[ "Return", "a", "simple", "transformer", "function", "for", "parsing", "EFF", "annotations", ".", "N", ".", "B", ".", "ignores", "all", "but", "the", "first", "effect", "." ]
c3f63fb11ada56d4a88076c61c81f99b8ee78b8f
https://github.com/alimanfoo/vcfnp/blob/c3f63fb11ada56d4a88076c61c81f99b8ee78b8f/vcfnp/eff.py#L69-L96
train
64,731
alimanfoo/vcfnp
vcfnp/eff.py
ann_default_transformer
def ann_default_transformer(fills=ANN_DEFAULT_FILLS): """ Return a simple transformer function for parsing ANN annotations. N.B., ignores all but the first effect. """ def _transformer(vals): if len(vals) == 0: return fills else: # ignore all but first effect...
python
def ann_default_transformer(fills=ANN_DEFAULT_FILLS): """ Return a simple transformer function for parsing ANN annotations. N.B., ignores all but the first effect. """ def _transformer(vals): if len(vals) == 0: return fills else: # ignore all but first effect...
[ "def", "ann_default_transformer", "(", "fills", "=", "ANN_DEFAULT_FILLS", ")", ":", "def", "_transformer", "(", "vals", ")", ":", "if", "len", "(", "vals", ")", "==", "0", ":", "return", "fills", "else", ":", "# ignore all but first effect", "ann", "=", "val...
Return a simple transformer function for parsing ANN annotations. N.B., ignores all but the first effect.
[ "Return", "a", "simple", "transformer", "function", "for", "parsing", "ANN", "annotations", ".", "N", ".", "B", ".", "ignores", "all", "but", "the", "first", "effect", "." ]
c3f63fb11ada56d4a88076c61c81f99b8ee78b8f
https://github.com/alimanfoo/vcfnp/blob/c3f63fb11ada56d4a88076c61c81f99b8ee78b8f/vcfnp/eff.py#L104-L126
train
64,732
bintoro/overloading.py
overloading.py
overloaded
def overloaded(func): """ Introduces a new overloaded function and registers its first implementation. """ fn = unwrap(func) ensure_function(fn) def dispatcher(*args, **kwargs): resolved = None if dispatcher.__complex_parameters: cache_key_pos = [] cache...
python
def overloaded(func): """ Introduces a new overloaded function and registers its first implementation. """ fn = unwrap(func) ensure_function(fn) def dispatcher(*args, **kwargs): resolved = None if dispatcher.__complex_parameters: cache_key_pos = [] cache...
[ "def", "overloaded", "(", "func", ")", ":", "fn", "=", "unwrap", "(", "func", ")", "ensure_function", "(", "fn", ")", "def", "dispatcher", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "resolved", "=", "None", "if", "dispatcher", ".", "__compl...
Introduces a new overloaded function and registers its first implementation.
[ "Introduces", "a", "new", "overloaded", "function", "and", "registers", "its", "first", "implementation", "." ]
d7b044d6f7e38043f0fc20f44f134baec84a5b32
https://github.com/bintoro/overloading.py/blob/d7b044d6f7e38043f0fc20f44f134baec84a5b32/overloading.py#L69-L151
train
64,733
bintoro/overloading.py
overloading.py
register
def register(dispatcher, func, *, hook=None): """ Registers `func` as an implementation on `dispatcher`. """ wrapper = None if isinstance(func, (classmethod, staticmethod)): wrapper = type(func) func = func.__func__ ensure_function(func) if isinstance(dispatcher, (classmethod...
python
def register(dispatcher, func, *, hook=None): """ Registers `func` as an implementation on `dispatcher`. """ wrapper = None if isinstance(func, (classmethod, staticmethod)): wrapper = type(func) func = func.__func__ ensure_function(func) if isinstance(dispatcher, (classmethod...
[ "def", "register", "(", "dispatcher", ",", "func", ",", "*", ",", "hook", "=", "None", ")", ":", "wrapper", "=", "None", "if", "isinstance", "(", "func", ",", "(", "classmethod", ",", "staticmethod", ")", ")", ":", "wrapper", "=", "type", "(", "func"...
Registers `func` as an implementation on `dispatcher`.
[ "Registers", "func", "as", "an", "implementation", "on", "dispatcher", "." ]
d7b044d6f7e38043f0fc20f44f134baec84a5b32
https://github.com/bintoro/overloading.py/blob/d7b044d6f7e38043f0fc20f44f134baec84a5b32/overloading.py#L179-L246
train
64,734
bintoro/overloading.py
overloading.py
find
def find(dispatcher, args, kwargs): """ Given the arguments contained in `args` and `kwargs`, returns the best match from the list of implementations registered on `dispatcher`. """ matches = [] full_args = args full_kwargs = kwargs for func, sig in dispatcher.__functions: params...
python
def find(dispatcher, args, kwargs): """ Given the arguments contained in `args` and `kwargs`, returns the best match from the list of implementations registered on `dispatcher`. """ matches = [] full_args = args full_kwargs = kwargs for func, sig in dispatcher.__functions: params...
[ "def", "find", "(", "dispatcher", ",", "args", ",", "kwargs", ")", ":", "matches", "=", "[", "]", "full_args", "=", "args", "full_kwargs", "=", "kwargs", "for", "func", ",", "sig", "in", "dispatcher", ".", "__functions", ":", "params", "=", "sig", ".",...
Given the arguments contained in `args` and `kwargs`, returns the best match from the list of implementations registered on `dispatcher`.
[ "Given", "the", "arguments", "contained", "in", "args", "and", "kwargs", "returns", "the", "best", "match", "from", "the", "list", "of", "implementations", "registered", "on", "dispatcher", "." ]
d7b044d6f7e38043f0fc20f44f134baec84a5b32
https://github.com/bintoro/overloading.py/blob/d7b044d6f7e38043f0fc20f44f134baec84a5b32/overloading.py#L257-L319
train
64,735
bintoro/overloading.py
overloading.py
get_signature
def get_signature(func): """ Gathers information about the call signature of `func`. """ code = func.__code__ # Names of regular parameters parameters = tuple(code.co_varnames[:code.co_argcount]) # Flags has_varargs = bool(code.co_flags & inspect.CO_VARARGS) has_varkw = bool(code.c...
python
def get_signature(func): """ Gathers information about the call signature of `func`. """ code = func.__code__ # Names of regular parameters parameters = tuple(code.co_varnames[:code.co_argcount]) # Flags has_varargs = bool(code.co_flags & inspect.CO_VARARGS) has_varkw = bool(code.c...
[ "def", "get_signature", "(", "func", ")", ":", "code", "=", "func", ".", "__code__", "# Names of regular parameters", "parameters", "=", "tuple", "(", "code", ".", "co_varnames", "[", ":", "code", ".", "co_argcount", "]", ")", "# Flags", "has_varargs", "=", ...
Gathers information about the call signature of `func`.
[ "Gathers", "information", "about", "the", "call", "signature", "of", "func", "." ]
d7b044d6f7e38043f0fc20f44f134baec84a5b32
https://github.com/bintoro/overloading.py/blob/d7b044d6f7e38043f0fc20f44f134baec84a5b32/overloading.py#L421-L450
train
64,736
bintoro/overloading.py
overloading.py
normalize_type
def normalize_type(type_, level=0): """ Reduces an arbitrarily complex type declaration into something manageable. """ if not typing or not isinstance(type_, typing.TypingMeta) or type_ is AnyType: return type_ if isinstance(type_, typing.TypeVar): if type_.__constraints__ or type_._...
python
def normalize_type(type_, level=0): """ Reduces an arbitrarily complex type declaration into something manageable. """ if not typing or not isinstance(type_, typing.TypingMeta) or type_ is AnyType: return type_ if isinstance(type_, typing.TypeVar): if type_.__constraints__ or type_._...
[ "def", "normalize_type", "(", "type_", ",", "level", "=", "0", ")", ":", "if", "not", "typing", "or", "not", "isinstance", "(", "type_", ",", "typing", ".", "TypingMeta", ")", "or", "type_", "is", "AnyType", ":", "return", "type_", "if", "isinstance", ...
Reduces an arbitrarily complex type declaration into something manageable.
[ "Reduces", "an", "arbitrarily", "complex", "type", "declaration", "into", "something", "manageable", "." ]
d7b044d6f7e38043f0fc20f44f134baec84a5b32
https://github.com/bintoro/overloading.py/blob/d7b044d6f7e38043f0fc20f44f134baec84a5b32/overloading.py#L464-L495
train
64,737
bintoro/overloading.py
overloading.py
type_complexity
def type_complexity(type_): """Computes an indicator for the complexity of `type_`. If the return value is 0, the supplied type is not parameterizable. Otherwise, set bits in the return value denote the following features: - bit 0: The type could be parameterized but is not. - bit 1: The type repre...
python
def type_complexity(type_): """Computes an indicator for the complexity of `type_`. If the return value is 0, the supplied type is not parameterizable. Otherwise, set bits in the return value denote the following features: - bit 0: The type could be parameterized but is not. - bit 1: The type repre...
[ "def", "type_complexity", "(", "type_", ")", ":", "if", "(", "not", "typing", "or", "not", "isinstance", "(", "type_", ",", "(", "typing", ".", "TypingMeta", ",", "GenericWrapperMeta", ")", ")", "or", "type_", "is", "AnyType", ")", ":", "return", "0", ...
Computes an indicator for the complexity of `type_`. If the return value is 0, the supplied type is not parameterizable. Otherwise, set bits in the return value denote the following features: - bit 0: The type could be parameterized but is not. - bit 1: The type represents an iterable container with 1 ...
[ "Computes", "an", "indicator", "for", "the", "complexity", "of", "type_", "." ]
d7b044d6f7e38043f0fc20f44f134baec84a5b32
https://github.com/bintoro/overloading.py/blob/d7b044d6f7e38043f0fc20f44f134baec84a5b32/overloading.py#L586-L620
train
64,738
bintoro/overloading.py
overloading.py
find_base_generic
def find_base_generic(type_): """Locates the underlying generic whose structure and behavior are known. For example, the base generic of a type that inherits from `typing.Mapping[T, int]` is `typing.Mapping`. """ for t in type_.__mro__: if t.__module__ == typing.__name__: return...
python
def find_base_generic(type_): """Locates the underlying generic whose structure and behavior are known. For example, the base generic of a type that inherits from `typing.Mapping[T, int]` is `typing.Mapping`. """ for t in type_.__mro__: if t.__module__ == typing.__name__: return...
[ "def", "find_base_generic", "(", "type_", ")", ":", "for", "t", "in", "type_", ".", "__mro__", ":", "if", "t", ".", "__module__", "==", "typing", ".", "__name__", ":", "return", "first_origin", "(", "t", ")" ]
Locates the underlying generic whose structure and behavior are known. For example, the base generic of a type that inherits from `typing.Mapping[T, int]` is `typing.Mapping`.
[ "Locates", "the", "underlying", "generic", "whose", "structure", "and", "behavior", "are", "known", "." ]
d7b044d6f7e38043f0fc20f44f134baec84a5b32
https://github.com/bintoro/overloading.py/blob/d7b044d6f7e38043f0fc20f44f134baec84a5b32/overloading.py#L629-L637
train
64,739
bintoro/overloading.py
overloading.py
iter_generic_bases
def iter_generic_bases(type_): """Iterates over all generics `type_` derives from, including origins. This function is only necessary because, in typing 3.5.0, a generic doesn't get included in the list of bases when it constructs a parameterized version of itself. This was fixed in aab2c59; now it wou...
python
def iter_generic_bases(type_): """Iterates over all generics `type_` derives from, including origins. This function is only necessary because, in typing 3.5.0, a generic doesn't get included in the list of bases when it constructs a parameterized version of itself. This was fixed in aab2c59; now it wou...
[ "def", "iter_generic_bases", "(", "type_", ")", ":", "for", "t", "in", "type_", ".", "__mro__", ":", "if", "not", "isinstance", "(", "t", ",", "typing", ".", "GenericMeta", ")", ":", "continue", "yield", "t", "t", "=", "t", ".", "__origin__", "while", ...
Iterates over all generics `type_` derives from, including origins. This function is only necessary because, in typing 3.5.0, a generic doesn't get included in the list of bases when it constructs a parameterized version of itself. This was fixed in aab2c59; now it would be enough to just iterate over ...
[ "Iterates", "over", "all", "generics", "type_", "derives", "from", "including", "origins", "." ]
d7b044d6f7e38043f0fc20f44f134baec84a5b32
https://github.com/bintoro/overloading.py/blob/d7b044d6f7e38043f0fc20f44f134baec84a5b32/overloading.py#L640-L655
train
64,740
bintoro/overloading.py
overloading.py
sig_cmp
def sig_cmp(sig1, sig2): """ Compares two normalized type signatures for validation purposes. """ types1 = sig1.required types2 = sig2.required if len(types1) != len(types2): return False dup_pos = [] dup_kw = {} for t1, t2 in zip(types1, types2): match = type_cmp(t1,...
python
def sig_cmp(sig1, sig2): """ Compares two normalized type signatures for validation purposes. """ types1 = sig1.required types2 = sig2.required if len(types1) != len(types2): return False dup_pos = [] dup_kw = {} for t1, t2 in zip(types1, types2): match = type_cmp(t1,...
[ "def", "sig_cmp", "(", "sig1", ",", "sig2", ")", ":", "types1", "=", "sig1", ".", "required", "types2", "=", "sig2", ".", "required", "if", "len", "(", "types1", ")", "!=", "len", "(", "types2", ")", ":", "return", "False", "dup_pos", "=", "[", "]"...
Compares two normalized type signatures for validation purposes.
[ "Compares", "two", "normalized", "type", "signatures", "for", "validation", "purposes", "." ]
d7b044d6f7e38043f0fc20f44f134baec84a5b32
https://github.com/bintoro/overloading.py/blob/d7b044d6f7e38043f0fc20f44f134baec84a5b32/overloading.py#L658-L691
train
64,741
bintoro/overloading.py
overloading.py
is_void
def is_void(func): """ Determines if a function is a void function, i.e., one whose body contains nothing but a docstring or an ellipsis. A void function can be used to introduce an overloaded function without actually registering an implementation. """ try: source = dedent(inspect.getso...
python
def is_void(func): """ Determines if a function is a void function, i.e., one whose body contains nothing but a docstring or an ellipsis. A void function can be used to introduce an overloaded function without actually registering an implementation. """ try: source = dedent(inspect.getso...
[ "def", "is_void", "(", "func", ")", ":", "try", ":", "source", "=", "dedent", "(", "inspect", ".", "getsource", "(", "func", ")", ")", "except", "(", "OSError", ",", "IOError", ")", ":", "return", "False", "fdef", "=", "next", "(", "ast", ".", "ite...
Determines if a function is a void function, i.e., one whose body contains nothing but a docstring or an ellipsis. A void function can be used to introduce an overloaded function without actually registering an implementation.
[ "Determines", "if", "a", "function", "is", "a", "void", "function", "i", ".", "e", ".", "one", "whose", "body", "contains", "nothing", "but", "a", "docstring", "or", "an", "ellipsis", ".", "A", "void", "function", "can", "be", "used", "to", "introduce", ...
d7b044d6f7e38043f0fc20f44f134baec84a5b32
https://github.com/bintoro/overloading.py/blob/d7b044d6f7e38043f0fc20f44f134baec84a5b32/overloading.py#L755-L769
train
64,742
bintoro/overloading.py
overloading.py
GenericWrapperMeta.derive_configuration
def derive_configuration(cls): """ Collect the nearest type variables and effective parameters from the type, its bases, and their origins as necessary. """ base_params = cls.base.__parameters__ if hasattr(cls.type, '__args__'): # typing as of commit abefbe4 ...
python
def derive_configuration(cls): """ Collect the nearest type variables and effective parameters from the type, its bases, and their origins as necessary. """ base_params = cls.base.__parameters__ if hasattr(cls.type, '__args__'): # typing as of commit abefbe4 ...
[ "def", "derive_configuration", "(", "cls", ")", ":", "base_params", "=", "cls", ".", "base", ".", "__parameters__", "if", "hasattr", "(", "cls", ".", "type", ",", "'__args__'", ")", ":", "# typing as of commit abefbe4", "tvars", "=", "{", "p", ":", "p", "f...
Collect the nearest type variables and effective parameters from the type, its bases, and their origins as necessary.
[ "Collect", "the", "nearest", "type", "variables", "and", "effective", "parameters", "from", "the", "type", "its", "bases", "and", "their", "origins", "as", "necessary", "." ]
d7b044d6f7e38043f0fc20f44f134baec84a5b32
https://github.com/bintoro/overloading.py/blob/d7b044d6f7e38043f0fc20f44f134baec84a5b32/overloading.py#L546-L579
train
64,743
Oneiroe/PySimpleAutomata
PySimpleAutomata/NFA.py
nfa_intersection
def nfa_intersection(nfa_1: dict, nfa_2: dict) -> dict: """ Returns a NFA that reads the intersection of the NFAs in input. Let :math:`A_1 = (Σ,S_1,S_1^0,ρ_1,F_1)` and :math:`A_2 =(Σ, S_2,S_2^0,ρ_2,F_2)` be two NFAs. There is a NFA :math:`A_∧` that runs simultaneously both :math:`A_1` and :math...
python
def nfa_intersection(nfa_1: dict, nfa_2: dict) -> dict: """ Returns a NFA that reads the intersection of the NFAs in input. Let :math:`A_1 = (Σ,S_1,S_1^0,ρ_1,F_1)` and :math:`A_2 =(Σ, S_2,S_2^0,ρ_2,F_2)` be two NFAs. There is a NFA :math:`A_∧` that runs simultaneously both :math:`A_1` and :math...
[ "def", "nfa_intersection", "(", "nfa_1", ":", "dict", ",", "nfa_2", ":", "dict", ")", "->", "dict", ":", "intersection", "=", "{", "'alphabet'", ":", "nfa_1", "[", "'alphabet'", "]", ".", "intersection", "(", "nfa_2", "[", "'alphabet'", "]", ")", ",", ...
Returns a NFA that reads the intersection of the NFAs in input. Let :math:`A_1 = (Σ,S_1,S_1^0,ρ_1,F_1)` and :math:`A_2 =(Σ, S_2,S_2^0,ρ_2,F_2)` be two NFAs. There is a NFA :math:`A_∧` that runs simultaneously both :math:`A_1` and :math:`A_2` on the input word, so :math:`L(A_∧) = L(A_1)∩L(A_2)`....
[ "Returns", "a", "NFA", "that", "reads", "the", "intersection", "of", "the", "NFAs", "in", "input", "." ]
0f9f2705fd8ddd5d8118bc31552a640f5d00c359
https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/NFA.py#L35-L99
train
64,744
Oneiroe/PySimpleAutomata
PySimpleAutomata/NFA.py
nfa_union
def nfa_union(nfa_1: dict, nfa_2: dict) -> dict: """ Returns a NFA that reads the union of the NFAs in input. Let :math:`A_1 = (Σ,S_1,S_1^0,ρ_1,F_1)` and :math:`A_2 =(Σ, S_2,S_2^0,ρ_2,F_2)` be two NFAs. here is a NFA :math:`A_∨` that nondeterministically chooses :math:`A_1` or :math:`A_2` and runs ...
python
def nfa_union(nfa_1: dict, nfa_2: dict) -> dict: """ Returns a NFA that reads the union of the NFAs in input. Let :math:`A_1 = (Σ,S_1,S_1^0,ρ_1,F_1)` and :math:`A_2 =(Σ, S_2,S_2^0,ρ_2,F_2)` be two NFAs. here is a NFA :math:`A_∨` that nondeterministically chooses :math:`A_1` or :math:`A_2` and runs ...
[ "def", "nfa_union", "(", "nfa_1", ":", "dict", ",", "nfa_2", ":", "dict", ")", "->", "dict", ":", "union", "=", "{", "'alphabet'", ":", "nfa_1", "[", "'alphabet'", "]", ".", "union", "(", "nfa_2", "[", "'alphabet'", "]", ")", ",", "'states'", ":", ...
Returns a NFA that reads the union of the NFAs in input. Let :math:`A_1 = (Σ,S_1,S_1^0,ρ_1,F_1)` and :math:`A_2 =(Σ, S_2,S_2^0,ρ_2,F_2)` be two NFAs. here is a NFA :math:`A_∨` that nondeterministically chooses :math:`A_1` or :math:`A_2` and runs it on the input word. It is defined as: :math:`A...
[ "Returns", "a", "NFA", "that", "reads", "the", "union", "of", "the", "NFAs", "in", "input", "." ]
0f9f2705fd8ddd5d8118bc31552a640f5d00c359
https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/NFA.py#L102-L142
train
64,745
Oneiroe/PySimpleAutomata
PySimpleAutomata/NFA.py
nfa_determinization
def nfa_determinization(nfa: dict) -> dict: """ Returns a DFA that reads the same language of the input NFA. Let A be an NFA, then there exists a DFA :math:`A_d` such that :math:`L(A_d) = L(A)`. Intuitively, :math:`A_d` collapses all possible runs of A on a given input word into one run over a larg...
python
def nfa_determinization(nfa: dict) -> dict: """ Returns a DFA that reads the same language of the input NFA. Let A be an NFA, then there exists a DFA :math:`A_d` such that :math:`L(A_d) = L(A)`. Intuitively, :math:`A_d` collapses all possible runs of A on a given input word into one run over a larg...
[ "def", "nfa_determinization", "(", "nfa", ":", "dict", ")", "->", "dict", ":", "def", "state_name", "(", "s", ")", ":", "return", "str", "(", "set", "(", "sorted", "(", "s", ")", ")", ")", "dfa", "=", "{", "'alphabet'", ":", "nfa", "[", "'alphabet'...
Returns a DFA that reads the same language of the input NFA. Let A be an NFA, then there exists a DFA :math:`A_d` such that :math:`L(A_d) = L(A)`. Intuitively, :math:`A_d` collapses all possible runs of A on a given input word into one run over a larger state set. :math:`A_d` is defined as: :m...
[ "Returns", "a", "DFA", "that", "reads", "the", "same", "language", "of", "the", "input", "NFA", "." ]
0f9f2705fd8ddd5d8118bc31552a640f5d00c359
https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/NFA.py#L146-L211
train
64,746
Oneiroe/PySimpleAutomata
PySimpleAutomata/NFA.py
nfa_complementation
def nfa_complementation(nfa: dict) -> dict: """ Returns a DFA reading the complemented language read by input NFA. Complement a nondeterministic automaton is possible complementing the determinization of it. The construction is effective, but it involves an exponential blow-up, since determiniz...
python
def nfa_complementation(nfa: dict) -> dict: """ Returns a DFA reading the complemented language read by input NFA. Complement a nondeterministic automaton is possible complementing the determinization of it. The construction is effective, but it involves an exponential blow-up, since determiniz...
[ "def", "nfa_complementation", "(", "nfa", ":", "dict", ")", "->", "dict", ":", "determinized_nfa", "=", "nfa_determinization", "(", "nfa", ")", "return", "DFA", ".", "dfa_complementation", "(", "determinized_nfa", ")" ]
Returns a DFA reading the complemented language read by input NFA. Complement a nondeterministic automaton is possible complementing the determinization of it. The construction is effective, but it involves an exponential blow-up, since determinization involves an unavoidable exponential blow-u...
[ "Returns", "a", "DFA", "reading", "the", "complemented", "language", "read", "by", "input", "NFA", "." ]
0f9f2705fd8ddd5d8118bc31552a640f5d00c359
https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/NFA.py#L214-L229
train
64,747
Oneiroe/PySimpleAutomata
PySimpleAutomata/NFA.py
nfa_word_acceptance
def nfa_word_acceptance(nfa: dict, word: list) -> bool: """ Checks if a given word is accepted by a NFA. The word w is accepted by a NFA if exists at least an accepting run on w. :param dict nfa: input NFA; :param list word: list of symbols ∈ nfa['alphabet']; :return: *(bool)*, True if the wor...
python
def nfa_word_acceptance(nfa: dict, word: list) -> bool: """ Checks if a given word is accepted by a NFA. The word w is accepted by a NFA if exists at least an accepting run on w. :param dict nfa: input NFA; :param list word: list of symbols ∈ nfa['alphabet']; :return: *(bool)*, True if the wor...
[ "def", "nfa_word_acceptance", "(", "nfa", ":", "dict", ",", "word", ":", "list", ")", "->", "bool", ":", "current_level", "=", "set", "(", ")", "current_level", "=", "current_level", ".", "union", "(", "nfa", "[", "'initial_states'", "]", ")", "next_level"...
Checks if a given word is accepted by a NFA. The word w is accepted by a NFA if exists at least an accepting run on w. :param dict nfa: input NFA; :param list word: list of symbols ∈ nfa['alphabet']; :return: *(bool)*, True if the word is accepted, False otherwise.
[ "Checks", "if", "a", "given", "word", "is", "accepted", "by", "a", "NFA", "." ]
0f9f2705fd8ddd5d8118bc31552a640f5d00c359
https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/NFA.py#L308-L333
train
64,748
entrepreneur-interet-general/mkinx
mkinx/utils.py
overwrite_view_source
def overwrite_view_source(project, dir_path): """In the project's index.html built file, replace the top "source" link with a link to the documentation's home, which is mkdoc's home Args: project (str): project to update dir_path (pathlib.Path): this file's path """ project_html_lo...
python
def overwrite_view_source(project, dir_path): """In the project's index.html built file, replace the top "source" link with a link to the documentation's home, which is mkdoc's home Args: project (str): project to update dir_path (pathlib.Path): this file's path """ project_html_lo...
[ "def", "overwrite_view_source", "(", "project", ",", "dir_path", ")", ":", "project_html_location", "=", "dir_path", "/", "project", "/", "HTML_LOCATION", "if", "not", "project_html_location", ".", "exists", "(", ")", ":", "return", "files_to_overwrite", "=", "[",...
In the project's index.html built file, replace the top "source" link with a link to the documentation's home, which is mkdoc's home Args: project (str): project to update dir_path (pathlib.Path): this file's path
[ "In", "the", "project", "s", "index", ".", "html", "built", "file", "replace", "the", "top", "source", "link", "with", "a", "link", "to", "the", "documentation", "s", "home", "which", "is", "mkdoc", "s", "home" ]
70ccf81d3fad974283829ca4ec069a873341461d
https://github.com/entrepreneur-interet-general/mkinx/blob/70ccf81d3fad974283829ca4ec069a873341461d/mkinx/utils.py#L74-L99
train
64,749
entrepreneur-interet-general/mkinx
mkinx/utils.py
get_listed_projects
def get_listed_projects(): """Find the projects listed in the Home Documentation's index.md file Returns: set(str): projects' names, with the '/' in their beginings """ index_path = Path().resolve() / "docs" / "index.md" with open(index_path, "r") as index_file: lines = index_fi...
python
def get_listed_projects(): """Find the projects listed in the Home Documentation's index.md file Returns: set(str): projects' names, with the '/' in their beginings """ index_path = Path().resolve() / "docs" / "index.md" with open(index_path, "r") as index_file: lines = index_fi...
[ "def", "get_listed_projects", "(", ")", ":", "index_path", "=", "Path", "(", ")", ".", "resolve", "(", ")", "/", "\"docs\"", "/", "\"index.md\"", "with", "open", "(", "index_path", ",", "\"r\"", ")", "as", "index_file", ":", "lines", "=", "index_file", "...
Find the projects listed in the Home Documentation's index.md file Returns: set(str): projects' names, with the '/' in their beginings
[ "Find", "the", "projects", "listed", "in", "the", "Home", "Documentation", "s", "index", ".", "md", "file" ]
70ccf81d3fad974283829ca4ec069a873341461d
https://github.com/entrepreneur-interet-general/mkinx/blob/70ccf81d3fad974283829ca4ec069a873341461d/mkinx/utils.py#L102-L133
train
64,750
entrepreneur-interet-general/mkinx
mkinx/utils.py
make_offline
def make_offline(): """Deletes references to the external google fonts in the Home Documentation's index.html file """ dir_path = Path(os.getcwd()).absolute() css_path = dir_path / "site" / "assets" / "stylesheets" material_css = css_path / "material-style.css" if not material_css.exists():...
python
def make_offline(): """Deletes references to the external google fonts in the Home Documentation's index.html file """ dir_path = Path(os.getcwd()).absolute() css_path = dir_path / "site" / "assets" / "stylesheets" material_css = css_path / "material-style.css" if not material_css.exists():...
[ "def", "make_offline", "(", ")", ":", "dir_path", "=", "Path", "(", "os", ".", "getcwd", "(", ")", ")", ".", "absolute", "(", ")", "css_path", "=", "dir_path", "/", "\"site\"", "/", "\"assets\"", "/", "\"stylesheets\"", "material_css", "=", "css_path", "...
Deletes references to the external google fonts in the Home Documentation's index.html file
[ "Deletes", "references", "to", "the", "external", "google", "fonts", "in", "the", "Home", "Documentation", "s", "index", ".", "html", "file" ]
70ccf81d3fad974283829ca4ec069a873341461d
https://github.com/entrepreneur-interet-general/mkinx/blob/70ccf81d3fad974283829ca4ec069a873341461d/mkinx/utils.py#L197-L215
train
64,751
alimanfoo/vcfnp
vcfnp/array.py
_filenames_from_arg
def _filenames_from_arg(filename): """Utility function to deal with polymorphic filenames argument.""" if isinstance(filename, string_types): filenames = [filename] elif isinstance(filename, (list, tuple)): filenames = filename else: raise Exception('filename argument must be str...
python
def _filenames_from_arg(filename): """Utility function to deal with polymorphic filenames argument.""" if isinstance(filename, string_types): filenames = [filename] elif isinstance(filename, (list, tuple)): filenames = filename else: raise Exception('filename argument must be str...
[ "def", "_filenames_from_arg", "(", "filename", ")", ":", "if", "isinstance", "(", "filename", ",", "string_types", ")", ":", "filenames", "=", "[", "filename", "]", "elif", "isinstance", "(", "filename", ",", "(", "list", ",", "tuple", ")", ")", ":", "fi...
Utility function to deal with polymorphic filenames argument.
[ "Utility", "function", "to", "deal", "with", "polymorphic", "filenames", "argument", "." ]
c3f63fb11ada56d4a88076c61c81f99b8ee78b8f
https://github.com/alimanfoo/vcfnp/blob/c3f63fb11ada56d4a88076c61c81f99b8ee78b8f/vcfnp/array.py#L203-L216
train
64,752
alimanfoo/vcfnp
vcfnp/array.py
_get_cache
def _get_cache(vcf_fn, array_type, region, cachedir, compress, log): """Utility function to obtain a cache file name and determine whether or not a fresh cache file is available.""" # guard condition if isinstance(vcf_fn, (list, tuple)): raise Exception( 'caching only supported when...
python
def _get_cache(vcf_fn, array_type, region, cachedir, compress, log): """Utility function to obtain a cache file name and determine whether or not a fresh cache file is available.""" # guard condition if isinstance(vcf_fn, (list, tuple)): raise Exception( 'caching only supported when...
[ "def", "_get_cache", "(", "vcf_fn", ",", "array_type", ",", "region", ",", "cachedir", ",", "compress", ",", "log", ")", ":", "# guard condition", "if", "isinstance", "(", "vcf_fn", ",", "(", "list", ",", "tuple", ")", ")", ":", "raise", "Exception", "("...
Utility function to obtain a cache file name and determine whether or not a fresh cache file is available.
[ "Utility", "function", "to", "obtain", "a", "cache", "file", "name", "and", "determine", "whether", "or", "not", "a", "fresh", "cache", "file", "is", "available", "." ]
c3f63fb11ada56d4a88076c61c81f99b8ee78b8f
https://github.com/alimanfoo/vcfnp/blob/c3f63fb11ada56d4a88076c61c81f99b8ee78b8f/vcfnp/array.py#L285-L311
train
64,753
alimanfoo/vcfnp
vcfnp/array.py
_variants_fields
def _variants_fields(fields, exclude_fields, info_ids): """Utility function to determine which fields to extract when loading variants.""" if fields is None: # no fields specified by user # by default extract all standard and INFO fields fields = config.STANDARD_VARIANT_FIELDS + info...
python
def _variants_fields(fields, exclude_fields, info_ids): """Utility function to determine which fields to extract when loading variants.""" if fields is None: # no fields specified by user # by default extract all standard and INFO fields fields = config.STANDARD_VARIANT_FIELDS + info...
[ "def", "_variants_fields", "(", "fields", ",", "exclude_fields", ",", "info_ids", ")", ":", "if", "fields", "is", "None", ":", "# no fields specified by user", "# by default extract all standard and INFO fields", "fields", "=", "config", ".", "STANDARD_VARIANT_FIELDS", "+...
Utility function to determine which fields to extract when loading variants.
[ "Utility", "function", "to", "determine", "which", "fields", "to", "extract", "when", "loading", "variants", "." ]
c3f63fb11ada56d4a88076c61c81f99b8ee78b8f
https://github.com/alimanfoo/vcfnp/blob/c3f63fb11ada56d4a88076c61c81f99b8ee78b8f/vcfnp/array.py#L413-L432
train
64,754
alimanfoo/vcfnp
vcfnp/array.py
_variants_fills
def _variants_fills(fields, fills, info_types): """Utility function to determine fill values for variants fields with missing values.""" if fills is None: # no fills specified by user fills = dict() for f, vcf_type in zip(fields, info_types): if f == 'FILTER': fills[f...
python
def _variants_fills(fields, fills, info_types): """Utility function to determine fill values for variants fields with missing values.""" if fills is None: # no fills specified by user fills = dict() for f, vcf_type in zip(fields, info_types): if f == 'FILTER': fills[f...
[ "def", "_variants_fills", "(", "fields", ",", "fills", ",", "info_types", ")", ":", "if", "fills", "is", "None", ":", "# no fills specified by user", "fills", "=", "dict", "(", ")", "for", "f", ",", "vcf_type", "in", "zip", "(", "fields", ",", "info_types"...
Utility function to determine fill values for variants fields with missing values.
[ "Utility", "function", "to", "determine", "fill", "values", "for", "variants", "fields", "with", "missing", "values", "." ]
c3f63fb11ada56d4a88076c61c81f99b8ee78b8f
https://github.com/alimanfoo/vcfnp/blob/c3f63fb11ada56d4a88076c61c81f99b8ee78b8f/vcfnp/array.py#L462-L478
train
64,755
alimanfoo/vcfnp
vcfnp/array.py
_info_transformers
def _info_transformers(fields, transformers): """Utility function to determine transformer functions for variants fields.""" if transformers is None: # no transformers specified by user transformers = dict() for f in fields: if f not in transformers: transformers[f] =...
python
def _info_transformers(fields, transformers): """Utility function to determine transformer functions for variants fields.""" if transformers is None: # no transformers specified by user transformers = dict() for f in fields: if f not in transformers: transformers[f] =...
[ "def", "_info_transformers", "(", "fields", ",", "transformers", ")", ":", "if", "transformers", "is", "None", ":", "# no transformers specified by user", "transformers", "=", "dict", "(", ")", "for", "f", "in", "fields", ":", "if", "f", "not", "in", "transfor...
Utility function to determine transformer functions for variants fields.
[ "Utility", "function", "to", "determine", "transformer", "functions", "for", "variants", "fields", "." ]
c3f63fb11ada56d4a88076c61c81f99b8ee78b8f
https://github.com/alimanfoo/vcfnp/blob/c3f63fb11ada56d4a88076c61c81f99b8ee78b8f/vcfnp/array.py#L481-L490
train
64,756
alimanfoo/vcfnp
vcfnp/array.py
_variants_dtype
def _variants_dtype(fields, dtypes, arities, filter_ids, flatten_filter, info_types): """Utility function to build a numpy dtype for a variants array, given user arguments and information available from VCF header.""" dtype = list() for f, n, vcf_type in zip(fields, arities, info_typ...
python
def _variants_dtype(fields, dtypes, arities, filter_ids, flatten_filter, info_types): """Utility function to build a numpy dtype for a variants array, given user arguments and information available from VCF header.""" dtype = list() for f, n, vcf_type in zip(fields, arities, info_typ...
[ "def", "_variants_dtype", "(", "fields", ",", "dtypes", ",", "arities", ",", "filter_ids", ",", "flatten_filter", ",", "info_types", ")", ":", "dtype", "=", "list", "(", ")", "for", "f", ",", "n", ",", "vcf_type", "in", "zip", "(", "fields", ",", "arit...
Utility function to build a numpy dtype for a variants array, given user arguments and information available from VCF header.
[ "Utility", "function", "to", "build", "a", "numpy", "dtype", "for", "a", "variants", "array", "given", "user", "arguments", "and", "information", "available", "from", "VCF", "header", "." ]
c3f63fb11ada56d4a88076c61c81f99b8ee78b8f
https://github.com/alimanfoo/vcfnp/blob/c3f63fb11ada56d4a88076c61c81f99b8ee78b8f/vcfnp/array.py#L493-L524
train
64,757
alimanfoo/vcfnp
vcfnp/array.py
_fromiter
def _fromiter(it, dtype, count, progress, log): """Utility function to load an array from an iterator.""" if progress > 0: it = _iter_withprogress(it, progress, log) if count is not None: a = np.fromiter(it, dtype=dtype, count=count) else: a = np.fromiter(it, dtype=dtype) ret...
python
def _fromiter(it, dtype, count, progress, log): """Utility function to load an array from an iterator.""" if progress > 0: it = _iter_withprogress(it, progress, log) if count is not None: a = np.fromiter(it, dtype=dtype, count=count) else: a = np.fromiter(it, dtype=dtype) ret...
[ "def", "_fromiter", "(", "it", ",", "dtype", ",", "count", ",", "progress", ",", "log", ")", ":", "if", "progress", ">", "0", ":", "it", "=", "_iter_withprogress", "(", "it", ",", "progress", ",", "log", ")", "if", "count", "is", "not", "None", ":"...
Utility function to load an array from an iterator.
[ "Utility", "function", "to", "load", "an", "array", "from", "an", "iterator", "." ]
c3f63fb11ada56d4a88076c61c81f99b8ee78b8f
https://github.com/alimanfoo/vcfnp/blob/c3f63fb11ada56d4a88076c61c81f99b8ee78b8f/vcfnp/array.py#L527-L535
train
64,758
alimanfoo/vcfnp
vcfnp/array.py
_iter_withprogress
def _iter_withprogress(iterable, progress, log): """Utility function to load an array from an iterator, reporting progress as we go.""" before_all = time.time() before = before_all n = 0 for i, o in enumerate(iterable): yield o n = i+1 if n % progress == 0: af...
python
def _iter_withprogress(iterable, progress, log): """Utility function to load an array from an iterator, reporting progress as we go.""" before_all = time.time() before = before_all n = 0 for i, o in enumerate(iterable): yield o n = i+1 if n % progress == 0: af...
[ "def", "_iter_withprogress", "(", "iterable", ",", "progress", ",", "log", ")", ":", "before_all", "=", "time", ".", "time", "(", ")", "before", "=", "before_all", "n", "=", "0", "for", "i", ",", "o", "in", "enumerate", "(", "iterable", ")", ":", "yi...
Utility function to load an array from an iterator, reporting progress as we go.
[ "Utility", "function", "to", "load", "an", "array", "from", "an", "iterator", "reporting", "progress", "as", "we", "go", "." ]
c3f63fb11ada56d4a88076c61c81f99b8ee78b8f
https://github.com/alimanfoo/vcfnp/blob/c3f63fb11ada56d4a88076c61c81f99b8ee78b8f/vcfnp/array.py#L538-L554
train
64,759
alimanfoo/vcfnp
vcfnp/array.py
calldata
def calldata(vcf_fn, region=None, samples=None, ploidy=2, fields=None, exclude_fields=None, dtypes=None, arities=None, fills=None, vcf_types=None, count=None, progress=0, logstream=None, condition=None, slice_args=None, verbose=True, cache=False, cachedir=None, skip_c...
python
def calldata(vcf_fn, region=None, samples=None, ploidy=2, fields=None, exclude_fields=None, dtypes=None, arities=None, fills=None, vcf_types=None, count=None, progress=0, logstream=None, condition=None, slice_args=None, verbose=True, cache=False, cachedir=None, skip_c...
[ "def", "calldata", "(", "vcf_fn", ",", "region", "=", "None", ",", "samples", "=", "None", ",", "ploidy", "=", "2", ",", "fields", "=", "None", ",", "exclude_fields", "=", "None", ",", "dtypes", "=", "None", ",", "arities", "=", "None", ",", "fills",...
Load a numpy 1-dimensional structured array with data from the sample columns of a VCF file. Parameters ---------- vcf_fn: string or list Name of the VCF file or list of file names. region: string Region to extract, e.g., 'chr1' or 'chr1:0-100000'. fields: list or array-like ...
[ "Load", "a", "numpy", "1", "-", "dimensional", "structured", "array", "with", "data", "from", "the", "sample", "columns", "of", "a", "VCF", "file", "." ]
c3f63fb11ada56d4a88076c61c81f99b8ee78b8f
https://github.com/alimanfoo/vcfnp/blob/c3f63fb11ada56d4a88076c61c81f99b8ee78b8f/vcfnp/array.py#L557-L718
train
64,760
myyang/django-unixtimestampfield
unixtimestampfield/fields.py
TimestampPatchMixin.get_datetimenow
def get_datetimenow(self): """ get datetime now according to USE_TZ and default time """ value = timezone.datetime.utcnow() if settings.USE_TZ: value = timezone.localtime( timezone.make_aware(value, timezone.utc), timezone.get_default_t...
python
def get_datetimenow(self): """ get datetime now according to USE_TZ and default time """ value = timezone.datetime.utcnow() if settings.USE_TZ: value = timezone.localtime( timezone.make_aware(value, timezone.utc), timezone.get_default_t...
[ "def", "get_datetimenow", "(", "self", ")", ":", "value", "=", "timezone", ".", "datetime", ".", "utcnow", "(", ")", "if", "settings", ".", "USE_TZ", ":", "value", "=", "timezone", ".", "localtime", "(", "timezone", ".", "make_aware", "(", "value", ",", ...
get datetime now according to USE_TZ and default time
[ "get", "datetime", "now", "according", "to", "USE_TZ", "and", "default", "time" ]
d647681cd628d1a5cdde8dcbb025bcb9612e9b24
https://github.com/myyang/django-unixtimestampfield/blob/d647681cd628d1a5cdde8dcbb025bcb9612e9b24/unixtimestampfield/fields.py#L87-L97
train
64,761
myyang/django-unixtimestampfield
unixtimestampfield/fields.py
TimestampPatchMixin.to_default_timezone_datetime
def to_default_timezone_datetime(self, value): """ convert to default timezone datetime """ return timezone.localtime(self.to_utc_datetime(value), timezone.get_default_timezone())
python
def to_default_timezone_datetime(self, value): """ convert to default timezone datetime """ return timezone.localtime(self.to_utc_datetime(value), timezone.get_default_timezone())
[ "def", "to_default_timezone_datetime", "(", "self", ",", "value", ")", ":", "return", "timezone", ".", "localtime", "(", "self", ".", "to_utc_datetime", "(", "value", ")", ",", "timezone", ".", "get_default_timezone", "(", ")", ")" ]
convert to default timezone datetime
[ "convert", "to", "default", "timezone", "datetime" ]
d647681cd628d1a5cdde8dcbb025bcb9612e9b24
https://github.com/myyang/django-unixtimestampfield/blob/d647681cd628d1a5cdde8dcbb025bcb9612e9b24/unixtimestampfield/fields.py#L165-L169
train
64,762
Oneiroe/PySimpleAutomata
PySimpleAutomata/automata_IO.py
dfa_json_importer
def dfa_json_importer(input_file: str) -> dict: """ Imports a DFA from a JSON file. :param str input_file: path + filename to json file; :return: *(dict)* representing a DFA. """ file = open(input_file) json_file = json.load(file) transitions = {} # key [state ∈ states, action ∈ alphabet]...
python
def dfa_json_importer(input_file: str) -> dict: """ Imports a DFA from a JSON file. :param str input_file: path + filename to json file; :return: *(dict)* representing a DFA. """ file = open(input_file) json_file = json.load(file) transitions = {} # key [state ∈ states, action ∈ alphabet]...
[ "def", "dfa_json_importer", "(", "input_file", ":", "str", ")", "->", "dict", ":", "file", "=", "open", "(", "input_file", ")", "json_file", "=", "json", ".", "load", "(", "file", ")", "transitions", "=", "{", "}", "# key [state ∈ states, action ∈ alphabet]", ...
Imports a DFA from a JSON file. :param str input_file: path + filename to json file; :return: *(dict)* representing a DFA.
[ "Imports", "a", "DFA", "from", "a", "JSON", "file", "." ]
0f9f2705fd8ddd5d8118bc31552a640f5d00c359
https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/automata_IO.py#L29-L50
train
64,763
Oneiroe/PySimpleAutomata
PySimpleAutomata/automata_IO.py
dfa_to_json
def dfa_to_json(dfa: dict, name: str, path: str = './'): """ Exports a DFA to a JSON file. If *path* do not exists, it will be created. :param dict dfa: DFA to export; :param str name: name of the output file; :param str path: path where to save the JSON file (default: working...
python
def dfa_to_json(dfa: dict, name: str, path: str = './'): """ Exports a DFA to a JSON file. If *path* do not exists, it will be created. :param dict dfa: DFA to export; :param str name: name of the output file; :param str path: path where to save the JSON file (default: working...
[ "def", "dfa_to_json", "(", "dfa", ":", "dict", ",", "name", ":", "str", ",", "path", ":", "str", "=", "'./'", ")", ":", "out", "=", "{", "'alphabet'", ":", "list", "(", "dfa", "[", "'alphabet'", "]", ")", ",", "'states'", ":", "list", "(", "dfa",...
Exports a DFA to a JSON file. If *path* do not exists, it will be created. :param dict dfa: DFA to export; :param str name: name of the output file; :param str path: path where to save the JSON file (default: working directory)
[ "Exports", "a", "DFA", "to", "a", "JSON", "file", "." ]
0f9f2705fd8ddd5d8118bc31552a640f5d00c359
https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/automata_IO.py#L53-L79
train
64,764
Oneiroe/PySimpleAutomata
PySimpleAutomata/automata_IO.py
dfa_dot_importer
def dfa_dot_importer(input_file: str) -> dict: """ Imports a DFA from a DOT file. Of DOT files are recognized the following attributes: • nodeX shape=doublecircle -> accepting node; • nodeX root=true -> initial node; • edgeX label="a" -> action in alphabet; • fake [style=invis...
python
def dfa_dot_importer(input_file: str) -> dict: """ Imports a DFA from a DOT file. Of DOT files are recognized the following attributes: • nodeX shape=doublecircle -> accepting node; • nodeX root=true -> initial node; • edgeX label="a" -> action in alphabet; • fake [style=invis...
[ "def", "dfa_dot_importer", "(", "input_file", ":", "str", ")", "->", "dict", ":", "# pyDot Object", "g", "=", "pydot", ".", "graph_from_dot_file", "(", "input_file", ")", "[", "0", "]", "states", "=", "set", "(", ")", "initial_state", "=", "None", "accepti...
Imports a DFA from a DOT file. Of DOT files are recognized the following attributes: • nodeX shape=doublecircle -> accepting node; • nodeX root=true -> initial node; • edgeX label="a" -> action in alphabet; • fake [style=invisible] -> dummy invisible node pointing ...
[ "Imports", "a", "DFA", "from", "a", "DOT", "file", "." ]
0f9f2705fd8ddd5d8118bc31552a640f5d00c359
https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/automata_IO.py#L82-L171
train
64,765
Oneiroe/PySimpleAutomata
PySimpleAutomata/automata_IO.py
nfa_json_importer
def nfa_json_importer(input_file: str) -> dict: """ Imports a NFA from a JSON file. :param str input_file: path+filename to JSON file; :return: *(dict)* representing a NFA. """ file = open(input_file) json_file = json.load(file) transitions = {} # key [state in states, action in alphabet]...
python
def nfa_json_importer(input_file: str) -> dict: """ Imports a NFA from a JSON file. :param str input_file: path+filename to JSON file; :return: *(dict)* representing a NFA. """ file = open(input_file) json_file = json.load(file) transitions = {} # key [state in states, action in alphabet]...
[ "def", "nfa_json_importer", "(", "input_file", ":", "str", ")", "->", "dict", ":", "file", "=", "open", "(", "input_file", ")", "json_file", "=", "json", ".", "load", "(", "file", ")", "transitions", "=", "{", "}", "# key [state in states, action in alphabet]"...
Imports a NFA from a JSON file. :param str input_file: path+filename to JSON file; :return: *(dict)* representing a NFA.
[ "Imports", "a", "NFA", "from", "a", "JSON", "file", "." ]
0f9f2705fd8ddd5d8118bc31552a640f5d00c359
https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/automata_IO.py#L227-L249
train
64,766
Oneiroe/PySimpleAutomata
PySimpleAutomata/automata_IO.py
nfa_to_json
def nfa_to_json(nfa: dict, name: str, path: str = './'): """ Exports a NFA to a JSON file. :param dict nfa: NFA to export; :param str name: name of the output file; :param str path: path where to save the JSON file (default: working directory). """ transitions = list() # k...
python
def nfa_to_json(nfa: dict, name: str, path: str = './'): """ Exports a NFA to a JSON file. :param dict nfa: NFA to export; :param str name: name of the output file; :param str path: path where to save the JSON file (default: working directory). """ transitions = list() # k...
[ "def", "nfa_to_json", "(", "nfa", ":", "dict", ",", "name", ":", "str", ",", "path", ":", "str", "=", "'./'", ")", ":", "transitions", "=", "list", "(", ")", "# key[state in states, action in alphabet]", "# value [Set of arriving states in states...
Exports a NFA to a JSON file. :param dict nfa: NFA to export; :param str name: name of the output file; :param str path: path where to save the JSON file (default: working directory).
[ "Exports", "a", "NFA", "to", "a", "JSON", "file", "." ]
0f9f2705fd8ddd5d8118bc31552a640f5d00c359
https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/automata_IO.py#L252-L278
train
64,767
Oneiroe/PySimpleAutomata
PySimpleAutomata/automata_IO.py
nfa_dot_importer
def nfa_dot_importer(input_file: str) -> dict: """ Imports a NFA from a DOT file. Of .dot files are recognized the following attributes • nodeX shape=doublecircle -> accepting node; • nodeX root=true -> initial node; • edgeX label="a" -> action in alphabet; • fakeX style=invisi...
python
def nfa_dot_importer(input_file: str) -> dict: """ Imports a NFA from a DOT file. Of .dot files are recognized the following attributes • nodeX shape=doublecircle -> accepting node; • nodeX root=true -> initial node; • edgeX label="a" -> action in alphabet; • fakeX style=invisi...
[ "def", "nfa_dot_importer", "(", "input_file", ":", "str", ")", "->", "dict", ":", "# pyDot Object", "g", "=", "pydot", ".", "graph_from_dot_file", "(", "input_file", ")", "[", "0", "]", "states", "=", "set", "(", ")", "initial_states", "=", "set", "(", "...
Imports a NFA from a DOT file. Of .dot files are recognized the following attributes • nodeX shape=doublecircle -> accepting node; • nodeX root=true -> initial node; • edgeX label="a" -> action in alphabet; • fakeX style=invisible -> dummy invisible nodes pointing t...
[ "Imports", "a", "NFA", "from", "a", "DOT", "file", "." ]
0f9f2705fd8ddd5d8118bc31552a640f5d00c359
https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/automata_IO.py#L281-L378
train
64,768
Oneiroe/PySimpleAutomata
PySimpleAutomata/automata_IO.py
afw_json_importer
def afw_json_importer(input_file: str) -> dict: """ Imports a AFW from a JSON file. :param str input_file: path+filename to input JSON file; :return: *(dict)* representing a AFW. """ file = open(input_file) json_file = json.load(file) transitions = {} # key [state in states, action in alp...
python
def afw_json_importer(input_file: str) -> dict: """ Imports a AFW from a JSON file. :param str input_file: path+filename to input JSON file; :return: *(dict)* representing a AFW. """ file = open(input_file) json_file = json.load(file) transitions = {} # key [state in states, action in alp...
[ "def", "afw_json_importer", "(", "input_file", ":", "str", ")", "->", "dict", ":", "file", "=", "open", "(", "input_file", ")", "json_file", "=", "json", ".", "load", "(", "file", ")", "transitions", "=", "{", "}", "# key [state in states, action in alphabet]"...
Imports a AFW from a JSON file. :param str input_file: path+filename to input JSON file; :return: *(dict)* representing a AFW.
[ "Imports", "a", "AFW", "from", "a", "JSON", "file", "." ]
0f9f2705fd8ddd5d8118bc31552a640f5d00c359
https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/automata_IO.py#L422-L444
train
64,769
Oneiroe/PySimpleAutomata
PySimpleAutomata/AFW.py
__recursive_acceptance
def __recursive_acceptance(afw, state, remaining_word): """ Recursive call for word acceptance. :param dict afw: input AFW; :param str state: current state; :param list remaining_word: list containing the remaining words. :return: *(bool)*, True if the word is accepted, fals...
python
def __recursive_acceptance(afw, state, remaining_word): """ Recursive call for word acceptance. :param dict afw: input AFW; :param str state: current state; :param list remaining_word: list containing the remaining words. :return: *(bool)*, True if the word is accepted, fals...
[ "def", "__recursive_acceptance", "(", "afw", ",", "state", ",", "remaining_word", ")", ":", "# the word is accepted only if all the final states are", "# accepting states", "if", "len", "(", "remaining_word", ")", "==", "0", ":", "if", "state", "in", "afw", "[", "'a...
Recursive call for word acceptance. :param dict afw: input AFW; :param str state: current state; :param list remaining_word: list containing the remaining words. :return: *(bool)*, True if the word is accepted, false otherwise.
[ "Recursive", "call", "for", "word", "acceptance", "." ]
0f9f2705fd8ddd5d8118bc31552a640f5d00c359
https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/AFW.py#L39-L103
train
64,770
Oneiroe/PySimpleAutomata
PySimpleAutomata/AFW.py
afw_completion
def afw_completion(afw): """ Side effect on input! Complete the afw adding not present transitions and marking them as False. :param dict afw: input AFW. """ for state in afw['states']: for a in afw['alphabet']: if (state, a) not in afw['transitions']: afw['tran...
python
def afw_completion(afw): """ Side effect on input! Complete the afw adding not present transitions and marking them as False. :param dict afw: input AFW. """ for state in afw['states']: for a in afw['alphabet']: if (state, a) not in afw['transitions']: afw['tran...
[ "def", "afw_completion", "(", "afw", ")", ":", "for", "state", "in", "afw", "[", "'states'", "]", ":", "for", "a", "in", "afw", "[", "'alphabet'", "]", ":", "if", "(", "state", ",", "a", ")", "not", "in", "afw", "[", "'transitions'", "]", ":", "a...
Side effect on input! Complete the afw adding not present transitions and marking them as False. :param dict afw: input AFW.
[ "Side", "effect", "on", "input!", "Complete", "the", "afw", "adding", "not", "present", "transitions", "and", "marking", "them", "as", "False", "." ]
0f9f2705fd8ddd5d8118bc31552a640f5d00c359
https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/AFW.py#L124-L135
train
64,771
Oneiroe/PySimpleAutomata
PySimpleAutomata/AFW.py
nfa_to_afw_conversion
def nfa_to_afw_conversion(nfa: dict) -> dict: """ Returns a AFW reading the same language of input NFA. Let :math:`A = (Σ,S,S^0, ρ,F)` be an nfa. Then we define the afw AA such that :math:`L(AA) = L(A)` as follows :math:`AA = (Σ, S ∪ {s_0}, s_0 , ρ_A , F )` where :math:`s_0` is a new state and :ma...
python
def nfa_to_afw_conversion(nfa: dict) -> dict: """ Returns a AFW reading the same language of input NFA. Let :math:`A = (Σ,S,S^0, ρ,F)` be an nfa. Then we define the afw AA such that :math:`L(AA) = L(A)` as follows :math:`AA = (Σ, S ∪ {s_0}, s_0 , ρ_A , F )` where :math:`s_0` is a new state and :ma...
[ "def", "nfa_to_afw_conversion", "(", "nfa", ":", "dict", ")", "->", "dict", ":", "afw", "=", "{", "'alphabet'", ":", "nfa", "[", "'alphabet'", "]", ".", "copy", "(", ")", ",", "'states'", ":", "nfa", "[", "'states'", "]", ".", "copy", "(", ")", ","...
Returns a AFW reading the same language of input NFA. Let :math:`A = (Σ,S,S^0, ρ,F)` be an nfa. Then we define the afw AA such that :math:`L(AA) = L(A)` as follows :math:`AA = (Σ, S ∪ {s_0}, s_0 , ρ_A , F )` where :math:`s_0` is a new state and :math:`ρ_A` is defined as follows: • :math:`ρ_A(s, ...
[ "Returns", "a", "AFW", "reading", "the", "same", "language", "of", "input", "NFA", "." ]
0f9f2705fd8ddd5d8118bc31552a640f5d00c359
https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/AFW.py#L138-L187
train
64,772
Oneiroe/PySimpleAutomata
PySimpleAutomata/AFW.py
afw_to_nfa_conversion
def afw_to_nfa_conversion(afw: dict) -> dict: """ Returns a NFA reading the same language of input AFW. Let :math:`A = (Σ, S, s^0 , ρ, F )` be an afw. Then we define the nfa :math:`A_N` such that :math:`L(A_N) = L(A)` as follows :math:`AN = (Σ, S_N , S^0_N , ρ_N , F_N )` where: • :math:`S_N = 2^...
python
def afw_to_nfa_conversion(afw: dict) -> dict: """ Returns a NFA reading the same language of input AFW. Let :math:`A = (Σ, S, s^0 , ρ, F )` be an afw. Then we define the nfa :math:`A_N` such that :math:`L(A_N) = L(A)` as follows :math:`AN = (Σ, S_N , S^0_N , ρ_N , F_N )` where: • :math:`S_N = 2^...
[ "def", "afw_to_nfa_conversion", "(", "afw", ":", "dict", ")", "->", "dict", ":", "nfa", "=", "{", "'alphabet'", ":", "afw", "[", "'alphabet'", "]", ".", "copy", "(", ")", ",", "'initial_states'", ":", "{", "(", "afw", "[", "'initial_state'", "]", ",", ...
Returns a NFA reading the same language of input AFW. Let :math:`A = (Σ, S, s^0 , ρ, F )` be an afw. Then we define the nfa :math:`A_N` such that :math:`L(A_N) = L(A)` as follows :math:`AN = (Σ, S_N , S^0_N , ρ_N , F_N )` where: • :math:`S_N = 2^S` • :math:`S^0_N= \{\{s^0 \}\}` • :math:`F_...
[ "Returns", "a", "NFA", "reading", "the", "same", "language", "of", "input", "AFW", "." ]
0f9f2705fd8ddd5d8118bc31552a640f5d00c359
https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/AFW.py#L190-L259
train
64,773
Oneiroe/PySimpleAutomata
PySimpleAutomata/AFW.py
formula_dual
def formula_dual(input_formula: str) -> str: """ Returns the dual of the input formula. The dual operation on formulas in :math:`B^+(X)` is defined as: the dual :math:`\overline{θ}` of a formula :math:`θ` is obtained from θ by switching :math:`∧` and :math:`∨`, and by switching :math:`true` and :ma...
python
def formula_dual(input_formula: str) -> str: """ Returns the dual of the input formula. The dual operation on formulas in :math:`B^+(X)` is defined as: the dual :math:`\overline{θ}` of a formula :math:`θ` is obtained from θ by switching :math:`∧` and :math:`∨`, and by switching :math:`true` and :ma...
[ "def", "formula_dual", "(", "input_formula", ":", "str", ")", "->", "str", ":", "conversion_dictionary", "=", "{", "'and'", ":", "'or'", ",", "'or'", ":", "'and'", ",", "'True'", ":", "'False'", ",", "'False'", ":", "'True'", "}", "return", "re", ".", ...
Returns the dual of the input formula. The dual operation on formulas in :math:`B^+(X)` is defined as: the dual :math:`\overline{θ}` of a formula :math:`θ` is obtained from θ by switching :math:`∧` and :math:`∨`, and by switching :math:`true` and :math:`false`. :param str input_formula: original s...
[ "Returns", "the", "dual", "of", "the", "input", "formula", "." ]
0f9f2705fd8ddd5d8118bc31552a640f5d00c359
https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/AFW.py#L262-L282
train
64,774
Oneiroe/PySimpleAutomata
PySimpleAutomata/AFW.py
afw_complementation
def afw_complementation(afw: dict) -> dict: """ Returns a AFW reading the complemented language read by input AFW. Let :math:`A = (Σ, S, s^0 , ρ, F )`. Define :math:`Ā = (Σ, S, s^0 , \overline{ρ}, S − F )`, where :math:`\overline{ρ}(s, a) = \overline{ρ(s, a)}` for all :math:`s ∈ S` and :math:`a...
python
def afw_complementation(afw: dict) -> dict: """ Returns a AFW reading the complemented language read by input AFW. Let :math:`A = (Σ, S, s^0 , ρ, F )`. Define :math:`Ā = (Σ, S, s^0 , \overline{ρ}, S − F )`, where :math:`\overline{ρ}(s, a) = \overline{ρ(s, a)}` for all :math:`s ∈ S` and :math:`a...
[ "def", "afw_complementation", "(", "afw", ":", "dict", ")", "->", "dict", ":", "completed_input", "=", "afw_completion", "(", "deepcopy", "(", "afw", ")", ")", "complemented_afw", "=", "{", "'alphabet'", ":", "completed_input", "[", "'alphabet'", "]", ",", "...
Returns a AFW reading the complemented language read by input AFW. Let :math:`A = (Σ, S, s^0 , ρ, F )`. Define :math:`Ā = (Σ, S, s^0 , \overline{ρ}, S − F )`, where :math:`\overline{ρ}(s, a) = \overline{ρ(s, a)}` for all :math:`s ∈ S` and :math:`a ∈ Σ`. That is, :math:`\overline{ρ}` is the dual...
[ "Returns", "a", "AFW", "reading", "the", "complemented", "language", "read", "by", "input", "AFW", "." ]
0f9f2705fd8ddd5d8118bc31552a640f5d00c359
https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/AFW.py#L285-L316
train
64,775
Oneiroe/PySimpleAutomata
PySimpleAutomata/AFW.py
afw_union
def afw_union(afw_1: dict, afw_2: dict) -> dict: """ Returns a AFW that reads the union of the languages read by input AFWs. Let :math:`A_1 = (Σ, S_1 , s^0_1, ρ_1 , F_1 )` and :math:`A_2 = (Σ, S_2 , s^0_2, ρ_2 , F_2 )` be alternating automata accepting the languages :math:`L( A_1)` and :math:`L...
python
def afw_union(afw_1: dict, afw_2: dict) -> dict: """ Returns a AFW that reads the union of the languages read by input AFWs. Let :math:`A_1 = (Σ, S_1 , s^0_1, ρ_1 , F_1 )` and :math:`A_2 = (Σ, S_2 , s^0_2, ρ_2 , F_2 )` be alternating automata accepting the languages :math:`L( A_1)` and :math:`L...
[ "def", "afw_union", "(", "afw_1", ":", "dict", ",", "afw_2", ":", "dict", ")", "->", "dict", ":", "# make sure new root state is unique", "initial_state", "=", "'root'", "i", "=", "0", "while", "initial_state", "in", "afw_1", "[", "'states'", "]", "or", "ini...
Returns a AFW that reads the union of the languages read by input AFWs. Let :math:`A_1 = (Σ, S_1 , s^0_1, ρ_1 , F_1 )` and :math:`A_2 = (Σ, S_2 , s^0_2, ρ_2 , F_2 )` be alternating automata accepting the languages :math:`L( A_1)` and :math:`L(A_2)`. Then, :math:`B_∪ = (Σ, S_1 ∪ S_2 ∪ {root}, ρ_...
[ "Returns", "a", "AFW", "that", "reads", "the", "union", "of", "the", "languages", "read", "by", "input", "AFWs", "." ]
0f9f2705fd8ddd5d8118bc31552a640f5d00c359
https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/AFW.py#L368-L432
train
64,776
Oneiroe/PySimpleAutomata
PySimpleAutomata/AFW.py
afw_intersection
def afw_intersection(afw_1: dict, afw_2: dict) -> dict: """ Returns a AFW that reads the intersection of the languages read by input AFWs. Let :math:`A_1 = (Σ, S_1 , s^0_1, ρ_1 , F_1 )` and :math:`A_2 = (Σ, S_2 , s^0_2, ρ_2 , F_2 )` be alternating automata accepting the languages :math:`L( A_1)...
python
def afw_intersection(afw_1: dict, afw_2: dict) -> dict: """ Returns a AFW that reads the intersection of the languages read by input AFWs. Let :math:`A_1 = (Σ, S_1 , s^0_1, ρ_1 , F_1 )` and :math:`A_2 = (Σ, S_2 , s^0_2, ρ_2 , F_2 )` be alternating automata accepting the languages :math:`L( A_1)...
[ "def", "afw_intersection", "(", "afw_1", ":", "dict", ",", "afw_2", ":", "dict", ")", "->", "dict", ":", "# make sure new root state is unique", "initial_state", "=", "'root'", "i", "=", "0", "while", "initial_state", "in", "afw_1", "[", "'states'", "]", "or",...
Returns a AFW that reads the intersection of the languages read by input AFWs. Let :math:`A_1 = (Σ, S_1 , s^0_1, ρ_1 , F_1 )` and :math:`A_2 = (Σ, S_2 , s^0_2, ρ_2 , F_2 )` be alternating automata accepting the languages :math:`L( A_1)` and :math:`L(A_2)`. Then, :math:`B_∩ = (Σ, S_1 ∪ S_2 ∪ {ro...
[ "Returns", "a", "AFW", "that", "reads", "the", "intersection", "of", "the", "languages", "read", "by", "input", "AFWs", "." ]
0f9f2705fd8ddd5d8118bc31552a640f5d00c359
https://github.com/Oneiroe/PySimpleAutomata/blob/0f9f2705fd8ddd5d8118bc31552a640f5d00c359/PySimpleAutomata/AFW.py#L435-L500
train
64,777
liamw9534/bt-manager
bt_manager/interface.py
translate_to_dbus_type
def translate_to_dbus_type(typeof, value): """ Helper function to map values from their native Python types to Dbus types. :param type typeof: Target for type conversion e.g., 'dbus.Dictionary' :param value: Value to assign using type 'typeof' :return: 'value' converted to type 'typeof' :rt...
python
def translate_to_dbus_type(typeof, value): """ Helper function to map values from their native Python types to Dbus types. :param type typeof: Target for type conversion e.g., 'dbus.Dictionary' :param value: Value to assign using type 'typeof' :return: 'value' converted to type 'typeof' :rt...
[ "def", "translate_to_dbus_type", "(", "typeof", ",", "value", ")", ":", "if", "(", "(", "isinstance", "(", "value", ",", "types", ".", "UnicodeType", ")", "or", "isinstance", "(", "value", ",", "str", ")", ")", "and", "typeof", "is", "not", "dbus", "."...
Helper function to map values from their native Python types to Dbus types. :param type typeof: Target for type conversion e.g., 'dbus.Dictionary' :param value: Value to assign using type 'typeof' :return: 'value' converted to type 'typeof' :rtype: typeof
[ "Helper", "function", "to", "map", "values", "from", "their", "native", "Python", "types", "to", "Dbus", "types", "." ]
51be2919394ce8134c698359649bfad09eedf4ec
https://github.com/liamw9534/bt-manager/blob/51be2919394ce8134c698359649bfad09eedf4ec/bt_manager/interface.py#L10-L26
train
64,778
liamw9534/bt-manager
bt_manager/interface.py
Signal.signal_handler
def signal_handler(self, *args): """ Method to call in order to invoke the user callback. :param args: list of signal-dependent arguments :return: """ self.user_callback(self.signal, self.user_arg, *args)
python
def signal_handler(self, *args): """ Method to call in order to invoke the user callback. :param args: list of signal-dependent arguments :return: """ self.user_callback(self.signal, self.user_arg, *args)
[ "def", "signal_handler", "(", "self", ",", "*", "args", ")", ":", "self", ".", "user_callback", "(", "self", ".", "signal", ",", "self", ".", "user_arg", ",", "*", "args", ")" ]
Method to call in order to invoke the user callback. :param args: list of signal-dependent arguments :return:
[ "Method", "to", "call", "in", "order", "to", "invoke", "the", "user", "callback", "." ]
51be2919394ce8134c698359649bfad09eedf4ec
https://github.com/liamw9534/bt-manager/blob/51be2919394ce8134c698359649bfad09eedf4ec/bt_manager/interface.py#L46-L53
train
64,779
liamw9534/bt-manager
bt_manager/interface.py
BTInterface.get_property
def get_property(self, name=None): """ Helper to get a property value by name or all properties as a dictionary. See also :py:meth:`set_property` :param str name: defaults to None which means all properties in the object's dictionary are returned as a dict. ...
python
def get_property(self, name=None): """ Helper to get a property value by name or all properties as a dictionary. See also :py:meth:`set_property` :param str name: defaults to None which means all properties in the object's dictionary are returned as a dict. ...
[ "def", "get_property", "(", "self", ",", "name", "=", "None", ")", ":", "if", "(", "name", ")", ":", "return", "self", ".", "_interface", ".", "GetProperties", "(", ")", "[", "name", "]", "else", ":", "return", "self", ".", "_interface", ".", "GetPro...
Helper to get a property value by name or all properties as a dictionary. See also :py:meth:`set_property` :param str name: defaults to None which means all properties in the object's dictionary are returned as a dict. Otherwise, the property name key is used and its va...
[ "Helper", "to", "get", "a", "property", "value", "by", "name", "or", "all", "properties", "as", "a", "dictionary", "." ]
51be2919394ce8134c698359649bfad09eedf4ec
https://github.com/liamw9534/bt-manager/blob/51be2919394ce8134c698359649bfad09eedf4ec/bt_manager/interface.py#L170-L191
train
64,780
liamw9534/bt-manager
bt_manager/interface.py
BTInterface.set_property
def set_property(self, name, value): """ Helper to set a property value by name, translating to correct dbus type See also :py:meth:`get_property` :param str name: The property name in the object's dictionary whose value shall be set. :param value: Propertie...
python
def set_property(self, name, value): """ Helper to set a property value by name, translating to correct dbus type See also :py:meth:`get_property` :param str name: The property name in the object's dictionary whose value shall be set. :param value: Propertie...
[ "def", "set_property", "(", "self", ",", "name", ",", "value", ")", ":", "typeof", "=", "type", "(", "self", ".", "get_property", "(", "name", ")", ")", "self", ".", "_interface", ".", "SetProperty", "(", "name", ",", "translate_to_dbus_type", "(", "type...
Helper to set a property value by name, translating to correct dbus type See also :py:meth:`get_property` :param str name: The property name in the object's dictionary whose value shall be set. :param value: Properties new value to be assigned. :return: :rai...
[ "Helper", "to", "set", "a", "property", "value", "by", "name", "translating", "to", "correct", "dbus", "type" ]
51be2919394ce8134c698359649bfad09eedf4ec
https://github.com/liamw9534/bt-manager/blob/51be2919394ce8134c698359649bfad09eedf4ec/bt_manager/interface.py#L193-L211
train
64,781
pavlov99/jsonapi
jsonapi/serializers.py
DatetimeDecimalEncoder.default
def default(self, o): """ Encode JSON. :return str: A JSON encoded string """ if isinstance(o, (datetime.datetime, datetime.date, datetime.time)): return o.isoformat() if isinstance(o, decimal.Decimal): return float(o) return json.JSONEncoder.d...
python
def default(self, o): """ Encode JSON. :return str: A JSON encoded string """ if isinstance(o, (datetime.datetime, datetime.date, datetime.time)): return o.isoformat() if isinstance(o, decimal.Decimal): return float(o) return json.JSONEncoder.d...
[ "def", "default", "(", "self", ",", "o", ")", ":", "if", "isinstance", "(", "o", ",", "(", "datetime", ".", "datetime", ",", "datetime", ".", "date", ",", "datetime", ".", "time", ")", ")", ":", "return", "o", ".", "isoformat", "(", ")", "if", "i...
Encode JSON. :return str: A JSON encoded string
[ "Encode", "JSON", "." ]
c27943f22f1f1d30d651fe267a99d2b38f69d604
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/serializers.py#L17-L29
train
64,782
pavlov99/jsonapi
jsonapi/serializers.py
Serializer.dump_document
def dump_document(cls, instance, fields_own=None, fields_to_many=None): """ Get document for model_instance. redefine dump rule for field x: def dump_document_x :param django.db.models.Model instance: model instance :param list<Field> or None fields: model_instance field to dump ...
python
def dump_document(cls, instance, fields_own=None, fields_to_many=None): """ Get document for model_instance. redefine dump rule for field x: def dump_document_x :param django.db.models.Model instance: model instance :param list<Field> or None fields: model_instance field to dump ...
[ "def", "dump_document", "(", "cls", ",", "instance", ",", "fields_own", "=", "None", ",", "fields_to_many", "=", "None", ")", ":", "if", "fields_own", "is", "not", "None", ":", "fields_own", "=", "{", "f", ".", "name", "for", "f", "in", "fields_own", "...
Get document for model_instance. redefine dump rule for field x: def dump_document_x :param django.db.models.Model instance: model instance :param list<Field> or None fields: model_instance field to dump :return dict: document Related documents are not included to current one....
[ "Get", "document", "for", "model_instance", "." ]
c27943f22f1f1d30d651fe267a99d2b38f69d604
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/serializers.py#L66-L148
train
64,783
pavlov99/jsonapi
jsonapi/utils.py
_cached
def _cached(f): """ Decorator that makes a method cached.""" attr_name = '_cached_' + f.__name__ def wrapper(obj, *args, **kwargs): if not hasattr(obj, attr_name): setattr(obj, attr_name, f(obj, *args, **kwargs)) return getattr(obj, attr_name) return wrapper
python
def _cached(f): """ Decorator that makes a method cached.""" attr_name = '_cached_' + f.__name__ def wrapper(obj, *args, **kwargs): if not hasattr(obj, attr_name): setattr(obj, attr_name, f(obj, *args, **kwargs)) return getattr(obj, attr_name) return wrapper
[ "def", "_cached", "(", "f", ")", ":", "attr_name", "=", "'_cached_'", "+", "f", ".", "__name__", "def", "wrapper", "(", "obj", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "hasattr", "(", "obj", ",", "attr_name", ")", ":", "s...
Decorator that makes a method cached.
[ "Decorator", "that", "makes", "a", "method", "cached", "." ]
c27943f22f1f1d30d651fe267a99d2b38f69d604
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/utils.py#L21-L30
train
64,784
pavlov99/jsonapi
jsonapi/model_inspector.py
ModelInspector._filter_child_model_fields
def _filter_child_model_fields(cls, fields): """ Keep only related model fields. Example: Inherited models: A -> B -> C B has one-to-many relationship to BMany. after inspection BMany would have links to B and C. Keep only B. Parent model A could not be used (It would not be in ...
python
def _filter_child_model_fields(cls, fields): """ Keep only related model fields. Example: Inherited models: A -> B -> C B has one-to-many relationship to BMany. after inspection BMany would have links to B and C. Keep only B. Parent model A could not be used (It would not be in ...
[ "def", "_filter_child_model_fields", "(", "cls", ",", "fields", ")", ":", "indexes_to_remove", "=", "set", "(", "[", "]", ")", "for", "index1", ",", "field1", "in", "enumerate", "(", "fields", ")", ":", "for", "index2", ",", "field2", "in", "enumerate", ...
Keep only related model fields. Example: Inherited models: A -> B -> C B has one-to-many relationship to BMany. after inspection BMany would have links to B and C. Keep only B. Parent model A could not be used (It would not be in fields) :param list fields: model fields. ...
[ "Keep", "only", "related", "model", "fields", "." ]
c27943f22f1f1d30d651fe267a99d2b38f69d604
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/model_inspector.py#L113-L139
train
64,785
python-wink/python-wink
src/pywink/api.py
post_session
def post_session(): """ This endpoint appears to be required in order to keep pubnub updates flowing for some user. This just posts a random nonce to the /users/me/session endpoint and returns the result. """ url_string = "{}/users/me/session".format(WinkApiInterface.BASE_URL) nonce = ''.join...
python
def post_session(): """ This endpoint appears to be required in order to keep pubnub updates flowing for some user. This just posts a random nonce to the /users/me/session endpoint and returns the result. """ url_string = "{}/users/me/session".format(WinkApiInterface.BASE_URL) nonce = ''.join...
[ "def", "post_session", "(", ")", ":", "url_string", "=", "\"{}/users/me/session\"", ".", "format", "(", "WinkApiInterface", ".", "BASE_URL", ")", "nonce", "=", "''", ".", "join", "(", "[", "str", "(", "random", ".", "randint", "(", "0", ",", "9", ")", ...
This endpoint appears to be required in order to keep pubnub updates flowing for some user. This just posts a random nonce to the /users/me/session endpoint and returns the result.
[ "This", "endpoint", "appears", "to", "be", "required", "in", "order", "to", "keep", "pubnub", "updates", "flowing", "for", "some", "user", "." ]
cf8bdce8c6518f30b91b23aa7aa32e89c2ce48da
https://github.com/python-wink/python-wink/blob/cf8bdce8c6518f30b91b23aa7aa32e89c2ce48da/src/pywink/api.py#L464-L483
train
64,786
python-wink/python-wink
src/pywink/api.py
WinkApiInterface.set_device_state
def set_device_state(self, device, state, id_override=None, type_override=None): """ Set device state via online API. Args: device (WinkDevice): The device the change is being requested for. state (Dict): The state being requested. id_override (String, option...
python
def set_device_state(self, device, state, id_override=None, type_override=None): """ Set device state via online API. Args: device (WinkDevice): The device the change is being requested for. state (Dict): The state being requested. id_override (String, option...
[ "def", "set_device_state", "(", "self", ",", "device", ",", "state", ",", "id_override", "=", "None", ",", "type_override", "=", "None", ")", ":", "_LOGGER", ".", "info", "(", "\"Setting state via online API\"", ")", "object_id", "=", "id_override", "or", "dev...
Set device state via online API. Args: device (WinkDevice): The device the change is being requested for. state (Dict): The state being requested. id_override (String, optional): A device ID used to override the passed in device's ID. Used to make changes on ...
[ "Set", "device", "state", "via", "online", "API", "." ]
cf8bdce8c6518f30b91b23aa7aa32e89c2ce48da
https://github.com/python-wink/python-wink/blob/cf8bdce8c6518f30b91b23aa7aa32e89c2ce48da/src/pywink/api.py#L40-L84
train
64,787
python-wink/python-wink
src/pywink/api.py
WinkApiInterface.local_set_state
def local_set_state(self, device, state, id_override=None, type_override=None): """ Set device state via local API, and fall back to online API. Args: device (WinkDevice): The device the change is being requested for. state (Dict): The state being requested. ...
python
def local_set_state(self, device, state, id_override=None, type_override=None): """ Set device state via local API, and fall back to online API. Args: device (WinkDevice): The device the change is being requested for. state (Dict): The state being requested. ...
[ "def", "local_set_state", "(", "self", ",", "device", ",", "state", ",", "id_override", "=", "None", ",", "type_override", "=", "None", ")", ":", "if", "ALLOW_LOCAL_CONTROL", ":", "if", "device", ".", "local_id", "(", ")", "is", "not", "None", ":", "hub"...
Set device state via local API, and fall back to online API. Args: device (WinkDevice): The device the change is being requested for. state (Dict): The state being requested. id_override (String, optional): A device ID used to override the passed in device's ...
[ "Set", "device", "state", "via", "local", "API", "and", "fall", "back", "to", "online", "API", "." ]
cf8bdce8c6518f30b91b23aa7aa32e89c2ce48da
https://github.com/python-wink/python-wink/blob/cf8bdce8c6518f30b91b23aa7aa32e89c2ce48da/src/pywink/api.py#L87-L131
train
64,788
python-wink/python-wink
src/pywink/api.py
WinkApiInterface.get_device_state
def get_device_state(self, device, id_override=None, type_override=None): """ Get device state via online API. Args: device (WinkDevice): The device the change is being requested for. id_override (String, optional): A device ID used to override the passed...
python
def get_device_state(self, device, id_override=None, type_override=None): """ Get device state via online API. Args: device (WinkDevice): The device the change is being requested for. id_override (String, optional): A device ID used to override the passed...
[ "def", "get_device_state", "(", "self", ",", "device", ",", "id_override", "=", "None", ",", "type_override", "=", "None", ")", ":", "_LOGGER", ".", "info", "(", "\"Getting state via online API\"", ")", "object_id", "=", "id_override", "or", "device", ".", "ob...
Get device state via online API. Args: device (WinkDevice): The device the change is being requested for. id_override (String, optional): A device ID used to override the passed in device's ID. Used to make changes on sub-devices. i.e. Outlet in a Powerst...
[ "Get", "device", "state", "via", "online", "API", "." ]
cf8bdce8c6518f30b91b23aa7aa32e89c2ce48da
https://github.com/python-wink/python-wink/blob/cf8bdce8c6518f30b91b23aa7aa32e89c2ce48da/src/pywink/api.py#L133-L155
train
64,789
python-wink/python-wink
src/pywink/api.py
WinkApiInterface.local_get_state
def local_get_state(self, device, id_override=None, type_override=None): """ Get device state via local API, and fall back to online API. Args: device (WinkDevice): The device the change is being requested for. id_override (String, optional): A device ID used to override...
python
def local_get_state(self, device, id_override=None, type_override=None): """ Get device state via local API, and fall back to online API. Args: device (WinkDevice): The device the change is being requested for. id_override (String, optional): A device ID used to override...
[ "def", "local_get_state", "(", "self", ",", "device", ",", "id_override", "=", "None", ",", "type_override", "=", "None", ")", ":", "if", "ALLOW_LOCAL_CONTROL", ":", "if", "device", ".", "local_id", "(", ")", "is", "not", "None", ":", "hub", "=", "HUBS",...
Get device state via local API, and fall back to online API. Args: device (WinkDevice): The device the change is being requested for. id_override (String, optional): A device ID used to override the passed in device's ID. Used to make changes on sub-devices. ...
[ "Get", "device", "state", "via", "local", "API", "and", "fall", "back", "to", "online", "API", "." ]
cf8bdce8c6518f30b91b23aa7aa32e89c2ce48da
https://github.com/python-wink/python-wink/blob/cf8bdce8c6518f30b91b23aa7aa32e89c2ce48da/src/pywink/api.py#L158-L203
train
64,790
python-wink/python-wink
src/pywink/api.py
WinkApiInterface.update_firmware
def update_firmware(self, device, id_override=None, type_override=None): """ Make a call to the update_firmware endpoint. As far as I know this is only valid for Wink hubs. Args: device (WinkDevice): The device the change is being requested for. id_override (Stri...
python
def update_firmware(self, device, id_override=None, type_override=None): """ Make a call to the update_firmware endpoint. As far as I know this is only valid for Wink hubs. Args: device (WinkDevice): The device the change is being requested for. id_override (Stri...
[ "def", "update_firmware", "(", "self", ",", "device", ",", "id_override", "=", "None", ",", "type_override", "=", "None", ")", ":", "object_id", "=", "id_override", "or", "device", ".", "object_id", "(", ")", "object_type", "=", "type_override", "or", "devic...
Make a call to the update_firmware endpoint. As far as I know this is only valid for Wink hubs. Args: device (WinkDevice): The device the change is being requested for. id_override (String, optional): A device ID used to override the passed in device's ID. Used t...
[ "Make", "a", "call", "to", "the", "update_firmware", "endpoint", ".", "As", "far", "as", "I", "know", "this", "is", "only", "valid", "for", "Wink", "hubs", "." ]
cf8bdce8c6518f30b91b23aa7aa32e89c2ce48da
https://github.com/python-wink/python-wink/blob/cf8bdce8c6518f30b91b23aa7aa32e89c2ce48da/src/pywink/api.py#L205-L231
train
64,791
python-wink/python-wink
src/pywink/api.py
WinkApiInterface.remove_device
def remove_device(self, device, id_override=None, type_override=None): """ Remove a device. Args: device (WinkDevice): The device the change is being requested for. id_override (String, optional): A device ID used to override the passed in device's ID. Us...
python
def remove_device(self, device, id_override=None, type_override=None): """ Remove a device. Args: device (WinkDevice): The device the change is being requested for. id_override (String, optional): A device ID used to override the passed in device's ID. Us...
[ "def", "remove_device", "(", "self", ",", "device", ",", "id_override", "=", "None", ",", "type_override", "=", "None", ")", ":", "object_id", "=", "id_override", "or", "device", ".", "object_id", "(", ")", "object_type", "=", "type_override", "or", "device"...
Remove a device. Args: device (WinkDevice): The device the change is being requested for. id_override (String, optional): A device ID used to override the passed in device's ID. Used to make changes on sub-devices. i.e. Outlet in a Powerstrip. The Parent ...
[ "Remove", "a", "device", "." ]
cf8bdce8c6518f30b91b23aa7aa32e89c2ce48da
https://github.com/python-wink/python-wink/blob/cf8bdce8c6518f30b91b23aa7aa32e89c2ce48da/src/pywink/api.py#L233-L262
train
64,792
python-wink/python-wink
src/pywink/api.py
WinkApiInterface.create_lock_key
def create_lock_key(self, device, new_device_json, id_override=None, type_override=None): """ Create a new lock key code. Args: device (WinkDevice): The device the change is being requested for. new_device_json (String): The JSON string required to create the device. ...
python
def create_lock_key(self, device, new_device_json, id_override=None, type_override=None): """ Create a new lock key code. Args: device (WinkDevice): The device the change is being requested for. new_device_json (String): The JSON string required to create the device. ...
[ "def", "create_lock_key", "(", "self", ",", "device", ",", "new_device_json", ",", "id_override", "=", "None", ",", "type_override", "=", "None", ")", ":", "object_id", "=", "id_override", "or", "device", ".", "object_id", "(", ")", "object_type", "=", "type...
Create a new lock key code. Args: device (WinkDevice): The device the change is being requested for. new_device_json (String): The JSON string required to create the device. id_override (String, optional): A device ID used to override the passed in device's I...
[ "Create", "a", "new", "lock", "key", "code", "." ]
cf8bdce8c6518f30b91b23aa7aa32e89c2ce48da
https://github.com/python-wink/python-wink/blob/cf8bdce8c6518f30b91b23aa7aa32e89c2ce48da/src/pywink/api.py#L264-L291
train
64,793
pavlov99/jsonapi
jsonapi/resource.py
get_concrete_model
def get_concrete_model(model): """ Get model defined in Meta. :param str or django.db.models.Model model: :return: model or None :rtype django.db.models.Model or None: :raise ValueError: model is not found or abstract """ if not(inspect.isclass(model) and issubclass(model, models.Model)): ...
python
def get_concrete_model(model): """ Get model defined in Meta. :param str or django.db.models.Model model: :return: model or None :rtype django.db.models.Model or None: :raise ValueError: model is not found or abstract """ if not(inspect.isclass(model) and issubclass(model, models.Model)): ...
[ "def", "get_concrete_model", "(", "model", ")", ":", "if", "not", "(", "inspect", ".", "isclass", "(", "model", ")", "and", "issubclass", "(", "model", ",", "models", ".", "Model", ")", ")", ":", "model", "=", "get_model_by_name", "(", "model", ")", "r...
Get model defined in Meta. :param str or django.db.models.Model model: :return: model or None :rtype django.db.models.Model or None: :raise ValueError: model is not found or abstract
[ "Get", "model", "defined", "in", "Meta", "." ]
c27943f22f1f1d30d651fe267a99d2b38f69d604
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/resource.py#L67-L79
train
64,794
pavlov99/jsonapi
jsonapi/resource.py
get_resource_name
def get_resource_name(meta): """ Define resource name based on Meta information. :param Resource.Meta meta: resource meta information :return: name of resource :rtype: str :raises ValueError: """ if meta.name is None and not meta.is_model: msg = "Either name or model for resource.M...
python
def get_resource_name(meta): """ Define resource name based on Meta information. :param Resource.Meta meta: resource meta information :return: name of resource :rtype: str :raises ValueError: """ if meta.name is None and not meta.is_model: msg = "Either name or model for resource.M...
[ "def", "get_resource_name", "(", "meta", ")", ":", "if", "meta", ".", "name", "is", "None", "and", "not", "meta", ".", "is_model", ":", "msg", "=", "\"Either name or model for resource.Meta shoud be provided\"", "raise", "ValueError", "(", "msg", ")", "name", "=...
Define resource name based on Meta information. :param Resource.Meta meta: resource meta information :return: name of resource :rtype: str :raises ValueError:
[ "Define", "resource", "name", "based", "on", "Meta", "information", "." ]
c27943f22f1f1d30d651fe267a99d2b38f69d604
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/resource.py#L82-L96
train
64,795
pavlov99/jsonapi
jsonapi/resource.py
merge_metas
def merge_metas(*metas): """ Merge meta parameters. next meta has priority over current, it will overwrite attributes. :param class or None meta: class with properties. :return class: merged meta. """ metadict = {} for meta in metas: metadict.update(meta.__dict__) metadict = ...
python
def merge_metas(*metas): """ Merge meta parameters. next meta has priority over current, it will overwrite attributes. :param class or None meta: class with properties. :return class: merged meta. """ metadict = {} for meta in metas: metadict.update(meta.__dict__) metadict = ...
[ "def", "merge_metas", "(", "*", "metas", ")", ":", "metadict", "=", "{", "}", "for", "meta", "in", "metas", ":", "metadict", ".", "update", "(", "meta", ".", "__dict__", ")", "metadict", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "metad...
Merge meta parameters. next meta has priority over current, it will overwrite attributes. :param class or None meta: class with properties. :return class: merged meta.
[ "Merge", "meta", "parameters", "." ]
c27943f22f1f1d30d651fe267a99d2b38f69d604
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/resource.py#L99-L113
train
64,796
python-wink/python-wink
src/pywink/devices/scene.py
WinkScene.activate
def activate(self): """ Activate the scene. """ response = self.api_interface.set_device_state(self, None) self._update_state_from_response(response)
python
def activate(self): """ Activate the scene. """ response = self.api_interface.set_device_state(self, None) self._update_state_from_response(response)
[ "def", "activate", "(", "self", ")", ":", "response", "=", "self", ".", "api_interface", ".", "set_device_state", "(", "self", ",", "None", ")", "self", ".", "_update_state_from_response", "(", "response", ")" ]
Activate the scene.
[ "Activate", "the", "scene", "." ]
cf8bdce8c6518f30b91b23aa7aa32e89c2ce48da
https://github.com/python-wink/python-wink/blob/cf8bdce8c6518f30b91b23aa7aa32e89c2ce48da/src/pywink/devices/scene.py#L23-L28
train
64,797
pavlov99/jsonapi
jsonapi/django_utils.py
get_model_by_name
def get_model_by_name(model_name): """ Get model by its name. :param str model_name: name of model. :return django.db.models.Model: Example: get_concrete_model_by_name('auth.User') django.contrib.auth.models.User """ if isinstance(model_name, six.string_types) and \ ...
python
def get_model_by_name(model_name): """ Get model by its name. :param str model_name: name of model. :return django.db.models.Model: Example: get_concrete_model_by_name('auth.User') django.contrib.auth.models.User """ if isinstance(model_name, six.string_types) and \ ...
[ "def", "get_model_by_name", "(", "model_name", ")", ":", "if", "isinstance", "(", "model_name", ",", "six", ".", "string_types", ")", "and", "len", "(", "model_name", ".", "split", "(", "'.'", ")", ")", "==", "2", ":", "app_name", ",", "model_name", "=",...
Get model by its name. :param str model_name: name of model. :return django.db.models.Model: Example: get_concrete_model_by_name('auth.User') django.contrib.auth.models.User
[ "Get", "model", "by", "its", "name", "." ]
c27943f22f1f1d30d651fe267a99d2b38f69d604
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/django_utils.py#L12-L35
train
64,798
pavlov99/jsonapi
jsonapi/django_utils.py
get_model_name
def get_model_name(model): """ Get model name for the field. Django 1.5 uses module_name, does not support model_name Django 1.6 uses module_name and model_name DJango 1.7 uses model_name, module_name raises RemovedInDjango18Warning """ opts = model._meta if django.VERSION[:2] < (1, 7): ...
python
def get_model_name(model): """ Get model name for the field. Django 1.5 uses module_name, does not support model_name Django 1.6 uses module_name and model_name DJango 1.7 uses model_name, module_name raises RemovedInDjango18Warning """ opts = model._meta if django.VERSION[:2] < (1, 7): ...
[ "def", "get_model_name", "(", "model", ")", ":", "opts", "=", "model", ".", "_meta", "if", "django", ".", "VERSION", "[", ":", "2", "]", "<", "(", "1", ",", "7", ")", ":", "model_name", "=", "opts", ".", "module_name", "else", ":", "model_name", "=...
Get model name for the field. Django 1.5 uses module_name, does not support model_name Django 1.6 uses module_name and model_name DJango 1.7 uses model_name, module_name raises RemovedInDjango18Warning
[ "Get", "model", "name", "for", "the", "field", "." ]
c27943f22f1f1d30d651fe267a99d2b38f69d604
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/django_utils.py#L38-L52
train
64,799