_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q43900
ParseContext.parse
train
def parse(self, **global_args): """Entry point to parsing a BUILD file. Args: **global_args: Variables to include in the parsing environment. """ if self.build_file not in ParseContext._parsed: # http://en.wikipedia.org/wiki/Abstract_syntax_tree # http...
python
{ "resource": "" }
q43901
ClientManager.add_client
train
def add_client(self, client): """ Adds the specified client to this manager. :param client: The client to add into this manager. :type client: :class:`revision.client.Client` :return: The ClientManager instance (method chaining) :rtype: :class:`revision.client_manager.Cl...
python
{ "resource": "" }
q43902
generate_conf_file
train
def generate_conf_file(argv: List[str]) -> bool: """ Convert a set of FHIR resources into their corresponding i2b2 counterparts. :param argv: Command line arguments. See: create_parser for details :return: """ parser = ArgumentParser(description="Generate SQL db_conf file template") parser...
python
{ "resource": "" }
q43903
Chain.compute
train
def compute(self, *args, **kwargs)->[Any, None]: """Compose and evaluate the function. """ return super().compute( self.compose, *args, **kwargs )
python
{ "resource": "" }
q43904
Chain.copy
train
def copy(self, klass=None): """Create a new instance of the current chain. """ chain = ( klass if klass else self.__class__ )(*self._args, **self._kwargs) chain._tokens = self._tokens.copy() return chain
python
{ "resource": "" }
q43905
ThisComposer.call
train
def call(self, tokens, *args, **kwargs): """Add args and kwargs to the tokens. """ tokens.append([evaluate, [args, kwargs], {}]) return tokens
python
{ "resource": "" }
q43906
_this.copy
train
def copy(self, klass=_x): """A new chain beginning with the current chain tokens and argument. """ chain = super().copy() new_chain = klass(chain._args[0]) new_chain._tokens = [[ chain.compose, [], {}, ]] return new_chain
python
{ "resource": "" }
q43907
prefix
train
def prefix(filename): ''' strips common fMRI dataset suffixes from filenames ''' return os.path.split(re.sub(_afni_suffix_regex,"",str(filename)))[1]
python
{ "resource": "" }
q43908
suffix
train
def suffix(filename,suffix): ''' returns a filenames with ``suffix`` inserted before the dataset suffix ''' return os.path.split(re.sub(_afni_suffix_regex,"%s\g<1>" % suffix,str(filename)))[1]
python
{ "resource": "" }
q43909
afni_copy
train
def afni_copy(filename): ''' creates a ``+orig`` copy of the given dataset and returns the filename as a string ''' if nl.pkg_available('afni',True): afni_filename = "%s+orig" % nl.prefix(filename) if not os.path.exists(afni_filename + ".HEAD"): nl.calc(filename,'a',prefix=nl.prefix(...
python
{ "resource": "" }
q43910
nifti_copy
train
def nifti_copy(filename,prefix=None,gzip=True): ''' creates a ``.nii`` copy of the given dataset and returns the filename as a string''' # I know, my argument ``prefix`` clobbers the global method... but it makes my arguments look nice and clean if prefix==None: prefix = filename nifti_filename ...
python
{ "resource": "" }
q43911
_dset_info_afni
train
def _dset_info_afni(dset): ''' returns raw output from running ``3dinfo`` ''' info = DsetInfo() try: raw_info = subprocess.check_output(['3dinfo','-verb',str(dset)],stderr=subprocess.STDOUT) except: return None if raw_info==None: return None # Subbrick info: sub_patte...
python
{ "resource": "" }
q43912
subbrick
train
def subbrick(dset,label,coef=False,tstat=False,fstat=False,rstat=False,number_only=False): ''' returns a string referencing the given subbrick within a dset This method reads the header of the dataset ``dset``, finds the subbrick whose label matches ``label`` and returns a string of type ``dataset[X]``, wh...
python
{ "resource": "" }
q43913
dset_grids_equal
train
def dset_grids_equal(dsets): '''Tests if each dataset in the ``list`` ``dsets`` has the same number of voxels and voxel-widths''' infos = [dset_info(dset) for dset in dsets] for i in xrange(3): if len(set([x.voxel_size[i] for x in infos]))>1 or len(set([x.voxel_dims[i] for x in infos]))>1: ...
python
{ "resource": "" }
q43914
resample_dset
train
def resample_dset(dset,template,prefix=None,resam='NN'): '''Resamples ``dset`` to the grid of ``template`` using resampling mode ``resam``. Default prefix is to suffix ``_resam`` at the end of ``dset`` Available resampling modes: :NN: Nearest Neighbor :Li: Linear :Cu: Cubic...
python
{ "resource": "" }
q43915
ijk_to_xyz
train
def ijk_to_xyz(dset,ijk): '''convert the dset indices ``ijk`` to RAI coordinates ``xyz``''' i = nl.dset_info(dset) orient_codes = [int(x) for x in nl.run(['@AfniOrient2RAImap',i.orient]).output.split()] orient_is = [abs(x)-1 for x in orient_codes] rai = [] for rai_i in xrange(3): ijk_i ...
python
{ "resource": "" }
q43916
value_at_coord
train
def value_at_coord(dset,coords): '''returns value at specified coordinate in ``dset``''' return nl.numberize(nl.run(['3dmaskave','-q','-dbox'] + list(coords) + [dset],stderr=None).output)
python
{ "resource": "" }
q43917
AwsAutoScalingGroup.do_printActivities
train
def do_printActivities(self,args): """Print scaling activities""" parser = CommandArgumentParser("printActivities") parser.add_argument('-r','--refresh',action='store_true',dest='refresh',help='refresh'); args = vars(parser.parse_args(args)) refresh = args['refresh'] or not self....
python
{ "resource": "" }
q43918
AwsAutoScalingGroup.do_printActivity
train
def do_printActivity(self,args): """Print scaling activity details""" parser = CommandArgumentParser("printActivity") parser.add_argument(dest='index',type=int,help='refresh'); args = vars(parser.parse_args(args)) index = args['index'] activity = self.activities[index] ...
python
{ "resource": "" }
q43919
AwsAutoScalingGroup.do_printInstances
train
def do_printInstances(self,args): """Print the list of instances in this auto scaling group. printInstances -h for detailed help""" parser = CommandArgumentParser("printInstances") parser.add_argument(dest='filters',nargs='*',default=["*"],help='Filter instances'); parser.add_argument('-...
python
{ "resource": "" }
q43920
AwsAutoScalingGroup.do_printPolicy
train
def do_printPolicy(self,args): """Print the autoscaling policy""" parser = CommandArgumentParser("printPolicy") args = vars(parser.parse_args(args)) policy = self.client.describe_policies(AutoScalingGroupName=self.scalingGroup) pprint(policy)
python
{ "resource": "" }
q43921
AwsAutoScalingGroup.do_rebootInstance
train
def do_rebootInstance(self,args): """Restart specified instance""" parser = CommandArgumentParser("rebootInstance") parser.add_argument(dest='instance',help='instance index or name'); args = vars(parser.parse_args(args)) instanceId = args['instance'] try: ind...
python
{ "resource": "" }
q43922
AwsAutoScalingGroup.do_run
train
def do_run(self,args): """SSH to each instance in turn and run specified command""" parser = CommandArgumentParser("run") parser.add_argument('-R','--replace-key',dest='replaceKey',default=False,action='store_true',help="Replace the host's key. This is useful when AWS recycles an IP address you'...
python
{ "resource": "" }
q43923
AwsAutoScalingGroup.do_startInstance
train
def do_startInstance(self,args): """Start specified instance""" parser = CommandArgumentParser("startInstance") parser.add_argument(dest='instance',help='instance index or name'); args = vars(parser.parse_args(args)) instanceId = args['instance'] force = args['force'] ...
python
{ "resource": "" }
q43924
AwsAutoScalingGroup.do_stopInstance
train
def do_stopInstance(self,args): """Stop specified instance""" parser = CommandArgumentParser("stopInstance") parser.add_argument(dest='instance',help='instance index or name'); parser.add_argument('-f','--force',action='store_true',dest='force',help='instance index or name'); arg...
python
{ "resource": "" }
q43925
AwsAutoScalingGroup.do_terminateInstance
train
def do_terminateInstance(self,args): """Terminate an EC2 instance""" parser = CommandArgumentParser("terminateInstance") parser.add_argument(dest='instance',help='instance index or name'); args = vars(parser.parse_args(args)) instanceId = args['instance'] try: ...
python
{ "resource": "" }
q43926
cli
train
def cli(sequencepath, report, refseq_database): """ Pass command line arguments to, and run the feature extraction functions """ main(sequencepath, report, refseq_database, num_threads=multiprocessing.cpu_count())
python
{ "resource": "" }
q43927
grouplabelencode
train
def grouplabelencode(data, mapping, nacode=None, nastate=False): """Encode data array with grouped labels Parameters: ----------- data : list array with labels mapping : dict, list of list the index of each element is used as encoding. Each element is a single label (str) o...
python
{ "resource": "" }
q43928
get_csv_col_headers
train
def get_csv_col_headers(rows, row_headers_count_value=0): """ Retrieve csv column headers """ count = 0 if rows: for row in rows: if exclude_empty_values(row[:row_headers_count_value]): break count += 1 if len(rows) == count: count = 1 #...
python
{ "resource": "" }
q43929
populate_csv_headers
train
def populate_csv_headers(rows, partial_headers, column_headers_count=1): """ Populate csv rows headers when are empty, extending the superior or upper headers. """ result = [''] * (len(rows) - column_headers_count) for i_index in range(0, len(p...
python
{ "resource": "" }
q43930
get_row_headers
train
def get_row_headers(rows, row_headers_count_value=0, column_headers_count=1): """ Return row headers. Assume that by default it has one column header. Assume that there is only one father row header. """ # TODO: REFACTOR ALGORITHM NEEDED partial_headers = [] if row_headers_count_value: ...
python
{ "resource": "" }
q43931
retrieve_csv_data
train
def retrieve_csv_data(rows, row_header=0, column_header=0, limit_column=0): """ Take the data from the rows. """ return [row[row_header:limit_column] for row in rows[column_header:]]
python
{ "resource": "" }
q43932
csv_tolist
train
def csv_tolist(path_to_file, **kwargs): """ Parse the csv file to a list of rows. """ result = [] encoding = kwargs.get('encoding', 'utf-8') delimiter = kwargs.get('delimiter', ',') dialect = kwargs.get('dialect', csv.excel) _, _ext = path_to_file.split('.', 1) try: file...
python
{ "resource": "" }
q43933
excel_todictlist
train
def excel_todictlist(path_to_file, **kwargs): """ Parse excel file to a dict list of sheets, rows. """ result = collections.OrderedDict() encoding = kwargs.get('encoding', 'utf-8') formatting_info = '.xlsx' not in path_to_file count = 0 with xlrd.open_workbook( path_to_file, ...
python
{ "resource": "" }
q43934
search_mergedcell_value
train
def search_mergedcell_value(xl_sheet, merged_range): """ Search for a value in merged_range cells. """ for search_row_idx in range(merged_range[0], merged_range[1]): for search_col_idx in range(merged_range[2], merged_range[3]): if xl_sheet.cell(search_row_idx, search_col_idx).value:...
python
{ "resource": "" }
q43935
is_merged
train
def is_merged(sheet, row, column): """ Check if a row, column cell is a merged cell """ for cell_range in sheet.merged_cells: row_low, row_high, column_low, column_high = cell_range if (row in range(row_low, row_high)) and \ (column in range(column_low, column_high)): ...
python
{ "resource": "" }
q43936
populate_headers
train
def populate_headers(headers): """ Concatenate headers with subheaders """ result = [''] * len(headers[0]) values = [''] * len(headers) for k_index in range(0, len(headers)): for i_index in range(0, len(headers[k_index])): if headers[k_index][i_index]: values[...
python
{ "resource": "" }
q43937
row_csv_limiter
train
def row_csv_limiter(rows, limits=None): """ Limit row passing a value or detect limits making the best effort. """ limits = [None, None] if limits is None else limits if len(exclude_empty_values(limits)) == 2: upper_limit = limits[0] lower_limit = limits[1] elif len(exclude_emp...
python
{ "resource": "" }
q43938
row_iter_limiter
train
def row_iter_limiter(rows, begin_row, way, c_value): """ Alghoritm to detect row limits when row have more that one column. Depending the init params find from the begin or behind. NOT SURE THAT IT WORKS WELL.. """ limit = None for index in range(begin_row, len(rows)): if not len(ex...
python
{ "resource": "" }
q43939
csv_dict_format
train
def csv_dict_format(csv_data, c_headers=None, r_headers=None): """ Format csv rows parsed to Dict. """ # format dict if has row_headers if r_headers: result = {} for k_index in range(0, len(csv_data)): if r_headers[k_index]: result[r_headers[k_index]] = co...
python
{ "resource": "" }
q43940
csv_array_clean_format
train
def csv_array_clean_format(csv_data, c_headers=None, r_headers=None): """ Format csv rows parsed to Array clean format. """ result = [] real_num_header = len(force_list(r_headers[0])) if r_headers else 0 result.append([""] * real_num_header + c_headers) for k_index in range(0, len(csv_data...
python
{ "resource": "" }
q43941
csv_format
train
def csv_format(csv_data, c_headers=None, r_headers=None, rows=None, **kwargs): """ Format csv rows parsed to Dict or Array """ result = None c_headers = [] if c_headers is None else c_headers r_headers = [] if r_headers is None else r_headers rows = [] if rows is None else rows result_f...
python
{ "resource": "" }
q43942
Notification._notify_on_condition
train
def _notify_on_condition(self, test_message=None, **kwargs): """Returns the value of `notify_on_condition` or False. """ if test_message: return True else: return self.enabled and self.notify_on_condition(**kwargs)
python
{ "resource": "" }
q43943
Notification.enabled
train
def enabled(self): """Returns True if this notification is enabled based on the value of Notification model instance. Note: Notification names/display_names are persisted in the "Notification" model where each mode instance can be flagged as enabled or not, and are selected/subs...
python
{ "resource": "" }
q43944
Notification.notification_model
train
def notification_model(self): """Returns the Notification 'model' instance associated with this notification. """ NotificationModel = django_apps.get_model("edc_notification.notification") # trigger exception if this class is not registered. site_notifications.get(self.na...
python
{ "resource": "" }
q43945
Notification.get_template_options
train
def get_template_options(self, instance=None, test_message=None, **kwargs): """Returns a dictionary of message template options. Extend using `extra_template_options`. """ protocol_name = django_apps.get_app_config("edc_protocol").protocol_name test_message = test_message or sel...
python
{ "resource": "" }
q43946
Notification.sms_recipients
train
def sms_recipients(self): """Returns a list of recipients subscribed to receive SMS's for this "notifications" class. See also: edc_auth.UserProfile. """ sms_recipients = [] UserProfile = django_apps.get_model("edc_auth.UserProfile") for user_profile in UserProfi...
python
{ "resource": "" }
q43947
sign_filter_permissions
train
def sign_filter_permissions(permissions): """ Return a compressed, signed dump of the json blob. This function expects a json blob that is a dictionary containing model dotted names as keys. Those keys each have a value that is a list of dictionaries, each of which contains the keys 'filters' and '...
python
{ "resource": "" }
q43948
unsign_filters_and_actions
train
def unsign_filters_and_actions(sign, dotted_model_name): """Return the list of filters and actions for dotted_model_name.""" permissions = signing.loads(sign) return permissions.get(dotted_model_name, [])
python
{ "resource": "" }
q43949
Comparable.equality
train
def equality(self, other): """Compare two objects for equality. @param self: first object to compare @param other: second object to compare @return: boolean result of comparison """ # Compare specified attributes for equality cname = self.__class__.__name__ ...
python
{ "resource": "" }
q43950
Comparable.similarity
train
def similarity(self, other): """Compare two objects for similarity. @param self: first object to compare @param other: second object to compare @return: L{Similarity} result of comparison """ sim = self.Similarity() total = 0.0 # Calculate similarity r...
python
{ "resource": "" }
q43951
Comparable.Similarity
train
def Similarity(self, value=None): # pylint: disable=C0103 """Constructor for new default Similarities.""" if value is None: value = 0.0 return Similarity(value, threshold=self.threshold)
python
{ "resource": "" }
q43952
Comparable.log
train
def log(obj1, obj2, sym, cname=None, aname=None, result=None): # pylint: disable=R0913 """Log the objects being compared and the result. When no result object is specified, subsequence calls will have an increased indentation level. The indentation level is decreased once a result obje...
python
{ "resource": "" }
q43953
PkgFileGroup.translate_path
train
def translate_path(self, dep_file, dep_rule): """Translate dep_file from dep_rule into this rule's output path.""" dst_base = dep_file.split(os.path.join(dep_rule.address.repo, dep_rule.address.path), 1)[-1] if self.params['strip_prefix']: ...
python
{ "resource": "" }
q43954
new
train
def new(ruletype, **kwargs): """Instantiate a new build rule based on kwargs. Appropriate args list varies with rule type. Minimum args required: [... fill this in ...] """ try: ruleclass = TYPE_MAP[ruletype] except KeyError: raise error.InvalidRule('Unrecognized rule type...
python
{ "resource": "" }
q43955
_countdown
train
def _countdown(seconds): """ Wait `seconds` counting down. """ for i in range(seconds, 0, -1): sys.stdout.write("%02d" % i) time.sleep(1) sys.stdout.write("\b\b") sys.stdout.flush() sys.stdout.flush()
python
{ "resource": "" }
q43956
post_process
train
def post_process(table, post_processors): """Applies the list of post processing methods if any""" table_result = table for processor in post_processors: table_result = processor(table_result) return table_result
python
{ "resource": "" }
q43957
describe
train
def describe(cls, full=False): """Prints a description of the table based on the provided documentation and post processors""" divider_double = "=" * 80 divider_single = "-" * 80 description = cls.__doc__ message = [] message.append(divider_double) message.append(cls.__name__ + ':') ...
python
{ "resource": "" }
q43958
BaseTableABC.describe_processors
train
def describe_processors(cls): """List all postprocessors and their description""" # TODO: Add dependencies to this dictionary for processor in cls.post_processors(cls): yield {'name': processor.__name__, 'description': processor.__doc__, 'process...
python
{ "resource": "" }
q43959
BaseTableABC.dependencies
train
def dependencies(cls): """Returns a list of all dependent tables, in the order they are defined. Add new dependencies for source and every post proecssor like this:: source.dependencies = [PersonalData] some_post_processor.dependencies = [SomeOtherTable, AnotherTable] ...
python
{ "resource": "" }
q43960
BaseTableABC.get_settings_list
train
def get_settings_list(self): """The settings list used for building the cache id.""" return [ self.source, self.output, self.kwargs, self.post_processors, ]
python
{ "resource": "" }
q43961
BaseTableABC.get_hash
train
def get_hash(self): """Retruns a hash based on the the current table code and kwargs. Also changes based on dependent tables.""" depencency_hashes = [dep.get_hash() for dep in self.dep()] sl = inspect.getsourcelines hash_sources = [sl(self.__class__), self.args, ...
python
{ "resource": "" }
q43962
BaseTableABC.get_cached_filename
train
def get_cached_filename(self, filename, extention, settings_list=None): """Creates a filename with md5 cache string based on settings list Args: filename (str): the filename without extention extention (str): the file extention without dot. (i.e. 'pkl') settings_list...
python
{ "resource": "" }
q43963
Table._process_table
train
def _process_table(self, cache=True): """Applies the post processors""" table = self.source() assert not isinstance(table, None.__class__), \ "{}.source needs to return something, not None".format(self.__class__.__name__) table = post_process(table, self.post_processors()) ...
python
{ "resource": "" }
q43964
APIGenerator.generate
train
def generate(self): """Runs generation process.""" for root, _, files in os.walk(self.source_dir): for fname in files: source_fpath = os.path.join(root, fname) self.generate_api_for_source(source_fpath)
python
{ "resource": "" }
q43965
APIGenerator.generate_api_for_source
train
def generate_api_for_source(self, source_fpath: str): """Generate end json api file with directory structure for concrete source file.""" content = self.convert_content(source_fpath) if content is None: return dest_fpath = self.dest_fpath(source_fpath) self.c...
python
{ "resource": "" }
q43966
APIGenerator.convert_content
train
def convert_content(self, fpath: str) -> typing.Optional[dict]: """Convert content of source file with loader, provided with `loader_cls` self attribute. Returns dict with converted content if loader class support source file extenstions, otherwise return nothing.""" try: ...
python
{ "resource": "" }
q43967
APIGenerator.dest_fpath
train
def dest_fpath(self, source_fpath: str) -> str: """Calculates full path for end json-api file from source file full path.""" relative_fpath = os.path.join(*source_fpath.split(os.sep)[1:]) relative_dirpath = os.path.dirname(relative_fpath) source_fname = relative_fpath.split(os.s...
python
{ "resource": "" }
q43968
APIGenerator.create_fpath_dir
train
def create_fpath_dir(self, fpath: str): """Creates directory for fpath.""" os.makedirs(os.path.dirname(fpath), exist_ok=True)
python
{ "resource": "" }
q43969
FilenameChecker.add_options
train
def add_options(cls, parser): """Required by flake8 add the possible options, called first Args: parser (OptionsManager): """ kwargs = {'action': 'store', 'default': '', 'parse_from_config': True, 'comma_separated_list': True} for num in ran...
python
{ "resource": "" }
q43970
FilenameChecker.parse_options
train
def parse_options(cls, options): """Required by flake8 parse the options, called after add_options Args: options (dict): options to be parsed """ d = {} for filename_check, dictionary in cls.filename_checks.items(): # retrieve the marks from the p...
python
{ "resource": "" }
q43971
FilenameChecker.run
train
def run(self): """Required by flake8 Will be called after add_options and parse_options. Yields: tuple: (int, int, str, type) the tuple used by flake8 to construct a violation """ if len(self.filename_checks) == 0: message = "N401 no configuration found ...
python
{ "resource": "" }
q43972
get_my_ips
train
def get_my_ips(): """highly os specific - works only in modern linux kernels""" ips = list() if not os.path.exists("/sys/class/net"): # not linux return ['127.0.0.1'] for ifdev in os.listdir("/sys/class/net"): if ifdev == "lo": continue try: sock = socket....
python
{ "resource": "" }
q43973
get_identity_document
train
def get_identity_document(current_block: dict, uid: str, salt: str, password: str) -> Identity: """ Get an Identity document :param current_block: Current block data :param uid: Unique IDentifier :param salt: Passphrase of the account :param password: Password of the account :rtype: Identi...
python
{ "resource": "" }
q43974
make_hash_id
train
def make_hash_id(): """ Compute the `datetime.now` based SHA-1 hash of a string. :return: Returns the sha1 hash as a string. :rtype: str """ today = datetime.datetime.now().strftime(DATETIME_FORMAT) return hashlib.sha1(today.encode('utf-8')).hexdigest()
python
{ "resource": "" }
q43975
read_header
train
def read_header(filename): ''' returns a dictionary of values in the header of the given file ''' header = {} in_header = False data = nl.universal_read(filename) lines = [x.strip() for x in data.split('\n')] for line in lines: if line=="*** Header Start ***": in_header=True ...
python
{ "resource": "" }
q43976
CustomLabelCondition.appointment
train
def appointment(self): """Returns the appointment instance for this request or None. """ return django_apps.get_model(self.appointment_model).objects.get( pk=self.request.GET.get("appointment") )
python
{ "resource": "" }
q43977
CustomLabelCondition.previous_visit
train
def previous_visit(self): """Returns the previous visit for this request or None. Requires attr `visit_model_cls`. """ previous_visit = None if self.appointment: appointment = self.appointment while appointment.previous_by_timepoint: try: ...
python
{ "resource": "" }
q43978
CustomLabelCondition.previous_obj
train
def previous_obj(self): """Returns a model obj that is the first occurrence of a previous obj relative to this object's appointment. Override this method if not am EDC subject model / CRF. """ previous_obj = None if self.previous_visit: try: p...
python
{ "resource": "" }
q43979
read
train
def read(fname): """ utility function to read and return file contents """ fpath = os.path.join(os.path.dirname(__file__), fname) with codecs.open(fpath, 'r', 'utf8') as fhandle: return fhandle.read().strip()
python
{ "resource": "" }
q43980
create_files
train
def create_files(filedef, cleanup=True): """Contextmanager that creates a directory structure from a yaml descripttion. """ cwd = os.getcwd() tmpdir = tempfile.mkdtemp() try: Filemaker(tmpdir, filedef) if not cleanup: # pragma: nocover pass # print("TM...
python
{ "resource": "" }
q43981
Filemaker.make_file
train
def make_file(self, filename, content): """Create a new file with name ``filename`` and content ``content``. """ with open(filename, 'w') as fp: fp.write(content)
python
{ "resource": "" }
q43982
insert_data_frame
train
def insert_data_frame(col, df, int_col=None, binary_col=None, minimal_size=5): """Insert ``pandas.DataFrame``. :param col: :class:`pymongo.collection.Collection` instance. :param df: :class:`pandas.DataFrame` instance. :param int_col: list of integer-type column. :param binary_col: list of binary-t...
python
{ "resource": "" }
q43983
AsciiArmor._remove_trailing_spaces
train
def _remove_trailing_spaces(text: str) -> str: """ Remove trailing spaces and tabs :param text: Text to clean up :return: """ clean_text = str() for line in text.splitlines(True): # remove trailing spaces (0x20) and tabs (0x09) clean_text...
python
{ "resource": "" }
q43984
AsciiArmor._parse_dash_escaped_line
train
def _parse_dash_escaped_line(dash_escaped_line: str) -> str: """ Parse a dash-escaped text line :param dash_escaped_line: Dash escaped text line :return: """ text = str() regex_dash_escape_prefix = compile('^' + DASH_ESCAPE_PREFIX) # if prefixed by a dash...
python
{ "resource": "" }
q43985
AsciiArmor._decrypt
train
def _decrypt(ascii_armor_message: str, signing_key: SigningKey) -> str: """ Decrypt a message from ascii armor format :param ascii_armor_message: Utf-8 message :param signing_key: SigningKey instance created from credentials :return: """ data = signing_key.decryp...
python
{ "resource": "" }
q43986
render
train
def render(request, template_name, context=None, content_type=None, status=None, using=None, logs=None): """ Wrapper around Django render method. Can take one or a list of logs and logs the response. No overhead if no logs are passed. """ if logs: obj_logger = ObjectLogger() if not i...
python
{ "resource": "" }
q43987
entify_main
train
def entify_main(args): ''' Main function. This function is created in this way so as to let other applications make use of the full configuration capabilities of the application. ''' # Recovering the logger # Calling the logger when being imported i3visiotools.logger.setupLogger(loggerName="entify", verbosity=...
python
{ "resource": "" }
q43988
grouper_df
train
def grouper_df(df, chunksize): """Evenly divide pd.DataFrame into n rows piece, no filled value if sub dataframe's size smaller than n. :param df: ``pandas.DataFrame`` instance. :param chunksize: number of rows of each small DataFrame. **中文文档** 将 ``pandas.DataFrame`` 分拆成等大小的小DataFrame。 "...
python
{ "resource": "" }
q43989
to_index_row_dict
train
def to_index_row_dict(df, index_col=None, use_ordered_dict=True): """Transform data frame to list of dict. :param index_col: None or str, the column that used as index. :param use_ordered_dict: if True, row dict is has same order as df.columns. **中文文档** 将dataframe以指定列为key, 转化成以行为视角的dict结构, 提升按行i...
python
{ "resource": "" }
q43990
to_dict_list
train
def to_dict_list(df, use_ordered_dict=True): """Transform each row to dict, and put them into a list. **中文文档** 将 ``pandas.DataFrame`` 转换成一个字典的列表。列表的长度与行数相同, 其中 每一个字典相当于表中的一行, 相当于一个 ``pandas.Series`` 对象。 """ if use_ordered_dict: dict = OrderedDict columns = df.columns data = li...
python
{ "resource": "" }
q43991
to_dict_list_generic_type
train
def to_dict_list_generic_type(df, int_col=None, binary_col=None): """Transform each row to dict, and put them into a list. And automatically convert ``np.int64`` to ``int``, ``pandas.tslib.Timestamp`` to ``datetime.datetime``, ``np.nan`` to ``None``. :param df: ``pandas.DataFrame`` instance. :para...
python
{ "resource": "" }
q43992
add_connection_args
train
def add_connection_args(parser: FileAwareParser, strong_config_file: bool=True) -> FileAwareParser: """ Add the database connection arguments to the supplied parser :param parser: parser to add arguments to :param strong_config_file: If True, force --conf to be processed. This is strictly a test for p...
python
{ "resource": "" }
q43993
versioned_storage.build_dir_tree
train
def build_dir_tree(self, files): """ Convert a flat file dict into the tree format used for storage """ def helper(split_files): this_dir = {'files' : {}, 'dirs' : {}} dirs = defaultdict(list) for fle in split_files: index = fle[0]; fileinfo = fle[1]...
python
{ "resource": "" }
q43994
versioned_storage.flatten_dir_tree
train
def flatten_dir_tree(self, tree): """ Convert a file tree back into a flat dict """ result = {} def helper(tree, leading_path = ''): dirs = tree['dirs']; files = tree['files'] for name, file_info in files.iteritems(): file_info['path'] = leading_path + ...
python
{ "resource": "" }
q43995
versioned_storage.read_dir_tree
train
def read_dir_tree(self, file_hash): """ Recursively read the directory structure beginning at hash """ json_d = self.read_index_object(file_hash, 'tree') node = {'files' : json_d['files'], 'dirs' : {}} for name, hsh in json_d['dirs'].iteritems(): node['dirs'][name] = self.read_dir_tree(...
python
{ "resource": "" }
q43996
versioned_storage.write_dir_tree
train
def write_dir_tree(self, tree): """ Recur through dir tree data structure and write it as a set of objects """ dirs = tree['dirs']; files = tree['files'] child_dirs = {name : self.write_dir_tree(contents) for name, contents in dirs.iteritems()} return self.write_index_object('tree', {'...
python
{ "resource": "" }
q43997
versioned_storage.have_active_commit
train
def have_active_commit(self): """ Checks if there is an active commit owned by the specified user """ commit_state = sfs.file_or_default(sfs.cpjoin(self.base_path, 'active_commit'), None) if commit_state != None: return True return False
python
{ "resource": "" }
q43998
AV.set_env_var
train
def set_env_var(key: str, value: str): """ Sets environment variable on AV Args: key: variable name value: variable value """ elib_run.run(f'appveyor SetVariable -Name {key} -Value {value}') AV.info('Env', f'set "{key}" -> "{value}"')
python
{ "resource": "" }
q43999
BuildFile.validate_internal_deps
train
def validate_internal_deps(self): """Freak out if there are missing local references.""" for node in self.node: if ('target_obj' not in self.node[node] and node not in self.crossrefs): raise error.BrokenGraph('Missing target: %s referenced from %s' ...
python
{ "resource": "" }