sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def create_zip_dir(zipfile_path, *file_list):
""" This function creates a zipfile located in zipFilePath with the files in
the file list
# fileList can be both a comma separated list or an array
"""
try:
if isinstance(file_list, (list, tuple)): #unfolding list of list or tuple
if len(file_... | This function creates a zipfile located in zipFilePath with the files in
the file list
# fileList can be both a comma separated list or an array | entailment |
def file_zipper(root_dir):
""" This function will zip the files created in the runroot directory and
subdirectories """
# FINDING AND ZIPPING UNZIPPED FILES
for root, dirs, files in os.walk(root_dir, topdown=False):
if root != "":
if root[-1] != '/': root += '/'
for current_file in f... | This function will zip the files created in the runroot directory and
subdirectories | entailment |
def file_unzipper(directory):
""" This function will unzip all files in the runroot directory and
subdirectories
"""
debug.log("Unzipping directory (%s)..."%directory)
#FINDING AND UNZIPPING ZIPPED FILES
for root, dirs, files in os.walk(directory, topdown=False):
if root != "":
orig_dir... | This function will unzip all files in the runroot directory and
subdirectories | entailment |
def move_file(src, dst):
""" this function will simply move the file from the source path to the dest
path given as input
"""
# Sanity checkpoint
src = re.sub('[^\w/\-\.\*]', '', src)
dst = re.sub('[^\w/\-\.\*]', '', dst)
if len(re.sub('[\W]', '', src)) < 5 or len(re.sub('[\W]', '', dst)) < 5:
... | this function will simply move the file from the source path to the dest
path given as input | entailment |
def copy_file(src, dst, ignore=None):
""" this function will simply copy the file from the source path to the dest
path given as input
"""
# Sanity checkpoint
src = re.sub('[^\w/\-\.\*]', '', src)
dst = re.sub('[^\w/\-\.\*]', '', dst)
if len(re.sub('[\W]', '', src)) < 5 or len(re.sub('[\W]', '', ds... | this function will simply copy the file from the source path to the dest
path given as input | entailment |
def copy_dir(src, dst):
""" this function will simply copy the file from the source path to the dest
path given as input
"""
try:
debug.log("copy dir from "+ src, "to "+ dst)
shutil.copytree(src, dst)
except Exception as e:
debug.log("Error: happened while copying!\n%s\n"%e) | this function will simply copy the file from the source path to the dest
path given as input | entailment |
def print_out(self, *lst):
""" Print list of strings to the predefined stdout. """
self.print2file(self.stdout, True, True, *lst) | Print list of strings to the predefined stdout. | entailment |
def print_err(self, *lst):
""" Print list of strings to the predefined stdout. """
self.print2file(self.stderr, False, True, *lst) | Print list of strings to the predefined stdout. | entailment |
def print2file(self, logfile, print2screen, addLineFeed, *lst):
""" This function prints to the screen and logs to a file, all the strings
given.
# print2screen eg. True, *lst is a commaseparated list of strings
"""
if addLineFeed:
linefeed = '\n'
else: linefeed = ''
i... | This function prints to the screen and logs to a file, all the strings
given.
# print2screen eg. True, *lst is a commaseparated list of strings | entailment |
def log(self, *lst):
""" Print list of strings to the predefined logfile if debug is set. and
sets the caught_error message if an error is found
"""
self.print2file(self.logfile, self.debug, True, *lst)
if 'Error' in '\n'.join([str(x) for x in lst]):
self.caught_error = '\n'.join(... | Print list of strings to the predefined logfile if debug is set. and
sets the caught_error message if an error is found | entailment |
def log_no_newline(self, msg):
""" print the message to the predefined log file without newline """
self.print2file(self.logfile, False, False, msg) | print the message to the predefined log file without newline | entailment |
def graceful_exit(self, msg):
""" This function Tries to update the MSQL database before exiting. """
# Print stored errors to stderr
if self.caught_error:
self.print2file(self.stderr, False, False, self.caught_error)
# Kill process with error message
self.log(msg)
sys.exit(... | This function Tries to update the MSQL database before exiting. | entailment |
def get_tree(self, list_of_keys):
""" gettree will extract the value from a nested tree
INPUT
list_of_keys: a list of keys ie. ['key1', 'key2']
USAGE
>>> # Access the value for key2 within the nested dictionary
>>> adv_dict({'key1': {'key2': 'value'}}).gettree(['key1', 'key... | gettree will extract the value from a nested tree
INPUT
list_of_keys: a list of keys ie. ['key1', 'key2']
USAGE
>>> # Access the value for key2 within the nested dictionary
>>> adv_dict({'key1': {'key2': 'value'}}).gettree(['key1', 'key2'])
'value' | entailment |
def invert(self):
''' Return inverse mapping of dictionary with sorted values.
USAGE
>>> # Switch the keys and values
>>> adv_dict({
... 'A': [1, 2, 3],
... 'B': [4, 2],
... 'C': [1, 4],
... }).invert()
{1: ['A', 'C'], 2: ['A', 'B'],... | Return inverse mapping of dictionary with sorted values.
USAGE
>>> # Switch the keys and values
>>> adv_dict({
... 'A': [1, 2, 3],
... 'B': [4, 2],
... 'C': [1, 4],
... }).invert()
{1: ['A', 'C'], 2: ['A', 'B'], 3: ['A'], 4: ['B', 'C']} | entailment |
def sub(self, replace, string, count=0):
""" returns new string where the matching cases (limited by the count) in
the string is replaced. """
return self.re.sub(replace, string, count) | returns new string where the matching cases (limited by the count) in
the string is replaced. | entailment |
def match(self, s):
""" Matches the string to the stored regular expression, and stores all
groups in mathches. Returns False on negative match. """
self.matches = self.re.search(s)
return self.matches | Matches the string to the stored regular expression, and stores all
groups in mathches. Returns False on negative match. | entailment |
def match(self, s):
""" Matching the pattern to the input string, returns True/False and
saves the matched string in the internal list
"""
if self.re.match(s):
self.list.append(s)
return True
else: return False | Matching the pattern to the input string, returns True/False and
saves the matched string in the internal list | entailment |
def reporter(self):
"""
Create the MASH report
"""
logging.info('Creating {} report'.format(self.analysistype))
make_path(self.reportpath)
header = 'Strain,ReferenceGenus,ReferenceFile,ReferenceGenomeMashDistance,Pvalue,NumMatchingHashes\n'
data = ''
for s... | Create the MASH report | entailment |
def get_function(pkgpath):
"""Take a full path to a python method or class, for example
mypkg.subpkg.method and return the method or class (after importing the
required packages)
"""
# Extract the module and function name from pkgpath
elems = pkgpath.split('.')
if len(elems) <= 1:
ra... | Take a full path to a python method or class, for example
mypkg.subpkg.method and return the method or class (after importing the
required packages) | entailment |
def runner(self):
"""
Run the necessary methods in the correct order
"""
printtime('Starting {} analysis pipeline'.format(self.analysistype), self.starttime)
# Create the objects to be used in the analyses
objects = Objectprep(self)
objects.objectprep()
se... | Run the necessary methods in the correct order | entailment |
def syllabify(word):
'''Syllabify the given word, whether simplex or complex.'''
word = split(word) # detect any non-delimited compounds
compound = True if re.search(r'-| |\.', word) else False
syllabify = _syllabify_compound if compound else _syllabify
syll, rules = syllabify(word)
yield syll... | Syllabify the given word, whether simplex or complex. | entailment |
def edges(self):
"""
Return the edge characters of this node.
"""
edge_str = ctypes.create_string_buffer(MAX_CHARS)
cgaddag.gdg_edges(self.gdg, self.node, edge_str)
return [char for char in edge_str.value.decode("ascii")] | Return the edge characters of this node. | entailment |
def letter_set(self):
"""
Return the letter set of this node.
"""
end_str = ctypes.create_string_buffer(MAX_CHARS)
cgaddag.gdg_letter_set(self.gdg, self.node, end_str)
return [char for char in end_str.value.decode("ascii")] | Return the letter set of this node. | entailment |
def is_end(self, char):
"""
Return `True` if this `char` is part of this node's letter set,
`False` otherwise.
"""
char = char.lower()
return bool(cgaddag.gdg_is_end(self.gdg, self.node, char.encode("ascii"))) | Return `True` if this `char` is part of this node's letter set,
`False` otherwise. | entailment |
def follow(self, chars):
"""
Traverse the GADDAG to the node at the end of the given characters.
Args:
chars: An string of characters to traverse in the GADDAG.
Returns:
The Node which is found by traversing the tree.
"""
chars = chars.lower()
... | Traverse the GADDAG to the node at the end of the given characters.
Args:
chars: An string of characters to traverse in the GADDAG.
Returns:
The Node which is found by traversing the tree. | entailment |
def _split_docker_link(alias_name):
"""
Splits a docker link string into a list of 3 items (protocol, host, port).
- Assumes IPv4 Docker links
ex: _split_docker_link('DB') -> ['tcp', '172.17.0.82', '8080']
"""
sanitized_name = alias_name.strip().upper()
split_list = re.split(r':|//', core.s... | Splits a docker link string into a list of 3 items (protocol, host, port).
- Assumes IPv4 Docker links
ex: _split_docker_link('DB') -> ['tcp', '172.17.0.82', '8080'] | entailment |
def read(alias_name, allow_none=False):
"""Get the raw docker link value.
Get the raw environment variable for the docker link
Args:
alias_name: The environment variable name
default: The default value if the link isn't available
allow_none: If the return value can be `None` (i.e. ... | Get the raw docker link value.
Get the raw environment variable for the docker link
Args:
alias_name: The environment variable name
default: The default value if the link isn't available
allow_none: If the return value can be `None` (i.e. optional) | entailment |
def isset(alias_name):
"""Return a boolean if the docker link is set or not and is a valid looking docker link value.
Args:
alias_name: The link alias name
"""
warnings.warn('Will be removed in v1.0', DeprecationWarning, stacklevel=2)
raw_value = read(alias_name, allow_none=True)
if raw... | Return a boolean if the docker link is set or not and is a valid looking docker link value.
Args:
alias_name: The link alias name | entailment |
def protocol(alias_name, default=None, allow_none=False):
"""Get the protocol from the docker link alias or return the default.
Args:
alias_name: The docker link alias
default: The default value if the link isn't available
allow_none: If the return value can be `None` (i.e. optional)
... | Get the protocol from the docker link alias or return the default.
Args:
alias_name: The docker link alias
default: The default value if the link isn't available
allow_none: If the return value can be `None` (i.e. optional)
Examples:
Assuming a Docker link was created with ``do... | entailment |
def port(alias_name, default=None, allow_none=False):
"""Get the port from the docker link alias or return the default.
Args:
alias_name: The docker link alias
default: The default value if the link isn't available
allow_none: If the return value can be `None` (i.e. optional)
Examp... | Get the port from the docker link alias or return the default.
Args:
alias_name: The docker link alias
default: The default value if the link isn't available
allow_none: If the return value can be `None` (i.e. optional)
Examples:
Assuming a Docker link was created with ``docker... | entailment |
def runner(self):
"""
Run the necessary methods in the correct order
"""
printtime('Starting {} analysis pipeline'.format(self.analysistype), self.starttime)
if not self.pipeline:
# If the metadata has been passed from the method script, self.pipeline must still be fa... | Run the necessary methods in the correct order | entailment |
def attributer(self):
"""
Parses the 16S target files to link accession numbers stored in the .fai and metadata files to the genera stored
in the target file
"""
from Bio import SeqIO
import operator
for sample in self.runmetadata.samples:
# Load the r... | Parses the 16S target files to link accession numbers stored in the .fai and metadata files to the genera stored
in the target file | entailment |
def reporter(self):
"""
Creates a report of the results
"""
# Create the path in which the reports are stored
make_path(self.reportpath)
header = 'Strain,Gene,PercentIdentity,Genus,FoldCoverage\n'
data = ''
with open(os.path.join(self.reportpath, self.anal... | Creates a report of the results | entailment |
def spawn_server_api(api_name, app, api_spec, error_callback, decorator):
"""Take a a Flask app and a swagger file in YAML format describing a REST
API, and populate the app with routes handling all the paths and methods
declared in the swagger file.
Also handle marshaling and unmarshaling between json... | Take a a Flask app and a swagger file in YAML format describing a REST
API, and populate the app with routes handling all the paths and methods
declared in the swagger file.
Also handle marshaling and unmarshaling between json and object instances
representing the definitions from the swagger file. | entailment |
def _responsify(api_spec, error, status):
"""Take a bravado-core model representing an error, and return a Flask Response
with the given error code and error instance as body"""
result_json = api_spec.model_to_json(error)
r = jsonify(result_json)
r.status_code = status
return r | Take a bravado-core model representing an error, and return a Flask Response
with the given error code and error instance as body | entailment |
def _generate_handler_wrapper(api_name, api_spec, endpoint, handler_func, error_callback, global_decorator):
"""Generate a handler method for the given url method+path and operation"""
# Decorate the handler function, if Swagger spec tells us to
if endpoint.decorate_server:
endpoint_decorator = get... | Generate a handler method for the given url method+path and operation | entailment |
def format_escape( foreground=None, background=None, bold=False, faint=False,
italic=False, underline=False, blink=False, inverted=False ):
"""Returns the ANSI escape sequence to set character formatting.
foreground
Foreground colour to use. Accepted types: None, int (xterm
palette ID), tup... | Returns the ANSI escape sequence to set character formatting.
foreground
Foreground colour to use. Accepted types: None, int (xterm
palette ID), tuple (RGB, RGBA), Colour
background
Background colour to use. Accepted types: None, int (xterm
palette ID), tuple (RGB, RGBA), Colou... | entailment |
def format_string( string, foreground=None, background=None, reset=True, bold=False,
faint=False, italic=False, underline=False, blink=False, inverted=False ):
"""Returns a Unicode string formatted with an ANSI escape sequence.
string
String to format
foreground
Foreground colour to us... | Returns a Unicode string formatted with an ANSI escape sequence.
string
String to format
foreground
Foreground colour to use. Accepted types: None, int (xterm
palette ID), tuple (RGB, RGBA), Colour
background
Background colour to use. Accepted types: None, int (xterm
... | entailment |
def format_pixels( top, bottom, reset=True, repeat=1 ):
"""Return the ANSI escape sequence to render two vertically-stacked pixels as a
single monospace character.
top
Top colour to use. Accepted types: None, int (xterm
palette ID), tuple (RGB, RGBA), Colour
bottom
Bottom colou... | Return the ANSI escape sequence to render two vertically-stacked pixels as a
single monospace character.
top
Top colour to use. Accepted types: None, int (xterm
palette ID), tuple (RGB, RGBA), Colour
bottom
Bottom colour to use. Accepted types: None, int (xterm
palette ID),... | entailment |
def format_image_iter( data_fetch, x_start=0, y_start=0, width=32, height=32, frame=0, columns=1, downsample=1 ):
"""Return the ANSI escape sequence to render a bitmap image.
data_fetch
Function that takes three arguments (x position, y position, and frame) and returns
a Colour corresponding to... | Return the ANSI escape sequence to render a bitmap image.
data_fetch
Function that takes three arguments (x position, y position, and frame) and returns
a Colour corresponding to the pixel stored there, or Transparent if the requested
pixel is out of bounds.
x_start
Offset fro... | entailment |
def update_buffer_with_value( self, value, buffer, parent=None ):
"""Write a Python object into a byte array, using the field definition.
value
Input Python object to process.
buffer
Output byte array to encode value into.
parent
Parent block object... | Write a Python object into a byte array, using the field definition.
value
Input Python object to process.
buffer
Output byte array to encode value into.
parent
Parent block object where this Field is defined. Used for e.g.
evaluating Refs. | entailment |
def get_end_offset( self, value, parent=None, index=None ):
"""Return the end offset of the Field's data. Useful for chainloading.
value
Input Python object to process.
parent
Parent block object where this Field is defined. Used for e.g.
evaluating Refs.
... | Return the end offset of the Field's data. Useful for chainloading.
value
Input Python object to process.
parent
Parent block object where this Field is defined. Used for e.g.
evaluating Refs.
index
Index of the Python object to measure from. Us... | entailment |
def nonalpha_split(string):
'''Split 'string' along any punctuation or whitespace.'''
return re.findall(r'[%s]+|[^%s]+' % (A, A), string, flags=FLAGS) | Split 'string' along any punctuation or whitespace. | entailment |
def syllable_split(string):
'''Split 'string' into (stressed) syllables and punctuation/whitespace.'''
p = r'\'[%s]+|`[%s]+|[%s]+|[^%s\'`\.]+|[^\.]{1}' % (A, A, A, A)
return re.findall(p, string, flags=FLAGS) | Split 'string' into (stressed) syllables and punctuation/whitespace. | entailment |
def extract_words(string):
'''Extract all alphabetic syllabified forms from 'string'.'''
return re.findall(r'[%s]+[%s\.]*[%s]+' % (A, A, A), string, flags=FLAGS) | Extract all alphabetic syllabified forms from 'string'. | entailment |
def init_threads(t=None, s=None):
"""Should define dummyThread class and dummySignal class"""
global THREAD, SIGNAL
THREAD = t or dummyThread
SIGNAL = s or dummySignal | Should define dummyThread class and dummySignal class | entailment |
def thread_with_callback(on_error, on_done, requete_with_callback):
"""
Return a thread emiting `state_changed` between each sub-requests.
:param on_error: callback str -> None
:param on_done: callback object -> None
:param requete_with_callback: Job to execute. monitor_callable -> None
:return... | Return a thread emiting `state_changed` between each sub-requests.
:param on_error: callback str -> None
:param on_done: callback object -> None
:param requete_with_callback: Job to execute. monitor_callable -> None
:return: Non started thread | entailment |
def protege_data(datas_str, sens):
"""
Used to crypt/decrypt data before saving locally.
Override if securit is needed.
bytes -> str when decrypting
str -> bytes when crypting
:param datas_str: When crypting, str. when decrypting bytes
:param sens: True to crypt, False to decrypt
"""
... | Used to crypt/decrypt data before saving locally.
Override if securit is needed.
bytes -> str when decrypting
str -> bytes when crypting
:param datas_str: When crypting, str. when decrypting bytes
:param sens: True to crypt, False to decrypt | entailment |
def build_parser(parser: argparse.ArgumentParser) -> None:
"""Build a parser for CLI arguments and options."""
parser.add_argument(
'--delimiter',
help='a delimiter for the samples (teeth) in the key',
default=' ',
)
parser.add_argument(
'--encoding',
help='the en... | Build a parser for CLI arguments and options. | entailment |
def default_parser() -> argparse.ArgumentParser:
"""Create a parser for CLI arguments and options."""
parser = argparse.ArgumentParser(
prog=CONSOLE_SCRIPT,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
build_parser(parser)
return parser | Create a parser for CLI arguments and options. | entailment |
def key(
seq: Sequence,
tooth: Callable[[Sequence], str] = (
lambda seq: str(random.SystemRandom().choice(seq)).strip()
),
nteeth: int = 6,
delimiter: str = ' ',
) -> str:
"""Concatenate strings generated by the tooth function."""
return delimiter.join(tooth(s... | Concatenate strings generated by the tooth function. | entailment |
def main(argv: Sequence[str] = SYS_ARGV) -> int:
"""Execute CLI commands."""
args = default_parser().parse_args(argv)
try:
seq = POPULATIONS[args.population] # type: Sequence
except KeyError:
try:
with open(args.population, 'r', encoding=args.encoding) as file_:
... | Execute CLI commands. | entailment |
def add_firewalld_service(service, permanent=True):
""" adds a firewall rule """
yum_install(packages=['firewalld'])
with settings(hide('warnings', 'running', 'stdout', 'stderr'),
warn_only=True, capture=True):
p = ''
if permanent:
p = '--permanent'
sud... | adds a firewall rule | entailment |
def add_firewalld_port(port, permanent=True):
""" adds a firewall rule """
yum_install(packages=['firewalld'])
log_green('adding a new fw rule: %s' % port)
with settings(hide('warnings', 'running', 'stdout', 'stderr'),
warn_only=True, capture=True):
p = ''
if permanen... | adds a firewall rule | entailment |
def apt_add_repository_from_apt_string(apt_string, apt_file):
""" adds a new repository file for apt """
apt_file_path = '/etc/apt/sources.list.d/%s' % apt_file
if not file_contains(apt_file_path, apt_string.lower(), use_sudo=True):
file_append(apt_file_path, apt_string.lower(), use_sudo=True)
... | adds a new repository file for apt | entailment |
def arch():
""" returns the current cpu archictecture """
with settings(hide('warnings', 'running', 'stdout', 'stderr'),
warn_only=True, capture=True):
result = sudo('rpm -E %dist').strip()
return result | returns the current cpu archictecture | entailment |
def disable_openssh_rdns(distribution):
"""
Set 'UseDNS no' in openssh config to disable rDNS lookups
On each request for a new channel openssh defaults to an
rDNS lookup on the client IP. This can be slow, if it fails
for instance, adding 10s of overhead to every request
for a new channel (not... | Set 'UseDNS no' in openssh config to disable rDNS lookups
On each request for a new channel openssh defaults to an
rDNS lookup on the client IP. This can be slow, if it fails
for instance, adding 10s of overhead to every request
for a new channel (not connection). This can add a lot of
time to a pr... | entailment |
def connect_to_ec2(region, access_key_id, secret_access_key):
""" returns a connection object to AWS EC2 """
conn = boto.ec2.connect_to_region(region,
aws_access_key_id=access_key_id,
aws_secret_access_key=secret_access_key)
return... | returns a connection object to AWS EC2 | entailment |
def connect_to_rackspace(region,
access_key_id,
secret_access_key):
""" returns a connection object to Rackspace """
pyrax.set_setting('identity_type', 'rackspace')
pyrax.set_default_region(region)
pyrax.set_credentials(access_key_id, secret_access_key)... | returns a connection object to Rackspace | entailment |
def create_gce_image(zone,
project,
instance_name,
name,
description):
"""
Shuts down the instance and creates and image from the disk.
Assumes that the disk name is the same as the instance_name (this is the
default be... | Shuts down the instance and creates and image from the disk.
Assumes that the disk name is the same as the instance_name (this is the
default behavior for boot disks on GCE). | entailment |
def create_image(cloud, **kwargs):
""" proxy call for ec2, rackspace create ami backend functions """
if cloud == 'ec2':
return create_ami(**kwargs)
if cloud == 'rackspace':
return create_rackspace_image(**kwargs)
if cloud == 'gce':
return create_gce_image(**kwargs) | proxy call for ec2, rackspace create ami backend functions | entailment |
def create_server(cloud, **kwargs):
"""
Create a new instance
"""
if cloud == 'ec2':
_create_server_ec2(**kwargs)
elif cloud == 'rackspace':
_create_server_rackspace(**kwargs)
elif cloud == 'gce':
_create_server_gce(**kwargs)
else:
raise ValueError("Unknow... | Create a new instance | entailment |
def gce_wait_until_done(operation):
"""
Perform a GCE operation, blocking until the operation completes.
This function will then poll the operation until it reaches state
'DONE' or times out, and then returns the final operation resource
dict.
:param operation: A dict representing a pending GC... | Perform a GCE operation, blocking until the operation completes.
This function will then poll the operation until it reaches state
'DONE' or times out, and then returns the final operation resource
dict.
:param operation: A dict representing a pending GCE operation resource.
:returns dict: A dict... | entailment |
def startup_gce_instance(instance_name, project, zone, username, machine_type,
image, public_key, disk_name=None):
"""
For now, jclouds is broken for GCE and we will have static slaves
in Jenkins. Use this to boot them.
"""
log_green("Started...")
log_yellow("...Creatin... | For now, jclouds is broken for GCE and we will have static slaves
in Jenkins. Use this to boot them. | entailment |
def _create_server_ec2(region,
access_key_id,
secret_access_key,
disk_name,
disk_size,
ami,
key_pair,
instance_type,
username,
... | Creates EC2 Instance and saves it state in a local json file | entailment |
def _create_server_rackspace(region,
access_key_id,
secret_access_key,
disk_name,
disk_size,
ami,
key_pair,
instance_... | Creates Rackspace Instance and saves it state in a local json file | entailment |
def dir_attribs(location, mode=None, owner=None,
group=None, recursive=False, use_sudo=False):
""" cuisine dir_attribs doesn't do sudo, so we implement our own
Updates the mode/owner/group for the given remote directory."""
recursive = recursive and "-R " or ""
if mode:
if us... | cuisine dir_attribs doesn't do sudo, so we implement our own
Updates the mode/owner/group for the given remote directory. | entailment |
def disable_selinux():
""" disables selinux """
if contains(filename='/etc/selinux/config',
text='SELINUX=enforcing'):
sed('/etc/selinux/config',
'SELINUX=enforcing', 'SELINUX=disabled', use_sudo=True)
if contains(filename='/etc/selinux/config',
text='SE... | disables selinux | entailment |
def destroy_ebs_volume(region, volume_id, access_key_id, secret_access_key):
""" destroys an ebs volume """
conn = connect_to_ec2(region, access_key_id, secret_access_key)
if ebs_volume_exists(region, volume_id, access_key_id, secret_access_key):
log_yellow('destroying EBS volume ...')
conn... | destroys an ebs volume | entailment |
def destroy_ec2(region, instance_id, access_key_id, secret_access_key):
""" terminates the instance """
conn = connect_to_ec2(region, access_key_id, secret_access_key)
data = get_ec2_info(instance_id=instance_id,
region=region,
access_key_id=access_key_id,
... | terminates the instance | entailment |
def destroy_rackspace(region, instance_id, access_key_id, secret_access_key):
""" terminates the instance """
nova = connect_to_rackspace(region,
access_key_id,
secret_access_key)
server = nova.servers.get(instance_id)
log_yellow('deleting... | terminates the instance | entailment |
def down_ec2(instance_id, region, access_key_id, secret_access_key):
""" shutdown of an existing EC2 instance """
conn = connect_to_ec2(region, access_key_id, secret_access_key)
# get the instance_id from the state file, and stop the instance
instance = conn.stop_instances(instance_ids=instance_id)[0]
... | shutdown of an existing EC2 instance | entailment |
def ebs_volume_exists(region, volume_id, access_key_id, secret_access_key):
""" finds out if a ebs volume exists """
conn = connect_to_ec2(region, access_key_id, secret_access_key)
for vol in conn.get_all_volumes():
if vol.id == volume_id:
return True | finds out if a ebs volume exists | entailment |
def enable_marathon_basic_authentication(principal, password):
""" configures marathon to start with authentication """
upstart_file = '/etc/init/marathon.conf'
with hide('running', 'stdout'):
sudo('echo -n "{}" > /etc/marathon-mesos.credentials'.format(password))
boot_args = ' '.join(['exec',
... | configures marathon to start with authentication | entailment |
def enable_mesos_basic_authentication(principal, password):
""" enables and adds a new authorized principal """
restart = False
secrets_file = '/etc/mesos/secrets'
secrets_entry = '%s %s' % (principal, password)
if not file_contains(filename=secrets_file,
text=secrets_entry,... | enables and adds a new authorized principal | entailment |
def file_attribs(location, mode=None, owner=None, group=None, sudo=False):
"""Updates the mode/owner/group for the remote file at the given
location."""
return dir_attribs(location, mode, owner, group, False, sudo) | Updates the mode/owner/group for the remote file at the given
location. | entailment |
def get_ec2_info(instance_id,
region,
access_key_id,
secret_access_key,
username):
""" queries EC2 for details about a particular instance_id
"""
conn = connect_to_ec2(region, access_key_id, secret_access_key)
instance = conn.get_only_i... | queries EC2 for details about a particular instance_id | entailment |
def get_ip_address_from_rackspace_server(server_id):
"""
returns an ipaddress for a rackspace instance
"""
nova = connect_to_rackspace()
server = nova.servers.get(server_id)
# the server was assigned IPv4 and IPv6 addresses, locate the IPv4 address
ip_address = None
for network in server... | returns an ipaddress for a rackspace instance | entailment |
def get_rackspace_info(server_id,
region,
access_key_id,
secret_access_key,
username):
""" queries Rackspace for details about a particular server id
"""
nova = connect_to_rackspace(region, access_key_id, secret_acce... | queries Rackspace for details about a particular server id | entailment |
def install_oracle_java(distribution, java_version):
""" installs oracle java """
if 'ubuntu' in distribution:
accept_oracle_license = ('echo '
'oracle-java' + java_version + 'installer '
'shared/accepted-oracle-license-v1-1 '
... | installs oracle java | entailment |
def install_mesos_single_box_mode(distribution):
""" install mesos (all of it) on a single node"""
if 'ubuntu' in distribution:
log_green('adding mesosphere apt-key')
apt_add_key(keyid='E56151BF')
os = lsb_release()
apt_string = 'deb http://repos.mesosphere.io/%s %s main' % (
... | install mesos (all of it) on a single node | entailment |
def insert_line_in_file_after_regex(path, line, after_regex, use_sudo=False):
""" inserts a line in the middle of a file """
tmpfile = str(uuid.uuid4())
get_file(path, tmpfile, use_sudo=use_sudo)
with open(tmpfile) as f:
original = f.read()
if line not in original:
outfile = str(uu... | inserts a line in the middle of a file | entailment |
def install_python_module(name):
""" instals a python module using pip """
with settings(hide('warnings', 'running', 'stdout', 'stderr'),
warn_only=False, capture=True):
run('pip --quiet install %s' % name) | instals a python module using pip | entailment |
def install_python_module_locally(name):
""" instals a python module using pip """
with settings(hide('warnings', 'running', 'stdout', 'stderr'),
warn_only=False, capture=True):
local('pip --quiet install %s' % name) | instals a python module using pip | entailment |
def install_system_gem(gem):
""" install a particular gem """
with settings(hide('warnings', 'running', 'stdout', 'stderr'),
warn_only=False, capture=True):
sudo("gem install %s --no-rdoc --no-ri" % gem) | install a particular gem | entailment |
def is_vagrant_plugin_installed(plugin, use_sudo=False):
""" checks if vagrant plugin is installed """
cmd = 'vagrant plugin list'
if use_sudo:
results = sudo(cmd)
else:
results = run(cmd)
installed_plugins = []
for line in results:
plugin = re.search('^(\S.*) \((.*)\)... | checks if vagrant plugin is installed | entailment |
def is_deb_package_installed(pkg):
""" checks if a particular deb package is installed """
with settings(hide('warnings', 'running', 'stdout', 'stderr'),
warn_only=True, capture=True):
result = sudo('dpkg-query -l "%s" | grep -q ^.i' % pkg)
return not bool(result.return_code) | checks if a particular deb package is installed | entailment |
def is_ssh_available(host, port=22):
""" checks if ssh port is open """
s = socket.socket()
try:
s.connect((host, port))
return True
except:
return False | checks if ssh port is open | entailment |
def os_release(username, ip_address):
""" returns /etc/os-release in a dictionary """
with settings(hide('warnings', 'running', 'stdout', 'stderr'),
warn_only=True, capture=True):
_os_release = {}
with settings(host_string=username + '@' + ip_address):
data = run('... | returns /etc/os-release in a dictionary | entailment |
def load_state_from_disk():
""" loads the state from a local data.json file
"""
if is_there_state():
with open('data.json', 'r') as f:
data = json.load(f)
return data
else:
return False | loads the state from a local data.json file | entailment |
def print_ec2_info(region,
instance_id,
access_key_id,
secret_access_key,
username):
""" outputs information about our EC2 instance """
data = get_ec2_info(instance_id=instance_id,
region=region,
... | outputs information about our EC2 instance | entailment |
def print_gce_info(zone, project, instance_name, data):
""" outputs information about our Rackspace instance """
try:
instance_info = _get_gce_compute().instances().get(
project=project,
zone=zone,
instance=instance_name
).execute()
log_yellow(pformat(... | outputs information about our Rackspace instance | entailment |
def print_rackspace_info(region,
instance_id,
access_key_id,
secret_access_key,
username):
""" outputs information about our Rackspace instance """
data = get_rackspace_info(server_id=instance_id,
... | outputs information about our Rackspace instance | entailment |
def restart_service(service):
""" restarts a service """
with settings(hide('running', 'stdout'), warn_only=True):
log_yellow('stoping service %s' % service)
sudo('service %s stop' % service)
log_yellow('starting service %s' % service)
sudo('service %s start' % service) | restarts a service | entailment |
def rsync():
""" syncs the src code to the remote box """
log_green('syncing code to remote box...')
data = load_state_from_disk()
if 'SOURCE_PATH' in os.environ:
with lcd(os.environ['SOURCE_PATH']):
local("rsync -a "
"--info=progress2 "
"--exclud... | syncs the src code to the remote box | entailment |
def save_ec2_state_locally(instance_id,
region,
username,
access_key_id,
secret_access_key):
""" queries EC2 for details about a particular instance_id and
stores those details locally
"""
# r... | queries EC2 for details about a particular instance_id and
stores those details locally | entailment |
def ssh_session(key_filename,
username,
ip_address,
*cli):
""" opens a ssh shell to the host """
local('ssh -t -i %s %s@%s %s' % (key_filename,
username,
ip_address,
... | opens a ssh shell to the host | entailment |
def up_ec2(region,
access_key_id,
secret_access_key,
instance_id,
username):
""" boots an existing ec2_instance """
conn = connect_to_ec2(region, access_key_id, secret_access_key)
# boot the ec2 instance
instance = conn.start_instances(instance_ids=instance_i... | boots an existing ec2_instance | entailment |
def wait_for_ssh(host, port=22, timeout=600):
""" probes the ssh port and waits until it is available """
log_yellow('waiting for ssh...')
for iteration in xrange(1, timeout): #noqa
sleep(1)
if is_ssh_available(host, port):
return True
else:
log_yellow('waitin... | probes the ssh port and waits until it is available | entailment |
def _get_visuals(user):
"""
Renvoi les éléments graphiques d'un utilisateur.
:param user: Dictionnaire d'infos de l'utilisateur
:return QPixmap,QLabel: Image et nom
"""
pixmap = SuperUserAvatar() if user["status"] == "admin" else UserAvatar()
label = user["label"]
return pixmap, QLabel(... | Renvoi les éléments graphiques d'un utilisateur.
:param user: Dictionnaire d'infos de l'utilisateur
:return QPixmap,QLabel: Image et nom | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.