_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q265700
MoveFile
validation
def MoveFile(source_filename, target_filename): ''' Moves a file. :param unicode source_filename: :param unicode target_filename: :raises NotImplementedForRemotePathError: If trying to operate with non-local files.
python
{ "resource": "" }
q265701
MoveDirectory
validation
def MoveDirectory(source_dir, target_dir): ''' Moves a directory. :param unicode source_dir: :param unicode target_dir: :raises NotImplementedError: If trying to move anything other than: Local dir -> local dir FTP dir -> FTP dir (same host) ''' if not IsDir(source_dir): from ._exceptions import DirectoryNotFoundError raise DirectoryNotFoundError(source_dir) if Exists(target_dir):
python
{ "resource": "" }
q265702
GetFileContents
validation
def GetFileContents(filename, binary=False, encoding=None, newline=None): ''' Reads a file and returns its contents. Works for both local and remote files. :param unicode filename: :param bool binary: If True returns the file as is, ignore any EOL conversion. :param unicode encoding: File's encoding. If not None, contents obtained from file will be decoded using this `encoding`. :param None|''|'\n'|'\r'|'\r\n' newline: Controls universal newlines. See 'io.open' newline parameter documentation for more details. :returns str|unicode: The file's contents. Returns
python
{ "resource": "" }
q265703
GetFileLines
validation
def GetFileLines(filename, newline=None, encoding=None): ''' Reads a file and returns its contents as a list of lines. Works for both local and remote files. :param unicode filename: :param None|''|'\n'|'\r'|'\r\n' newline: Controls universal newlines. See 'io.open' newline parameter documentation for more details. :param unicode encoding: File's encoding. If not None, contents obtained from file will be decoded using this
python
{ "resource": "" }
q265704
ListFiles
validation
def ListFiles(directory): ''' Lists the files in the given directory :type directory: unicode | unicode :param directory: A directory or URL :rtype: list(unicode) | list(unicode) :returns: List of filenames/directories found in the given directory. Returns None if the given directory does not exists. If `directory` is a unicode string, all files returned will also be unicode :raises NotImplementedProtocol: If file protocol is not local or FTP .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information ''' from six.moves.urllib.parse import urlparse directory_url = urlparse(directory) # Handle local if _UrlIsLocal(directory_url):
python
{ "resource": "" }
q265705
CreateFile
validation
def CreateFile(filename, contents, eol_style=EOL_STYLE_NATIVE, create_dir=True, encoding=None, binary=False): ''' Create a file with the given contents. :param unicode filename: Filename and path to be created. :param unicode contents: The file contents as a string. :type eol_style: EOL_STYLE_XXX constant :param eol_style: Replaces the EOL by the appropriate EOL depending on the eol_style value. Considers that all content is using only "\n" as EOL. :param bool create_dir: If True, also creates directories needed in filename's path :param unicode encoding: Target file's content encoding. Defaults to sys.getfilesystemencoding() Ignored if `binary` = True :param bool binary: If True, file is created in binary mode. In this case, `contents` must be `bytes` and not `unicode` :return unicode: Returns the name of the file created. :raises NotImplementedProtocol: If file protocol is not local or FTP :raises ValueError: If trying to mix unicode `contents` without `encoding`, or `encoding` without unicode `contents` .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information ''' # Lots of checks when writing binary files if binary: if isinstance(contents, six.text_type): raise TypeError('contents must be str (bytes) when binary=True') else: if not isinstance(contents, six.text_type): raise TypeError('contents must be unicode when binary=False') # Replaces eol on each line by the given eol_style.
python
{ "resource": "" }
q265706
ReplaceInFile
validation
def ReplaceInFile(filename, old, new, encoding=None): ''' Replaces all occurrences of "old" by "new" in the given file. :param unicode filename: The name of the file. :param unicode old: The string to search for. :param unicode new: Replacement string. :return unicode:
python
{ "resource": "" }
q265707
CreateDirectory
validation
def CreateDirectory(directory): ''' Create directory including any missing intermediate directory. :param unicode directory: :return unicode|urlparse.ParseResult: Returns the created directory or url (see urlparse). :raises NotImplementedProtocol: If protocol is not local or FTP. .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information ''' from six.moves.urllib.parse import urlparse directory_url = urlparse(directory) # Handle local if _UrlIsLocal(directory_url): if not os.path.exists(directory): os.makedirs(directory) return directory
python
{ "resource": "" }
q265708
DeleteDirectory
validation
def DeleteDirectory(directory, skip_on_error=False): ''' Deletes a directory. :param unicode directory: :param bool skip_on_error: If True, ignore any errors when trying to delete directory (for example, directory not found) :raises NotImplementedForRemotePathError: If trying to delete a remote directory. ''' _AssertIsLocal(directory) import shutil def OnError(fn, path, excinfo): ''' Remove the read-only flag and try to remove again. On Windows, rmtree fails when trying to remove a read-only file. This fix it!
python
{ "resource": "" }
q265709
ListMappedNetworkDrives
validation
def ListMappedNetworkDrives(): ''' On Windows, returns a list of mapped network drives :return: tuple(string, string, bool) For each mapped netword drive, return 3 values tuple: - the local drive - the remote path- - True if the mapping is enabled (warning: not reliable) ''' if sys.platform != 'win32': raise NotImplementedError drives_list = []
python
{ "resource": "" }
q265710
CreateLink
validation
def CreateLink(target_path, link_path, override=True): ''' Create a symbolic link at `link_path` pointing to `target_path`. :param unicode target_path: Link target :param unicode link_path: Fullpath to link name :param bool override: If True and `link_path` already exists as a link, that link is overridden. ''' _AssertIsLocal(target_path) _AssertIsLocal(link_path) if override and IsLink(link_path): DeleteLink(link_path) # Create directories leading up to link dirname = os.path.dirname(link_path) if dirname: CreateDirectory(dirname) if sys.platform != 'win32': return os.symlink(target_path, link_path) # @UndefinedVariable else: #import ntfsutils.junction #return ntfsutils.junction.create(target_path, link_path)
python
{ "resource": "" }
q265711
ReadLink
validation
def ReadLink(path): ''' Read the target of the symbolic link at `path`. :param unicode path: Path to a symbolic link :returns unicode: Target of a symbolic link ''' _AssertIsLocal(path) if sys.platform != 'win32': return os.readlink(path) # @UndefinedVariable if not IsLink(path): from ._exceptions import FileNotFoundError
python
{ "resource": "" }
q265712
_AssertIsLocal
validation
def _AssertIsLocal(path): ''' Checks if a given path is local, raise an exception if not. This is used in filesystem functions that do not support remote operations yet. :param unicode path: :raises NotImplementedForRemotePathError: If the given path is not local ''' from six.moves.urllib.parse import urlparse
python
{ "resource": "" }
q265713
_HandleContentsEol
validation
def _HandleContentsEol(contents, eol_style): ''' Replaces eol on each line by the given eol_style. :param unicode contents: :type eol_style: EOL_STYLE_XXX constant :param eol_style: ''' if eol_style == EOL_STYLE_NONE: return contents if eol_style == EOL_STYLE_UNIX:
python
{ "resource": "" }
q265714
MatchMasks
validation
def MatchMasks(filename, masks): ''' Verifies if a filename match with given patterns. :param str filename: The filename to match. :param list(str) masks: The patterns to search in the filename. :return bool: True if the filename has matched with one pattern, False otherwise. ''' import fnmatch
python
{ "resource": "" }
q265715
FindFiles
validation
def FindFiles(dir_, in_filters=None, out_filters=None, recursive=True, include_root_dir=True, standard_paths=False): ''' Searches for files in a given directory that match with the given patterns. :param str dir_: the directory root, to search the files. :param list(str) in_filters: a list with patterns to match (default = all). E.g.: ['*.py'] :param list(str) out_filters: a list with patterns to ignore (default = none). E.g.: ['*.py'] :param bool recursive: if True search in subdirectories, otherwise, just in the root. :param bool include_root_dir: if True, includes the directory being searched in the returned paths :param bool standard_paths: if True, always uses unix path separators "/" :return list(str): A list of strings with the files that matched (with the full path in the filesystem). ''' # all files if in_filters is None: in_filters = ['*'] if out_filters is None: out_filters = [] result = [] # maintain just files that don't have a pattern that match with out_filters # walk through all directories based on dir for dir_root, directories, filenames in os.walk(dir_): for i_directory in directories[:]:
python
{ "resource": "" }
q265716
ExpandUser
validation
def ExpandUser(path): ''' os.path.expanduser wrapper, necessary because it cannot handle unicode strings properly. This is not necessary in Python 3. :param path: .. seealso:: os.path.expanduser ''' if six.PY2: encoding = sys.getfilesystemencoding()
python
{ "resource": "" }
q265717
DumpDirHashToStringIO
validation
def DumpDirHashToStringIO(directory, stringio, base='', exclude=None, include=None): ''' Helper to iterate over the files in a directory putting those in the passed StringIO in ini format. :param unicode directory: The directory for which the hash should be done. :param StringIO stringio: The string to which the dump should be put. :param unicode base: If provided should be added (along with a '/') before the name=hash of file. :param unicode exclude: Pattern to match files to exclude from the hashing. E.g.: *.gz :param unicode include: Pattern to match files to include in the hashing. E.g.: *.zip ''' import fnmatch import os files = [(os.path.join(directory, i), i) for i in os.listdir(directory)]
python
{ "resource": "" }
q265718
IterHashes
validation
def IterHashes(iterator_size, hash_length=7): ''' Iterator for random hexadecimal hashes :param iterator_size: Amount of hashes return before this iterator stops. Goes on forever if `iterator_size` is negative. :param int hash_length: Size of each hash returned. :return generator(unicode): '''
python
{ "resource": "" }
q265719
PushPopItem
validation
def PushPopItem(obj, key, value): ''' A context manager to replace and restore a value using a getter and setter. :param object obj: The object to replace/restore. :param object key: The key to replace/restore in the object. :param object value: The value to replace. Example:: with PushPop2(sys.modules, 'alpha', None): pytest.raises(ImportError):
python
{ "resource": "" }
q265720
db_to_specifier
validation
def db_to_specifier(db_string): """ Return the database specifier for a database string. This accepts a database name or URL, and returns a database specifier in the format accepted by ``specifier_to_db``. It is recommended that you consult the documentation for that function for an explanation of the format. """ local_match = PLAIN_RE.match(db_string) remote_match = URL_RE.match(db_string) # If this looks like a local specifier: if local_match: return 'local:' + local_match.groupdict()['database'] # If this looks like a remote specifier: elif remote_match: # Just a fancy way of getting 3 variables in 2 lines... hostname, portnum, database = map(remote_match.groupdict().get, ('hostname', 'portnum', 'database'))
python
{ "resource": "" }
q265721
get_db_from_db
validation
def get_db_from_db(db_string): """Return a CouchDB database instance from a database string.""" server = get_server_from_db(db_string) local_match = PLAIN_RE.match(db_string) remote_match = URL_RE.match(db_string) # If this looks like a local specifier:
python
{ "resource": "" }
q265722
ensure_specifier_exists
validation
def ensure_specifier_exists(db_spec): """Make sure a DB specifier exists, creating it if necessary.""" local_match = LOCAL_RE.match(db_spec) remote_match = REMOTE_RE.match(db_spec) plain_match = PLAIN_RE.match(db_spec) if local_match: db_name = local_match.groupdict().get('database') server = shortcuts.get_server() if db_name not in server: server.create(db_name) return True elif remote_match: hostname, portnum, database = map(remote_match.groupdict().get, ('hostname', 'portnum', 'database')) server = shortcuts.get_server( server_url=('http://%s:%s' % (hostname, portnum)))
python
{ "resource": "" }
q265723
coerce
validation
def coerce(value1, value2, default=None): """Exclude NoSet objec .. code-block:: >>> coerce(NoSet, 'value')
python
{ "resource": "" }
q265724
parse_hub_key
validation
def parse_hub_key(key): """Parse a hub key into a dictionary of component parts :param key: str, a hub key :returns: dict, hub key split into parts :raises: ValueError """ if key is None: raise ValueError('Not a valid key') match = re.match(PATTERN, key) if not match: match = re.match(PATTERN_S0, key)
python
{ "resource": "" }
q265725
match_part
validation
def match_part(string, part): """Raise an exception if string doesn't match a part's regex :param string: str :param part: a key in the PARTS dict :raises: ValueError, TypeError """
python
{ "resource": "" }
q265726
Clifier.apply_defaults
validation
def apply_defaults(self, commands): """ apply default settings to commands not static, shadow "self" in eval """ for command in commands: if
python
{ "resource": "" }
q265727
Clifier.create_commands
validation
def create_commands(self, commands, parser): """ add commands to parser """ self.apply_defaults(commands) def create_single_command(command): keys = command['keys'] del command['keys']
python
{ "resource": "" }
q265728
Clifier.create_subparsers
validation
def create_subparsers(self, parser): """ get config for subparser and create commands""" subparsers = parser.add_subparsers() for name in self.config['subparsers']:
python
{ "resource": "" }
q265729
Clifier.show_version
validation
def show_version(self): """ custom command line action to show version """ class ShowVersionAction(argparse.Action): def __init__(inner_self, nargs=0, **kw): super(ShowVersionAction, inner_self).__init__(nargs=nargs, **kw) def __call__(inner_self, parser, args, value, option_string=None):
python
{ "resource": "" }
q265730
Clifier.check_path_action
validation
def check_path_action(self): """ custom command line action to check file exist """ class CheckPathAction(argparse.Action): def __call__(self, parser, args, value, option_string=None): if type(value) is list: value = value[0] user_value = value if option_string == 'None': if not os.path.isdir(value): _current_user = os.path.expanduser("~") if not value.startswith(_current_user) \ and not value.startswith(os.getcwd()): if os.path.isdir(os.path.join(_current_user, value)):
python
{ "resource": "" }
q265731
new_user
validation
def new_user(yaml_path): ''' Return the consumer and oauth tokens with three-legged OAuth process and save in a yaml file in the user's home directory. ''' print 'Retrieve API Key from https://www.shirts.io/accounts/api_console/' api_key = raw_input('Shirts.io API Key: ')
python
{ "resource": "" }
q265732
_AddPropertiesForExtensions
validation
def _AddPropertiesForExtensions(descriptor, cls): """Adds properties for all fields in this protocol message type.""" extension_dict = descriptor.extensions_by_name for extension_name, extension_field in extension_dict.items():
python
{ "resource": "" }
q265733
_InternalUnpackAny
validation
def _InternalUnpackAny(msg): """Unpacks Any message and returns the unpacked message. This internal method is differnt from public Any Unpack method which takes the target message as argument. _InternalUnpackAny method does not have target message type and need to find the message type in descriptor pool. Args: msg: An Any message to be unpacked. Returns: The unpacked message. """ type_url = msg.type_url db = symbol_database.Default() if not type_url:
python
{ "resource": "" }
q265734
sina_xml_to_url_list
test
def sina_xml_to_url_list(xml_data): """str->list Convert XML to URL List. From Biligrab. """ rawurl = [] dom = parseString(xml_data) for node in dom.getElementsByTagName('durl'):
python
{ "resource": "" }
q265735
dailymotion_download
test
def dailymotion_download(url, output_dir='.', merge=True, info_only=False, **kwargs): """Downloads Dailymotion videos by URL. """ html = get_content(rebuilt_url(url)) info = json.loads(match1(html, r'qualities":({.+?}),"')) title = match1(html, r'"video_title"\s*:\s*"([^"]+)"') or \ match1(html, r'"title"\s*:\s*"([^"]+)"')
python
{ "resource": "" }
q265736
sina_download
test
def sina_download(url, output_dir='.', merge=True, info_only=False, **kwargs): """Downloads Sina videos by URL. """ if 'news.sina.com.cn/zxt' in url: sina_zxt(url, output_dir=output_dir, merge=merge, info_only=info_only, **kwargs) return vid = match1(url, r'vid=(\d+)') if vid is None: video_page = get_content(url) vid = hd_vid = match1(video_page, r'hd_vid\s*:\s*\'([^\']+)\'') if hd_vid == '0': vids = match1(video_page, r'[^\w]vid\s*:\s*\'([^\']+)\'').split('|') vid = vids[-1] if vid is None: vid = match1(video_page, r'vid:"?(\d+)"?') if vid: #title = match1(video_page, r'title\s*:\s*\'([^\']+)\'') sina_download_by_vid(vid, output_dir=output_dir, merge=merge, info_only=info_only) else:
python
{ "resource": "" }
q265737
sprint
test
def sprint(text, *colors): """Format text with color or other effects into ANSI escaped string."""
python
{ "resource": "" }
q265738
print_log
test
def print_log(text, *colors): """Print a log message to standard error."""
python
{ "resource": "" }
q265739
e
test
def e(message, exit_code=None): """Print an error log message.""" print_log(message, YELLOW, BOLD)
python
{ "resource": "" }
q265740
wtf
test
def wtf(message, exit_code=1): """What a Terrible Failure!""" print_log(message, RED, BOLD)
python
{ "resource": "" }
q265741
detect_os
test
def detect_os(): """Detect operating system. """ # Inspired by: # https://github.com/scivision/pybashutils/blob/78b7f2b339cb03b1c37df94015098bbe462f8526/pybashutils/windows_linux_detect.py syst = system().lower() os = 'unknown' if 'cygwin' in syst: os = 'cygwin' elif 'darwin' in syst: os = 'mac' elif 'linux' in syst: os = 'linux' # detect WSL https://github.com/Microsoft/BashOnWindows/issues/423 try: with open('/proc/version',
python
{ "resource": "" }
q265742
vimeo_download_by_channel
test
def vimeo_download_by_channel(url, output_dir='.', merge=False, info_only=False, **kwargs): """str->None""" # https://vimeo.com/channels/464686
python
{ "resource": "" }
q265743
ckplayer_get_info_by_xml
test
def ckplayer_get_info_by_xml(ckinfo): """str->dict Information for CKPlayer API content.""" e = ET.XML(ckinfo) video_dict = {'title': '', #'duration': 0, 'links': [], 'size': 0, 'flashvars': '',} dictified = dictify(e)['ckplayer'] if 'info' in dictified: if '_text' in dictified['info'][0]['title'][0]: #title video_dict['title'] = dictified['info'][0]['title'][0]['_text'].strip() #if dictify(e)['ckplayer']['info'][0]['title'][0]['_text'].strip(): #duration #video_dict['title'] = dictify(e)['ckplayer']['info'][0]['title'][0]['_text'].strip() if '_text' in dictified['video'][0]['size'][0]: #size exists for 1 piece
python
{ "resource": "" }
q265744
get_video_url_from_video_id
test
def get_video_url_from_video_id(video_id): """Splicing URLs according to video ID to get video details""" # from js data = [""] * 256 for index, _ in enumerate(data): t = index for i in range(8): t = -306674912 ^ unsigned_right_shitf(t, 1) if 1 & t else unsigned_right_shitf(t, 1) data[index] = t def tmp(): rand_num = random.random() path = "/video/urls/v/1/toutiao/mp4/{video_id}?r={random_num}".format(video_id=video_id, random_num=str(rand_num)[2:]) e = o = r = -1 i, a = 0, len(path) while i < a: e = ord(path[i]) i += 1 if e < 128: r = unsigned_right_shitf(r, 8) ^ data[255 & (r ^ e)] else: if e < 2048: r = unsigned_right_shitf(r, 8) ^ data[255 & (r ^ (192 | e >> 6 & 31))] r = unsigned_right_shitf(r, 8) ^ data[255 & (r ^ (128 | 63 & e))] else: if 55296 <= e < 57344: e = (1023 & e) + 64 i += 1 o = 1023 & t.url(i) r = unsigned_right_shitf(r, 8) ^ data[255 & (r ^ (240 | e >> 8 & 7))] r = unsigned_right_shitf(r, 8) ^ data[255 & (r ^ (128 | e >> 2 & 63))]
python
{ "resource": "" }
q265745
MGTV.get_mgtv_real_url
test
def get_mgtv_real_url(url): """str->list of str Give you the real URLs.""" content = loads(get_content(url)) m3u_url = content['info'] split = urlsplit(m3u_url) base_url = "{scheme}://{netloc}{path}/".format(scheme = split[0], netloc = split[1], path = dirname(split[2])) content = get_content(content['info']) #get the REAL M3U url, maybe to be changed later? segment_list = [] segments_size = 0
python
{ "resource": "" }
q265746
legitimize
test
def legitimize(text, os=detect_os()): """Converts a string to a valid filename. """ # POSIX systems text = text.translate({ 0: None, ord('/'): '-', ord('|'): '-', }) # FIXME: do some filesystem detection if os == 'windows' or os == 'cygwin' or os == 'wsl': # Windows (non-POSIX namespace) text = text.translate({ # Reserved in Windows VFAT and NTFS ord(':'): '-', ord('*'): '-', ord('?'): '-', ord('\\'): '-', ord('\"'): '\'', # Reserved in Windows VFAT ord('+'): '-', ord('<'): '-', ord('>'): '-', ord('['): '(', ord(']'):
python
{ "resource": "" }
q265747
cbs_download
test
def cbs_download(url, output_dir='.', merge=True, info_only=False, **kwargs): """Downloads CBS videos by URL. """ html = get_content(url) pid = match1(html, r'video\.settings\.pid\s*=\s*\'([^\']+)\'') title =
python
{ "resource": "" }
q265748
Iqiyi.download
test
def download(self, **kwargs): """Override the original one Ugly ugly dirty hack""" if 'json_output' in kwargs and kwargs['json_output']: json_output.output(self) elif 'info_only' in kwargs and kwargs['info_only']: if 'stream_id' in kwargs and kwargs['stream_id']: # Display the stream stream_id = kwargs['stream_id'] if 'index' not in kwargs: self.p(stream_id) else: self.p_i(stream_id) else: # Display all available streams if 'index' not in kwargs: self.p([]) else: stream_id = self.streams_sorted[0]['id'] if 'id' in self.streams_sorted[0] else self.streams_sorted[0]['itag'] self.p_i(stream_id) else: if 'stream_id' in kwargs and kwargs['stream_id']: # Download the stream stream_id = kwargs['stream_id'] else: # Download stream with the best quality stream_id = self.streams_sorted[0]['id'] if 'id' in self.streams_sorted[0] else self.streams_sorted[0]['itag'] if 'index' not in kwargs: self.p(stream_id) else: self.p_i(stream_id) if stream_id in self.streams: urls = self.streams[stream_id]['src'] ext = self.streams[stream_id]['container'] total_size = self.streams[stream_id]['size'] else: urls = self.dash_streams[stream_id]['src'] ext = self.dash_streams[stream_id]['container'] total_size = self.dash_streams[stream_id]['size'] if not urls:
python
{ "resource": "" }
q265749
acfun_download_by_vid
test
def acfun_download_by_vid(vid, title, output_dir='.', merge=True, info_only=False, **kwargs): """str, str, str, bool, bool ->None Download Acfun video by vid. Call Acfun API, decide which site to use, and pass the job to its extractor. """ #first call the main parasing API info = json.loads(get_content('http://www.acfun.cn/video/getVideo.aspx?id=' + vid)) sourceType = info['sourceType'] #decide sourceId to know which extractor to use if 'sourceId' in info: sourceId = info['sourceId'] # danmakuId = info['danmakuId'] #call extractor decided by sourceId if sourceType == 'sina': sina_download_by_vid(sourceId, title, output_dir=output_dir, merge=merge, info_only=info_only) elif sourceType == 'youku': youku_download_by_vid(sourceId, title=title, output_dir=output_dir, merge=merge, info_only=info_only, **kwargs) elif sourceType == 'tudou': tudou_download_by_iid(sourceId, title, output_dir=output_dir, merge=merge, info_only=info_only) elif sourceType == 'qq': qq_download_by_vid(sourceId, title, True, output_dir=output_dir, merge=merge, info_only=info_only) elif sourceType == 'letv': letvcloud_download_by_vu(sourceId, '2d8c027396', title, output_dir=output_dir, merge=merge, info_only=info_only) elif sourceType == 'zhuzhan': #As in Jul.28.2016, Acfun is using embsig to anti hotlink so we need to pass this #In Mar. 2017 there is a dedicated ``acfun_proxy'' in youku cloud player #old code removed url = 'http://www.acfun.cn/v/ac' + vid yk_streams = youku_acfun_proxy(info['sourceId'], info['encode'], url) seq = ['mp4hd3', 'mp4hd2', 'mp4hd', 'flvhd'] for t in seq: if yk_streams.get(t):
python
{ "resource": "" }
q265750
matchall
test
def matchall(text, patterns): """Scans through a string for substrings matched some patterns. Args: text: A string to be scanned. patterns: a list of regex pattern. Returns: a list if matched. empty if not.
python
{ "resource": "" }
q265751
parse_query_param
test
def parse_query_param(url, param): """Parses the query string of a URL and returns the value of a parameter. Args: url: A URL.
python
{ "resource": "" }
q265752
get_content
test
def get_content(url, headers={}, decoded=True): """Gets the content of a URL via sending a HTTP GET request. Args: url: A URL. headers: Request headers used by the client. decoded: Whether decode the response body using UTF-8 or the charset specified in Content-Type. Returns: The content as a string. """ logging.debug('get_content: %s' % url) req = request.Request(url, headers=headers) if cookies: cookies.add_cookie_header(req)
python
{ "resource": "" }
q265753
post_content
test
def post_content(url, headers={}, post_data={}, decoded=True, **kwargs): """Post the content of a URL via sending a HTTP POST request. Args: url: A URL. headers: Request headers used by the client. decoded: Whether decode the response body using UTF-8 or the charset specified in Content-Type. Returns: The content as a string. """ if kwargs.get('post_data_raw'): logging.debug('post_content: %s\npost_data_raw: %s' % (url, kwargs['post_data_raw'])) else: logging.debug('post_content: %s\npost_data: %s' % (url, post_data)) req = request.Request(url, headers=headers) if cookies: cookies.add_cookie_header(req) req.headers.update(req.unredirected_hdrs) if kwargs.get('post_data_raw'): post_data_enc = bytes(kwargs['post_data_raw'], 'utf-8') else: post_data_enc = bytes(parse.urlencode(post_data), 'utf-8') response = urlopen_with_retry(req, data=post_data_enc) data
python
{ "resource": "" }
q265754
parse_host
test
def parse_host(host): """Parses host name and port number from a string. """ if re.match(r'^(\d+)$', host) is not None: return ("0.0.0.0", int(host)) if re.match(r'^(\w+)://', host) is None:
python
{ "resource": "" }
q265755
showroom_get_roomid_by_room_url_key
test
def showroom_get_roomid_by_room_url_key(room_url_key): """str->str""" fake_headers_mobile = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Charset': 'UTF-8,*;q=0.5', 'Accept-Encoding': 'gzip,deflate,sdch', 'Accept-Language':
python
{ "resource": "" }
q265756
_wanmen_get_title_by_json_topic_part
test
def _wanmen_get_title_by_json_topic_part(json_content, tIndex, pIndex): """JSON, int, int, int->str Get a proper title with courseid+topicID+partID.""" return '_'.join([json_content[0]['name'],
python
{ "resource": "" }
q265757
wanmen_download_by_course
test
def wanmen_download_by_course(json_api_content, output_dir='.', merge=True, info_only=False, **kwargs): """int->None Download a WHOLE course. Reuse the API call to save time.""" for tIndex in range(len(json_api_content[0]['Topics'])): for pIndex in range(len(json_api_content[0]['Topics'][tIndex]['Parts'])):
python
{ "resource": "" }
q265758
wanmen_download_by_course_topic_part
test
def wanmen_download_by_course_topic_part(json_api_content, tIndex, pIndex, output_dir='.', merge=True, info_only=False, **kwargs): """int, int, int->None Download ONE PART of the course.""" html = json_api_content title = _wanmen_get_title_by_json_topic_part(html, tIndex, pIndex) bokeccID = _wanmen_get_boke_id_by_json_topic_part(html,
python
{ "resource": "" }
q265759
BaseExecutor.has_task
test
def has_task(self, task_instance): """ Checks if a task is either queued or running in this executor :param task_instance: TaskInstance :return: True if the task is known to this executor """
python
{ "resource": "" }
q265760
BaseExecutor.get_event_buffer
test
def get_event_buffer(self, dag_ids=None): """ Returns and flush the event buffer. In case dag_ids is specified it will only return and flush events for the given dag_ids. Otherwise it returns and flushes all :param dag_ids: to dag_ids to return events for, if None returns all :return: a dict of events """ cleared_events = dict() if dag_ids is None: cleared_events = self.event_buffer
python
{ "resource": "" }
q265761
SnowflakeHook.get_conn
test
def get_conn(self): """ Returns a snowflake.connection object """ conn_config = self._get_conn_params()
python
{ "resource": "" }
q265762
SnowflakeHook._get_aws_credentials
test
def _get_aws_credentials(self): """ returns aws_access_key_id, aws_secret_access_key from extra intended to be used by external import and export statements """ if self.snowflake_conn_id: connection_object = self.get_connection(self.snowflake_conn_id) if 'aws_secret_access_key' in connection_object.extra_dejson: aws_access_key_id = connection_object.extra_dejson.get(
python
{ "resource": "" }
q265763
GrpcHook._get_field
test
def _get_field(self, field_name, default=None): """ Fetches a field from extras, and returns it. This is some Airflow magic. The grpc hook type adds custom UI elements to the hook page, which allow admins to specify scopes, credential pem files, etc. They get formatted as shown below. """
python
{ "resource": "" }
q265764
PostgresHook.copy_expert
test
def copy_expert(self, sql, filename, open=open): """ Executes SQL using psycopg2 copy_expert method. Necessary to execute COPY command without access to a superuser. Note: if this method is called with a "COPY FROM" statement and the specified input file does not exist, it creates an empty file and no data is loaded, but the operation succeeds. So if users want to be aware when the input file does not exist, they have to check its existence by themselves. """ if not os.path.isfile(filename):
python
{ "resource": "" }
q265765
PostgresHook.bulk_dump
test
def bulk_dump(self, table, tmp_file): """ Dumps a database table into a tab-delimited file """
python
{ "resource": "" }
q265766
FileToGoogleCloudStorageOperator.execute
test
def execute(self, context): """ Uploads the file to Google cloud storage """ hook = GoogleCloudStorageHook( google_cloud_storage_conn_id=self.google_cloud_storage_conn_id, delegate_to=self.delegate_to) hook.upload( bucket_name=self.bucket,
python
{ "resource": "" }
q265767
max_partition
test
def max_partition( table, schema="default", field=None, filter_map=None, metastore_conn_id='metastore_default'): """ Gets the max partition for a table. :param schema: The hive schema the table lives in :type schema: str :param table: The hive table you are interested in, supports the dot notation as in "my_database.my_table", if a dot is found, the schema param is disregarded :type table: str :param metastore_conn_id: The hive connection you are interested in. If your default is set you don't need to use this parameter. :type metastore_conn_id: str
python
{ "resource": "" }
q265768
MySqlHook.get_conn
test
def get_conn(self): """ Returns a mysql connection object """ conn = self.get_connection(self.mysql_conn_id) conn_config = { "user": conn.login, "passwd": conn.password or '', "host": conn.host or 'localhost', "db": self.schema or conn.schema or '' } if not conn.port: conn_config["port"] = 3306 else: conn_config["port"] = int(conn.port) if conn.extra_dejson.get('charset', False): conn_config["charset"] = conn.extra_dejson["charset"] if (conn_config["charset"]).lower() == 'utf8' or\ (conn_config["charset"]).lower() == 'utf-8': conn_config["use_unicode"] = True if conn.extra_dejson.get('cursor', False):
python
{ "resource": "" }
q265769
task_state
test
def task_state(args): """ Returns the state of a TaskInstance at the command line. >>> airflow task_state tutorial sleep 2015-01-01 success """ dag =
python
{ "resource": "" }
q265770
restart_workers
test
def restart_workers(gunicorn_master_proc, num_workers_expected, master_timeout): """ Runs forever, monitoring the child processes of @gunicorn_master_proc and restarting workers occasionally. Each iteration of the loop traverses one edge of this state transition diagram, where each state (node) represents [ num_ready_workers_running / num_workers_running ]. We expect most time to be spent in [n / n]. `bs` is the setting webserver.worker_refresh_batch_size. The horizontal transition at ? happens after the new worker parses all the dags (so it could take a while!) V ────────────────────────────────────────────────────────────────────────┐ [n / n] ──TTIN──> [ [n, n+bs) / n + bs ] ────?───> [n + bs / n + bs] ──TTOU─┘ ^ ^───────────────┘ │ │ ┌────────────────v └──────┴────── [ [0, n) / n ] <─── start We change the number of workers by sending TTIN and TTOU to the gunicorn master process, which increases and decreases the number of child workers respectively. Gunicorn guarantees that on TTOU workers are terminated gracefully and that the oldest worker is terminated. """ def wait_until_true(fn, timeout=0): """ Sleeps until fn is true """ t = time.time() while not fn(): if 0 < timeout <= time.time() - t: raise AirflowWebServerTimeout( "No response from gunicorn master within {0} seconds" .format(timeout)) time.sleep(0.1) def start_refresh(gunicorn_master_proc): batch_size = conf.getint('webserver', 'worker_refresh_batch_size') log.debug('%s doing a refresh of %s workers', state, batch_size) sys.stdout.flush() sys.stderr.flush() excess = 0 for _ in range(batch_size): gunicorn_master_proc.send_signal(signal.SIGTTIN) excess += 1 wait_until_true(lambda: num_workers_expected + excess == get_num_workers_running(gunicorn_master_proc), master_timeout) try: wait_until_true(lambda: num_workers_expected == get_num_workers_running(gunicorn_master_proc), master_timeout) while True: num_workers_running = get_num_workers_running(gunicorn_master_proc) num_ready_workers_running = \ get_num_ready_workers_running(gunicorn_master_proc) state = '[{0} / {1}]'.format(num_ready_workers_running, num_workers_running) # Whenever some workers are not ready, wait until all workers are ready if num_ready_workers_running < num_workers_running: log.debug('%s
python
{ "resource": "" }
q265771
CloudTranslateHook.get_conn
test
def get_conn(self): """ Retrieves connection to Cloud Translate :return: Google Cloud Translate client object. :rtype: Client """ if not self._client:
python
{ "resource": "" }
q265772
CloudTranslateHook.translate
test
def translate( self, values, target_language, format_=None, source_language=None, model=None ): """Translate a string or list of strings. See https://cloud.google.com/translate/docs/translating-text :type values: str or list :param values: String or list of strings to translate. :type target_language: str :param target_language: The language to translate results into. This is required by the API and defaults to the target language of the current instance. :type format_: str :param format_: (Optional) One of ``text`` or ``html``, to specify if the input text is plain text or HTML. :type source_language: str or None :param source_language: (Optional) The language of the text to
python
{ "resource": "" }
q265773
CloudSqlHook.get_instance
test
def get_instance(self, instance, project_id=None): """ Retrieves a resource containing information about a Cloud SQL instance. :param instance: Database instance ID. This does not include the project ID. :type instance: str :param project_id: Project ID of the project that contains the instance. If set to None or missing, the default project_id from the GCP connection is used.
python
{ "resource": "" }
q265774
CloudSqlHook.create_instance
test
def create_instance(self, body, project_id=None): """ Creates a new Cloud SQL instance. :param body: Body required by the Cloud SQL insert API, as described in https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/instances/insert#request-body. :type body: dict :param project_id: Project ID of the project that contains the instance. If set to None or missing, the default project_id from the GCP connection is used. :type project_id: str :return: None """ response = self.get_conn().instances().insert(
python
{ "resource": "" }
q265775
CloudSqlHook.patch_instance
test
def patch_instance(self, body, instance, project_id=None): """ Updates settings of a Cloud SQL instance. Caution: This is not a partial update, so you must include values for all the settings that you want to retain. :param body: Body required by the Cloud SQL patch API, as described in https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/instances/patch#request-body. :type body: dict :param instance: Cloud SQL instance ID. This does not include the project ID. :type instance: str :param project_id: Project ID of the project that contains the instance. If set to None or missing, the default project_id from the GCP connection is used.
python
{ "resource": "" }
q265776
CloudSqlHook.delete_instance
test
def delete_instance(self, instance, project_id=None): """ Deletes a Cloud SQL instance. :param project_id: Project ID of the project that contains the instance. If set to None or missing, the default project_id from the GCP connection is used. :type project_id: str :param instance: Cloud SQL instance ID. This does not include the project ID. :type instance: str :return: None """ response = self.get_conn().instances().delete( project=project_id,
python
{ "resource": "" }
q265777
CloudSqlHook.get_database
test
def get_database(self, instance, database, project_id=None): """ Retrieves a database resource from a Cloud SQL instance. :param instance: Database instance ID. This does not include the project ID. :type instance: str :param database: Name of the database in the instance. :type database: str :param project_id: Project ID of the project that contains the instance. If set to None or missing, the default project_id from the GCP connection is used. :type project_id: str :return: A Cloud SQL database resource, as described in
python
{ "resource": "" }
q265778
CloudSqlHook.create_database
test
def create_database(self, instance, body, project_id=None): """ Creates a new database inside a Cloud SQL instance. :param instance: Database instance ID. This does not include the project ID. :type instance: str :param body: The request body, as described in https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/databases/insert#request-body. :type body: dict :param project_id: Project ID of the project that contains the instance. If set to None or missing, the default project_id from the GCP connection is used. :type project_id: str :return: None
python
{ "resource": "" }
q265779
CloudSqlHook.patch_database
test
def patch_database(self, instance, database, body, project_id=None): """ Updates a database resource inside a Cloud SQL instance. This method supports patch semantics. See https://cloud.google.com/sql/docs/mysql/admin-api/how-tos/performance#patch. :param instance: Database instance ID. This does not include the project ID. :type instance: str :param database: Name of the database to be updated in the instance. :type database: str :param body: The request body, as described in https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/databases/insert#request-body. :type body: dict :param project_id: Project ID of the project that contains the instance. If set to None or missing, the default project_id from the GCP connection is
python
{ "resource": "" }
q265780
CloudSqlHook.delete_database
test
def delete_database(self, instance, database, project_id=None): """ Deletes a database from a Cloud SQL instance. :param instance: Database instance ID. This does not include the project ID. :type instance: str :param database: Name of the database to be deleted in the instance. :type database: str :param project_id: Project ID of the project that contains the instance. If set to None or missing, the default project_id from the GCP connection is used. :type project_id: str :return: None """ response =
python
{ "resource": "" }
q265781
CloudSqlHook.export_instance
test
def export_instance(self, instance, body, project_id=None): """ Exports data from a Cloud SQL instance to a Cloud Storage bucket as a SQL dump or CSV file. :param instance: Database instance ID of the Cloud SQL instance. This does not include the project ID. :type instance: str :param body: The request body, as described in https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/instances/export#request-body :type body: dict :param project_id: Project ID of the project that contains the instance. If set to None or missing, the default project_id from the GCP connection is used. :type project_id: str :return: None """ try: response = self.get_conn().instances().export( project=project_id, instance=instance, body=body
python
{ "resource": "" }
q265782
CloudSqlProxyRunner.start_proxy
test
def start_proxy(self): """ Starts Cloud SQL Proxy. You have to remember to stop the proxy if you started it! """ self._download_sql_proxy_if_needed() if self.sql_proxy_process: raise AirflowException("The sql proxy is already running: {}".format( self.sql_proxy_process)) else: command_to_run = [self.sql_proxy_path] command_to_run.extend(self.command_line_parameters) try: self.log.info("Creating directory %s", self.cloud_sql_proxy_socket_directory) os.makedirs(self.cloud_sql_proxy_socket_directory) except OSError: # Needed for python 2 compatibility (exists_ok missing) pass command_to_run.extend(self._get_credential_parameters()) self.log.info("Running the command: `%s`", " ".join(command_to_run)) self.sql_proxy_process = Popen(command_to_run, stdin=PIPE, stdout=PIPE, stderr=PIPE) self.log.info("The pid of cloud_sql_proxy: %s", self.sql_proxy_process.pid) while True: line = self.sql_proxy_process.stderr.readline().decode('utf-8')
python
{ "resource": "" }
q265783
CloudSqlProxyRunner.stop_proxy
test
def stop_proxy(self): """ Stops running proxy. You should stop the proxy after you stop using it. """ if not self.sql_proxy_process: raise AirflowException("The sql proxy is not started yet") else: self.log.info("Stopping the cloud_sql_proxy pid: %s", self.sql_proxy_process.pid) self.sql_proxy_process.kill() self.sql_proxy_process = None # Cleanup! self.log.info("Removing the socket directory: %s", self.cloud_sql_proxy_socket_directory)
python
{ "resource": "" }
q265784
CloudSqlProxyRunner.get_proxy_version
test
def get_proxy_version(self): """ Returns version of the Cloud SQL Proxy. """ self._download_sql_proxy_if_needed() command_to_run = [self.sql_proxy_path] command_to_run.extend(['--version']) command_to_run.extend(self._get_credential_parameters()) result
python
{ "resource": "" }
q265785
CloudSqlDatabaseHook.create_connection
test
def create_connection(self, session=None): """ Create connection in the Connection table, according to whether it uses proxy, TCP, UNIX sockets, SSL. Connection ID will be randomly generated. :param session: Session of the SQL Alchemy
python
{ "resource": "" }
q265786
CloudSqlDatabaseHook.retrieve_connection
test
def retrieve_connection(self, session=None): """ Retrieves the dynamically created connection from the Connection table. :param session: Session of the SQL Alchemy ORM (automatically generated with decorator). """
python
{ "resource": "" }
q265787
CloudSqlDatabaseHook.delete_connection
test
def delete_connection(self, session=None): """ Delete the dynamically created connection from the Connection table. :param session: Session of the SQL Alchemy ORM (automatically generated with decorator). """ self.log.info("Deleting connection %s", self.db_conn_id) connections = session.query(Connection).filter(
python
{ "resource": "" }
q265788
CloudSqlDatabaseHook.get_sqlproxy_runner
test
def get_sqlproxy_runner(self): """ Retrieve Cloud SQL Proxy runner. It is used to manage the proxy lifecycle per task. :return: The Cloud SQL Proxy runner. :rtype: CloudSqlProxyRunner """ if not self.use_proxy: raise AirflowException("Proxy runner can only be retrieved in case of use_proxy = True") return CloudSqlProxyRunner( path_prefix=self.sql_proxy_unique_path,
python
{ "resource": "" }
q265789
CloudSqlDatabaseHook.get_database_hook
test
def get_database_hook(self): """ Retrieve database hook. This is the actual Postgres or MySQL database hook that uses proxy or connects directly to the Google Cloud SQL database. """ if self.database_type == 'postgres': self.db_hook = PostgresHook(postgres_conn_id=self.db_conn_id,
python
{ "resource": "" }
q265790
CloudSqlDatabaseHook.cleanup_database_hook
test
def cleanup_database_hook(self): """ Clean up database hook after it was used. """ if self.database_type == 'postgres': if hasattr(self.db_hook,
python
{ "resource": "" }
q265791
CloudSqlDatabaseHook.reserve_free_tcp_port
test
def reserve_free_tcp_port(self): """ Reserve free TCP port to be used by Cloud SQL Proxy """ self.reserved_tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
python
{ "resource": "" }
q265792
_normalize_mlengine_job_id
test
def _normalize_mlengine_job_id(job_id): """ Replaces invalid MLEngine job_id characters with '_'. This also adds a leading 'z' in case job_id starts with an invalid character. Args: job_id: A job_id str that may have invalid characters. Returns: A valid job_id representation. """ # Add a prefix when a job_id starts with a digit or a template match = re.search(r'\d|\{{2}', job_id) if match and match.start() == 0: job = 'z_{}'.format(job_id) else: job = job_id # Clean up 'bad' characters except templates tracker = 0 cleansed_job_id = '' for m in re.finditer(r'\{{2}.+?\}{2}', job):
python
{ "resource": "" }
q265793
FTPSensor._get_error_code
test
def _get_error_code(self, e): """Extract error code from ftp exception""" try: matches
python
{ "resource": "" }
q265794
clear_dag_runs
test
def clear_dag_runs(): """ Remove any existing DAG runs for the perf test DAGs. """ session = settings.Session() drs = session.query(DagRun).filter( DagRun.dag_id.in_(DAG_IDS),
python
{ "resource": "" }
q265795
clear_dag_task_instances
test
def clear_dag_task_instances(): """ Remove any existing task instances for the perf test DAGs. """ session = settings.Session() TI = TaskInstance tis = ( session .query(TI) .filter(TI.dag_id.in_(DAG_IDS))
python
{ "resource": "" }
q265796
set_dags_paused_state
test
def set_dags_paused_state(is_paused): """ Toggle the pause state of the DAGs in the test. """ session = settings.Session() dms = session.query(DagModel).filter( DagModel.dag_id.in_(DAG_IDS)) for dm in dms:
python
{ "resource": "" }
q265797
SchedulerMetricsJob.print_stats
test
def print_stats(self): """ Print operational metrics for the scheduler test. """ session = settings.Session() TI = TaskInstance tis = ( session .query(TI) .filter(TI.dag_id.in_(DAG_IDS)) .all() ) successful_tis = [x for x in tis if x.state == State.SUCCESS] ti_perf = [(ti.dag_id, ti.task_id, ti.execution_date, (ti.queued_dttm - self.start_date).total_seconds(), (ti.start_date - self.start_date).total_seconds(), (ti.end_date - self.start_date).total_seconds(), ti.duration) for ti in successful_tis] ti_perf_df = pd.DataFrame(ti_perf, columns=['dag_id',
python
{ "resource": "" }
q265798
SchedulerMetricsJob.heartbeat
test
def heartbeat(self): """ Override the scheduler heartbeat to determine when the test is complete """ super(SchedulerMetricsJob, self).heartbeat() session = settings.Session() # Get all the relevant task instances TI = TaskInstance successful_tis = ( session .query(TI) .filter(TI.dag_id.in_(DAG_IDS)) .filter(TI.state.in_([State.SUCCESS])) .all() ) session.commit() dagbag = DagBag(SUBDIR) dags = [dagbag.dags[dag_id] for dag_id in DAG_IDS] # the tasks in perf_dag_1 and per_dag_2 have a daily schedule interval. num_task_instances = sum([(timezone.utcnow() - task.start_date).days
python
{ "resource": "" }
q265799
AwsLambdaHook.invoke_lambda
test
def invoke_lambda(self, payload): """ Invoke Lambda Function """ awslambda_conn = self.get_conn() response = awslambda_conn.invoke( FunctionName=self.function_name, InvocationType=self.invocation_type,
python
{ "resource": "" }