_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | 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.
'''
_AssertIsLocal(source_filename)
_AssertIsLocal(target_file... | 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 IsDi... | 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:
... | 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 d... | 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 g... | 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_styl... | 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.
... | 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 try... | 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 r... | 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 ... | 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
... | 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.move... | 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:
retu... | 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.
'''
im... | 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 pattern... | 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()
path = path.encode(e... | 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:
... | 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 ge... | 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 Push... | 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... | 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:
if local_match:
return server[loca... | 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')
... | python | {
"resource": ""
} |
q265723 | coerce | validation | def coerce(value1, value2, default=None):
"""Exclude NoSet objec
.. code-block::
>>> coerce(NoSet, 'value')
'value'
"""
if value1 is not NoSet:
return value1
elif value2 is not NoSet:
return value2
else:
return default | 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:
m... | 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
"""
if not string or not re.match('^(' + PARTS[part] + ')$', string):
raise ValueError('{} should match {}'.f... | 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 'action' in command and "()" in command['action']:
command['action'] = eval("self.{}".format(command['action']))
... | 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']
kwargs = {}
for item in command:
kwargs[item] =... | 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']:
subparser = subparsers.add_parser(name)
self.create_commands(self.config['subparsers'][name], subparser) | 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, ... | 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 = v... | 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: ')
tokens = {
... | 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():
constant_name = extension_name.upper() + "_FIELD_NUMBER"
setattr(cls, constant... | 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.
A... | 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'):
url = node.getElementsByTagName('url')[0]
rawurl.append(url.childNodes[0].data)
return rawurl | 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 \
mat... | 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 Non... | python | {
"resource": ""
} |
q265737 | sprint | test | def sprint(text, *colors):
"""Format text with color or other effects into ANSI escaped string."""
return "\33[{}m{content}\33[{}m".format(";".join([str(color) for color in colors]), RESET, content=text) if IS_ANSI_TERMINAL and colors else text | python | {
"resource": ""
} |
q265738 | print_log | test | def print_log(text, *colors):
"""Print a log message to standard error."""
sys.stderr.write(sprint("{}: {}".format(script_name, text), *colors) + "\n") | python | {
"resource": ""
} |
q265739 | e | test | def e(message, exit_code=None):
"""Print an error log message."""
print_log(message, YELLOW, BOLD)
if exit_code is not None:
sys.exit(exit_code) | python | {
"resource": ""
} |
q265740 | wtf | test | def wtf(message, exit_code=1):
"""What a Terrible Failure!"""
print_log(message, RED, BOLD)
if exit_code is not None:
sys.exit(exit_code) | 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' ... | 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
channel_id = match1(url, r'http://vimeo.com/channels/(\w+)')
vimeo_download_by_channel_id(channel_id, output_dir, merge, info_only, **kwargs) | 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... | 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... | 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],
... | 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':
#... | 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 = match1(html, r'video\.settings\.title\s*=\s*\"([^\"]+)\"')
theplatform_download_by_pi... | 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']:
... | 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.loa... | 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.
"""
ret = []
for pattern in patterns:
match = re.finda... | 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.
param: A string representing the name of the parameter.
Returns:
The value of the parameter.
"""
try:
return parse.parse_qs(parse.urlparse... | 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:
... | 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... | 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:
host = "//" + host
o = parse.urlparse(host)
hostname = o.hostname or "0.0.0.0"
port =... | 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': 'en-US,en;q=0.8... | 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'],
json_content[0]['Topics'][tIndex]['name'],
json_content[0]['Topics']... | 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'][t... | 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,
... | 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
"""
if task_instance.key in self.queued_tasks or task_instance.key in self.running:... | 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
... | python | {
"resource": ""
} |
q265761 | SnowflakeHook.get_conn | test | def get_conn(self):
"""
Returns a snowflake.connection object
"""
conn_config = self._get_conn_params()
conn = snowflake.connector.connect(**conn_config)
return conn | 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)
... | 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 b... | 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 creat... | python | {
"resource": ""
} |
q265765 | PostgresHook.bulk_dump | test | def bulk_dump(self, table, tmp_file):
"""
Dumps a database table into a tab-delimited file
"""
self.copy_expert("COPY {table} TO STDOUT".format(table=table), tmp_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 t... | 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 c... | 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 = get_dag(args)
task = dag.get_task(task_id=args.task_id)
ti = TaskInstance(task, args.execution_date)
print(ti.current_state()) | 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) repr... | 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:
self._client = Client(credentials=self._get_credentials())
return 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 trans... | 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 conta... | 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
:... | 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 des... | 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
:... | 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.
... | 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:/... | 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 ins... | 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.... | 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 in... | 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(
... | 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: ... | 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 ORM (automatically generated with
... | 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).
"""
self.log.info("Retrieving connection %s",... | 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.d... | 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... | 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=sel... | 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,
'conn') and self.db_hook.conn and self.db_hook.conn.notices:
for output in self.db_hook.conn... | 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)
self.reserved_tcp_socket.bind(('127.0.0.1', 0))
self.sql_proxy_tcp_port = self.reserved_tcp_socket.get... | 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.
... | python | {
"resource": ""
} |
q265793 | FTPSensor._get_error_code | test | def _get_error_code(self, e):
"""Extract error code from ftp exception"""
try:
matches = self.error_code_pattern.match(str(e))
code = int(matches.group(0))
return code
except ValueError:
return e | 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),
).all()
for dr in drs:
logging.info('Deleting DagRun :: {}'.format(dr))
session.delete(dr) | 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))
.all()
)
for ti in tis:
logging.info('Delet... | 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:
logging.info('Setting DAG :: {} is_paused={}'.format(dm, is_paused))
... | 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_t... | 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 = (
... | 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,
LogType=self.log_type,
Paylo... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.