_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 = {}...
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: fil...
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(...
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...
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, 'al...
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_id...
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...
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_jo...
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...
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 u...
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)],), ...
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...
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: ra...
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...
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'))...
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_: ra...
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=F...
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 No...
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_r...
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, **kwarg...
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 = __...
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) ...
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:...
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.concaten...
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 =...
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 ...
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/pro...
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...
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...
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(...
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_co...
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 @"): pr...
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(): ...
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': Stat...
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, ...
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.__v...
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, da...
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...
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 f...
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 = cpj...
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)...
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 e...
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_pat...
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 fai...
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(...
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_u...
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_a...
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 curre...
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['REMO...
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: r...
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...
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': retu...
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 ...
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(Const...
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...
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 ...
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 na...
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/weat...
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'): ...
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(): ...
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 f...
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': 'ass...
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": {"ski...
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.val...
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_...
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, s...
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. ...
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 ex...
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: specifi...
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': ...
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. """ hashe...
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): ...
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 ...
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(...
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 associ...
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 associ...
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 th...
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. ...
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. ...
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 wi...
python
{ "resource": "" }