repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
pmac/urlwait
urlwait.py
wait_for_service
def wait_for_service(host, port, timeout=DEFAULT_TIMEOUT): """ Return True if connection to the host and port is successful within the timeout. @param host: str: hostname of the server @param port: int: TCP port to which to connect @param timeout: int: length of time in seconds to try to connect be...
python
def wait_for_service(host, port, timeout=DEFAULT_TIMEOUT): """ Return True if connection to the host and port is successful within the timeout. @param host: str: hostname of the server @param port: int: TCP port to which to connect @param timeout: int: length of time in seconds to try to connect be...
[ "def", "wait_for_service", "(", "host", ",", "port", ",", "timeout", "=", "DEFAULT_TIMEOUT", ")", ":", "service", "=", "ServiceURL", "(", "'tcp://{}:{}'", ".", "format", "(", "host", ",", "port", ")", ",", "timeout", ")", "return", "service", ".", "wait", ...
Return True if connection to the host and port is successful within the timeout. @param host: str: hostname of the server @param port: int: TCP port to which to connect @param timeout: int: length of time in seconds to try to connect before giving up @return: bool
[ "Return", "True", "if", "connection", "to", "the", "host", "and", "port", "is", "successful", "within", "the", "timeout", "." ]
train
https://github.com/pmac/urlwait/blob/0a846177a15a7f6f5a9d76c7229e572f779a048a/urlwait.py#L108-L118
pmac/urlwait
urlwait.py
wait_for_url
def wait_for_url(url, timeout=DEFAULT_TIMEOUT): """ Return True if connection to the host and port specified in url is successful within the timeout. @param url: str: connection url for a TCP service @param timeout: int: length of time in seconds to try to connect before giving up @raise Runtim...
python
def wait_for_url(url, timeout=DEFAULT_TIMEOUT): """ Return True if connection to the host and port specified in url is successful within the timeout. @param url: str: connection url for a TCP service @param timeout: int: length of time in seconds to try to connect before giving up @raise Runtim...
[ "def", "wait_for_url", "(", "url", ",", "timeout", "=", "DEFAULT_TIMEOUT", ")", ":", "service", "=", "ServiceURL", "(", "url", ",", "timeout", ")", "return", "service", ".", "wait", "(", ")" ]
Return True if connection to the host and port specified in url is successful within the timeout. @param url: str: connection url for a TCP service @param timeout: int: length of time in seconds to try to connect before giving up @raise RuntimeError: if no port is given or can't be guessed via the sche...
[ "Return", "True", "if", "connection", "to", "the", "host", "and", "port", "specified", "in", "url", "is", "successful", "within", "the", "timeout", "." ]
train
https://github.com/pmac/urlwait/blob/0a846177a15a7f6f5a9d76c7229e572f779a048a/urlwait.py#L121-L132
pmac/urlwait
urlwait.py
ServiceURL.is_available
def is_available(self): """ Return True if the connection to the host and port is successful. @return: bool """ if self.scheme in NOOP_PROTOCOLS: return True if not self.port: raise RuntimeError('port is required') s = socket.socket() ...
python
def is_available(self): """ Return True if the connection to the host and port is successful. @return: bool """ if self.scheme in NOOP_PROTOCOLS: return True if not self.port: raise RuntimeError('port is required') s = socket.socket() ...
[ "def", "is_available", "(", "self", ")", ":", "if", "self", ".", "scheme", "in", "NOOP_PROTOCOLS", ":", "return", "True", "if", "not", "self", ".", "port", ":", "raise", "RuntimeError", "(", "'port is required'", ")", "s", "=", "socket", ".", "socket", "...
Return True if the connection to the host and port is successful. @return: bool
[ "Return", "True", "if", "the", "connection", "to", "the", "host", "and", "port", "is", "successful", "." ]
train
https://github.com/pmac/urlwait/blob/0a846177a15a7f6f5a9d76c7229e572f779a048a/urlwait.py#L75-L93
cthorey/pdsimage
pdsimage/Structure.py
Area.change_window
def change_window(self, size_window): ''' Change the region of interest Args: size_window (float): Radius of the region of interest (km) Notes: Change the attributes ``size_window`` and ``window`` to correspond to the new region of interest. ''' ...
python
def change_window(self, size_window): ''' Change the region of interest Args: size_window (float): Radius of the region of interest (km) Notes: Change the attributes ``size_window`` and ``window`` to correspond to the new region of interest. ''' ...
[ "def", "change_window", "(", "self", ",", "size_window", ")", ":", "self", ".", "size_window", "=", "size_window", "self", ".", "window", "=", "self", ".", "lambert_window", "(", "self", ".", "size_window", ",", "self", ".", "lat0", ",", "self", ".", "lo...
Change the region of interest Args: size_window (float): Radius of the region of interest (km) Notes: Change the attributes ``size_window`` and ``window`` to correspond to the new region of interest.
[ "Change", "the", "region", "of", "interest" ]
train
https://github.com/cthorey/pdsimage/blob/f71de6dfddd3d538d76da229b4b9605c40f3fbac/pdsimage/Structure.py#L92-L105
cthorey/pdsimage
pdsimage/Structure.py
Area._add_scale
def _add_scale(self, m, ax1): ''' Add scale to the map instance ''' lol, loM, lam, laM = self.lambert_window( 0.6 * self.size_window, self.lat0, self.lon0) m.drawmapscale(loM, lam, self.lon0, self.lat0, 10, barstyle='fancy', units='km', ...
python
def _add_scale(self, m, ax1): ''' Add scale to the map instance ''' lol, loM, lam, laM = self.lambert_window( 0.6 * self.size_window, self.lat0, self.lon0) m.drawmapscale(loM, lam, self.lon0, self.lat0, 10, barstyle='fancy', units='km', ...
[ "def", "_add_scale", "(", "self", ",", "m", ",", "ax1", ")", ":", "lol", ",", "loM", ",", "lam", ",", "laM", "=", "self", ".", "lambert_window", "(", "0.6", "*", "self", ".", "size_window", ",", "self", ".", "lat0", ",", "self", ".", "lon0", ")",...
Add scale to the map instance
[ "Add", "scale", "to", "the", "map", "instance" ]
train
https://github.com/cthorey/pdsimage/blob/f71de6dfddd3d538d76da229b4b9605c40f3fbac/pdsimage/Structure.py#L200-L213
cthorey/pdsimage
pdsimage/Structure.py
Area._add_colorbar
def _add_colorbar(self, m, CS, ax, name): ''' Add colorbar to the map instance ''' cb = m.colorbar(CS, "right", size="5%", pad="2%") cb.set_label(name, size=34) cb.ax.tick_params(labelsize=18)
python
def _add_colorbar(self, m, CS, ax, name): ''' Add colorbar to the map instance ''' cb = m.colorbar(CS, "right", size="5%", pad="2%") cb.set_label(name, size=34) cb.ax.tick_params(labelsize=18)
[ "def", "_add_colorbar", "(", "self", ",", "m", ",", "CS", ",", "ax", ",", "name", ")", ":", "cb", "=", "m", ".", "colorbar", "(", "CS", ",", "\"right\"", ",", "size", "=", "\"5%\"", ",", "pad", "=", "\"2%\"", ")", "cb", ".", "set_label", "(", "...
Add colorbar to the map instance
[ "Add", "colorbar", "to", "the", "map", "instance" ]
train
https://github.com/cthorey/pdsimage/blob/f71de6dfddd3d538d76da229b4b9605c40f3fbac/pdsimage/Structure.py#L215-L220
cthorey/pdsimage
pdsimage/Structure.py
Area.get_arrays
def get_arrays(self, type_img): ''' Return arrays the region of interest Args: type_img (str): Either lola or wac. Returns: A tupple of three arrays ``(X,Y,Z)`` with ``X`` contains the longitudes, ``Y`` contains the latitude and ``Z`` the values ...
python
def get_arrays(self, type_img): ''' Return arrays the region of interest Args: type_img (str): Either lola or wac. Returns: A tupple of three arrays ``(X,Y,Z)`` with ``X`` contains the longitudes, ``Y`` contains the latitude and ``Z`` the values ...
[ "def", "get_arrays", "(", "self", ",", "type_img", ")", ":", "if", "type_img", ".", "lower", "(", ")", "==", "'lola'", ":", "return", "LolaMap", "(", "self", ".", "ppdlola", ",", "*", "self", ".", "window", ",", "path_pdsfile", "=", "self", ".", "pat...
Return arrays the region of interest Args: type_img (str): Either lola or wac. Returns: A tupple of three arrays ``(X,Y,Z)`` with ``X`` contains the longitudes, ``Y`` contains the latitude and ``Z`` the values extracted for the region of interest. ...
[ "Return", "arrays", "the", "region", "of", "interest" ]
train
https://github.com/cthorey/pdsimage/blob/f71de6dfddd3d538d76da229b4b9605c40f3fbac/pdsimage/Structure.py#L222-L245
cthorey/pdsimage
pdsimage/Structure.py
Area._format_coordinate
def _format_coordinate(self, ax, m): ''' Format the basemap plot to show lat/long properly ''' lon_m, lon_M, lat_m, lat_M = self.window xlocs = np.linspace(lon_m, lon_M, 5) ylocs = np.linspace(lat_m, lat_M, 5) xlocs = map(lambda x: float('%1.2f' % (x)), xlocs) ylocs = map...
python
def _format_coordinate(self, ax, m): ''' Format the basemap plot to show lat/long properly ''' lon_m, lon_M, lat_m, lat_M = self.window xlocs = np.linspace(lon_m, lon_M, 5) ylocs = np.linspace(lat_m, lat_M, 5) xlocs = map(lambda x: float('%1.2f' % (x)), xlocs) ylocs = map...
[ "def", "_format_coordinate", "(", "self", ",", "ax", ",", "m", ")", ":", "lon_m", ",", "lon_M", ",", "lat_m", ",", "lat_M", "=", "self", ".", "window", "xlocs", "=", "np", ".", "linspace", "(", "lon_m", ",", "lon_M", ",", "5", ")", "ylocs", "=", ...
Format the basemap plot to show lat/long properly
[ "Format", "the", "basemap", "plot", "to", "show", "lat", "/", "long", "properly" ]
train
https://github.com/cthorey/pdsimage/blob/f71de6dfddd3d538d76da229b4b9605c40f3fbac/pdsimage/Structure.py#L247-L255
cthorey/pdsimage
pdsimage/Structure.py
Area.get_profile
def get_profile(self, img_type, coordinate, num_points): ''' Extract a profile from (lat1,lon1) to (lat2,lon2) Args: img_type (str): Either lola or wac. coordinate (float,float,float,flaot): A tupple ``(lon0,lon1,lat0,lat1)`` with: - lon0: First ...
python
def get_profile(self, img_type, coordinate, num_points): ''' Extract a profile from (lat1,lon1) to (lat2,lon2) Args: img_type (str): Either lola or wac. coordinate (float,float,float,flaot): A tupple ``(lon0,lon1,lat0,lat1)`` with: - lon0: First ...
[ "def", "get_profile", "(", "self", ",", "img_type", ",", "coordinate", ",", "num_points", ")", ":", "lon0", ",", "lon1", ",", "lat0", ",", "lat1", "=", "coordinate", "X", ",", "Y", ",", "Z", "=", "self", ".", "get_arrays", "(", "img_type", ")", "y0",...
Extract a profile from (lat1,lon1) to (lat2,lon2) Args: img_type (str): Either lola or wac. coordinate (float,float,float,flaot): A tupple ``(lon0,lon1,lat0,lat1)`` with: - lon0: First point longitude - lat0: First point latitude ...
[ "Extract", "a", "profile", "from", "(", "lat1", "lon1", ")", "to", "(", "lat2", "lon2", ")" ]
train
https://github.com/cthorey/pdsimage/blob/f71de6dfddd3d538d76da229b4b9605c40f3fbac/pdsimage/Structure.py#L257-L286
cthorey/pdsimage
pdsimage/Structure.py
Area.draw_profile
def draw_profile(self, coordinates, num_points=500, save=False, name='BaseProfile.png'): ''' Draw a profile between a point (lon0,lat0) and (lon1,lat1). Args: coordinates: Tupples which list the different desired profiles. Each profil ha...
python
def draw_profile(self, coordinates, num_points=500, save=False, name='BaseProfile.png'): ''' Draw a profile between a point (lon0,lat0) and (lon1,lat1). Args: coordinates: Tupples which list the different desired profiles. Each profil ha...
[ "def", "draw_profile", "(", "self", ",", "coordinates", ",", "num_points", "=", "500", ",", "save", "=", "False", ",", "name", "=", "'BaseProfile.png'", ")", ":", "fig", "=", "plt", ".", "figure", "(", "figsize", "=", "(", "27", ",", "len", "(", "coo...
Draw a profile between a point (lon0,lat0) and (lon1,lat1). Args: coordinates: Tupples which list the different desired profiles. Each profil has to be defined as a tupple which follows (lon0,lon1,lat0,lat1) with (lon0,lat0) the first point ...
[ "Draw", "a", "profile", "between", "a", "point", "(", "lon0", "lat0", ")", "and", "(", "lon1", "lat1", ")", "." ]
train
https://github.com/cthorey/pdsimage/blob/f71de6dfddd3d538d76da229b4b9605c40f3fbac/pdsimage/Structure.py#L288-L374
cthorey/pdsimage
pdsimage/Structure.py
Area.lola_image
def lola_image(self, save=False, name='BaseLola.png'): ''' Draw the topography of the region of interest Args: save (Optional[bool]): Weither or not to save the image. Defaults to False. name (Optional[str]): Absolut path to save the resulting ima...
python
def lola_image(self, save=False, name='BaseLola.png'): ''' Draw the topography of the region of interest Args: save (Optional[bool]): Weither or not to save the image. Defaults to False. name (Optional[str]): Absolut path to save the resulting ima...
[ "def", "lola_image", "(", "self", ",", "save", "=", "False", ",", "name", "=", "'BaseLola.png'", ")", ":", "fig", "=", "plt", ".", "figure", "(", "figsize", "=", "(", "10", ",", "8", ")", ")", "ax1", "=", "fig", ".", "add_subplot", "(", "111", ")...
Draw the topography of the region of interest Args: save (Optional[bool]): Weither or not to save the image. Defaults to False. name (Optional[str]): Absolut path to save the resulting image. Default to 'BaseLola.png' in the working direct...
[ "Draw", "the", "topography", "of", "the", "region", "of", "interest" ]
train
https://github.com/cthorey/pdsimage/blob/f71de6dfddd3d538d76da229b4b9605c40f3fbac/pdsimage/Structure.py#L376-L421
qwilka/vn-tree
examples/simple_tree.py
make_file_system_tree
def make_file_system_tree(root_folder, _parent=None): """This function makes a tree from folders and files. """ root_node = Node(os.path.basename(root_folder), _parent) root_node.path = root_folder for item in os.listdir(root_folder): item_path = os.path.join(root_folder, item) if os...
python
def make_file_system_tree(root_folder, _parent=None): """This function makes a tree from folders and files. """ root_node = Node(os.path.basename(root_folder), _parent) root_node.path = root_folder for item in os.listdir(root_folder): item_path = os.path.join(root_folder, item) if os...
[ "def", "make_file_system_tree", "(", "root_folder", ",", "_parent", "=", "None", ")", ":", "root_node", "=", "Node", "(", "os", ".", "path", ".", "basename", "(", "root_folder", ")", ",", "_parent", ")", "root_node", ".", "path", "=", "root_folder", "for",...
This function makes a tree from folders and files.
[ "This", "function", "makes", "a", "tree", "from", "folders", "and", "files", "." ]
train
https://github.com/qwilka/vn-tree/blob/f08106e9c7232d8748d78d1d39b019699a7407dd/examples/simple_tree.py#L126-L139
aodag/WebDispatch
webdispatch/urldispatcher.py
URLMapper.add
def add(self, name: str, pattern: str) -> None: """ add url pattern for name """ self.patterns[name] = URITemplate( pattern, converters=self.converters)
python
def add(self, name: str, pattern: str) -> None: """ add url pattern for name """ self.patterns[name] = URITemplate( pattern, converters=self.converters)
[ "def", "add", "(", "self", ",", "name", ":", "str", ",", "pattern", ":", "str", ")", "->", "None", ":", "self", ".", "patterns", "[", "name", "]", "=", "URITemplate", "(", "pattern", ",", "converters", "=", "self", ".", "converters", ")" ]
add url pattern for name
[ "add", "url", "pattern", "for", "name" ]
train
https://github.com/aodag/WebDispatch/blob/55f8658a2b4100498e098a80303a346c3940f1bc/webdispatch/urldispatcher.py#L26-L30
aodag/WebDispatch
webdispatch/urldispatcher.py
URLMapper.lookup
def lookup(self, path_info: str) -> MatchResult: """ lookup url match for path_info """ for name, pattern in self.patterns.items(): match = pattern.match(path_info) if match is None: continue match.name = name return match r...
python
def lookup(self, path_info: str) -> MatchResult: """ lookup url match for path_info """ for name, pattern in self.patterns.items(): match = pattern.match(path_info) if match is None: continue match.name = name return match r...
[ "def", "lookup", "(", "self", ",", "path_info", ":", "str", ")", "->", "MatchResult", ":", "for", "name", ",", "pattern", "in", "self", ".", "patterns", ".", "items", "(", ")", ":", "match", "=", "pattern", ".", "match", "(", "path_info", ")", "if", ...
lookup url match for path_info
[ "lookup", "url", "match", "for", "path_info" ]
train
https://github.com/aodag/WebDispatch/blob/55f8658a2b4100498e098a80303a346c3940f1bc/webdispatch/urldispatcher.py#L32-L41
aodag/WebDispatch
webdispatch/urldispatcher.py
URLMapper.generate
def generate(self, name: str, **kwargs: Dict[str, str]) -> str: """ generate url for named url pattern with kwargs """ template = self.patterns[name] return template.substitute(kwargs)
python
def generate(self, name: str, **kwargs: Dict[str, str]) -> str: """ generate url for named url pattern with kwargs """ template = self.patterns[name] return template.substitute(kwargs)
[ "def", "generate", "(", "self", ",", "name", ":", "str", ",", "*", "*", "kwargs", ":", "Dict", "[", "str", ",", "str", "]", ")", "->", "str", ":", "template", "=", "self", ".", "patterns", "[", "name", "]", "return", "template", ".", "substitute", ...
generate url for named url pattern with kwargs
[ "generate", "url", "for", "named", "url", "pattern", "with", "kwargs" ]
train
https://github.com/aodag/WebDispatch/blob/55f8658a2b4100498e098a80303a346c3940f1bc/webdispatch/urldispatcher.py#L43-L47
aodag/WebDispatch
webdispatch/urldispatcher.py
URLGenerator.generate
def generate(self, name: str, **kwargs): """ generate full qualified url for named url pattern with kwargs """ path = self.urlmapper.generate(name, **kwargs) return self.make_full_qualified_url(path)
python
def generate(self, name: str, **kwargs): """ generate full qualified url for named url pattern with kwargs """ path = self.urlmapper.generate(name, **kwargs) return self.make_full_qualified_url(path)
[ "def", "generate", "(", "self", ",", "name", ":", "str", ",", "*", "*", "kwargs", ")", ":", "path", "=", "self", ".", "urlmapper", ".", "generate", "(", "name", ",", "*", "*", "kwargs", ")", "return", "self", ".", "make_full_qualified_url", "(", "pat...
generate full qualified url for named url pattern with kwargs
[ "generate", "full", "qualified", "url", "for", "named", "url", "pattern", "with", "kwargs" ]
train
https://github.com/aodag/WebDispatch/blob/55f8658a2b4100498e098a80303a346c3940f1bc/webdispatch/urldispatcher.py#L59-L63
aodag/WebDispatch
webdispatch/urldispatcher.py
URLGenerator.make_full_qualified_url
def make_full_qualified_url(self, path: str) -> str: """ append application url to path""" return self.application_uri.rstrip('/') + '/' + path.lstrip('/')
python
def make_full_qualified_url(self, path: str) -> str: """ append application url to path""" return self.application_uri.rstrip('/') + '/' + path.lstrip('/')
[ "def", "make_full_qualified_url", "(", "self", ",", "path", ":", "str", ")", "->", "str", ":", "return", "self", ".", "application_uri", ".", "rstrip", "(", "'/'", ")", "+", "'/'", "+", "path", ".", "lstrip", "(", "'/'", ")" ]
append application url to path
[ "append", "application", "url", "to", "path" ]
train
https://github.com/aodag/WebDispatch/blob/55f8658a2b4100498e098a80303a346c3940f1bc/webdispatch/urldispatcher.py#L65-L67
aodag/WebDispatch
webdispatch/urldispatcher.py
URLDispatcher.add_url
def add_url(self, name: str, pattern: str, application: Callable) -> None: """ add url pattern dispatching to application""" self.urlmapper.add(name, self.prefix + pattern) self.register_app(name, application)
python
def add_url(self, name: str, pattern: str, application: Callable) -> None: """ add url pattern dispatching to application""" self.urlmapper.add(name, self.prefix + pattern) self.register_app(name, application)
[ "def", "add_url", "(", "self", ",", "name", ":", "str", ",", "pattern", ":", "str", ",", "application", ":", "Callable", ")", "->", "None", ":", "self", ".", "urlmapper", ".", "add", "(", "name", ",", "self", ".", "prefix", "+", "pattern", ")", "se...
add url pattern dispatching to application
[ "add", "url", "pattern", "dispatching", "to", "application" ]
train
https://github.com/aodag/WebDispatch/blob/55f8658a2b4100498e098a80303a346c3940f1bc/webdispatch/urldispatcher.py#L90-L93
aodag/WebDispatch
webdispatch/urldispatcher.py
URLDispatcher.add_subroute
def add_subroute(self, pattern: str) -> "URLDispatcher": """ create new URLDispatcher routed by pattern """ return URLDispatcher( urlmapper=self.urlmapper, prefix=self.prefix + pattern, applications=self.applications, extra_environ=self.extra_environ)
python
def add_subroute(self, pattern: str) -> "URLDispatcher": """ create new URLDispatcher routed by pattern """ return URLDispatcher( urlmapper=self.urlmapper, prefix=self.prefix + pattern, applications=self.applications, extra_environ=self.extra_environ)
[ "def", "add_subroute", "(", "self", ",", "pattern", ":", "str", ")", "->", "\"URLDispatcher\"", ":", "return", "URLDispatcher", "(", "urlmapper", "=", "self", ".", "urlmapper", ",", "prefix", "=", "self", ".", "prefix", "+", "pattern", ",", "applications", ...
create new URLDispatcher routed by pattern
[ "create", "new", "URLDispatcher", "routed", "by", "pattern" ]
train
https://github.com/aodag/WebDispatch/blob/55f8658a2b4100498e098a80303a346c3940f1bc/webdispatch/urldispatcher.py#L95-L101
aodag/WebDispatch
webdispatch/urldispatcher.py
URLDispatcher.detect_view_name
def detect_view_name(self, environ: Dict[str, Any]) -> str: """ detect view name from environ """ script_name = environ.get('SCRIPT_NAME', '') path_info = environ.get('PATH_INFO', '') match = self.urlmapper.lookup(path_info) if match is None: return None spli...
python
def detect_view_name(self, environ: Dict[str, Any]) -> str: """ detect view name from environ """ script_name = environ.get('SCRIPT_NAME', '') path_info = environ.get('PATH_INFO', '') match = self.urlmapper.lookup(path_info) if match is None: return None spli...
[ "def", "detect_view_name", "(", "self", ",", "environ", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "str", ":", "script_name", "=", "environ", ".", "get", "(", "'SCRIPT_NAME'", ",", "''", ")", "path_info", "=", "environ", ".", "get", "(", "'...
detect view name from environ
[ "detect", "view", "name", "from", "environ" ]
train
https://github.com/aodag/WebDispatch/blob/55f8658a2b4100498e098a80303a346c3940f1bc/webdispatch/urldispatcher.py#L103-L126
aodag/WebDispatch
webdispatch/urldispatcher.py
URLDispatcher.on_view_not_found
def on_view_not_found( self, environ: Dict[str, Any], start_response: Callable[[str, List[Tuple[str, str]]], None], ) -> Iterable[bytes]: """ called when views not found""" start_response('404 Not Found', [('Content-type', 'text/plain')]) return [b'Not fou...
python
def on_view_not_found( self, environ: Dict[str, Any], start_response: Callable[[str, List[Tuple[str, str]]], None], ) -> Iterable[bytes]: """ called when views not found""" start_response('404 Not Found', [('Content-type', 'text/plain')]) return [b'Not fou...
[ "def", "on_view_not_found", "(", "self", ",", "environ", ":", "Dict", "[", "str", ",", "Any", "]", ",", "start_response", ":", "Callable", "[", "[", "str", ",", "List", "[", "Tuple", "[", "str", ",", "str", "]", "]", "]", ",", "None", "]", ",", "...
called when views not found
[ "called", "when", "views", "not", "found" ]
train
https://github.com/aodag/WebDispatch/blob/55f8658a2b4100498e098a80303a346c3940f1bc/webdispatch/urldispatcher.py#L128-L135
JulianKahnert/geizhals
geizhals/geizhals.py
Geizhals.parse
def parse(self): """Get new data, parses it and returns a device.""" # fetch data sess = requests.session() request = sess.get('https://{}/{}'.format(self.locale, self.product_id), allow_redirects=True, ...
python
def parse(self): """Get new data, parses it and returns a device.""" # fetch data sess = requests.session() request = sess.get('https://{}/{}'.format(self.locale, self.product_id), allow_redirects=True, ...
[ "def", "parse", "(", "self", ")", ":", "# fetch data", "sess", "=", "requests", ".", "session", "(", ")", "request", "=", "sess", ".", "get", "(", "'https://{}/{}'", ".", "format", "(", "self", ".", "locale", ",", "self", ".", "product_id", ")", ",", ...
Get new data, parses it and returns a device.
[ "Get", "new", "data", "parses", "it", "and", "returns", "a", "device", "." ]
train
https://github.com/JulianKahnert/geizhals/blob/31405b2afc416940f34a211e1e64ed165b11dec4/geizhals/geizhals.py#L61-L93
conchoecia/gloTK
gloTK/wrappers.py
BaseWrapper.check_input
def check_input(self, flag, path): """ turns path into an absolute path and checks that it exists, then appends it to the args using the given flag (or none). """ path = os.path.abspath(path) if os.path.exists(path): if flag: self.args.append(f...
python
def check_input(self, flag, path): """ turns path into an absolute path and checks that it exists, then appends it to the args using the given flag (or none). """ path = os.path.abspath(path) if os.path.exists(path): if flag: self.args.append(f...
[ "def", "check_input", "(", "self", ",", "flag", ",", "path", ")", ":", "path", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "if", "flag", ":", "self", ".", "args", ".",...
turns path into an absolute path and checks that it exists, then appends it to the args using the given flag (or none).
[ "turns", "path", "into", "an", "absolute", "path", "and", "checks", "that", "it", "exists", "then", "appends", "it", "to", "the", "args", "using", "the", "given", "flag", "(", "or", "none", ")", "." ]
train
https://github.com/conchoecia/gloTK/blob/58abee663fcfbbd09f4863c3ca3ae054e33184a8/gloTK/wrappers.py#L104-L116
conchoecia/gloTK
gloTK/wrappers.py
BaseWrapper.check_path
def check_path(self, path): """ turns path into an absolute path and checks that it exists, then returns it as a string. """ path = os.path.abspath(path) if os.path.exists(path): return path else: utils.die("input file does not exists:\n {...
python
def check_path(self, path): """ turns path into an absolute path and checks that it exists, then returns it as a string. """ path = os.path.abspath(path) if os.path.exists(path): return path else: utils.die("input file does not exists:\n {...
[ "def", "check_path", "(", "self", ",", "path", ")", ":", "path", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return", "path", "else", ":", "utils", ".", "die", "(", "...
turns path into an absolute path and checks that it exists, then returns it as a string.
[ "turns", "path", "into", "an", "absolute", "path", "and", "checks", "that", "it", "exists", "then", "returns", "it", "as", "a", "string", "." ]
train
https://github.com/conchoecia/gloTK/blob/58abee663fcfbbd09f4863c3ca3ae054e33184a8/gloTK/wrappers.py#L118-L127
conchoecia/gloTK
gloTK/wrappers.py
BaseWrapper.run
def run(self): """ Call this function at the end of your class's `__init__` function. """ stderr = os.path.abspath(os.path.join(self.outdir, self.name + '.log')) if self.pipe: self.args += ('|', self.pipe, '2>>'+stderr) if self.gzip: self.args +=...
python
def run(self): """ Call this function at the end of your class's `__init__` function. """ stderr = os.path.abspath(os.path.join(self.outdir, self.name + '.log')) if self.pipe: self.args += ('|', self.pipe, '2>>'+stderr) if self.gzip: self.args +=...
[ "def", "run", "(", "self", ")", ":", "stderr", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "self", ".", "outdir", ",", "self", ".", "name", "+", "'.log'", ")", ")", "if", "self", ".", "pipe", ":", "self", ...
Call this function at the end of your class's `__init__` function.
[ "Call", "this", "function", "at", "the", "end", "of", "your", "class", "s", "__init__", "function", "." ]
train
https://github.com/conchoecia/gloTK/blob/58abee663fcfbbd09f4863c3ca3ae054e33184a8/gloTK/wrappers.py#L151-L197
conchoecia/gloTK
gloTK/wrappers.py
BaseWrapper.run_jar
def run_jar(self, mem=None): """ Special case of run() when the executable is a JAR file. """ cmd = config.get_command('java') if mem: cmd.append('-Xmx%s' % mem) cmd.append('-jar') cmd += self.cmd self.run(cmd)
python
def run_jar(self, mem=None): """ Special case of run() when the executable is a JAR file. """ cmd = config.get_command('java') if mem: cmd.append('-Xmx%s' % mem) cmd.append('-jar') cmd += self.cmd self.run(cmd)
[ "def", "run_jar", "(", "self", ",", "mem", "=", "None", ")", ":", "cmd", "=", "config", ".", "get_command", "(", "'java'", ")", "if", "mem", ":", "cmd", ".", "append", "(", "'-Xmx%s'", "%", "mem", ")", "cmd", ".", "append", "(", "'-jar'", ")", "c...
Special case of run() when the executable is a JAR file.
[ "Special", "case", "of", "run", "()", "when", "the", "executable", "is", "a", "JAR", "file", "." ]
train
https://github.com/conchoecia/gloTK/blob/58abee663fcfbbd09f4863c3ca3ae054e33184a8/gloTK/wrappers.py#L208-L217
mamrhein/identifiers
identifiers/gs1.py
GS1NumericalIdentifier.calc_check_digit
def calc_check_digit(digits): """Calculate and return the GS1 check digit.""" ints = [int(d) for d in digits] l = len(ints) odds = slice((l - 1) % 2, l, 2) even = slice(l % 2, l, 2) checksum = 3 * sum(ints[odds]) + sum(ints[even]) return str(-checksum % 10)
python
def calc_check_digit(digits): """Calculate and return the GS1 check digit.""" ints = [int(d) for d in digits] l = len(ints) odds = slice((l - 1) % 2, l, 2) even = slice(l % 2, l, 2) checksum = 3 * sum(ints[odds]) + sum(ints[even]) return str(-checksum % 10)
[ "def", "calc_check_digit", "(", "digits", ")", ":", "ints", "=", "[", "int", "(", "d", ")", "for", "d", "in", "digits", "]", "l", "=", "len", "(", "ints", ")", "odds", "=", "slice", "(", "(", "l", "-", "1", ")", "%", "2", ",", "l", ",", "2"...
Calculate and return the GS1 check digit.
[ "Calculate", "and", "return", "the", "GS1", "check", "digit", "." ]
train
https://github.com/mamrhein/identifiers/blob/93ab2609e461faff245d1f582411bf831b428eef/identifiers/gs1.py#L47-L54
mamrhein/identifiers
identifiers/gs1.py
GS1NumericalIdentifier.company_prefix
def company_prefix(self): """Return the identifier's company prefix part.""" offset = self.EXTRA_DIGITS return self._id[offset:self._ref_idx]
python
def company_prefix(self): """Return the identifier's company prefix part.""" offset = self.EXTRA_DIGITS return self._id[offset:self._ref_idx]
[ "def", "company_prefix", "(", "self", ")", ":", "offset", "=", "self", ".", "EXTRA_DIGITS", "return", "self", ".", "_id", "[", "offset", ":", "self", ".", "_ref_idx", "]" ]
Return the identifier's company prefix part.
[ "Return", "the", "identifier", "s", "company", "prefix", "part", "." ]
train
https://github.com/mamrhein/identifiers/blob/93ab2609e461faff245d1f582411bf831b428eef/identifiers/gs1.py#L71-L74
mamrhein/identifiers
identifiers/gs1.py
GS1NumericalIdentifier.elements
def elements(self): """Return the identifier's elements as tuple.""" offset = self.EXTRA_DIGITS if offset: return (self._id[:offset], self.company_prefix, self._reference, self.check_digit) else: return (self.company_prefix, self._reference, se...
python
def elements(self): """Return the identifier's elements as tuple.""" offset = self.EXTRA_DIGITS if offset: return (self._id[:offset], self.company_prefix, self._reference, self.check_digit) else: return (self.company_prefix, self._reference, se...
[ "def", "elements", "(", "self", ")", ":", "offset", "=", "self", ".", "EXTRA_DIGITS", "if", "offset", ":", "return", "(", "self", ".", "_id", "[", ":", "offset", "]", ",", "self", ".", "company_prefix", ",", "self", ".", "_reference", ",", "self", "....
Return the identifier's elements as tuple.
[ "Return", "the", "identifier", "s", "elements", "as", "tuple", "." ]
train
https://github.com/mamrhein/identifiers/blob/93ab2609e461faff245d1f582411bf831b428eef/identifiers/gs1.py#L220-L227
mamrhein/identifiers
identifiers/gs1.py
GS1NumericalIdentifier.separated
def separated(self, separator='-'): """Return a string representation of the identifier with its elements separated by the given separator.""" return separator.join((part for part in self.elements() if part))
python
def separated(self, separator='-'): """Return a string representation of the identifier with its elements separated by the given separator.""" return separator.join((part for part in self.elements() if part))
[ "def", "separated", "(", "self", ",", "separator", "=", "'-'", ")", ":", "return", "separator", ".", "join", "(", "(", "part", "for", "part", "in", "self", ".", "elements", "(", ")", "if", "part", ")", ")" ]
Return a string representation of the identifier with its elements separated by the given separator.
[ "Return", "a", "string", "representation", "of", "the", "identifier", "with", "its", "elements", "separated", "by", "the", "given", "separator", "." ]
train
https://github.com/mamrhein/identifiers/blob/93ab2609e461faff245d1f582411bf831b428eef/identifiers/gs1.py#L229-L232
chop-dbhi/varify-data-warehouse
vdw/genes/managers.py
GeneManager.find
def find(self, symbol, chrom=None, create=False): """ Find a gene based on the symbol or disambiguate using synonyms. If no gene is found, if the create is True, a new instance will be created with that symbol. """ queryset = self.get_query_set() # Filter by chro...
python
def find(self, symbol, chrom=None, create=False): """ Find a gene based on the symbol or disambiguate using synonyms. If no gene is found, if the create is True, a new instance will be created with that symbol. """ queryset = self.get_query_set() # Filter by chro...
[ "def", "find", "(", "self", ",", "symbol", ",", "chrom", "=", "None", ",", "create", "=", "False", ")", ":", "queryset", "=", "self", ".", "get_query_set", "(", ")", "# Filter by chromosome if one is specified", "if", "chrom", ":", "queryset", "=", "queryset...
Find a gene based on the symbol or disambiguate using synonyms. If no gene is found, if the create is True, a new instance will be created with that symbol.
[ "Find", "a", "gene", "based", "on", "the", "symbol", "or", "disambiguate", "using", "synonyms", ".", "If", "no", "gene", "is", "found", "if", "the", "create", "is", "True", "a", "new", "instance", "will", "be", "created", "with", "that", "symbol", "." ]
train
https://github.com/chop-dbhi/varify-data-warehouse/blob/1600ee1bc5fae6c68fd03b23624467298570cca8/vdw/genes/managers.py#L5-L41
leosartaj/tvstats
tvstats/graph.py
graphdata
def graphdata(data): """returns ratings and episode number to be used for making graphs""" data = jh.get_ratings(data) num = 1 rating_final = [] episode_final = [] for k,v in data.iteritems(): rating=[] epinum=[] for r in v: if r != None: r...
python
def graphdata(data): """returns ratings and episode number to be used for making graphs""" data = jh.get_ratings(data) num = 1 rating_final = [] episode_final = [] for k,v in data.iteritems(): rating=[] epinum=[] for r in v: if r != None: r...
[ "def", "graphdata", "(", "data", ")", ":", "data", "=", "jh", ".", "get_ratings", "(", "data", ")", "num", "=", "1", "rating_final", "=", "[", "]", "episode_final", "=", "[", "]", "for", "k", ",", "v", "in", "data", ".", "iteritems", "(", ")", ":...
returns ratings and episode number to be used for making graphs
[ "returns", "ratings", "and", "episode", "number", "to", "be", "used", "for", "making", "graphs" ]
train
https://github.com/leosartaj/tvstats/blob/164fe736111d43869f8c9686e07a5ab1b9f22444/tvstats/graph.py#L7-L24
leosartaj/tvstats
tvstats/graph.py
graph
def graph(data): """Draws graph of rating vs episode number""" title = data['name'] + ' (' + data['rating'] + ') ' plt.title(title) plt.xlabel('Episode Number') plt.ylabel('Ratings') rf,ef=graphdata(data) col=['red', 'green' , 'orange'] for i in range(len(rf)): x,y=ef[i],rf[i] ...
python
def graph(data): """Draws graph of rating vs episode number""" title = data['name'] + ' (' + data['rating'] + ') ' plt.title(title) plt.xlabel('Episode Number') plt.ylabel('Ratings') rf,ef=graphdata(data) col=['red', 'green' , 'orange'] for i in range(len(rf)): x,y=ef[i],rf[i] ...
[ "def", "graph", "(", "data", ")", ":", "title", "=", "data", "[", "'name'", "]", "+", "' ('", "+", "data", "[", "'rating'", "]", "+", "') '", "plt", ".", "title", "(", "title", ")", "plt", ".", "xlabel", "(", "'Episode Number'", ")", "plt", ".", ...
Draws graph of rating vs episode number
[ "Draws", "graph", "of", "rating", "vs", "episode", "number" ]
train
https://github.com/leosartaj/tvstats/blob/164fe736111d43869f8c9686e07a5ab1b9f22444/tvstats/graph.py#L27-L44
klen/adrest
adrest/utils/serializer.py
BaseSerializer.to_simple
def to_simple(self, value, **options): # nolint " Simplify object. " # (string, unicode) if isinstance(value, basestring): return smart_unicode(value) # (int, long, float, real, complex, decimal) if isinstance(value, Number): return float(str(value)) if...
python
def to_simple(self, value, **options): # nolint " Simplify object. " # (string, unicode) if isinstance(value, basestring): return smart_unicode(value) # (int, long, float, real, complex, decimal) if isinstance(value, Number): return float(str(value)) if...
[ "def", "to_simple", "(", "self", ",", "value", ",", "*", "*", "options", ")", ":", "# nolint", "# (string, unicode)", "if", "isinstance", "(", "value", ",", "basestring", ")", ":", "return", "smart_unicode", "(", "value", ")", "# (int, long, float, real, complex...
Simplify object.
[ "Simplify", "object", "." ]
train
https://github.com/klen/adrest/blob/8b75c67123cffabe5ed98c222bb7ab43c904d89c/adrest/utils/serializer.py#L39-L73
klen/adrest
adrest/utils/serializer.py
BaseSerializer.to_simple_model
def to_simple_model(self, instance, **options): # noqa """ Convert model to simple python structure. """ options = self.init_options(**options) fields, include, exclude, related = options['fields'], options['include'], options['exclude'], options['related'] # noqa result = dict(...
python
def to_simple_model(self, instance, **options): # noqa """ Convert model to simple python structure. """ options = self.init_options(**options) fields, include, exclude, related = options['fields'], options['include'], options['exclude'], options['related'] # noqa result = dict(...
[ "def", "to_simple_model", "(", "self", ",", "instance", ",", "*", "*", "options", ")", ":", "# noqa", "options", "=", "self", ".", "init_options", "(", "*", "*", "options", ")", "fields", ",", "include", ",", "exclude", ",", "related", "=", "options", ...
Convert model to simple python structure.
[ "Convert", "model", "to", "simple", "python", "structure", "." ]
train
https://github.com/klen/adrest/blob/8b75c67123cffabe5ed98c222bb7ab43c904d89c/adrest/utils/serializer.py#L87-L134
bitlabstudio/python-server-metrics
server_metrics/memcached.py
get_memcached_usage
def get_memcached_usage(socket=None): """ Returns memcached statistics. :param socket: Path to memcached's socket file. """ cmd = 'echo \'stats\' | nc -U {0}'.format(socket) output = getoutput(cmd) curr_items = None bytes_ = None rows = output.split('\n')[:-1] for row in rows:...
python
def get_memcached_usage(socket=None): """ Returns memcached statistics. :param socket: Path to memcached's socket file. """ cmd = 'echo \'stats\' | nc -U {0}'.format(socket) output = getoutput(cmd) curr_items = None bytes_ = None rows = output.split('\n')[:-1] for row in rows:...
[ "def", "get_memcached_usage", "(", "socket", "=", "None", ")", ":", "cmd", "=", "'echo \\'stats\\' | nc -U {0}'", ".", "format", "(", "socket", ")", "output", "=", "getoutput", "(", "cmd", ")", "curr_items", "=", "None", "bytes_", "=", "None", "rows", "=", ...
Returns memcached statistics. :param socket: Path to memcached's socket file.
[ "Returns", "memcached", "statistics", "." ]
train
https://github.com/bitlabstudio/python-server-metrics/blob/5f61e02db549a727d3d1d8e11ad2672728da3c4a/server_metrics/memcached.py#L8-L27
mamrhein/identifiers
identifiers/bookland.py
_BooklandGTIN.elements
def elements(self): """Return the identifier's elements (gs1_prefix, registration_group, registrant, publication, check_digit) as tuple.""" return (self.gs1_prefix, self.registration_group, self.registrant, self.publication, self.check_digit)
python
def elements(self): """Return the identifier's elements (gs1_prefix, registration_group, registrant, publication, check_digit) as tuple.""" return (self.gs1_prefix, self.registration_group, self.registrant, self.publication, self.check_digit)
[ "def", "elements", "(", "self", ")", ":", "return", "(", "self", ".", "gs1_prefix", ",", "self", ".", "registration_group", ",", "self", ".", "registrant", ",", "self", ".", "publication", ",", "self", ".", "check_digit", ")" ]
Return the identifier's elements (gs1_prefix, registration_group, registrant, publication, check_digit) as tuple.
[ "Return", "the", "identifier", "s", "elements", "(", "gs1_prefix", "registration_group", "registrant", "publication", "check_digit", ")", "as", "tuple", "." ]
train
https://github.com/mamrhein/identifiers/blob/93ab2609e461faff245d1f582411bf831b428eef/identifiers/bookland.py#L166-L170
uw-it-aca/uw-restclients
restclients/util/date_formator.py
abbr_month_date_time_str
def abbr_month_date_time_str(adatetime): """ Return a date value in the format of "Month(abbreviated name) day, 4-digit-year at hour:minute [AP]M" """ return "%s %d, %d at %s" % (adatetime.strftime("%b"), adatetime.day, adatetime.year, ...
python
def abbr_month_date_time_str(adatetime): """ Return a date value in the format of "Month(abbreviated name) day, 4-digit-year at hour:minute [AP]M" """ return "%s %d, %d at %s" % (adatetime.strftime("%b"), adatetime.day, adatetime.year, ...
[ "def", "abbr_month_date_time_str", "(", "adatetime", ")", ":", "return", "\"%s %d, %d at %s\"", "%", "(", "adatetime", ".", "strftime", "(", "\"%b\"", ")", ",", "adatetime", ".", "day", ",", "adatetime", ".", "year", ",", "time_str", "(", "adatetime", ")", "...
Return a date value in the format of "Month(abbreviated name) day, 4-digit-year at hour:minute [AP]M"
[ "Return", "a", "date", "value", "in", "the", "format", "of", "Month", "(", "abbreviated", "name", ")", "day", "4", "-", "digit", "-", "year", "at", "hour", ":", "minute", "[", "AP", "]", "M" ]
train
https://github.com/uw-it-aca/uw-restclients/blob/e12dcd32bf5296b6ebdf71798031594afb7852cb/restclients/util/date_formator.py#L20-L28
pyrapt/rapt
rapt/treebrd/grammars/proto_grammar.py
ProtoGrammar.string_literal
def string_literal(self): """ string_literal ::= "'" string "'" | "\"" string "\"" Any successful match is converted to a single quoted string to simplify post-parsed operations. """ return quotedString.setParseAction( lambda s, l, t: "'{string}'".format(stri...
python
def string_literal(self): """ string_literal ::= "'" string "'" | "\"" string "\"" Any successful match is converted to a single quoted string to simplify post-parsed operations. """ return quotedString.setParseAction( lambda s, l, t: "'{string}'".format(stri...
[ "def", "string_literal", "(", "self", ")", ":", "return", "quotedString", ".", "setParseAction", "(", "lambda", "s", ",", "l", ",", "t", ":", "\"'{string}'\"", ".", "format", "(", "string", "=", "removeQuotes", "(", "s", ",", "l", ",", "t", ")", ")", ...
string_literal ::= "'" string "'" | "\"" string "\"" Any successful match is converted to a single quoted string to simplify post-parsed operations.
[ "string_literal", "::", "=", "string", "|", "\\", "string", "\\" ]
train
https://github.com/pyrapt/rapt/blob/0193a07aafff83a887fdc9e5e0f25eafa5b1b205/rapt/treebrd/grammars/proto_grammar.py#L38-L46
j3ffhubb/pymarshal
pymarshal/api_docs/routes.py
RouteMethod.factory
def factory( method, description="", request_example=None, request_ctor=None, responses=None, method_choices=HTTP_METHODS, ): """ desc: Describes a single HTTP method of a URI args: - name: method type: str ...
python
def factory( method, description="", request_example=None, request_ctor=None, responses=None, method_choices=HTTP_METHODS, ): """ desc: Describes a single HTTP method of a URI args: - name: method type: str ...
[ "def", "factory", "(", "method", ",", "description", "=", "\"\"", ",", "request_example", "=", "None", ",", "request_ctor", "=", "None", ",", "responses", "=", "None", ",", "method_choices", "=", "HTTP_METHODS", ",", ")", ":", "return", "RouteMethod", "(", ...
desc: Describes a single HTTP method of a URI args: - name: method type: str desc: The HTTP request method to use - name: description type: str desc: The description of what this call does required: false...
[ "desc", ":", "Describes", "a", "single", "HTTP", "method", "of", "a", "URI", "args", ":", "-", "name", ":", "method", "type", ":", "str", "desc", ":", "The", "HTTP", "request", "method", "to", "use", "-", "name", ":", "description", "type", ":", "str...
train
https://github.com/j3ffhubb/pymarshal/blob/42cd1cccfabfdce5af633358a641fcd5183ee192/pymarshal/api_docs/routes.py#L178-L229
j3ffhubb/pymarshal
pymarshal/api_docs/routes.py
RouteMethodResponse.factory
def factory( description="", codes=[200], response_example=None, response_ctor=None, ): """ desc: Describes a response to an API call args: - name: description type: str desc: A description of the condition that ca...
python
def factory( description="", codes=[200], response_example=None, response_ctor=None, ): """ desc: Describes a response to an API call args: - name: description type: str desc: A description of the condition that ca...
[ "def", "factory", "(", "description", "=", "\"\"", ",", "codes", "=", "[", "200", "]", ",", "response_example", "=", "None", ",", "response_ctor", "=", "None", ",", ")", ":", "return", "RouteMethodResponse", "(", "description", ",", "codes", ",", "response...
desc: Describes a response to an API call args: - name: description type: str desc: A description of the condition that causes this response required: false default: "" - name: codes type: int ...
[ "desc", ":", "Describes", "a", "response", "to", "an", "API", "call", "args", ":", "-", "name", ":", "description", "type", ":", "str", "desc", ":", "A", "description", "of", "the", "condition", "that", "causes", "this", "response", "required", ":", "fal...
train
https://github.com/j3ffhubb/pymarshal/blob/42cd1cccfabfdce5af633358a641fcd5183ee192/pymarshal/api_docs/routes.py#L287-L324
bapakode/OmMongo
ommongo/query_expression.py
QueryField.get_absolute_name
def get_absolute_name(self): """ Returns the full dotted name of this field """ res = [] current = self while type(current) != type(None): if current.__matched_index: res.append('$') res.append(current.get_type().db_field) current = cu...
python
def get_absolute_name(self): """ Returns the full dotted name of this field """ res = [] current = self while type(current) != type(None): if current.__matched_index: res.append('$') res.append(current.get_type().db_field) current = cu...
[ "def", "get_absolute_name", "(", "self", ")", ":", "res", "=", "[", "]", "current", "=", "self", "while", "type", "(", "current", ")", "!=", "type", "(", "None", ")", ":", "if", "current", ".", "__matched_index", ":", "res", ".", "append", "(", "'$'"...
Returns the full dotted name of this field
[ "Returns", "the", "full", "dotted", "name", "of", "this", "field" ]
train
https://github.com/bapakode/OmMongo/blob/52b5a5420516dc709f2d2eb065818c7973991ce3/ommongo/query_expression.py#L121-L131
bapakode/OmMongo
ommongo/query_expression.py
QueryField.startswith
def startswith(self, prefix, ignore_case=False, options=None): """ A query to check if a field starts with a given prefix string **Example**: ``session.query(Spell).filter(Spells.name.startswith("abra", ignore_case=True))`` .. note:: This is a shortcut to .regex('^' + re.escape(prefix)...
python
def startswith(self, prefix, ignore_case=False, options=None): """ A query to check if a field starts with a given prefix string **Example**: ``session.query(Spell).filter(Spells.name.startswith("abra", ignore_case=True))`` .. note:: This is a shortcut to .regex('^' + re.escape(prefix)...
[ "def", "startswith", "(", "self", ",", "prefix", ",", "ignore_case", "=", "False", ",", "options", "=", "None", ")", ":", "return", "self", ".", "regex", "(", "'^'", "+", "re", ".", "escape", "(", "prefix", ")", ",", "ignore_case", "=", "ignore_case", ...
A query to check if a field starts with a given prefix string **Example**: ``session.query(Spell).filter(Spells.name.startswith("abra", ignore_case=True))`` .. note:: This is a shortcut to .regex('^' + re.escape(prefix)) MongoDB optimises such prefix expressions to use indexes ...
[ "A", "query", "to", "check", "if", "a", "field", "starts", "with", "a", "given", "prefix", "string" ]
train
https://github.com/bapakode/OmMongo/blob/52b5a5420516dc709f2d2eb065818c7973991ce3/ommongo/query_expression.py#L133-L144
bapakode/OmMongo
ommongo/query_expression.py
QueryField.endswith
def endswith(self, suffix, ignore_case=False, options=None): """ A query to check if a field ends with a given suffix string **Example**: ``session.query(Spell).filter(Spells.name.endswith("cadabra", ignore_case=True))`` """ return self.regex(re.escape(suffix) + '$', ignore_case=ig...
python
def endswith(self, suffix, ignore_case=False, options=None): """ A query to check if a field ends with a given suffix string **Example**: ``session.query(Spell).filter(Spells.name.endswith("cadabra", ignore_case=True))`` """ return self.regex(re.escape(suffix) + '$', ignore_case=ig...
[ "def", "endswith", "(", "self", ",", "suffix", ",", "ignore_case", "=", "False", ",", "options", "=", "None", ")", ":", "return", "self", ".", "regex", "(", "re", ".", "escape", "(", "suffix", ")", "+", "'$'", ",", "ignore_case", "=", "ignore_case", ...
A query to check if a field ends with a given suffix string **Example**: ``session.query(Spell).filter(Spells.name.endswith("cadabra", ignore_case=True))``
[ "A", "query", "to", "check", "if", "a", "field", "ends", "with", "a", "given", "suffix", "string" ]
train
https://github.com/bapakode/OmMongo/blob/52b5a5420516dc709f2d2eb065818c7973991ce3/ommongo/query_expression.py#L146-L152
bapakode/OmMongo
ommongo/query_expression.py
QueryField.regex
def regex(self, expression, ignore_case=False, options=None): """ A query to check if a field matches a given regular expression :param ignore_case: Whether or not to ignore the case (setting this to True is the same as setting the 'i' option) :param options: A string of option character...
python
def regex(self, expression, ignore_case=False, options=None): """ A query to check if a field matches a given regular expression :param ignore_case: Whether or not to ignore the case (setting this to True is the same as setting the 'i' option) :param options: A string of option character...
[ "def", "regex", "(", "self", ",", "expression", ",", "ignore_case", "=", "False", ",", "options", "=", "None", ")", ":", "regex", "=", "{", "'$regex'", ":", "expression", "}", "if", "options", "is", "not", "None", ":", "regex", "[", "'$options'", "]", ...
A query to check if a field matches a given regular expression :param ignore_case: Whether or not to ignore the case (setting this to True is the same as setting the 'i' option) :param options: A string of option characters, as per the MongoDB $regex operator (e.g. "imxs") **Example...
[ "A", "query", "to", "check", "if", "a", "field", "matches", "a", "given", "regular", "expression", ":", "param", "ignore_case", ":", "Whether", "or", "not", "to", "ignore", "the", "case", "(", "setting", "this", "to", "True", "is", "the", "same", "as", ...
train
https://github.com/bapakode/OmMongo/blob/52b5a5420516dc709f2d2eb065818c7973991ce3/ommongo/query_expression.py#L154-L170
bapakode/OmMongo
ommongo/query_expression.py
QueryField.near
def near(self, x, y, max_distance=None): """ Return documents near the given point """ expr = { self : {'$near' : [x, y]} } if max_distance is not None: expr[self]['$maxDistance'] = max_distance # if bucket_size is not None: # expr['$bu...
python
def near(self, x, y, max_distance=None): """ Return documents near the given point """ expr = { self : {'$near' : [x, y]} } if max_distance is not None: expr[self]['$maxDistance'] = max_distance # if bucket_size is not None: # expr['$bu...
[ "def", "near", "(", "self", ",", "x", ",", "y", ",", "max_distance", "=", "None", ")", ":", "expr", "=", "{", "self", ":", "{", "'$near'", ":", "[", "x", ",", "y", "]", "}", "}", "if", "max_distance", "is", "not", "None", ":", "expr", "[", "s...
Return documents near the given point
[ "Return", "documents", "near", "the", "given", "point" ]
train
https://github.com/bapakode/OmMongo/blob/52b5a5420516dc709f2d2eb065818c7973991ce3/ommongo/query_expression.py#L172-L182
bapakode/OmMongo
ommongo/query_expression.py
QueryField.near_sphere
def near_sphere(self, x, y, max_distance=None): """ Return documents near the given point using sphere distances """ expr = { self : {'$nearSphere' : [x, y]} } if max_distance is not None: expr[self]['$maxDistance'] = max_distance return QueryExpre...
python
def near_sphere(self, x, y, max_distance=None): """ Return documents near the given point using sphere distances """ expr = { self : {'$nearSphere' : [x, y]} } if max_distance is not None: expr[self]['$maxDistance'] = max_distance return QueryExpre...
[ "def", "near_sphere", "(", "self", ",", "x", ",", "y", ",", "max_distance", "=", "None", ")", ":", "expr", "=", "{", "self", ":", "{", "'$nearSphere'", ":", "[", "x", ",", "y", "]", "}", "}", "if", "max_distance", "is", "not", "None", ":", "expr"...
Return documents near the given point using sphere distances
[ "Return", "documents", "near", "the", "given", "point", "using", "sphere", "distances" ]
train
https://github.com/bapakode/OmMongo/blob/52b5a5420516dc709f2d2eb065818c7973991ce3/ommongo/query_expression.py#L184-L192
bapakode/OmMongo
ommongo/query_expression.py
QueryField.within_radius
def within_radius(self, x, y, radius): """ Adapted from the Mongo docs:: session.query(Places).filter(Places.loc.within_radius(1, 2, 50) """ return QueryExpression({ self : {'$within' : { '$center' : [[x, y], radius], }...
python
def within_radius(self, x, y, radius): """ Adapted from the Mongo docs:: session.query(Places).filter(Places.loc.within_radius(1, 2, 50) """ return QueryExpression({ self : {'$within' : { '$center' : [[x, y], radius], }...
[ "def", "within_radius", "(", "self", ",", "x", ",", "y", ",", "radius", ")", ":", "return", "QueryExpression", "(", "{", "self", ":", "{", "'$within'", ":", "{", "'$center'", ":", "[", "[", "x", ",", "y", "]", ",", "radius", "]", ",", "}", "}", ...
Adapted from the Mongo docs:: session.query(Places).filter(Places.loc.within_radius(1, 2, 50)
[ "Adapted", "from", "the", "Mongo", "docs", "::" ]
train
https://github.com/bapakode/OmMongo/blob/52b5a5420516dc709f2d2eb065818c7973991ce3/ommongo/query_expression.py#L205-L215
bapakode/OmMongo
ommongo/query_expression.py
QueryField.within_radius_sphere
def within_radius_sphere(self, x, y, radius): """ Adapted from the Mongo docs:: session.query(Places).filter(Places.loc.within_radius_sphere(1, 2, 50) """ return QueryExpression({ self : {'$within' : { '$centerSphere' : [[x, y], radius...
python
def within_radius_sphere(self, x, y, radius): """ Adapted from the Mongo docs:: session.query(Places).filter(Places.loc.within_radius_sphere(1, 2, 50) """ return QueryExpression({ self : {'$within' : { '$centerSphere' : [[x, y], radius...
[ "def", "within_radius_sphere", "(", "self", ",", "x", ",", "y", ",", "radius", ")", ":", "return", "QueryExpression", "(", "{", "self", ":", "{", "'$within'", ":", "{", "'$centerSphere'", ":", "[", "[", "x", ",", "y", "]", ",", "radius", "]", ",", ...
Adapted from the Mongo docs:: session.query(Places).filter(Places.loc.within_radius_sphere(1, 2, 50)
[ "Adapted", "from", "the", "Mongo", "docs", "::" ]
train
https://github.com/bapakode/OmMongo/blob/52b5a5420516dc709f2d2eb065818c7973991ce3/ommongo/query_expression.py#L216-L226
bapakode/OmMongo
ommongo/query_expression.py
QueryField.in_
def in_(self, *values): ''' A query to check if this query field is one of the values in ``values``. Produces a MongoDB ``$in`` expression. ''' return QueryExpression({ self : { '$in' : [self.get_type().wrap_value(value) for value in values] } })
python
def in_(self, *values): ''' A query to check if this query field is one of the values in ``values``. Produces a MongoDB ``$in`` expression. ''' return QueryExpression({ self : { '$in' : [self.get_type().wrap_value(value) for value in values] } })
[ "def", "in_", "(", "self", ",", "*", "values", ")", ":", "return", "QueryExpression", "(", "{", "self", ":", "{", "'$in'", ":", "[", "self", ".", "get_type", "(", ")", ".", "wrap_value", "(", "value", ")", "for", "value", "in", "values", "]", "}", ...
A query to check if this query field is one of the values in ``values``. Produces a MongoDB ``$in`` expression.
[ "A", "query", "to", "check", "if", "this", "query", "field", "is", "one", "of", "the", "values", "in", "values", ".", "Produces", "a", "MongoDB", "$in", "expression", "." ]
train
https://github.com/bapakode/OmMongo/blob/52b5a5420516dc709f2d2eb065818c7973991ce3/ommongo/query_expression.py#L242-L248
bapakode/OmMongo
ommongo/query_expression.py
QueryField.nin
def nin(self, *values): ''' A query to check if this query field is not one of the values in ``values``. Produces a MongoDB ``$nin`` expression. ''' return QueryExpression({ self : { '$nin' : [self.get_type().wrap_value(value) for value in values] } })
python
def nin(self, *values): ''' A query to check if this query field is not one of the values in ``values``. Produces a MongoDB ``$nin`` expression. ''' return QueryExpression({ self : { '$nin' : [self.get_type().wrap_value(value) for value in values] } })
[ "def", "nin", "(", "self", ",", "*", "values", ")", ":", "return", "QueryExpression", "(", "{", "self", ":", "{", "'$nin'", ":", "[", "self", ".", "get_type", "(", ")", ".", "wrap_value", "(", "value", ")", "for", "value", "in", "values", "]", "}",...
A query to check if this query field is not one of the values in ``values``. Produces a MongoDB ``$nin`` expression.
[ "A", "query", "to", "check", "if", "this", "query", "field", "is", "not", "one", "of", "the", "values", "in", "values", ".", "Produces", "a", "MongoDB", "$nin", "expression", "." ]
train
https://github.com/bapakode/OmMongo/blob/52b5a5420516dc709f2d2eb065818c7973991ce3/ommongo/query_expression.py#L250-L256
bapakode/OmMongo
ommongo/query_expression.py
QueryField.eq_
def eq_(self, value): ''' Creates a query expression where ``this field == value`` .. note:: The prefered usage is via an operator: ``User.name == value`` ''' if isinstance(value, QueryField): return self.__cached_id == value.__cached_id return QueryExpression({ ...
python
def eq_(self, value): ''' Creates a query expression where ``this field == value`` .. note:: The prefered usage is via an operator: ``User.name == value`` ''' if isinstance(value, QueryField): return self.__cached_id == value.__cached_id return QueryExpression({ ...
[ "def", "eq_", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "QueryField", ")", ":", "return", "self", ".", "__cached_id", "==", "value", ".", "__cached_id", "return", "QueryExpression", "(", "{", "self", ":", "self", ".", ...
Creates a query expression where ``this field == value`` .. note:: The prefered usage is via an operator: ``User.name == value``
[ "Creates", "a", "query", "expression", "where", "this", "field", "==", "value" ]
train
https://github.com/bapakode/OmMongo/blob/52b5a5420516dc709f2d2eb065818c7973991ce3/ommongo/query_expression.py#L274-L281
bapakode/OmMongo
ommongo/query_expression.py
QueryField.ne_
def ne_(self, value): ''' Creates a query expression where ``this field != value`` .. note:: The prefered usage is via an operator: ``User.name != value`` ''' if isinstance(value, QueryField): return self.__cached_id != value.__cached_id return self.__comparator(...
python
def ne_(self, value): ''' Creates a query expression where ``this field != value`` .. note:: The prefered usage is via an operator: ``User.name != value`` ''' if isinstance(value, QueryField): return self.__cached_id != value.__cached_id return self.__comparator(...
[ "def", "ne_", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "QueryField", ")", ":", "return", "self", ".", "__cached_id", "!=", "value", ".", "__cached_id", "return", "self", ".", "__comparator", "(", "'$ne'", ",", "value", ...
Creates a query expression where ``this field != value`` .. note:: The prefered usage is via an operator: ``User.name != value``
[ "Creates", "a", "query", "expression", "where", "this", "field", "!", "=", "value" ]
train
https://github.com/bapakode/OmMongo/blob/52b5a5420516dc709f2d2eb065818c7973991ce3/ommongo/query_expression.py#L303-L310
bapakode/OmMongo
ommongo/query_expression.py
QueryField.elem_match
def elem_match(self, value): ''' This method does two things depending on the context: 1. In the context of a query expression it: Creates a query expression to do an $elemMatch on the selected field. If the type of this field is a DocumentField the value can b...
python
def elem_match(self, value): ''' This method does two things depending on the context: 1. In the context of a query expression it: Creates a query expression to do an $elemMatch on the selected field. If the type of this field is a DocumentField the value can b...
[ "def", "elem_match", "(", "self", ",", "value", ")", ":", "self", ".", "__is_elem_match", "=", "True", "if", "not", "self", ".", "__type", ".", "is_sequence_field", ":", "raise", "BadQueryException", "(", "'elem_match called on a non-sequence '", "'field: '", "+",...
This method does two things depending on the context: 1. In the context of a query expression it: Creates a query expression to do an $elemMatch on the selected field. If the type of this field is a DocumentField the value can be either a QueryExpression using that Doc...
[ "This", "method", "does", "two", "things", "depending", "on", "the", "context", ":" ]
train
https://github.com/bapakode/OmMongo/blob/52b5a5420516dc709f2d2eb065818c7973991ce3/ommongo/query_expression.py#L330-L365
bapakode/OmMongo
ommongo/query_expression.py
QueryExpression.not_
def not_(self): ''' Negates this instance's query expression using MongoDB's ``$not`` operator **Example**: ``(User.name == 'Jeff').not_()`` .. note:: Another usage is via an operator, but parens are needed to get past precedence issues: ``~ (User.name == 'J...
python
def not_(self): ''' Negates this instance's query expression using MongoDB's ``$not`` operator **Example**: ``(User.name == 'Jeff').not_()`` .. note:: Another usage is via an operator, but parens are needed to get past precedence issues: ``~ (User.name == 'J...
[ "def", "not_", "(", "self", ")", ":", "ret_obj", "=", "{", "}", "for", "k", ",", "v", "in", "self", ".", "obj", ".", "items", "(", ")", ":", "if", "not", "isinstance", "(", "v", ",", "dict", ")", ":", "ret_obj", "[", "k", "]", "=", "{", "'$...
Negates this instance's query expression using MongoDB's ``$not`` operator **Example**: ``(User.name == 'Jeff').not_()`` .. note:: Another usage is via an operator, but parens are needed to get past precedence issues: ``~ (User.name == 'Jeff')``
[ "Negates", "this", "instance", "s", "query", "expression", "using", "MongoDB", "s", "$not", "operator" ]
train
https://github.com/bapakode/OmMongo/blob/52b5a5420516dc709f2d2eb065818c7973991ce3/ommongo/query_expression.py#L393-L421
bapakode/OmMongo
ommongo/query_expression.py
QueryExpression.or_
def or_(self, expression): ''' Adds the given expression to this instance's MongoDB ``$or`` expression, starting a new one if one does not exst **Example**: ``(User.name == 'Jeff').or_(User.name == 'Jack')`` .. note:: The prefered usageis via an operator: ``User.name == 'Je...
python
def or_(self, expression): ''' Adds the given expression to this instance's MongoDB ``$or`` expression, starting a new one if one does not exst **Example**: ``(User.name == 'Jeff').or_(User.name == 'Jack')`` .. note:: The prefered usageis via an operator: ``User.name == 'Je...
[ "def", "or_", "(", "self", ",", "expression", ")", ":", "if", "'$or'", "in", "self", ".", "obj", ":", "self", ".", "obj", "[", "'$or'", "]", ".", "append", "(", "expression", ".", "obj", ")", "return", "self", "self", ".", "obj", "=", "{", "'$or'...
Adds the given expression to this instance's MongoDB ``$or`` expression, starting a new one if one does not exst **Example**: ``(User.name == 'Jeff').or_(User.name == 'Jack')`` .. note:: The prefered usageis via an operator: ``User.name == 'Jeff' | User.name == 'Jack'``
[ "Adds", "the", "given", "expression", "to", "this", "instance", "s", "MongoDB", "$or", "expression", "starting", "a", "new", "one", "if", "one", "does", "not", "exst" ]
train
https://github.com/bapakode/OmMongo/blob/52b5a5420516dc709f2d2eb065818c7973991ce3/ommongo/query_expression.py#L429-L445
uw-it-aca/uw-restclients
restclients/r25/__init__.py
get_resource
def get_resource(url): """ Issue a GET request to R25 with the given url and return a response as an etree element. """ response = R25_DAO().getURL(url, {"Accept": "text/xml"}) if response.status != 200: raise DataFailureException(url, response.status, response.data) tree = etree.fr...
python
def get_resource(url): """ Issue a GET request to R25 with the given url and return a response as an etree element. """ response = R25_DAO().getURL(url, {"Accept": "text/xml"}) if response.status != 200: raise DataFailureException(url, response.status, response.data) tree = etree.fr...
[ "def", "get_resource", "(", "url", ")", ":", "response", "=", "R25_DAO", "(", ")", ".", "getURL", "(", "url", ",", "{", "\"Accept\"", ":", "\"text/xml\"", "}", ")", "if", "response", ".", "status", "!=", "200", ":", "raise", "DataFailureException", "(", ...
Issue a GET request to R25 with the given url and return a response as an etree element.
[ "Issue", "a", "GET", "request", "to", "R25", "with", "the", "given", "url", "and", "return", "a", "response", "as", "an", "etree", "element", "." ]
train
https://github.com/uw-it-aca/uw-restclients/blob/e12dcd32bf5296b6ebdf71798031594afb7852cb/restclients/r25/__init__.py#L10-L26
PvtHaggard/pydarksky
pydarksky/darksky.py
weather
def weather(api_key, latitude, longitude, date_time=None): # type:(str, float, float) -> Weather """ This is a shortcut method that can be used to perform a basic weather request with the default settings. :param str api_key: Darksky.net API key :param float latitude: The requested latitude. Maybe ...
python
def weather(api_key, latitude, longitude, date_time=None): # type:(str, float, float) -> Weather """ This is a shortcut method that can be used to perform a basic weather request with the default settings. :param str api_key: Darksky.net API key :param float latitude: The requested latitude. Maybe ...
[ "def", "weather", "(", "api_key", ",", "latitude", ",", "longitude", ",", "date_time", "=", "None", ")", ":", "# type:(str, float, float) -> Weather", "return", "DarkSky", "(", "api_key", ")", ".", "weather", "(", "latitude", ",", "longitude", ",", "date_time", ...
This is a shortcut method that can be used to perform a basic weather request with the default settings. :param str api_key: Darksky.net API key :param float latitude: The requested latitude. Maybe different from the value returned from an API request :param float longitude: The requested longitude. Maybe ...
[ "This", "is", "a", "shortcut", "method", "that", "can", "be", "used", "to", "perform", "a", "basic", "weather", "request", "with", "the", "default", "settings", "." ]
train
https://github.com/PvtHaggard/pydarksky/blob/c2d68d311bf0a58125fbfe31eff124356899c75b/pydarksky/darksky.py#L353-L365
PvtHaggard/pydarksky
pydarksky/darksky.py
DarkSky.url
def url(self): # type:() -> str """ Build and returns a URL used to make a Dark Sky API call. """ url = "https://api.darksky.net/forecast/{key}/{lat},{lon}".format(key=self.api_key, lat=self.latitude, ...
python
def url(self): # type:() -> str """ Build and returns a URL used to make a Dark Sky API call. """ url = "https://api.darksky.net/forecast/{key}/{lat},{lon}".format(key=self.api_key, lat=self.latitude, ...
[ "def", "url", "(", "self", ")", ":", "# type:() -> str", "url", "=", "\"https://api.darksky.net/forecast/{key}/{lat},{lon}\"", ".", "format", "(", "key", "=", "self", ".", "api_key", ",", "lat", "=", "self", ".", "latitude", ",", "lon", "=", "self", ".", "lo...
Build and returns a URL used to make a Dark Sky API call.
[ "Build", "and", "returns", "a", "URL", "used", "to", "make", "a", "Dark", "Sky", "API", "call", "." ]
train
https://github.com/PvtHaggard/pydarksky/blob/c2d68d311bf0a58125fbfe31eff124356899c75b/pydarksky/darksky.py#L88-L114
PvtHaggard/pydarksky
pydarksky/darksky.py
DarkSky.weather
def weather(self, latitude=None, longitude=None, date=None): # type:(float, float, datetime) -> Weather """ :param float latitude: Locations latitude :param float longitude: Locations longitude :param datetime or str or int date: Date/time for historical weather data :ra...
python
def weather(self, latitude=None, longitude=None, date=None): # type:(float, float, datetime) -> Weather """ :param float latitude: Locations latitude :param float longitude: Locations longitude :param datetime or str or int date: Date/time for historical weather data :ra...
[ "def", "weather", "(", "self", ",", "latitude", "=", "None", ",", "longitude", "=", "None", ",", "date", "=", "None", ")", ":", "# type:(float, float, datetime) -> Weather", "# If params are default(None) check if latitude/longitude have already been defined(Not None)", "# Ot...
:param float latitude: Locations latitude :param float longitude: Locations longitude :param datetime or str or int date: Date/time for historical weather data :raises requests.exceptions.HTTPError: Raises on bad http response :raises TypeError: Raises on invalid param types :r...
[ ":", "param", "float", "latitude", ":", "Locations", "latitude", ":", "param", "float", "longitude", ":", "Locations", "longitude", ":", "param", "datetime", "or", "str", "or", "int", "date", ":", "Date", "/", "time", "for", "historical", "weather", "data" ]
train
https://github.com/PvtHaggard/pydarksky/blob/c2d68d311bf0a58125fbfe31eff124356899c75b/pydarksky/darksky.py#L255-L311
PvtHaggard/pydarksky
pydarksky/darksky.py
DarkSky.exclude_invert
def exclude_invert(self): # type:() -> None """ Inverts the values in self.exclude .. code-block:: python >>> import pydarksky >>> darksky = pydarksky.DarkSky('0' * 32) >>> darksky.EXCLUDES ('currently', 'minutely', 'hourly', 'daily', 'a...
python
def exclude_invert(self): # type:() -> None """ Inverts the values in self.exclude .. code-block:: python >>> import pydarksky >>> darksky = pydarksky.DarkSky('0' * 32) >>> darksky.EXCLUDES ('currently', 'minutely', 'hourly', 'daily', 'a...
[ "def", "exclude_invert", "(", "self", ")", ":", "# type:() -> None", "tmp", "=", "self", ".", "exclude", "self", ".", "_exclude", "=", "[", "]", "for", "i", "in", "self", ".", "EXCLUDES", ":", "if", "i", "not", "in", "tmp", ":", "self", ".", "_exclud...
Inverts the values in self.exclude .. code-block:: python >>> import pydarksky >>> darksky = pydarksky.DarkSky('0' * 32) >>> darksky.EXCLUDES ('currently', 'minutely', 'hourly', 'daily', 'alerts', 'flags') >>> darksky.exclude = ["alerts", "flags"] ...
[ "Inverts", "the", "values", "in", "self", ".", "exclude" ]
train
https://github.com/PvtHaggard/pydarksky/blob/c2d68d311bf0a58125fbfe31eff124356899c75b/pydarksky/darksky.py#L322-L350
klen/adrest
adrest/mixin/auth.py
AuthMixin.authenticate
def authenticate(self, request): """ Attempt to authenticate the request. :param request: django.http.Request instance :return bool: True if success else raises HTTP_401 """ authenticators = self._meta.authenticators if request.method == 'OPTIONS' and ADREST_ALLOW_OPT...
python
def authenticate(self, request): """ Attempt to authenticate the request. :param request: django.http.Request instance :return bool: True if success else raises HTTP_401 """ authenticators = self._meta.authenticators if request.method == 'OPTIONS' and ADREST_ALLOW_OPT...
[ "def", "authenticate", "(", "self", ",", "request", ")", ":", "authenticators", "=", "self", ".", "_meta", ".", "authenticators", "if", "request", ".", "method", "==", "'OPTIONS'", "and", "ADREST_ALLOW_OPTIONS", ":", "self", ".", "auth", "=", "AnonimousAuthent...
Attempt to authenticate the request. :param request: django.http.Request instance :return bool: True if success else raises HTTP_401
[ "Attempt", "to", "authenticate", "the", "request", "." ]
train
https://github.com/klen/adrest/blob/8b75c67123cffabe5ed98c222bb7ab43c904d89c/adrest/mixin/auth.py#L46-L73
klen/adrest
adrest/mixin/auth.py
AuthMixin.check_rights
def check_rights(self, resources, request=None): """ Check rights for resources. :return bool: True if operation is success else HTTP_403_FORBIDDEN """ if not self.auth: return True try: if not self.auth.test_rights(resources, request=request): ...
python
def check_rights(self, resources, request=None): """ Check rights for resources. :return bool: True if operation is success else HTTP_403_FORBIDDEN """ if not self.auth: return True try: if not self.auth.test_rights(resources, request=request): ...
[ "def", "check_rights", "(", "self", ",", "resources", ",", "request", "=", "None", ")", ":", "if", "not", "self", ".", "auth", ":", "return", "True", "try", ":", "if", "not", "self", ".", "auth", ".", "test_rights", "(", "resources", ",", "request", ...
Check rights for resources. :return bool: True if operation is success else HTTP_403_FORBIDDEN
[ "Check", "rights", "for", "resources", "." ]
train
https://github.com/klen/adrest/blob/8b75c67123cffabe5ed98c222bb7ab43c904d89c/adrest/mixin/auth.py#L75-L89
draperunner/fjlc
fjlc/lexicon/lexicon_creator.py
LexiconCreator.create_lexicon
def create_lexicon(self, data_set_reader, n_grams, min_total_occurrences, min_sentiment_value, filters): """ Generates sentiment lexicon using PMI on words and classification of context they are in. :param: dataSetReader Dataset containing tweets and their sentiment classificat...
python
def create_lexicon(self, data_set_reader, n_grams, min_total_occurrences, min_sentiment_value, filters): """ Generates sentiment lexicon using PMI on words and classification of context they are in. :param: dataSetReader Dataset containing tweets and their sentiment classificat...
[ "def", "create_lexicon", "(", "self", ",", "data_set_reader", ",", "n_grams", ",", "min_total_occurrences", ",", "min_sentiment_value", ",", "filters", ")", ":", "counter", "=", "self", ".", "count_n_grams_py_polarity", "(", "data_set_reader", ",", "n_grams", ",", ...
Generates sentiment lexicon using PMI on words and classification of context they are in. :param: dataSetReader Dataset containing tweets and their sentiment classification :param: nGrams n-grams to calculate sentiment for (with n>1, singletons are calculated automatically...
[ "Generates", "sentiment", "lexicon", "using", "PMI", "on", "words", "and", "classification", "of", "context", "they", "are", "in", ".", ":", "param", ":", "dataSetReader", "Dataset", "containing", "tweets", "and", "their", "sentiment", "classification", ":", "pa...
train
https://github.com/draperunner/fjlc/blob/d2cc8cf1244984e7caf0bf95b11ed1677a94c994/fjlc/lexicon/lexicon_creator.py#L15-L52
draperunner/fjlc
fjlc/lexicon/lexicon_creator.py
LexiconCreator.count_n_grams_py_polarity
def count_n_grams_py_polarity(self, data_set_reader, n_grams, filters): """ Returns a map of n-gram and the number of times it appeared in positive context and the number of times it appeared in negative context in dataset file. :param data_set_reader: Dataset containing tweets and thei...
python
def count_n_grams_py_polarity(self, data_set_reader, n_grams, filters): """ Returns a map of n-gram and the number of times it appeared in positive context and the number of times it appeared in negative context in dataset file. :param data_set_reader: Dataset containing tweets and thei...
[ "def", "count_n_grams_py_polarity", "(", "self", ",", "data_set_reader", ",", "n_grams", ",", "filters", ")", ":", "self", ".", "data_set_reader", "=", "data_set_reader", "token_trie", "=", "TokenTrie", "(", "n_grams", ")", "counter", "=", "{", "}", "# Todo: par...
Returns a map of n-gram and the number of times it appeared in positive context and the number of times it appeared in negative context in dataset file. :param data_set_reader: Dataset containing tweets and their classification :param n_grams: n-grams to count occurrences for :param fil...
[ "Returns", "a", "map", "of", "n", "-", "gram", "and", "the", "number", "of", "times", "it", "appeared", "in", "positive", "context", "and", "the", "number", "of", "times", "it", "appeared", "in", "negative", "context", "in", "dataset", "file", "." ]
train
https://github.com/draperunner/fjlc/blob/d2cc8cf1244984e7caf0bf95b11ed1677a94c994/fjlc/lexicon/lexicon_creator.py#L54-L86
inspirehep/inspire-utils
inspire_utils/config.py
load_config
def load_config(paths=DEFAULT_CONFIG_PATHS): """Attempt to load config from paths, in order. Args: paths (List[string]): list of paths to python files Return: Config: loaded config """ config = Config() for path in paths: if os.path.isfile(path): config.load...
python
def load_config(paths=DEFAULT_CONFIG_PATHS): """Attempt to load config from paths, in order. Args: paths (List[string]): list of paths to python files Return: Config: loaded config """ config = Config() for path in paths: if os.path.isfile(path): config.load...
[ "def", "load_config", "(", "paths", "=", "DEFAULT_CONFIG_PATHS", ")", ":", "config", "=", "Config", "(", ")", "for", "path", "in", "paths", ":", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "config", ".", "load_pyfile", "(", "path", ...
Attempt to load config from paths, in order. Args: paths (List[string]): list of paths to python files Return: Config: loaded config
[ "Attempt", "to", "load", "config", "from", "paths", "in", "order", "." ]
train
https://github.com/inspirehep/inspire-utils/blob/b0b5983c58700735dfde75e4c8bd32834f2473d4/inspire_utils/config.py#L75-L89
inspirehep/inspire-utils
inspire_utils/config.py
Config.load_pyfile
def load_pyfile(self, path): """Load python file as config. Args: path (string): path to the python file """ with open(path) as config_file: contents = config_file.read() try: exec(compile(contents, path, 'exec'), self) exc...
python
def load_pyfile(self, path): """Load python file as config. Args: path (string): path to the python file """ with open(path) as config_file: contents = config_file.read() try: exec(compile(contents, path, 'exec'), self) exc...
[ "def", "load_pyfile", "(", "self", ",", "path", ")", ":", "with", "open", "(", "path", ")", "as", "config_file", ":", "contents", "=", "config_file", ".", "read", "(", ")", "try", ":", "exec", "(", "compile", "(", "contents", ",", "path", ",", "'exec...
Load python file as config. Args: path (string): path to the python file
[ "Load", "python", "file", "as", "config", "." ]
train
https://github.com/inspirehep/inspire-utils/blob/b0b5983c58700735dfde75e4c8bd32834f2473d4/inspire_utils/config.py#L61-L72
coldmind/django-postgres-pgpfields
django_postgres_pgpfields/managers.py
PGPEncryptedManager.get_queryset
def get_queryset(self, *args, **kwargs): """Django queryset.extra() is used here to add decryption sql to query.""" select_sql = {} encrypted_fields = [] for f in self.model._meta.get_fields_with_model(): field = f[0] if isinstance(field, PGPMixin): ...
python
def get_queryset(self, *args, **kwargs): """Django queryset.extra() is used here to add decryption sql to query.""" select_sql = {} encrypted_fields = [] for f in self.model._meta.get_fields_with_model(): field = f[0] if isinstance(field, PGPMixin): ...
[ "def", "get_queryset", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "select_sql", "=", "{", "}", "encrypted_fields", "=", "[", "]", "for", "f", "in", "self", ".", "model", ".", "_meta", ".", "get_fields_with_model", "(", ")", ":"...
Django queryset.extra() is used here to add decryption sql to query.
[ "Django", "queryset", ".", "extra", "()", "is", "used", "here", "to", "add", "decryption", "sql", "to", "query", "." ]
train
https://github.com/coldmind/django-postgres-pgpfields/blob/8ad7ab6254f06104012696fa7f99d0f6727fb667/django_postgres_pgpfields/managers.py#L22-L36
andycasey/sick
sick/models/base.py
channel_parameters
def channel_parameters(parameter_prefix, channel_names, configuration_entry): """ Return parameters specific to a channel for a model. """ if configuration_entry in (True, False): return ([], [parameter_prefix])[configuration_entry] parameters = [] if isinstance(configuration_entry, di...
python
def channel_parameters(parameter_prefix, channel_names, configuration_entry): """ Return parameters specific to a channel for a model. """ if configuration_entry in (True, False): return ([], [parameter_prefix])[configuration_entry] parameters = [] if isinstance(configuration_entry, di...
[ "def", "channel_parameters", "(", "parameter_prefix", ",", "channel_names", ",", "configuration_entry", ")", ":", "if", "configuration_entry", "in", "(", "True", ",", "False", ")", ":", "return", "(", "[", "]", ",", "[", "parameter_prefix", "]", ")", "[", "c...
Return parameters specific to a channel for a model.
[ "Return", "parameters", "specific", "to", "a", "channel", "for", "a", "model", "." ]
train
https://github.com/andycasey/sick/blob/6c37686182794c4cafea45abf7062b30b789b1a2/sick/models/base.py#L644-L660
andycasey/sick
sick/models/base.py
BaseModel.save
def save(self, filename, clobber=False, **kwargs): """ Save the model configuration to a YAML-formatted file. :param filename: The filename to save the model configuration to. :type filename: str :param clobber: [optional] Clobber the filena...
python
def save(self, filename, clobber=False, **kwargs): """ Save the model configuration to a YAML-formatted file. :param filename: The filename to save the model configuration to. :type filename: str :param clobber: [optional] Clobber the filena...
[ "def", "save", "(", "self", ",", "filename", ",", "clobber", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", "and", "not", "clobber", ":", "raise", "IOError", "(", "\"filename {} already ex...
Save the model configuration to a YAML-formatted file. :param filename: The filename to save the model configuration to. :type filename: str :param clobber: [optional] Clobber the filename if it already exists. :type clobber: bool ...
[ "Save", "the", "model", "configuration", "to", "a", "YAML", "-", "formatted", "file", "." ]
train
https://github.com/andycasey/sick/blob/6c37686182794c4cafea45abf7062b30b789b1a2/sick/models/base.py#L82-L115
andycasey/sick
sick/models/base.py
BaseModel._latex_labels
def _latex_labels(self, labels): """ LaTeX-ify labels based on information provided in the configuration. """ config = self._configuration.get("latex_labels", {}) return [config.get(label, label) for label in labels]
python
def _latex_labels(self, labels): """ LaTeX-ify labels based on information provided in the configuration. """ config = self._configuration.get("latex_labels", {}) return [config.get(label, label) for label in labels]
[ "def", "_latex_labels", "(", "self", ",", "labels", ")", ":", "config", "=", "self", ".", "_configuration", ".", "get", "(", "\"latex_labels\"", ",", "{", "}", ")", "return", "[", "config", ".", "get", "(", "label", ",", "label", ")", "for", "label", ...
LaTeX-ify labels based on information provided in the configuration.
[ "LaTeX", "-", "ify", "labels", "based", "on", "information", "provided", "in", "the", "configuration", "." ]
train
https://github.com/andycasey/sick/blob/6c37686182794c4cafea45abf7062b30b789b1a2/sick/models/base.py#L169-L175
andycasey/sick
sick/models/base.py
BaseModel.parameters
def parameters(self): """ Return the model parameters. """ try: return self._parameters except AttributeError: None parameters = [] parameters.extend(self.grid_points.dtype.names) model_configuration = self._configuration.get("model", {}) ...
python
def parameters(self): """ Return the model parameters. """ try: return self._parameters except AttributeError: None parameters = [] parameters.extend(self.grid_points.dtype.names) model_configuration = self._configuration.get("model", {}) ...
[ "def", "parameters", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_parameters", "except", "AttributeError", ":", "None", "parameters", "=", "[", "]", "parameters", ".", "extend", "(", "self", ".", "grid_points", ".", "dtype", ".", "names", ...
Return the model parameters.
[ "Return", "the", "model", "parameters", "." ]
train
https://github.com/andycasey/sick/blob/6c37686182794c4cafea45abf7062b30b789b1a2/sick/models/base.py#L192-L247
andycasey/sick
sick/models/base.py
BaseModel._overlapping_channels
def _overlapping_channels(self, wavelengths): """ Return the channels that match the given wavelength array. """ sizes = self.meta["channel_sizes"] min_a, max_a = wavelengths.min(), wavelengths.max() matched_channel_names = [] for i, (name, size) in enumerate(zi...
python
def _overlapping_channels(self, wavelengths): """ Return the channels that match the given wavelength array. """ sizes = self.meta["channel_sizes"] min_a, max_a = wavelengths.min(), wavelengths.max() matched_channel_names = [] for i, (name, size) in enumerate(zi...
[ "def", "_overlapping_channels", "(", "self", ",", "wavelengths", ")", ":", "sizes", "=", "self", ".", "meta", "[", "\"channel_sizes\"", "]", "min_a", ",", "max_a", "=", "wavelengths", ".", "min", "(", ")", ",", "wavelengths", ".", "max", "(", ")", "match...
Return the channels that match the given wavelength array.
[ "Return", "the", "channels", "that", "match", "the", "given", "wavelength", "array", "." ]
train
https://github.com/andycasey/sick/blob/6c37686182794c4cafea45abf7062b30b789b1a2/sick/models/base.py#L250-L265
andycasey/sick
sick/models/base.py
BaseModel._format_data
def _format_data(self, data): """ Sort the data in blue wavelengths to red, and ignore any spectra that have entirely non-finite or negative fluxes. """ return [spectrum for spectrum in \ sorted(data if isinstance(data, (list, tuple)) else [data], key=...
python
def _format_data(self, data): """ Sort the data in blue wavelengths to red, and ignore any spectra that have entirely non-finite or negative fluxes. """ return [spectrum for spectrum in \ sorted(data if isinstance(data, (list, tuple)) else [data], key=...
[ "def", "_format_data", "(", "self", ",", "data", ")", ":", "return", "[", "spectrum", "for", "spectrum", "in", "sorted", "(", "data", "if", "isinstance", "(", "data", ",", "(", "list", ",", "tuple", ")", ")", "else", "[", "data", "]", ",", "key", "...
Sort the data in blue wavelengths to red, and ignore any spectra that have entirely non-finite or negative fluxes.
[ "Sort", "the", "data", "in", "blue", "wavelengths", "to", "red", "and", "ignore", "any", "spectra", "that", "have", "entirely", "non", "-", "finite", "or", "negative", "fluxes", "." ]
train
https://github.com/andycasey/sick/blob/6c37686182794c4cafea45abf7062b30b789b1a2/sick/models/base.py#L277-L284
andycasey/sick
sick/models/base.py
BaseModel._apply_data_mask
def _apply_data_mask(self, data): """ Apply pre-defined masks to the data. """ data = self._format_data(data) masked_data, pixels_affected = [], 0 data_mask = self._configuration.get("masks", {}).get("data", []) for spectrum in data: masked_spectrum ...
python
def _apply_data_mask(self, data): """ Apply pre-defined masks to the data. """ data = self._format_data(data) masked_data, pixels_affected = [], 0 data_mask = self._configuration.get("masks", {}).get("data", []) for spectrum in data: masked_spectrum ...
[ "def", "_apply_data_mask", "(", "self", ",", "data", ")", ":", "data", "=", "self", ".", "_format_data", "(", "data", ")", "masked_data", ",", "pixels_affected", "=", "[", "]", ",", "0", "data_mask", "=", "self", ".", "_configuration", ".", "get", "(", ...
Apply pre-defined masks to the data.
[ "Apply", "pre", "-", "defined", "masks", "to", "the", "data", "." ]
train
https://github.com/andycasey/sick/blob/6c37686182794c4cafea45abf7062b30b789b1a2/sick/models/base.py#L286-L308
andycasey/sick
sick/models/base.py
BaseModel._model_mask
def _model_mask(self, wavelengths=None): """ Apply pre-defined model masks. """ if wavelengths is None: wavelengths = self.wavelengths wavelengths = np.array(wavelengths) mask = np.ones_like(wavelengths, dtype=bool) model_mask = self._configuration.g...
python
def _model_mask(self, wavelengths=None): """ Apply pre-defined model masks. """ if wavelengths is None: wavelengths = self.wavelengths wavelengths = np.array(wavelengths) mask = np.ones_like(wavelengths, dtype=bool) model_mask = self._configuration.g...
[ "def", "_model_mask", "(", "self", ",", "wavelengths", "=", "None", ")", ":", "if", "wavelengths", "is", "None", ":", "wavelengths", "=", "self", ".", "wavelengths", "wavelengths", "=", "np", ".", "array", "(", "wavelengths", ")", "mask", "=", "np", ".",...
Apply pre-defined model masks.
[ "Apply", "pre", "-", "defined", "model", "masks", "." ]
train
https://github.com/andycasey/sick/blob/6c37686182794c4cafea45abf7062b30b789b1a2/sick/models/base.py#L310-L326
andycasey/sick
sick/models/base.py
BaseModel._match_channels_to_data
def _match_channels_to_data(self, data): """ Match observed data to a channel, and return possibly superfluous model parameters. """ data = self._format_data(data) matched_channels = [] for spectrum in data: match = self._overlapping_channels(spectru...
python
def _match_channels_to_data(self, data): """ Match observed data to a channel, and return possibly superfluous model parameters. """ data = self._format_data(data) matched_channels = [] for spectrum in data: match = self._overlapping_channels(spectru...
[ "def", "_match_channels_to_data", "(", "self", ",", "data", ")", ":", "data", "=", "self", ".", "_format_data", "(", "data", ")", "matched_channels", "=", "[", "]", "for", "spectrum", "in", "data", ":", "match", "=", "self", ".", "_overlapping_channels", "...
Match observed data to a channel, and return possibly superfluous model parameters.
[ "Match", "observed", "data", "to", "a", "channel", "and", "return", "possibly", "superfluous", "model", "parameters", "." ]
train
https://github.com/andycasey/sick/blob/6c37686182794c4cafea45abf7062b30b789b1a2/sick/models/base.py#L329-L373
andycasey/sick
sick/models/base.py
BaseModel._initial_proposal_distribution
def _initial_proposal_distribution(self, parameters, theta, size, default_std=1e-4): """ Generate an initial proposal distribution around the point theta. """ missing_parameters = set(parameters).difference(theta) if missing_parameters: raise ValueError("cann...
python
def _initial_proposal_distribution(self, parameters, theta, size, default_std=1e-4): """ Generate an initial proposal distribution around the point theta. """ missing_parameters = set(parameters).difference(theta) if missing_parameters: raise ValueError("cann...
[ "def", "_initial_proposal_distribution", "(", "self", ",", "parameters", ",", "theta", ",", "size", ",", "default_std", "=", "1e-4", ")", ":", "missing_parameters", "=", "set", "(", "parameters", ")", ".", "difference", "(", "theta", ")", "if", "missing_parame...
Generate an initial proposal distribution around the point theta.
[ "Generate", "an", "initial", "proposal", "distribution", "around", "the", "point", "theta", "." ]
train
https://github.com/andycasey/sick/blob/6c37686182794c4cafea45abf7062b30b789b1a2/sick/models/base.py#L376-L398
andycasey/sick
sick/models/base.py
BaseModel.cast
def cast(self, new_model_name, new_channels, output_dir=None, clobber=False, **kwargs): """ Cast a new model from this model. The new model might have a restricted wavelength range, different channels, larger sampling/binning, and/or a lower spectral resolution. """ ...
python
def cast(self, new_model_name, new_channels, output_dir=None, clobber=False, **kwargs): """ Cast a new model from this model. The new model might have a restricted wavelength range, different channels, larger sampling/binning, and/or a lower spectral resolution. """ ...
[ "def", "cast", "(", "self", ",", "new_model_name", ",", "new_channels", ",", "output_dir", "=", "None", ",", "clobber", "=", "False", ",", "*", "*", "kwargs", ")", ":", "output_dir", "=", "output_dir", "if", "output_dir", "is", "not", "None", "else", "os...
Cast a new model from this model. The new model might have a restricted wavelength range, different channels, larger sampling/binning, and/or a lower spectral resolution.
[ "Cast", "a", "new", "model", "from", "this", "model", ".", "The", "new", "model", "might", "have", "a", "restricted", "wavelength", "range", "different", "channels", "larger", "sampling", "/", "binning", "and", "/", "or", "a", "lower", "spectral", "resolutio...
train
https://github.com/andycasey/sick/blob/6c37686182794c4cafea45abf7062b30b789b1a2/sick/models/base.py#L416-L639
uw-it-aca/uw-restclients
restclients/dao_implementation/mock.py
get_mockdata_url
def get_mockdata_url(service_name, implementation_name, url, headers): """ :param service_name: possible "sws", "pws", "book", "hfs", etc. :param implementation_name: possible values: "file", etc. """ RESOURCE_ROOT = _mockdata_path_root(service_name, implementat...
python
def get_mockdata_url(service_name, implementation_name, url, headers): """ :param service_name: possible "sws", "pws", "book", "hfs", etc. :param implementation_name: possible values: "file", etc. """ RESOURCE_ROOT = _mockdata_path_root(service_name, implementat...
[ "def", "get_mockdata_url", "(", "service_name", ",", "implementation_name", ",", "url", ",", "headers", ")", ":", "RESOURCE_ROOT", "=", "_mockdata_path_root", "(", "service_name", ",", "implementation_name", ")", "file_path", "=", "None", "success", "=", "False", ...
:param service_name: possible "sws", "pws", "book", "hfs", etc. :param implementation_name: possible values: "file", etc.
[ ":", "param", "service_name", ":", "possible", "sws", "pws", "book", "hfs", "etc", ".", ":", "param", "implementation_name", ":", "possible", "values", ":", "file", "etc", "." ]
train
https://github.com/uw-it-aca/uw-restclients/blob/e12dcd32bf5296b6ebdf71798031594afb7852cb/restclients/dao_implementation/mock.py#L88-L140
uw-it-aca/uw-restclients
restclients/dao_implementation/mock.py
post_mockdata_url
def post_mockdata_url(service_name, implementation_name, url, headers, body, dir_base=dirname(__file__)): """ :param service_name: possible "sws", "pws", "book", "hfs", etc. :param implementation_name: possible values: "file", etc. """ # Cu...
python
def post_mockdata_url(service_name, implementation_name, url, headers, body, dir_base=dirname(__file__)): """ :param service_name: possible "sws", "pws", "book", "hfs", etc. :param implementation_name: possible values: "file", etc. """ # Cu...
[ "def", "post_mockdata_url", "(", "service_name", ",", "implementation_name", ",", "url", ",", "headers", ",", "body", ",", "dir_base", "=", "dirname", "(", "__file__", ")", ")", ":", "# Currently this post method does not return a response body", "response", "=", "Moc...
:param service_name: possible "sws", "pws", "book", "hfs", etc. :param implementation_name: possible values: "file", etc.
[ ":", "param", "service_name", ":", "possible", "sws", "pws", "book", "hfs", "etc", ".", ":", "param", "implementation_name", ":", "possible", "values", ":", "file", "etc", "." ]
train
https://github.com/uw-it-aca/uw-restclients/blob/e12dcd32bf5296b6ebdf71798031594afb7852cb/restclients/dao_implementation/mock.py#L213-L234
uw-it-aca/uw-restclients
restclients/dao_implementation/mock.py
delete_mockdata_url
def delete_mockdata_url(service_name, implementation_name, url, headers, dir_base=dirname(__file__)): """ :param service_name: possible "sws", "pws", "book", "hfs", etc. :param implementation_name: possible values: "file", etc. """ # Ht...
python
def delete_mockdata_url(service_name, implementation_name, url, headers, dir_base=dirname(__file__)): """ :param service_name: possible "sws", "pws", "book", "hfs", etc. :param implementation_name: possible values: "file", etc. """ # Ht...
[ "def", "delete_mockdata_url", "(", "service_name", ",", "implementation_name", ",", "url", ",", "headers", ",", "dir_base", "=", "dirname", "(", "__file__", ")", ")", ":", "# Http response code 204 No Content:", "# The server has fulfilled the request but does not need to", ...
:param service_name: possible "sws", "pws", "book", "hfs", etc. :param implementation_name: possible values: "file", etc.
[ ":", "param", "service_name", ":", "possible", "sws", "pws", "book", "hfs", "etc", ".", ":", "param", "implementation_name", ":", "possible", "values", ":", "file", "etc", "." ]
train
https://github.com/uw-it-aca/uw-restclients/blob/e12dcd32bf5296b6ebdf71798031594afb7852cb/restclients/dao_implementation/mock.py#L282-L296
uw-it-aca/uw-restclients
restclients/dao_implementation/mock.py
read_resp_data
def read_resp_data(service_name, implementation_name, url, response): """ Read the (DELETE, PATCH, POST, PUT) response body and header if exist. """ RR = _mockdata_path_root(service_name, implementation_name) for resource_dir in app_resource_dirs: path = os.path.join(resource_dir['path'], ...
python
def read_resp_data(service_name, implementation_name, url, response): """ Read the (DELETE, PATCH, POST, PUT) response body and header if exist. """ RR = _mockdata_path_root(service_name, implementation_name) for resource_dir in app_resource_dirs: path = os.path.join(resource_dir['path'], ...
[ "def", "read_resp_data", "(", "service_name", ",", "implementation_name", ",", "url", ",", "response", ")", ":", "RR", "=", "_mockdata_path_root", "(", "service_name", ",", "implementation_name", ")", "for", "resource_dir", "in", "app_resource_dirs", ":", "path", ...
Read the (DELETE, PATCH, POST, PUT) response body and header if exist.
[ "Read", "the", "(", "DELETE", "PATCH", "POST", "PUT", ")", "response", "body", "and", "header", "if", "exist", "." ]
train
https://github.com/uw-it-aca/uw-restclients/blob/e12dcd32bf5296b6ebdf71798031594afb7852cb/restclients/dao_implementation/mock.py#L307-L321
chop-dbhi/varify-data-warehouse
vdw/samples/utils.py
file_md5
def file_md5(f, size=8192): "Calculates the MD5 of a file." md5 = hashlib.md5() while True: data = f.read(size) if not data: break md5.update(data) return md5.hexdigest()
python
def file_md5(f, size=8192): "Calculates the MD5 of a file." md5 = hashlib.md5() while True: data = f.read(size) if not data: break md5.update(data) return md5.hexdigest()
[ "def", "file_md5", "(", "f", ",", "size", "=", "8192", ")", ":", "md5", "=", "hashlib", ".", "md5", "(", ")", "while", "True", ":", "data", "=", "f", ".", "read", "(", "size", ")", "if", "not", "data", ":", "break", "md5", ".", "update", "(", ...
Calculates the MD5 of a file.
[ "Calculates", "the", "MD5", "of", "a", "file", "." ]
train
https://github.com/chop-dbhi/varify-data-warehouse/blob/1600ee1bc5fae6c68fd03b23624467298570cca8/vdw/samples/utils.py#L4-L12
sirosen/callable-pip
callable_pip/__init__.py
main
def main(*args): """ Invoke pip in a subprocess, with semantics very similar to `pip.main()` Why use check_call instead of check_output? It's behavior is slightly closer to the older `pip.main()` behavior, printing output information directly to stdout. check_call was added in py2.5 and is sup...
python
def main(*args): """ Invoke pip in a subprocess, with semantics very similar to `pip.main()` Why use check_call instead of check_output? It's behavior is slightly closer to the older `pip.main()` behavior, printing output information directly to stdout. check_call was added in py2.5 and is sup...
[ "def", "main", "(", "*", "args", ")", ":", "try", ":", "subprocess", ".", "check_call", "(", "[", "sys", ".", "executable", ",", "'-m'", ",", "'pip'", "]", "+", "list", "(", "args", ")", ")", "return", "0", "except", "subprocess", ".", "CalledProcess...
Invoke pip in a subprocess, with semantics very similar to `pip.main()` Why use check_call instead of check_output? It's behavior is slightly closer to the older `pip.main()` behavior, printing output information directly to stdout. check_call was added in py2.5 and is supported through py3.x , so it'...
[ "Invoke", "pip", "in", "a", "subprocess", "with", "semantics", "very", "similar", "to", "pip", ".", "main", "()" ]
train
https://github.com/sirosen/callable-pip/blob/b62017526001820ced09c00e818019d583f2d3f8/callable_pip/__init__.py#L11-L26
quantum5/2048
_2048/manager.py
GameManager.open_fd
def open_fd(cls, name): """Open a file or create it.""" # Try to create it, if can't, try to open. try: return os.open(name, os.O_CREAT | os.O_RDWR | os.O_EXCL) except OSError as e: if e.errno != errno.EEXIST: raise return os.open(name,...
python
def open_fd(cls, name): """Open a file or create it.""" # Try to create it, if can't, try to open. try: return os.open(name, os.O_CREAT | os.O_RDWR | os.O_EXCL) except OSError as e: if e.errno != errno.EEXIST: raise return os.open(name,...
[ "def", "open_fd", "(", "cls", ",", "name", ")", ":", "# Try to create it, if can't, try to open.", "try", ":", "return", "os", ".", "open", "(", "name", ",", "os", ".", "O_CREAT", "|", "os", ".", "O_RDWR", "|", "os", ".", "O_EXCL", ")", "except", "OSErro...
Open a file or create it.
[ "Open", "a", "file", "or", "create", "it", "." ]
train
https://github.com/quantum5/2048/blob/93ada2e3026eaf154e1bbee943d0500c9253e66f/_2048/manager.py#L78-L86
quantum5/2048
_2048/manager.py
GameManager.new_game
def new_game(self): """Creates a new game of 2048.""" self.game = self.game_class(self, self.screen) self.save()
python
def new_game(self): """Creates a new game of 2048.""" self.game = self.game_class(self, self.screen) self.save()
[ "def", "new_game", "(", "self", ")", ":", "self", ".", "game", "=", "self", ".", "game_class", "(", "self", ",", "self", ".", "screen", ")", "self", ".", "save", "(", ")" ]
Creates a new game of 2048.
[ "Creates", "a", "new", "game", "of", "2048", "." ]
train
https://github.com/quantum5/2048/blob/93ada2e3026eaf154e1bbee943d0500c9253e66f/_2048/manager.py#L88-L91
quantum5/2048
_2048/manager.py
GameManager._load_score
def _load_score(self): """Load the best score from file.""" score = int(self.score_file.read()) self.score_file.seek(0, os.SEEK_SET) return score
python
def _load_score(self): """Load the best score from file.""" score = int(self.score_file.read()) self.score_file.seek(0, os.SEEK_SET) return score
[ "def", "_load_score", "(", "self", ")", ":", "score", "=", "int", "(", "self", ".", "score_file", ".", "read", "(", ")", ")", "self", ".", "score_file", ".", "seek", "(", "0", ",", "os", ".", "SEEK_SET", ")", "return", "score" ]
Load the best score from file.
[ "Load", "the", "best", "score", "from", "file", "." ]
train
https://github.com/quantum5/2048/blob/93ada2e3026eaf154e1bbee943d0500c9253e66f/_2048/manager.py#L93-L97
quantum5/2048
_2048/manager.py
GameManager.got_score
def got_score(self, score): """Update the best score if the new score is higher, returning the change.""" if score > self._score: delta = score - self._score self._score = score self._score_changed = True self.save() return delta return...
python
def got_score(self, score): """Update the best score if the new score is higher, returning the change.""" if score > self._score: delta = score - self._score self._score = score self._score_changed = True self.save() return delta return...
[ "def", "got_score", "(", "self", ",", "score", ")", ":", "if", "score", ">", "self", ".", "_score", ":", "delta", "=", "score", "-", "self", ".", "_score", "self", ".", "_score", "=", "score", "self", ".", "_score_changed", "=", "True", "self", ".", ...
Update the best score if the new score is higher, returning the change.
[ "Update", "the", "best", "score", "if", "the", "new", "score", "is", "higher", "returning", "the", "change", "." ]
train
https://github.com/quantum5/2048/blob/93ada2e3026eaf154e1bbee943d0500c9253e66f/_2048/manager.py#L99-L107
fusionbox/django-backupdb
backupdb/utils/commands.py
require_backup_exists
def require_backup_exists(func): """ Requires that the file referred to by `backup_file` exists in the file system before running the decorated function. """ def new_func(*args, **kwargs): backup_file = kwargs['backup_file'] if not os.path.exists(backup_file): raise Resto...
python
def require_backup_exists(func): """ Requires that the file referred to by `backup_file` exists in the file system before running the decorated function. """ def new_func(*args, **kwargs): backup_file = kwargs['backup_file'] if not os.path.exists(backup_file): raise Resto...
[ "def", "require_backup_exists", "(", "func", ")", ":", "def", "new_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "backup_file", "=", "kwargs", "[", "'backup_file'", "]", "if", "not", "os", ".", "path", ".", "exists", "(", "backup_file", "...
Requires that the file referred to by `backup_file` exists in the file system before running the decorated function.
[ "Requires", "that", "the", "file", "referred", "to", "by", "backup_file", "exists", "in", "the", "file", "system", "before", "running", "the", "decorated", "function", "." ]
train
https://github.com/fusionbox/django-backupdb/blob/db4aa73049303245ef0182cda5c76b1dd194cd00/backupdb/utils/commands.py#L46-L56
fusionbox/django-backupdb
backupdb/utils/commands.py
get_mysql_args
def get_mysql_args(db_config): """ Returns an array of argument values that will be passed to a `mysql` or `mysqldump` process when it is started based on the given database configuration. """ db = db_config['NAME'] mapping = [('--user={0}', db_config.get('USER')), ('--passwo...
python
def get_mysql_args(db_config): """ Returns an array of argument values that will be passed to a `mysql` or `mysqldump` process when it is started based on the given database configuration. """ db = db_config['NAME'] mapping = [('--user={0}', db_config.get('USER')), ('--passwo...
[ "def", "get_mysql_args", "(", "db_config", ")", ":", "db", "=", "db_config", "[", "'NAME'", "]", "mapping", "=", "[", "(", "'--user={0}'", ",", "db_config", ".", "get", "(", "'USER'", ")", ")", ",", "(", "'--password={0}'", ",", "db_config", ".", "get", ...
Returns an array of argument values that will be passed to a `mysql` or `mysqldump` process when it is started based on the given database configuration.
[ "Returns", "an", "array", "of", "argument", "values", "that", "will", "be", "passed", "to", "a", "mysql", "or", "mysqldump", "process", "when", "it", "is", "started", "based", "on", "the", "given", "database", "configuration", "." ]
train
https://github.com/fusionbox/django-backupdb/blob/db4aa73049303245ef0182cda5c76b1dd194cd00/backupdb/utils/commands.py#L59-L74
fusionbox/django-backupdb
backupdb/utils/commands.py
get_postgresql_args
def get_postgresql_args(db_config, extra_args=None): """ Returns an array of argument values that will be passed to a `psql` or `pg_dump` process when it is started based on the given database configuration. """ db = db_config['NAME'] mapping = [('--username={0}', db_config.get('USER')), ...
python
def get_postgresql_args(db_config, extra_args=None): """ Returns an array of argument values that will be passed to a `psql` or `pg_dump` process when it is started based on the given database configuration. """ db = db_config['NAME'] mapping = [('--username={0}', db_config.get('USER')), ...
[ "def", "get_postgresql_args", "(", "db_config", ",", "extra_args", "=", "None", ")", ":", "db", "=", "db_config", "[", "'NAME'", "]", "mapping", "=", "[", "(", "'--username={0}'", ",", "db_config", ".", "get", "(", "'USER'", ")", ")", ",", "(", "'--host=...
Returns an array of argument values that will be passed to a `psql` or `pg_dump` process when it is started based on the given database configuration.
[ "Returns", "an", "array", "of", "argument", "values", "that", "will", "be", "passed", "to", "a", "psql", "or", "pg_dump", "process", "when", "it", "is", "started", "based", "on", "the", "given", "database", "configuration", "." ]
train
https://github.com/fusionbox/django-backupdb/blob/db4aa73049303245ef0182cda5c76b1dd194cd00/backupdb/utils/commands.py#L77-L94
nestauk/gtr
gtr/services/projects.py
Projects.project
def project(self, term, **kwargs): """Search for a project by id. Args: term (str): Term to search for. kwargs (dict): additional keywords passed into requests.session.get params keyword. """ params = kwargs baseuri = self._BASE_URI + 'projects/' ...
python
def project(self, term, **kwargs): """Search for a project by id. Args: term (str): Term to search for. kwargs (dict): additional keywords passed into requests.session.get params keyword. """ params = kwargs baseuri = self._BASE_URI + 'projects/' ...
[ "def", "project", "(", "self", ",", "term", ",", "*", "*", "kwargs", ")", ":", "params", "=", "kwargs", "baseuri", "=", "self", ".", "_BASE_URI", "+", "'projects/'", "+", "term", "res", "=", "self", ".", "session", ".", "get", "(", "baseuri", ",", ...
Search for a project by id. Args: term (str): Term to search for. kwargs (dict): additional keywords passed into requests.session.get params keyword.
[ "Search", "for", "a", "project", "by", "id", "." ]
train
https://github.com/nestauk/gtr/blob/49e1b8db1f4376612ea1ec8585a79375fa15a899/gtr/services/projects.py#L26-L38
nestauk/gtr
gtr/services/projects.py
Projects.projects
def projects(self, term, field=None, **kwargs): """Search for projects. Defaults to project_title. Other fields are: project_reference project_abstract Args: term (str): Term to search for. kwargs (dict): additional keywords passed into re...
python
def projects(self, term, field=None, **kwargs): """Search for projects. Defaults to project_title. Other fields are: project_reference project_abstract Args: term (str): Term to search for. kwargs (dict): additional keywords passed into re...
[ "def", "projects", "(", "self", ",", "term", ",", "field", "=", "None", ",", "*", "*", "kwargs", ")", ":", "params", "=", "kwargs", "params", "[", "'q'", "]", "=", "term", "if", "field", ":", "params", "[", "'f'", "]", "=", "self", ".", "_FIELD_M...
Search for projects. Defaults to project_title. Other fields are: project_reference project_abstract Args: term (str): Term to search for. kwargs (dict): additional keywords passed into requests.session.get params keyword.
[ "Search", "for", "projects", ".", "Defaults", "to", "project_title", ".", "Other", "fields", "are", ":", "project_reference", "project_abstract" ]
train
https://github.com/nestauk/gtr/blob/49e1b8db1f4376612ea1ec8585a79375fa15a899/gtr/services/projects.py#L40-L60
bapakode/OmMongo
ommongo/fields/mapping.py
DictField.validate_unwrap
def validate_unwrap(self, value): ''' Checks that value is a ``dict``, that every key is a valid MongoDB key, and that every value validates based on DictField.value_type ''' if not isinstance(value, dict): self._fail_validation_type(value, dict) for k, v in value...
python
def validate_unwrap(self, value): ''' Checks that value is a ``dict``, that every key is a valid MongoDB key, and that every value validates based on DictField.value_type ''' if not isinstance(value, dict): self._fail_validation_type(value, dict) for k, v in value...
[ "def", "validate_unwrap", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "dict", ")", ":", "self", ".", "_fail_validation_type", "(", "value", ",", "dict", ")", "for", "k", ",", "v", "in", "value", ".", "items", "(...
Checks that value is a ``dict``, that every key is a valid MongoDB key, and that every value validates based on DictField.value_type
[ "Checks", "that", "value", "is", "a", "dict", "that", "every", "key", "is", "a", "valid", "MongoDB", "key", "and", "that", "every", "value", "validates", "based", "on", "DictField", ".", "value_type" ]
train
https://github.com/bapakode/OmMongo/blob/52b5a5420516dc709f2d2eb065818c7973991ce3/ommongo/fields/mapping.py#L78-L89
bapakode/OmMongo
ommongo/fields/mapping.py
DictField.validate_wrap
def validate_wrap(self, value): ''' Checks that value is a ``dict``, that every key is a valid MongoDB key, and that every value validates based on DictField.value_type ''' if not isinstance(value, dict): self._fail_validation_type(value, dict) for k, v in value.i...
python
def validate_wrap(self, value): ''' Checks that value is a ``dict``, that every key is a valid MongoDB key, and that every value validates based on DictField.value_type ''' if not isinstance(value, dict): self._fail_validation_type(value, dict) for k, v in value.i...
[ "def", "validate_wrap", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "dict", ")", ":", "self", ".", "_fail_validation_type", "(", "value", ",", "dict", ")", "for", "k", ",", "v", "in", "value", ".", "items", "(",...
Checks that value is a ``dict``, that every key is a valid MongoDB key, and that every value validates based on DictField.value_type
[ "Checks", "that", "value", "is", "a", "dict", "that", "every", "key", "is", "a", "valid", "MongoDB", "key", "and", "that", "every", "value", "validates", "based", "on", "DictField", ".", "value_type" ]
train
https://github.com/bapakode/OmMongo/blob/52b5a5420516dc709f2d2eb065818c7973991ce3/ommongo/fields/mapping.py#L91-L102
bapakode/OmMongo
ommongo/fields/mapping.py
DictField.wrap
def wrap(self, value): ''' Validates ``value`` and then returns a dictionary with each key in ``value`` mapped to its value wrapped with ``DictField.value_type`` ''' self.validate_wrap(value) ret = {} for k, v in value.items(): ret[k] = self.value_type.wra...
python
def wrap(self, value): ''' Validates ``value`` and then returns a dictionary with each key in ``value`` mapped to its value wrapped with ``DictField.value_type`` ''' self.validate_wrap(value) ret = {} for k, v in value.items(): ret[k] = self.value_type.wra...
[ "def", "wrap", "(", "self", ",", "value", ")", ":", "self", ".", "validate_wrap", "(", "value", ")", "ret", "=", "{", "}", "for", "k", ",", "v", "in", "value", ".", "items", "(", ")", ":", "ret", "[", "k", "]", "=", "self", ".", "value_type", ...
Validates ``value`` and then returns a dictionary with each key in ``value`` mapped to its value wrapped with ``DictField.value_type``
[ "Validates", "value", "and", "then", "returns", "a", "dictionary", "with", "each", "key", "in", "value", "mapped", "to", "its", "value", "wrapped", "with", "DictField", ".", "value_type" ]
train
https://github.com/bapakode/OmMongo/blob/52b5a5420516dc709f2d2eb065818c7973991ce3/ommongo/fields/mapping.py#L104-L112
bapakode/OmMongo
ommongo/fields/mapping.py
DictField.unwrap
def unwrap(self, value, session=None): ''' Validates ``value`` and then returns a dictionary with each key in ``value`` mapped to its value unwrapped using ``DictField.value_type`` ''' self.validate_unwrap(value) ret = {} for k, v in value.items(): ret[k] ...
python
def unwrap(self, value, session=None): ''' Validates ``value`` and then returns a dictionary with each key in ``value`` mapped to its value unwrapped using ``DictField.value_type`` ''' self.validate_unwrap(value) ret = {} for k, v in value.items(): ret[k] ...
[ "def", "unwrap", "(", "self", ",", "value", ",", "session", "=", "None", ")", ":", "self", ".", "validate_unwrap", "(", "value", ")", "ret", "=", "{", "}", "for", "k", ",", "v", "in", "value", ".", "items", "(", ")", ":", "ret", "[", "k", "]", ...
Validates ``value`` and then returns a dictionary with each key in ``value`` mapped to its value unwrapped using ``DictField.value_type``
[ "Validates", "value", "and", "then", "returns", "a", "dictionary", "with", "each", "key", "in", "value", "mapped", "to", "its", "value", "unwrapped", "using", "DictField", ".", "value_type" ]
train
https://github.com/bapakode/OmMongo/blob/52b5a5420516dc709f2d2eb065818c7973991ce3/ommongo/fields/mapping.py#L114-L122
bapakode/OmMongo
ommongo/fields/mapping.py
KVField.validate_unwrap
def validate_unwrap(self, value): ''' Expects a list of dictionaries with ``k`` and ``v`` set to the keys and values that will be unwrapped into the output python dictionary should have ''' if not isinstance(value, list): self._fail_validation_type(value, lis...
python
def validate_unwrap(self, value): ''' Expects a list of dictionaries with ``k`` and ``v`` set to the keys and values that will be unwrapped into the output python dictionary should have ''' if not isinstance(value, list): self._fail_validation_type(value, lis...
[ "def", "validate_unwrap", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "list", ")", ":", "self", ".", "_fail_validation_type", "(", "value", ",", "list", ")", "for", "value_dict", "in", "value", ":", "if", "not", "...
Expects a list of dictionaries with ``k`` and ``v`` set to the keys and values that will be unwrapped into the output python dictionary should have
[ "Expects", "a", "list", "of", "dictionaries", "with", "k", "and", "v", "set", "to", "the", "keys", "and", "values", "that", "will", "be", "unwrapped", "into", "the", "output", "python", "dictionary", "should", "have" ]
train
https://github.com/bapakode/OmMongo/blob/52b5a5420516dc709f2d2eb065818c7973991ce3/ommongo/fields/mapping.py#L176-L201
bapakode/OmMongo
ommongo/fields/mapping.py
KVField.wrap
def wrap(self, value): ''' Expects a dictionary with the keys being instances of ``KVField.key_type`` and the values being instances of ``KVField.value_type``. After validation, the dictionary is transformed into a list of dictionaries with ``k`` and ``v`` fields set to the ...
python
def wrap(self, value): ''' Expects a dictionary with the keys being instances of ``KVField.key_type`` and the values being instances of ``KVField.value_type``. After validation, the dictionary is transformed into a list of dictionaries with ``k`` and ``v`` fields set to the ...
[ "def", "wrap", "(", "self", ",", "value", ")", ":", "self", ".", "validate_wrap", "(", "value", ")", "ret", "=", "[", "]", "for", "k", ",", "v", "in", "value", ".", "items", "(", ")", ":", "k", "=", "self", ".", "key_type", ".", "wrap", "(", ...
Expects a dictionary with the keys being instances of ``KVField.key_type`` and the values being instances of ``KVField.value_type``. After validation, the dictionary is transformed into a list of dictionaries with ``k`` and ``v`` fields set to the keys and values from the original d...
[ "Expects", "a", "dictionary", "with", "the", "keys", "being", "instances", "of", "KVField", ".", "key_type", "and", "the", "values", "being", "instances", "of", "KVField", ".", "value_type", ".", "After", "validation", "the", "dictionary", "is", "transformed", ...
train
https://github.com/bapakode/OmMongo/blob/52b5a5420516dc709f2d2eb065818c7973991ce3/ommongo/fields/mapping.py#L203-L215