code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def Morlet (sampr, freq, width=7.0): """ Morlet's wavelet for frequency f and time t Wavelet normalized so total energy is 1 freq: specific frequency (Hz) width: number of cycles for the Morlet wavelet output returned: final units are 1/s """ dt = 1. / sampr sf = freq / width # sf in Hz st = 1. / (2. * np.pi * sf) # st in s t = np.arange(-3.5*st, 3.5*st, dt) A = 1. / (st * np.sqrt(2.*np.pi)) # A in 1 / s # units: 1/s * (exp (s**2 / s**2)) * exp( 1/ s * s) return A * np.exp(-t**2. / (2. * st**2.)) * np.exp(1.j * 2. * np.pi * freq * t)
Morlet's wavelet for frequency f and time t Wavelet normalized so total energy is 1 freq: specific frequency (Hz) width: number of cycles for the Morlet wavelet output returned: final units are 1/s
Below is the the instruction that describes the task: ### Input: Morlet's wavelet for frequency f and time t Wavelet normalized so total energy is 1 freq: specific frequency (Hz) width: number of cycles for the Morlet wavelet output returned: final units are 1/s ### Response: def Morlet (sampr, freq, width=7.0): """ Morlet's wavelet for frequency f and time t Wavelet normalized so total energy is 1 freq: specific frequency (Hz) width: number of cycles for the Morlet wavelet output returned: final units are 1/s """ dt = 1. / sampr sf = freq / width # sf in Hz st = 1. / (2. * np.pi * sf) # st in s t = np.arange(-3.5*st, 3.5*st, dt) A = 1. / (st * np.sqrt(2.*np.pi)) # A in 1 / s # units: 1/s * (exp (s**2 / s**2)) * exp( 1/ s * s) return A * np.exp(-t**2. / (2. * st**2.)) * np.exp(1.j * 2. * np.pi * freq * t)
def update(self, data): """ New data will only contain the changed attributes. """ if not data.get('status', []): return status_data = data['status'][0] media_data = status_data.get('media') or {} volume_data = status_data.get('volume', {}) self.current_time = status_data.get('currentTime', self.current_time) self.content_id = media_data.get('contentId', self.content_id) self.content_type = media_data.get('contentType', self.content_type) self.duration = media_data.get('duration', self.duration) self.stream_type = media_data.get('streamType', self.stream_type) self.idle_reason = status_data.get('idleReason', self.idle_reason) self.media_session_id = status_data.get( 'mediaSessionId', self.media_session_id) self.playback_rate = status_data.get( 'playbackRate', self.playback_rate) self.player_state = status_data.get('playerState', self.player_state) self.supported_media_commands = status_data.get( 'supportedMediaCommands', self.supported_media_commands) self.volume_level = volume_data.get('level', self.volume_level) self.volume_muted = volume_data.get('muted', self.volume_muted) self.media_custom_data = media_data.get( 'customData', self.media_custom_data) self.media_metadata = media_data.get('metadata', self.media_metadata) self.subtitle_tracks = media_data.get('tracks', self.subtitle_tracks) self.current_subtitle_tracks = status_data.get( 'activeTrackIds', self.current_subtitle_tracks) self.last_updated = datetime.utcnow()
New data will only contain the changed attributes.
Below is the the instruction that describes the task: ### Input: New data will only contain the changed attributes. ### Response: def update(self, data): """ New data will only contain the changed attributes. """ if not data.get('status', []): return status_data = data['status'][0] media_data = status_data.get('media') or {} volume_data = status_data.get('volume', {}) self.current_time = status_data.get('currentTime', self.current_time) self.content_id = media_data.get('contentId', self.content_id) self.content_type = media_data.get('contentType', self.content_type) self.duration = media_data.get('duration', self.duration) self.stream_type = media_data.get('streamType', self.stream_type) self.idle_reason = status_data.get('idleReason', self.idle_reason) self.media_session_id = status_data.get( 'mediaSessionId', self.media_session_id) self.playback_rate = status_data.get( 'playbackRate', self.playback_rate) self.player_state = status_data.get('playerState', self.player_state) self.supported_media_commands = status_data.get( 'supportedMediaCommands', self.supported_media_commands) self.volume_level = volume_data.get('level', self.volume_level) self.volume_muted = volume_data.get('muted', self.volume_muted) self.media_custom_data = media_data.get( 'customData', self.media_custom_data) self.media_metadata = media_data.get('metadata', self.media_metadata) self.subtitle_tracks = media_data.get('tracks', self.subtitle_tracks) self.current_subtitle_tracks = status_data.get( 'activeTrackIds', self.current_subtitle_tracks) self.last_updated = datetime.utcnow()
def plot (data, pconfig=None): """ Plot a scatter plot with X,Y data. :param data: 2D dict, first keys as sample names, then x:y data pairs :param pconfig: optional dict with config key:value pairs. See CONTRIBUTING.md :return: HTML and JS, ready to be inserted into the page """ if pconfig is None: pconfig = {} # Allow user to overwrite any given config for this plot if 'id' in pconfig and pconfig['id'] and pconfig['id'] in config.custom_plot_config: for k, v in config.custom_plot_config[pconfig['id']].items(): pconfig[k] = v # Given one dataset - turn it into a list if type(data) is not list: data = [data] # Generate the data dict structure expected by HighCharts series plotdata = list() for data_index, ds in enumerate(data): d = list() for s_name in ds: # Ensure any overwritting conditionals from data_labels (e.g. ymax) are taken in consideration series_config = pconfig.copy() if 'data_labels' in pconfig and type(pconfig['data_labels'][data_index]) is dict: # if not a dict: only dataset name is provided series_config.update(pconfig['data_labels'][data_index]) if type(ds[s_name]) is not list: ds[s_name] = [ ds[s_name] ] for k in ds[s_name]: if k['x'] is not None: if 'xmax' in series_config and float(k['x']) > float(series_config['xmax']): continue if 'xmin' in series_config and float(k['x']) < float(series_config['xmin']): continue if k['y'] is not None: if 'ymax' in series_config and float(k['y']) > float(series_config['ymax']): continue if 'ymin' in series_config and float(k['y']) < float(series_config['ymin']): continue this_series = { 'x': k['x'], 'y': k['y'] } try: this_series['name'] = "{}: {}".format(s_name, k['name']) except KeyError: this_series['name'] = s_name try: this_series['color'] = k['color'] except KeyError: try: this_series['color'] = series_config['colors'][s_name] except KeyError: pass d.append(this_series) plotdata.append(d) # Add on annotation data series try: if pconfig.get('extra_series'): extra_series = pconfig['extra_series'] if type(pconfig['extra_series']) == dict: extra_series = [[ pconfig['extra_series'] ]] elif type(pconfig['extra_series']) == list and type(pconfig['extra_series'][0]) == dict: extra_series = [ pconfig['extra_series'] ] for i, es in enumerate(extra_series): for s in es: plotdata[i].append(s) except (KeyError, IndexError): pass # Make a plot return highcharts_scatter_plot(plotdata, pconfig)
Plot a scatter plot with X,Y data. :param data: 2D dict, first keys as sample names, then x:y data pairs :param pconfig: optional dict with config key:value pairs. See CONTRIBUTING.md :return: HTML and JS, ready to be inserted into the page
Below is the the instruction that describes the task: ### Input: Plot a scatter plot with X,Y data. :param data: 2D dict, first keys as sample names, then x:y data pairs :param pconfig: optional dict with config key:value pairs. See CONTRIBUTING.md :return: HTML and JS, ready to be inserted into the page ### Response: def plot (data, pconfig=None): """ Plot a scatter plot with X,Y data. :param data: 2D dict, first keys as sample names, then x:y data pairs :param pconfig: optional dict with config key:value pairs. See CONTRIBUTING.md :return: HTML and JS, ready to be inserted into the page """ if pconfig is None: pconfig = {} # Allow user to overwrite any given config for this plot if 'id' in pconfig and pconfig['id'] and pconfig['id'] in config.custom_plot_config: for k, v in config.custom_plot_config[pconfig['id']].items(): pconfig[k] = v # Given one dataset - turn it into a list if type(data) is not list: data = [data] # Generate the data dict structure expected by HighCharts series plotdata = list() for data_index, ds in enumerate(data): d = list() for s_name in ds: # Ensure any overwritting conditionals from data_labels (e.g. ymax) are taken in consideration series_config = pconfig.copy() if 'data_labels' in pconfig and type(pconfig['data_labels'][data_index]) is dict: # if not a dict: only dataset name is provided series_config.update(pconfig['data_labels'][data_index]) if type(ds[s_name]) is not list: ds[s_name] = [ ds[s_name] ] for k in ds[s_name]: if k['x'] is not None: if 'xmax' in series_config and float(k['x']) > float(series_config['xmax']): continue if 'xmin' in series_config and float(k['x']) < float(series_config['xmin']): continue if k['y'] is not None: if 'ymax' in series_config and float(k['y']) > float(series_config['ymax']): continue if 'ymin' in series_config and float(k['y']) < float(series_config['ymin']): continue this_series = { 'x': k['x'], 'y': k['y'] } try: this_series['name'] = "{}: {}".format(s_name, k['name']) except KeyError: this_series['name'] = s_name try: this_series['color'] = k['color'] except KeyError: try: this_series['color'] = series_config['colors'][s_name] except KeyError: pass d.append(this_series) plotdata.append(d) # Add on annotation data series try: if pconfig.get('extra_series'): extra_series = pconfig['extra_series'] if type(pconfig['extra_series']) == dict: extra_series = [[ pconfig['extra_series'] ]] elif type(pconfig['extra_series']) == list and type(pconfig['extra_series'][0]) == dict: extra_series = [ pconfig['extra_series'] ] for i, es in enumerate(extra_series): for s in es: plotdata[i].append(s) except (KeyError, IndexError): pass # Make a plot return highcharts_scatter_plot(plotdata, pconfig)
def qasm(self, prec=15): """Return the corresponding OPENQASM string.""" if self.value == pi: return "pi" return ccode(self.value, precision=prec)
Return the corresponding OPENQASM string.
Below is the the instruction that describes the task: ### Input: Return the corresponding OPENQASM string. ### Response: def qasm(self, prec=15): """Return the corresponding OPENQASM string.""" if self.value == pi: return "pi" return ccode(self.value, precision=prec)
def get_item_template(self): '''returns template for signle object from queryset If you have a template name my_list_template.html then template for a single object will be _my_list_template.html Now only for default generates _item.html _item.html is obsolete use _default.html ''' content_template = self.content_theme.name # _item.html is obsolete use _default.html # TODO: remove this condition after all _item.html will be converted if content_template == "default": return "widget/%s/_item.html" % self.widget_name # TODO: support more template suffixes return "widget/%s/_%s.html" % (self.widget_name, content_template)
returns template for signle object from queryset If you have a template name my_list_template.html then template for a single object will be _my_list_template.html Now only for default generates _item.html _item.html is obsolete use _default.html
Below is the the instruction that describes the task: ### Input: returns template for signle object from queryset If you have a template name my_list_template.html then template for a single object will be _my_list_template.html Now only for default generates _item.html _item.html is obsolete use _default.html ### Response: def get_item_template(self): '''returns template for signle object from queryset If you have a template name my_list_template.html then template for a single object will be _my_list_template.html Now only for default generates _item.html _item.html is obsolete use _default.html ''' content_template = self.content_theme.name # _item.html is obsolete use _default.html # TODO: remove this condition after all _item.html will be converted if content_template == "default": return "widget/%s/_item.html" % self.widget_name # TODO: support more template suffixes return "widget/%s/_%s.html" % (self.widget_name, content_template)
def from_yaml(cls, yaml_str=None, str_or_buffer=None): """ Create a RegressionModel instance from a saved YAML configuration. Arguments are mutually exclusive. Parameters ---------- yaml_str : str, optional A YAML string from which to load model. str_or_buffer : str or file like, optional File name or buffer from which to load YAML. Returns ------- RegressionModel """ cfg = yamlio.yaml_to_dict(yaml_str, str_or_buffer) model = cls( cfg['fit_filters'], cfg['predict_filters'], cfg['model_expression'], YTRANSFORM_MAPPING[cfg['ytransform']], cfg['name']) if 'fitted' in cfg and cfg['fitted']: fit_parameters = pd.DataFrame(cfg['fit_parameters']) fit_parameters.rsquared = cfg['fit_rsquared'] fit_parameters.rsquared_adj = cfg['fit_rsquared_adj'] model.model_fit = _FakeRegressionResults( model.str_model_expression, fit_parameters, cfg['fit_rsquared'], cfg['fit_rsquared_adj']) model.fit_parameters = fit_parameters logger.debug('loaded regression model {} from YAML'.format(model.name)) return model
Create a RegressionModel instance from a saved YAML configuration. Arguments are mutually exclusive. Parameters ---------- yaml_str : str, optional A YAML string from which to load model. str_or_buffer : str or file like, optional File name or buffer from which to load YAML. Returns ------- RegressionModel
Below is the the instruction that describes the task: ### Input: Create a RegressionModel instance from a saved YAML configuration. Arguments are mutually exclusive. Parameters ---------- yaml_str : str, optional A YAML string from which to load model. str_or_buffer : str or file like, optional File name or buffer from which to load YAML. Returns ------- RegressionModel ### Response: def from_yaml(cls, yaml_str=None, str_or_buffer=None): """ Create a RegressionModel instance from a saved YAML configuration. Arguments are mutually exclusive. Parameters ---------- yaml_str : str, optional A YAML string from which to load model. str_or_buffer : str or file like, optional File name or buffer from which to load YAML. Returns ------- RegressionModel """ cfg = yamlio.yaml_to_dict(yaml_str, str_or_buffer) model = cls( cfg['fit_filters'], cfg['predict_filters'], cfg['model_expression'], YTRANSFORM_MAPPING[cfg['ytransform']], cfg['name']) if 'fitted' in cfg and cfg['fitted']: fit_parameters = pd.DataFrame(cfg['fit_parameters']) fit_parameters.rsquared = cfg['fit_rsquared'] fit_parameters.rsquared_adj = cfg['fit_rsquared_adj'] model.model_fit = _FakeRegressionResults( model.str_model_expression, fit_parameters, cfg['fit_rsquared'], cfg['fit_rsquared_adj']) model.fit_parameters = fit_parameters logger.debug('loaded regression model {} from YAML'.format(model.name)) return model
def parse_log(log, url_pattern): """Parse ``log`` buffer based on ``url_pattern``. Given a buffer as ``log``, parse the log buffer into a mapping of ident-hashes to a hit count, the timestamp of the initial log, and the last timestamp in the log. """ hits = {} initial_timestamp = None def clean_timestamp(v): return ' '.join(v).strip('[]') for line in log: data = line.split() if not initial_timestamp: initial_timestamp = clean_timestamp(data[3:5]) match = url_pattern.match(data[6]) if match: ident_hash = '@'.join(match.groups()) if ident_hash: hits[ident_hash] = hits.get(ident_hash, 0) + 1 else: end_timestamp = clean_timestamp(data[3:5]) return hits, initial_timestamp, end_timestamp
Parse ``log`` buffer based on ``url_pattern``. Given a buffer as ``log``, parse the log buffer into a mapping of ident-hashes to a hit count, the timestamp of the initial log, and the last timestamp in the log.
Below is the the instruction that describes the task: ### Input: Parse ``log`` buffer based on ``url_pattern``. Given a buffer as ``log``, parse the log buffer into a mapping of ident-hashes to a hit count, the timestamp of the initial log, and the last timestamp in the log. ### Response: def parse_log(log, url_pattern): """Parse ``log`` buffer based on ``url_pattern``. Given a buffer as ``log``, parse the log buffer into a mapping of ident-hashes to a hit count, the timestamp of the initial log, and the last timestamp in the log. """ hits = {} initial_timestamp = None def clean_timestamp(v): return ' '.join(v).strip('[]') for line in log: data = line.split() if not initial_timestamp: initial_timestamp = clean_timestamp(data[3:5]) match = url_pattern.match(data[6]) if match: ident_hash = '@'.join(match.groups()) if ident_hash: hits[ident_hash] = hits.get(ident_hash, 0) + 1 else: end_timestamp = clean_timestamp(data[3:5]) return hits, initial_timestamp, end_timestamp
def on_frame(self, frame_in): """Handle frame sent to this specific channel. :param pamqp.Frame frame_in: Amqp frame. :return: """ if self.rpc.on_frame(frame_in): return if frame_in.name in CONTENT_FRAME: self._inbound.append(frame_in) elif frame_in.name == 'Basic.Cancel': self._basic_cancel(frame_in) elif frame_in.name == 'Basic.CancelOk': self.remove_consumer_tag(frame_in.consumer_tag) elif frame_in.name == 'Basic.ConsumeOk': self.add_consumer_tag(frame_in['consumer_tag']) elif frame_in.name == 'Basic.Return': self._basic_return(frame_in) elif frame_in.name == 'Channel.Close': self._close_channel(frame_in) elif frame_in.name == 'Channel.Flow': self.write_frame(specification.Channel.FlowOk(frame_in.active)) else: LOGGER.error( '[Channel%d] Unhandled Frame: %s -- %s', self.channel_id, frame_in.name, dict(frame_in) )
Handle frame sent to this specific channel. :param pamqp.Frame frame_in: Amqp frame. :return:
Below is the the instruction that describes the task: ### Input: Handle frame sent to this specific channel. :param pamqp.Frame frame_in: Amqp frame. :return: ### Response: def on_frame(self, frame_in): """Handle frame sent to this specific channel. :param pamqp.Frame frame_in: Amqp frame. :return: """ if self.rpc.on_frame(frame_in): return if frame_in.name in CONTENT_FRAME: self._inbound.append(frame_in) elif frame_in.name == 'Basic.Cancel': self._basic_cancel(frame_in) elif frame_in.name == 'Basic.CancelOk': self.remove_consumer_tag(frame_in.consumer_tag) elif frame_in.name == 'Basic.ConsumeOk': self.add_consumer_tag(frame_in['consumer_tag']) elif frame_in.name == 'Basic.Return': self._basic_return(frame_in) elif frame_in.name == 'Channel.Close': self._close_channel(frame_in) elif frame_in.name == 'Channel.Flow': self.write_frame(specification.Channel.FlowOk(frame_in.active)) else: LOGGER.error( '[Channel%d] Unhandled Frame: %s -- %s', self.channel_id, frame_in.name, dict(frame_in) )
def build_includes(cls, include_packages): """ cx_freeze doesn't support the star (*) method of sub-module inclusion, so all submodules must be included explicitly. Example (From SaltStack 2014.7): salt salt.fileserver salt.fileserver.gitfs salt.fileserver.hgfs salt.fileserver.minionfs salt.fileserver.roots etc... :param include_packages: List of package references to recurse for subpackages """ includes, package_root_paths = cls._split_packages(include_packages) for package_path, package_name in six.iteritems(package_root_paths): includes.add(package_name) if re.search(r'__init__.py.*$', package_path): # Looks like a package. Walk the directory and see if there are more. package_modules = set() for root, dirs, files in os.walk(os.path.dirname(package_path)): if '__init__.py' in files: package_modules.add(root) for module in [f for f in files if f != u"__init__.py" and f.endswith('.py')]: package_modules.add(os.path.join(root, module)) common_prefix = os.path.commonprefix(package_modules) common_dir = os.path.dirname(common_prefix) package_tails = set([f[len(common_dir) + len(os.sep):] for f in package_modules]) package_names = set([os.path.splitext(tail)[0].replace(os.sep, '.') for tail in package_tails]) includes |= package_names return includes
cx_freeze doesn't support the star (*) method of sub-module inclusion, so all submodules must be included explicitly. Example (From SaltStack 2014.7): salt salt.fileserver salt.fileserver.gitfs salt.fileserver.hgfs salt.fileserver.minionfs salt.fileserver.roots etc... :param include_packages: List of package references to recurse for subpackages
Below is the the instruction that describes the task: ### Input: cx_freeze doesn't support the star (*) method of sub-module inclusion, so all submodules must be included explicitly. Example (From SaltStack 2014.7): salt salt.fileserver salt.fileserver.gitfs salt.fileserver.hgfs salt.fileserver.minionfs salt.fileserver.roots etc... :param include_packages: List of package references to recurse for subpackages ### Response: def build_includes(cls, include_packages): """ cx_freeze doesn't support the star (*) method of sub-module inclusion, so all submodules must be included explicitly. Example (From SaltStack 2014.7): salt salt.fileserver salt.fileserver.gitfs salt.fileserver.hgfs salt.fileserver.minionfs salt.fileserver.roots etc... :param include_packages: List of package references to recurse for subpackages """ includes, package_root_paths = cls._split_packages(include_packages) for package_path, package_name in six.iteritems(package_root_paths): includes.add(package_name) if re.search(r'__init__.py.*$', package_path): # Looks like a package. Walk the directory and see if there are more. package_modules = set() for root, dirs, files in os.walk(os.path.dirname(package_path)): if '__init__.py' in files: package_modules.add(root) for module in [f for f in files if f != u"__init__.py" and f.endswith('.py')]: package_modules.add(os.path.join(root, module)) common_prefix = os.path.commonprefix(package_modules) common_dir = os.path.dirname(common_prefix) package_tails = set([f[len(common_dir) + len(os.sep):] for f in package_modules]) package_names = set([os.path.splitext(tail)[0].replace(os.sep, '.') for tail in package_tails]) includes |= package_names return includes
def roles(self): """gets user groups""" result = AuthGroup.objects(creator=self.client).only('role') return json.loads(result.to_json())
gets user groups
Below is the the instruction that describes the task: ### Input: gets user groups ### Response: def roles(self): """gets user groups""" result = AuthGroup.objects(creator=self.client).only('role') return json.loads(result.to_json())
def crash_handler_lite(etype, evalue, tb): """a light excepthook, adding a small message to the usual traceback""" traceback.print_exception(etype, evalue, tb) from IPython.core.interactiveshell import InteractiveShell if InteractiveShell.initialized(): # we are in a Shell environment, give %magic example config = "%config " else: # we are not in a shell, show generic config config = "c." print >> sys.stderr, _lite_message_template.format(email=author_email, config=config)
a light excepthook, adding a small message to the usual traceback
Below is the the instruction that describes the task: ### Input: a light excepthook, adding a small message to the usual traceback ### Response: def crash_handler_lite(etype, evalue, tb): """a light excepthook, adding a small message to the usual traceback""" traceback.print_exception(etype, evalue, tb) from IPython.core.interactiveshell import InteractiveShell if InteractiveShell.initialized(): # we are in a Shell environment, give %magic example config = "%config " else: # we are not in a shell, show generic config config = "c." print >> sys.stderr, _lite_message_template.format(email=author_email, config=config)
def get_field_names(self): """ Different field names depending on self.add setting (see load_data) For BaseIO """ if self.add: return ['date', 'elem', 'value'] + [flag for flag in self.add] else: field_names = ['date'] for elem in self.parameter: # namedtuple doesn't like numeric field names if elem.isdigit(): elem = "e%s" % elem field_names.append(elem) return field_names
Different field names depending on self.add setting (see load_data) For BaseIO
Below is the the instruction that describes the task: ### Input: Different field names depending on self.add setting (see load_data) For BaseIO ### Response: def get_field_names(self): """ Different field names depending on self.add setting (see load_data) For BaseIO """ if self.add: return ['date', 'elem', 'value'] + [flag for flag in self.add] else: field_names = ['date'] for elem in self.parameter: # namedtuple doesn't like numeric field names if elem.isdigit(): elem = "e%s" % elem field_names.append(elem) return field_names
def process_bib_files(local_dir): """Run the refresh-lsst-bib program's logic: iterates through bib URLs, downloads the file from GitHub, and writes it to a local directory. Parameters ---------- local_dir : `str` Directory to write bib files into. Returns ------- error_count : `int` Number of download errors. """ logger = logging.getLogger(__name__) # check the output directory exists if not os.path.isdir(local_dir): logger.error('Output directory "{}" does not exist'.format(local_dir)) sys.exit(1) root_blob_url = ('https://raw.githubusercontent.com/lsst/lsst-texmf/' 'master/texmf/bibtex/bib/') bib_filenames = ['books.bib', 'lsst-dm.bib', 'lsst.bib', 'refs.bib', 'refs_ads.bib'] error_count = 0 for bib_filename in bib_filenames: url = urllib.parse.urljoin(root_blob_url, bib_filename) logger.info('Downloading {}'.format(url)) try: content = _get_content(url) except requests.HTTPError as e: logger.exception(str(e)) logger.warning('Could not download {}'.format(url)) error_count += 1 continue local_filename = os.path.join(local_dir, bib_filename) with open(local_filename, 'w') as f: f.write(content) return error_count
Run the refresh-lsst-bib program's logic: iterates through bib URLs, downloads the file from GitHub, and writes it to a local directory. Parameters ---------- local_dir : `str` Directory to write bib files into. Returns ------- error_count : `int` Number of download errors.
Below is the the instruction that describes the task: ### Input: Run the refresh-lsst-bib program's logic: iterates through bib URLs, downloads the file from GitHub, and writes it to a local directory. Parameters ---------- local_dir : `str` Directory to write bib files into. Returns ------- error_count : `int` Number of download errors. ### Response: def process_bib_files(local_dir): """Run the refresh-lsst-bib program's logic: iterates through bib URLs, downloads the file from GitHub, and writes it to a local directory. Parameters ---------- local_dir : `str` Directory to write bib files into. Returns ------- error_count : `int` Number of download errors. """ logger = logging.getLogger(__name__) # check the output directory exists if not os.path.isdir(local_dir): logger.error('Output directory "{}" does not exist'.format(local_dir)) sys.exit(1) root_blob_url = ('https://raw.githubusercontent.com/lsst/lsst-texmf/' 'master/texmf/bibtex/bib/') bib_filenames = ['books.bib', 'lsst-dm.bib', 'lsst.bib', 'refs.bib', 'refs_ads.bib'] error_count = 0 for bib_filename in bib_filenames: url = urllib.parse.urljoin(root_blob_url, bib_filename) logger.info('Downloading {}'.format(url)) try: content = _get_content(url) except requests.HTTPError as e: logger.exception(str(e)) logger.warning('Could not download {}'.format(url)) error_count += 1 continue local_filename = os.path.join(local_dir, bib_filename) with open(local_filename, 'w') as f: f.write(content) return error_count
def detect(byte_str): """ Detect the encoding of the given byte string. :param byte_str: The byte sequence to examine. :type byte_str: ``bytes`` or ``bytearray`` """ if not isinstance(byte_str, bytearray): if not isinstance(byte_str, bytes): raise TypeError('Expected object of type bytes or bytearray, got: ' '{0}'.format(type(byte_str))) else: byte_str = bytearray(byte_str) detector = UniversalDetector() detector.feed(byte_str) return detector.close()
Detect the encoding of the given byte string. :param byte_str: The byte sequence to examine. :type byte_str: ``bytes`` or ``bytearray``
Below is the the instruction that describes the task: ### Input: Detect the encoding of the given byte string. :param byte_str: The byte sequence to examine. :type byte_str: ``bytes`` or ``bytearray`` ### Response: def detect(byte_str): """ Detect the encoding of the given byte string. :param byte_str: The byte sequence to examine. :type byte_str: ``bytes`` or ``bytearray`` """ if not isinstance(byte_str, bytearray): if not isinstance(byte_str, bytes): raise TypeError('Expected object of type bytes or bytearray, got: ' '{0}'.format(type(byte_str))) else: byte_str = bytearray(byte_str) detector = UniversalDetector() detector.feed(byte_str) return detector.close()
def _metadata_fetch(self, metadata_fields, label=None): """Takes a list of metadata fields, some of which can contain taxon names or taxon IDs, and returns a DataFrame with transformed data that can be used for plotting. Parameters ---------- metadata_fields : `list` of `string` A list of metadata fields, taxon names, or taxon IDs to fetch and transform for display. label : `string` or `callable`, optional A metadata field (or function) used to label each analysis. If passing a function, a dict containing the metadata for each analysis is passed as the first and only positional argument. The callable function must return a string. If this argument is not given, and "Label" is in `metadata_fields`, "Label" will be set to the filename associated with an analysis. Notes ----- Taxon names and IDs are transformed into the relative abundances of those taxa within their own rank. For example, 'Bacteroides' will return the relative abundances of 'Bacteroides' among all taxa of rank genus. Taxon IDs are stored as strings in `ClassificationsDataFrame` and are coerced to strings if integers are given. Metadata fields are returned as is, from the `self.metadata` DataFrame. If multiple metadata fields are specified in a tuple, their values are joined as strings separated by underscore. Multiple metadata fields in a tuple must both be categorical. That is, a numerical field and boolean can not be joined, or the result would be something like '87.4_True'. The 'Label' field name is transformed to '_display_name'. This lets us label points in plots by the name generated for each sample in `SampleCollection._collate_metadata`. Returns ------- `pandas.DataFrame` Columns are renamed (if applicable) metadata fields and rows are `Classifications.id`. Elements are transformed values. Not all metadata fields will have been renamed, but will be present in the below `dict` nonetheless. `dict` Keys are metadata fields and values are renamed metadata fields. This can be used to map metadata fields which were passed to this function, to prettier names. For example, if 'bacteroid' is passed, it will be matched with the Bacteroides genus and renamed to 'Bacteroides (816)', which includes its taxon ID. """ import pandas as pd help_metadata = ", ".join(self.metadata.keys()) magic_metadata = pd.DataFrame({"classification_id": self._results.index}).set_index( "classification_id" ) # if user passed label kwarg but didn't put "Label" in the fields, assume the user wants # that field added if label is not None and "Label" not in metadata_fields: metadata_fields.append("Label") # if we magically rename fields, keep track magic_fields = {} for f in set([f for f in metadata_fields if f]): if isinstance(f, tuple): # joined categorical metadata for field in f: if field not in self.metadata: raise OneCodexException( "Field {} not found. Choose from: {}".format(field, help_metadata) ) if not ( pd.api.types.is_bool_dtype(self.metadata[field]) or pd.api.types.is_categorical_dtype(self.metadata[field]) # noqa or pd.api.types.is_object_dtype(self.metadata[field]) # noqa ): raise OneCodexException( "When specifying multiple metadata fields, all must be categorical" ) # concatenate the columns together with underscores composite_field = "_".join(f) magic_metadata[composite_field] = "" magic_metadata[composite_field] = ( magic_metadata[composite_field] .str.cat([self.metadata[field].astype(str) for field in f], sep="_") .str.lstrip("_") ) magic_fields[f] = composite_field else: str_f = str(f) if str_f == "Label": magic_metadata[str_f] = self.metadata["filename"] magic_fields[f] = str_f if isinstance(label, six.string_types): if label in self.metadata.columns: magic_metadata[str_f] = self.metadata[label] else: raise OneCodexException( "Label field {} not found. Choose from: {}".format( label, help_metadata ) ) elif callable(label): for classification_id, metadata in self.metadata.to_dict( orient="index" ).items(): c_id_label = label(metadata) if not isinstance(c_id_label, six.string_types): raise OneCodexException( "Expected string from label function, got: {}".format( type(c_id_label).__name__ ) ) magic_metadata.loc[classification_id, "Label"] = c_id_label elif label is not None: raise OneCodexException( "Expected string or callable for label, got: {}".format( type(label).__name__ ) ) elif str_f in self.metadata: # exactly matches existing metadata field magic_metadata[f] = self.metadata[str_f] magic_fields[f] = str_f elif str_f in self._results.keys(): # is a tax_id tax_name = self.taxonomy["name"][str_f] # report within-rank abundance df = self.to_df(rank=self.taxonomy["rank"][str_f]) renamed_field = "{} ({})".format(tax_name, str_f) magic_metadata[renamed_field] = df[str_f] magic_fields[f] = renamed_field else: # try to match it up with a taxon name hits = [] # don't both searching if the query is really short if len(str_f) > 4: for tax_id, tax_name in zip(self.taxonomy.index, self.taxonomy["name"]): # if it's an exact match, use that and skip the rest if str_f.lower() == tax_name.lower(): hits = [(tax_id, tax_name)] break # otherwise, keep trying to match elif str_f.lower() in tax_name.lower(): hits.append((tax_id, tax_name)) # take the hit with the lowest tax_id hits = sorted(hits, key=lambda x: int(x[0])) if hits: # report within-rank abundance df = self.to_df(rank=self.taxonomy["rank"][hits[0][0]]) renamed_field = "{} ({})".format(hits[0][1], hits[0][0]) magic_metadata[renamed_field] = df[hits[0][0]] magic_fields[f] = renamed_field else: # matched nothing raise OneCodexException( "Field or taxon {} not found. Choose from: {}".format( str_f, help_metadata ) ) return magic_metadata, magic_fields
Takes a list of metadata fields, some of which can contain taxon names or taxon IDs, and returns a DataFrame with transformed data that can be used for plotting. Parameters ---------- metadata_fields : `list` of `string` A list of metadata fields, taxon names, or taxon IDs to fetch and transform for display. label : `string` or `callable`, optional A metadata field (or function) used to label each analysis. If passing a function, a dict containing the metadata for each analysis is passed as the first and only positional argument. The callable function must return a string. If this argument is not given, and "Label" is in `metadata_fields`, "Label" will be set to the filename associated with an analysis. Notes ----- Taxon names and IDs are transformed into the relative abundances of those taxa within their own rank. For example, 'Bacteroides' will return the relative abundances of 'Bacteroides' among all taxa of rank genus. Taxon IDs are stored as strings in `ClassificationsDataFrame` and are coerced to strings if integers are given. Metadata fields are returned as is, from the `self.metadata` DataFrame. If multiple metadata fields are specified in a tuple, their values are joined as strings separated by underscore. Multiple metadata fields in a tuple must both be categorical. That is, a numerical field and boolean can not be joined, or the result would be something like '87.4_True'. The 'Label' field name is transformed to '_display_name'. This lets us label points in plots by the name generated for each sample in `SampleCollection._collate_metadata`. Returns ------- `pandas.DataFrame` Columns are renamed (if applicable) metadata fields and rows are `Classifications.id`. Elements are transformed values. Not all metadata fields will have been renamed, but will be present in the below `dict` nonetheless. `dict` Keys are metadata fields and values are renamed metadata fields. This can be used to map metadata fields which were passed to this function, to prettier names. For example, if 'bacteroid' is passed, it will be matched with the Bacteroides genus and renamed to 'Bacteroides (816)', which includes its taxon ID.
Below is the the instruction that describes the task: ### Input: Takes a list of metadata fields, some of which can contain taxon names or taxon IDs, and returns a DataFrame with transformed data that can be used for plotting. Parameters ---------- metadata_fields : `list` of `string` A list of metadata fields, taxon names, or taxon IDs to fetch and transform for display. label : `string` or `callable`, optional A metadata field (or function) used to label each analysis. If passing a function, a dict containing the metadata for each analysis is passed as the first and only positional argument. The callable function must return a string. If this argument is not given, and "Label" is in `metadata_fields`, "Label" will be set to the filename associated with an analysis. Notes ----- Taxon names and IDs are transformed into the relative abundances of those taxa within their own rank. For example, 'Bacteroides' will return the relative abundances of 'Bacteroides' among all taxa of rank genus. Taxon IDs are stored as strings in `ClassificationsDataFrame` and are coerced to strings if integers are given. Metadata fields are returned as is, from the `self.metadata` DataFrame. If multiple metadata fields are specified in a tuple, their values are joined as strings separated by underscore. Multiple metadata fields in a tuple must both be categorical. That is, a numerical field and boolean can not be joined, or the result would be something like '87.4_True'. The 'Label' field name is transformed to '_display_name'. This lets us label points in plots by the name generated for each sample in `SampleCollection._collate_metadata`. Returns ------- `pandas.DataFrame` Columns are renamed (if applicable) metadata fields and rows are `Classifications.id`. Elements are transformed values. Not all metadata fields will have been renamed, but will be present in the below `dict` nonetheless. `dict` Keys are metadata fields and values are renamed metadata fields. This can be used to map metadata fields which were passed to this function, to prettier names. For example, if 'bacteroid' is passed, it will be matched with the Bacteroides genus and renamed to 'Bacteroides (816)', which includes its taxon ID. ### Response: def _metadata_fetch(self, metadata_fields, label=None): """Takes a list of metadata fields, some of which can contain taxon names or taxon IDs, and returns a DataFrame with transformed data that can be used for plotting. Parameters ---------- metadata_fields : `list` of `string` A list of metadata fields, taxon names, or taxon IDs to fetch and transform for display. label : `string` or `callable`, optional A metadata field (or function) used to label each analysis. If passing a function, a dict containing the metadata for each analysis is passed as the first and only positional argument. The callable function must return a string. If this argument is not given, and "Label" is in `metadata_fields`, "Label" will be set to the filename associated with an analysis. Notes ----- Taxon names and IDs are transformed into the relative abundances of those taxa within their own rank. For example, 'Bacteroides' will return the relative abundances of 'Bacteroides' among all taxa of rank genus. Taxon IDs are stored as strings in `ClassificationsDataFrame` and are coerced to strings if integers are given. Metadata fields are returned as is, from the `self.metadata` DataFrame. If multiple metadata fields are specified in a tuple, their values are joined as strings separated by underscore. Multiple metadata fields in a tuple must both be categorical. That is, a numerical field and boolean can not be joined, or the result would be something like '87.4_True'. The 'Label' field name is transformed to '_display_name'. This lets us label points in plots by the name generated for each sample in `SampleCollection._collate_metadata`. Returns ------- `pandas.DataFrame` Columns are renamed (if applicable) metadata fields and rows are `Classifications.id`. Elements are transformed values. Not all metadata fields will have been renamed, but will be present in the below `dict` nonetheless. `dict` Keys are metadata fields and values are renamed metadata fields. This can be used to map metadata fields which were passed to this function, to prettier names. For example, if 'bacteroid' is passed, it will be matched with the Bacteroides genus and renamed to 'Bacteroides (816)', which includes its taxon ID. """ import pandas as pd help_metadata = ", ".join(self.metadata.keys()) magic_metadata = pd.DataFrame({"classification_id": self._results.index}).set_index( "classification_id" ) # if user passed label kwarg but didn't put "Label" in the fields, assume the user wants # that field added if label is not None and "Label" not in metadata_fields: metadata_fields.append("Label") # if we magically rename fields, keep track magic_fields = {} for f in set([f for f in metadata_fields if f]): if isinstance(f, tuple): # joined categorical metadata for field in f: if field not in self.metadata: raise OneCodexException( "Field {} not found. Choose from: {}".format(field, help_metadata) ) if not ( pd.api.types.is_bool_dtype(self.metadata[field]) or pd.api.types.is_categorical_dtype(self.metadata[field]) # noqa or pd.api.types.is_object_dtype(self.metadata[field]) # noqa ): raise OneCodexException( "When specifying multiple metadata fields, all must be categorical" ) # concatenate the columns together with underscores composite_field = "_".join(f) magic_metadata[composite_field] = "" magic_metadata[composite_field] = ( magic_metadata[composite_field] .str.cat([self.metadata[field].astype(str) for field in f], sep="_") .str.lstrip("_") ) magic_fields[f] = composite_field else: str_f = str(f) if str_f == "Label": magic_metadata[str_f] = self.metadata["filename"] magic_fields[f] = str_f if isinstance(label, six.string_types): if label in self.metadata.columns: magic_metadata[str_f] = self.metadata[label] else: raise OneCodexException( "Label field {} not found. Choose from: {}".format( label, help_metadata ) ) elif callable(label): for classification_id, metadata in self.metadata.to_dict( orient="index" ).items(): c_id_label = label(metadata) if not isinstance(c_id_label, six.string_types): raise OneCodexException( "Expected string from label function, got: {}".format( type(c_id_label).__name__ ) ) magic_metadata.loc[classification_id, "Label"] = c_id_label elif label is not None: raise OneCodexException( "Expected string or callable for label, got: {}".format( type(label).__name__ ) ) elif str_f in self.metadata: # exactly matches existing metadata field magic_metadata[f] = self.metadata[str_f] magic_fields[f] = str_f elif str_f in self._results.keys(): # is a tax_id tax_name = self.taxonomy["name"][str_f] # report within-rank abundance df = self.to_df(rank=self.taxonomy["rank"][str_f]) renamed_field = "{} ({})".format(tax_name, str_f) magic_metadata[renamed_field] = df[str_f] magic_fields[f] = renamed_field else: # try to match it up with a taxon name hits = [] # don't both searching if the query is really short if len(str_f) > 4: for tax_id, tax_name in zip(self.taxonomy.index, self.taxonomy["name"]): # if it's an exact match, use that and skip the rest if str_f.lower() == tax_name.lower(): hits = [(tax_id, tax_name)] break # otherwise, keep trying to match elif str_f.lower() in tax_name.lower(): hits.append((tax_id, tax_name)) # take the hit with the lowest tax_id hits = sorted(hits, key=lambda x: int(x[0])) if hits: # report within-rank abundance df = self.to_df(rank=self.taxonomy["rank"][hits[0][0]]) renamed_field = "{} ({})".format(hits[0][1], hits[0][0]) magic_metadata[renamed_field] = df[hits[0][0]] magic_fields[f] = renamed_field else: # matched nothing raise OneCodexException( "Field or taxon {} not found. Choose from: {}".format( str_f, help_metadata ) ) return magic_metadata, magic_fields
def rtc_as_set(self): """Returns current RTC AS configured for current neighbors. """ rtc_as_set = set() for neigh in self._neighbors.values(): rtc_as_set.add(neigh.rtc_as) return rtc_as_set
Returns current RTC AS configured for current neighbors.
Below is the the instruction that describes the task: ### Input: Returns current RTC AS configured for current neighbors. ### Response: def rtc_as_set(self): """Returns current RTC AS configured for current neighbors. """ rtc_as_set = set() for neigh in self._neighbors.values(): rtc_as_set.add(neigh.rtc_as) return rtc_as_set
def to_dict(self): """ Returns: dict: Concise represented as a dictionary. """ final_res = { "param": self._param, "unused_param": self.unused_param, "execution_time": self._exec_time, "output": {"accuracy": self.get_accuracy(), "weights": self.get_weights(), "splines": self._splines } } return final_res
Returns: dict: Concise represented as a dictionary.
Below is the the instruction that describes the task: ### Input: Returns: dict: Concise represented as a dictionary. ### Response: def to_dict(self): """ Returns: dict: Concise represented as a dictionary. """ final_res = { "param": self._param, "unused_param": self.unused_param, "execution_time": self._exec_time, "output": {"accuracy": self.get_accuracy(), "weights": self.get_weights(), "splines": self._splines } } return final_res
def get_difference_model(self, category): """ Get the equation corresponding to a variation wrt category. For example if:: modelstr = { 'full' :'H(I) + B', 'dH' : 'dH(I)', 'dI' : 'H(dI)', 'dB' : 'dB' } varmap = {'H': 'psf', 'I': 'obj', 'B': 'bkg'} then ``get_difference_model('obj') == modelstr['dI'] == 'H(dI)'`` """ name = self.diffname(self.ivarmap[category]) return self.modelstr.get(name)
Get the equation corresponding to a variation wrt category. For example if:: modelstr = { 'full' :'H(I) + B', 'dH' : 'dH(I)', 'dI' : 'H(dI)', 'dB' : 'dB' } varmap = {'H': 'psf', 'I': 'obj', 'B': 'bkg'} then ``get_difference_model('obj') == modelstr['dI'] == 'H(dI)'``
Below is the the instruction that describes the task: ### Input: Get the equation corresponding to a variation wrt category. For example if:: modelstr = { 'full' :'H(I) + B', 'dH' : 'dH(I)', 'dI' : 'H(dI)', 'dB' : 'dB' } varmap = {'H': 'psf', 'I': 'obj', 'B': 'bkg'} then ``get_difference_model('obj') == modelstr['dI'] == 'H(dI)'`` ### Response: def get_difference_model(self, category): """ Get the equation corresponding to a variation wrt category. For example if:: modelstr = { 'full' :'H(I) + B', 'dH' : 'dH(I)', 'dI' : 'H(dI)', 'dB' : 'dB' } varmap = {'H': 'psf', 'I': 'obj', 'B': 'bkg'} then ``get_difference_model('obj') == modelstr['dI'] == 'H(dI)'`` """ name = self.diffname(self.ivarmap[category]) return self.modelstr.get(name)
def update_record(cls, fqdn, name, type, value, ttl, content): """Update all records for a domain.""" data = { "rrset_name": name, "rrset_type": type, "rrset_values": value, } if ttl: data['rrset_ttl'] = int(ttl) meta = cls.get_fqdn_info(fqdn) if content: url = meta['domain_records_href'] kwargs = {'headers': {'Content-Type': 'text/plain'}, 'data': content} return cls.json_put(url, **kwargs) url = '%s/domains/%s/records/%s/%s' % (cls.api_url, fqdn, name, type) return cls.json_put(url, data=json.dumps(data))
Update all records for a domain.
Below is the the instruction that describes the task: ### Input: Update all records for a domain. ### Response: def update_record(cls, fqdn, name, type, value, ttl, content): """Update all records for a domain.""" data = { "rrset_name": name, "rrset_type": type, "rrset_values": value, } if ttl: data['rrset_ttl'] = int(ttl) meta = cls.get_fqdn_info(fqdn) if content: url = meta['domain_records_href'] kwargs = {'headers': {'Content-Type': 'text/plain'}, 'data': content} return cls.json_put(url, **kwargs) url = '%s/domains/%s/records/%s/%s' % (cls.api_url, fqdn, name, type) return cls.json_put(url, data=json.dumps(data))
def _finalize_batch(self): """ Method to finalize the batch, this will iterate over the _batches dict and create a PmtInf node for each batch. The correct information (from the batch_key and batch_totals) will be inserted and the batch transaction nodes will be folded. Finally, the batches will be added to the main XML. """ for batch_meta, batch_nodes in self._batches.items(): batch_meta_split = batch_meta.split("::") PmtInf_nodes = self._create_PmtInf_node() PmtInf_nodes['PmtInfIdNode'].text = make_id(self._config['name']) PmtInf_nodes['PmtMtdNode'].text = "DD" PmtInf_nodes['BtchBookgNode'].text = "true" PmtInf_nodes['Cd_SvcLvl_Node'].text = "SEPA" PmtInf_nodes['Cd_LclInstrm_Node'].text = self._config['instrument'] PmtInf_nodes['SeqTpNode'].text = batch_meta_split[0] PmtInf_nodes['ReqdColltnDtNode'].text = batch_meta_split[1] PmtInf_nodes['Nm_Cdtr_Node'].text = self._config['name'] PmtInf_nodes['IBAN_CdtrAcct_Node'].text = self._config['IBAN'] if 'BIC' in self._config: PmtInf_nodes['BIC_CdtrAgt_Node'].text = self._config['BIC'] PmtInf_nodes['ChrgBrNode'].text = "SLEV" PmtInf_nodes['Nm_CdtrSchmeId_Node'].text = self._config['name'] PmtInf_nodes['Id_Othr_Node'].text = self._config['creditor_id'] PmtInf_nodes['PrtryNode'].text = "SEPA" PmtInf_nodes['NbOfTxsNode'].text = str(len(batch_nodes)) PmtInf_nodes['CtrlSumNode'].text = int_to_decimal_str(self._batch_totals[batch_meta]) PmtInf_nodes['PmtInfNode'].append(PmtInf_nodes['PmtInfIdNode']) PmtInf_nodes['PmtInfNode'].append(PmtInf_nodes['PmtMtdNode']) PmtInf_nodes['PmtInfNode'].append(PmtInf_nodes['BtchBookgNode']) PmtInf_nodes['PmtInfNode'].append(PmtInf_nodes['NbOfTxsNode']) PmtInf_nodes['PmtInfNode'].append(PmtInf_nodes['CtrlSumNode']) PmtInf_nodes['SvcLvlNode'].append(PmtInf_nodes['Cd_SvcLvl_Node']) PmtInf_nodes['LclInstrmNode'].append( PmtInf_nodes['Cd_LclInstrm_Node']) PmtInf_nodes['PmtTpInfNode'].append(PmtInf_nodes['SvcLvlNode']) PmtInf_nodes['PmtTpInfNode'].append(PmtInf_nodes['LclInstrmNode']) PmtInf_nodes['PmtTpInfNode'].append(PmtInf_nodes['SeqTpNode']) PmtInf_nodes['PmtInfNode'].append(PmtInf_nodes['PmtTpInfNode']) PmtInf_nodes['PmtInfNode'].append(PmtInf_nodes['ReqdColltnDtNode']) PmtInf_nodes['CdtrNode'].append(PmtInf_nodes['Nm_Cdtr_Node']) PmtInf_nodes['PmtInfNode'].append(PmtInf_nodes['CdtrNode']) PmtInf_nodes['Id_CdtrAcct_Node'].append( PmtInf_nodes['IBAN_CdtrAcct_Node']) PmtInf_nodes['CdtrAcctNode'].append( PmtInf_nodes['Id_CdtrAcct_Node']) PmtInf_nodes['PmtInfNode'].append(PmtInf_nodes['CdtrAcctNode']) if 'BIC' in self._config: PmtInf_nodes['FinInstnId_CdtrAgt_Node'].append( PmtInf_nodes['BIC_CdtrAgt_Node']) PmtInf_nodes['CdtrAgtNode'].append( PmtInf_nodes['FinInstnId_CdtrAgt_Node']) PmtInf_nodes['PmtInfNode'].append(PmtInf_nodes['CdtrAgtNode']) PmtInf_nodes['PmtInfNode'].append(PmtInf_nodes['ChrgBrNode']) if self.schema == 'pain.008.001.02': PmtInf_nodes['CdtrSchmeIdNode'].append(PmtInf_nodes['Nm_CdtrSchmeId_Node']) PmtInf_nodes['OthrNode'].append(PmtInf_nodes['Id_Othr_Node']) PmtInf_nodes['SchmeNmNode'].append(PmtInf_nodes['PrtryNode']) PmtInf_nodes['OthrNode'].append(PmtInf_nodes['SchmeNmNode']) PmtInf_nodes['PrvtIdNode'].append(PmtInf_nodes['OthrNode']) PmtInf_nodes['Id_CdtrSchmeId_Node'].append( PmtInf_nodes['PrvtIdNode']) PmtInf_nodes['CdtrSchmeIdNode'].append( PmtInf_nodes['Id_CdtrSchmeId_Node']) PmtInf_nodes['PmtInfNode'].append(PmtInf_nodes['CdtrSchmeIdNode']) for txnode in batch_nodes: PmtInf_nodes['PmtInfNode'].append(txnode) CstmrDrctDbtInitn_node = self._xml.find('CstmrDrctDbtInitn') CstmrDrctDbtInitn_node.append(PmtInf_nodes['PmtInfNode'])
Method to finalize the batch, this will iterate over the _batches dict and create a PmtInf node for each batch. The correct information (from the batch_key and batch_totals) will be inserted and the batch transaction nodes will be folded. Finally, the batches will be added to the main XML.
Below is the the instruction that describes the task: ### Input: Method to finalize the batch, this will iterate over the _batches dict and create a PmtInf node for each batch. The correct information (from the batch_key and batch_totals) will be inserted and the batch transaction nodes will be folded. Finally, the batches will be added to the main XML. ### Response: def _finalize_batch(self): """ Method to finalize the batch, this will iterate over the _batches dict and create a PmtInf node for each batch. The correct information (from the batch_key and batch_totals) will be inserted and the batch transaction nodes will be folded. Finally, the batches will be added to the main XML. """ for batch_meta, batch_nodes in self._batches.items(): batch_meta_split = batch_meta.split("::") PmtInf_nodes = self._create_PmtInf_node() PmtInf_nodes['PmtInfIdNode'].text = make_id(self._config['name']) PmtInf_nodes['PmtMtdNode'].text = "DD" PmtInf_nodes['BtchBookgNode'].text = "true" PmtInf_nodes['Cd_SvcLvl_Node'].text = "SEPA" PmtInf_nodes['Cd_LclInstrm_Node'].text = self._config['instrument'] PmtInf_nodes['SeqTpNode'].text = batch_meta_split[0] PmtInf_nodes['ReqdColltnDtNode'].text = batch_meta_split[1] PmtInf_nodes['Nm_Cdtr_Node'].text = self._config['name'] PmtInf_nodes['IBAN_CdtrAcct_Node'].text = self._config['IBAN'] if 'BIC' in self._config: PmtInf_nodes['BIC_CdtrAgt_Node'].text = self._config['BIC'] PmtInf_nodes['ChrgBrNode'].text = "SLEV" PmtInf_nodes['Nm_CdtrSchmeId_Node'].text = self._config['name'] PmtInf_nodes['Id_Othr_Node'].text = self._config['creditor_id'] PmtInf_nodes['PrtryNode'].text = "SEPA" PmtInf_nodes['NbOfTxsNode'].text = str(len(batch_nodes)) PmtInf_nodes['CtrlSumNode'].text = int_to_decimal_str(self._batch_totals[batch_meta]) PmtInf_nodes['PmtInfNode'].append(PmtInf_nodes['PmtInfIdNode']) PmtInf_nodes['PmtInfNode'].append(PmtInf_nodes['PmtMtdNode']) PmtInf_nodes['PmtInfNode'].append(PmtInf_nodes['BtchBookgNode']) PmtInf_nodes['PmtInfNode'].append(PmtInf_nodes['NbOfTxsNode']) PmtInf_nodes['PmtInfNode'].append(PmtInf_nodes['CtrlSumNode']) PmtInf_nodes['SvcLvlNode'].append(PmtInf_nodes['Cd_SvcLvl_Node']) PmtInf_nodes['LclInstrmNode'].append( PmtInf_nodes['Cd_LclInstrm_Node']) PmtInf_nodes['PmtTpInfNode'].append(PmtInf_nodes['SvcLvlNode']) PmtInf_nodes['PmtTpInfNode'].append(PmtInf_nodes['LclInstrmNode']) PmtInf_nodes['PmtTpInfNode'].append(PmtInf_nodes['SeqTpNode']) PmtInf_nodes['PmtInfNode'].append(PmtInf_nodes['PmtTpInfNode']) PmtInf_nodes['PmtInfNode'].append(PmtInf_nodes['ReqdColltnDtNode']) PmtInf_nodes['CdtrNode'].append(PmtInf_nodes['Nm_Cdtr_Node']) PmtInf_nodes['PmtInfNode'].append(PmtInf_nodes['CdtrNode']) PmtInf_nodes['Id_CdtrAcct_Node'].append( PmtInf_nodes['IBAN_CdtrAcct_Node']) PmtInf_nodes['CdtrAcctNode'].append( PmtInf_nodes['Id_CdtrAcct_Node']) PmtInf_nodes['PmtInfNode'].append(PmtInf_nodes['CdtrAcctNode']) if 'BIC' in self._config: PmtInf_nodes['FinInstnId_CdtrAgt_Node'].append( PmtInf_nodes['BIC_CdtrAgt_Node']) PmtInf_nodes['CdtrAgtNode'].append( PmtInf_nodes['FinInstnId_CdtrAgt_Node']) PmtInf_nodes['PmtInfNode'].append(PmtInf_nodes['CdtrAgtNode']) PmtInf_nodes['PmtInfNode'].append(PmtInf_nodes['ChrgBrNode']) if self.schema == 'pain.008.001.02': PmtInf_nodes['CdtrSchmeIdNode'].append(PmtInf_nodes['Nm_CdtrSchmeId_Node']) PmtInf_nodes['OthrNode'].append(PmtInf_nodes['Id_Othr_Node']) PmtInf_nodes['SchmeNmNode'].append(PmtInf_nodes['PrtryNode']) PmtInf_nodes['OthrNode'].append(PmtInf_nodes['SchmeNmNode']) PmtInf_nodes['PrvtIdNode'].append(PmtInf_nodes['OthrNode']) PmtInf_nodes['Id_CdtrSchmeId_Node'].append( PmtInf_nodes['PrvtIdNode']) PmtInf_nodes['CdtrSchmeIdNode'].append( PmtInf_nodes['Id_CdtrSchmeId_Node']) PmtInf_nodes['PmtInfNode'].append(PmtInf_nodes['CdtrSchmeIdNode']) for txnode in batch_nodes: PmtInf_nodes['PmtInfNode'].append(txnode) CstmrDrctDbtInitn_node = self._xml.find('CstmrDrctDbtInitn') CstmrDrctDbtInitn_node.append(PmtInf_nodes['PmtInfNode'])
def validate_srec_checksum(srec): """ Validate if the checksum of the supplied s-record is valid Returns: True if valid, False if not """ checksum = srec[len(srec)-2:] # Strip the original checksum and compare with the computed one if compute_srec_checksum(srec[:len(srec) - 2]) == int(checksum, 16): return True else: return False
Validate if the checksum of the supplied s-record is valid Returns: True if valid, False if not
Below is the the instruction that describes the task: ### Input: Validate if the checksum of the supplied s-record is valid Returns: True if valid, False if not ### Response: def validate_srec_checksum(srec): """ Validate if the checksum of the supplied s-record is valid Returns: True if valid, False if not """ checksum = srec[len(srec)-2:] # Strip the original checksum and compare with the computed one if compute_srec_checksum(srec[:len(srec) - 2]) == int(checksum, 16): return True else: return False
def _query_mssql(self): """ Queries MSSQL and returns a cursor of results. :return: mssql cursor """ mssql = MsSqlHook(mssql_conn_id=self.mssql_conn_id) conn = mssql.get_conn() cursor = conn.cursor() cursor.execute(self.sql) return cursor
Queries MSSQL and returns a cursor of results. :return: mssql cursor
Below is the the instruction that describes the task: ### Input: Queries MSSQL and returns a cursor of results. :return: mssql cursor ### Response: def _query_mssql(self): """ Queries MSSQL and returns a cursor of results. :return: mssql cursor """ mssql = MsSqlHook(mssql_conn_id=self.mssql_conn_id) conn = mssql.get_conn() cursor = conn.cursor() cursor.execute(self.sql) return cursor
def load_matrix_sparse(filename): coo = np.load(filename) """Check if coo is (M, 3) ndarray""" if len(coo.shape) == 2 and coo.shape[1] == 3: row = coo[:, 0] col = coo[:, 1] values = coo[:, 2] """Check if imaginary part of row and col is zero""" if np.all(np.isreal(row)) and np.all(np.isreal(col)): row = row.real col = col.real """Check if first and second column contain only integer entries""" if np.all(is_integer(row)) and np.all(is_integer(col)): """Convert row and col to int""" row = row.astype(int) col = col.astype(int) """Create coo-matrix""" A = scipy.sparse.coo_matrix((values, (row, col))) return A else: raise ValueError('File contains non-integer entries for row and col.') else: raise ValueError('File contains complex entries for row and col.') else: raise ValueError('Given file is not a sparse matrix in coo-format.')
Check if coo is (M, 3) ndarray
Below is the the instruction that describes the task: ### Input: Check if coo is (M, 3) ndarray ### Response: def load_matrix_sparse(filename): coo = np.load(filename) """Check if coo is (M, 3) ndarray""" if len(coo.shape) == 2 and coo.shape[1] == 3: row = coo[:, 0] col = coo[:, 1] values = coo[:, 2] """Check if imaginary part of row and col is zero""" if np.all(np.isreal(row)) and np.all(np.isreal(col)): row = row.real col = col.real """Check if first and second column contain only integer entries""" if np.all(is_integer(row)) and np.all(is_integer(col)): """Convert row and col to int""" row = row.astype(int) col = col.astype(int) """Create coo-matrix""" A = scipy.sparse.coo_matrix((values, (row, col))) return A else: raise ValueError('File contains non-integer entries for row and col.') else: raise ValueError('File contains complex entries for row and col.') else: raise ValueError('Given file is not a sparse matrix in coo-format.')
def get_rest_apis(self, project_name): """ Generator that allows to iterate per every available apis. """ all_apis = self.apigateway_client.get_rest_apis( limit=500 ) for api in all_apis['items']: if api['name'] != project_name: continue yield api
Generator that allows to iterate per every available apis.
Below is the the instruction that describes the task: ### Input: Generator that allows to iterate per every available apis. ### Response: def get_rest_apis(self, project_name): """ Generator that allows to iterate per every available apis. """ all_apis = self.apigateway_client.get_rest_apis( limit=500 ) for api in all_apis['items']: if api['name'] != project_name: continue yield api
def _pack_with_tf_ops(dataset, keys, length): """Helper-function for packing a dataset which has already been batched. See pack_dataset() Uses tf.while_loop. Slow. Args: dataset: a dataset containing padded batches of examples. keys: a list of strings length: an integer Returns: a dataset. """ empty_example = {} for k in keys: empty_example[k] = tf.zeros([0], dtype=tf.int32) empty_example[k + "_position"] = tf.zeros([0], dtype=tf.int32) keys_etc = empty_example.keys() def write_packed_example(partial, outputs): new_partial = empty_example.copy() new_outputs = {} for k in keys_etc: new_outputs[k] = outputs[k].write( outputs[k].size(), tf.pad(partial[k], [[0, length - tf.size(partial[k])]])) return new_partial, new_outputs def map_fn(x): """Internal function to flat_map over. Consumes a batch of input examples and produces a variable number of output examples. Args: x: a single example Returns: a tf.data.Dataset """ partial = empty_example.copy() i = tf.zeros([], dtype=tf.int32) dynamic_batch_size = tf.shape(x[keys[0]])[0] outputs = {} for k in keys: outputs[k] = tf.TensorArray( tf.int32, size=0, dynamic_size=True, element_shape=[length]) outputs[k + "_position"] = tf.TensorArray( tf.int32, size=0, dynamic_size=True, element_shape=[length]) def cond_fn(i, partial, outputs): del partial, outputs return i < dynamic_batch_size def body_fn(i, partial, outputs): """Body function for while_loop. Args: i: integer scalar partial: dictionary of Tensor (partially-constructed example) outputs: dictionary of TensorArray Returns: A triple containing the new values of the inputs. """ can_append = True one_example = {} for k in keys: val = tf.cast(x[k][i], tf.int32) val = val[:tf.reduce_sum(tf.cast(tf.not_equal(val, 0), tf.int32))] one_example[k] = val for k in keys: can_append = tf.logical_and( can_append, tf.less_equal( tf.size(partial[k]) + tf.size(one_example[k]), length)) def false_fn(): return write_packed_example(partial, outputs) def true_fn(): return partial, outputs partial, outputs = tf.cond(can_append, true_fn, false_fn) new_partial = {} for k in keys: new_seq = one_example[k][:length] new_seq_len = tf.size(new_seq) new_partial[k] = tf.concat([partial[k], new_seq], 0) new_partial[k + "_position"] = tf.concat( [partial[k + "_position"], tf.range(new_seq_len, dtype=tf.int32)], 0) partial = new_partial return i+1, partial, outputs i, partial, outputs = tf.while_loop( cond_fn, body_fn, (i, partial, outputs), back_prop=False, shape_invariants=( tf.TensorShape([]), {k: tf.TensorShape([None]) for k in keys_etc}, {k: tf.TensorShape(None) for k in keys_etc}, )) partial, outputs = write_packed_example(partial, outputs) packed = {k: outputs[k].stack() for k in keys_etc} for k in keys: packed[k + "_segmentation"] = ( tf.cumsum( tf.cast(tf.equal(packed[k + "_position"], 0), tf.int32), axis=1) * tf.cast(tf.not_equal(packed[k], 0), tf.int32)) return packed dataset = dataset.map(map_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE) return dataset.flat_map(tf.data.Dataset.from_tensor_slices)
Helper-function for packing a dataset which has already been batched. See pack_dataset() Uses tf.while_loop. Slow. Args: dataset: a dataset containing padded batches of examples. keys: a list of strings length: an integer Returns: a dataset.
Below is the the instruction that describes the task: ### Input: Helper-function for packing a dataset which has already been batched. See pack_dataset() Uses tf.while_loop. Slow. Args: dataset: a dataset containing padded batches of examples. keys: a list of strings length: an integer Returns: a dataset. ### Response: def _pack_with_tf_ops(dataset, keys, length): """Helper-function for packing a dataset which has already been batched. See pack_dataset() Uses tf.while_loop. Slow. Args: dataset: a dataset containing padded batches of examples. keys: a list of strings length: an integer Returns: a dataset. """ empty_example = {} for k in keys: empty_example[k] = tf.zeros([0], dtype=tf.int32) empty_example[k + "_position"] = tf.zeros([0], dtype=tf.int32) keys_etc = empty_example.keys() def write_packed_example(partial, outputs): new_partial = empty_example.copy() new_outputs = {} for k in keys_etc: new_outputs[k] = outputs[k].write( outputs[k].size(), tf.pad(partial[k], [[0, length - tf.size(partial[k])]])) return new_partial, new_outputs def map_fn(x): """Internal function to flat_map over. Consumes a batch of input examples and produces a variable number of output examples. Args: x: a single example Returns: a tf.data.Dataset """ partial = empty_example.copy() i = tf.zeros([], dtype=tf.int32) dynamic_batch_size = tf.shape(x[keys[0]])[0] outputs = {} for k in keys: outputs[k] = tf.TensorArray( tf.int32, size=0, dynamic_size=True, element_shape=[length]) outputs[k + "_position"] = tf.TensorArray( tf.int32, size=0, dynamic_size=True, element_shape=[length]) def cond_fn(i, partial, outputs): del partial, outputs return i < dynamic_batch_size def body_fn(i, partial, outputs): """Body function for while_loop. Args: i: integer scalar partial: dictionary of Tensor (partially-constructed example) outputs: dictionary of TensorArray Returns: A triple containing the new values of the inputs. """ can_append = True one_example = {} for k in keys: val = tf.cast(x[k][i], tf.int32) val = val[:tf.reduce_sum(tf.cast(tf.not_equal(val, 0), tf.int32))] one_example[k] = val for k in keys: can_append = tf.logical_and( can_append, tf.less_equal( tf.size(partial[k]) + tf.size(one_example[k]), length)) def false_fn(): return write_packed_example(partial, outputs) def true_fn(): return partial, outputs partial, outputs = tf.cond(can_append, true_fn, false_fn) new_partial = {} for k in keys: new_seq = one_example[k][:length] new_seq_len = tf.size(new_seq) new_partial[k] = tf.concat([partial[k], new_seq], 0) new_partial[k + "_position"] = tf.concat( [partial[k + "_position"], tf.range(new_seq_len, dtype=tf.int32)], 0) partial = new_partial return i+1, partial, outputs i, partial, outputs = tf.while_loop( cond_fn, body_fn, (i, partial, outputs), back_prop=False, shape_invariants=( tf.TensorShape([]), {k: tf.TensorShape([None]) for k in keys_etc}, {k: tf.TensorShape(None) for k in keys_etc}, )) partial, outputs = write_packed_example(partial, outputs) packed = {k: outputs[k].stack() for k in keys_etc} for k in keys: packed[k + "_segmentation"] = ( tf.cumsum( tf.cast(tf.equal(packed[k + "_position"], 0), tf.int32), axis=1) * tf.cast(tf.not_equal(packed[k], 0), tf.int32)) return packed dataset = dataset.map(map_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE) return dataset.flat_map(tf.data.Dataset.from_tensor_slices)
def get_objects_by_type_in_subtree(self, *types): """ :param types: requested object types. :return: all children of the specified types. """ typed_objects = self.get_objects_by_type(*types) for child in self.objects.values(): typed_objects += child.get_objects_by_type_in_subtree(*types) return typed_objects
:param types: requested object types. :return: all children of the specified types.
Below is the the instruction that describes the task: ### Input: :param types: requested object types. :return: all children of the specified types. ### Response: def get_objects_by_type_in_subtree(self, *types): """ :param types: requested object types. :return: all children of the specified types. """ typed_objects = self.get_objects_by_type(*types) for child in self.objects.values(): typed_objects += child.get_objects_by_type_in_subtree(*types) return typed_objects
def earth_accel2_df(IMU,IMU2,ATT): '''return earth frame acceleration vector from df log''' r = rotation_df(ATT) accel1 = Vector3(IMU.AccX, IMU.AccY, IMU.AccZ) accel2 = Vector3(IMU2.AccX, IMU2.AccY, IMU2.AccZ) accel = 0.5 * (accel1 + accel2) return r * accel
return earth frame acceleration vector from df log
Below is the the instruction that describes the task: ### Input: return earth frame acceleration vector from df log ### Response: def earth_accel2_df(IMU,IMU2,ATT): '''return earth frame acceleration vector from df log''' r = rotation_df(ATT) accel1 = Vector3(IMU.AccX, IMU.AccY, IMU.AccZ) accel2 = Vector3(IMU2.AccX, IMU2.AccY, IMU2.AccZ) accel = 0.5 * (accel1 + accel2) return r * accel
def strip_xss(html, whitelist=None, replacement="(removed)"): """ This function returns a tuple containing: * *html* with all non-whitelisted HTML tags replaced with *replacement*. * A `set()` containing the tags that were removed. Any tags that contain JavaScript, VBScript, or other known XSS/executable functions will also be removed. If *whitelist* is not given the following will be used:: whitelist = set([ 'a', 'abbr', 'aside', 'audio', 'bdi', 'bdo', 'blockquote', 'canvas', 'caption', 'code', 'col', 'colgroup', 'data', 'dd', 'del', 'details', 'div', 'dl', 'dt', 'em', 'figcaption', 'figure', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'ins', 'kbd', 'li', 'mark', 'ol', 'p', 'pre', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'small', 'source', 'span', 'strong', 'sub', 'summary', 'sup', 'table', 'td', 'th', 'time', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr' ]) .. note:: To disable the whitelisting simply set `whitelist="off"`. Example:: >>> html = '<span>Hello, exploit: <img src="javascript:alert(\"pwned!\")"></span>' >>> html, rejects = strip_xss(html) >>> print("'%s', Rejected: '%s'" % (html, " ".join(rejects))) '<span>Hello, exploit: (removed)</span>', Rejected: '<img src="javascript:alert("pwned!")">' .. note:: The default *replacement* is "(removed)". If *replacement* is "entities" bad HTML tags will be encoded into HTML entities. This allows things like <script>'whatever'</script> to be displayed without execution (which would be much less annoying to users that were merely trying to share a code example). Here's an example:: >>> html = '<span>Hello, exploit: <img src="javascript:alert(\"pwned!\")"></span>' >>> html, rejects = strip_xss(html, replacement="entities") >>> print(html) <span>Hello, exploit: &lt;img src="javascript:alert("pwned!")"&gt;</span> >>> print("Rejected: '%s'" % ", ".join(rejects)) Rejected: '<img src="javascript:alert("pwned!")">' **NOTE:** This function should work to protect against *all* `the XSS examples at OWASP <https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet>`_. Please `let us know <https://github.com/LiftoffSoftware/htmltag/issues>`_ if you find something we missed. """ re_html_tag = re.compile( # This matches HTML tags (if used correctly) "(?i)<\/?\w+((\s+\w+(\s*=\s*(?:\".*?\"|'.*?'|[^'\">\s]+))?)+\s*|\s*)\/?>") # This will match things like 'onmouseover=' ('on<whatever>=') on_events_re = re.compile('.*\s+(on[a-z]+\s*=).*') if not whitelist: # These are all pretty safe and covers most of what users would want in # terms of formatting and sharing media (images, audio, video, etc). whitelist = set([ 'a', 'abbr', 'aside', 'audio', 'bdi', 'bdo', 'blockquote', 'canvas', 'caption', 'code', 'col', 'colgroup', 'data', 'dd', 'del', 'details', 'div', 'dl', 'dt', 'em', 'figcaption', 'figure', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'ins', 'kbd', 'li', 'mark', 'ol', 'p', 'pre', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'small', 'source', 'span', 'strong', 'sub', 'summary', 'sup', 'table', 'td', 'th', 'time', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr' ]) elif whitelist == "off": whitelist = None # Disable it altogether bad_tags = set() for tag in re_html_tag.finditer(html): tag = tag.group() tag_lower = tag.lower() short_tag = tag_lower.split()[0].lstrip('</').rstrip('>') if whitelist and short_tag not in whitelist: bad_tags.add(tag) continue # Make sure the tag can't execute any JavaScript if "javascript:" in tag_lower: bad_tags.add(tag) continue # on<whatever> events are not allowed (just another XSS vuln) if on_events_re.search(tag_lower): bad_tags.add(tag) continue # Flash sucks if "fscommand" in tag_lower: bad_tags.add(tag) continue # I'd be impressed if an attacker tried this one (super obscure) if "seeksegmenttime" in tag_lower: bad_tags.add(tag) continue # Yes we'll protect IE users from themselves... if "vbscript:" in tag_lower: bad_tags.add(tag) continue if replacement == "entities": for bad_tag in bad_tags: escaped = cgi.escape(bad_tag).encode('ascii', 'xmlcharrefreplace') html = html.replace(bad_tag, escaped.decode('ascii')) else: for bad_tag in bad_tags: html = html.replace(bad_tag, replacement) return (html, bad_tags)
This function returns a tuple containing: * *html* with all non-whitelisted HTML tags replaced with *replacement*. * A `set()` containing the tags that were removed. Any tags that contain JavaScript, VBScript, or other known XSS/executable functions will also be removed. If *whitelist* is not given the following will be used:: whitelist = set([ 'a', 'abbr', 'aside', 'audio', 'bdi', 'bdo', 'blockquote', 'canvas', 'caption', 'code', 'col', 'colgroup', 'data', 'dd', 'del', 'details', 'div', 'dl', 'dt', 'em', 'figcaption', 'figure', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'ins', 'kbd', 'li', 'mark', 'ol', 'p', 'pre', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'small', 'source', 'span', 'strong', 'sub', 'summary', 'sup', 'table', 'td', 'th', 'time', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr' ]) .. note:: To disable the whitelisting simply set `whitelist="off"`. Example:: >>> html = '<span>Hello, exploit: <img src="javascript:alert(\"pwned!\")"></span>' >>> html, rejects = strip_xss(html) >>> print("'%s', Rejected: '%s'" % (html, " ".join(rejects))) '<span>Hello, exploit: (removed)</span>', Rejected: '<img src="javascript:alert("pwned!")">' .. note:: The default *replacement* is "(removed)". If *replacement* is "entities" bad HTML tags will be encoded into HTML entities. This allows things like <script>'whatever'</script> to be displayed without execution (which would be much less annoying to users that were merely trying to share a code example). Here's an example:: >>> html = '<span>Hello, exploit: <img src="javascript:alert(\"pwned!\")"></span>' >>> html, rejects = strip_xss(html, replacement="entities") >>> print(html) <span>Hello, exploit: &lt;img src="javascript:alert("pwned!")"&gt;</span> >>> print("Rejected: '%s'" % ", ".join(rejects)) Rejected: '<img src="javascript:alert("pwned!")">' **NOTE:** This function should work to protect against *all* `the XSS examples at OWASP <https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet>`_. Please `let us know <https://github.com/LiftoffSoftware/htmltag/issues>`_ if you find something we missed.
Below is the the instruction that describes the task: ### Input: This function returns a tuple containing: * *html* with all non-whitelisted HTML tags replaced with *replacement*. * A `set()` containing the tags that were removed. Any tags that contain JavaScript, VBScript, or other known XSS/executable functions will also be removed. If *whitelist* is not given the following will be used:: whitelist = set([ 'a', 'abbr', 'aside', 'audio', 'bdi', 'bdo', 'blockquote', 'canvas', 'caption', 'code', 'col', 'colgroup', 'data', 'dd', 'del', 'details', 'div', 'dl', 'dt', 'em', 'figcaption', 'figure', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'ins', 'kbd', 'li', 'mark', 'ol', 'p', 'pre', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'small', 'source', 'span', 'strong', 'sub', 'summary', 'sup', 'table', 'td', 'th', 'time', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr' ]) .. note:: To disable the whitelisting simply set `whitelist="off"`. Example:: >>> html = '<span>Hello, exploit: <img src="javascript:alert(\"pwned!\")"></span>' >>> html, rejects = strip_xss(html) >>> print("'%s', Rejected: '%s'" % (html, " ".join(rejects))) '<span>Hello, exploit: (removed)</span>', Rejected: '<img src="javascript:alert("pwned!")">' .. note:: The default *replacement* is "(removed)". If *replacement* is "entities" bad HTML tags will be encoded into HTML entities. This allows things like <script>'whatever'</script> to be displayed without execution (which would be much less annoying to users that were merely trying to share a code example). Here's an example:: >>> html = '<span>Hello, exploit: <img src="javascript:alert(\"pwned!\")"></span>' >>> html, rejects = strip_xss(html, replacement="entities") >>> print(html) <span>Hello, exploit: &lt;img src="javascript:alert("pwned!")"&gt;</span> >>> print("Rejected: '%s'" % ", ".join(rejects)) Rejected: '<img src="javascript:alert("pwned!")">' **NOTE:** This function should work to protect against *all* `the XSS examples at OWASP <https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet>`_. Please `let us know <https://github.com/LiftoffSoftware/htmltag/issues>`_ if you find something we missed. ### Response: def strip_xss(html, whitelist=None, replacement="(removed)"): """ This function returns a tuple containing: * *html* with all non-whitelisted HTML tags replaced with *replacement*. * A `set()` containing the tags that were removed. Any tags that contain JavaScript, VBScript, or other known XSS/executable functions will also be removed. If *whitelist* is not given the following will be used:: whitelist = set([ 'a', 'abbr', 'aside', 'audio', 'bdi', 'bdo', 'blockquote', 'canvas', 'caption', 'code', 'col', 'colgroup', 'data', 'dd', 'del', 'details', 'div', 'dl', 'dt', 'em', 'figcaption', 'figure', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'ins', 'kbd', 'li', 'mark', 'ol', 'p', 'pre', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'small', 'source', 'span', 'strong', 'sub', 'summary', 'sup', 'table', 'td', 'th', 'time', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr' ]) .. note:: To disable the whitelisting simply set `whitelist="off"`. Example:: >>> html = '<span>Hello, exploit: <img src="javascript:alert(\"pwned!\")"></span>' >>> html, rejects = strip_xss(html) >>> print("'%s', Rejected: '%s'" % (html, " ".join(rejects))) '<span>Hello, exploit: (removed)</span>', Rejected: '<img src="javascript:alert("pwned!")">' .. note:: The default *replacement* is "(removed)". If *replacement* is "entities" bad HTML tags will be encoded into HTML entities. This allows things like <script>'whatever'</script> to be displayed without execution (which would be much less annoying to users that were merely trying to share a code example). Here's an example:: >>> html = '<span>Hello, exploit: <img src="javascript:alert(\"pwned!\")"></span>' >>> html, rejects = strip_xss(html, replacement="entities") >>> print(html) <span>Hello, exploit: &lt;img src="javascript:alert("pwned!")"&gt;</span> >>> print("Rejected: '%s'" % ", ".join(rejects)) Rejected: '<img src="javascript:alert("pwned!")">' **NOTE:** This function should work to protect against *all* `the XSS examples at OWASP <https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet>`_. Please `let us know <https://github.com/LiftoffSoftware/htmltag/issues>`_ if you find something we missed. """ re_html_tag = re.compile( # This matches HTML tags (if used correctly) "(?i)<\/?\w+((\s+\w+(\s*=\s*(?:\".*?\"|'.*?'|[^'\">\s]+))?)+\s*|\s*)\/?>") # This will match things like 'onmouseover=' ('on<whatever>=') on_events_re = re.compile('.*\s+(on[a-z]+\s*=).*') if not whitelist: # These are all pretty safe and covers most of what users would want in # terms of formatting and sharing media (images, audio, video, etc). whitelist = set([ 'a', 'abbr', 'aside', 'audio', 'bdi', 'bdo', 'blockquote', 'canvas', 'caption', 'code', 'col', 'colgroup', 'data', 'dd', 'del', 'details', 'div', 'dl', 'dt', 'em', 'figcaption', 'figure', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'ins', 'kbd', 'li', 'mark', 'ol', 'p', 'pre', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'small', 'source', 'span', 'strong', 'sub', 'summary', 'sup', 'table', 'td', 'th', 'time', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr' ]) elif whitelist == "off": whitelist = None # Disable it altogether bad_tags = set() for tag in re_html_tag.finditer(html): tag = tag.group() tag_lower = tag.lower() short_tag = tag_lower.split()[0].lstrip('</').rstrip('>') if whitelist and short_tag not in whitelist: bad_tags.add(tag) continue # Make sure the tag can't execute any JavaScript if "javascript:" in tag_lower: bad_tags.add(tag) continue # on<whatever> events are not allowed (just another XSS vuln) if on_events_re.search(tag_lower): bad_tags.add(tag) continue # Flash sucks if "fscommand" in tag_lower: bad_tags.add(tag) continue # I'd be impressed if an attacker tried this one (super obscure) if "seeksegmenttime" in tag_lower: bad_tags.add(tag) continue # Yes we'll protect IE users from themselves... if "vbscript:" in tag_lower: bad_tags.add(tag) continue if replacement == "entities": for bad_tag in bad_tags: escaped = cgi.escape(bad_tag).encode('ascii', 'xmlcharrefreplace') html = html.replace(bad_tag, escaped.decode('ascii')) else: for bad_tag in bad_tags: html = html.replace(bad_tag, replacement) return (html, bad_tags)
def get_dict_to_print(field_to_obs): """Transform the field-to-obs mapping into a printable dictionary. Args: field_to_obs: Dict that maps string field to `Observation` list. Returns: A dict with the keys and values to print to console. """ def compressed_steps(steps): return {'num_steps': len(set(steps)), 'min_step': min(steps), 'max_step': max(steps), 'last_step': steps[-1], 'first_step': steps[0], 'outoforder_steps': get_out_of_order(steps)} def full_steps(steps): return {'steps': steps, 'outoforder_steps': get_out_of_order(steps)} output = {} for field, observations in field_to_obs.items(): if not observations: output[field] = None continue steps = [x['step'] for x in observations] if field in SHORT_FIELDS: output[field] = compressed_steps(steps) if field in LONG_FIELDS: output[field] = full_steps(steps) return output
Transform the field-to-obs mapping into a printable dictionary. Args: field_to_obs: Dict that maps string field to `Observation` list. Returns: A dict with the keys and values to print to console.
Below is the the instruction that describes the task: ### Input: Transform the field-to-obs mapping into a printable dictionary. Args: field_to_obs: Dict that maps string field to `Observation` list. Returns: A dict with the keys and values to print to console. ### Response: def get_dict_to_print(field_to_obs): """Transform the field-to-obs mapping into a printable dictionary. Args: field_to_obs: Dict that maps string field to `Observation` list. Returns: A dict with the keys and values to print to console. """ def compressed_steps(steps): return {'num_steps': len(set(steps)), 'min_step': min(steps), 'max_step': max(steps), 'last_step': steps[-1], 'first_step': steps[0], 'outoforder_steps': get_out_of_order(steps)} def full_steps(steps): return {'steps': steps, 'outoforder_steps': get_out_of_order(steps)} output = {} for field, observations in field_to_obs.items(): if not observations: output[field] = None continue steps = [x['step'] for x in observations] if field in SHORT_FIELDS: output[field] = compressed_steps(steps) if field in LONG_FIELDS: output[field] = full_steps(steps) return output
def make_association_id(definedby, sub, pred, obj, attributes=None): """ A method to create unique identifiers for OBAN-style associations, based on all the parts of the association If any of the items is empty or None, it will convert it to blank. It effectively digests the string of concatonated values. Subclasses of Assoc can submit an additional array of attributes that will be appeded to the ID. Note this is equivalent to a RDF blank node :param definedby: The (data) resource that provided the annotation :param subject: :param predicate: :param object: :param attributes: :return: """ items_to_hash = [definedby, sub, pred, obj] if attributes is not None and len(attributes) > 0: items_to_hash += attributes items_to_hash = [x for x in items_to_hash if x is not None] assoc_id = ':'.join(('MONARCH', GraphUtils.digest_id('+'.join(items_to_hash)))) assert assoc_id is not None return assoc_id
A method to create unique identifiers for OBAN-style associations, based on all the parts of the association If any of the items is empty or None, it will convert it to blank. It effectively digests the string of concatonated values. Subclasses of Assoc can submit an additional array of attributes that will be appeded to the ID. Note this is equivalent to a RDF blank node :param definedby: The (data) resource that provided the annotation :param subject: :param predicate: :param object: :param attributes: :return:
Below is the the instruction that describes the task: ### Input: A method to create unique identifiers for OBAN-style associations, based on all the parts of the association If any of the items is empty or None, it will convert it to blank. It effectively digests the string of concatonated values. Subclasses of Assoc can submit an additional array of attributes that will be appeded to the ID. Note this is equivalent to a RDF blank node :param definedby: The (data) resource that provided the annotation :param subject: :param predicate: :param object: :param attributes: :return: ### Response: def make_association_id(definedby, sub, pred, obj, attributes=None): """ A method to create unique identifiers for OBAN-style associations, based on all the parts of the association If any of the items is empty or None, it will convert it to blank. It effectively digests the string of concatonated values. Subclasses of Assoc can submit an additional array of attributes that will be appeded to the ID. Note this is equivalent to a RDF blank node :param definedby: The (data) resource that provided the annotation :param subject: :param predicate: :param object: :param attributes: :return: """ items_to_hash = [definedby, sub, pred, obj] if attributes is not None and len(attributes) > 0: items_to_hash += attributes items_to_hash = [x for x in items_to_hash if x is not None] assoc_id = ':'.join(('MONARCH', GraphUtils.digest_id('+'.join(items_to_hash)))) assert assoc_id is not None return assoc_id
def sqrt( data: AnnData, copy: bool = False, chunked: bool = False, chunk_size: Optional[int] = None, ) -> Optional[AnnData]: """Square root the data matrix. Computes :math:`X = \\sqrt(X)`. Parameters ---------- data The (annotated) data matrix of shape ``n_obs`` × ``n_vars``. Rows correspond to cells and columns to genes. copy If an :class:`~scanpy.api.AnnData` is passed, determines whether a copy is returned. chunked Process the data matrix in chunks, which will save memory. Applies only to :class:`~anndata.AnnData`. chunk_size ``n_obs`` of the chunks to process the data in. Returns ------- Returns or updates `data`, depending on `copy`. """ if isinstance(data, AnnData): adata = data.copy() if copy else data if chunked: for chunk, start, end in adata.chunked_X(chunk_size): adata.X[start:end] = sqrt(chunk) else: adata.X = sqrt(data.X) return adata if copy else None X = data # proceed with data matrix if not issparse(X): return np.sqrt(X) else: return X.sqrt()
Square root the data matrix. Computes :math:`X = \\sqrt(X)`. Parameters ---------- data The (annotated) data matrix of shape ``n_obs`` × ``n_vars``. Rows correspond to cells and columns to genes. copy If an :class:`~scanpy.api.AnnData` is passed, determines whether a copy is returned. chunked Process the data matrix in chunks, which will save memory. Applies only to :class:`~anndata.AnnData`. chunk_size ``n_obs`` of the chunks to process the data in. Returns ------- Returns or updates `data`, depending on `copy`.
Below is the the instruction that describes the task: ### Input: Square root the data matrix. Computes :math:`X = \\sqrt(X)`. Parameters ---------- data The (annotated) data matrix of shape ``n_obs`` × ``n_vars``. Rows correspond to cells and columns to genes. copy If an :class:`~scanpy.api.AnnData` is passed, determines whether a copy is returned. chunked Process the data matrix in chunks, which will save memory. Applies only to :class:`~anndata.AnnData`. chunk_size ``n_obs`` of the chunks to process the data in. Returns ------- Returns or updates `data`, depending on `copy`. ### Response: def sqrt( data: AnnData, copy: bool = False, chunked: bool = False, chunk_size: Optional[int] = None, ) -> Optional[AnnData]: """Square root the data matrix. Computes :math:`X = \\sqrt(X)`. Parameters ---------- data The (annotated) data matrix of shape ``n_obs`` × ``n_vars``. Rows correspond to cells and columns to genes. copy If an :class:`~scanpy.api.AnnData` is passed, determines whether a copy is returned. chunked Process the data matrix in chunks, which will save memory. Applies only to :class:`~anndata.AnnData`. chunk_size ``n_obs`` of the chunks to process the data in. Returns ------- Returns or updates `data`, depending on `copy`. """ if isinstance(data, AnnData): adata = data.copy() if copy else data if chunked: for chunk, start, end in adata.chunked_X(chunk_size): adata.X[start:end] = sqrt(chunk) else: adata.X = sqrt(data.X) return adata if copy else None X = data # proceed with data matrix if not issparse(X): return np.sqrt(X) else: return X.sqrt()
def _winsorize_wrapper(x, limits): """ Wraps scipy winsorize function to drop na's """ if isinstance(x, pd.Series): if x.count() == 0: return x notnanx = ~np.isnan(x) x[notnanx] = scipy.stats.mstats.winsorize(x[notnanx], limits=limits) return x else: return scipy.stats.mstats.winsorize(x, limits=limits)
Wraps scipy winsorize function to drop na's
Below is the the instruction that describes the task: ### Input: Wraps scipy winsorize function to drop na's ### Response: def _winsorize_wrapper(x, limits): """ Wraps scipy winsorize function to drop na's """ if isinstance(x, pd.Series): if x.count() == 0: return x notnanx = ~np.isnan(x) x[notnanx] = scipy.stats.mstats.winsorize(x[notnanx], limits=limits) return x else: return scipy.stats.mstats.winsorize(x, limits=limits)
def storageLevel(self): """Get the :class:`DataFrame`'s current storage level. >>> df.storageLevel StorageLevel(False, False, False, False, 1) >>> df.cache().storageLevel StorageLevel(True, True, False, True, 1) >>> df2.persist(StorageLevel.DISK_ONLY_2).storageLevel StorageLevel(True, False, False, False, 2) """ java_storage_level = self._jdf.storageLevel() storage_level = StorageLevel(java_storage_level.useDisk(), java_storage_level.useMemory(), java_storage_level.useOffHeap(), java_storage_level.deserialized(), java_storage_level.replication()) return storage_level
Get the :class:`DataFrame`'s current storage level. >>> df.storageLevel StorageLevel(False, False, False, False, 1) >>> df.cache().storageLevel StorageLevel(True, True, False, True, 1) >>> df2.persist(StorageLevel.DISK_ONLY_2).storageLevel StorageLevel(True, False, False, False, 2)
Below is the the instruction that describes the task: ### Input: Get the :class:`DataFrame`'s current storage level. >>> df.storageLevel StorageLevel(False, False, False, False, 1) >>> df.cache().storageLevel StorageLevel(True, True, False, True, 1) >>> df2.persist(StorageLevel.DISK_ONLY_2).storageLevel StorageLevel(True, False, False, False, 2) ### Response: def storageLevel(self): """Get the :class:`DataFrame`'s current storage level. >>> df.storageLevel StorageLevel(False, False, False, False, 1) >>> df.cache().storageLevel StorageLevel(True, True, False, True, 1) >>> df2.persist(StorageLevel.DISK_ONLY_2).storageLevel StorageLevel(True, False, False, False, 2) """ java_storage_level = self._jdf.storageLevel() storage_level = StorageLevel(java_storage_level.useDisk(), java_storage_level.useMemory(), java_storage_level.useOffHeap(), java_storage_level.deserialized(), java_storage_level.replication()) return storage_level
def get_nowait(self): """Remove and return an item from the queue. Return an item if one is immediately available, else raise QueueEmpty. """ self._parent._check_closing() with self._parent._sync_mutex: if self._parent._qsize() == 0: raise AsyncQueueEmpty item = self._parent._get() self._parent._notify_async_not_full(threadsafe=False) self._parent._notify_sync_not_full() return item
Remove and return an item from the queue. Return an item if one is immediately available, else raise QueueEmpty.
Below is the the instruction that describes the task: ### Input: Remove and return an item from the queue. Return an item if one is immediately available, else raise QueueEmpty. ### Response: def get_nowait(self): """Remove and return an item from the queue. Return an item if one is immediately available, else raise QueueEmpty. """ self._parent._check_closing() with self._parent._sync_mutex: if self._parent._qsize() == 0: raise AsyncQueueEmpty item = self._parent._get() self._parent._notify_async_not_full(threadsafe=False) self._parent._notify_sync_not_full() return item
def unflat_unique_rowid_map(func, unflat_rowids, **kwargs): """ performs only one call to the underlying func with unique rowids the func must be some lookup function TODO: move this to a better place. CommandLine: python -m utool.util_list --test-unflat_unique_rowid_map:0 python -m utool.util_list --test-unflat_unique_rowid_map:1 Example0: >>> # ENABLE_DOCTEST >>> from utool.util_list import * # NOQA >>> import utool as ut >>> kwargs = {} >>> unflat_rowids = [[1, 2, 3], [2, 5], [1], []] >>> num_calls0 = [0] >>> num_input0 = [0] >>> def func0(rowids, num_calls0=num_calls0, num_input0=num_input0): ... num_calls0[0] += 1 ... num_input0[0] += len(rowids) ... return [rowid + 10 for rowid in rowids] >>> func = func0 >>> unflat_vals = unflat_unique_rowid_map(func, unflat_rowids, **kwargs) >>> result = [arr.tolist() for arr in unflat_vals] >>> print(result) >>> ut.assert_eq(num_calls0[0], 1) >>> ut.assert_eq(num_input0[0], 4) [[11, 12, 13], [12, 15], [11], []] Example1: >>> # ENABLE_DOCTEST >>> from utool.util_list import * # NOQA >>> import utool as ut >>> import numpy as np >>> kwargs = {} >>> unflat_rowids = [[1, 2, 3], [2, 5], [1], []] >>> num_calls1 = [0] >>> num_input1 = [0] >>> def func1(rowids, num_calls1=num_calls1, num_input1=num_input1, np=np): ... num_calls1[0] += 1 ... num_input1[0] += len(rowids) ... return [np.array([rowid + 10, rowid, 3]) for rowid in rowids] >>> func = func1 >>> unflat_vals = unflat_unique_rowid_map(func, unflat_rowids, **kwargs) >>> result = [arr.tolist() for arr in unflat_vals] >>> print(result) >>> ut.assert_eq(num_calls1[0], 1) >>> ut.assert_eq(num_input1[0], 4) [[[11, 1, 3], [12, 2, 3], [13, 3, 3]], [[12, 2, 3], [15, 5, 3]], [[11, 1, 3]], []] """ import utool as ut # First flatten the list, and remember the original dimensions flat_rowids, reverse_list = ut.invertible_flatten2(unflat_rowids) # Then make the input unique flat_rowids_arr = np.array(flat_rowids) unique_flat_rowids, inverse_unique = np.unique(flat_rowids_arr, return_inverse=True) # Then preform the lookup / implicit mapping unique_flat_vals = func(unique_flat_rowids, **kwargs) # Then broadcast unique values back to original flat positions flat_vals_ = np.array(unique_flat_vals)[inverse_unique] #flat_vals_ = np.array(unique_flat_vals).take(inverse_unique, axis=0) output_shape = tuple(list(flat_rowids_arr.shape) + list(flat_vals_.shape[1:])) flat_vals = np.array(flat_vals_).reshape(output_shape) # Then _unflatten the results to the original input dimensions unflat_vals = ut.unflatten2(flat_vals, reverse_list) return unflat_vals
performs only one call to the underlying func with unique rowids the func must be some lookup function TODO: move this to a better place. CommandLine: python -m utool.util_list --test-unflat_unique_rowid_map:0 python -m utool.util_list --test-unflat_unique_rowid_map:1 Example0: >>> # ENABLE_DOCTEST >>> from utool.util_list import * # NOQA >>> import utool as ut >>> kwargs = {} >>> unflat_rowids = [[1, 2, 3], [2, 5], [1], []] >>> num_calls0 = [0] >>> num_input0 = [0] >>> def func0(rowids, num_calls0=num_calls0, num_input0=num_input0): ... num_calls0[0] += 1 ... num_input0[0] += len(rowids) ... return [rowid + 10 for rowid in rowids] >>> func = func0 >>> unflat_vals = unflat_unique_rowid_map(func, unflat_rowids, **kwargs) >>> result = [arr.tolist() for arr in unflat_vals] >>> print(result) >>> ut.assert_eq(num_calls0[0], 1) >>> ut.assert_eq(num_input0[0], 4) [[11, 12, 13], [12, 15], [11], []] Example1: >>> # ENABLE_DOCTEST >>> from utool.util_list import * # NOQA >>> import utool as ut >>> import numpy as np >>> kwargs = {} >>> unflat_rowids = [[1, 2, 3], [2, 5], [1], []] >>> num_calls1 = [0] >>> num_input1 = [0] >>> def func1(rowids, num_calls1=num_calls1, num_input1=num_input1, np=np): ... num_calls1[0] += 1 ... num_input1[0] += len(rowids) ... return [np.array([rowid + 10, rowid, 3]) for rowid in rowids] >>> func = func1 >>> unflat_vals = unflat_unique_rowid_map(func, unflat_rowids, **kwargs) >>> result = [arr.tolist() for arr in unflat_vals] >>> print(result) >>> ut.assert_eq(num_calls1[0], 1) >>> ut.assert_eq(num_input1[0], 4) [[[11, 1, 3], [12, 2, 3], [13, 3, 3]], [[12, 2, 3], [15, 5, 3]], [[11, 1, 3]], []]
Below is the the instruction that describes the task: ### Input: performs only one call to the underlying func with unique rowids the func must be some lookup function TODO: move this to a better place. CommandLine: python -m utool.util_list --test-unflat_unique_rowid_map:0 python -m utool.util_list --test-unflat_unique_rowid_map:1 Example0: >>> # ENABLE_DOCTEST >>> from utool.util_list import * # NOQA >>> import utool as ut >>> kwargs = {} >>> unflat_rowids = [[1, 2, 3], [2, 5], [1], []] >>> num_calls0 = [0] >>> num_input0 = [0] >>> def func0(rowids, num_calls0=num_calls0, num_input0=num_input0): ... num_calls0[0] += 1 ... num_input0[0] += len(rowids) ... return [rowid + 10 for rowid in rowids] >>> func = func0 >>> unflat_vals = unflat_unique_rowid_map(func, unflat_rowids, **kwargs) >>> result = [arr.tolist() for arr in unflat_vals] >>> print(result) >>> ut.assert_eq(num_calls0[0], 1) >>> ut.assert_eq(num_input0[0], 4) [[11, 12, 13], [12, 15], [11], []] Example1: >>> # ENABLE_DOCTEST >>> from utool.util_list import * # NOQA >>> import utool as ut >>> import numpy as np >>> kwargs = {} >>> unflat_rowids = [[1, 2, 3], [2, 5], [1], []] >>> num_calls1 = [0] >>> num_input1 = [0] >>> def func1(rowids, num_calls1=num_calls1, num_input1=num_input1, np=np): ... num_calls1[0] += 1 ... num_input1[0] += len(rowids) ... return [np.array([rowid + 10, rowid, 3]) for rowid in rowids] >>> func = func1 >>> unflat_vals = unflat_unique_rowid_map(func, unflat_rowids, **kwargs) >>> result = [arr.tolist() for arr in unflat_vals] >>> print(result) >>> ut.assert_eq(num_calls1[0], 1) >>> ut.assert_eq(num_input1[0], 4) [[[11, 1, 3], [12, 2, 3], [13, 3, 3]], [[12, 2, 3], [15, 5, 3]], [[11, 1, 3]], []] ### Response: def unflat_unique_rowid_map(func, unflat_rowids, **kwargs): """ performs only one call to the underlying func with unique rowids the func must be some lookup function TODO: move this to a better place. CommandLine: python -m utool.util_list --test-unflat_unique_rowid_map:0 python -m utool.util_list --test-unflat_unique_rowid_map:1 Example0: >>> # ENABLE_DOCTEST >>> from utool.util_list import * # NOQA >>> import utool as ut >>> kwargs = {} >>> unflat_rowids = [[1, 2, 3], [2, 5], [1], []] >>> num_calls0 = [0] >>> num_input0 = [0] >>> def func0(rowids, num_calls0=num_calls0, num_input0=num_input0): ... num_calls0[0] += 1 ... num_input0[0] += len(rowids) ... return [rowid + 10 for rowid in rowids] >>> func = func0 >>> unflat_vals = unflat_unique_rowid_map(func, unflat_rowids, **kwargs) >>> result = [arr.tolist() for arr in unflat_vals] >>> print(result) >>> ut.assert_eq(num_calls0[0], 1) >>> ut.assert_eq(num_input0[0], 4) [[11, 12, 13], [12, 15], [11], []] Example1: >>> # ENABLE_DOCTEST >>> from utool.util_list import * # NOQA >>> import utool as ut >>> import numpy as np >>> kwargs = {} >>> unflat_rowids = [[1, 2, 3], [2, 5], [1], []] >>> num_calls1 = [0] >>> num_input1 = [0] >>> def func1(rowids, num_calls1=num_calls1, num_input1=num_input1, np=np): ... num_calls1[0] += 1 ... num_input1[0] += len(rowids) ... return [np.array([rowid + 10, rowid, 3]) for rowid in rowids] >>> func = func1 >>> unflat_vals = unflat_unique_rowid_map(func, unflat_rowids, **kwargs) >>> result = [arr.tolist() for arr in unflat_vals] >>> print(result) >>> ut.assert_eq(num_calls1[0], 1) >>> ut.assert_eq(num_input1[0], 4) [[[11, 1, 3], [12, 2, 3], [13, 3, 3]], [[12, 2, 3], [15, 5, 3]], [[11, 1, 3]], []] """ import utool as ut # First flatten the list, and remember the original dimensions flat_rowids, reverse_list = ut.invertible_flatten2(unflat_rowids) # Then make the input unique flat_rowids_arr = np.array(flat_rowids) unique_flat_rowids, inverse_unique = np.unique(flat_rowids_arr, return_inverse=True) # Then preform the lookup / implicit mapping unique_flat_vals = func(unique_flat_rowids, **kwargs) # Then broadcast unique values back to original flat positions flat_vals_ = np.array(unique_flat_vals)[inverse_unique] #flat_vals_ = np.array(unique_flat_vals).take(inverse_unique, axis=0) output_shape = tuple(list(flat_rowids_arr.shape) + list(flat_vals_.shape[1:])) flat_vals = np.array(flat_vals_).reshape(output_shape) # Then _unflatten the results to the original input dimensions unflat_vals = ut.unflatten2(flat_vals, reverse_list) return unflat_vals
def pivoted_cholesky(matrix, max_rank, diag_rtol=1e-3, name=None): """Computes the (partial) pivoted cholesky decomposition of `matrix`. The pivoted Cholesky is a low rank approximation of the Cholesky decomposition of `matrix`, i.e. as described in [(Harbrecht et al., 2012)][1]. The currently-worst-approximated diagonal element is selected as the pivot at each iteration. This yields from a `[B1...Bn, N, N]` shaped `matrix` a `[B1...Bn, N, K]` shaped rank-`K` approximation `lr` such that `lr @ lr.T ~= matrix`. Note that, unlike the Cholesky decomposition, `lr` is not triangular even in a rectangular-matrix sense. However, under a permutation it could be made triangular (it has one more zero in each column as you move to the right). Such a matrix can be useful as a preconditioner for conjugate gradient optimization, i.e. as in [(Wang et al. 2019)][2], as matmuls and solves can be cheaply done via the Woodbury matrix identity, as implemented by `tf.linalg.LinearOperatorLowRankUpdate`. Args: matrix: Floating point `Tensor` batch of symmetric, positive definite matrices. max_rank: Scalar `int` `Tensor`, the rank at which to truncate the approximation. diag_rtol: Scalar floating point `Tensor` (same dtype as `matrix`). If the errors of all diagonal elements of `lr @ lr.T` are each lower than `element * diag_rtol`, iteration is permitted to terminate early. name: Optional name for the op. Returns: lr: Low rank pivoted Cholesky approximation of `matrix`. #### References [1]: H Harbrecht, M Peters, R Schneider. On the low-rank approximation by the pivoted Cholesky decomposition. _Applied numerical mathematics_, 62(4):428-440, 2012. [2]: K. A. Wang et al. Exact Gaussian Processes on a Million Data Points. _arXiv preprint arXiv:1903.08114_, 2019. https://arxiv.org/abs/1903.08114 """ with tf.compat.v2.name_scope(name or 'pivoted_cholesky'): dtype = dtype_util.common_dtype([matrix, diag_rtol], preferred_dtype=tf.float32) matrix = tf.convert_to_tensor(value=matrix, name='matrix', dtype=dtype) if tensorshape_util.rank(matrix.shape) is None: raise NotImplementedError('Rank of `matrix` must be known statically') max_rank = tf.convert_to_tensor( value=max_rank, name='max_rank', dtype=tf.int64) max_rank = tf.minimum(max_rank, prefer_static.shape(matrix, out_type=tf.int64)[-1]) diag_rtol = tf.convert_to_tensor( value=diag_rtol, dtype=dtype, name='diag_rtol') matrix_diag = tf.linalg.diag_part(matrix) # matrix is P.D., therefore all matrix_diag > 0, so we don't need abs. orig_error = tf.reduce_max(input_tensor=matrix_diag, axis=-1) def cond(m, pchol, perm, matrix_diag): """Condition for `tf.while_loop` continuation.""" del pchol del perm error = tf.linalg.norm(tensor=matrix_diag, ord=1, axis=-1) max_err = tf.reduce_max(input_tensor=error / orig_error) return (m < max_rank) & (tf.equal(m, 0) | (max_err > diag_rtol)) batch_dims = tensorshape_util.rank(matrix.shape) - 2 def batch_gather(params, indices, axis=-1): return tf.gather(params, indices, axis=axis, batch_dims=batch_dims) def body(m, pchol, perm, matrix_diag): """Body of a single `tf.while_loop` iteration.""" # Here is roughly a numpy, non-batched version of what's going to happen. # (See also Algorithm 1 of Harbrecht et al.) # 1: maxi = np.argmax(matrix_diag[perm[m:]]) + m # 2: maxval = matrix_diag[perm][maxi] # 3: perm[m], perm[maxi] = perm[maxi], perm[m] # 4: row = matrix[perm[m]][perm[m + 1:]] # 5: row -= np.sum(pchol[:m][perm[m + 1:]] * pchol[:m][perm[m]]], axis=-2) # 6: pivot = np.sqrt(maxval); row /= pivot # 7: row = np.concatenate([[[pivot]], row], -1) # 8: matrix_diag[perm[m:]] -= row**2 # 9: pchol[m, perm[m:]] = row # Find the maximal position of the (remaining) permuted diagonal. # Steps 1, 2 above. permuted_diag = batch_gather(matrix_diag, perm[..., m:]) maxi = tf.argmax( input=permuted_diag, axis=-1, output_type=tf.int64)[..., tf.newaxis] maxval = batch_gather(permuted_diag, maxi) maxi = maxi + m maxval = maxval[..., 0] # Update perm: Swap perm[...,m] with perm[...,maxi]. Step 3 above. perm = _swap_m_with_i(perm, m, maxi) # Step 4. row = batch_gather(matrix, perm[..., m:m + 1], axis=-2) row = batch_gather(row, perm[..., m + 1:]) # Step 5. prev_rows = pchol[..., :m, :] prev_rows_perm_m_onward = batch_gather(prev_rows, perm[..., m + 1:]) prev_rows_pivot_col = batch_gather(prev_rows, perm[..., m:m + 1]) row -= tf.reduce_sum( input_tensor=prev_rows_perm_m_onward * prev_rows_pivot_col, axis=-2)[..., tf.newaxis, :] # Step 6. pivot = tf.sqrt(maxval)[..., tf.newaxis, tf.newaxis] # Step 7. row = tf.concat([pivot, row / pivot], axis=-1) # TODO(b/130899118): Pad grad fails with int64 paddings. # Step 8. paddings = tf.concat([ tf.zeros([prefer_static.rank(pchol) - 1, 2], dtype=tf.int32), [[tf.cast(m, tf.int32), 0]]], axis=0) diag_update = tf.pad(tensor=row**2, paddings=paddings)[..., 0, :] reverse_perm = _invert_permutation(perm) matrix_diag -= batch_gather(diag_update, reverse_perm) # Step 9. row = tf.pad(tensor=row, paddings=paddings) # TODO(bjp): Defer the reverse permutation all-at-once at the end? row = batch_gather(row, reverse_perm) pchol_shape = pchol.shape pchol = tf.concat([pchol[..., :m, :], row, pchol[..., m + 1:, :]], axis=-2) tensorshape_util.set_shape(pchol, pchol_shape) return m + 1, pchol, perm, matrix_diag m = np.int64(0) pchol = tf.zeros_like(matrix[..., :max_rank, :]) matrix_shape = prefer_static.shape(matrix, out_type=tf.int64) perm = tf.broadcast_to( prefer_static.range(matrix_shape[-1]), matrix_shape[:-1]) _, pchol, _, _ = tf.while_loop( cond=cond, body=body, loop_vars=(m, pchol, perm, matrix_diag)) pchol = tf.linalg.matrix_transpose(pchol) tensorshape_util.set_shape( pchol, tensorshape_util.concatenate(matrix_diag.shape, [None])) return pchol
Computes the (partial) pivoted cholesky decomposition of `matrix`. The pivoted Cholesky is a low rank approximation of the Cholesky decomposition of `matrix`, i.e. as described in [(Harbrecht et al., 2012)][1]. The currently-worst-approximated diagonal element is selected as the pivot at each iteration. This yields from a `[B1...Bn, N, N]` shaped `matrix` a `[B1...Bn, N, K]` shaped rank-`K` approximation `lr` such that `lr @ lr.T ~= matrix`. Note that, unlike the Cholesky decomposition, `lr` is not triangular even in a rectangular-matrix sense. However, under a permutation it could be made triangular (it has one more zero in each column as you move to the right). Such a matrix can be useful as a preconditioner for conjugate gradient optimization, i.e. as in [(Wang et al. 2019)][2], as matmuls and solves can be cheaply done via the Woodbury matrix identity, as implemented by `tf.linalg.LinearOperatorLowRankUpdate`. Args: matrix: Floating point `Tensor` batch of symmetric, positive definite matrices. max_rank: Scalar `int` `Tensor`, the rank at which to truncate the approximation. diag_rtol: Scalar floating point `Tensor` (same dtype as `matrix`). If the errors of all diagonal elements of `lr @ lr.T` are each lower than `element * diag_rtol`, iteration is permitted to terminate early. name: Optional name for the op. Returns: lr: Low rank pivoted Cholesky approximation of `matrix`. #### References [1]: H Harbrecht, M Peters, R Schneider. On the low-rank approximation by the pivoted Cholesky decomposition. _Applied numerical mathematics_, 62(4):428-440, 2012. [2]: K. A. Wang et al. Exact Gaussian Processes on a Million Data Points. _arXiv preprint arXiv:1903.08114_, 2019. https://arxiv.org/abs/1903.08114
Below is the the instruction that describes the task: ### Input: Computes the (partial) pivoted cholesky decomposition of `matrix`. The pivoted Cholesky is a low rank approximation of the Cholesky decomposition of `matrix`, i.e. as described in [(Harbrecht et al., 2012)][1]. The currently-worst-approximated diagonal element is selected as the pivot at each iteration. This yields from a `[B1...Bn, N, N]` shaped `matrix` a `[B1...Bn, N, K]` shaped rank-`K` approximation `lr` such that `lr @ lr.T ~= matrix`. Note that, unlike the Cholesky decomposition, `lr` is not triangular even in a rectangular-matrix sense. However, under a permutation it could be made triangular (it has one more zero in each column as you move to the right). Such a matrix can be useful as a preconditioner for conjugate gradient optimization, i.e. as in [(Wang et al. 2019)][2], as matmuls and solves can be cheaply done via the Woodbury matrix identity, as implemented by `tf.linalg.LinearOperatorLowRankUpdate`. Args: matrix: Floating point `Tensor` batch of symmetric, positive definite matrices. max_rank: Scalar `int` `Tensor`, the rank at which to truncate the approximation. diag_rtol: Scalar floating point `Tensor` (same dtype as `matrix`). If the errors of all diagonal elements of `lr @ lr.T` are each lower than `element * diag_rtol`, iteration is permitted to terminate early. name: Optional name for the op. Returns: lr: Low rank pivoted Cholesky approximation of `matrix`. #### References [1]: H Harbrecht, M Peters, R Schneider. On the low-rank approximation by the pivoted Cholesky decomposition. _Applied numerical mathematics_, 62(4):428-440, 2012. [2]: K. A. Wang et al. Exact Gaussian Processes on a Million Data Points. _arXiv preprint arXiv:1903.08114_, 2019. https://arxiv.org/abs/1903.08114 ### Response: def pivoted_cholesky(matrix, max_rank, diag_rtol=1e-3, name=None): """Computes the (partial) pivoted cholesky decomposition of `matrix`. The pivoted Cholesky is a low rank approximation of the Cholesky decomposition of `matrix`, i.e. as described in [(Harbrecht et al., 2012)][1]. The currently-worst-approximated diagonal element is selected as the pivot at each iteration. This yields from a `[B1...Bn, N, N]` shaped `matrix` a `[B1...Bn, N, K]` shaped rank-`K` approximation `lr` such that `lr @ lr.T ~= matrix`. Note that, unlike the Cholesky decomposition, `lr` is not triangular even in a rectangular-matrix sense. However, under a permutation it could be made triangular (it has one more zero in each column as you move to the right). Such a matrix can be useful as a preconditioner for conjugate gradient optimization, i.e. as in [(Wang et al. 2019)][2], as matmuls and solves can be cheaply done via the Woodbury matrix identity, as implemented by `tf.linalg.LinearOperatorLowRankUpdate`. Args: matrix: Floating point `Tensor` batch of symmetric, positive definite matrices. max_rank: Scalar `int` `Tensor`, the rank at which to truncate the approximation. diag_rtol: Scalar floating point `Tensor` (same dtype as `matrix`). If the errors of all diagonal elements of `lr @ lr.T` are each lower than `element * diag_rtol`, iteration is permitted to terminate early. name: Optional name for the op. Returns: lr: Low rank pivoted Cholesky approximation of `matrix`. #### References [1]: H Harbrecht, M Peters, R Schneider. On the low-rank approximation by the pivoted Cholesky decomposition. _Applied numerical mathematics_, 62(4):428-440, 2012. [2]: K. A. Wang et al. Exact Gaussian Processes on a Million Data Points. _arXiv preprint arXiv:1903.08114_, 2019. https://arxiv.org/abs/1903.08114 """ with tf.compat.v2.name_scope(name or 'pivoted_cholesky'): dtype = dtype_util.common_dtype([matrix, diag_rtol], preferred_dtype=tf.float32) matrix = tf.convert_to_tensor(value=matrix, name='matrix', dtype=dtype) if tensorshape_util.rank(matrix.shape) is None: raise NotImplementedError('Rank of `matrix` must be known statically') max_rank = tf.convert_to_tensor( value=max_rank, name='max_rank', dtype=tf.int64) max_rank = tf.minimum(max_rank, prefer_static.shape(matrix, out_type=tf.int64)[-1]) diag_rtol = tf.convert_to_tensor( value=diag_rtol, dtype=dtype, name='diag_rtol') matrix_diag = tf.linalg.diag_part(matrix) # matrix is P.D., therefore all matrix_diag > 0, so we don't need abs. orig_error = tf.reduce_max(input_tensor=matrix_diag, axis=-1) def cond(m, pchol, perm, matrix_diag): """Condition for `tf.while_loop` continuation.""" del pchol del perm error = tf.linalg.norm(tensor=matrix_diag, ord=1, axis=-1) max_err = tf.reduce_max(input_tensor=error / orig_error) return (m < max_rank) & (tf.equal(m, 0) | (max_err > diag_rtol)) batch_dims = tensorshape_util.rank(matrix.shape) - 2 def batch_gather(params, indices, axis=-1): return tf.gather(params, indices, axis=axis, batch_dims=batch_dims) def body(m, pchol, perm, matrix_diag): """Body of a single `tf.while_loop` iteration.""" # Here is roughly a numpy, non-batched version of what's going to happen. # (See also Algorithm 1 of Harbrecht et al.) # 1: maxi = np.argmax(matrix_diag[perm[m:]]) + m # 2: maxval = matrix_diag[perm][maxi] # 3: perm[m], perm[maxi] = perm[maxi], perm[m] # 4: row = matrix[perm[m]][perm[m + 1:]] # 5: row -= np.sum(pchol[:m][perm[m + 1:]] * pchol[:m][perm[m]]], axis=-2) # 6: pivot = np.sqrt(maxval); row /= pivot # 7: row = np.concatenate([[[pivot]], row], -1) # 8: matrix_diag[perm[m:]] -= row**2 # 9: pchol[m, perm[m:]] = row # Find the maximal position of the (remaining) permuted diagonal. # Steps 1, 2 above. permuted_diag = batch_gather(matrix_diag, perm[..., m:]) maxi = tf.argmax( input=permuted_diag, axis=-1, output_type=tf.int64)[..., tf.newaxis] maxval = batch_gather(permuted_diag, maxi) maxi = maxi + m maxval = maxval[..., 0] # Update perm: Swap perm[...,m] with perm[...,maxi]. Step 3 above. perm = _swap_m_with_i(perm, m, maxi) # Step 4. row = batch_gather(matrix, perm[..., m:m + 1], axis=-2) row = batch_gather(row, perm[..., m + 1:]) # Step 5. prev_rows = pchol[..., :m, :] prev_rows_perm_m_onward = batch_gather(prev_rows, perm[..., m + 1:]) prev_rows_pivot_col = batch_gather(prev_rows, perm[..., m:m + 1]) row -= tf.reduce_sum( input_tensor=prev_rows_perm_m_onward * prev_rows_pivot_col, axis=-2)[..., tf.newaxis, :] # Step 6. pivot = tf.sqrt(maxval)[..., tf.newaxis, tf.newaxis] # Step 7. row = tf.concat([pivot, row / pivot], axis=-1) # TODO(b/130899118): Pad grad fails with int64 paddings. # Step 8. paddings = tf.concat([ tf.zeros([prefer_static.rank(pchol) - 1, 2], dtype=tf.int32), [[tf.cast(m, tf.int32), 0]]], axis=0) diag_update = tf.pad(tensor=row**2, paddings=paddings)[..., 0, :] reverse_perm = _invert_permutation(perm) matrix_diag -= batch_gather(diag_update, reverse_perm) # Step 9. row = tf.pad(tensor=row, paddings=paddings) # TODO(bjp): Defer the reverse permutation all-at-once at the end? row = batch_gather(row, reverse_perm) pchol_shape = pchol.shape pchol = tf.concat([pchol[..., :m, :], row, pchol[..., m + 1:, :]], axis=-2) tensorshape_util.set_shape(pchol, pchol_shape) return m + 1, pchol, perm, matrix_diag m = np.int64(0) pchol = tf.zeros_like(matrix[..., :max_rank, :]) matrix_shape = prefer_static.shape(matrix, out_type=tf.int64) perm = tf.broadcast_to( prefer_static.range(matrix_shape[-1]), matrix_shape[:-1]) _, pchol, _, _ = tf.while_loop( cond=cond, body=body, loop_vars=(m, pchol, perm, matrix_diag)) pchol = tf.linalg.matrix_transpose(pchol) tensorshape_util.set_shape( pchol, tensorshape_util.concatenate(matrix_diag.shape, [None])) return pchol
def _process_packet(self, sequence): """ Check packet list for acks. """ if self._packets: with self._packet_lock: self._packets[:] = [packet for packet in self._packets if self._packet_ack(packet, sequence)]
Check packet list for acks.
Below is the the instruction that describes the task: ### Input: Check packet list for acks. ### Response: def _process_packet(self, sequence): """ Check packet list for acks. """ if self._packets: with self._packet_lock: self._packets[:] = [packet for packet in self._packets if self._packet_ack(packet, sequence)]
def getAnalysisServiceSettings(self, uid): """Returns a dictionary with the settings for the analysis service that match with the uid provided. If there are no settings for the analysis service and template, returns a dictionary with the key 'uid' """ settings = self.getAnalysisServicesSettings() sets = [s for s in settings if s.get("uid", "") == uid] return sets[0] if sets else {"uid": uid}
Returns a dictionary with the settings for the analysis service that match with the uid provided. If there are no settings for the analysis service and template, returns a dictionary with the key 'uid'
Below is the the instruction that describes the task: ### Input: Returns a dictionary with the settings for the analysis service that match with the uid provided. If there are no settings for the analysis service and template, returns a dictionary with the key 'uid' ### Response: def getAnalysisServiceSettings(self, uid): """Returns a dictionary with the settings for the analysis service that match with the uid provided. If there are no settings for the analysis service and template, returns a dictionary with the key 'uid' """ settings = self.getAnalysisServicesSettings() sets = [s for s in settings if s.get("uid", "") == uid] return sets[0] if sets else {"uid": uid}
def revoke_security_group(self, group_name=None, src_security_group_name=None, src_security_group_owner_id=None, ip_protocol=None, from_port=None, to_port=None, cidr_ip=None, group_id=None, src_security_group_group_id=None): """ Remove an existing rule from an existing security group. You need to pass in either src_security_group_name and src_security_group_owner_id OR ip_protocol, from_port, to_port, and cidr_ip. In other words, either you are revoking another group or you are revoking some ip-based rule. :type group_name: string :param group_name: The name of the security group you are removing the rule from. :type src_security_group_name: string :param src_security_group_name: The name of the security group you are revoking access to. :type src_security_group_owner_id: string :param src_security_group_owner_id: The ID of the owner of the security group you are revoking access to. :type ip_protocol: string :param ip_protocol: Either tcp | udp | icmp :type from_port: int :param from_port: The beginning port number you are disabling :type to_port: int :param to_port: The ending port number you are disabling :type cidr_ip: string :param cidr_ip: The CIDR block you are revoking access to. See http://goo.gl/Yj5QC :rtype: bool :return: True if successful. """ if src_security_group_name: if from_port is None and to_port is None and ip_protocol is None: return self.revoke_security_group_deprecated( group_name, src_security_group_name, src_security_group_owner_id) params = {} if group_name is not None: params['GroupName'] = group_name if group_id is not None: params['GroupId'] = group_id if src_security_group_name: param_name = 'IpPermissions.1.Groups.1.GroupName' params[param_name] = src_security_group_name if src_security_group_group_id: param_name = 'IpPermissions.1.Groups.1.GroupId' params[param_name] = src_security_group_group_id if src_security_group_owner_id: param_name = 'IpPermissions.1.Groups.1.UserId' params[param_name] = src_security_group_owner_id if ip_protocol: params['IpPermissions.1.IpProtocol'] = ip_protocol if from_port is not None: params['IpPermissions.1.FromPort'] = from_port if to_port is not None: params['IpPermissions.1.ToPort'] = to_port if cidr_ip: params['IpPermissions.1.IpRanges.1.CidrIp'] = cidr_ip return self.get_status('RevokeSecurityGroupIngress', params, verb='POST')
Remove an existing rule from an existing security group. You need to pass in either src_security_group_name and src_security_group_owner_id OR ip_protocol, from_port, to_port, and cidr_ip. In other words, either you are revoking another group or you are revoking some ip-based rule. :type group_name: string :param group_name: The name of the security group you are removing the rule from. :type src_security_group_name: string :param src_security_group_name: The name of the security group you are revoking access to. :type src_security_group_owner_id: string :param src_security_group_owner_id: The ID of the owner of the security group you are revoking access to. :type ip_protocol: string :param ip_protocol: Either tcp | udp | icmp :type from_port: int :param from_port: The beginning port number you are disabling :type to_port: int :param to_port: The ending port number you are disabling :type cidr_ip: string :param cidr_ip: The CIDR block you are revoking access to. See http://goo.gl/Yj5QC :rtype: bool :return: True if successful.
Below is the the instruction that describes the task: ### Input: Remove an existing rule from an existing security group. You need to pass in either src_security_group_name and src_security_group_owner_id OR ip_protocol, from_port, to_port, and cidr_ip. In other words, either you are revoking another group or you are revoking some ip-based rule. :type group_name: string :param group_name: The name of the security group you are removing the rule from. :type src_security_group_name: string :param src_security_group_name: The name of the security group you are revoking access to. :type src_security_group_owner_id: string :param src_security_group_owner_id: The ID of the owner of the security group you are revoking access to. :type ip_protocol: string :param ip_protocol: Either tcp | udp | icmp :type from_port: int :param from_port: The beginning port number you are disabling :type to_port: int :param to_port: The ending port number you are disabling :type cidr_ip: string :param cidr_ip: The CIDR block you are revoking access to. See http://goo.gl/Yj5QC :rtype: bool :return: True if successful. ### Response: def revoke_security_group(self, group_name=None, src_security_group_name=None, src_security_group_owner_id=None, ip_protocol=None, from_port=None, to_port=None, cidr_ip=None, group_id=None, src_security_group_group_id=None): """ Remove an existing rule from an existing security group. You need to pass in either src_security_group_name and src_security_group_owner_id OR ip_protocol, from_port, to_port, and cidr_ip. In other words, either you are revoking another group or you are revoking some ip-based rule. :type group_name: string :param group_name: The name of the security group you are removing the rule from. :type src_security_group_name: string :param src_security_group_name: The name of the security group you are revoking access to. :type src_security_group_owner_id: string :param src_security_group_owner_id: The ID of the owner of the security group you are revoking access to. :type ip_protocol: string :param ip_protocol: Either tcp | udp | icmp :type from_port: int :param from_port: The beginning port number you are disabling :type to_port: int :param to_port: The ending port number you are disabling :type cidr_ip: string :param cidr_ip: The CIDR block you are revoking access to. See http://goo.gl/Yj5QC :rtype: bool :return: True if successful. """ if src_security_group_name: if from_port is None and to_port is None and ip_protocol is None: return self.revoke_security_group_deprecated( group_name, src_security_group_name, src_security_group_owner_id) params = {} if group_name is not None: params['GroupName'] = group_name if group_id is not None: params['GroupId'] = group_id if src_security_group_name: param_name = 'IpPermissions.1.Groups.1.GroupName' params[param_name] = src_security_group_name if src_security_group_group_id: param_name = 'IpPermissions.1.Groups.1.GroupId' params[param_name] = src_security_group_group_id if src_security_group_owner_id: param_name = 'IpPermissions.1.Groups.1.UserId' params[param_name] = src_security_group_owner_id if ip_protocol: params['IpPermissions.1.IpProtocol'] = ip_protocol if from_port is not None: params['IpPermissions.1.FromPort'] = from_port if to_port is not None: params['IpPermissions.1.ToPort'] = to_port if cidr_ip: params['IpPermissions.1.IpRanges.1.CidrIp'] = cidr_ip return self.get_status('RevokeSecurityGroupIngress', params, verb='POST')
def wait(self, milliseconds, **options): """ Allows the thread to sleep for a given amount of time in milliseconds Argument: milliseconds is an Integer Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/wait """ self._steps.append(Wait(milliseconds, **options).obj)
Allows the thread to sleep for a given amount of time in milliseconds Argument: milliseconds is an Integer Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/wait
Below is the the instruction that describes the task: ### Input: Allows the thread to sleep for a given amount of time in milliseconds Argument: milliseconds is an Integer Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/wait ### Response: def wait(self, milliseconds, **options): """ Allows the thread to sleep for a given amount of time in milliseconds Argument: milliseconds is an Integer Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/wait """ self._steps.append(Wait(milliseconds, **options).obj)
def get_session(): """Gets a session. If there's no yet, creates one. :returns: a session """ if hasattr(g, 'session'): return g.session sess = create_session(bind=current_app.config['DATABASE_ENGINE']) try: g.session = sess except RuntimeError: pass return sess
Gets a session. If there's no yet, creates one. :returns: a session
Below is the the instruction that describes the task: ### Input: Gets a session. If there's no yet, creates one. :returns: a session ### Response: def get_session(): """Gets a session. If there's no yet, creates one. :returns: a session """ if hasattr(g, 'session'): return g.session sess = create_session(bind=current_app.config['DATABASE_ENGINE']) try: g.session = sess except RuntimeError: pass return sess
def get_block_statistics(cls, block_id): """ Get block statistics. Only works in test mode. """ if not os.environ.get("BLOCKSTACK_TEST"): raise Exception("This method is only available in the test framework") global STATISTICS return STATISTICS.get(block_id)
Get block statistics. Only works in test mode.
Below is the the instruction that describes the task: ### Input: Get block statistics. Only works in test mode. ### Response: def get_block_statistics(cls, block_id): """ Get block statistics. Only works in test mode. """ if not os.environ.get("BLOCKSTACK_TEST"): raise Exception("This method is only available in the test framework") global STATISTICS return STATISTICS.get(block_id)
def _parse(template): """Parse a top-level template string Expression. Any extraneous text is considered literal text. """ parser = Parser(template) parser.parse_expression() parts = parser.parts remainder = parser.string[parser.pos:] if remainder: parts.append(remainder) return Expression(parts)
Parse a top-level template string Expression. Any extraneous text is considered literal text.
Below is the the instruction that describes the task: ### Input: Parse a top-level template string Expression. Any extraneous text is considered literal text. ### Response: def _parse(template): """Parse a top-level template string Expression. Any extraneous text is considered literal text. """ parser = Parser(template) parser.parse_expression() parts = parser.parts remainder = parser.string[parser.pos:] if remainder: parts.append(remainder) return Expression(parts)
def _set_asn1_time(boundary, when): """ The the time value of an ASN1 time object. @param boundary: An ASN1_TIME pointer (or an object safely castable to that type) which will have its value set. @param when: A string representation of the desired time value. @raise TypeError: If C{when} is not a L{bytes} string. @raise ValueError: If C{when} does not represent a time in the required format. @raise RuntimeError: If the time value cannot be set for some other (unspecified) reason. """ if not isinstance(when, bytes): raise TypeError("when must be a byte string") set_result = _lib.ASN1_TIME_set_string(boundary, when) if set_result == 0: raise ValueError("Invalid string")
The the time value of an ASN1 time object. @param boundary: An ASN1_TIME pointer (or an object safely castable to that type) which will have its value set. @param when: A string representation of the desired time value. @raise TypeError: If C{when} is not a L{bytes} string. @raise ValueError: If C{when} does not represent a time in the required format. @raise RuntimeError: If the time value cannot be set for some other (unspecified) reason.
Below is the the instruction that describes the task: ### Input: The the time value of an ASN1 time object. @param boundary: An ASN1_TIME pointer (or an object safely castable to that type) which will have its value set. @param when: A string representation of the desired time value. @raise TypeError: If C{when} is not a L{bytes} string. @raise ValueError: If C{when} does not represent a time in the required format. @raise RuntimeError: If the time value cannot be set for some other (unspecified) reason. ### Response: def _set_asn1_time(boundary, when): """ The the time value of an ASN1 time object. @param boundary: An ASN1_TIME pointer (or an object safely castable to that type) which will have its value set. @param when: A string representation of the desired time value. @raise TypeError: If C{when} is not a L{bytes} string. @raise ValueError: If C{when} does not represent a time in the required format. @raise RuntimeError: If the time value cannot be set for some other (unspecified) reason. """ if not isinstance(when, bytes): raise TypeError("when must be a byte string") set_result = _lib.ASN1_TIME_set_string(boundary, when) if set_result == 0: raise ValueError("Invalid string")
def extract_path_info( environ_or_baseurl, path_or_url, charset="utf-8", errors="werkzeug.url_quote", collapse_http_schemes=True, ): """Extracts the path info from the given URL (or WSGI environment) and path. The path info returned is a unicode string, not a bytestring suitable for a WSGI environment. The URLs might also be IRIs. If the path info could not be determined, `None` is returned. Some examples: >>> extract_path_info('http://example.com/app', '/app/hello') u'/hello' >>> extract_path_info('http://example.com/app', ... 'https://example.com/app/hello') u'/hello' >>> extract_path_info('http://example.com/app', ... 'https://example.com/app/hello', ... collapse_http_schemes=False) is None True Instead of providing a base URL you can also pass a WSGI environment. :param environ_or_baseurl: a WSGI environment dict, a base URL or base IRI. This is the root of the application. :param path_or_url: an absolute path from the server root, a relative path (in which case it's the path info) or a full URL. Also accepts IRIs and unicode parameters. :param charset: the charset for byte data in URLs :param errors: the error handling on decode :param collapse_http_schemes: if set to `False` the algorithm does not assume that http and https on the same server point to the same resource. .. versionchanged:: 0.15 The ``errors`` parameter defaults to leaving invalid bytes quoted instead of replacing them. .. versionadded:: 0.6 """ def _normalize_netloc(scheme, netloc): parts = netloc.split(u"@", 1)[-1].split(u":", 1) if len(parts) == 2: netloc, port = parts if (scheme == u"http" and port == u"80") or ( scheme == u"https" and port == u"443" ): port = None else: netloc = parts[0] port = None if port is not None: netloc += u":" + port return netloc # make sure whatever we are working on is a IRI and parse it path = uri_to_iri(path_or_url, charset, errors) if isinstance(environ_or_baseurl, dict): environ_or_baseurl = get_current_url(environ_or_baseurl, root_only=True) base_iri = uri_to_iri(environ_or_baseurl, charset, errors) base_scheme, base_netloc, base_path = url_parse(base_iri)[:3] cur_scheme, cur_netloc, cur_path, = url_parse(url_join(base_iri, path))[:3] # normalize the network location base_netloc = _normalize_netloc(base_scheme, base_netloc) cur_netloc = _normalize_netloc(cur_scheme, cur_netloc) # is that IRI even on a known HTTP scheme? if collapse_http_schemes: for scheme in base_scheme, cur_scheme: if scheme not in (u"http", u"https"): return None else: if not (base_scheme in (u"http", u"https") and base_scheme == cur_scheme): return None # are the netlocs compatible? if base_netloc != cur_netloc: return None # are we below the application path? base_path = base_path.rstrip(u"/") if not cur_path.startswith(base_path): return None return u"/" + cur_path[len(base_path) :].lstrip(u"/")
Extracts the path info from the given URL (or WSGI environment) and path. The path info returned is a unicode string, not a bytestring suitable for a WSGI environment. The URLs might also be IRIs. If the path info could not be determined, `None` is returned. Some examples: >>> extract_path_info('http://example.com/app', '/app/hello') u'/hello' >>> extract_path_info('http://example.com/app', ... 'https://example.com/app/hello') u'/hello' >>> extract_path_info('http://example.com/app', ... 'https://example.com/app/hello', ... collapse_http_schemes=False) is None True Instead of providing a base URL you can also pass a WSGI environment. :param environ_or_baseurl: a WSGI environment dict, a base URL or base IRI. This is the root of the application. :param path_or_url: an absolute path from the server root, a relative path (in which case it's the path info) or a full URL. Also accepts IRIs and unicode parameters. :param charset: the charset for byte data in URLs :param errors: the error handling on decode :param collapse_http_schemes: if set to `False` the algorithm does not assume that http and https on the same server point to the same resource. .. versionchanged:: 0.15 The ``errors`` parameter defaults to leaving invalid bytes quoted instead of replacing them. .. versionadded:: 0.6
Below is the the instruction that describes the task: ### Input: Extracts the path info from the given URL (or WSGI environment) and path. The path info returned is a unicode string, not a bytestring suitable for a WSGI environment. The URLs might also be IRIs. If the path info could not be determined, `None` is returned. Some examples: >>> extract_path_info('http://example.com/app', '/app/hello') u'/hello' >>> extract_path_info('http://example.com/app', ... 'https://example.com/app/hello') u'/hello' >>> extract_path_info('http://example.com/app', ... 'https://example.com/app/hello', ... collapse_http_schemes=False) is None True Instead of providing a base URL you can also pass a WSGI environment. :param environ_or_baseurl: a WSGI environment dict, a base URL or base IRI. This is the root of the application. :param path_or_url: an absolute path from the server root, a relative path (in which case it's the path info) or a full URL. Also accepts IRIs and unicode parameters. :param charset: the charset for byte data in URLs :param errors: the error handling on decode :param collapse_http_schemes: if set to `False` the algorithm does not assume that http and https on the same server point to the same resource. .. versionchanged:: 0.15 The ``errors`` parameter defaults to leaving invalid bytes quoted instead of replacing them. .. versionadded:: 0.6 ### Response: def extract_path_info( environ_or_baseurl, path_or_url, charset="utf-8", errors="werkzeug.url_quote", collapse_http_schemes=True, ): """Extracts the path info from the given URL (or WSGI environment) and path. The path info returned is a unicode string, not a bytestring suitable for a WSGI environment. The URLs might also be IRIs. If the path info could not be determined, `None` is returned. Some examples: >>> extract_path_info('http://example.com/app', '/app/hello') u'/hello' >>> extract_path_info('http://example.com/app', ... 'https://example.com/app/hello') u'/hello' >>> extract_path_info('http://example.com/app', ... 'https://example.com/app/hello', ... collapse_http_schemes=False) is None True Instead of providing a base URL you can also pass a WSGI environment. :param environ_or_baseurl: a WSGI environment dict, a base URL or base IRI. This is the root of the application. :param path_or_url: an absolute path from the server root, a relative path (in which case it's the path info) or a full URL. Also accepts IRIs and unicode parameters. :param charset: the charset for byte data in URLs :param errors: the error handling on decode :param collapse_http_schemes: if set to `False` the algorithm does not assume that http and https on the same server point to the same resource. .. versionchanged:: 0.15 The ``errors`` parameter defaults to leaving invalid bytes quoted instead of replacing them. .. versionadded:: 0.6 """ def _normalize_netloc(scheme, netloc): parts = netloc.split(u"@", 1)[-1].split(u":", 1) if len(parts) == 2: netloc, port = parts if (scheme == u"http" and port == u"80") or ( scheme == u"https" and port == u"443" ): port = None else: netloc = parts[0] port = None if port is not None: netloc += u":" + port return netloc # make sure whatever we are working on is a IRI and parse it path = uri_to_iri(path_or_url, charset, errors) if isinstance(environ_or_baseurl, dict): environ_or_baseurl = get_current_url(environ_or_baseurl, root_only=True) base_iri = uri_to_iri(environ_or_baseurl, charset, errors) base_scheme, base_netloc, base_path = url_parse(base_iri)[:3] cur_scheme, cur_netloc, cur_path, = url_parse(url_join(base_iri, path))[:3] # normalize the network location base_netloc = _normalize_netloc(base_scheme, base_netloc) cur_netloc = _normalize_netloc(cur_scheme, cur_netloc) # is that IRI even on a known HTTP scheme? if collapse_http_schemes: for scheme in base_scheme, cur_scheme: if scheme not in (u"http", u"https"): return None else: if not (base_scheme in (u"http", u"https") and base_scheme == cur_scheme): return None # are the netlocs compatible? if base_netloc != cur_netloc: return None # are we below the application path? base_path = base_path.rstrip(u"/") if not cur_path.startswith(base_path): return None return u"/" + cur_path[len(base_path) :].lstrip(u"/")
def BuildArtifactsRegistry( cls, artifact_definitions_path, custom_artifacts_path): """Build Find Specs from artifacts or filter file if available. Args: artifact_definitions_path (str): path to artifact definitions file. custom_artifacts_path (str): path to custom artifact definitions file. Returns: artifacts.ArtifactDefinitionsRegistry: artifact definitions registry. Raises: RuntimeError: if no valid FindSpecs are built. """ if artifact_definitions_path and not os.path.isdir( artifact_definitions_path): raise errors.BadConfigOption( 'No such artifacts filter file: {0:s}.'.format( artifact_definitions_path)) if custom_artifacts_path and not os.path.isfile(custom_artifacts_path): raise errors.BadConfigOption( 'No such artifacts filter file: {0:s}.'.format(custom_artifacts_path)) registry = artifacts_registry.ArtifactDefinitionsRegistry() reader = artifacts_reader.YamlArtifactsReader() try: registry.ReadFromDirectory(reader, artifact_definitions_path) except (KeyError, artifacts_errors.FormatError) as exception: raise errors.BadConfigOption(( 'Unable to read artifact definitions from: {0:s} with error: ' '{1!s}').format(artifact_definitions_path, exception)) if custom_artifacts_path: try: registry.ReadFromFile(reader, custom_artifacts_path) except (KeyError, artifacts_errors.FormatError) as exception: raise errors.BadConfigOption(( 'Unable to read artifact definitions from: {0:s} with error: ' '{1!s}').format(custom_artifacts_path, exception)) return registry
Build Find Specs from artifacts or filter file if available. Args: artifact_definitions_path (str): path to artifact definitions file. custom_artifacts_path (str): path to custom artifact definitions file. Returns: artifacts.ArtifactDefinitionsRegistry: artifact definitions registry. Raises: RuntimeError: if no valid FindSpecs are built.
Below is the the instruction that describes the task: ### Input: Build Find Specs from artifacts or filter file if available. Args: artifact_definitions_path (str): path to artifact definitions file. custom_artifacts_path (str): path to custom artifact definitions file. Returns: artifacts.ArtifactDefinitionsRegistry: artifact definitions registry. Raises: RuntimeError: if no valid FindSpecs are built. ### Response: def BuildArtifactsRegistry( cls, artifact_definitions_path, custom_artifacts_path): """Build Find Specs from artifacts or filter file if available. Args: artifact_definitions_path (str): path to artifact definitions file. custom_artifacts_path (str): path to custom artifact definitions file. Returns: artifacts.ArtifactDefinitionsRegistry: artifact definitions registry. Raises: RuntimeError: if no valid FindSpecs are built. """ if artifact_definitions_path and not os.path.isdir( artifact_definitions_path): raise errors.BadConfigOption( 'No such artifacts filter file: {0:s}.'.format( artifact_definitions_path)) if custom_artifacts_path and not os.path.isfile(custom_artifacts_path): raise errors.BadConfigOption( 'No such artifacts filter file: {0:s}.'.format(custom_artifacts_path)) registry = artifacts_registry.ArtifactDefinitionsRegistry() reader = artifacts_reader.YamlArtifactsReader() try: registry.ReadFromDirectory(reader, artifact_definitions_path) except (KeyError, artifacts_errors.FormatError) as exception: raise errors.BadConfigOption(( 'Unable to read artifact definitions from: {0:s} with error: ' '{1!s}').format(artifact_definitions_path, exception)) if custom_artifacts_path: try: registry.ReadFromFile(reader, custom_artifacts_path) except (KeyError, artifacts_errors.FormatError) as exception: raise errors.BadConfigOption(( 'Unable to read artifact definitions from: {0:s} with error: ' '{1!s}').format(custom_artifacts_path, exception)) return registry
def save_state_recursively(state, base_path, parent_path, as_copy=False): """Recursively saves a state to a json file It calls this method on all its substates. :param state: State to be stored :param base_path: Path to the state machine :param parent_path: Path to the parent state :param bool as_copy: Temporary storage flag to signal that the given path is not the new file_system_path :return: """ from rafcon.core.states.execution_state import ExecutionState from rafcon.core.states.container_state import ContainerState state_path = os.path.join(parent_path, get_storage_id_for_state(state)) state_path_full = os.path.join(base_path, state_path) if not os.path.exists(state_path_full): os.makedirs(state_path_full) storage_utils.write_dict_to_json(state, os.path.join(state_path_full, FILE_NAME_CORE_DATA)) if not as_copy: state.file_system_path = state_path_full if isinstance(state, ExecutionState): save_script_file_for_state_and_source_path(state, state_path_full, as_copy) save_semantic_data_for_state(state, state_path_full) # create yaml files for all children if isinstance(state, ContainerState): remove_obsolete_folders(state.states.values(), os.path.join(base_path, state_path)) for state in state.states.values(): save_state_recursively(state, base_path, state_path, as_copy)
Recursively saves a state to a json file It calls this method on all its substates. :param state: State to be stored :param base_path: Path to the state machine :param parent_path: Path to the parent state :param bool as_copy: Temporary storage flag to signal that the given path is not the new file_system_path :return:
Below is the the instruction that describes the task: ### Input: Recursively saves a state to a json file It calls this method on all its substates. :param state: State to be stored :param base_path: Path to the state machine :param parent_path: Path to the parent state :param bool as_copy: Temporary storage flag to signal that the given path is not the new file_system_path :return: ### Response: def save_state_recursively(state, base_path, parent_path, as_copy=False): """Recursively saves a state to a json file It calls this method on all its substates. :param state: State to be stored :param base_path: Path to the state machine :param parent_path: Path to the parent state :param bool as_copy: Temporary storage flag to signal that the given path is not the new file_system_path :return: """ from rafcon.core.states.execution_state import ExecutionState from rafcon.core.states.container_state import ContainerState state_path = os.path.join(parent_path, get_storage_id_for_state(state)) state_path_full = os.path.join(base_path, state_path) if not os.path.exists(state_path_full): os.makedirs(state_path_full) storage_utils.write_dict_to_json(state, os.path.join(state_path_full, FILE_NAME_CORE_DATA)) if not as_copy: state.file_system_path = state_path_full if isinstance(state, ExecutionState): save_script_file_for_state_and_source_path(state, state_path_full, as_copy) save_semantic_data_for_state(state, state_path_full) # create yaml files for all children if isinstance(state, ContainerState): remove_obsolete_folders(state.states.values(), os.path.join(base_path, state_path)) for state in state.states.values(): save_state_recursively(state, base_path, state_path, as_copy)
def send_to_contact(self, obj_id, contact_id): """ Send email to a specific contact :param obj_id: int :param contact_id: int :return: dict|str """ response = self._client.session.post( '{url}/{id}/send/contact/{contact_id}'.format( url=self.endpoint_url, id=obj_id, contact_id=contact_id ) ) return self.process_response(response)
Send email to a specific contact :param obj_id: int :param contact_id: int :return: dict|str
Below is the the instruction that describes the task: ### Input: Send email to a specific contact :param obj_id: int :param contact_id: int :return: dict|str ### Response: def send_to_contact(self, obj_id, contact_id): """ Send email to a specific contact :param obj_id: int :param contact_id: int :return: dict|str """ response = self._client.session.post( '{url}/{id}/send/contact/{contact_id}'.format( url=self.endpoint_url, id=obj_id, contact_id=contact_id ) ) return self.process_response(response)
def build_transaction_for_function( address, web3, function_name=None, transaction=None, contract_abi=None, fn_abi=None, *args, **kwargs): """Builds a dictionary with the fields required to make the given transaction Don't call this directly, instead use :meth:`Contract.buildTransaction` on your contract instance. """ prepared_transaction = prepare_transaction( address, web3, fn_identifier=function_name, contract_abi=contract_abi, fn_abi=fn_abi, transaction=transaction, fn_args=args, fn_kwargs=kwargs, ) prepared_transaction = fill_transaction_defaults(web3, prepared_transaction) return prepared_transaction
Builds a dictionary with the fields required to make the given transaction Don't call this directly, instead use :meth:`Contract.buildTransaction` on your contract instance.
Below is the the instruction that describes the task: ### Input: Builds a dictionary with the fields required to make the given transaction Don't call this directly, instead use :meth:`Contract.buildTransaction` on your contract instance. ### Response: def build_transaction_for_function( address, web3, function_name=None, transaction=None, contract_abi=None, fn_abi=None, *args, **kwargs): """Builds a dictionary with the fields required to make the given transaction Don't call this directly, instead use :meth:`Contract.buildTransaction` on your contract instance. """ prepared_transaction = prepare_transaction( address, web3, fn_identifier=function_name, contract_abi=contract_abi, fn_abi=fn_abi, transaction=transaction, fn_args=args, fn_kwargs=kwargs, ) prepared_transaction = fill_transaction_defaults(web3, prepared_transaction) return prepared_transaction
def get_setupcfg_version(): """As get_setup_version(), but configure via setup.cfg. If your project uses setup.cfg to configure setuptools, and hence has at least a "name" key in the [metadata] section, you can set the version as follows: ``` [metadata] name = mypackage version = attr: autover.version.get_setup_version2 ``` If the repository name is different from the package name, specify `reponame` as a [tool:autover] option: ``` [tool:autover] reponame = mypackage ``` To ensure git information is included in a git archive, add setup.cfg to .gitattributes (in addition to __init__): ``` __init__.py export-subst setup.cfg export-subst ``` Then add the following to setup.cfg: ``` [tool:autover.configparser_workaround.archive_commit=$Format:%h$] ``` The above being a section heading rather than just a key is because setuptools requires % to be escaped with %, or it can't parse setup.cfg...but then git export-subst would not work. """ try: import configparser except ImportError: import ConfigParser as configparser # python2 (also prevents dict-like access) import re cfg = "setup.cfg" autover_section = 'tool:autover' config = configparser.ConfigParser() config.read(cfg) pkgname = config.get('metadata','name') reponame = config.get(autover_section,'reponame',vars={'reponame':pkgname}) if autover_section in config.sections() else pkgname ### # hack archive_commit into section heading; see docstring archive_commit = None archive_commit_key = autover_section+'.configparser_workaround.archive_commit' for section in config.sections(): if section.startswith(archive_commit_key): archive_commit = re.match(r".*=\s*(\S*)\s*",section).group(1) ### return get_setup_version(cfg,reponame=reponame,pkgname=pkgname,archive_commit=archive_commit)
As get_setup_version(), but configure via setup.cfg. If your project uses setup.cfg to configure setuptools, and hence has at least a "name" key in the [metadata] section, you can set the version as follows: ``` [metadata] name = mypackage version = attr: autover.version.get_setup_version2 ``` If the repository name is different from the package name, specify `reponame` as a [tool:autover] option: ``` [tool:autover] reponame = mypackage ``` To ensure git information is included in a git archive, add setup.cfg to .gitattributes (in addition to __init__): ``` __init__.py export-subst setup.cfg export-subst ``` Then add the following to setup.cfg: ``` [tool:autover.configparser_workaround.archive_commit=$Format:%h$] ``` The above being a section heading rather than just a key is because setuptools requires % to be escaped with %, or it can't parse setup.cfg...but then git export-subst would not work.
Below is the the instruction that describes the task: ### Input: As get_setup_version(), but configure via setup.cfg. If your project uses setup.cfg to configure setuptools, and hence has at least a "name" key in the [metadata] section, you can set the version as follows: ``` [metadata] name = mypackage version = attr: autover.version.get_setup_version2 ``` If the repository name is different from the package name, specify `reponame` as a [tool:autover] option: ``` [tool:autover] reponame = mypackage ``` To ensure git information is included in a git archive, add setup.cfg to .gitattributes (in addition to __init__): ``` __init__.py export-subst setup.cfg export-subst ``` Then add the following to setup.cfg: ``` [tool:autover.configparser_workaround.archive_commit=$Format:%h$] ``` The above being a section heading rather than just a key is because setuptools requires % to be escaped with %, or it can't parse setup.cfg...but then git export-subst would not work. ### Response: def get_setupcfg_version(): """As get_setup_version(), but configure via setup.cfg. If your project uses setup.cfg to configure setuptools, and hence has at least a "name" key in the [metadata] section, you can set the version as follows: ``` [metadata] name = mypackage version = attr: autover.version.get_setup_version2 ``` If the repository name is different from the package name, specify `reponame` as a [tool:autover] option: ``` [tool:autover] reponame = mypackage ``` To ensure git information is included in a git archive, add setup.cfg to .gitattributes (in addition to __init__): ``` __init__.py export-subst setup.cfg export-subst ``` Then add the following to setup.cfg: ``` [tool:autover.configparser_workaround.archive_commit=$Format:%h$] ``` The above being a section heading rather than just a key is because setuptools requires % to be escaped with %, or it can't parse setup.cfg...but then git export-subst would not work. """ try: import configparser except ImportError: import ConfigParser as configparser # python2 (also prevents dict-like access) import re cfg = "setup.cfg" autover_section = 'tool:autover' config = configparser.ConfigParser() config.read(cfg) pkgname = config.get('metadata','name') reponame = config.get(autover_section,'reponame',vars={'reponame':pkgname}) if autover_section in config.sections() else pkgname ### # hack archive_commit into section heading; see docstring archive_commit = None archive_commit_key = autover_section+'.configparser_workaround.archive_commit' for section in config.sections(): if section.startswith(archive_commit_key): archive_commit = re.match(r".*=\s*(\S*)\s*",section).group(1) ### return get_setup_version(cfg,reponame=reponame,pkgname=pkgname,archive_commit=archive_commit)
def submit_rpc(self, rpc_name, params, flags=0): """ Sends an RPC request. This call will transition session into pending state. If some operation is currently pending on the session, it will be cancelled before sending this request. Spec: http://msdn.microsoft.com/en-us/library/dd357576.aspx :param rpc_name: Name of the RPC to call, can be an instance of :class:`InternalProc` :param params: Stored proc parameters, should be a list of :class:`Column` instances. :param flags: See spec for possible flags. """ logger.info('Sending RPC %s flags=%d', rpc_name, flags) self.messages = [] self.output_params = {} self.cancel_if_pending() self.res_info = None w = self._writer with self.querying_context(tds_base.PacketType.RPC): if tds_base.IS_TDS72_PLUS(self): self._start_query() if tds_base.IS_TDS71_PLUS(self) and isinstance(rpc_name, tds_base.InternalProc): w.put_smallint(-1) w.put_smallint(rpc_name.proc_id) else: if isinstance(rpc_name, tds_base.InternalProc): rpc_name = rpc_name.name w.put_smallint(len(rpc_name)) w.write_ucs2(rpc_name) # # TODO support flags # bit 0 (1 as flag) in TDS7/TDS5 is "recompile" # bit 1 (2 as flag) in TDS7+ is "no metadata" bit this will prevent sending of column infos # w.put_usmallint(flags) self._out_params_indexes = [] for i, param in enumerate(params): if param.flags & tds_base.fByRefValue: self._out_params_indexes.append(i) w.put_byte(len(param.column_name)) w.write_ucs2(param.column_name) # # TODO support other flags (use defaul null/no metadata) # bit 1 (2 as flag) in TDS7+ is "default value" bit # (what's the meaning of "default value" ?) # w.put_byte(param.flags) # TYPE_INFO structure: https://msdn.microsoft.com/en-us/library/dd358284.aspx serializer = param.choose_serializer( type_factory=self._tds.type_factory, collation=self._tds.collation or raw_collation ) type_id = serializer.type w.put_byte(type_id) serializer.write_info(w) serializer.write(w, param.value)
Sends an RPC request. This call will transition session into pending state. If some operation is currently pending on the session, it will be cancelled before sending this request. Spec: http://msdn.microsoft.com/en-us/library/dd357576.aspx :param rpc_name: Name of the RPC to call, can be an instance of :class:`InternalProc` :param params: Stored proc parameters, should be a list of :class:`Column` instances. :param flags: See spec for possible flags.
Below is the the instruction that describes the task: ### Input: Sends an RPC request. This call will transition session into pending state. If some operation is currently pending on the session, it will be cancelled before sending this request. Spec: http://msdn.microsoft.com/en-us/library/dd357576.aspx :param rpc_name: Name of the RPC to call, can be an instance of :class:`InternalProc` :param params: Stored proc parameters, should be a list of :class:`Column` instances. :param flags: See spec for possible flags. ### Response: def submit_rpc(self, rpc_name, params, flags=0): """ Sends an RPC request. This call will transition session into pending state. If some operation is currently pending on the session, it will be cancelled before sending this request. Spec: http://msdn.microsoft.com/en-us/library/dd357576.aspx :param rpc_name: Name of the RPC to call, can be an instance of :class:`InternalProc` :param params: Stored proc parameters, should be a list of :class:`Column` instances. :param flags: See spec for possible flags. """ logger.info('Sending RPC %s flags=%d', rpc_name, flags) self.messages = [] self.output_params = {} self.cancel_if_pending() self.res_info = None w = self._writer with self.querying_context(tds_base.PacketType.RPC): if tds_base.IS_TDS72_PLUS(self): self._start_query() if tds_base.IS_TDS71_PLUS(self) and isinstance(rpc_name, tds_base.InternalProc): w.put_smallint(-1) w.put_smallint(rpc_name.proc_id) else: if isinstance(rpc_name, tds_base.InternalProc): rpc_name = rpc_name.name w.put_smallint(len(rpc_name)) w.write_ucs2(rpc_name) # # TODO support flags # bit 0 (1 as flag) in TDS7/TDS5 is "recompile" # bit 1 (2 as flag) in TDS7+ is "no metadata" bit this will prevent sending of column infos # w.put_usmallint(flags) self._out_params_indexes = [] for i, param in enumerate(params): if param.flags & tds_base.fByRefValue: self._out_params_indexes.append(i) w.put_byte(len(param.column_name)) w.write_ucs2(param.column_name) # # TODO support other flags (use defaul null/no metadata) # bit 1 (2 as flag) in TDS7+ is "default value" bit # (what's the meaning of "default value" ?) # w.put_byte(param.flags) # TYPE_INFO structure: https://msdn.microsoft.com/en-us/library/dd358284.aspx serializer = param.choose_serializer( type_factory=self._tds.type_factory, collation=self._tds.collation or raw_collation ) type_id = serializer.type w.put_byte(type_id) serializer.write_info(w) serializer.write(w, param.value)
def assemble_rom_code(self, asm): """ assemble the given code and program the ROM """ stream = StringIO(asm) worker = assembler.Assembler(self.processor, stream) try: result = worker.assemble() except BaseException as e: return e, None self.rom.program(result) return None, result
assemble the given code and program the ROM
Below is the the instruction that describes the task: ### Input: assemble the given code and program the ROM ### Response: def assemble_rom_code(self, asm): """ assemble the given code and program the ROM """ stream = StringIO(asm) worker = assembler.Assembler(self.processor, stream) try: result = worker.assemble() except BaseException as e: return e, None self.rom.program(result) return None, result
def primeSieve(k): """return a list with length k + 1, showing if list[i] == 1, i is a prime else if list[i] == 0, i is a composite, if list[i] == -1, not defined""" def isPrime(n): """return True is given number n is absolutely prime, return False is otherwise.""" for i in range(2, int(n ** 0.5) + 1): if n % i == 0: return False return True result = [-1] * (k + 1) for i in range(2, int(k + 1)): if isPrime(i): result[i] = 1 else: result[i] = 0 return result
return a list with length k + 1, showing if list[i] == 1, i is a prime else if list[i] == 0, i is a composite, if list[i] == -1, not defined
Below is the the instruction that describes the task: ### Input: return a list with length k + 1, showing if list[i] == 1, i is a prime else if list[i] == 0, i is a composite, if list[i] == -1, not defined ### Response: def primeSieve(k): """return a list with length k + 1, showing if list[i] == 1, i is a prime else if list[i] == 0, i is a composite, if list[i] == -1, not defined""" def isPrime(n): """return True is given number n is absolutely prime, return False is otherwise.""" for i in range(2, int(n ** 0.5) + 1): if n % i == 0: return False return True result = [-1] * (k + 1) for i in range(2, int(k + 1)): if isPrime(i): result[i] = 1 else: result[i] = 0 return result
def do_status(self, subcmd, opts, *args): """Print the status of working copy files and directories. usage: status [PATH...] With no args, print only locally modified items (no network access). With -u, add working revision and server out-of-date information. With -v, print full revision information on every item. The first five columns in the output are each one character wide: First column: Says if item was added, deleted, or otherwise changed ' ' no modifications 'A' Added 'C' Conflicted 'D' Deleted 'G' Merged 'I' Ignored 'M' Modified 'R' Replaced 'X' item is unversioned, but is used by an externals definition '?' item is not under version control '!' item is missing (removed by non-svn command) or incomplete '~' versioned item obstructed by some item of a different kind Second column: Modifications of a file's or directory's properties ' ' no modifications 'C' Conflicted 'M' Modified Third column: Whether the working copy directory is locked ' ' not locked 'L' locked Fourth column: Scheduled commit will contain addition-with-history ' ' no history scheduled with commit '+' history scheduled with commit Fifth column: Whether the item is switched relative to its parent ' ' normal 'S' switched The out-of-date information appears in the eighth column (with -u): '*' a newer revision exists on the server ' ' the working copy is up to date Remaining fields are variable width and delimited by spaces: The working revision (with -u or -v) The last committed revision and last committed author (with -v) The working copy path is always the final field, so it can include spaces. Example output: svn status wc M wc/bar.c A + wc/qax.c svn status -u wc M 965 wc/bar.c * 965 wc/foo.c A + 965 wc/qax.c Head revision: 981 svn status --show-updates --verbose wc M 965 938 kfogel wc/bar.c * 965 922 sussman wc/foo.c A + 965 687 joe wc/qax.c 965 687 joe wc/zig.c Head revision: 981 ${cmd_option_list} """ print "'svn %s' opts: %s" % (subcmd, opts) print "'svn %s' args: %s" % (subcmd, args)
Print the status of working copy files and directories. usage: status [PATH...] With no args, print only locally modified items (no network access). With -u, add working revision and server out-of-date information. With -v, print full revision information on every item. The first five columns in the output are each one character wide: First column: Says if item was added, deleted, or otherwise changed ' ' no modifications 'A' Added 'C' Conflicted 'D' Deleted 'G' Merged 'I' Ignored 'M' Modified 'R' Replaced 'X' item is unversioned, but is used by an externals definition '?' item is not under version control '!' item is missing (removed by non-svn command) or incomplete '~' versioned item obstructed by some item of a different kind Second column: Modifications of a file's or directory's properties ' ' no modifications 'C' Conflicted 'M' Modified Third column: Whether the working copy directory is locked ' ' not locked 'L' locked Fourth column: Scheduled commit will contain addition-with-history ' ' no history scheduled with commit '+' history scheduled with commit Fifth column: Whether the item is switched relative to its parent ' ' normal 'S' switched The out-of-date information appears in the eighth column (with -u): '*' a newer revision exists on the server ' ' the working copy is up to date Remaining fields are variable width and delimited by spaces: The working revision (with -u or -v) The last committed revision and last committed author (with -v) The working copy path is always the final field, so it can include spaces. Example output: svn status wc M wc/bar.c A + wc/qax.c svn status -u wc M 965 wc/bar.c * 965 wc/foo.c A + 965 wc/qax.c Head revision: 981 svn status --show-updates --verbose wc M 965 938 kfogel wc/bar.c * 965 922 sussman wc/foo.c A + 965 687 joe wc/qax.c 965 687 joe wc/zig.c Head revision: 981 ${cmd_option_list}
Below is the the instruction that describes the task: ### Input: Print the status of working copy files and directories. usage: status [PATH...] With no args, print only locally modified items (no network access). With -u, add working revision and server out-of-date information. With -v, print full revision information on every item. The first five columns in the output are each one character wide: First column: Says if item was added, deleted, or otherwise changed ' ' no modifications 'A' Added 'C' Conflicted 'D' Deleted 'G' Merged 'I' Ignored 'M' Modified 'R' Replaced 'X' item is unversioned, but is used by an externals definition '?' item is not under version control '!' item is missing (removed by non-svn command) or incomplete '~' versioned item obstructed by some item of a different kind Second column: Modifications of a file's or directory's properties ' ' no modifications 'C' Conflicted 'M' Modified Third column: Whether the working copy directory is locked ' ' not locked 'L' locked Fourth column: Scheduled commit will contain addition-with-history ' ' no history scheduled with commit '+' history scheduled with commit Fifth column: Whether the item is switched relative to its parent ' ' normal 'S' switched The out-of-date information appears in the eighth column (with -u): '*' a newer revision exists on the server ' ' the working copy is up to date Remaining fields are variable width and delimited by spaces: The working revision (with -u or -v) The last committed revision and last committed author (with -v) The working copy path is always the final field, so it can include spaces. Example output: svn status wc M wc/bar.c A + wc/qax.c svn status -u wc M 965 wc/bar.c * 965 wc/foo.c A + 965 wc/qax.c Head revision: 981 svn status --show-updates --verbose wc M 965 938 kfogel wc/bar.c * 965 922 sussman wc/foo.c A + 965 687 joe wc/qax.c 965 687 joe wc/zig.c Head revision: 981 ${cmd_option_list} ### Response: def do_status(self, subcmd, opts, *args): """Print the status of working copy files and directories. usage: status [PATH...] With no args, print only locally modified items (no network access). With -u, add working revision and server out-of-date information. With -v, print full revision information on every item. The first five columns in the output are each one character wide: First column: Says if item was added, deleted, or otherwise changed ' ' no modifications 'A' Added 'C' Conflicted 'D' Deleted 'G' Merged 'I' Ignored 'M' Modified 'R' Replaced 'X' item is unversioned, but is used by an externals definition '?' item is not under version control '!' item is missing (removed by non-svn command) or incomplete '~' versioned item obstructed by some item of a different kind Second column: Modifications of a file's or directory's properties ' ' no modifications 'C' Conflicted 'M' Modified Third column: Whether the working copy directory is locked ' ' not locked 'L' locked Fourth column: Scheduled commit will contain addition-with-history ' ' no history scheduled with commit '+' history scheduled with commit Fifth column: Whether the item is switched relative to its parent ' ' normal 'S' switched The out-of-date information appears in the eighth column (with -u): '*' a newer revision exists on the server ' ' the working copy is up to date Remaining fields are variable width and delimited by spaces: The working revision (with -u or -v) The last committed revision and last committed author (with -v) The working copy path is always the final field, so it can include spaces. Example output: svn status wc M wc/bar.c A + wc/qax.c svn status -u wc M 965 wc/bar.c * 965 wc/foo.c A + 965 wc/qax.c Head revision: 981 svn status --show-updates --verbose wc M 965 938 kfogel wc/bar.c * 965 922 sussman wc/foo.c A + 965 687 joe wc/qax.c 965 687 joe wc/zig.c Head revision: 981 ${cmd_option_list} """ print "'svn %s' opts: %s" % (subcmd, opts) print "'svn %s' args: %s" % (subcmd, args)
def accuracy(self): """ Calculates the accuracy of the tree by comparing the model predictions to the dataset (TP + TN) / (TP + TN + FP + FN) == (T / (T + F)) """ sub_observed = np.array([self.observed.metadata[i] for i in self.observed.arr]) return float((self.model_predictions() == sub_observed).sum()) / self.data_size
Calculates the accuracy of the tree by comparing the model predictions to the dataset (TP + TN) / (TP + TN + FP + FN) == (T / (T + F))
Below is the the instruction that describes the task: ### Input: Calculates the accuracy of the tree by comparing the model predictions to the dataset (TP + TN) / (TP + TN + FP + FN) == (T / (T + F)) ### Response: def accuracy(self): """ Calculates the accuracy of the tree by comparing the model predictions to the dataset (TP + TN) / (TP + TN + FP + FN) == (T / (T + F)) """ sub_observed = np.array([self.observed.metadata[i] for i in self.observed.arr]) return float((self.model_predictions() == sub_observed).sum()) / self.data_size
def _parse_paginated_members(self, direction="children"): """ Launch parsing of children """ page = self._last_page_parsed[direction] if not page: page = 1 else: page = int(page) while page: if page > 1: response = self._resolver.endpoint.get_collection( collection_id=self.id, page=page, nav=direction ) else: response = self._resolver.endpoint.get_collection( collection_id=self.id, nav=direction ) response.raise_for_status() data = response.json() data = expand(data)[0] if direction == "children": self.children.update({ o.id: o for o in type(self).parse_member( obj=data, collection=self, direction=direction, resolver=self._resolver ) }) else: self.parents.update({ o for o in type(self).parse_member( obj=data, collection=self, direction=direction, resolver=self._resolver ) }) self._last_page_parsed[direction] = page page = None if "https://www.w3.org/ns/hydra/core#view" in data: if "https://www.w3.org/ns/hydra/core#next" in data["https://www.w3.org/ns/hydra/core#view"][0]: page = int(_re_page.findall( data["https://www.w3.org/ns/hydra/core#view"] [0]["https://www.w3.org/ns/hydra/core#next"] [0]["@value"] )[0]) self._parsed[direction] = True
Launch parsing of children
Below is the the instruction that describes the task: ### Input: Launch parsing of children ### Response: def _parse_paginated_members(self, direction="children"): """ Launch parsing of children """ page = self._last_page_parsed[direction] if not page: page = 1 else: page = int(page) while page: if page > 1: response = self._resolver.endpoint.get_collection( collection_id=self.id, page=page, nav=direction ) else: response = self._resolver.endpoint.get_collection( collection_id=self.id, nav=direction ) response.raise_for_status() data = response.json() data = expand(data)[0] if direction == "children": self.children.update({ o.id: o for o in type(self).parse_member( obj=data, collection=self, direction=direction, resolver=self._resolver ) }) else: self.parents.update({ o for o in type(self).parse_member( obj=data, collection=self, direction=direction, resolver=self._resolver ) }) self._last_page_parsed[direction] = page page = None if "https://www.w3.org/ns/hydra/core#view" in data: if "https://www.w3.org/ns/hydra/core#next" in data["https://www.w3.org/ns/hydra/core#view"][0]: page = int(_re_page.findall( data["https://www.w3.org/ns/hydra/core#view"] [0]["https://www.w3.org/ns/hydra/core#next"] [0]["@value"] )[0]) self._parsed[direction] = True
def get_asset(self): """ Returns an instance of the Asset Service. """ import predix.data.asset asset = predix.data.asset.Asset() return asset
Returns an instance of the Asset Service.
Below is the the instruction that describes the task: ### Input: Returns an instance of the Asset Service. ### Response: def get_asset(self): """ Returns an instance of the Asset Service. """ import predix.data.asset asset = predix.data.asset.Asset() return asset
def real(prompt=None, empty=False): """Prompt a real number. Parameters ---------- prompt : str, optional Use an alternative prompt. empty : bool, optional Allow an empty response. Returns ------- float or None A float if the user entered a valid real number. None if the user pressed only Enter and ``empty`` was True. """ s = _prompt_input(prompt) if empty and not s: return None else: try: return float(s) except ValueError: return real(prompt=prompt, empty=empty)
Prompt a real number. Parameters ---------- prompt : str, optional Use an alternative prompt. empty : bool, optional Allow an empty response. Returns ------- float or None A float if the user entered a valid real number. None if the user pressed only Enter and ``empty`` was True.
Below is the the instruction that describes the task: ### Input: Prompt a real number. Parameters ---------- prompt : str, optional Use an alternative prompt. empty : bool, optional Allow an empty response. Returns ------- float or None A float if the user entered a valid real number. None if the user pressed only Enter and ``empty`` was True. ### Response: def real(prompt=None, empty=False): """Prompt a real number. Parameters ---------- prompt : str, optional Use an alternative prompt. empty : bool, optional Allow an empty response. Returns ------- float or None A float if the user entered a valid real number. None if the user pressed only Enter and ``empty`` was True. """ s = _prompt_input(prompt) if empty and not s: return None else: try: return float(s) except ValueError: return real(prompt=prompt, empty=empty)
def data_from_dict(self, data): """ Populate model parameters from a dictionary of parameters Parameters ---------- data : dict List of parameter dictionaries Returns ------- None """ nvars = [] for key, val in data.items(): self.__dict__[key].extend(val) # assure the same parameter matrix size if len(nvars) > 1 and len(val) != nvars[-1]: raise IndexError( 'Model <{}> parameter <{}> must have the same length'. format(self._name, key)) nvars.append(len(val)) # assign idx-uid mapping for i, idx in zip(range(self.n), self.idx): self.uid[idx] = i
Populate model parameters from a dictionary of parameters Parameters ---------- data : dict List of parameter dictionaries Returns ------- None
Below is the the instruction that describes the task: ### Input: Populate model parameters from a dictionary of parameters Parameters ---------- data : dict List of parameter dictionaries Returns ------- None ### Response: def data_from_dict(self, data): """ Populate model parameters from a dictionary of parameters Parameters ---------- data : dict List of parameter dictionaries Returns ------- None """ nvars = [] for key, val in data.items(): self.__dict__[key].extend(val) # assure the same parameter matrix size if len(nvars) > 1 and len(val) != nvars[-1]: raise IndexError( 'Model <{}> parameter <{}> must have the same length'. format(self._name, key)) nvars.append(len(val)) # assign idx-uid mapping for i, idx in zip(range(self.n), self.idx): self.uid[idx] = i
def candidates(word): "Generate possible spelling corrections for word." return (known([word]) or known(edits1(word)) or known(edits2(word)) or [word])
Generate possible spelling corrections for word.
Below is the the instruction that describes the task: ### Input: Generate possible spelling corrections for word. ### Response: def candidates(word): "Generate possible spelling corrections for word." return (known([word]) or known(edits1(word)) or known(edits2(word)) or [word])
def pix2ang(nside, pix): r"""Convert pixel to angle :math:`\theta` :math:`\phi`. nside and pix are broadcast with numpy rules. Returns: theta, phi This is translated from chealpix.c; but refer to Section 4.1 of http://adsabs.harvard.edu/abs/2005ApJ...622..759G """ nside, pix = numpy.lib.stride_tricks.broadcast_arrays(nside, pix) ncap = nside * (nside - 1) * 2 npix = 12 * nside * nside def northpole(pix, npix): iring = (1 + ((1 + 2 * pix) ** 0.5)).astype('i8') // 2 iphi = (pix + 1) - 2 * iring * (iring - 1) z = 1.0 - (iring*iring) * 4. / npix phi = (iphi - 0.5) * 0.5 * numpy.pi / iring return z, phi def equatorial(pix, nside, npix, ncap): ip = pix - ncap iring = ip // (4 * nside) + nside iphi = ip % (4 * nside) + 1 fodd = (((iring + nside) &1) + 1.) * 0.5 z = (2 * nside - iring) * nside * 8.0 / npix phi = (iphi - fodd) * (0.5 * numpy.pi) / nside return z, phi def southpole(pix, npix): ip = npix - pix iring = (1 + ((2 * ip - 1)**0.5).astype('i8')) // 2 iphi = 4 * iring + 1 - (ip - 2 * iring * (iring - 1)) z = -1 + (iring * iring) * 4. / npix phi = (iphi - 0.5 ) * 0.5 * numpy.pi / iring return z, phi mask1 = pix < ncap mask2 = (~mask1) & (pix < npix - ncap) mask3 = pix >= npix - ncap z = numpy.zeros(pix.shape, dtype='f8') phi = numpy.zeros(pix.shape, dtype='f8') z[mask1], phi[mask1] = northpole(pix[mask1], npix[mask1]) z[mask2], phi[mask2] = equatorial(pix[mask2], nside[mask2], npix[mask2], ncap[mask2]) z[mask3], phi[mask3] = southpole(pix[mask3], npix[mask3]) return numpy.arccos(z), phi
r"""Convert pixel to angle :math:`\theta` :math:`\phi`. nside and pix are broadcast with numpy rules. Returns: theta, phi This is translated from chealpix.c; but refer to Section 4.1 of http://adsabs.harvard.edu/abs/2005ApJ...622..759G
Below is the the instruction that describes the task: ### Input: r"""Convert pixel to angle :math:`\theta` :math:`\phi`. nside and pix are broadcast with numpy rules. Returns: theta, phi This is translated from chealpix.c; but refer to Section 4.1 of http://adsabs.harvard.edu/abs/2005ApJ...622..759G ### Response: def pix2ang(nside, pix): r"""Convert pixel to angle :math:`\theta` :math:`\phi`. nside and pix are broadcast with numpy rules. Returns: theta, phi This is translated from chealpix.c; but refer to Section 4.1 of http://adsabs.harvard.edu/abs/2005ApJ...622..759G """ nside, pix = numpy.lib.stride_tricks.broadcast_arrays(nside, pix) ncap = nside * (nside - 1) * 2 npix = 12 * nside * nside def northpole(pix, npix): iring = (1 + ((1 + 2 * pix) ** 0.5)).astype('i8') // 2 iphi = (pix + 1) - 2 * iring * (iring - 1) z = 1.0 - (iring*iring) * 4. / npix phi = (iphi - 0.5) * 0.5 * numpy.pi / iring return z, phi def equatorial(pix, nside, npix, ncap): ip = pix - ncap iring = ip // (4 * nside) + nside iphi = ip % (4 * nside) + 1 fodd = (((iring + nside) &1) + 1.) * 0.5 z = (2 * nside - iring) * nside * 8.0 / npix phi = (iphi - fodd) * (0.5 * numpy.pi) / nside return z, phi def southpole(pix, npix): ip = npix - pix iring = (1 + ((2 * ip - 1)**0.5).astype('i8')) // 2 iphi = 4 * iring + 1 - (ip - 2 * iring * (iring - 1)) z = -1 + (iring * iring) * 4. / npix phi = (iphi - 0.5 ) * 0.5 * numpy.pi / iring return z, phi mask1 = pix < ncap mask2 = (~mask1) & (pix < npix - ncap) mask3 = pix >= npix - ncap z = numpy.zeros(pix.shape, dtype='f8') phi = numpy.zeros(pix.shape, dtype='f8') z[mask1], phi[mask1] = northpole(pix[mask1], npix[mask1]) z[mask2], phi[mask2] = equatorial(pix[mask2], nside[mask2], npix[mask2], ncap[mask2]) z[mask3], phi[mask3] = southpole(pix[mask3], npix[mask3]) return numpy.arccos(z), phi
def get_SQL(self, schema, query, **sql_options): """ convert the query instance into SQL this is the glue method that translates the generic Query() instance to the SQL specific query, this is where the magic happens **sql_options -- dict count_query -- boolean -- true if this is a count query SELECT only_where_clause -- boolean -- true to only return after WHERE ... """ only_where_clause = sql_options.get('only_where_clause', False) symbol_map = { 'in': {'symbol': 'IN', 'list': True}, 'nin': {'symbol': 'NOT IN', 'list': True}, 'is': {'symbol': '=', 'none_symbol': 'IS'}, 'not': {'symbol': '!=', 'none_symbol': 'IS NOT'}, 'gt': {'symbol': '>'}, 'gte': {'symbol': '>='}, 'lt': {'symbol': '<'}, 'lte': {'symbol': '<='}, # https://www.tutorialspoint.com/postgresql/postgresql_like_clause.htm # https://www.tutorialspoint.com/sqlite/sqlite_like_clause.htm 'like': {'symbol': 'LIKE'}, 'nlike': {'symbol': 'NOT LIKE'}, } query_args = [] query_str = [] if not only_where_clause: query_str.append('SELECT') select_fields = query.fields_select if select_fields: distinct = "DISTINCT " if select_fields.options.get("unique", False) else "" select_fields_str = distinct + ',{}'.format(os.linesep).join( (self._normalize_name(f) for f in select_fields.names()) ) else: select_fields_str = "*" if sql_options.get('count_query', False): query_str.append(' count({}) as ct'.format(select_fields_str)) else: query_str.append(' {}'.format(select_fields_str)) query_str.append('FROM') query_str.append(" {}".format(self._normalize_table_name(schema))) if query.fields_where: query_str.append('WHERE') for i, field in enumerate(query.fields_where): if i > 0: query_str.append('AND') field_str = '' field_args = [] sd = symbol_map[field[0]] # field[0], field[1], field[2], field[3] _, field_name, field_val, field_kwargs = field field_str, field_args = self._normalize_val_SQL( schema, sd, field_name, field_val, field_kwargs ) query_str.append(' {}'.format(field_str)) query_args.extend(field_args) if query.fields_sort: query_sort_str = [] query_str.append('ORDER BY') for field in query.fields_sort: sort_dir_str = 'ASC' if field[0] > 0 else 'DESC' if field[2]: field_sort_str, field_sort_args = self._normalize_sort_SQL(field[1], field[2], sort_dir_str) query_sort_str.append(field_sort_str) query_args.extend(field_sort_args) else: query_sort_str.append(' {} {}'.format(field[1], sort_dir_str)) query_str.append(',{}'.format(os.linesep).join(query_sort_str)) if query.bounds: offset = query.bounds.offset limit = 1 if sql_options.get('one_query', False) else query.bounds.limit query_str.append('LIMIT {} OFFSET {}'.format( limit, offset )) query_str = os.linesep.join(query_str) return query_str, query_args
convert the query instance into SQL this is the glue method that translates the generic Query() instance to the SQL specific query, this is where the magic happens **sql_options -- dict count_query -- boolean -- true if this is a count query SELECT only_where_clause -- boolean -- true to only return after WHERE ...
Below is the the instruction that describes the task: ### Input: convert the query instance into SQL this is the glue method that translates the generic Query() instance to the SQL specific query, this is where the magic happens **sql_options -- dict count_query -- boolean -- true if this is a count query SELECT only_where_clause -- boolean -- true to only return after WHERE ... ### Response: def get_SQL(self, schema, query, **sql_options): """ convert the query instance into SQL this is the glue method that translates the generic Query() instance to the SQL specific query, this is where the magic happens **sql_options -- dict count_query -- boolean -- true if this is a count query SELECT only_where_clause -- boolean -- true to only return after WHERE ... """ only_where_clause = sql_options.get('only_where_clause', False) symbol_map = { 'in': {'symbol': 'IN', 'list': True}, 'nin': {'symbol': 'NOT IN', 'list': True}, 'is': {'symbol': '=', 'none_symbol': 'IS'}, 'not': {'symbol': '!=', 'none_symbol': 'IS NOT'}, 'gt': {'symbol': '>'}, 'gte': {'symbol': '>='}, 'lt': {'symbol': '<'}, 'lte': {'symbol': '<='}, # https://www.tutorialspoint.com/postgresql/postgresql_like_clause.htm # https://www.tutorialspoint.com/sqlite/sqlite_like_clause.htm 'like': {'symbol': 'LIKE'}, 'nlike': {'symbol': 'NOT LIKE'}, } query_args = [] query_str = [] if not only_where_clause: query_str.append('SELECT') select_fields = query.fields_select if select_fields: distinct = "DISTINCT " if select_fields.options.get("unique", False) else "" select_fields_str = distinct + ',{}'.format(os.linesep).join( (self._normalize_name(f) for f in select_fields.names()) ) else: select_fields_str = "*" if sql_options.get('count_query', False): query_str.append(' count({}) as ct'.format(select_fields_str)) else: query_str.append(' {}'.format(select_fields_str)) query_str.append('FROM') query_str.append(" {}".format(self._normalize_table_name(schema))) if query.fields_where: query_str.append('WHERE') for i, field in enumerate(query.fields_where): if i > 0: query_str.append('AND') field_str = '' field_args = [] sd = symbol_map[field[0]] # field[0], field[1], field[2], field[3] _, field_name, field_val, field_kwargs = field field_str, field_args = self._normalize_val_SQL( schema, sd, field_name, field_val, field_kwargs ) query_str.append(' {}'.format(field_str)) query_args.extend(field_args) if query.fields_sort: query_sort_str = [] query_str.append('ORDER BY') for field in query.fields_sort: sort_dir_str = 'ASC' if field[0] > 0 else 'DESC' if field[2]: field_sort_str, field_sort_args = self._normalize_sort_SQL(field[1], field[2], sort_dir_str) query_sort_str.append(field_sort_str) query_args.extend(field_sort_args) else: query_sort_str.append(' {} {}'.format(field[1], sort_dir_str)) query_str.append(',{}'.format(os.linesep).join(query_sort_str)) if query.bounds: offset = query.bounds.offset limit = 1 if sql_options.get('one_query', False) else query.bounds.limit query_str.append('LIMIT {} OFFSET {}'.format( limit, offset )) query_str = os.linesep.join(query_str) return query_str, query_args
def get_from_clause(self): """ Add the JOINS for related multilingual fields filtering. """ result = super(MultilingualSQLCompiler, self).get_from_clause() if not self.query.include_translation_data: return result from_ = result[0] for join in self.query.extra_join.values(): from_.append(join) return (from_, result[1])
Add the JOINS for related multilingual fields filtering.
Below is the the instruction that describes the task: ### Input: Add the JOINS for related multilingual fields filtering. ### Response: def get_from_clause(self): """ Add the JOINS for related multilingual fields filtering. """ result = super(MultilingualSQLCompiler, self).get_from_clause() if not self.query.include_translation_data: return result from_ = result[0] for join in self.query.extra_join.values(): from_.append(join) return (from_, result[1])
def execute(self, command=None, container_id=None, sudo=False, stream=False): '''execute a command to a container instance based on container_id Parameters ========== container_id: the container_id to delete command: the command to execute to the container sudo: whether to issue the command with sudo (or not) a container started with sudo will belong to the root user If started by a user, the user needs to control deleting it stream: if True, return an iterate to iterate over results of exec. default is False, will return full output as string. Returns ======= return_code: the return code from the delete command. 0 indicates a successful delete, 255 indicates not. ''' sudo = self._get_sudo(sudo) container_id = self.get_container_id(container_id) # singularity oci delete cmd = self._init_command('exec') # Add the container_id cmd.append(container_id) if command != None: if not isinstance(command, list): command = [command] cmd = cmd + command # Execute the command, return response to user if stream: return stream_command(cmd, sudo=sudo) return self._run_command(cmd, sudo=sudo, quiet=True)
execute a command to a container instance based on container_id Parameters ========== container_id: the container_id to delete command: the command to execute to the container sudo: whether to issue the command with sudo (or not) a container started with sudo will belong to the root user If started by a user, the user needs to control deleting it stream: if True, return an iterate to iterate over results of exec. default is False, will return full output as string. Returns ======= return_code: the return code from the delete command. 0 indicates a successful delete, 255 indicates not.
Below is the the instruction that describes the task: ### Input: execute a command to a container instance based on container_id Parameters ========== container_id: the container_id to delete command: the command to execute to the container sudo: whether to issue the command with sudo (or not) a container started with sudo will belong to the root user If started by a user, the user needs to control deleting it stream: if True, return an iterate to iterate over results of exec. default is False, will return full output as string. Returns ======= return_code: the return code from the delete command. 0 indicates a successful delete, 255 indicates not. ### Response: def execute(self, command=None, container_id=None, sudo=False, stream=False): '''execute a command to a container instance based on container_id Parameters ========== container_id: the container_id to delete command: the command to execute to the container sudo: whether to issue the command with sudo (or not) a container started with sudo will belong to the root user If started by a user, the user needs to control deleting it stream: if True, return an iterate to iterate over results of exec. default is False, will return full output as string. Returns ======= return_code: the return code from the delete command. 0 indicates a successful delete, 255 indicates not. ''' sudo = self._get_sudo(sudo) container_id = self.get_container_id(container_id) # singularity oci delete cmd = self._init_command('exec') # Add the container_id cmd.append(container_id) if command != None: if not isinstance(command, list): command = [command] cmd = cmd + command # Execute the command, return response to user if stream: return stream_command(cmd, sudo=sudo) return self._run_command(cmd, sudo=sudo, quiet=True)
def fit_texture(layer): """Fits a layer into a texture by scaling each axis to (0, 1). Does not preserve aspect ratio (TODO: make this an option). Args: layer (layer): the layer to scale Returns: texture: A texture. """ x, y = layer x = (x - np.nanmin(x)) / (np.nanmax(x) - np.nanmin(x)) y = (y - np.nanmin(y)) / (np.nanmax(y) - np.nanmin(y)) return x, y
Fits a layer into a texture by scaling each axis to (0, 1). Does not preserve aspect ratio (TODO: make this an option). Args: layer (layer): the layer to scale Returns: texture: A texture.
Below is the the instruction that describes the task: ### Input: Fits a layer into a texture by scaling each axis to (0, 1). Does not preserve aspect ratio (TODO: make this an option). Args: layer (layer): the layer to scale Returns: texture: A texture. ### Response: def fit_texture(layer): """Fits a layer into a texture by scaling each axis to (0, 1). Does not preserve aspect ratio (TODO: make this an option). Args: layer (layer): the layer to scale Returns: texture: A texture. """ x, y = layer x = (x - np.nanmin(x)) / (np.nanmax(x) - np.nanmin(x)) y = (y - np.nanmin(y)) / (np.nanmax(y) - np.nanmin(y)) return x, y
def build_task(current_target): """ Build a target. Arguments target - The target to build. """ target = current_target.config try: builder = _make_builder(target, current_target) build_path = _get_build_path(target, builder) if not os.path.exists(build_path): os.makedirs(build_path) builder.configure(src_dir=target.get("dp.src_dir"), build_dir=build_path) builder.build(build_dir=build_path) no_install = devpipeline_core.toolsupport.choose_tool_key( current_target, _NO_INSTALL_KEYS ) if no_install not in target: install_path = target.get( devpipeline_core.toolsupport.choose_tool_key( current_target, _INSTALL_PATH_KEYS ), fallback="install", ) builder.install(build_dir=build_path, install_dir=install_path) _find_file_paths(target, os.path.join(build_path, install_path)) except devpipeline_core.toolsupport.MissingToolKey as mtk: current_target.executor.warning(mtk)
Build a target. Arguments target - The target to build.
Below is the the instruction that describes the task: ### Input: Build a target. Arguments target - The target to build. ### Response: def build_task(current_target): """ Build a target. Arguments target - The target to build. """ target = current_target.config try: builder = _make_builder(target, current_target) build_path = _get_build_path(target, builder) if not os.path.exists(build_path): os.makedirs(build_path) builder.configure(src_dir=target.get("dp.src_dir"), build_dir=build_path) builder.build(build_dir=build_path) no_install = devpipeline_core.toolsupport.choose_tool_key( current_target, _NO_INSTALL_KEYS ) if no_install not in target: install_path = target.get( devpipeline_core.toolsupport.choose_tool_key( current_target, _INSTALL_PATH_KEYS ), fallback="install", ) builder.install(build_dir=build_path, install_dir=install_path) _find_file_paths(target, os.path.join(build_path, install_path)) except devpipeline_core.toolsupport.MissingToolKey as mtk: current_target.executor.warning(mtk)
def between(value, min=None, max=None): """ Validate that a number is between minimum and/or maximum value. This will work with any comparable type, such as floats, decimals and dates not just integers. This validator is originally based on `WTForms NumberRange validator`_. .. _WTForms NumberRange validator: https://github.com/wtforms/wtforms/blob/master/wtforms/validators.py Examples:: >>> from datetime import datetime >>> between(5, min=2) True >>> between(13.2, min=13, max=14) True >>> between(500, max=400) ValidationFailure(func=between, args=...) >>> between( ... datetime(2000, 11, 11), ... min=datetime(1999, 11, 11) ... ) True :param min: The minimum required value of the number. If not provided, minimum value will not be checked. :param max: The maximum value of the number. If not provided, maximum value will not be checked. .. versionadded:: 0.2 """ if min is None and max is None: raise AssertionError( 'At least one of `min` or `max` must be specified.' ) if min is None: min = Min if max is None: max = Max try: min_gt_max = min > max except TypeError: min_gt_max = max < min if min_gt_max: raise AssertionError('`min` cannot be more than `max`.') return min <= value and max >= value
Validate that a number is between minimum and/or maximum value. This will work with any comparable type, such as floats, decimals and dates not just integers. This validator is originally based on `WTForms NumberRange validator`_. .. _WTForms NumberRange validator: https://github.com/wtforms/wtforms/blob/master/wtforms/validators.py Examples:: >>> from datetime import datetime >>> between(5, min=2) True >>> between(13.2, min=13, max=14) True >>> between(500, max=400) ValidationFailure(func=between, args=...) >>> between( ... datetime(2000, 11, 11), ... min=datetime(1999, 11, 11) ... ) True :param min: The minimum required value of the number. If not provided, minimum value will not be checked. :param max: The maximum value of the number. If not provided, maximum value will not be checked. .. versionadded:: 0.2
Below is the the instruction that describes the task: ### Input: Validate that a number is between minimum and/or maximum value. This will work with any comparable type, such as floats, decimals and dates not just integers. This validator is originally based on `WTForms NumberRange validator`_. .. _WTForms NumberRange validator: https://github.com/wtforms/wtforms/blob/master/wtforms/validators.py Examples:: >>> from datetime import datetime >>> between(5, min=2) True >>> between(13.2, min=13, max=14) True >>> between(500, max=400) ValidationFailure(func=between, args=...) >>> between( ... datetime(2000, 11, 11), ... min=datetime(1999, 11, 11) ... ) True :param min: The minimum required value of the number. If not provided, minimum value will not be checked. :param max: The maximum value of the number. If not provided, maximum value will not be checked. .. versionadded:: 0.2 ### Response: def between(value, min=None, max=None): """ Validate that a number is between minimum and/or maximum value. This will work with any comparable type, such as floats, decimals and dates not just integers. This validator is originally based on `WTForms NumberRange validator`_. .. _WTForms NumberRange validator: https://github.com/wtforms/wtforms/blob/master/wtforms/validators.py Examples:: >>> from datetime import datetime >>> between(5, min=2) True >>> between(13.2, min=13, max=14) True >>> between(500, max=400) ValidationFailure(func=between, args=...) >>> between( ... datetime(2000, 11, 11), ... min=datetime(1999, 11, 11) ... ) True :param min: The minimum required value of the number. If not provided, minimum value will not be checked. :param max: The maximum value of the number. If not provided, maximum value will not be checked. .. versionadded:: 0.2 """ if min is None and max is None: raise AssertionError( 'At least one of `min` or `max` must be specified.' ) if min is None: min = Min if max is None: max = Max try: min_gt_max = min > max except TypeError: min_gt_max = max < min if min_gt_max: raise AssertionError('`min` cannot be more than `max`.') return min <= value and max >= value
def modify_password(self, username, newpwd, oldpwd): """ Params: username - user name newpwd - new password oldpwd - old password """ ret = self.command( 'userManager.cgi?action=modifyPassword&name={0}&pwd={1}' '&pwdOld={2}'.format(username, newpwd, oldpwd) ) return ret.content.decode('utf-8')
Params: username - user name newpwd - new password oldpwd - old password
Below is the the instruction that describes the task: ### Input: Params: username - user name newpwd - new password oldpwd - old password ### Response: def modify_password(self, username, newpwd, oldpwd): """ Params: username - user name newpwd - new password oldpwd - old password """ ret = self.command( 'userManager.cgi?action=modifyPassword&name={0}&pwd={1}' '&pwdOld={2}'.format(username, newpwd, oldpwd) ) return ret.content.decode('utf-8')
def extract_text(self, node): """Return the string representation of the node or list of nodes by parsing the subnodes, but returning the result as a string instead of adding it to `self.pieces`. Note that this allows extracting text even if the node is in the ignore list. """ if not isinstance(node, (list, tuple)): node = [node] pieces, self.pieces = self.pieces, [''] for n in node: for sn in n.childNodes: self.parse(sn) ret = ''.join(self.pieces) self.pieces = pieces return ret
Return the string representation of the node or list of nodes by parsing the subnodes, but returning the result as a string instead of adding it to `self.pieces`. Note that this allows extracting text even if the node is in the ignore list.
Below is the the instruction that describes the task: ### Input: Return the string representation of the node or list of nodes by parsing the subnodes, but returning the result as a string instead of adding it to `self.pieces`. Note that this allows extracting text even if the node is in the ignore list. ### Response: def extract_text(self, node): """Return the string representation of the node or list of nodes by parsing the subnodes, but returning the result as a string instead of adding it to `self.pieces`. Note that this allows extracting text even if the node is in the ignore list. """ if not isinstance(node, (list, tuple)): node = [node] pieces, self.pieces = self.pieces, [''] for n in node: for sn in n.childNodes: self.parse(sn) ret = ''.join(self.pieces) self.pieces = pieces return ret
def get_rule(self, field_id): """ Returns the rule for the field identified by the id. If it is set as not being compulsory, the rule will be adapted to accept string composed only of white characters. :param field_id: unique id in the system for the field :return: the rule of a field """ if field_id in self._fields: # Field already exists field = self._fields[field_id] else: # Field does not exist # It is created field = self._create_field(field_id) # Field is saved self._fields[field_id] = field return field
Returns the rule for the field identified by the id. If it is set as not being compulsory, the rule will be adapted to accept string composed only of white characters. :param field_id: unique id in the system for the field :return: the rule of a field
Below is the the instruction that describes the task: ### Input: Returns the rule for the field identified by the id. If it is set as not being compulsory, the rule will be adapted to accept string composed only of white characters. :param field_id: unique id in the system for the field :return: the rule of a field ### Response: def get_rule(self, field_id): """ Returns the rule for the field identified by the id. If it is set as not being compulsory, the rule will be adapted to accept string composed only of white characters. :param field_id: unique id in the system for the field :return: the rule of a field """ if field_id in self._fields: # Field already exists field = self._fields[field_id] else: # Field does not exist # It is created field = self._create_field(field_id) # Field is saved self._fields[field_id] = field return field
def Deserialize(self, reader): """ Deserialize full object. Args: reader (neo.IO.BinaryReader): """ usage = reader.ReadByte() self.Usage = usage if usage == TransactionAttributeUsage.ContractHash or usage == TransactionAttributeUsage.Vote or \ (usage >= TransactionAttributeUsage.Hash1 and usage <= TransactionAttributeUsage.Hash15): self.Data = reader.ReadBytes(32) elif usage == TransactionAttributeUsage.ECDH02 or usage == TransactionAttributeUsage.ECDH03: self.Data = bytearray(usage) + bytearray(reader.ReadBytes(32)) elif usage == TransactionAttributeUsage.Script: self.Data = reader.ReadBytes(20) elif usage == TransactionAttributeUsage.DescriptionUrl: self.Data = reader.ReadBytes(reader.ReadByte()) elif usage == TransactionAttributeUsage.Description or usage >= TransactionAttributeUsage.Remark: self.Data = reader.ReadVarBytes(max=self.MAX_ATTR_DATA_SIZE) else: logger.error("format error!!!")
Deserialize full object. Args: reader (neo.IO.BinaryReader):
Below is the the instruction that describes the task: ### Input: Deserialize full object. Args: reader (neo.IO.BinaryReader): ### Response: def Deserialize(self, reader): """ Deserialize full object. Args: reader (neo.IO.BinaryReader): """ usage = reader.ReadByte() self.Usage = usage if usage == TransactionAttributeUsage.ContractHash or usage == TransactionAttributeUsage.Vote or \ (usage >= TransactionAttributeUsage.Hash1 and usage <= TransactionAttributeUsage.Hash15): self.Data = reader.ReadBytes(32) elif usage == TransactionAttributeUsage.ECDH02 or usage == TransactionAttributeUsage.ECDH03: self.Data = bytearray(usage) + bytearray(reader.ReadBytes(32)) elif usage == TransactionAttributeUsage.Script: self.Data = reader.ReadBytes(20) elif usage == TransactionAttributeUsage.DescriptionUrl: self.Data = reader.ReadBytes(reader.ReadByte()) elif usage == TransactionAttributeUsage.Description or usage >= TransactionAttributeUsage.Remark: self.Data = reader.ReadVarBytes(max=self.MAX_ATTR_DATA_SIZE) else: logger.error("format error!!!")
def by_group_name(cls, group_name, db_session=None): """ fetch group by name :param group_name: :param db_session: :return: """ db_session = get_db_session(db_session) query = db_session.query(cls.model).filter(cls.model.group_name == group_name) return query.first()
fetch group by name :param group_name: :param db_session: :return:
Below is the the instruction that describes the task: ### Input: fetch group by name :param group_name: :param db_session: :return: ### Response: def by_group_name(cls, group_name, db_session=None): """ fetch group by name :param group_name: :param db_session: :return: """ db_session = get_db_session(db_session) query = db_session.query(cls.model).filter(cls.model.group_name == group_name) return query.first()
def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._document_patched`` if it exists. ''' super(DocumentPatchedEvent, self).dispatch(receiver) if hasattr(receiver, '_document_patched'): receiver._document_patched(self)
Dispatch handling of this event to a receiver. This method will invoke ``receiver._document_patched`` if it exists.
Below is the the instruction that describes the task: ### Input: Dispatch handling of this event to a receiver. This method will invoke ``receiver._document_patched`` if it exists. ### Response: def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._document_patched`` if it exists. ''' super(DocumentPatchedEvent, self).dispatch(receiver) if hasattr(receiver, '_document_patched'): receiver._document_patched(self)
def get(self, aid): """ Get manga information by id. :param int aid: ID of the manga. :return: Dictionary or None (for not found) :rtype: Dictionary or None :raises: :class:`Pymoe.errors.ServerError` """ r = requests.get(self.apiurl + "/manga/{}".format(aid), headers=self.header) if r.status_code != 200: if r.status_code == 404: return None else: raise ServerError return r.json()
Get manga information by id. :param int aid: ID of the manga. :return: Dictionary or None (for not found) :rtype: Dictionary or None :raises: :class:`Pymoe.errors.ServerError`
Below is the the instruction that describes the task: ### Input: Get manga information by id. :param int aid: ID of the manga. :return: Dictionary or None (for not found) :rtype: Dictionary or None :raises: :class:`Pymoe.errors.ServerError` ### Response: def get(self, aid): """ Get manga information by id. :param int aid: ID of the manga. :return: Dictionary or None (for not found) :rtype: Dictionary or None :raises: :class:`Pymoe.errors.ServerError` """ r = requests.get(self.apiurl + "/manga/{}".format(aid), headers=self.header) if r.status_code != 200: if r.status_code == 404: return None else: raise ServerError return r.json()
def fetch_project(self, project_id): """Fetch an existing project and it's relevant metadata by ID. .. note:: If the project does not exist, this will raise a :class:`NotFound <google.cloud.exceptions.NotFound>` error. :type project_id: str :param project_id: The ID for this project. :rtype: :class:`~google.cloud.resource_manager.project.Project` :returns: A :class:`~google.cloud.resource_manager.project.Project` with metadata fetched from the API. """ project = self.new_project(project_id) project.reload() return project
Fetch an existing project and it's relevant metadata by ID. .. note:: If the project does not exist, this will raise a :class:`NotFound <google.cloud.exceptions.NotFound>` error. :type project_id: str :param project_id: The ID for this project. :rtype: :class:`~google.cloud.resource_manager.project.Project` :returns: A :class:`~google.cloud.resource_manager.project.Project` with metadata fetched from the API.
Below is the the instruction that describes the task: ### Input: Fetch an existing project and it's relevant metadata by ID. .. note:: If the project does not exist, this will raise a :class:`NotFound <google.cloud.exceptions.NotFound>` error. :type project_id: str :param project_id: The ID for this project. :rtype: :class:`~google.cloud.resource_manager.project.Project` :returns: A :class:`~google.cloud.resource_manager.project.Project` with metadata fetched from the API. ### Response: def fetch_project(self, project_id): """Fetch an existing project and it's relevant metadata by ID. .. note:: If the project does not exist, this will raise a :class:`NotFound <google.cloud.exceptions.NotFound>` error. :type project_id: str :param project_id: The ID for this project. :rtype: :class:`~google.cloud.resource_manager.project.Project` :returns: A :class:`~google.cloud.resource_manager.project.Project` with metadata fetched from the API. """ project = self.new_project(project_id) project.reload() return project
def unzoom(self,event=None): """zoom out 1 level, or to full data range """ if self.panel is not None: self.panel.unzoom(event=event)
zoom out 1 level, or to full data range
Below is the the instruction that describes the task: ### Input: zoom out 1 level, or to full data range ### Response: def unzoom(self,event=None): """zoom out 1 level, or to full data range """ if self.panel is not None: self.panel.unzoom(event=event)
def get_start_date_metadata(self): """Gets the metadata for a start date. return: (osid.Metadata) - metadata for the date *compliance: mandatory -- This method must be implemented.* """ metadata = dict(self._mdata['start_date']) metadata.update({'existing_date_time_values': self._my_map['startDate']}) return Metadata(**metadata)
Gets the metadata for a start date. return: (osid.Metadata) - metadata for the date *compliance: mandatory -- This method must be implemented.*
Below is the the instruction that describes the task: ### Input: Gets the metadata for a start date. return: (osid.Metadata) - metadata for the date *compliance: mandatory -- This method must be implemented.* ### Response: def get_start_date_metadata(self): """Gets the metadata for a start date. return: (osid.Metadata) - metadata for the date *compliance: mandatory -- This method must be implemented.* """ metadata = dict(self._mdata['start_date']) metadata.update({'existing_date_time_values': self._my_map['startDate']}) return Metadata(**metadata)
def attrdict_middleware(make_request, web3): """ Converts any result which is a dictionary into an a """ def middleware(method, params): response = make_request(method, params) if 'result' in response: result = response['result'] if is_dict(result) and not isinstance(result, AttributeDict): return assoc(response, 'result', AttributeDict.recursive(result)) else: return response else: return response return middleware
Converts any result which is a dictionary into an a
Below is the the instruction that describes the task: ### Input: Converts any result which is a dictionary into an a ### Response: def attrdict_middleware(make_request, web3): """ Converts any result which is a dictionary into an a """ def middleware(method, params): response = make_request(method, params) if 'result' in response: result = response['result'] if is_dict(result) and not isinstance(result, AttributeDict): return assoc(response, 'result', AttributeDict.recursive(result)) else: return response else: return response return middleware
def get_MD_VDS(tail_check_max, vds): """ input: tail_check_max, vector difference sum output: MD_VDS """ if tail_check_max == 0 or numpy.isnan(tail_check_max): return float('nan') MD_VDS = (old_div(tail_check_max, vds)) * 100 return MD_VDS
input: tail_check_max, vector difference sum output: MD_VDS
Below is the the instruction that describes the task: ### Input: input: tail_check_max, vector difference sum output: MD_VDS ### Response: def get_MD_VDS(tail_check_max, vds): """ input: tail_check_max, vector difference sum output: MD_VDS """ if tail_check_max == 0 or numpy.isnan(tail_check_max): return float('nan') MD_VDS = (old_div(tail_check_max, vds)) * 100 return MD_VDS
def get_terminal_size(): '''Finds the width of the terminal, or returns a suitable default value.''' def read_terminal_size_by_ioctl(fd): try: import struct, fcntl, termios cr = struct.unpack('hh', fcntl.ioctl(1, termios.TIOCGWINSZ, '0000')) except ImportError: return None except IOError as e: return None return cr[1], cr[0] cr = read_terminal_size_by_ioctl(0) or \ read_terminal_size_by_ioctl(1) or \ read_terminal_size_by_ioctl(2) if not cr: try: import os fd = os.open(os.ctermid(), os.O_RDONLY) cr = read_terminal_size_by_ioctl(fd) os.close(fd) except: pass if not cr: import os cr = [80, 25] # 25 rows, 80 columns is the default value if os.getenv('ROWS'): cr[1] = int(os.getenv('ROWS')) if os.getenv('COLUMNS'): cr[0] = int(os.getenv('COLUMNS')) return cr[1], cr[0]
Finds the width of the terminal, or returns a suitable default value.
Below is the the instruction that describes the task: ### Input: Finds the width of the terminal, or returns a suitable default value. ### Response: def get_terminal_size(): '''Finds the width of the terminal, or returns a suitable default value.''' def read_terminal_size_by_ioctl(fd): try: import struct, fcntl, termios cr = struct.unpack('hh', fcntl.ioctl(1, termios.TIOCGWINSZ, '0000')) except ImportError: return None except IOError as e: return None return cr[1], cr[0] cr = read_terminal_size_by_ioctl(0) or \ read_terminal_size_by_ioctl(1) or \ read_terminal_size_by_ioctl(2) if not cr: try: import os fd = os.open(os.ctermid(), os.O_RDONLY) cr = read_terminal_size_by_ioctl(fd) os.close(fd) except: pass if not cr: import os cr = [80, 25] # 25 rows, 80 columns is the default value if os.getenv('ROWS'): cr[1] = int(os.getenv('ROWS')) if os.getenv('COLUMNS'): cr[0] = int(os.getenv('COLUMNS')) return cr[1], cr[0]
def get_group_offsets(self, group, topic=None): """Fetch group offsets for given topic and partition otherwise all topics and partitions otherwise. { 'topic': { 'partition': offset-value, ... ... } } """ group_offsets = {} try: all_topics = self.get_my_subscribed_topics(group) except NoNodeError: # No offset information of given consumer-group _log.warning( "No topics subscribed to consumer-group {group}.".format( group=group, ), ) return group_offsets if topic: if topic in all_topics: topics = [topic] else: _log.error( "Topic {topic} not found in topic list {topics} for consumer" "-group {consumer_group}.".format( topic=topic, topics=', '.join(topic for topic in all_topics), consumer_group=group, ), ) return group_offsets else: topics = all_topics for topic in topics: group_offsets[topic] = {} try: partitions = self.get_my_subscribed_partitions(group, topic) except NoNodeError: _log.warning( "No partition offsets found for topic {topic}. " "Continuing to next one...".format(topic=topic), ) continue # Fetch offsets for each partition for partition in partitions: path = "/consumers/{group_id}/offsets/{topic}/{partition}".format( group_id=group, topic=topic, partition=partition, ) try: # Get current offset offset_json, _ = self.get(path) group_offsets[topic][partition] = load_json(offset_json) except NoNodeError: _log.error("Path {path} not found".format(path=path)) raise return group_offsets
Fetch group offsets for given topic and partition otherwise all topics and partitions otherwise. { 'topic': { 'partition': offset-value, ... ... } }
Below is the the instruction that describes the task: ### Input: Fetch group offsets for given topic and partition otherwise all topics and partitions otherwise. { 'topic': { 'partition': offset-value, ... ... } } ### Response: def get_group_offsets(self, group, topic=None): """Fetch group offsets for given topic and partition otherwise all topics and partitions otherwise. { 'topic': { 'partition': offset-value, ... ... } } """ group_offsets = {} try: all_topics = self.get_my_subscribed_topics(group) except NoNodeError: # No offset information of given consumer-group _log.warning( "No topics subscribed to consumer-group {group}.".format( group=group, ), ) return group_offsets if topic: if topic in all_topics: topics = [topic] else: _log.error( "Topic {topic} not found in topic list {topics} for consumer" "-group {consumer_group}.".format( topic=topic, topics=', '.join(topic for topic in all_topics), consumer_group=group, ), ) return group_offsets else: topics = all_topics for topic in topics: group_offsets[topic] = {} try: partitions = self.get_my_subscribed_partitions(group, topic) except NoNodeError: _log.warning( "No partition offsets found for topic {topic}. " "Continuing to next one...".format(topic=topic), ) continue # Fetch offsets for each partition for partition in partitions: path = "/consumers/{group_id}/offsets/{topic}/{partition}".format( group_id=group, topic=topic, partition=partition, ) try: # Get current offset offset_json, _ = self.get(path) group_offsets[topic][partition] = load_json(offset_json) except NoNodeError: _log.error("Path {path} not found".format(path=path)) raise return group_offsets
def cylinders_from_ellipses(ellipses): """Create 3d cylinders from ellipses.""" ellipses = np.asarray(ellipses) ellipsoids = np.zeros((ellipses.shape[0], 10)) ellipsoids[:, [0, 1, 2, 4, 5, 7]] = ellipses ellipsoids[:, 3] = 100000.0 return ellipsoids
Create 3d cylinders from ellipses.
Below is the the instruction that describes the task: ### Input: Create 3d cylinders from ellipses. ### Response: def cylinders_from_ellipses(ellipses): """Create 3d cylinders from ellipses.""" ellipses = np.asarray(ellipses) ellipsoids = np.zeros((ellipses.shape[0], 10)) ellipsoids[:, [0, 1, 2, 4, 5, 7]] = ellipses ellipsoids[:, 3] = 100000.0 return ellipsoids
def as_status(cls, obj): """Convert obj into Status.""" if obj is None: return None return obj if isinstance(obj, cls) else cls.from_string(obj)
Convert obj into Status.
Below is the the instruction that describes the task: ### Input: Convert obj into Status. ### Response: def as_status(cls, obj): """Convert obj into Status.""" if obj is None: return None return obj if isinstance(obj, cls) else cls.from_string(obj)
def find_datafile(name, search_path, codecs=get_codecs()): """ find all matching data files in search_path search_path: path of directories to load from codecs: allow to override from list of installed returns array of tuples (codec_object, filename) """ return munge.find_datafile(name, search_path, codecs)
find all matching data files in search_path search_path: path of directories to load from codecs: allow to override from list of installed returns array of tuples (codec_object, filename)
Below is the the instruction that describes the task: ### Input: find all matching data files in search_path search_path: path of directories to load from codecs: allow to override from list of installed returns array of tuples (codec_object, filename) ### Response: def find_datafile(name, search_path, codecs=get_codecs()): """ find all matching data files in search_path search_path: path of directories to load from codecs: allow to override from list of installed returns array of tuples (codec_object, filename) """ return munge.find_datafile(name, search_path, codecs)
def _check_inputs(self): """Check the inputs to ensure they are valid. Returns ------- status : bool True if all inputs are valid, False if one is not. """ valid_detector = True valid_filter = True valid_date = True # Determine the submitted detector is valid if self.detector not in self._valid_detectors: msg = ('{} is not a valid detector option.\n' 'Please choose one of the following:\n{}\n' '{}'.format(self.detector, '\n'.join(self._valid_detectors), self._msg_div)) LOG.error(msg) valid_detector = False # Determine if the submitted filter is valid if (self.filt is not None and valid_detector and self.filt not in self.valid_filters[self.detector]): msg = ('{} is not a valid filter for {}\n' 'Please choose one of the following:\n{}\n' '{}'.format(self.filt, self.detector, '\n'.join(self.valid_filters[self.detector]), self._msg_div)) LOG.error(msg) valid_filter = False # Determine if the submitted date is valid date_check = self._check_date() if date_check is not None: LOG.error('{}\n{}'.format(date_check, self._msg_div)) valid_date = False if not valid_detector or not valid_filter or not valid_date: return False return True
Check the inputs to ensure they are valid. Returns ------- status : bool True if all inputs are valid, False if one is not.
Below is the the instruction that describes the task: ### Input: Check the inputs to ensure they are valid. Returns ------- status : bool True if all inputs are valid, False if one is not. ### Response: def _check_inputs(self): """Check the inputs to ensure they are valid. Returns ------- status : bool True if all inputs are valid, False if one is not. """ valid_detector = True valid_filter = True valid_date = True # Determine the submitted detector is valid if self.detector not in self._valid_detectors: msg = ('{} is not a valid detector option.\n' 'Please choose one of the following:\n{}\n' '{}'.format(self.detector, '\n'.join(self._valid_detectors), self._msg_div)) LOG.error(msg) valid_detector = False # Determine if the submitted filter is valid if (self.filt is not None and valid_detector and self.filt not in self.valid_filters[self.detector]): msg = ('{} is not a valid filter for {}\n' 'Please choose one of the following:\n{}\n' '{}'.format(self.filt, self.detector, '\n'.join(self.valid_filters[self.detector]), self._msg_div)) LOG.error(msg) valid_filter = False # Determine if the submitted date is valid date_check = self._check_date() if date_check is not None: LOG.error('{}\n{}'.format(date_check, self._msg_div)) valid_date = False if not valid_detector or not valid_filter or not valid_date: return False return True
def img2img_transformer2d_n31(): """Set of hyperparameters.""" hparams = img2img_transformer2d_base() hparams.batch_size = 1 hparams.num_encoder_layers = 6 hparams.num_decoder_layers = 12 hparams.num_heads = 8 hparams.query_shape = (16, 32) hparams.memory_flange = (16, 32) return hparams
Set of hyperparameters.
Below is the the instruction that describes the task: ### Input: Set of hyperparameters. ### Response: def img2img_transformer2d_n31(): """Set of hyperparameters.""" hparams = img2img_transformer2d_base() hparams.batch_size = 1 hparams.num_encoder_layers = 6 hparams.num_decoder_layers = 12 hparams.num_heads = 8 hparams.query_shape = (16, 32) hparams.memory_flange = (16, 32) return hparams
def can_fetch(self, url_info: URLInfo, user_agent: str): '''Return whether the URL can be fetched.''' key = self.url_info_key(url_info) parser = self._parsers[key] return parser.is_allowed(user_agent, url_info.url)
Return whether the URL can be fetched.
Below is the the instruction that describes the task: ### Input: Return whether the URL can be fetched. ### Response: def can_fetch(self, url_info: URLInfo, user_agent: str): '''Return whether the URL can be fetched.''' key = self.url_info_key(url_info) parser = self._parsers[key] return parser.is_allowed(user_agent, url_info.url)
def _set_BC(self, pores, bctype, bcvalues=None, mode='merge'): r""" Apply boundary conditions to specified pores if no source terms are already assigned to these pores. Otherwise, raise an error. Parameters ---------- pores : array_like The pores where the boundary conditions should be applied bctype : string Specifies the type or the name of boundary condition to apply. The types can be one one of the following: - *'value'* : Specify the value of the quantity in each location - *'rate'* : Specify the flow rate into each location bcvalues : int or array_like The boundary value to apply, such as concentration or rate. If a single value is given, it's assumed to apply to all locations. Different values can be applied to all pores in the form of an array of the same length as ``pores``. mode : string, optional Controls how the conditions are applied. Options are: *'merge'*: (Default) Adds supplied boundary conditions to already existing conditions. *'overwrite'*: Deletes all boundary condition on object then add the given ones Notes ----- It is not possible to have multiple boundary conditions for a specified location in one algorithm. Use ``remove_BCs`` to clear existing BCs before applying new ones or ``mode='overwrite'`` which removes all existing BC's before applying the new ones. """ # First check that given pores do not have source terms already set for item in self.settings['sources']: if np.any(self[item][pores]): raise Exception('Source term already present in given ' + 'pores, cannot also assign boundary ' + 'conditions') # Then call parent class function if above check passes super()._set_BC(pores=pores, bctype=bctype, bcvalues=bcvalues, mode=mode)
r""" Apply boundary conditions to specified pores if no source terms are already assigned to these pores. Otherwise, raise an error. Parameters ---------- pores : array_like The pores where the boundary conditions should be applied bctype : string Specifies the type or the name of boundary condition to apply. The types can be one one of the following: - *'value'* : Specify the value of the quantity in each location - *'rate'* : Specify the flow rate into each location bcvalues : int or array_like The boundary value to apply, such as concentration or rate. If a single value is given, it's assumed to apply to all locations. Different values can be applied to all pores in the form of an array of the same length as ``pores``. mode : string, optional Controls how the conditions are applied. Options are: *'merge'*: (Default) Adds supplied boundary conditions to already existing conditions. *'overwrite'*: Deletes all boundary condition on object then add the given ones Notes ----- It is not possible to have multiple boundary conditions for a specified location in one algorithm. Use ``remove_BCs`` to clear existing BCs before applying new ones or ``mode='overwrite'`` which removes all existing BC's before applying the new ones.
Below is the the instruction that describes the task: ### Input: r""" Apply boundary conditions to specified pores if no source terms are already assigned to these pores. Otherwise, raise an error. Parameters ---------- pores : array_like The pores where the boundary conditions should be applied bctype : string Specifies the type or the name of boundary condition to apply. The types can be one one of the following: - *'value'* : Specify the value of the quantity in each location - *'rate'* : Specify the flow rate into each location bcvalues : int or array_like The boundary value to apply, such as concentration or rate. If a single value is given, it's assumed to apply to all locations. Different values can be applied to all pores in the form of an array of the same length as ``pores``. mode : string, optional Controls how the conditions are applied. Options are: *'merge'*: (Default) Adds supplied boundary conditions to already existing conditions. *'overwrite'*: Deletes all boundary condition on object then add the given ones Notes ----- It is not possible to have multiple boundary conditions for a specified location in one algorithm. Use ``remove_BCs`` to clear existing BCs before applying new ones or ``mode='overwrite'`` which removes all existing BC's before applying the new ones. ### Response: def _set_BC(self, pores, bctype, bcvalues=None, mode='merge'): r""" Apply boundary conditions to specified pores if no source terms are already assigned to these pores. Otherwise, raise an error. Parameters ---------- pores : array_like The pores where the boundary conditions should be applied bctype : string Specifies the type or the name of boundary condition to apply. The types can be one one of the following: - *'value'* : Specify the value of the quantity in each location - *'rate'* : Specify the flow rate into each location bcvalues : int or array_like The boundary value to apply, such as concentration or rate. If a single value is given, it's assumed to apply to all locations. Different values can be applied to all pores in the form of an array of the same length as ``pores``. mode : string, optional Controls how the conditions are applied. Options are: *'merge'*: (Default) Adds supplied boundary conditions to already existing conditions. *'overwrite'*: Deletes all boundary condition on object then add the given ones Notes ----- It is not possible to have multiple boundary conditions for a specified location in one algorithm. Use ``remove_BCs`` to clear existing BCs before applying new ones or ``mode='overwrite'`` which removes all existing BC's before applying the new ones. """ # First check that given pores do not have source terms already set for item in self.settings['sources']: if np.any(self[item][pores]): raise Exception('Source term already present in given ' + 'pores, cannot also assign boundary ' + 'conditions') # Then call parent class function if above check passes super()._set_BC(pores=pores, bctype=bctype, bcvalues=bcvalues, mode=mode)
def ReflexVacuumAgent(): "A reflex agent for the two-state vacuum environment. [Fig. 2.8]" def program((location, status)): if status == 'Dirty': return 'Suck' elif location == loc_A: return 'Right' elif location == loc_B: return 'Left' return Agent(program)
A reflex agent for the two-state vacuum environment. [Fig. 2.8]
Below is the the instruction that describes the task: ### Input: A reflex agent for the two-state vacuum environment. [Fig. 2.8] ### Response: def ReflexVacuumAgent(): "A reflex agent for the two-state vacuum environment. [Fig. 2.8]" def program((location, status)): if status == 'Dirty': return 'Suck' elif location == loc_A: return 'Right' elif location == loc_B: return 'Left' return Agent(program)
def _set_nameserver_cos(self, v, load=False): """ Setter method for nameserver_cos, mapped from YANG variable /brocade_nameserver_rpc/get_nameserver_detail/output/show_nameserver/nameserver_cos (nameserver-cos-type) If this variable is read-only (config: false) in the source YANG file, then _set_nameserver_cos is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_nameserver_cos() directly. YANG Description: Indicates the Fibre Channel Class of Service supported by the device. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'F|1|2|3|,', 'length': [u'0..8']}), is_leaf=True, yang_name="nameserver-cos", rest_name="nameserver-cos", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions={u'tailf-common': {u'info': u'class of service'}}, namespace='urn:brocade.com:mgmt:brocade-nameserver', defining_module='brocade-nameserver', yang_type='nameserver-cos-type', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """nameserver_cos must be of a type compatible with nameserver-cos-type""", 'defined-type': "brocade-nameserver:nameserver-cos-type", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'F|1|2|3|,', 'length': [u'0..8']}), is_leaf=True, yang_name="nameserver-cos", rest_name="nameserver-cos", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions={u'tailf-common': {u'info': u'class of service'}}, namespace='urn:brocade.com:mgmt:brocade-nameserver', defining_module='brocade-nameserver', yang_type='nameserver-cos-type', is_config=True)""", }) self.__nameserver_cos = t if hasattr(self, '_set'): self._set()
Setter method for nameserver_cos, mapped from YANG variable /brocade_nameserver_rpc/get_nameserver_detail/output/show_nameserver/nameserver_cos (nameserver-cos-type) If this variable is read-only (config: false) in the source YANG file, then _set_nameserver_cos is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_nameserver_cos() directly. YANG Description: Indicates the Fibre Channel Class of Service supported by the device.
Below is the the instruction that describes the task: ### Input: Setter method for nameserver_cos, mapped from YANG variable /brocade_nameserver_rpc/get_nameserver_detail/output/show_nameserver/nameserver_cos (nameserver-cos-type) If this variable is read-only (config: false) in the source YANG file, then _set_nameserver_cos is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_nameserver_cos() directly. YANG Description: Indicates the Fibre Channel Class of Service supported by the device. ### Response: def _set_nameserver_cos(self, v, load=False): """ Setter method for nameserver_cos, mapped from YANG variable /brocade_nameserver_rpc/get_nameserver_detail/output/show_nameserver/nameserver_cos (nameserver-cos-type) If this variable is read-only (config: false) in the source YANG file, then _set_nameserver_cos is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_nameserver_cos() directly. YANG Description: Indicates the Fibre Channel Class of Service supported by the device. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'F|1|2|3|,', 'length': [u'0..8']}), is_leaf=True, yang_name="nameserver-cos", rest_name="nameserver-cos", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions={u'tailf-common': {u'info': u'class of service'}}, namespace='urn:brocade.com:mgmt:brocade-nameserver', defining_module='brocade-nameserver', yang_type='nameserver-cos-type', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """nameserver_cos must be of a type compatible with nameserver-cos-type""", 'defined-type': "brocade-nameserver:nameserver-cos-type", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'F|1|2|3|,', 'length': [u'0..8']}), is_leaf=True, yang_name="nameserver-cos", rest_name="nameserver-cos", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=False, extensions={u'tailf-common': {u'info': u'class of service'}}, namespace='urn:brocade.com:mgmt:brocade-nameserver', defining_module='brocade-nameserver', yang_type='nameserver-cos-type', is_config=True)""", }) self.__nameserver_cos = t if hasattr(self, '_set'): self._set()
def remove_edge(self, u, v, key=None): """Version of remove_edge that's much like normal networkx but only deletes once, since the database doesn't keep separate adj and succ mappings """ try: d = self.adj[u][v] except KeyError: raise NetworkXError( "The edge {}-{} is not in the graph.".format(u, v) ) if key is None: d.popitem() else: try: del d[key] except KeyError: raise NetworkXError( "The edge {}-{} with key {} is not in the graph.".format (u, v, key) ) if len(d) == 0: del self.succ[u][v]
Version of remove_edge that's much like normal networkx but only deletes once, since the database doesn't keep separate adj and succ mappings
Below is the the instruction that describes the task: ### Input: Version of remove_edge that's much like normal networkx but only deletes once, since the database doesn't keep separate adj and succ mappings ### Response: def remove_edge(self, u, v, key=None): """Version of remove_edge that's much like normal networkx but only deletes once, since the database doesn't keep separate adj and succ mappings """ try: d = self.adj[u][v] except KeyError: raise NetworkXError( "The edge {}-{} is not in the graph.".format(u, v) ) if key is None: d.popitem() else: try: del d[key] except KeyError: raise NetworkXError( "The edge {}-{} with key {} is not in the graph.".format (u, v, key) ) if len(d) == 0: del self.succ[u][v]
def to_nnf(self): """Return an equivalent expression is negation normal form.""" node = self.node.to_nnf() if node is self.node: return self else: return _expr(node)
Return an equivalent expression is negation normal form.
Below is the the instruction that describes the task: ### Input: Return an equivalent expression is negation normal form. ### Response: def to_nnf(self): """Return an equivalent expression is negation normal form.""" node = self.node.to_nnf() if node is self.node: return self else: return _expr(node)
def _backwards_search(self, start_node, split_name, max_depth=float('inf'), shortcuts=True): """ Performs a backwards search from the terminal node back to the start node :param start_node: The node from where search starts, or here better way where backwards search should end. :param split_name: List of names :param max_depth: Maximum search depth where to look for :param shortcuts: If shortcuts are allowed """ result_list = [] # Result list of all found items full_name_set = set() # Set containing full names of all found items to avoid finding items # twice due to links colon_name = '.'.join(split_name) key = split_name[-1] candidate_dict = self._get_candidate_dict(key, None, use_upper_bound=False) parent_full_name = start_node.v_full_name split_length = len(split_name) for candidate_name in candidate_dict: # Check if candidate startswith the parent's name candidate = candidate_dict[candidate_name] if key != candidate.v_name or candidate.v_full_name in full_name_set: # If this is not the case we do have link, that we need to skip continue if candidate_name.startswith(parent_full_name): if parent_full_name != '': reduced_candidate_name = candidate_name[len(parent_full_name) + 1:] else: reduced_candidate_name = candidate_name candidate_split_name = reduced_candidate_name.split('.') if len(candidate_split_name) > max_depth: break if len(split_name) == 1 or reduced_candidate_name.endswith(colon_name): result_list.append(candidate) full_name_set.add(candidate.v_full_name) elif shortcuts: candidate_set = set(candidate_split_name) climbing = True for name in split_name: if name not in candidate_set: climbing = False break if climbing: count = 0 candidate_length = len(candidate_split_name) for idx in range(candidate_length): if idx + split_length - count > candidate_length: break if split_name[count] == candidate_split_name[idx]: count += 1 if count == len(split_name): result_list.append(candidate) full_name_set.add(candidate.v_full_name) break return result_list
Performs a backwards search from the terminal node back to the start node :param start_node: The node from where search starts, or here better way where backwards search should end. :param split_name: List of names :param max_depth: Maximum search depth where to look for :param shortcuts: If shortcuts are allowed
Below is the the instruction that describes the task: ### Input: Performs a backwards search from the terminal node back to the start node :param start_node: The node from where search starts, or here better way where backwards search should end. :param split_name: List of names :param max_depth: Maximum search depth where to look for :param shortcuts: If shortcuts are allowed ### Response: def _backwards_search(self, start_node, split_name, max_depth=float('inf'), shortcuts=True): """ Performs a backwards search from the terminal node back to the start node :param start_node: The node from where search starts, or here better way where backwards search should end. :param split_name: List of names :param max_depth: Maximum search depth where to look for :param shortcuts: If shortcuts are allowed """ result_list = [] # Result list of all found items full_name_set = set() # Set containing full names of all found items to avoid finding items # twice due to links colon_name = '.'.join(split_name) key = split_name[-1] candidate_dict = self._get_candidate_dict(key, None, use_upper_bound=False) parent_full_name = start_node.v_full_name split_length = len(split_name) for candidate_name in candidate_dict: # Check if candidate startswith the parent's name candidate = candidate_dict[candidate_name] if key != candidate.v_name or candidate.v_full_name in full_name_set: # If this is not the case we do have link, that we need to skip continue if candidate_name.startswith(parent_full_name): if parent_full_name != '': reduced_candidate_name = candidate_name[len(parent_full_name) + 1:] else: reduced_candidate_name = candidate_name candidate_split_name = reduced_candidate_name.split('.') if len(candidate_split_name) > max_depth: break if len(split_name) == 1 or reduced_candidate_name.endswith(colon_name): result_list.append(candidate) full_name_set.add(candidate.v_full_name) elif shortcuts: candidate_set = set(candidate_split_name) climbing = True for name in split_name: if name not in candidate_set: climbing = False break if climbing: count = 0 candidate_length = len(candidate_split_name) for idx in range(candidate_length): if idx + split_length - count > candidate_length: break if split_name[count] == candidate_split_name[idx]: count += 1 if count == len(split_name): result_list.append(candidate) full_name_set.add(candidate.v_full_name) break return result_list
def evaluator(self, candidates, args): """Return the fitness values for the given candidates.""" fitness = [] if self._use_ants: for candidate in candidates: total = 0 for c in candidate: total += c.value fitness.append(total) else: for candidate in candidates: total_value = 0 total_weight = 0 for c, i in zip(candidate, self.items): total_weight += c * i[0] total_value += c * i[1] if total_weight > self.capacity: fitness.append(self.capacity - total_weight) else: fitness.append(total_value) return fitness
Return the fitness values for the given candidates.
Below is the the instruction that describes the task: ### Input: Return the fitness values for the given candidates. ### Response: def evaluator(self, candidates, args): """Return the fitness values for the given candidates.""" fitness = [] if self._use_ants: for candidate in candidates: total = 0 for c in candidate: total += c.value fitness.append(total) else: for candidate in candidates: total_value = 0 total_weight = 0 for c, i in zip(candidate, self.items): total_weight += c * i[0] total_value += c * i[1] if total_weight > self.capacity: fitness.append(self.capacity - total_weight) else: fitness.append(total_value) return fitness
def create_download_specifications(ctx_cli_options, config): # type: (dict, dict) -> List[blobxfer.models.download.Specification] """Create a list of Download Specification objects from configuration :param dict ctx_cli_options: cli options :param dict config: config dict :rtype: list :return: list of Download Specification objects """ cli_conf = ctx_cli_options[ctx_cli_options['_action']] cli_options = cli_conf['options'] specs = [] for conf in config['download']: if 'options' in conf: conf_options = conf['options'] else: conf_options = {} # create download options mode = _merge_setting( cli_options, conf_options, 'mode', default='auto').lower() if mode == 'auto': mode = blobxfer.models.azure.StorageModes.Auto elif mode == 'append': mode = blobxfer.models.azure.StorageModes.Append elif mode == 'block': mode = blobxfer.models.azure.StorageModes.Block elif mode == 'file': mode = blobxfer.models.azure.StorageModes.File elif mode == 'page': mode = blobxfer.models.azure.StorageModes.Page else: raise ValueError('unknown mode: {}'.format(mode)) # load RSA private key PEM file if specified rpk = _merge_setting( cli_options, conf_options, 'rsa_private_key', default=None) if blobxfer.util.is_not_empty(rpk): rpkp = _merge_setting( cli_options, conf_options, 'rsa_private_key_passphrase', default=None) rpk = blobxfer.operations.crypto.load_rsa_private_key_file( rpk, rpkp) else: rpk = None # create specification conf_sod = conf_options.get('skip_on', {}) cli_sod = cli_options['skip_on'] conf_rfp = conf_options.get('restore_file_properties', {}) cli_rfp = cli_options['restore_file_properties'] ds = blobxfer.models.download.Specification( download_options=blobxfer.models.options.Download( check_file_md5=_merge_setting( cli_options, conf_options, 'check_file_md5', default=False), chunk_size_bytes=_merge_setting( cli_options, conf_options, 'chunk_size_bytes', default=0), delete_extraneous_destination=_merge_setting( cli_options, conf_options, 'delete_extraneous_destination', default=False), max_single_object_concurrency=_merge_setting( cli_options, conf_options, 'max_single_object_concurrency', default=8), mode=mode, overwrite=_merge_setting( cli_options, conf_options, 'overwrite', default=True), recursive=_merge_setting( cli_options, conf_options, 'recursive', default=True), rename=_merge_setting( cli_options, conf_options, 'rename', default=False), restore_file_properties=blobxfer.models.options.FileProperties( attributes=_merge_setting( cli_rfp, conf_rfp, 'attributes', default=False), cache_control=None, lmt=_merge_setting( cli_rfp, conf_rfp, 'lmt', default=False), md5=None, ), rsa_private_key=rpk, strip_components=_merge_setting( cli_options, conf_options, 'strip_components', default=0), ), skip_on_options=blobxfer.models.options.SkipOn( filesize_match=_merge_setting( cli_sod, conf_sod, 'filesize_match', default=False), lmt_ge=_merge_setting( cli_sod, conf_sod, 'lmt_ge', default=False), md5_match=_merge_setting( cli_sod, conf_sod, 'md5_match', default=False), ), local_destination_path=blobxfer.models.download. LocalDestinationPath( conf['destination'] ) ) # create remote source paths for src in conf['source']: if len(src) != 1: raise RuntimeError( 'invalid number of source pairs specified per entry') sa = next(iter(src)) asp = blobxfer.operations.azure.SourcePath() asp.add_path_with_storage_account(src[sa], sa) incl = _merge_setting(cli_conf, conf, 'include', default=None) if blobxfer.util.is_not_empty(incl): asp.add_includes(incl) excl = _merge_setting(cli_conf, conf, 'exclude', default=None) if blobxfer.util.is_not_empty(excl): asp.add_excludes(excl) ds.add_azure_source_path(asp) # append spec to list specs.append(ds) return specs
Create a list of Download Specification objects from configuration :param dict ctx_cli_options: cli options :param dict config: config dict :rtype: list :return: list of Download Specification objects
Below is the the instruction that describes the task: ### Input: Create a list of Download Specification objects from configuration :param dict ctx_cli_options: cli options :param dict config: config dict :rtype: list :return: list of Download Specification objects ### Response: def create_download_specifications(ctx_cli_options, config): # type: (dict, dict) -> List[blobxfer.models.download.Specification] """Create a list of Download Specification objects from configuration :param dict ctx_cli_options: cli options :param dict config: config dict :rtype: list :return: list of Download Specification objects """ cli_conf = ctx_cli_options[ctx_cli_options['_action']] cli_options = cli_conf['options'] specs = [] for conf in config['download']: if 'options' in conf: conf_options = conf['options'] else: conf_options = {} # create download options mode = _merge_setting( cli_options, conf_options, 'mode', default='auto').lower() if mode == 'auto': mode = blobxfer.models.azure.StorageModes.Auto elif mode == 'append': mode = blobxfer.models.azure.StorageModes.Append elif mode == 'block': mode = blobxfer.models.azure.StorageModes.Block elif mode == 'file': mode = blobxfer.models.azure.StorageModes.File elif mode == 'page': mode = blobxfer.models.azure.StorageModes.Page else: raise ValueError('unknown mode: {}'.format(mode)) # load RSA private key PEM file if specified rpk = _merge_setting( cli_options, conf_options, 'rsa_private_key', default=None) if blobxfer.util.is_not_empty(rpk): rpkp = _merge_setting( cli_options, conf_options, 'rsa_private_key_passphrase', default=None) rpk = blobxfer.operations.crypto.load_rsa_private_key_file( rpk, rpkp) else: rpk = None # create specification conf_sod = conf_options.get('skip_on', {}) cli_sod = cli_options['skip_on'] conf_rfp = conf_options.get('restore_file_properties', {}) cli_rfp = cli_options['restore_file_properties'] ds = blobxfer.models.download.Specification( download_options=blobxfer.models.options.Download( check_file_md5=_merge_setting( cli_options, conf_options, 'check_file_md5', default=False), chunk_size_bytes=_merge_setting( cli_options, conf_options, 'chunk_size_bytes', default=0), delete_extraneous_destination=_merge_setting( cli_options, conf_options, 'delete_extraneous_destination', default=False), max_single_object_concurrency=_merge_setting( cli_options, conf_options, 'max_single_object_concurrency', default=8), mode=mode, overwrite=_merge_setting( cli_options, conf_options, 'overwrite', default=True), recursive=_merge_setting( cli_options, conf_options, 'recursive', default=True), rename=_merge_setting( cli_options, conf_options, 'rename', default=False), restore_file_properties=blobxfer.models.options.FileProperties( attributes=_merge_setting( cli_rfp, conf_rfp, 'attributes', default=False), cache_control=None, lmt=_merge_setting( cli_rfp, conf_rfp, 'lmt', default=False), md5=None, ), rsa_private_key=rpk, strip_components=_merge_setting( cli_options, conf_options, 'strip_components', default=0), ), skip_on_options=blobxfer.models.options.SkipOn( filesize_match=_merge_setting( cli_sod, conf_sod, 'filesize_match', default=False), lmt_ge=_merge_setting( cli_sod, conf_sod, 'lmt_ge', default=False), md5_match=_merge_setting( cli_sod, conf_sod, 'md5_match', default=False), ), local_destination_path=blobxfer.models.download. LocalDestinationPath( conf['destination'] ) ) # create remote source paths for src in conf['source']: if len(src) != 1: raise RuntimeError( 'invalid number of source pairs specified per entry') sa = next(iter(src)) asp = blobxfer.operations.azure.SourcePath() asp.add_path_with_storage_account(src[sa], sa) incl = _merge_setting(cli_conf, conf, 'include', default=None) if blobxfer.util.is_not_empty(incl): asp.add_includes(incl) excl = _merge_setting(cli_conf, conf, 'exclude', default=None) if blobxfer.util.is_not_empty(excl): asp.add_excludes(excl) ds.add_azure_source_path(asp) # append spec to list specs.append(ds) return specs
def extract_grid(self, longmin, longmax, latmin, latmax): ''' Extract part of the image ``img`` Args: longmin (float): Minimum longitude of the window longmax (float): Maximum longitude of the window latmin (float): Minimum latitude of the window latmax (float): Maximum latitude of the window Returns: A tupple of three arrays ``(X,Y,Z)`` with ``X`` contains the longitudes, ``Y`` contains the latitude and ``Z`` the values extracted from the window. Note: All return arrays have the same size. All coordinate are in degree. ''' sample_min, sample_max = map( int, map(self.sample_id, [longmin, longmax])) line_min, line_max = map(int, map(self.line_id, [latmax, latmin])) X = np.array(map(self.long_id, (range(sample_min, sample_max, 1)))) Y = np.array(map(self.lat_id, (range(line_min, line_max + 1, 1)))) for i, line in enumerate(range(int(line_min), int(line_max) + 1)): start = (line - 1) * int(self.SAMPLE_LAST_PIXEL) + sample_min chunk_size = int(sample_max - sample_min) Za = self.array(chunk_size, start, self.bytesize) if i == 0: Z = Za else: Z = np.vstack((Z, Za)) X, Y = np.meshgrid(X, Y) return X, Y, Z
Extract part of the image ``img`` Args: longmin (float): Minimum longitude of the window longmax (float): Maximum longitude of the window latmin (float): Minimum latitude of the window latmax (float): Maximum latitude of the window Returns: A tupple of three arrays ``(X,Y,Z)`` with ``X`` contains the longitudes, ``Y`` contains the latitude and ``Z`` the values extracted from the window. Note: All return arrays have the same size. All coordinate are in degree.
Below is the the instruction that describes the task: ### Input: Extract part of the image ``img`` Args: longmin (float): Minimum longitude of the window longmax (float): Maximum longitude of the window latmin (float): Minimum latitude of the window latmax (float): Maximum latitude of the window Returns: A tupple of three arrays ``(X,Y,Z)`` with ``X`` contains the longitudes, ``Y`` contains the latitude and ``Z`` the values extracted from the window. Note: All return arrays have the same size. All coordinate are in degree. ### Response: def extract_grid(self, longmin, longmax, latmin, latmax): ''' Extract part of the image ``img`` Args: longmin (float): Minimum longitude of the window longmax (float): Maximum longitude of the window latmin (float): Minimum latitude of the window latmax (float): Maximum latitude of the window Returns: A tupple of three arrays ``(X,Y,Z)`` with ``X`` contains the longitudes, ``Y`` contains the latitude and ``Z`` the values extracted from the window. Note: All return arrays have the same size. All coordinate are in degree. ''' sample_min, sample_max = map( int, map(self.sample_id, [longmin, longmax])) line_min, line_max = map(int, map(self.line_id, [latmax, latmin])) X = np.array(map(self.long_id, (range(sample_min, sample_max, 1)))) Y = np.array(map(self.lat_id, (range(line_min, line_max + 1, 1)))) for i, line in enumerate(range(int(line_min), int(line_max) + 1)): start = (line - 1) * int(self.SAMPLE_LAST_PIXEL) + sample_min chunk_size = int(sample_max - sample_min) Za = self.array(chunk_size, start, self.bytesize) if i == 0: Z = Za else: Z = np.vstack((Z, Za)) X, Y = np.meshgrid(X, Y) return X, Y, Z
def min(self, axis=None, dtype=None, out=None, keepdims=False): """Return the minimum of ``self``. See Also -------- numpy.amin max """ return self.elem.__array_ufunc__( np.minimum, 'reduce', self.elem, axis=axis, dtype=dtype, out=(out,), keepdims=keepdims)
Return the minimum of ``self``. See Also -------- numpy.amin max
Below is the the instruction that describes the task: ### Input: Return the minimum of ``self``. See Also -------- numpy.amin max ### Response: def min(self, axis=None, dtype=None, out=None, keepdims=False): """Return the minimum of ``self``. See Also -------- numpy.amin max """ return self.elem.__array_ufunc__( np.minimum, 'reduce', self.elem, axis=axis, dtype=dtype, out=(out,), keepdims=keepdims)
def default_mp_batchify_fn(data): """Collate data into batch. Use shared memory for stacking.""" if isinstance(data[0], nd.NDArray): out = nd.empty((len(data),) + data[0].shape, dtype=data[0].dtype, ctx=context.Context('cpu_shared', 0)) return nd.stack(*data, out=out) elif isinstance(data[0], tuple): data = zip(*data) return [default_mp_batchify_fn(i) for i in data] else: data = np.asarray(data) return nd.array(data, dtype=data.dtype, ctx=context.Context('cpu_shared', 0))
Collate data into batch. Use shared memory for stacking.
Below is the the instruction that describes the task: ### Input: Collate data into batch. Use shared memory for stacking. ### Response: def default_mp_batchify_fn(data): """Collate data into batch. Use shared memory for stacking.""" if isinstance(data[0], nd.NDArray): out = nd.empty((len(data),) + data[0].shape, dtype=data[0].dtype, ctx=context.Context('cpu_shared', 0)) return nd.stack(*data, out=out) elif isinstance(data[0], tuple): data = zip(*data) return [default_mp_batchify_fn(i) for i in data] else: data = np.asarray(data) return nd.array(data, dtype=data.dtype, ctx=context.Context('cpu_shared', 0))
def show_task(successful_transfers, task_id): """ Executor for `globus task show` """ client = get_client() if successful_transfers: print_successful_transfers(client, task_id) else: print_task_detail(client, task_id)
Executor for `globus task show`
Below is the the instruction that describes the task: ### Input: Executor for `globus task show` ### Response: def show_task(successful_transfers, task_id): """ Executor for `globus task show` """ client = get_client() if successful_transfers: print_successful_transfers(client, task_id) else: print_task_detail(client, task_id)
def _ReadMakefileAm(self): """Reads Makefile.am to initialize the project information.""" if not self.library_name: raise RuntimeError("Missing library name") file_object = open("Makefile.am", "rb") if not file_object: raise IOError("Unable to open: Makefile.am") found_subdirs = False for line in file_object.readlines(): line = line.strip() if found_subdirs: library_name, _, _ = line.partition(b" ") if sys.version_info[0] >= 3: library_name = library_name.decode("ascii") self.include_directories.append(library_name) if library_name.startswith("lib"): self.library_names.append(library_name) if library_name == self.library_name: break elif line.startswith(b"SUBDIRS"): found_subdirs = True file_object.close() if not self.include_directories or not self.library_names: raise RuntimeError( "Unable to find include directories and library names in: " "Makefile.am")
Reads Makefile.am to initialize the project information.
Below is the the instruction that describes the task: ### Input: Reads Makefile.am to initialize the project information. ### Response: def _ReadMakefileAm(self): """Reads Makefile.am to initialize the project information.""" if not self.library_name: raise RuntimeError("Missing library name") file_object = open("Makefile.am", "rb") if not file_object: raise IOError("Unable to open: Makefile.am") found_subdirs = False for line in file_object.readlines(): line = line.strip() if found_subdirs: library_name, _, _ = line.partition(b" ") if sys.version_info[0] >= 3: library_name = library_name.decode("ascii") self.include_directories.append(library_name) if library_name.startswith("lib"): self.library_names.append(library_name) if library_name == self.library_name: break elif line.startswith(b"SUBDIRS"): found_subdirs = True file_object.close() if not self.include_directories or not self.library_names: raise RuntimeError( "Unable to find include directories and library names in: " "Makefile.am")