_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3 values | text stringlengths 75 19.8k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q43300 | Decon.run | train | def run(self):
'''runs 3dDeconvolve through the neural.utils.run shortcut'''
out = nl.run(self.command_list(),products=self.prefix)
if out and out.output:
sds_list = re.findall(r'Stimulus: (.*?) *\n +h\[ 0\] norm\. std\. dev\. = +(\d+\.\d+)',out.output)
self.stim_sds = {}
for s in sds_list:
self.stim_sds[s[0]] = float(s[1]) | python | {
"resource": ""
} |
q43301 | DeconStim.read_file | train | def read_file(self):
'''if this is stored in a file, read it into self.column'''
column_selector = r'(.*)\[(\d+)\]$'
if self.column_file:
column = None
m = re.match(column_selector,self.column_file)
file = self.column_file
if m:
file = m.group(1)
column = int(m.group(2))
with open(file) as f:
lines = f.read().split('\n')
if column!=None:
lines = [x.split()[column] for x in lines]
self.column = [nl.numberize(x) for x in lines]
self.column_file = None
if self.times_file:
with open(self.times_file) as f:
self.times = [[nl.numberize(x) for x in y.split()] for y in f.read().split('\n')]
self.times_file = None | python | {
"resource": ""
} |
q43302 | DeconStim.blank_stim | train | def blank_stim(self,type=None,fill=0):
'''Makes a blank version of stim. If a type is not given, returned as same type as current stim.
If a column stim, will fill in blanks with ``fill``'''
blank = copy.copy(self)
blank.name = 'Blank'
if type==None:
type = self.type()
if type=="column":
num_reps = self.reps
if num_reps==None:
if self.type()=="column":
self.read_file()
num_reps = len(self.column)
else:
nl.notify('Error: requested to return a blank column, but I can\'t figure out how many reps to make it!',level=nl.level.error)
blank.column = [fill]*num_reps
return blank
if type=="times":
blank.times = []
return blank | python | {
"resource": ""
} |
q43303 | DelayedNotification.notify | train | def notify(self):
"""
Calls the notification method
:return: True if the notification method has been called
"""
if self.__method is not None:
self.__method(self.__peer)
return True
return False | python | {
"resource": ""
} |
q43304 | setup | train | def setup(args):
"""Returns the JobManager and sets up the basic infrastructure"""
kwargs = {'wrapper_script' : args.wrapper_script, 'debug' : args.verbose==3, 'database' : args.database}
if args.local:
jm = local.JobManagerLocal(**kwargs)
else:
jm = sge.JobManagerSGE(**kwargs)
# set-up logging
if args.verbose not in range(0,4):
raise ValueError("The verbosity level %d does not exist. Please reduce the number of '--verbose' parameters in your call to maximum 3" % level)
# set up the verbosity level of the logging system
log_level = {
0: logging.ERROR,
1: logging.WARNING,
2: logging.INFO,
3: logging.DEBUG
}[args.verbose]
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s"))
logger.addHandler(handler)
logger.setLevel(log_level)
return jm | python | {
"resource": ""
} |
q43305 | get_memfree | train | def get_memfree(memory, parallel):
"""Computes the memory required for the memfree field."""
number = int(memory.rstrip(string.ascii_letters))
memtype = memory.lstrip(string.digits)
if not memtype:
memtype = "G"
return "%d%s" % (number*parallel, memtype) | python | {
"resource": ""
} |
q43306 | resubmit | train | def resubmit(args):
"""Re-submits the jobs with the given ids."""
jm = setup(args)
kwargs = {
'cwd': True,
'verbosity' : args.verbose
}
if args.qname is not None:
kwargs['queue'] = args.qname
if args.memory is not None:
kwargs['memfree'] = args.memory
if args.qname not in (None, 'all.q'):
kwargs['hvmem'] = args.memory
# if this is a GPU queue and args.memory is provided, we set gpumem flag
# remove 'G' last character from the args.memory string
if args.qname in ('gpu', 'lgpu', 'sgpu', 'gpum') and args.memory is not None:
kwargs['gpumem'] = args.memory
# don't set these for GPU processing or the maximum virtual memroy will be
# set on ulimit
kwargs.pop('memfree', None)
kwargs.pop('hvmem', None)
if args.parallel is not None:
kwargs['pe_opt'] = "pe_mth %d" % args.parallel
kwargs['memfree'] = get_memfree(args.memory, args.parallel)
if args.io_big:
kwargs['io_big'] = True
if args.no_io_big:
kwargs['io_big'] = False
jm.resubmit(get_ids(args.job_ids), args.also_success, args.running_jobs, args.overwrite_command, keep_logs=args.keep_logs, **kwargs) | python | {
"resource": ""
} |
q43307 | run_scheduler | train | def run_scheduler(args):
"""Runs the scheduler on the local machine. To stop it, please use Ctrl-C."""
if not args.local:
raise ValueError("The execute command can only be used with the '--local' command line option")
jm = setup(args)
jm.run_scheduler(parallel_jobs=args.parallel, job_ids=get_ids(args.job_ids), sleep_time=args.sleep_time, die_when_finished=args.die_when_finished, no_log=args.no_log_files, nice=args.nice, verbosity=args.verbose) | python | {
"resource": ""
} |
q43308 | list | train | def list(args):
"""Lists the jobs in the given database."""
jm = setup(args)
jm.list(job_ids=get_ids(args.job_ids), print_array_jobs=args.print_array_jobs, print_dependencies=args.print_dependencies, status=args.status, long=args.long, print_times=args.print_times, ids_only=args.ids_only, names=args.names) | python | {
"resource": ""
} |
q43309 | communicate | train | def communicate(args):
"""Uses qstat to get the status of the requested jobs."""
if args.local:
raise ValueError("The communicate command can only be used without the '--local' command line option")
jm = setup(args)
jm.communicate(job_ids=get_ids(args.job_ids)) | python | {
"resource": ""
} |
q43310 | delete | train | def delete(args):
"""Deletes the jobs from the job manager. If the jobs are still running in the grid, they are stopped."""
jm = setup(args)
# first, stop the jobs if they are running in the grid
if not args.local and 'executing' in args.status:
stop(args)
# then, delete them from the database
jm.delete(job_ids=get_ids(args.job_ids), array_ids=get_ids(args.array_ids), delete_logs=not args.keep_logs, delete_log_dir=not args.keep_log_dir, status=args.status) | python | {
"resource": ""
} |
q43311 | run_job | train | def run_job(args):
"""Starts the wrapper script to execute a job, interpreting the JOB_ID and SGE_TASK_ID keywords that are set by the grid or by us."""
jm = setup(args)
job_id = int(os.environ['JOB_ID'])
array_id = int(os.environ['SGE_TASK_ID']) if os.environ['SGE_TASK_ID'] != 'undefined' else None
jm.run_job(job_id, array_id) | python | {
"resource": ""
} |
q43312 | SoftOptions.with_random_weights | train | def with_random_weights(cls, options):
"""
Initialize from a list of options with random weights.
The weights assigned to each object are uniformally random
integers between ``1`` and ``len(options)``
Args:
options (list): The list of options of any type this object
can return with the ``get()`` method.
Returns:
SoftOptions: A newly constructed instance
"""
return cls([(value, random.randint(1, len(options)))
for value in options]) | python | {
"resource": ""
} |
q43313 | SoftFloat.bounded_uniform | train | def bounded_uniform(cls, lowest, highest, weight_interval=None):
"""
Initialize with a uniform distribution between two values.
If no ``weight_interval`` is passed, this weight distribution
will just consist of ``[(lowest, 1), (highest, 1)]``. If specified,
weights (still with uniform weight distribution) will be added every
``weight_interval``. Use this if you intend to modify the weights
in any complex way after initialization.
Args:
lowest (float or int):
highest (float or int):
weight_interval (int):
Returns:
SoftFloat: A newly constructed instance.
"""
if weight_interval is None:
weights = [(lowest, 1), (highest, 1)]
else:
i = lowest
weights = []
while i < highest:
weights.append((i, 1))
i += weight_interval
weights.append((highest, 1))
return cls(weights) | python | {
"resource": ""
} |
q43314 | SoftColor.get | train | def get(self):
"""
Get an rgb color tuple according to the probability distribution.
Returns:
tuple(int, int, int): A ``(red, green, blue)`` tuple.
Example:
>>> color = SoftColor(([(0, 1), (255, 10)],),
... ([(0, 1), (255, 10)],),
... ([(0, 1), (255, 10)],))
>>> color.get() # doctest: +SKIP
(234, 201, 243)
"""
if isinstance(self.red, SoftInt):
red = self.red.get()
else:
red = self.red
if isinstance(self.green, SoftInt):
green = self.green.get()
else:
green = self.green
if isinstance(self.blue, SoftInt):
blue = self.blue.get()
else:
blue = self.blue
return (red, green, blue) | python | {
"resource": ""
} |
q43315 | grow | train | def grow(files: hug.types.multiple, in_ext: hug.types.text="short", out_ext: hug.types.text="html",
out_dir: hug.types.text="", recursive: hug.types.smart_boolean=False):
"""Grow up your markup"""
if files == ['-']:
print(text(sys.stdin.read()))
return
print(INTRO)
if recursive:
files = iter_source_code(files, in_ext)
for file_name in files:
with open(file_name, 'r') as input_file:
output_file_name = "{0}.{1}".format(os.path.join(out_dir, ".".join(file_name.split('.')[:-1])), out_ext)
with open(output_file_name, 'w') as output_file:
print(" |-> [{2}]: {3} '{0}' -> '{1}' till it's not short...".format(file_name, output_file_name,
'HTML', 'Growing'))
output_file.write(text(input_file.read()))
print(" |")
print(" | >>> Done Growing! :) <<<")
print("") | python | {
"resource": ""
} |
q43316 | read_csv_arg_preprocess | train | def read_csv_arg_preprocess(abspath, memory_usage=100 * 1000 * 1000):
"""Automatically decide if we need to use iterator mode to read a csv file.
:param abspath: csv file absolute path.
:param memory_usage: max memory will be used for pandas.read_csv().
"""
if memory_usage < 1000 * 1000:
raise ValueError("Please specify a valid memory usage for read_csv, "
"the value should larger than 1MB and less than "
"your available memory.")
size = os.path.getsize(abspath) # total size in bytes
n_time = math.ceil(size * 1.0 / memory_usage) # at lease read n times
lines = count_lines(abspath) # total lines
chunksize = math.ceil(lines / n_time) # lines to read each time
if chunksize >= lines:
iterator = False
chunksize = None
else:
iterator = True
return iterator, chunksize | python | {
"resource": ""
} |
q43317 | to_prettytable | train | def to_prettytable(df):
"""Convert DataFrame into ``PrettyTable``.
"""
pt = PrettyTable()
pt.field_names = df.columns
for tp in zip(*(l for col, l in df.iteritems())):
pt.add_row(tp)
return pt | python | {
"resource": ""
} |
q43318 | cli | train | def cli():
"""\
Frogsay generates an ASCII picture of a FROG spouting a FROG tip.
FROG tips are fetched from frog.tips's API endpoint when needed,
otherwise they are cached locally in an application-specific folder.
"""
with open_client(cache_dir=get_cache_dir()) as client:
tip = client.frog_tip()
terminal_width = click.termui.get_terminal_size()[0]
wisdom = make_frog_fresco(tip, width=terminal_width)
click.echo(wisdom) | python | {
"resource": ""
} |
q43319 | parse_spss_headerfile | train | def parse_spss_headerfile(path, **kwargs):
"""
Parse spss header file
Arguments:
path {str} -- path al fichero de cabecera.
leyend_position -- posicion del la leyenda en el header.
"""
headers_clean = {}
try:
with codecs.open(path, 'r', kwargs.get('encoding', 'latin-1')) as file_:
raw_file = file_.read()
raw_splited = exclude_empty_values(raw_file.split('.\r\n'))
# suposse that by default spss leyend is in position 0.
leyend = parse_spss_header_leyend(
raw_leyend=raw_splited.pop(kwargs.get('leyend_position', 0)),
leyend=headers_clean)
if not leyend:
raise Exception('Empty leyend')
# only want VARIABLE(S) LABEL(S) & VALUE(S) LABEL(S)
for label in [x for x in raw_splited if 'label' in x.lower()]:
values = parse_spss_header_labels(
raw_labels=label,
headers=leyend)
except Exception as ex:
logger.error('Fail to parse spss headerfile - {}'.format(ex), header_file=path)
headers_clean = {}
return headers_clean | python | {
"resource": ""
} |
q43320 | parse_spss_datafile | train | def parse_spss_datafile(path, **kwargs):
"""
Parse spss data file
Arguments:
path {str} -- path al fichero de cabecera.
**kwargs {[dict]} -- otros argumentos que puedan llegar
"""
data_clean = []
with codecs.open(path, 'r', kwargs.get('encoding', 'latin-1')) as file_:
raw_file = file_.read()
data_clean = raw_file.split('\r\n')
return exclude_empty_values(data_clean) | python | {
"resource": ""
} |
q43321 | pdf_to_text | train | def pdf_to_text(pdf_filepath='', **kwargs):
"""
Parse pdf to a list of strings using the pdfminer lib.
Args:
no_laparams=False,
all_texts=None,
detect_vertical=None, word_margin=None, char_margin=None,
line_margin=None, boxes_flow=None, codec='utf-8',
strip_control=False, maxpages=0, page_numbers=None, password="",
scale=1.0, rotation=0, layoutmode='normal', debug=False,
disable_caching=False,
"""
result = []
try:
if not os.path.exists(pdf_filepath):
raise ValueError("No valid pdf filepath introduced..")
# TODO: REVIEW THIS PARAMS
# update params if not defined
kwargs['outfp'] = kwargs.get('outfp', StringIO())
kwargs['laparams'] = kwargs.get('laparams', pdfminer.layout.LAParams())
kwargs['imagewriter'] = kwargs.get('imagewriter', None)
kwargs['output_type'] = kwargs.get('output_type', "text")
kwargs['codec'] = kwargs.get('codec', 'utf-8')
kwargs['disable_caching'] = kwargs.get('disable_caching', False)
with open(pdf_filepath, "rb") as f_pdf:
pdfminer.high_level.extract_text_to_fp(f_pdf, **kwargs)
result = kwargs.get('outfp').getvalue()
except Exception:
logger.error('fail pdf to text parsing')
return result | python | {
"resource": ""
} |
q43322 | pdf_row_limiter | train | def pdf_row_limiter(rows, limits=None, **kwargs):
"""
Limit row passing a value. In this case we dont implementate a best effort
algorithm because the posibilities are infite with a data text structure
from a pdf.
"""
limits = limits or [None, None]
upper_limit = limits[0] if limits else None
lower_limit = limits[1] if len(limits) > 1 else None
return rows[upper_limit: lower_limit] | python | {
"resource": ""
} |
q43323 | pdf_to_dict | train | def pdf_to_dict(pdf_filepath, **kwargs):
"""
Main method to parse a pdf file to a dict.
"""
callbacks = {
'pdf_to_text': pdf_to_text,
'pdf_row_format': pdf_row_format,
'pdf_row_limiter': pdf_row_limiter,
'pdf_row_parser': pdf_row_parser,
'pdf_row_cleaner': pdf_row_cleaner
}
callbacks.update(kwargs.get('alt_callbacks', {}))
rows = kwargs.get('rows', [])
if not rows:
# pdf to string
rows_str = callbacks.get('pdf_to_text')(pdf_filepath, **kwargs)
# string to list of rows
rows = callbacks.get('pdf_row_format')(rows_str, **kwargs)
# apply limits
rows = callbacks.get('pdf_row_limiter')(rows, **kwargs)
# Parse data from rows to dict
rows = callbacks.get('pdf_row_parser')(rows, **kwargs)
# apply cleaner
rows = callbacks.get('pdf_row_cleaner')(rows)
return rows | python | {
"resource": ""
} |
q43324 | stashed | train | def stashed(func):
"""
Simple decorator to stash changed files between a destructive repo operation
"""
@functools.wraps(func)
def _wrapper(*args, **kwargs):
if CTX.stash and not CTX.repo.stashed:
CTX.repo.stash(func.__name__)
try:
func(*args, **kwargs)
finally:
CTX.repo.unstash()
else:
func(*args, **kwargs)
return _wrapper | python | {
"resource": ""
} |
q43325 | dynamic_load | train | def dynamic_load(name):
"""Equivalent of "from X import Y" statement using dot notation to specify
what to import and return. For example, foo.bar.thing returns the item
"thing" in the module "foo.bar" """
pieces = name.split('.')
item = pieces[-1]
mod_name = '.'.join(pieces[:-1])
mod = __import__(mod_name, globals(), locals(), [item])
return getattr(mod, item) | python | {
"resource": ""
} |
q43326 | list_to_rows | train | def list_to_rows(src, size):
"""A generator that takes a enumerable item and returns a series of
slices. Useful for turning a list into a series of rows.
>>> list(list_to_rows([1, 2, 3, 4, 5, 6, 7], 3))
[[1, 2, 3], [4, 5, 6], [7, ]]
"""
row = []
for item in src:
row.append(item)
if len(row) == size:
yield row
row = []
if row:
yield row | python | {
"resource": ""
} |
q43327 | head_tail_middle | train | def head_tail_middle(src):
"""Returns a tuple consisting of the head of a enumerable, the middle
as a list and the tail of the enumerable. If the enumerable is 1 item, the
middle will be empty and the tail will be None.
>>> head_tail_middle([1, 2, 3, 4])
1, [2, 3], 4
"""
if len(src) == 0:
return None, [], None
if len(src) == 1:
return src[0], [], None
if len(src) == 2:
return src[0], [], src[1]
return src[0], src[1:-1], src[-1] | python | {
"resource": ""
} |
q43328 | getMetastable | train | def getMetastable(rates, ver: np.ndarray, lamb, br, reactfn: Path):
with h5py.File(reactfn, 'r') as f:
A = f['/metastable/A'][:]
lambnew = f['/metastable/lambda'].value.ravel(order='F') # some are not 1-D!
"""
concatenate along the reaction dimension, axis=-1
"""
vnew = np.concatenate((A[:2] * rates.loc[..., 'no1s'].values[:, None],
A[2:4] * rates.loc[..., 'no1d'].values[:, None],
A[4:] * rates.loc[..., 'noii2p'].values[:, None]), axis=-1)
assert vnew.shape == (rates.shape[0], A.size)
return catvl(rates.alt_km, ver, vnew, lamb, lambnew, br) | python | {
"resource": ""
} |
q43329 | catvl | train | def catvl(z, ver, vnew, lamb, lambnew, br):
"""
trapz integrates over altitude axis, axis = -2
concatenate over reaction dimension, axis = -1
br: column integrated brightness
lamb: wavelength [nm]
ver: volume emission rate [photons / cm^-3 s^-3 ...]
"""
if ver is not None:
br = np.concatenate((br, np.trapz(vnew, z, axis=-2)), axis=-1) # must come first!
ver = np.concatenate((ver, vnew), axis=-1)
lamb = np.concatenate((lamb, lambnew))
else:
ver = vnew.copy(order='F')
lamb = lambnew.copy()
br = np.trapz(ver, z, axis=-2)
return ver, lamb, br | python | {
"resource": ""
} |
q43330 | AwsLogStream.do_tail | train | def do_tail(self,args):
"""Tail the logs"""
response = AwsConnectionFactory.getLogClient().get_log_events(
logGroupName=self.logStream['logGroupName'],
logStreamName=self.logStream['logStreamName'],
limit=10,
startFromHead=False
)
pprint(response) | python | {
"resource": ""
} |
q43331 | get_local_filepath | train | def get_local_filepath(filename):
"""
Helper for finding our raw SQL files locally.
Expects files to be in:
$SOCORRO_PATH/socorrolib/external/postgresql/raw_sql/procs/
"""
procs_dir = os.path.normpath(os.path.join(
__file__,
'../../',
'external/postgresql/raw_sql/procs'
))
return os.path.join(procs_dir, filename) | python | {
"resource": ""
} |
q43332 | load_stored_proc | train | def load_stored_proc(op, filelist):
"""
Takes the alembic op object as arguments and a list of files as arguments
Load and run CREATE OR REPLACE function commands from files
"""
for filename in filelist:
sqlfile = get_local_filepath(filename)
# Capturing "file not exists" here rather than allowing
# an exception to be thrown. Some of the rollback scripts
# would otherwise throw unhelpful exceptions when a SQL
# file is removed from the repo.
if not os.path.isfile(sqlfile):
warnings.warn(
"Did not find %r. Continuing migration." % sqlfile,
UserWarning,
2
)
continue
with open(sqlfile, 'r') as stored_proc:
op.execute(stored_proc.read()) | python | {
"resource": ""
} |
q43333 | get_pathext | train | def get_pathext(default_pathext=None):
"""Returns the path extensions from environment or a default"""
if default_pathext is None:
default_pathext = os.pathsep.join([ '.COM', '.EXE', '.BAT', '.CMD' ])
pathext = os.environ.get('PATHEXT', default_pathext)
return pathext | python | {
"resource": ""
} |
q43334 | ask | train | def ask(message, options):
"""Ask the message interactively, with the given possible responses"""
while 1:
if os.environ.get('PIP_NO_INPUT'):
raise Exception('No input was expected ($PIP_NO_INPUT set); question: %s' % message)
response = raw_input(message)
response = response.strip().lower()
if response not in options:
print('Your response (%r) was not one of the expected responses: %s' % (
response, ', '.join(options)))
else:
return response | python | {
"resource": ""
} |
q43335 | dist_location | train | def dist_location(dist):
"""
Get the site-packages location of this distribution. Generally
this is dist.location, except in the case of develop-installed
packages, where dist.location is the source code location, and we
want to know where the egg-link file is.
"""
egg_link = egg_link_path(dist)
if os.path.exists(egg_link):
return egg_link
return dist.location | python | {
"resource": ""
} |
q43336 | _has_desired_permit | train | def _has_desired_permit(permits, acategory, astatus):
"""
return True if permits has one whose
category_code and status_code match with the given ones
"""
if permits is None:
return False
for permit in permits:
if permit.category_code == acategory and\
permit.status_code == astatus:
return True
return False | python | {
"resource": ""
} |
q43337 | makeRetweetNetwork | train | def makeRetweetNetwork(tweets):
"""Receives tweets, returns directed retweet networks.
Without and with isolated nodes.
"""
G=x.DiGraph()
G_=x.DiGraph()
for tweet in tweets:
text=tweet["text"]
us=tweet["user"]["screen_name"]
if text.startswith("RT @"):
prev_us=text.split(":")[0].split("@")[1]
#print(us,prev_us,text)
if G.has_edge(prev_us,us):
G[prev_us][us]["weight"]+=1
G_[prev_us][us]["weight"]+=1
else:
G.add_edge(prev_us, us, weight=1.)
G_.add_edge(prev_us, us, weight=1.)
if us not in G_.nodes():
G_.add_node(us)
return G,G_ | python | {
"resource": ""
} |
q43338 | GDFgraph.makeNetwork | train | def makeNetwork(self):
"""Makes graph object from .gdf loaded data"""
if "weight" in self.data_friendships.keys():
self.G=G=x.DiGraph()
else:
self.G=G=x.Graph()
F=self.data_friends
for friendn in range(self.n_friends):
if "posts" in F.keys():
G.add_node(F["name"][friendn],
label=F["label"][friendn],
posts=F["posts"][friendn])
elif "agerank" in F.keys():
G.add_node(F["name"][friendn],
label=F["label"][friendn],
gender=F["sex"][friendn],
locale=F["locale"][friendn],
agerank=F["agerank"][friendn])
else:
G.add_node(F["name"][friendn],
label=F["label"][friendn],
gender=F["sex"][friendn],
locale=F["locale"][friendn])
F=self.data_friendships
for friendshipn in range(self.n_friendships):
if "weight" in F.keys():
G.add_edge(F["node1"][friendshipn],F["node2"][friendshipn],weight=F["weight"][friendshipn])
else:
G.add_edge(F["node1"][friendshipn],F["node2"][friendshipn]) | python | {
"resource": ""
} |
q43339 | downlad_file | train | def downlad_file(url, fname):
"""Download file from url and save as fname."""
print("Downloading {} as {}".format(url, fname))
response = urlopen(url)
download = response.read()
with open(fname, 'wb') as fh:
fh.write(download) | python | {
"resource": ""
} |
q43340 | unzip_file | train | def unzip_file(zip_fname):
"""Unzip the zip_fname in the current directory."""
print("Unzipping {}".format(zip_fname))
with zipfile.ZipFile(zip_fname) as zf:
zf.extractall() | python | {
"resource": ""
} |
q43341 | install_from_zip | train | def install_from_zip(url):
"""Download and unzip from url."""
fname = 'tmp.zip'
downlad_file(url, fname)
unzip_file(fname)
print("Removing {}".format(fname))
os.unlink(fname) | python | {
"resource": ""
} |
q43342 | system_status | train | def system_status(): # noqa: E501
"""Retrieve the system status
Retrieve the system status # noqa: E501
:rtype: Response
"""
if(not hasAccess()):
return redirectUnauthorized()
body = State.config.serialize(["driver", "log", "log-file", "log-colorize"])
body.update({'debug': State.options.debug, 'sensitive': State.options.sensitive})
return Response(status=200, body=body) | python | {
"resource": ""
} |
q43343 | ServerCommand.login_server | train | def login_server(self):
"""
Login to server
"""
local('ssh -i {0} {1}@{2}'.format(
env.key_filename, env.user, env.host_string
)) | python | {
"resource": ""
} |
q43344 | Indicator.add_seperator | train | def add_seperator(self):
"""
Add separator between labels in menu that called on right mouse click.
"""
m_item = Gtk.SeparatorMenuItem()
self.menu.append(m_item)
self.menu.show_all() | python | {
"resource": ""
} |
q43345 | Indicator.right_click_event_statusicon | train | def right_click_event_statusicon(self, icon, button, time):
"""
It's just way how popup menu works in GTK. Don't ask me how it works.
"""
def pos(menu, aicon):
"""Just return menu"""
return Gtk.StatusIcon.position_menu(menu, aicon)
self.menu.popup(None, None, pos, icon, button, time) | python | {
"resource": ""
} |
q43346 | Application.tooltip_query | train | def tooltip_query(self, widget, x, y, keyboard_mode, tooltip):
"""
Set tooltip which appears when you hover mouse curson onto icon in system panel.
"""
tooltip.set_text(subprocess.getoutput("acpi"))
return True | python | {
"resource": ""
} |
q43347 | about | train | def about():
"""
About box for aps. Gives version numbers for
aps, NumPy, SciPy, Cython, and MatPlotLib.
"""
print("")
print("aps: APS Journals API in Python for Humans")
print("Copyright (c) 2017 and later.")
print("Xiao Shang")
print("")
print("aps Version: %s" % aps.__version__)
print("Numpy Version: %s" % numpy.__version__)
print("Scipy Version: %s" % scipy.__version__)
try:
import Cython
cython_ver = Cython.__version__
except:
cython_ver = 'None'
print("Cython Version: %s" % cython_ver)
try:
import matplotlib
matplotlib_ver = matplotlib.__version__
except:
matplotlib_ver = 'None'
print("Matplotlib Version: %s" % matplotlib_ver)
print("Python Version: %d.%d.%d" % sys.version_info[0:3])
print("Number of CPUs: %s" % hardware_info()['cpus'])
# print("BLAS Info: %s" % _blas_info())
print("Platform Info: %s (%s)" % (platform.system(),
platform.machine()))
aps_install_path = os.path.dirname(inspect.getsourcefile(aps))
print("Installation path: %s" % aps_install_path)
print("") | python | {
"resource": ""
} |
q43348 | success | train | def success(headers = None, data = ''):
""" Generate success JSON to send to client """
passed_headers = {} if headers is None else headers
if isinstance(data, dict): data = json.dumps(data)
ret_headers = {'status' : 'ok'}
ret_headers.update(passed_headers)
return server_responce(ret_headers, data) | python | {
"resource": ""
} |
q43349 | lock_access | train | def lock_access(repository_path, callback):
""" Synchronise access to the user file between processes, this specifies
which user is allowed write access at the current time """
with open(cpjoin(repository_path, 'lock_file'), 'w') as fd:
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
returned = callback()
fcntl.flock(fd, fcntl.LOCK_UN)
return returned
except IOError:
return fail(lock_fail_msg) | python | {
"resource": ""
} |
q43350 | update_user_lock | train | def update_user_lock(repository_path, session_token):
""" Write or clear the user lock file """ # NOTE ALWAYS use within lock access callback
# While the user lock file should ALWAYS be written only within a lock_access
# callback, it is sometimes read asynchronously. Because of this updates to
# the file must be atomic. Write plus move is used to achieve this.
real_path = cpjoin(repository_path, 'user_file')
tmp_path = cpjoin(repository_path, 'new_user_file')
with open(tmp_path, 'w') as fd2:
if session_token is None: fd2.write('')
else: fd2.write(json.dumps({'session_token' : session_token, 'expires' : int(time.time()) + 30}))
fd2.flush()
os.rename(tmp_path, real_path) | python | {
"resource": ""
} |
q43351 | can_aquire_user_lock | train | def can_aquire_user_lock(repository_path, session_token):
""" Allow a user to acquire the lock if no other user is currently using it, if the original
user is returning, presumably after a network error, or if the lock has expired. """
# NOTE ALWAYS use within lock access callback
user_file_path = cpjoin(repository_path, 'user_file')
if not os.path.isfile(user_file_path): return True
with open(user_file_path, 'r') as fd2:
content = fd2.read()
if len(content) == 0: return True
try: res = json.loads(content)
except ValueError: return True
if res['expires'] < int(time.time()): return True
elif res['session_token'] == session_token: return True
return False | python | {
"resource": ""
} |
q43352 | varify_user_lock | train | def varify_user_lock(repository_path, session_token):
""" Verify that a returning user has a valid token and their lock has not expired """
with open(cpjoin(repository_path, 'user_file'), 'r') as fd2:
content = fd2.read()
if len(content) == 0: return False
try: res = json.loads(content)
except ValueError: return False
return res['session_token'] == session_token and int(time.time()) < int(res['expires'])
return False | python | {
"resource": ""
} |
q43353 | auth_db_connect | train | def auth_db_connect(db_path):
""" An SQLite database is used to store authentication transient data,
this is tokens, strings of random data which are signed by the client,
and session_tokens which identify authenticated users """
def dict_factory(cursor, row): return {col[0] : row[idx] for idx,col in enumerate(cursor.description)}
conn = db.connect(db_path)
conn.row_factory = dict_factory
if not auth_db_connect.init:
conn.execute('create table if not exists tokens (expires int, token text, ip text)')
conn.execute('create table if not exists session_tokens (expires int, token text, ip text, username text)')
auth_db_connect.init = True
return conn | python | {
"resource": ""
} |
q43354 | begin_auth | train | def begin_auth():
""" Request authentication token to sign """
repository = request.headers['repository']
if repository not in config['repositories']: return fail(no_such_repo_msg)
# ==
repository_path = config['repositories'][repository]['path']
conn = auth_db_connect(cpjoin(repository_path, 'auth_transient.db')); gc_tokens(conn)
# Issue a new token
auth_token = base64.b64encode(pysodium.randombytes(35)).decode('utf-8')
conn.execute("insert into tokens (expires, token, ip) values (?,?,?)",
(time.time() + 30, auth_token, request.environ['REMOTE_ADDR']))
conn.commit()
return success({'auth_token' : auth_token}) | python | {
"resource": ""
} |
q43355 | authenticate | train | def authenticate():
""" This does two things, either validate a pre-existing session token
or create a new one from a signed authentication token. """
client_ip = request.environ['REMOTE_ADDR']
repository = request.headers['repository']
if repository not in config['repositories']: return fail(no_such_repo_msg)
# ==
repository_path = config['repositories'][repository]['path']
conn = auth_db_connect(cpjoin(repository_path, 'auth_transient.db')); gc_tokens(conn)
gc_tokens(conn)
# Allow resume of an existing session
if 'session_token' in request.headers:
session_token = request.headers['session_token']
conn.execute("delete from session_tokens where expires < ?", (time.time(),)); conn.commit()
res = conn.execute("select * from session_tokens where token = ? and ip = ?", (session_token, client_ip)).fetchall()
if res != []: return success({'session_token' : session_token})
else: return fail(user_auth_fail_msg)
# Create a new session
else:
user = request.headers['user']
auth_token = request.headers['auth_token']
signiture = request.headers['signature']
try:
public_key = config['users'][user]['public_key']
# signature
pysodium.crypto_sign_verify_detached(base64.b64decode(signiture), auth_token, base64.b64decode(public_key))
# check token was previously issued by this system and is still valid
res = conn.execute("select * from tokens where token = ? and ip = ? ", (auth_token, client_ip)).fetchall()
# Validate token matches one we sent
if res == [] or len(res) > 1: return fail(user_auth_fail_msg)
# Does the user have permission to use this repository?
if repository not in config['users'][user]['uses_repositories']: return fail(user_auth_fail_msg)
# Everything OK
conn.execute("delete from tokens where token = ?", (auth_token,)); conn.commit()
# generate a session token and send it to the client
session_token = base64.b64encode(pysodium.randombytes(35))
conn.execute("insert into session_tokens (token, expires, ip, username) values (?,?,?, ?)",
(session_token, time.time() + extend_session_duration, client_ip, user))
conn.commit()
return success({'session_token' : session_token})
except Exception: # pylint: disable=broad-except
return fail(user_auth_fail_msg) | python | {
"resource": ""
} |
q43356 | have_authenticated_user | train | def have_authenticated_user(client_ip, repository, session_token):
""" check user submitted session token against the db and that ip has not changed """
if repository not in config['repositories']: return False
repository_path = config['repositories'][repository]['path']
conn = auth_db_connect(cpjoin(repository_path, 'auth_transient.db'))
# Garbage collect session tokens. We must not garbage collect the authentication token of the client
# which is currently doing a commit. Large files can take a long time to upload and during this time,
# the locks expiration is not being updated thus can expire. This is a problem here as session tokens
# table is garbage collected every time a user authenticates. It does not matter if the user_lock
# expires while the client also holds the flock, as it is updated to be in the future at the end of
# the current operation. We exclude any tokens owned by the client which currently owns the user
# lock for this reason.
user_lock = read_user_lock(repository_path)
active_commit = user_lock['session_token'] if user_lock != None else None
if active_commit != None: conn.execute("delete from session_tokens where expires < ? and token != ?", (time.time(), active_commit))
else: conn.execute("delete from session_tokens where expires < ?", (time.time(),))
# Get the session token
res = conn.execute("select * from session_tokens where token = ? and ip = ?", (session_token, client_ip)).fetchall()
if res != [] and repository in config['users'][res[0]['username']]['uses_repositories']:
conn.execute("update session_tokens set expires = ? where token = ? and ip = ?",
(time.time() + extend_session_duration, session_token, client_ip))
conn.commit() # to make sure the update and delete have the same view
return res[0]
conn.commit()
return False | python | {
"resource": ""
} |
q43357 | find_changed | train | def find_changed():
""" Find changes since the revision it is currently holding """
session_token = request.headers['session_token']
repository = request.headers['repository']
#===
current_user = have_authenticated_user(request.environ['REMOTE_ADDR'], repository, session_token)
if current_user is False: return fail(user_auth_fail_msg)
#===
repository_path = config['repositories'][repository]['path']
body_data = request.get_json()
#===
data_store = versioned_storage(repository_path)
head = data_store.get_head()
if head == 'root': return success({}, {'head' : 'root', 'sorted_changes' : {'none' : []}})
# Find changed items
client_changes = json.loads(body_data['client_changes'])
server_changes = data_store.get_changes_since(request.headers["previous_revision"], head)
# Resolve conflicts
conflict_resolutions = json.loads(body_data['conflict_resolutions'])
if conflict_resolutions != []:
resolutions = {'server' : {},'client' : {}}
for r in conflict_resolutions:
if len(r['4_resolution']) != 1 or r['4_resolution'][0] not in ['client', 'server']: return fail(conflict_msg)
resolutions[r['4_resolution'][0]][r['1_path']] = None
client_changes = {k : v for k,v in client_changes.iteritems() if v['path'] not in resolutions['server']}
server_changes = {k : v for k,v in server_changes.iteritems() if v['path'] not in resolutions['client']}
sorted_changes = merge_client_and_server_changes(server_changes, client_changes)
return success({}, {'head' : head, 'sorted_changes': sorted_changes}) | python | {
"resource": ""
} |
q43358 | pull_file | train | def pull_file():
""" Get a file from the server """
session_token = request.headers['session_token']
repository = request.headers['repository']
#===
current_user = have_authenticated_user(request.environ['REMOTE_ADDR'], repository, session_token)
if current_user is False: return fail(user_auth_fail_msg)
#===
data_store = versioned_storage(config['repositories'][repository]['path'])
file_info = data_store.get_file_info_from_path(request.headers['path'])
return success({'file_info_json' : json.dumps(file_info)},
send_from_directory(data_store.get_file_directory_path(file_info['hash']), file_info['hash'][2:])) | python | {
"resource": ""
} |
q43359 | begin_commit | train | def begin_commit():
""" Allow a client to begin a commit and acquire the write lock """
session_token = request.headers['session_token']
repository = request.headers['repository']
#===
current_user = have_authenticated_user(request.environ['REMOTE_ADDR'], repository, session_token)
if current_user is False: return fail(user_auth_fail_msg)
#===
repository_path = config['repositories'][repository]['path']
def with_exclusive_lock():
# The commit is locked for a given time period to a given session token,
# a client must hold this lock to use any of push_file(), delete_files() and commit().
# It does not matter if the user lock technically expires while a client is writing
# a large file, as the user lock is locked using flock for the duration of any
# operation and thus cannot be stolen by another client. It is updated to be in
# the future before returning to the client. The lock only needs to survive until
# the client owning the lock sends another request and re acquires the flock.
if not can_aquire_user_lock(repository_path, session_token): return fail(lock_fail_msg)
# Commits can only take place if the committing user has the latest revision,
# as committing from an outdated state could cause unexpected results, and may
# have conflicts. Conflicts are resolved during a client update so they are
# handled by the client, and a server interface for this is not needed.
data_store = versioned_storage(repository_path)
if data_store.get_head() != request.headers["previous_revision"]: return fail(need_to_update_msg)
# Should the lock expire, the client which had the lock previously will be unable
# to continue the commit it had in progress. When this, or another client attempts
# to commit again it must do so by first obtaining the lock again by calling begin_commit().
# Any remaining commit data from failed prior commits is garbage collected here.
# While it would technically be possible to implement commit resume should the same
# client resume, I only see commits failing due to a network error and this is so
# rare I don't think it's worth the trouble.
if data_store.have_active_commit(): data_store.rollback()
#------------
data_store.begin()
update_user_lock(repository_path, session_token)
return success()
return lock_access(repository_path, with_exclusive_lock) | python | {
"resource": ""
} |
q43360 | push_file | train | def push_file():
""" Push a file to the server """ #NOTE beware that reading post data in flask causes hang until file upload is complete
session_token = request.headers['session_token']
repository = request.headers['repository']
#===
current_user = have_authenticated_user(request.environ['REMOTE_ADDR'], repository, session_token)
if current_user is False: return fail(user_auth_fail_msg)
#===
repository_path = config['repositories'][repository]['path']
def with_exclusive_lock():
if not varify_user_lock(repository_path, session_token): return fail(lock_fail_msg)
#===
data_store = versioned_storage(repository_path)
if not data_store.have_active_commit(): return fail(no_active_commit_msg)
# There is no valid reason for path traversal characters to be in a file path within this system
file_path = request.headers['path']
if any(True for item in re.split(r'\\|/', file_path) if item in ['..', '.']): return fail()
#===
tmp_path = cpjoin(repository_path, 'tmp_file')
with open(tmp_path, 'wb') as f:
while True:
chunk = request.stream.read(1000 * 1000)
if chunk == b'': break
f.write(chunk)
#===
data_store.fs_put_from_file(tmp_path, {'path' : file_path})
# updates the user lock expiry
update_user_lock(repository_path, session_token)
return success()
return lock_access(repository_path, with_exclusive_lock) | python | {
"resource": ""
} |
q43361 | delete_files | train | def delete_files():
""" Delete one or more files from the server """
session_token = request.headers['session_token']
repository = request.headers['repository']
#===
current_user = have_authenticated_user(request.environ['REMOTE_ADDR'], repository, session_token)
if current_user is False: return fail(user_auth_fail_msg)
#===
repository_path = config['repositories'][repository]['path']
body_data = request.get_json()
def with_exclusive_lock():
if not varify_user_lock(repository_path, session_token): return fail(lock_fail_msg)
try:
data_store = versioned_storage(repository_path)
if not data_store.have_active_commit(): return fail(no_active_commit_msg)
#-------------
for fle in json.loads(body_data['files']):
data_store.fs_delete(fle)
# updates the user lock expiry
update_user_lock(repository_path, session_token)
return success()
except Exception: return fail() # pylint: disable=broad-except
return lock_access(repository_path, with_exclusive_lock) | python | {
"resource": ""
} |
q43362 | commit | train | def commit():
""" Commit changes and release the write lock """
session_token = request.headers['session_token']
repository = request.headers['repository']
#===
current_user = have_authenticated_user(request.environ['REMOTE_ADDR'], repository, session_token)
if current_user is False: return fail(user_auth_fail_msg)
#===
repository_path = config['repositories'][repository]['path']
def with_exclusive_lock():
if not varify_user_lock(repository_path, session_token): return fail(lock_fail_msg)
#===
data_store = versioned_storage(repository_path)
if not data_store.have_active_commit(): return fail(no_active_commit_msg)
result = {}
if request.headers['mode'] == 'commit':
new_head = data_store.commit(request.headers['commit_message'], current_user['username'])
result = {'head' : new_head}
else:
data_store.rollback()
# Release the user lock
update_user_lock(repository_path, None)
return success(result)
return lock_access(repository_path, with_exclusive_lock) | python | {
"resource": ""
} |
q43363 | APIModel.get_annotation | train | def get_annotation(self, key, result_format='list'):
"""
Is a convenience method for accessing annotations on models that have them
"""
value = self.get('_annotations_by_key', {}).get(key)
if not value:
return value
if result_format == 'one':
return value[0]
return value | python | {
"resource": ""
} |
q43364 | User.update_user | train | def update_user(self):
"""
Save the state of the current user
"""
# First create a copy of the current user
user_dict = self.serialize()
# Then delete the entities in the description field
del user_dict['description']['entities']
# Then upload user_dict
user, meta = self._api.update_user('me', data=user_dict) | python | {
"resource": ""
} |
q43365 | _Constant.Subclasses | train | def Subclasses(cls, sort_by=None, reverse=False):
"""Get all nested Constant class and it's name pair.
:param sort_by: the attribute name used for sorting.
:param reverse: if True, return in descend order.
:returns: [(attr, value),...] pairs.
::
>>> class MyClass(Constant):
... a = 1 # non-class attributre
... b = 2 # non-class attributre
...
... class C(Constant):
... pass
...
... class D(Constant):
... pass
>>> MyClass.Subclasses()
[("C", MyClass.C), ("D", MyClass.D)]
.. versionadded:: 0.0.3
"""
l = list()
for attr, value in get_all_attributes(cls):
try:
if issubclass(value, Constant):
l.append((attr, value))
except:
pass
if sort_by is None:
sort_by = "__creation_index__"
l = list(
sorted(l, key=lambda x: getattr(x[1], sort_by), reverse=reverse))
return l | python | {
"resource": ""
} |
q43366 | _Constant.subclasses | train | def subclasses(self, sort_by=None, reverse=False):
"""Get all nested Constant class instance and it's name pair.
:param sort_by: the attribute name used for sorting.
:param reverse: if True, return in descend order.
:returns: [(attr, value),...] pairs.
::
>>> class MyClass(Constant):
... a = 1 # non-class attributre
... b = 2 # non-class attributre
...
... class C(Constant):
... pass
...
... class D(Constant):
... pass
>>> my_class = MyClass()
>>> my_class.subclasses()
[("C", my_class.C), ("D", my_class.D)]
.. versionadded:: 0.0.4
"""
l = list()
for attr, _ in self.Subclasses(sort_by, reverse):
value = getattr(self, attr)
l.append((attr, value))
return l | python | {
"resource": ""
} |
q43367 | _Constant.BackAssign | train | def BackAssign(cls,
other_entity_klass,
this_entity_backpopulate_field,
other_entity_backpopulate_field,
is_many_to_one=False):
"""
Assign defined one side mapping relationship to other side.
For example, each employee belongs to one department, then one department
includes many employees. If you defined each employee's department,
this method will assign employees to ``Department.employees`` field.
This is an one to many (department to employee) example.
Another example would be, each employee has multiple tags. If you defined
tags for each employee, this method will assign employees to
``Tag.employees`` field. This is and many to many (employee to tag) example.
Support:
- many to many mapping
- one to many mapping
:param other_entity_klass: a :class:`Constant` class.
:param this_entity_backpopulate_field: str
:param other_entity_backpopulate_field: str
:param is_many_to_one: bool
:return:
"""
data = dict()
for _, other_klass in other_entity_klass.Subclasses():
other_field_value = getattr(
other_klass, this_entity_backpopulate_field)
if isinstance(other_field_value, (tuple, list)):
for self_klass in other_field_value:
self_key = self_klass.__name__
try:
data[self_key].append(other_klass)
except KeyError:
data[self_key] = [other_klass, ]
else:
if other_field_value is not None:
self_klass = other_field_value
self_key = self_klass.__name__
try:
data[self_key].append(other_klass)
except KeyError:
data[self_key] = [other_klass, ]
if is_many_to_one:
new_data = dict()
for key, value in data.items():
try:
new_data[key] = value[0]
except: # pragma: no cover
pass
data = new_data
for self_key, other_klass_list in data.items():
setattr(getattr(cls, self_key),
other_entity_backpopulate_field, other_klass_list) | python | {
"resource": ""
} |
q43368 | _Constant.dump | train | def dump(cls):
"""Dump data into a dict.
.. versionadded:: 0.0.2
"""
d = OrderedDict(cls.Items())
d["__classname__"] = cls.__name__
for attr, klass in cls.Subclasses():
d[attr] = klass.dump()
return OrderedDict([(cls.__name__, d)]) | python | {
"resource": ""
} |
q43369 | _Constant.load | train | def load(cls, data):
"""Construct a Constant class from it's dict data.
.. versionadded:: 0.0.2
"""
if len(data) == 1:
for key, value in data.items():
if "__classname__" not in value: # pragma: no cover
raise ValueError
name = key
bases = (Constant,)
attrs = dict()
for k, v in value.items():
if isinstance(v, dict):
if "__classname__" in v:
attrs[k] = cls.load({k: v})
else:
attrs[k] = v
else:
attrs[k] = v
return type(name, bases, attrs)
else: # pragma: no cover
raise ValueError | python | {
"resource": ""
} |
q43370 | api | train | def api(feature='conditions', city='Portland', state='OR', key=None):
"""Use the wunderground API to get current conditions instead of scraping
Please be kind and use your own key (they're FREE!):
http://www.wunderground.com/weather/api/d/login.html
References:
http://www.wunderground.com/weather/api/d/terms.html
Examples:
>>> api('hurric', 'Boise', 'ID') # doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS
{u'currenthurricane': ...}}}
>>> features = ('alerts astronomy conditions currenthurricane forecast forecast10day geolookup history hourly hourly10day ' +
... 'planner rawtide satellite tide webcams yesterday').split(' ')
>> everything = [api(f, 'Portland') for f in features]
>> js = api('alerts', 'Portland', 'OR')
>> js = api('condit', 'Sacramento', 'CA')
>> js = api('forecast', 'Mobile', 'AL')
>> js = api('10day', 'Fairhope', 'AL')
>> js = api('geo', 'Decatur', 'AL')
>> js = api('hist', 'history', 'AL')
>> js = api('astro')
"""
features = ('alerts astronomy conditions currenthurricane forecast forecast10day geolookup history hourly hourly10day ' +
'planner rawtide satellite tide webcams yesterday').split(' ')
feature = util.fuzzy_get(features, feature)
# Please be kind and use your own key (they're FREE!):
# http://www.wunderground.com/weather/api/d/login.html
key = key or env.get('WUNDERGROUND', None, verbosity=-1) or env.get('WUNDERGROUND_KEY', 'c45a86c2fc63f7d0', verbosity=-1)
url = 'http://api.wunderground.com/api/{key}/{feature}/q/{state}/{city}.json'.format(
key=key, feature=feature, state=state, city=city)
return json.load(urllib.urlopen(url)) | python | {
"resource": ""
} |
q43371 | GradleBuild.ensure_cache_folder | train | def ensure_cache_folder(self):
"""
Creates a gradle cache folder if it does not exist.
"""
if os.path.exists(self.cache_folder) is False:
os.makedirs(self.cache_folder) | python | {
"resource": ""
} |
q43372 | GradleBuild.is_app_folder | train | def is_app_folder(self, folder):
"""
checks if a folder
"""
with open('%s/%s/build.gradle' % (self.path, folder)) as f:
for line in f.readlines():
if config.gradle_plugin in line:
return True
return False | python | {
"resource": ""
} |
q43373 | GradleBuild.get_src_folder | train | def get_src_folder(self):
"""
Gets the app source folder from settings.gradle file.
Returns:
A string containing the project source folder name (default is "app")
"""
with open('%s/settings.gradle' % self.path) as f:
for line in f.readlines():
if line.startswith('include'):
matches = re.findall(r'\'\:?(.+?)\'', line)
if len(matches) == 0:
continue
for folder in matches:
if self.is_app_folder(folder):
return folder
return 'app' | python | {
"resource": ""
} |
q43374 | GradleBuild.get_build_tool_version | train | def get_build_tool_version(self):
"""
Gets the build tool version to be used by zipalign from build.gradle file.
Returns:
A string containing the build tool version, default is 23.0.2.
"""
with open('%s/%s/build.gradle' % (self.path, self.src_folder)) as f:
for line in f.readlines():
if 'buildToolsVersion' in line:
matches = re.findall(r'buildToolsVersion \"(.+?)\"', line)
if len(matches) == 1:
return matches[0]
return config.build_tool_version | python | {
"resource": ""
} |
q43375 | GradleBuild.validate | train | def validate(self):
"""
Validates the app project before the build.
This is the first step in the build process.
Needs to be implemented by the subclass.
"""
if os.path.exists('%s/gradlew' % self.path) is False:
raise errors.InvalidProjectStructure(message='Missing gradlew project root folder')
self.touch_log('validate') | python | {
"resource": ""
} |
q43376 | GradleBuild.build | train | def build(self, mode='debug'):
"""
Builds the app project after the execution of validate and prepare.
This is the third and last step in the build process.
Needs to be implemented by the subclass.
"""
self.ensure_cache_folder()
ref = {
'debug': 'assembleDebug',
'release': 'assembleRelease'
}
cmd = [
'./gradlew',
ref.get(mode, mode),
'--gradle-user-home',
self.cache_folder
]
self.run_cmd(cmd, 'build') | python | {
"resource": ""
} |
q43377 | excel_to_sql | train | def excel_to_sql(excel_file_path, engine,
read_excel_kwargs=None,
to_generic_type_kwargs=None,
to_sql_kwargs=None):
"""Create a database from excel.
:param read_excel_kwargs: dict, arguments for ``pandas.read_excel`` method.
example: ``{"employee": {"skiprows": 10}, "department": {}}``
:param to_sql_kwargs: dict, arguments for ``pandas.DataFrame.to_sql``
method.
limitation:
1. If a integer column has None value, data type in database will be float.
Because pandas thinks that it is ``np.nan``.
2. If a string column looks like integer, ``pandas.read_excel()`` method
doesn't have options to convert it to string.
"""
if read_excel_kwargs is None:
read_excel_kwargs = dict()
if to_sql_kwargs is None:
to_sql_kwargs = dict()
if to_generic_type_kwargs is None:
to_generic_type_kwargs = dict()
xl = pd.ExcelFile(excel_file_path)
for sheet_name in xl.sheet_names:
df = pd.read_excel(
excel_file_path, sheet_name,
**read_excel_kwargs.get(sheet_name, dict())
)
kwargs = to_generic_type_kwargs.get(sheet_name)
if kwargs:
data = to_dict_list_generic_type(df, **kwargs)
smart_insert(data, sheet_name, engine)
else:
df.to_sql(
sheet_name, engine, index=False,
**to_sql_kwargs.get(sheet_name, dict(if_exists="replace"))
) | python | {
"resource": ""
} |
q43378 | database_to_excel | train | def database_to_excel(engine, excel_file_path):
"""Export database to excel.
:param engine:
:param excel_file_path:
"""
from sqlalchemy import MetaData, select
metadata = MetaData()
metadata.reflect(engine)
writer = pd.ExcelWriter(excel_file_path)
for table in metadata.tables.values():
sql = select([table])
df = pd.read_sql(sql, engine)
df.to_excel(writer, table.name, index=False)
writer.save() | python | {
"resource": ""
} |
q43379 | requirements | train | def requirements(requirements_file):
"""Return packages mentioned in the given file.
Args:
requirements_file (str): path to the requirements file to be parsed.
Returns:
(list): 3rd-party package dependencies contained in the file.
"""
return [
str(pkg.req) for pkg in parse_requirements(
requirements_file, session=pip_download.PipSession()) if pkg.req is not None] | python | {
"resource": ""
} |
q43380 | RepoState.HeadList | train | def HeadList(self):
"""Return a list of all the currently loaded repo HEAD objects."""
return [(rname, repo.currenthead) for rname, repo in self.repos.items()
] | python | {
"resource": ""
} |
q43381 | GitRepo.setorigin | train | def setorigin(self):
"""Set the 'origin' remote to the upstream url that we trust."""
try:
origin = self.repo.remotes.origin
if origin.url != self.origin_url:
log.debug('[%s] Changing origin url. Old: %s New: %s',
self.name, origin.url, self.origin_url)
origin.config_writer.set('url', self.origin_url)
except AttributeError:
origin = self.repo.create_remote('origin', self.origin_url)
log.debug('[%s] Created remote "origin" with URL: %s',
self.name, origin.url) | python | {
"resource": ""
} |
q43382 | GitRepo.fetchall | train | def fetchall(self):
"""Fetch all refs from the upstream repo."""
try:
self.repo.remotes.origin.fetch()
except git.exc.GitCommandError as err:
raise GitError(err) | python | {
"resource": ""
} |
q43383 | GitRepo.fetchref | train | def fetchref(self, ref):
"""Fetch a particular git ref."""
log.debug('[%s] Fetching ref: %s', self.name, ref)
fetch_info = self.repo.remotes.origin.fetch(ref).pop()
return fetch_info.ref | python | {
"resource": ""
} |
q43384 | GitRepo.sethead | train | def sethead(self, ref):
"""Set head to a git ref."""
log.debug('[%s] Setting to ref %s', self.name, ref)
try:
ref = self.repo.rev_parse(ref)
except gitdb.exc.BadObject:
# Probably means we don't have it cached yet.
# So maybe we can fetch it.
ref = self.fetchref(ref)
log.debug('[%s] Setting head to %s', self.name, ref)
self.repo.head.reset(ref, working_tree=True)
log.debug('[%s] Head object: %s', self.name, self.currenthead) | python | {
"resource": ""
} |
q43385 | GitRepo.get_file | train | def get_file(self, filename):
"""Get a file from the repo.
Returns a file-like stream with the data.
"""
log.debug('[%s]: reading: //%s/%s', self.name, self.name, filename)
try:
blob = self.repo.head.commit.tree/filename
return blob.data_stream
except KeyError as err:
raise GitError(err) | python | {
"resource": ""
} |
q43386 | create | train | def create(app_id: int = None,
login: str = None,
password: str = None,
service_token: str = None,
proxies: dict = None) -> API:
"""
Creates an API instance, requires app ID,
login and password or service token to create connection
:param app_id: int: specifies app ID
:param login: str: specifies login, can be phone number or email
:param password: str: specifies password
:param service_token: str: specifies password service token
:param proxies: dict: specifies proxies, require http and https proxy
"""
session_ = APISession(app_id,
login,
password,
service_token,
proxies)
return API(session_) | python | {
"resource": ""
} |
q43387 | user_homedir | train | def user_homedir(username=None):
"""Returns a user's home directory.
If no username is specified, returns the current user's homedir.
"""
if username:
return os.path.expanduser('~%s/' % username)
elif 'HOME' in os.environ:
return os.environ['HOME']
elif os.name == 'posix':
return os.path.expanduser('~/')
else:
raise RuntimeError('This function has failed at life.') | python | {
"resource": ""
} |
q43388 | hash_stream | train | def hash_stream(fileobj, hasher=None, blocksize=65536):
"""Read from fileobj stream, return hash of its contents.
Args:
fileobj: File-like object with read()
hasher: Hash object such as hashlib.sha1(). Defaults to sha1.
blocksize: Read from fileobj this many bytes at a time.
"""
hasher = hasher or hashlib.sha1()
buf = fileobj.read(blocksize)
while buf:
hasher.update(buf)
buf = fileobj.read(blocksize)
return hasher | python | {
"resource": ""
} |
q43389 | hash_str | train | def hash_str(data, hasher=None):
"""Checksum hash a string."""
hasher = hasher or hashlib.sha1()
hasher.update(data)
return hasher | python | {
"resource": ""
} |
q43390 | glob | train | def glob(*args):
"""Returns list of paths matching one or more wildcard patterns.
Args:
include_dirs: Include directories in the output
"""
if len(args) is 1 and isinstance(args[0], list):
args = args[0]
matches = []
for pattern in args:
for item in glob2.glob(pattern):
if not os.path.isdir(item):
matches.append(item)
return matches | python | {
"resource": ""
} |
q43391 | flatten | train | def flatten(listish):
"""Flatten an arbitrarily-nested list of strings and lists.
Works for any subclass of basestring and any type of iterable.
"""
for elem in listish:
if (isinstance(elem, collections.Iterable)
and not isinstance(elem, basestring)):
for subelem in flatten(elem):
yield subelem
else:
yield elem | python | {
"resource": ""
} |
q43392 | linkorcopy | train | def linkorcopy(src, dst):
"""Hardlink src file to dst if possible, otherwise copy."""
if not os.path.isfile(src):
raise error.ButcherError('linkorcopy called with non-file source. '
'(src: %s dst: %s)' % src, dst)
elif os.path.isdir(dst):
dst = os.path.join(dst, os.path.basename(src))
elif os.path.exists(dst):
os.unlink(dst)
elif not os.path.exists(os.path.dirname(dst)):
os.makedirs(os.path.dirname(dst))
try:
os.link(src, dst)
log.debug('Hardlinked: %s -> %s', src, dst)
except OSError:
shutil.copy2(src, dst)
log.debug('Couldn\'t hardlink. Copied: %s -> %s', src, dst) | python | {
"resource": ""
} |
q43393 | Dir.getcwd | train | def getcwd(cls):
"""
Provide a context dependent current working directory. This method
will return the directory currently holding the lock.
"""
if not hasattr(cls._tl, "cwd"):
cls._tl.cwd = os.getcwd()
return cls._tl.cwd | python | {
"resource": ""
} |
q43394 | Dataset.fname | train | def fname(self, version=None, tags=None, ext=None):
"""Returns the filename appropriate for an instance of this dataset.
Parameters
----------
version: str, optional
The version of the instance of this dataset.
tags : list of str, optional
The tags associated with the instance of this dataset.
ext : str, optional
The file extension to use. If not given, the default extension is
used.
Returns
-------
str
The appropariate filename.
"""
if ext is None:
ext = self.default_ext
return '{}{}{}.{}'.format(
self.fname_base,
self._tags_to_str(tags=tags),
self._version_to_str(version=version),
ext,
) | python | {
"resource": ""
} |
q43395 | Dataset.fpath | train | def fpath(self, version=None, tags=None, ext=None):
"""Returns the filepath appropriate for an instance of this dataset.
Parameters
----------
version: str, optional
The version of the instance of this dataset.
tags : list of str, optional
The tags associated with the given instance of this dataset.
ext : str, optional
The file extension to use. If not given, the default extension is
used.
Returns
-------
str
The appropariate filepath.
"""
if self.singleton:
return dataset_filepath(
filename=self.fname(version=version, tags=tags, ext=ext),
task=self.task,
**self.kwargs,
)
return dataset_filepath(
filename=self.fname(version=version, tags=tags, ext=ext),
dataset_name=self.name,
task=self.task,
**self.kwargs,
) | python | {
"resource": ""
} |
q43396 | Dataset.add_local | train | def add_local(self, source_fpath, version=None, tags=None):
"""Copies a given file into local store as an instance of this dataset.
Parameters
----------
source_fpath : str
The full path for the source file to use.
version: str, optional
The version of the instance of this dataset.
tags : list of str, optional
The tags associated with the given instance of this dataset.
Returns
-------
ext : str
The extension of the file added.
"""
ext = os.path.splitext(source_fpath)[1]
ext = ext[1:] # we dont need the dot
fpath = self.fpath(version=version, tags=tags, ext=ext)
shutil.copyfile(src=source_fpath, dst=fpath)
return ext | python | {
"resource": ""
} |
q43397 | Dataset.upload | train | def upload(self, version=None, tags=None, ext=None, source_fpath=None,
overwrite=False, **kwargs):
"""Uploads the given instance of this dataset to dataset store.
Parameters
----------
version: str, optional
The version of the instance of this dataset.
tags : list of str, optional
The tags associated with the given instance of this dataset.
ext : str, optional
The file extension to use. If not given, the default extension is
used. If source_fpath is given, this is ignored, and the extension
of the source f
source_fpath : str, optional
The full path for the source file to use. If given, the file is
copied from the given path to the local storage path before
uploading.
**kwargs : extra keyword arguments
Extra keyword arguments are forwarded to
azure.storage.blob.BlockBlobService.create_blob_from_path.
"""
if source_fpath:
ext = self.add_local(
source_fpath=source_fpath, version=version, tags=tags)
if ext is None:
ext = self._find_extension(version=version, tags=tags)
if ext is None:
attribs = "{}{}".format(
"version={} and ".format(version) if version else "",
"tags={}".format(tags) if tags else "",
)
raise MissingDatasetError(
"No dataset with {} in local store!".format(attribs))
fpath = self.fpath(version=version, tags=tags, ext=ext)
if not os.path.isfile(fpath):
attribs = "{}{}ext={}".format(
"version={} and ".format(version) if version else "",
"tags={} and ".format(tags) if tags else "",
ext,
)
raise MissingDatasetError(
"No dataset with {} in local store! (path={})".format(
attribs, fpath))
upload_dataset(
dataset_name=self.name,
file_path=fpath,
task=self.task,
dataset_attributes=self.kwargs,
**kwargs,
) | python | {
"resource": ""
} |
q43398 | Dataset.download | train | def download(self, version=None, tags=None, ext=None, overwrite=False,
verbose=False, **kwargs):
"""Downloads the given instance of this dataset from dataset store.
Parameters
----------
version: str, optional
The version of the instance of this dataset.
tags : list of str, optional
The tags associated with the given instance of this dataset.
ext : str, optional
The file extension to use. If not given, the default extension is
used.
overwrite : bool, default False
If set to True, the given instance of the dataset is downloaded
from dataset store even if it exists in the local data directory.
Otherwise, if a matching dataset is found localy, download is
skipped.
verbose : bool, default False
If set to True, informative messages are printed.
**kwargs : extra keyword arguments
Extra keyword arguments are forwarded to
azure.storage.blob.BlockBlobService.get_blob_to_path.
"""
fpath = self.fpath(version=version, tags=tags, ext=ext)
if os.path.isfile(fpath) and not overwrite:
if verbose:
print(
"File exists and overwrite set to False, so not "
"downloading {} with version={} and tags={}".format(
self.name, version, tags))
return
download_dataset(
dataset_name=self.name,
file_path=fpath,
task=self.task,
dataset_attributes=self.kwargs,
**kwargs,
) | python | {
"resource": ""
} |
q43399 | Dataset.df | train | def df(self, version=None, tags=None, ext=None, **kwargs):
"""Loads an instance of this dataset into a dataframe.
Parameters
----------
version: str, optional
The version of the instance of this dataset.
tags : list of str, optional
The tags associated with the desired instance of this dataset.
ext : str, optional
The file extension to use. If not given, the default extension is
used.
**kwargs : extra keyword arguments, optional
Extra keyword arguments are forwarded to the deserialization method
of the SerializationFormat object corresponding to the extension
used.
Returns
-------
pandas.DataFrame
A dataframe containing the desired instance of this dataset.
"""
ext = self._find_extension(version=version, tags=tags)
if ext is None:
attribs = "{}{}".format(
"version={} and ".format(version) if version else "",
"tags={}".format(tags) if tags else "",
)
raise MissingDatasetError(
"No dataset with {} in local store!".format(attribs))
fpath = self.fpath(version=version, tags=tags, ext=ext)
fmt = SerializationFormat.by_name(ext)
return fmt.deserialize(fpath, **kwargs) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.