text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_host_lun(self, lun_or_snap, cg_member=None): """Gets the host lun of a lun, lun snap, cg snap or a member snap of cg snap. :param lun_or_snap: can be lun...
import storops.unity.resource.lun as lun_module import storops.unity.resource.snap as snap_module which = None if isinstance(lun_or_snap, lun_module.UnityLun): which = self._get_host_luns(lun=lun_or_snap) elif isinstance(lun_or_snap, snap_module.UnitySnap): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_hlu(self, resource, cg_member=None): """Gets the hlu number of a lun, lun snap, cg snap or a member snap of cg snap. :param resource: can be lun, lun sna...
host_lun = self.get_host_lun(resource, cg_member=cg_member) return host_lun if host_lun is None else host_lun.hlu
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_files(tag=None, sat_id=None, data_path=None, format_str=None, supported_tags=None, fake_daily_files_from_monthly=False, two_digit_year_break=None): """R...
if data_path is not None: if format_str is None: try: format_str = supported_tags[sat_id][tag] except KeyError: raise ValueError('Unknown tag') out = pysat.Files.from_os(data_path=data_path, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(fnames, tag=None, sat_id=None, fake_daily_files_from_monthly=False, flatten_twod=True): """Load NASA CDAWeb CDF files. This routine is intended to be us...
import pysatCDF if len(fnames) <= 0 : return pysat.DataFrame(None), None else: # going to use pysatCDF to load the CDF and format # data and metadata for pysat using some assumptions. # Depending upon your needs the resulting pandas DataFrame may # need modific...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download(supported_tags, date_array, tag, sat_id, ftp_site='cdaweb.gsfc.nasa.gov', data_path=None, user=None, password=None, fake_daily_files_from_monthly=Fal...
import os import ftplib # connect to CDAWeb default port ftp = ftplib.FTP(ftp_site) # user anonymous, passwd anonymous@ ftp.login() try: ftp_dict = supported_tags[tag] except KeyError: raise ValueError('Tag name unknown.') # path to re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_pool(self, name, raid_groups, description=None, **kwargs): """Create pool based on RaidGroupParameter. :param name: pool name :param raid_groups: a li...
return UnityPool.create(self._cli, name=name, description=description, raid_groups=raid_groups, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_file_port(self): """Returns ports list can be used by File File ports includes ethernet ports and link aggregation ports. """
eths = self.get_ethernet_port(bond=False) las = self.get_link_aggregation() return eths + las
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_files(tag='', sat_id=None, data_path=None, format_str=None): """Return a Pandas Series of every file for chosen SuperMAG data Parameters tag : (string o...
if format_str is None and data_path is not None: file_base = 'supermag_magnetometer' if tag == "indices" or tag == "all": file_base += '_all' # Can't just download indices if tag == "indices": psplit = path.split(data_path[:-1]) data_path = p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_csv_data(fname, tag): """Load data from a comma separated SuperMAG file Parameters fname : (str) CSV SuperMAG file name tag : (str) Denotes type of file...
import re if tag == "stations": # Because there may be multiple operators, the default pandas reader # cannot be used. ddict = dict() dkeys = list() date_list = list() # Open and read the file with open(fname, "r") as fopen: dtime = pds.date...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_baseline_list(baseline_list): """Format the list of baseline information from the loaded files into a cohesive, informative string Parameters baseline...
uniq_base = dict() uniq_delta = dict() for bline in baseline_list: bsplit = bline.split() bdate = " ".join(bsplit[2:]) if bsplit[0] not in uniq_base.keys(): uniq_base[bsplit[0]] = "" if bsplit[1] not in uniq_delta.keys(): uniq_delta[bsplit[1]] = "" ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append_ascii_data(file_strings, tag): """ Append data from multiple files for the same time period Parameters file_strings : array-like Lists or arrays of st...
import re # Start with data from the first list element out_lines = file_strings[0].split('\n') iparam = -1 # Index for the parameter line ihead = -1 # Index for the last header line idates = list() # Indices for the date lines date_list = list() # List of dates num_stations = list...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append_csv_data(file_strings): """ Append data from multiple csv files for the same time period Parameters file_strings : array-like Lists or arrays of strin...
# Start with data from the first list element out_lines = list() head_line = None # Cycle through the lists of file strings, creating a list of line strings for fstrings in file_strings: file_lines = fstrings.split('\n') # Remove and save the header line head_line = file_l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_files(tag=None, sat_id=None, data_path=None, format_str=None): """Produce a fake list of files spanning a year"""
index = pds.date_range(pysat.datetime(2017,12,1), pysat.datetime(2018,12,1)) # file list is effectively just the date in string format - '%D' works only in Mac. '%x' workins in both Windows and Mac names = [ data_path+date.strftime('%Y-%m-%d')+'.nofile' for date in index] return pysat.Series(name...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enable_log(level=logging.DEBUG): """Enable console logging. This is a utils method for try run with storops. :param level: log level, default to DEBUG """
logger = logging.getLogger(__name__) logger.setLevel(level) if not logger.handlers: logger.info('enabling logging to console.') logger.addHandler(logging.StreamHandler(sys.stdout))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def round_60(value): """ round the number to the multiple of 60 Say a random value is represented by: 60 * n + r n is an integer and r is an integer between 0 an...
t = 60 if value is not None: r = value % t if r > t / 2: ret = value + (t - r) else: ret = value - r else: ret = NaN return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def utilization(prev, curr, counters): """ calculate the utilization delta_busy = curr.busy - prev.busy delta_idle = curr.idle - prev.idle utilization = delta_bu...
busy_prop, idle_prop = counters pb = getattr(prev, busy_prop) pi = getattr(prev, idle_prop) cb = getattr(curr, busy_prop) ci = getattr(curr, idle_prop) db = minus(cb, pb) di = minus(ci, pi) return mul(div(db, add(db, di)), 100)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delta_ps(prev, curr, counters): """ calculate the delta per second of one counter formula: (curr - prev) / delta_time :param prev: previous resource :param c...
counter = get_counter(counters) pv = getattr(prev, counter) cv = getattr(curr, counter) return minus(cv, pv)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def io_size_kb(prev, curr, counters): """ calculate the io size based on bandwidth and throughput formula: average_io_size = bandwidth / throughput :param prev: ...
bw_stats, io_stats = counters size_mb = div(getattr(curr, bw_stats), getattr(curr, io_stats)) return mul(size_mb, 1024)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _assign_funcs(self, by_name=False, inst_module=None): """Assign all external science instrument methods to Instrument object. """
import importlib # set defaults self._list_rtn = self._pass_func self._load_rtn = self._pass_func self._default_rtn = self._pass_func self._clean_rtn = self._pass_func self._init_rtn = self._pass_func self._download_rtn = self._pass_func # default...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _load_data(self, date=None, fid=None): """ Load data for an instrument on given date or fid, dependng upon input. Parameters date : (dt.datetime.date object ...
if fid is not None: # get filename based off of index value fname = self.files[fid:fid+1] elif date is not None: fname = self.files[date: date+pds.DateOffset(days=1)] else: raise ValueError('Must supply either a date or file id number.') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _get_var_type_code(self, coltype): '''Determines the two-character type code for a given variable type Parameters ---------- coltype : type or np.dtype The type of the variable Returns ------- str The variable type code for the given ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_data_info(self, data, file_format): """Support file writing by determiniing data type and other options Parameters data : pandas object Data to be writt...
# get type of data data_type = data.dtype # check if older file_format # if file_format[:7] == 'NETCDF3': if file_format != 'NETCDF4': old_format = True else: old_format = False # check for object type if data_type != np.dtype('O')...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def generic_meta_translator(self, meta_to_translate): '''Translates the metadate contained in an object into a dictionary suitable for export. Parameters ---------- meta_to_translate : Meta The metadata object to translate Returns ------- dic...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_alu_hlu_map(input_str): """Converter for alu hlu map Convert following input into a alu -> hlu map: Sample input: ``` HLU Number ALU Number 0 12 1 23 ``` ...
ret = {} if input_str is not None: pattern = re.compile(r'(\d+)\s*(\d+)') for line in input_str.split('\n'): line = line.strip() if len(line) == 0: continue matched = re.search(pattern, line) if matched is None or len(matched.group...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_disk_indices(value): """Convert following input to disk indices Sample input: ``` Disks: Bus 0 Enclosure 0 Disk 9 Bus 1 Enclosure 0 Disk 12 Bus 1 Enclosur...
ret = [] p = re.compile(r'Bus\s+(\w+)\s+Enclosure\s+(\w+)\s+Disk\s+(\w+)') if value is not None: for line in value.split('\n'): line = line.strip() if len(line) == 0: continue matched = re.search(p, line) if matched is None or len(matc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ipv4_prefix_to_mask(prefix): """ ipv4 cidr prefix to net mask :param prefix: cidr prefix , rang in (0, 32) :type prefix: int :return: dot separated ipv4 net ...
if prefix > 32 or prefix < 0: raise ValueError("invalid cidr prefix for ipv4") else: mask = ((1 << 32) - 1) ^ ((1 << (32 - prefix)) - 1) eight_ones = 255 # 0b11111111 mask_str = '' for i in range(0, 4): mask_str = str(mask & eight_ones) + mask_str ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ipv6_prefix_to_mask(prefix): """ ipv6 cidr prefix to net mask :param prefix: cidr prefix, rang in (0, 128) :type prefix: int :return: comma separated ipv6 ne...
if prefix > 128 or prefix < 0: raise ValueError("invalid cidr prefix for ipv6") else: mask = ((1 << 128) - 1) ^ ((1 << (128 - prefix)) - 1) f = 15 # 0xf or 0b1111 hex_mask_str = '' for i in range(0, 32): hex_mask_str = format((mask & f), 'x') + hex_mask_str ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expand(self, new_size): """ expand the LUN to a new size :param new_size: new size in bytes. :return: the old size """
ret = self.size_total resp = self.modify(size=new_size) resp.raise_if_err() return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replicate(self, dst_lun_id, max_time_out_of_sync, replication_name=None, replicate_existing_snaps=None, remote_system=None): """ Creates a replication sessio...
return UnityReplicationSession.create( self._cli, self.get_id(), dst_lun_id, max_time_out_of_sync, name=replication_name, replicate_existing_snaps=replicate_existing_snaps, remote_system=remote_system)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replicate_with_dst_resource_provisioning(self, max_time_out_of_sync, dst_pool_id, dst_lun_name=None, remote_system=None, replication_name=None, dst_size=None,...
dst_size = self.size_total if dst_size is None else dst_size dst_resource = UnityResourceConfig.to_embedded( name=dst_lun_name, pool_id=dst_pool_id, size=dst_size, default_sp=dst_sp, tiering_policy=dst_tiering_policy, is_thin_enabled=is_dst_thin, is_com...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_physical_port(self): """Returns the link aggregation object or the ethernet port object."""
obj = None if self.is_link_aggregation(): obj = UnityLinkAggregation.get(self._cli, self.get_id()) else: obj = UnityEthernetPort.get(self._cli, self.get_id()) return obj
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_embedded(pool_id=None, is_thin_enabled=None, is_deduplication_enabled=None, is_compression_enabled=None, is_backup_only=None, size=None, tiering_policy=Non...
return {'poolId': pool_id, 'isThinEnabled': is_thin_enabled, 'isDeduplicationEnabled': is_deduplication_enabled, 'isCompressionEnabled': is_compression_enabled, 'isBackupOnly': is_backup_only, 'size': size, 'tieringPolicy': tiering_policy, 'reques...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(cls, cli, src_resource_id, dst_resource_id, max_time_out_of_sync, name=None, members=None, auto_initiate=None, hourly_snap_replication_policy=None, dai...
req_body = cli.make_body( srcResourceId=src_resource_id, dstResourceId=dst_resource_id, maxTimeOutOfSync=max_time_out_of_sync, members=members, autoInitiate=auto_initiate, name=name, hourlySnapReplicationPolicy=hourly_snap_replication_policy, dailySn...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_with_dst_resource_provisioning( cls, cli, src_resource_id, dst_resource_config, max_time_out_of_sync, name=None, remote_system=None, src_spa_interface=...
req_body = cli.make_body( srcResourceId=src_resource_id, dstResourceConfig=dst_resource_config, maxTimeOutOfSync=max_time_out_of_sync, name=name, remoteSystem=remote_system, srcSPAInterface=src_spa_interface, srcSPBInterface=src_spb_inter...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def modify(self, max_time_out_of_sync=None, name=None, hourly_snap_replication_policy=None, daily_snap_replication_policy=None, src_spa_interface=None, src_spb_in...
req_body = self._cli.make_body( maxTimeOutOfSync=max_time_out_of_sync, name=name, hourlySnapReplicationPolicy=hourly_snap_replication_policy, dailySnapReplicationPolicy=daily_snap_replication_policy, srcSPAInterface=src_spa_interface, srcSPBInterface=...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resume(self, force_full_copy=None, src_spa_interface=None, src_spb_interface=None, dst_spa_interface=None, dst_spb_interface=None): """ Resumes a replication...
req_body = self._cli.make_body(forceFullCopy=force_full_copy, srcSPAInterface=src_spa_interface, srcSPBInterface=src_spb_interface, dstSPAInterface=dst_spa_interface, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def failover(self, sync=None, force=None): """ Fails over a replication session. :param sync: True - sync the source and destination resources before failing ove...
req_body = self._cli.make_body(sync=sync, force=force) resp = self.action('failover', **req_body) resp.raise_if_err() return resp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def failback(self, force_full_copy=None): """ Fails back a replication session. This can be applied on a replication session that is failed over. Fail back will ...
req_body = self._cli.make_body(forceFullCopy=force_full_copy) resp = self.action('failback', **req_body) resp.raise_if_err() return resp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _calcOrbits(self): """Prepares data structure for breaking data into orbits. Not intended for end user."""
# if the breaks between orbit have not been defined, define them # also, store the data so that grabbing different orbits does not # require reloads of whole dataset if len(self._orbit_breaks) == 0: # determine orbit breaks self._detBreaks() # store a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _polarBreaks(self): """Determine where breaks in a polar orbiting satellite orbit occur. Looks for sign changes in latitude (magnetic or geographic) as well ...
if self.orbit_index is None: raise ValueError('Orbit properties must be defined at ' + 'pysat.Instrument object instantiation.' + 'See Instrument docs.') else: try: self.sat[self.orbit_index] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _orbitNumberBreaks(self): """Determine where orbital breaks in a dataset with orbit numbers occur. Looks for changes in unique values. """
if self.orbit_index is None: raise ValueError('Orbit properties must be defined at ' + 'pysat.Instrument object instantiation.' + 'See Instrument docs.') else: try: self.sat[self.orbit_index] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse(yr, mo, day): """ Basic parser to deal with date format of the Kp file. """
yr = '20'+yr yr = int(yr) mo = int(mo) day = int(day) return pds.datetime(yr, mo, day)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download(date_array, tag, sat_id, data_path, user=None, password=None): """Routine to download Kp index data Parameters tag : (string or NoneType) Denotes ty...
import ftplib from ftplib import FTP import sys ftp = FTP('ftp.gfz-potsdam.de') # connect to host, default port ftp.login() # user anonymous, passwd anonymous@ ftp.cwd('/pub/home/obs/kp-ap/tab') for date in date_array: fname = 'kp{year:02d}{month:02d}.tab' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_converter(self, converter_str): """find converter function reference by name find converter by name, converter name follows this convention: Class.metho...
ret = None if converter_str is not None: converter_desc_list = converter_str.split('.') if len(converter_desc_list) == 1: converter = converter_desc_list[0] # default to `converter` ret = getattr(cvt, converter, None) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy_file_to_remote(self, local_path, remote_path): """scp the local file to remote folder. :param local_path: local path :param remote_path: remote path """
sftp_client = self.transport.open_sftp_client() LOG.debug('Copy the local file to remote. ' 'Source=%(src)s. Target=%(target)s.' % {'src': local_path, 'target': remote_path}) try: sftp_client.put(local_path, remote_path) except Exception a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_remote_file(self, remote_path, local_path): """Fetch remote File. :param remote_path: remote path :param local_path: local path """
sftp_client = self.transport.open_sftp_client() LOG.debug('Get the remote file. ' 'Source=%(src)s. Target=%(target)s.' % {'src': remote_path, 'target': local_path}) try: sftp_client.get(remote_path, local_path) except Exception as ex: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """Closes the ssh connection."""
if 'isLive' in self.__dict__ and self.isLive: self.transport.close() self.isLive = False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def xml_request(check_object=False, check_invalid_data_mover=False): """ indicate the return value is a xml api request :param check_invalid_data_mover: :param c...
def decorator(f): @functools.wraps(f) def func_wrapper(self, *argv, **kwargs): request = f(self, *argv, **kwargs) return self.request( request, check_object=check_object, check_invalid_data_mover=check_invalid_data_mover) return func...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nas_command(f): """ indicate it's a command of nas command run with ssh :param f: function that returns the command in list :return: command execution result...
@functools.wraps(f) def func_wrapper(self, *argv, **kwargs): commands = f(self, *argv, **kwargs) return self.ssh_execute(['env', 'NAS_DB=/nas'] + commands) return func_wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restore(self, backup=None, delete_backup=False): """Restore the snapshot to the associated storage resource. :param backup: name of the backup snapshot :para...
resp = self._cli.action(self.resource_class, self.get_id(), 'restore', copyName=backup) resp.raise_if_err() backup = resp.first_content['backup'] backup_snap = UnitySnap(_id=backup['id'], cli=self._cli) if delete_backup: log.info("Del...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, async_mode=False, even_attached=False): """Deletes the snapshot. :param async_mode: whether to delete the snapshot in async mode. :param even_at...
try: return super(UnitySnap, self).delete(async_mode=async_mode) except UnityDeleteAttachedSnapError: if even_attached: log.debug("Force delete the snapshot even if it is attached. " "First detach the snapshot from hosts, then delete " ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _flat_vports(self, connection_port): """Flat the virtual ports."""
vports = [] for vport in connection_port.virtual_ports: self._set_child_props(connection_port, vport) vports.append(vport) return vports
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_snap(self): """ This method won't count the snaps in "destroying" state! :return: false if no snaps or all snaps are destroying. """
return len(list(filter(lambda s: s.state != SnapStateEnum.DESTROYING, self.snapshots))) > 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def median2D(const, bin1, label1, bin2, label2, data_label, returnData=False): """Return a 2D average of data_label over a season and label1, label2. Parameters ...
# const is either an Instrument or a Constellation, and we want to # iterate over it. # If it's a Constellation, then we can do that as is, but if it's # an Instrument, we just have to put that Instrument into something # that will yeild that Instrument, like a list. if isinstance(const, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_rsc_list_2(self, rsc_clz_list=None): """get the list of resource list to collect based on clz list :param rsc_clz_list: the list of classes to collect :r...
rsc_list_2 = self._default_rsc_list_with_perf_stats() if rsc_clz_list is None: rsc_clz_list = ResourceList.get_rsc_clz_list(rsc_list_2) return [rsc_list for rsc_list in rsc_list_2 if rsc_list.get_resource_class() in rsc_clz_list]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(cosmicFiles, tag=None, sat_id=None): """ cosmic data load routine, called by pysat """
import netCDF4 num = len(cosmicFiles) # make sure there are files to read if num != 0: # call separate load_files routine, segemented for possible # multiprocessor load, not included and only benefits about 20% output = pysat.DataFrame(load_files(cosmicFiles, tag=tag, sat_id...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean(self): """Routine to return DMSP IVM data cleaned to the specified level 'Clean' enforces that both RPA and DM flags are <= 1 'Dusty' <= 2 'Dirty' <= 3...
if self.clean_level == 'clean': idx, = np.where((self['rpa_flag_ut'] <= 1) & (self['idm_flag_ut'] <= 1)) elif self.clean_level == 'dusty': idx, = np.where((self['rpa_flag_ut'] <= 2) & (self['idm_flag_ut'] <= 2)) elif self.clean_level == 'dirty': idx, = np.where((self['rpa_flag_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def modify(self, management_address=None, username=None, password=None, connection_type=None): """ Modifies a remote system for remote replication. :param manage...
req_body = self._cli.make_body( managementAddress=management_address, username=username, password=password, connectionType=connection_type) resp = self.action('modify', **req_body) resp.raise_if_err() return resp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def verify(self, connection_type=None): """ Verifies and update the remote system settings. :param connection_type: same as the one in `create` method. """
req_body = self._cli.make_body(connectionType=connection_type) resp = self.action('verify', **req_body) resp.raise_if_err() return resp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def modify(self, sp=None, ip_port=None, ip_address=None, netmask=None, v6_prefix_length=None, gateway=None, vlan_id=None): """ Modifies a replication interface. ...
req_body = self._cli.make_body(sp=sp, ipPort=ip_port, ipAddress=ip_address, netmask=netmask, v6PrefixLength=v6_prefix_length, gateway=gateway, vlanId=vlan_id) resp = self.action('modify...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sp_sum_values(self): """ return sp level values input: "values": { "spa": { "19": "385", "18": "0", "20": "0", "17": "0", "16": "0" }, "spb": { "19": "101", ...
if self.values is None: ret = IdValues() else: ret = IdValues({k: sum(int(x) for x in v.values()) for k, v in self.values.items()}) return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add(self, function, kind='add', at_pos='end',*args, **kwargs): """Add a function to custom processing queue. Custom functions are applied automatically to as...
if isinstance(function, str): # convert string to function object function=eval(function) if (at_pos == 'end') | (at_pos == len(self._functions)): # store function object self._functions.append(function) self._args.append(args) s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _apply_all(self, sat): """ Apply all of the custom functions to the satellite data object. """
if len(self._functions) > 0: for func, arg, kwarg, kind in zip(self._functions, self._args, self._kwargs, self._kind): if len(sat.data) > 0: if kind == 'add': # apply custom functions t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear(self): """Clear custom function list."""
self._functions=[] self._args=[] self._kwargs=[] self._kind=[]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download(date_array, tag, sat_id, data_path, user=None, password=None): """ Download SuperDARN data from Virginia Tech organized for loading by pysat. """
import sys import os import pysftp import davitpy if user is None: user = os.environ['DBREADUSER'] if password is None: password = os.environ['DBREADPASS'] with pysftp.Connection( os.environ['VTDB'], username=user, password...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def same_disks(self, count=2): """ filter self to the required number of disks with same size and type Select the disks with the same type and same size. If not ...
ret = self if len(self) > 0: type_counter = Counter(self.drive_type) drive_type, counts = type_counter.most_common()[0] self.set_drive_type(drive_type) if len(self) > 0: size_counter = Counter(self.capacity) size, counts = size_counte...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_bounds(self, start, stop): """ Sets boundaries for all instruments in constellation """
for instrument in self.instruments: instrument.bounds = (start, stop)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def data_mod(self, *args, **kwargs): """ Register a function to modify data of member Instruments. The function is not partially applied to modify member data. W...
for instrument in self.instruments: instrument.custom.add(*args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(self, *args, **kwargs): """ Load instrument data into instrument object.data (Wraps pysat.Instrument.load; documentation of that function is reproduced ...
for instrument in self.instruments: instrument.load(*args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add(self, bounds1, label1, bounds2, label2, bin3, label3, data_label): """ Combines signals from multiple instruments within given bounds. Parameters bounds1...
# TODO Update for 2.7 compatability. if isinstance(data_label, str): data_label = [data_label, ] elif not isinstance(data_label, collections.Sequence): raise ValueError("Please pass data_label as a string or " "collection of strings.") ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def difference(self, instrument1, instrument2, bounds, data_labels, cost_function): """ Calculates the difference in signals from multiple instruments within the...
""" Draft Pseudocode ---------------- Check integrity of inputs. Let STD_LABELS be the constant tuple: ("time", "lat", "long", "alt") Note: modify so that user can override labels for time, lat, long, data for each satelite. // We only...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def computational_form(data): """ Input Series of numbers, Series, or DataFrames repackaged for calculation. Parameters data : pandas.Series Series of numbers, S...
if isinstance(data.iloc[0], DataFrame): dslice = Panel.from_dict(dict([(i,data.iloc[i]) for i in xrange(len(data))])) elif isinstance(data.iloc[0], Series): dslice = DataFrame(data.tolist()) dslice.index = data.index else: dslice = dat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_data_dir(path=None, store=None): """ Set the top level directory pysat uses to look for data and reload. Parameters path : string valid path to directory...
import sys import os import pysat if sys.version_info[0] >= 3: if sys.version_info[1] < 4: import imp re_load = imp.reload else: import importlib re_load = importlib.reload else: re_load = reload if store is None: s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getyrdoy(date): """Return a tuple of year, day of year for a supplied datetime object."""
try: doy = date.toordinal()-datetime(date.year,1,1).toordinal()+1 except AttributeError: raise AttributeError("Must supply a pandas datetime object or " + "equivalent") else: return date.year, doy
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def season_date_range(start, stop, freq='D'): """ Return array of datetime objects using input frequency from start to stop Supports single datetime object or li...
if hasattr(start, '__iter__'): # missing check for datetime season = pds.date_range(start[0], stop[0], freq=freq) for (sta,stp) in zip(start[1:], stop[1:]): season = season.append(pds.date_range(sta, stp, freq=freq)) else: season = pds.date_range(start, stop, freq...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_datetime_index(year=None, month=None, day=None, uts=None): """Create a timeseries index using supplied year, month, day, and ut in seconds. Parameters...
# need a timeseries index for storing satellite data in pandas but # creating a datetime object for everything is too slow # so I calculate the number of nanoseconds elapsed since first sample, # and create timeseries index from that. # Factor of 20 improvement compared to previous method, # ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nan_circmean(samples, high=2.0*np.pi, low=0.0, axis=None): """NaN insensitive version of scipy's circular mean routine Parameters samples : array_like Input ...
samples = np.asarray(samples) samples = samples[~np.isnan(samples)] if samples.size == 0: return np.nan # Ensure the samples are in radians ang = (samples - low) * 2.0 * np.pi / (high - low) # Calculate the means of the sine and cosine, as well as the length # of their unit vecto...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nan_circstd(samples, high=2.0*np.pi, low=0.0, axis=None): """NaN insensitive version of scipy's circular standard deviation routine Parameters samples : arra...
samples = np.asarray(samples) samples = samples[~np.isnan(samples)] if samples.size == 0: return np.nan # Ensure the samples are in radians ang = (samples - low) * 2.0 * np.pi / (high - low) # Calculate the means of the sine and cosine, as well as the length # of their unit vecto...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def default(inst): """Default routine to be applied when loading data. Removes redundant naming """
import pysat.instruments.icon_ivm as icivm inst.tag = 'level_2' icivm.remove_icon_names(inst, target='ICON_L2_EUV_Daytime_OP_')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_files(tag=None, sat_id=None, data_path=None, format_str=None): """Produce a list of ICON EUV files. Notes ----- Currently fixed to level-2 """
desc = None level = tag if level == 'level_1': code = 'L1' desc = None elif level == 'level_2': code = 'L2' desc = None else: raise ValueError('Unsupported level supplied: ' + level) if format_str is None: format_str = 'ICON_'+code+'_EUV_Daytime...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shadow_copy(self): """ Return a copy of the resource with same raw data :return: copy of the resource """
ret = self.__class__() if not self._is_updated(): # before copy, make sure source is updated. self.update() ret._parsed_resource = self._parsed_resource return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(fnames, tag=None, sat_id=None, **kwargs): """Loads data using pysat.utils.load_netcdf4 . This routine is called as needed by pysat. It is not intended f...
return pysat.utils.load_netcdf4(fnames, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_files(tag=None, sat_id=None, data_path=None, format_str=None): """Produce a list of files corresponding to format_str located at data_path. This routine...
return pysat.Files.from_os(data_path=data_path, format_str=format_str)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def command(f): """ indicate it's a command of naviseccli :param f: function that returns the command in list :return: command execution result """
@functools.wraps(f) def func_wrapper(self, *argv, **kwargs): if 'ip' in kwargs: ip = kwargs['ip'] del kwargs['ip'] else: ip = None commands = _get_commands(f, self, *argv, **kwargs) return self.execute(commands, ip=ip) return func_wrapp...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def duel_command(f): """ indicate it's a command need to be called on both SP :param f: function that returns the command in list :return: command execution resu...
@functools.wraps(f) def func_wrapper(self, *argv, **kwargs): commands = _get_commands(f, self, *argv, **kwargs) return self.execute_dual(commands) return func_wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def supplement_filesystem(old_size, user_cap=False): """Return new size accounting for the metadata."""
new_size = old_size if user_cap: if old_size <= _GiB_to_Byte(1.5): new_size = _GiB_to_Byte(3) else: new_size += _GiB_to_Byte(1.5) return int(new_size)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def synchronized(cls, obj=None): """ synchronize on obj if obj is supplied. :param obj: the obj to lock on. if none, lock to the function :return: return of the ...
def get_key(f, o): if o is None: key = hash(f) else: key = hash(o) return key def get_lock(f, o): key = get_key(f, o) if key not in cls.lock_map: with cls.lock_map_lock: if ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def re_enqueue(self, item): """Re-enqueue till reach max retries."""
if 'retries' in item: retries = item['retries'] if retries >= self.MAX_RETRIES: log.warn("Failed to execute {} after {} retries, give it " " up.".format(item['method'], retries)) else: retries += 1 item...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _support_op(*args): """Internal decorator to define an criteria compare operations."""
def inner(func): for one_arg in args: _op_mapping_[one_arg] = func return func return inner
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean(inst): """Routine to return VEFI data cleaned to the specified level Parameters inst : (pysat.Instrument) Instrument class object, whose attribute clea...
if (inst.clean_level == 'dusty') | (inst.clean_level == 'clean'): idx, = np.where(inst['B_flag'] == 0) inst.data = inst[idx, :] return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_icon_names(inst, target=None): """Removes leading text on ICON project variable names Parameters inst : pysat.Instrument ICON associated pysat.Instrum...
if target is None: lev = inst.tag if lev == 'level_2': lev = 'L2' elif lev == 'level_0': lev = 'L0' elif lev == 'level_0p': lev = 'L0P' elif lev == 'level_1.5': lev = 'L1-5' elif lev == 'level_1': lev = '...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def time_shift_to_magnetic_poles(inst): """ OMNI data is time-shifted to bow shock. Time shifted again to intersections with magnetic pole. Parameters inst : Ins...
# need to fill in Vx to get an estimate of what is going on inst['Vx'] = inst['Vx'].interpolate('nearest') inst['Vx'] = inst['Vx'].fillna(method='backfill') inst['Vx'] = inst['Vx'].fillna(method='pad') inst['BSN_x'] = inst['BSN_x'].interpolate('nearest') inst['BSN_x'] = inst['BSN_x'].fill...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calculate_clock_angle(inst): """ Calculate IMF clock angle and magnitude of IMF in GSM Y-Z plane Parameters inst : pysat.Instrument Instrument with OMNI HRO ...
# Calculate clock angle in degrees clock_angle = np.degrees(np.arctan2(inst['BY_GSM'], inst['BZ_GSM'])) clock_angle[clock_angle < 0.0] += 360.0 inst['clock_angle'] = pds.Series(clock_angle, index=inst.data.index) # Calculate magnitude of IMF in Y-Z plane inst['BYZ_GSM'] = pds.Series(np.sq...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calculate_imf_steadiness(inst, steady_window=15, min_window_frac=0.75, max_clock_angle_std=90.0/np.pi, max_bmag_cv=0.5): """ Calculate IMF steadiness using c...
# We are not going to interpolate through missing values sample_rate = int(inst.tag[0]) max_wnum = np.floor(steady_window / sample_rate) if max_wnum != steady_window / sample_rate: steady_window = max_wnum * sample_rate print("WARNING: sample rate is not a factor of the statistical win...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear_access(self, white_list=None): """ clear all ace entries of the share :param white_list: list of username whose access entry won't be cleared :return: ...
access_entries = self.get_ace_list() sid_list = access_entries.sid_list if white_list: sid_white_list = [UnityAclUser.get_sid(self._cli, user, self.cifs_server.domain) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_ace(self, domain=None, user=None, sid=None): """ delete ACE for the share delete ACE for the share. User could either supply the domain and username o...
if sid is None: if domain is None: domain = self.cifs_server.domain sid = UnityAclUser.get_sid(self._cli, user=user, domain=domain) if isinstance(sid, six.string_types): sid = [sid] ace_list = [self._make_remove_ace_entry(s) for s in sid] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def luns(self): """Aggregator for ioclass_luns and ioclass_snapshots."""
lun_list, smp_list = [], [] if self.ioclass_luns: lun_list = map(lambda l: VNXLun(lun_id=l.lun_id, name=l.name, cli=self._cli), self.ioclass_luns) if self.ioclass_snapshots: smp_list = map(lambda smp: VNXLun(name=smp.name, cli=...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def policy(self): """Returns policy which contains this ioclass."""
policies = VNXIOPolicy.get(cli=self._cli) ret = None for policy in policies: contained = policy.ioclasses.name if self._get_name() in contained: ret = VNXIOPolicy.get(name=policy.name, cli=self._cli) break return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def modify(self, new_name=None, iotype=None, lun_ids=None, smp_names=None, ctrlmethod=None, minsize=None, maxsize=None): """Overwrite the current properties for ...
if not any([new_name, iotype, lun_ids, smp_names, ctrlmethod]): raise ValueError('Cannot apply modification, please specify ' 'parameters to modify.') def _do_modify(): out = self._cli.modify_ioclass( self._get_name(), new_name, ioty...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_lun(self, luns): """A wrapper for modify method. .. note:: This API only append luns to existing luns. """
curr_lun_ids, curr_smp_names = self._get_current_names() luns = normalize_lun(luns, self._cli) new_ids, new_smps = convert_lun(luns) if new_ids: curr_lun_ids.extend(new_ids) if new_smps: curr_smp_names.extend(new_smps) return self.modify(lun_ids=c...