code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def gen_send_version_url(ip, port): '''Generate send error url''' return '{0}:{1}{2}{3}/{4}/{5}'.format(BASE_URL.format(ip), port, API_ROOT_URL, VERSION_API, NNI_EXP_ID, NNI_TRIAL_JOB_ID)
Generate send error url
Below is the the instruction that describes the task: ### Input: Generate send error url ### Response: def gen_send_version_url(ip, port): '''Generate send error url''' return '{0}:{1}{2}{3}/{4}/{5}'.format(BASE_URL.format(ip), port, API_ROOT_URL, VERSION_API, NNI_EXP_ID, NNI_TRIAL_JOB_ID)
def pivot(self, pivot_col, values=None): """ Pivots a column of the current :class:`DataFrame` and perform the specified aggregation. There are two versions of pivot function: one that requires the caller to specify the list of distinct values to pivot on, and one that does not. The latter is more concise but less efficient, because Spark needs to first compute the list of distinct values internally. :param pivot_col: Name of the column to pivot. :param values: List of values that will be translated to columns in the output DataFrame. # Compute the sum of earnings for each year by course with each course as a separate column >>> df4.groupBy("year").pivot("course", ["dotNET", "Java"]).sum("earnings").collect() [Row(year=2012, dotNET=15000, Java=20000), Row(year=2013, dotNET=48000, Java=30000)] # Or without specifying column values (less efficient) >>> df4.groupBy("year").pivot("course").sum("earnings").collect() [Row(year=2012, Java=20000, dotNET=15000), Row(year=2013, Java=30000, dotNET=48000)] >>> df5.groupBy("sales.year").pivot("sales.course").sum("sales.earnings").collect() [Row(year=2012, Java=20000, dotNET=15000), Row(year=2013, Java=30000, dotNET=48000)] """ if values is None: jgd = self._jgd.pivot(pivot_col) else: jgd = self._jgd.pivot(pivot_col, values) return GroupedData(jgd, self._df)
Pivots a column of the current :class:`DataFrame` and perform the specified aggregation. There are two versions of pivot function: one that requires the caller to specify the list of distinct values to pivot on, and one that does not. The latter is more concise but less efficient, because Spark needs to first compute the list of distinct values internally. :param pivot_col: Name of the column to pivot. :param values: List of values that will be translated to columns in the output DataFrame. # Compute the sum of earnings for each year by course with each course as a separate column >>> df4.groupBy("year").pivot("course", ["dotNET", "Java"]).sum("earnings").collect() [Row(year=2012, dotNET=15000, Java=20000), Row(year=2013, dotNET=48000, Java=30000)] # Or without specifying column values (less efficient) >>> df4.groupBy("year").pivot("course").sum("earnings").collect() [Row(year=2012, Java=20000, dotNET=15000), Row(year=2013, Java=30000, dotNET=48000)] >>> df5.groupBy("sales.year").pivot("sales.course").sum("sales.earnings").collect() [Row(year=2012, Java=20000, dotNET=15000), Row(year=2013, Java=30000, dotNET=48000)]
Below is the the instruction that describes the task: ### Input: Pivots a column of the current :class:`DataFrame` and perform the specified aggregation. There are two versions of pivot function: one that requires the caller to specify the list of distinct values to pivot on, and one that does not. The latter is more concise but less efficient, because Spark needs to first compute the list of distinct values internally. :param pivot_col: Name of the column to pivot. :param values: List of values that will be translated to columns in the output DataFrame. # Compute the sum of earnings for each year by course with each course as a separate column >>> df4.groupBy("year").pivot("course", ["dotNET", "Java"]).sum("earnings").collect() [Row(year=2012, dotNET=15000, Java=20000), Row(year=2013, dotNET=48000, Java=30000)] # Or without specifying column values (less efficient) >>> df4.groupBy("year").pivot("course").sum("earnings").collect() [Row(year=2012, Java=20000, dotNET=15000), Row(year=2013, Java=30000, dotNET=48000)] >>> df5.groupBy("sales.year").pivot("sales.course").sum("sales.earnings").collect() [Row(year=2012, Java=20000, dotNET=15000), Row(year=2013, Java=30000, dotNET=48000)] ### Response: def pivot(self, pivot_col, values=None): """ Pivots a column of the current :class:`DataFrame` and perform the specified aggregation. There are two versions of pivot function: one that requires the caller to specify the list of distinct values to pivot on, and one that does not. The latter is more concise but less efficient, because Spark needs to first compute the list of distinct values internally. :param pivot_col: Name of the column to pivot. :param values: List of values that will be translated to columns in the output DataFrame. # Compute the sum of earnings for each year by course with each course as a separate column >>> df4.groupBy("year").pivot("course", ["dotNET", "Java"]).sum("earnings").collect() [Row(year=2012, dotNET=15000, Java=20000), Row(year=2013, dotNET=48000, Java=30000)] # Or without specifying column values (less efficient) >>> df4.groupBy("year").pivot("course").sum("earnings").collect() [Row(year=2012, Java=20000, dotNET=15000), Row(year=2013, Java=30000, dotNET=48000)] >>> df5.groupBy("sales.year").pivot("sales.course").sum("sales.earnings").collect() [Row(year=2012, Java=20000, dotNET=15000), Row(year=2013, Java=30000, dotNET=48000)] """ if values is None: jgd = self._jgd.pivot(pivot_col) else: jgd = self._jgd.pivot(pivot_col, values) return GroupedData(jgd, self._df)
def calibrate_signal(signal, resp, fs, frange): """Given original signal and recording, spits out a calibrated signal""" # remove dc offset from recorded response (synthesized orignal shouldn't have one) dc = np.mean(resp) resp = resp - dc npts = len(signal) f0 = np.ceil(frange[0] / (float(fs) / npts)) f1 = np.floor(frange[1] / (float(fs) / npts)) y = resp # y = y/np.amax(y) # normalize Y = np.fft.rfft(y) x = signal # x = x/np.amax(x) # normalize X = np.fft.rfft(x) H = Y / X # still issues warning because all of Y/X is executed to selected answers from # H = np.where(X.real!=0, Y/X, 1) # H[:f0].real = 1 # H[f1:].real = 1 # H = smooth(H) A = X / H return np.fft.irfft(A)
Given original signal and recording, spits out a calibrated signal
Below is the the instruction that describes the task: ### Input: Given original signal and recording, spits out a calibrated signal ### Response: def calibrate_signal(signal, resp, fs, frange): """Given original signal and recording, spits out a calibrated signal""" # remove dc offset from recorded response (synthesized orignal shouldn't have one) dc = np.mean(resp) resp = resp - dc npts = len(signal) f0 = np.ceil(frange[0] / (float(fs) / npts)) f1 = np.floor(frange[1] / (float(fs) / npts)) y = resp # y = y/np.amax(y) # normalize Y = np.fft.rfft(y) x = signal # x = x/np.amax(x) # normalize X = np.fft.rfft(x) H = Y / X # still issues warning because all of Y/X is executed to selected answers from # H = np.where(X.real!=0, Y/X, 1) # H[:f0].real = 1 # H[f1:].real = 1 # H = smooth(H) A = X / H return np.fft.irfft(A)
def calc_track_errors(model_tracks, obs_tracks, track_pairings): """ Calculates spatial and temporal translation errors between matched forecast and observed tracks. Args: model_tracks: List of model track STObjects obs_tracks: List of observed track STObjects track_pairings: List of tuples pairing forecast and observed tracks. Returns: pandas DataFrame containing different track errors """ columns = ['obs_track_id', 'translation_error_x', 'translation_error_y', 'start_time_difference', 'end_time_difference', ] track_errors = pd.DataFrame(index=list(range(len(model_tracks))), columns=columns) for p, pair in enumerate(track_pairings): model_track = model_tracks[pair[0]] if type(pair[1]) in [int, np.int64]: obs_track = obs_tracks[pair[1]] else: obs_track = obs_tracks[pair[1][0]] model_com = model_track.center_of_mass(model_track.start_time) obs_com = obs_track.center_of_mass(obs_track.start_time) track_errors.loc[pair[0], 'obs_track_id'] = pair[1] if type(pair[1]) in [int, np.int64] else pair[1][0] track_errors.loc[pair[0], 'translation_error_x'] = model_com[0] - obs_com[0] track_errors.loc[pair[0], 'translation_error_y'] = model_com[1] - obs_com[1] track_errors.loc[pair[0], 'start_time_difference'] = model_track.start_time - obs_track.start_time track_errors.loc[pair[0], 'end_time_difference'] = model_track.end_time - obs_track.end_time return track_errors
Calculates spatial and temporal translation errors between matched forecast and observed tracks. Args: model_tracks: List of model track STObjects obs_tracks: List of observed track STObjects track_pairings: List of tuples pairing forecast and observed tracks. Returns: pandas DataFrame containing different track errors
Below is the the instruction that describes the task: ### Input: Calculates spatial and temporal translation errors between matched forecast and observed tracks. Args: model_tracks: List of model track STObjects obs_tracks: List of observed track STObjects track_pairings: List of tuples pairing forecast and observed tracks. Returns: pandas DataFrame containing different track errors ### Response: def calc_track_errors(model_tracks, obs_tracks, track_pairings): """ Calculates spatial and temporal translation errors between matched forecast and observed tracks. Args: model_tracks: List of model track STObjects obs_tracks: List of observed track STObjects track_pairings: List of tuples pairing forecast and observed tracks. Returns: pandas DataFrame containing different track errors """ columns = ['obs_track_id', 'translation_error_x', 'translation_error_y', 'start_time_difference', 'end_time_difference', ] track_errors = pd.DataFrame(index=list(range(len(model_tracks))), columns=columns) for p, pair in enumerate(track_pairings): model_track = model_tracks[pair[0]] if type(pair[1]) in [int, np.int64]: obs_track = obs_tracks[pair[1]] else: obs_track = obs_tracks[pair[1][0]] model_com = model_track.center_of_mass(model_track.start_time) obs_com = obs_track.center_of_mass(obs_track.start_time) track_errors.loc[pair[0], 'obs_track_id'] = pair[1] if type(pair[1]) in [int, np.int64] else pair[1][0] track_errors.loc[pair[0], 'translation_error_x'] = model_com[0] - obs_com[0] track_errors.loc[pair[0], 'translation_error_y'] = model_com[1] - obs_com[1] track_errors.loc[pair[0], 'start_time_difference'] = model_track.start_time - obs_track.start_time track_errors.loc[pair[0], 'end_time_difference'] = model_track.end_time - obs_track.end_time return track_errors
def setup_cmd_parser(cls): """Returns the Gerrit argument parser.""" parser = BackendCommandArgumentParser(cls.BACKEND.CATEGORIES, from_date=True, archive=True) # Gerrit options group = parser.parser.add_argument_group('Gerrit arguments') group.add_argument('--user', dest='user', help="Gerrit ssh user") group.add_argument('--max-reviews', dest='max_reviews', type=int, default=MAX_REVIEWS, help="Max number of reviews per ssh query.") group.add_argument('--blacklist-reviews', dest='blacklist_reviews', nargs='*', help="Wrong reviews that must not be retrieved.") group.add_argument('--disable-host-key-check', dest='disable_host_key_check', action='store_true', help="Don't check remote host identity") group.add_argument('--ssh-port', dest='port', default=PORT, type=int, help="Set SSH port of the Gerrit server") # Required arguments parser.parser.add_argument('hostname', help="Hostname of the Gerrit server") return parser
Returns the Gerrit argument parser.
Below is the the instruction that describes the task: ### Input: Returns the Gerrit argument parser. ### Response: def setup_cmd_parser(cls): """Returns the Gerrit argument parser.""" parser = BackendCommandArgumentParser(cls.BACKEND.CATEGORIES, from_date=True, archive=True) # Gerrit options group = parser.parser.add_argument_group('Gerrit arguments') group.add_argument('--user', dest='user', help="Gerrit ssh user") group.add_argument('--max-reviews', dest='max_reviews', type=int, default=MAX_REVIEWS, help="Max number of reviews per ssh query.") group.add_argument('--blacklist-reviews', dest='blacklist_reviews', nargs='*', help="Wrong reviews that must not be retrieved.") group.add_argument('--disable-host-key-check', dest='disable_host_key_check', action='store_true', help="Don't check remote host identity") group.add_argument('--ssh-port', dest='port', default=PORT, type=int, help="Set SSH port of the Gerrit server") # Required arguments parser.parser.add_argument('hostname', help="Hostname of the Gerrit server") return parser
def add_watcher(self, issue, watcher): """Add a user to an issue's watchers list. :param issue: ID or key of the issue affected :param watcher: username of the user to add to the watchers list """ url = self._get_url('issue/' + str(issue) + '/watchers') self._session.post( url, data=json.dumps(watcher))
Add a user to an issue's watchers list. :param issue: ID or key of the issue affected :param watcher: username of the user to add to the watchers list
Below is the the instruction that describes the task: ### Input: Add a user to an issue's watchers list. :param issue: ID or key of the issue affected :param watcher: username of the user to add to the watchers list ### Response: def add_watcher(self, issue, watcher): """Add a user to an issue's watchers list. :param issue: ID or key of the issue affected :param watcher: username of the user to add to the watchers list """ url = self._get_url('issue/' + str(issue) + '/watchers') self._session.post( url, data=json.dumps(watcher))
def get_all_connected_devices(self): """ Get all info about devices connected to the box :return: a list with each device info :rtype: list """ self.bbox_auth.set_access(BboxConstant.AUTHENTICATION_LEVEL_PUBLIC, BboxConstant.AUTHENTICATION_LEVEL_PRIVATE) self.bbox_url.set_api_name(BboxConstant.API_HOSTS, None) api = BboxApiCall(self.bbox_url, BboxConstant.HTTP_METHOD_GET, None, self.bbox_auth) resp = api.execute_api_request() return resp.json()[0]["hosts"]["list"]
Get all info about devices connected to the box :return: a list with each device info :rtype: list
Below is the the instruction that describes the task: ### Input: Get all info about devices connected to the box :return: a list with each device info :rtype: list ### Response: def get_all_connected_devices(self): """ Get all info about devices connected to the box :return: a list with each device info :rtype: list """ self.bbox_auth.set_access(BboxConstant.AUTHENTICATION_LEVEL_PUBLIC, BboxConstant.AUTHENTICATION_LEVEL_PRIVATE) self.bbox_url.set_api_name(BboxConstant.API_HOSTS, None) api = BboxApiCall(self.bbox_url, BboxConstant.HTTP_METHOD_GET, None, self.bbox_auth) resp = api.execute_api_request() return resp.json()[0]["hosts"]["list"]
def fetch_entities(self): """Fetch entities for which we have data.""" query = text( """ SELECT entity_id FROM states GROUP BY entity_id """ ) response = self.perform_query(query) # Parse the domains from the entities. entities = {} domains = set() for [entity] in response: domain = entity.split(".")[0] domains.add(domain) entities.setdefault(domain, []).append(entity) self._domains = list(domains) self._entities = entities print("There are {} entities with data".format(len(entities)))
Fetch entities for which we have data.
Below is the the instruction that describes the task: ### Input: Fetch entities for which we have data. ### Response: def fetch_entities(self): """Fetch entities for which we have data.""" query = text( """ SELECT entity_id FROM states GROUP BY entity_id """ ) response = self.perform_query(query) # Parse the domains from the entities. entities = {} domains = set() for [entity] in response: domain = entity.split(".")[0] domains.add(domain) entities.setdefault(domain, []).append(entity) self._domains = list(domains) self._entities = entities print("There are {} entities with data".format(len(entities)))
def monday_of_week(year, week): """ Returns a datetime for the monday of the given week of the given year. """ str_time = time.strptime('{0} {1} 1'.format(year, week), '%Y %W %w') date = timezone.datetime(year=str_time.tm_year, month=str_time.tm_mon, day=str_time.tm_mday, tzinfo=timezone.utc) if timezone.datetime(year, 1, 4).isoweekday() > 4: # ISO 8601 where week 1 is the first week that has at least 4 days in # the current year date -= timezone.timedelta(days=7) return date
Returns a datetime for the monday of the given week of the given year.
Below is the the instruction that describes the task: ### Input: Returns a datetime for the monday of the given week of the given year. ### Response: def monday_of_week(year, week): """ Returns a datetime for the monday of the given week of the given year. """ str_time = time.strptime('{0} {1} 1'.format(year, week), '%Y %W %w') date = timezone.datetime(year=str_time.tm_year, month=str_time.tm_mon, day=str_time.tm_mday, tzinfo=timezone.utc) if timezone.datetime(year, 1, 4).isoweekday() > 4: # ISO 8601 where week 1 is the first week that has at least 4 days in # the current year date -= timezone.timedelta(days=7) return date
def get_command_instance(name, parent=None, checkexists=True): """Try to guess and create the appropriate command instance Given a command name (encountered by the parser), construct the associated class name and, if known, return a new instance. If the command is not known or has not been loaded using require, an UnknownCommand exception is raised. :param name: the command's name :param parent: the eventual parent command :return: a new class instance """ cname = "%sCommand" % name.lower().capitalize() gl = globals() condition = ( cname not in gl or (checkexists and gl[cname].extension and gl[cname].extension not in RequireCommand.loaded_extensions) ) if condition: raise UnknownCommand(name) return gl[cname](parent)
Try to guess and create the appropriate command instance Given a command name (encountered by the parser), construct the associated class name and, if known, return a new instance. If the command is not known or has not been loaded using require, an UnknownCommand exception is raised. :param name: the command's name :param parent: the eventual parent command :return: a new class instance
Below is the the instruction that describes the task: ### Input: Try to guess and create the appropriate command instance Given a command name (encountered by the parser), construct the associated class name and, if known, return a new instance. If the command is not known or has not been loaded using require, an UnknownCommand exception is raised. :param name: the command's name :param parent: the eventual parent command :return: a new class instance ### Response: def get_command_instance(name, parent=None, checkexists=True): """Try to guess and create the appropriate command instance Given a command name (encountered by the parser), construct the associated class name and, if known, return a new instance. If the command is not known or has not been loaded using require, an UnknownCommand exception is raised. :param name: the command's name :param parent: the eventual parent command :return: a new class instance """ cname = "%sCommand" % name.lower().capitalize() gl = globals() condition = ( cname not in gl or (checkexists and gl[cname].extension and gl[cname].extension not in RequireCommand.loaded_extensions) ) if condition: raise UnknownCommand(name) return gl[cname](parent)
def search(self, buf): """Search the provided buffer for a match to any sub-searchers. Search the provided buffer for a match to any of this collection's sub-searchers. If a single matching sub-searcher is found, returns that sub-searcher's *match* object. If multiple matches are found, the match with the smallest index is returned. If no matches are found, returns ``None``. :param buf: Buffer to search for a match. :return: :class:`RegexMatch` if matched, None if no match was found. """ self._check_type(buf) best_match = None best_index = sys.maxsize for searcher in self: match = searcher.search(buf) if match and match.start < best_index: best_match = match best_index = match.start return best_match
Search the provided buffer for a match to any sub-searchers. Search the provided buffer for a match to any of this collection's sub-searchers. If a single matching sub-searcher is found, returns that sub-searcher's *match* object. If multiple matches are found, the match with the smallest index is returned. If no matches are found, returns ``None``. :param buf: Buffer to search for a match. :return: :class:`RegexMatch` if matched, None if no match was found.
Below is the the instruction that describes the task: ### Input: Search the provided buffer for a match to any sub-searchers. Search the provided buffer for a match to any of this collection's sub-searchers. If a single matching sub-searcher is found, returns that sub-searcher's *match* object. If multiple matches are found, the match with the smallest index is returned. If no matches are found, returns ``None``. :param buf: Buffer to search for a match. :return: :class:`RegexMatch` if matched, None if no match was found. ### Response: def search(self, buf): """Search the provided buffer for a match to any sub-searchers. Search the provided buffer for a match to any of this collection's sub-searchers. If a single matching sub-searcher is found, returns that sub-searcher's *match* object. If multiple matches are found, the match with the smallest index is returned. If no matches are found, returns ``None``. :param buf: Buffer to search for a match. :return: :class:`RegexMatch` if matched, None if no match was found. """ self._check_type(buf) best_match = None best_index = sys.maxsize for searcher in self: match = searcher.search(buf) if match and match.start < best_index: best_match = match best_index = match.start return best_match
def translate_text(estimator, subtokenizer, txt): """Translate a single string.""" encoded_txt = _encode_and_add_eos(txt, subtokenizer) def input_fn(): ds = tf.data.Dataset.from_tensors(encoded_txt) ds = ds.batch(_DECODE_BATCH_SIZE) return ds predictions = estimator.predict(input_fn) translation = next(predictions)["outputs"] translation = _trim_and_decode(translation, subtokenizer) print("Translation of \"%s\": \"%s\"" % (txt, translation))
Translate a single string.
Below is the the instruction that describes the task: ### Input: Translate a single string. ### Response: def translate_text(estimator, subtokenizer, txt): """Translate a single string.""" encoded_txt = _encode_and_add_eos(txt, subtokenizer) def input_fn(): ds = tf.data.Dataset.from_tensors(encoded_txt) ds = ds.batch(_DECODE_BATCH_SIZE) return ds predictions = estimator.predict(input_fn) translation = next(predictions)["outputs"] translation = _trim_and_decode(translation, subtokenizer) print("Translation of \"%s\": \"%s\"" % (txt, translation))
def get(cls, key): """ str, int or Enum => Enum """ if isinstance(key, Enum) and not isinstance(key, cls): raise TypeError("Cannot type cast between enums") if isinstance(key, int): if not int(key) in cls._values: raise KeyError("There is no enum with key %d" % key) return cls._values[key] if isinstance(key, (str, unicode)): if not key in cls._names: raise KeyError("There is no enum with name %s" % key) return cls._names[key] raise TypeError("Invalid enum key type: %s" % (key.__class__.__name__))
str, int or Enum => Enum
Below is the the instruction that describes the task: ### Input: str, int or Enum => Enum ### Response: def get(cls, key): """ str, int or Enum => Enum """ if isinstance(key, Enum) and not isinstance(key, cls): raise TypeError("Cannot type cast between enums") if isinstance(key, int): if not int(key) in cls._values: raise KeyError("There is no enum with key %d" % key) return cls._values[key] if isinstance(key, (str, unicode)): if not key in cls._names: raise KeyError("There is no enum with name %s" % key) return cls._names[key] raise TypeError("Invalid enum key type: %s" % (key.__class__.__name__))
def fit_error_ellipse(tsmap, xy=None, dpix=3, zmin=None): """Fit a positional uncertainty ellipse from a TS map. The fit will be performed over pixels in the vicinity of the peak pixel with D < dpix OR z > zmin where D is the distance from the peak pixel in pixel coordinates and z is the difference in amplitude from the peak pixel. Parameters ---------- tsmap : `~gammapy.maps.WcsMap` xy : tuple dpix : float zmin : float Returns ------- fit : dict Dictionary with fit results. """ if xy is None: ix, iy = np.unravel_index(np.argmax(tsmap.data.T), tsmap.data.T.shape) else: ix, iy = xy pbfit0 = utils.fit_parabola(tsmap.data.T, ix, iy, dpix=1.5) pbfit1 = utils.fit_parabola(tsmap.data.T, ix, iy, dpix=dpix, zmin=zmin) wcs = tsmap.geom.wcs cdelt0 = tsmap.geom.wcs.wcs.cdelt[0] cdelt1 = tsmap.geom.wcs.wcs.cdelt[1] npix0 = tsmap.data.T.shape[0] npix1 = tsmap.data.T.shape[1] o = {} o['fit_success'] = pbfit0['fit_success'] o['fit_inbounds'] = True if pbfit0['fit_success']: o['xpix'] = pbfit0['x0'] o['ypix'] = pbfit0['y0'] o['zoffset'] = pbfit0['z0'] else: o['xpix'] = float(ix) o['ypix'] = float(iy) o['zoffset'] = tsmap.data.T[ix, iy] if pbfit1['fit_success']: sigmax = 2.0**0.5 * pbfit1['sigmax'] * np.abs(cdelt0) sigmay = 2.0**0.5 * pbfit1['sigmay'] * np.abs(cdelt1) theta = pbfit1['theta'] sigmax = min(sigmax, np.abs(2.0 * npix0 * cdelt0)) sigmay = min(sigmay, np.abs(2.0 * npix1 * cdelt1)) elif pbfit0['fit_success']: sigmax = 2.0**0.5 * pbfit0['sigmax'] * np.abs(cdelt0) sigmay = 2.0**0.5 * pbfit0['sigmay'] * np.abs(cdelt1) theta = pbfit0['theta'] sigmax = min(sigmax, np.abs(2.0 * npix0 * cdelt0)) sigmay = min(sigmay, np.abs(2.0 * npix1 * cdelt1)) else: pix_area = np.abs(cdelt0) * np.abs(cdelt1) mask = get_region_mask(tsmap.data, 1.0, (ix, iy)) area = np.sum(mask) * pix_area sigmax = (area / np.pi)**0.5 sigmay = (area / np.pi)**0.5 theta = 0.0 if (o['xpix'] <= 0 or o['xpix'] >= npix0 - 1 or o['ypix'] <= 0 or o['ypix'] >= npix1 - 1): o['fit_inbounds'] = False o['xpix'] = float(ix) o['ypix'] = float(iy) o['peak_offset'] = np.sqrt((float(ix) - o['xpix'])**2 + (float(iy) - o['ypix'])**2) skydir = SkyCoord.from_pixel(o['xpix'], o['ypix'], wcs) sigma = (sigmax * sigmay)**0.5 r68 = 2.30**0.5 * sigma r95 = 5.99**0.5 * sigma r99 = 9.21**0.5 * sigma if sigmax < sigmay: o['pos_err_semimajor'] = sigmay o['pos_err_semiminor'] = sigmax o['theta'] = np.fmod(2 * np.pi + np.pi / 2. + theta, np.pi) else: o['pos_err_semimajor'] = sigmax o['pos_err_semiminor'] = sigmay o['theta'] = np.fmod(2 * np.pi + theta, np.pi) o['pos_angle'] = np.degrees(o['theta']) o['pos_err'] = sigma o['pos_r68'] = r68 o['pos_r95'] = r95 o['pos_r99'] = r99 o['ra'] = skydir.icrs.ra.deg o['dec'] = skydir.icrs.dec.deg o['glon'] = skydir.galactic.l.deg o['glat'] = skydir.galactic.b.deg a = o['pos_err_semimajor'] b = o['pos_err_semiminor'] o['pos_ecc'] = np.sqrt(1 - b**2 / a**2) o['pos_ecc2'] = np.sqrt(a**2 / b**2 - 1) o['skydir'] = skydir if tsmap.geom.coordsys == 'GAL': gal_cov = utils.ellipse_to_cov(o['pos_err_semimajor'], o['pos_err_semiminor'], o['theta']) theta_cel = wcs_utils.get_cel_to_gal_angle(skydir) cel_cov = utils.ellipse_to_cov(o['pos_err_semimajor'], o['pos_err_semiminor'], o['theta'] + theta_cel) else: cel_cov = utils.ellipse_to_cov(o['pos_err_semimajor'], o['pos_err_semiminor'], o['theta']) theta_gal = 2 * np.pi - wcs_utils.get_cel_to_gal_angle(skydir) gal_cov = utils.ellipse_to_cov(o['pos_err_semimajor'], o['pos_err_semiminor'], o['theta'] + theta_gal) o['pos_gal_cov'] = gal_cov o['pos_cel_cov'] = cel_cov o['pos_gal_corr'] = utils.cov_to_correlation(gal_cov) o['pos_cel_corr'] = utils.cov_to_correlation(cel_cov) o['glon_err'], o['glat_err'] = np.sqrt( gal_cov[0, 0]), np.sqrt(gal_cov[1, 1]) o['ra_err'], o['dec_err'] = np.sqrt(cel_cov[0, 0]), np.sqrt(cel_cov[1, 1]) return o
Fit a positional uncertainty ellipse from a TS map. The fit will be performed over pixels in the vicinity of the peak pixel with D < dpix OR z > zmin where D is the distance from the peak pixel in pixel coordinates and z is the difference in amplitude from the peak pixel. Parameters ---------- tsmap : `~gammapy.maps.WcsMap` xy : tuple dpix : float zmin : float Returns ------- fit : dict Dictionary with fit results.
Below is the the instruction that describes the task: ### Input: Fit a positional uncertainty ellipse from a TS map. The fit will be performed over pixels in the vicinity of the peak pixel with D < dpix OR z > zmin where D is the distance from the peak pixel in pixel coordinates and z is the difference in amplitude from the peak pixel. Parameters ---------- tsmap : `~gammapy.maps.WcsMap` xy : tuple dpix : float zmin : float Returns ------- fit : dict Dictionary with fit results. ### Response: def fit_error_ellipse(tsmap, xy=None, dpix=3, zmin=None): """Fit a positional uncertainty ellipse from a TS map. The fit will be performed over pixels in the vicinity of the peak pixel with D < dpix OR z > zmin where D is the distance from the peak pixel in pixel coordinates and z is the difference in amplitude from the peak pixel. Parameters ---------- tsmap : `~gammapy.maps.WcsMap` xy : tuple dpix : float zmin : float Returns ------- fit : dict Dictionary with fit results. """ if xy is None: ix, iy = np.unravel_index(np.argmax(tsmap.data.T), tsmap.data.T.shape) else: ix, iy = xy pbfit0 = utils.fit_parabola(tsmap.data.T, ix, iy, dpix=1.5) pbfit1 = utils.fit_parabola(tsmap.data.T, ix, iy, dpix=dpix, zmin=zmin) wcs = tsmap.geom.wcs cdelt0 = tsmap.geom.wcs.wcs.cdelt[0] cdelt1 = tsmap.geom.wcs.wcs.cdelt[1] npix0 = tsmap.data.T.shape[0] npix1 = tsmap.data.T.shape[1] o = {} o['fit_success'] = pbfit0['fit_success'] o['fit_inbounds'] = True if pbfit0['fit_success']: o['xpix'] = pbfit0['x0'] o['ypix'] = pbfit0['y0'] o['zoffset'] = pbfit0['z0'] else: o['xpix'] = float(ix) o['ypix'] = float(iy) o['zoffset'] = tsmap.data.T[ix, iy] if pbfit1['fit_success']: sigmax = 2.0**0.5 * pbfit1['sigmax'] * np.abs(cdelt0) sigmay = 2.0**0.5 * pbfit1['sigmay'] * np.abs(cdelt1) theta = pbfit1['theta'] sigmax = min(sigmax, np.abs(2.0 * npix0 * cdelt0)) sigmay = min(sigmay, np.abs(2.0 * npix1 * cdelt1)) elif pbfit0['fit_success']: sigmax = 2.0**0.5 * pbfit0['sigmax'] * np.abs(cdelt0) sigmay = 2.0**0.5 * pbfit0['sigmay'] * np.abs(cdelt1) theta = pbfit0['theta'] sigmax = min(sigmax, np.abs(2.0 * npix0 * cdelt0)) sigmay = min(sigmay, np.abs(2.0 * npix1 * cdelt1)) else: pix_area = np.abs(cdelt0) * np.abs(cdelt1) mask = get_region_mask(tsmap.data, 1.0, (ix, iy)) area = np.sum(mask) * pix_area sigmax = (area / np.pi)**0.5 sigmay = (area / np.pi)**0.5 theta = 0.0 if (o['xpix'] <= 0 or o['xpix'] >= npix0 - 1 or o['ypix'] <= 0 or o['ypix'] >= npix1 - 1): o['fit_inbounds'] = False o['xpix'] = float(ix) o['ypix'] = float(iy) o['peak_offset'] = np.sqrt((float(ix) - o['xpix'])**2 + (float(iy) - o['ypix'])**2) skydir = SkyCoord.from_pixel(o['xpix'], o['ypix'], wcs) sigma = (sigmax * sigmay)**0.5 r68 = 2.30**0.5 * sigma r95 = 5.99**0.5 * sigma r99 = 9.21**0.5 * sigma if sigmax < sigmay: o['pos_err_semimajor'] = sigmay o['pos_err_semiminor'] = sigmax o['theta'] = np.fmod(2 * np.pi + np.pi / 2. + theta, np.pi) else: o['pos_err_semimajor'] = sigmax o['pos_err_semiminor'] = sigmay o['theta'] = np.fmod(2 * np.pi + theta, np.pi) o['pos_angle'] = np.degrees(o['theta']) o['pos_err'] = sigma o['pos_r68'] = r68 o['pos_r95'] = r95 o['pos_r99'] = r99 o['ra'] = skydir.icrs.ra.deg o['dec'] = skydir.icrs.dec.deg o['glon'] = skydir.galactic.l.deg o['glat'] = skydir.galactic.b.deg a = o['pos_err_semimajor'] b = o['pos_err_semiminor'] o['pos_ecc'] = np.sqrt(1 - b**2 / a**2) o['pos_ecc2'] = np.sqrt(a**2 / b**2 - 1) o['skydir'] = skydir if tsmap.geom.coordsys == 'GAL': gal_cov = utils.ellipse_to_cov(o['pos_err_semimajor'], o['pos_err_semiminor'], o['theta']) theta_cel = wcs_utils.get_cel_to_gal_angle(skydir) cel_cov = utils.ellipse_to_cov(o['pos_err_semimajor'], o['pos_err_semiminor'], o['theta'] + theta_cel) else: cel_cov = utils.ellipse_to_cov(o['pos_err_semimajor'], o['pos_err_semiminor'], o['theta']) theta_gal = 2 * np.pi - wcs_utils.get_cel_to_gal_angle(skydir) gal_cov = utils.ellipse_to_cov(o['pos_err_semimajor'], o['pos_err_semiminor'], o['theta'] + theta_gal) o['pos_gal_cov'] = gal_cov o['pos_cel_cov'] = cel_cov o['pos_gal_corr'] = utils.cov_to_correlation(gal_cov) o['pos_cel_corr'] = utils.cov_to_correlation(cel_cov) o['glon_err'], o['glat_err'] = np.sqrt( gal_cov[0, 0]), np.sqrt(gal_cov[1, 1]) o['ra_err'], o['dec_err'] = np.sqrt(cel_cov[0, 0]), np.sqrt(cel_cov[1, 1]) return o
def remove_usage_rights_courses(self, file_ids, course_id, folder_ids=None): """ Remove usage rights. Removes copyright and license information associated with one or more files """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - file_ids """List of ids of files to remove associated usage rights from.""" params["file_ids"] = file_ids # OPTIONAL - folder_ids """List of ids of folders. Usage rights will be removed from all files in these folders.""" if folder_ids is not None: params["folder_ids"] = folder_ids self.logger.debug("DELETE /api/v1/courses/{course_id}/usage_rights with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("DELETE", "/api/v1/courses/{course_id}/usage_rights".format(**path), data=data, params=params, no_data=True)
Remove usage rights. Removes copyright and license information associated with one or more files
Below is the the instruction that describes the task: ### Input: Remove usage rights. Removes copyright and license information associated with one or more files ### Response: def remove_usage_rights_courses(self, file_ids, course_id, folder_ids=None): """ Remove usage rights. Removes copyright and license information associated with one or more files """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - file_ids """List of ids of files to remove associated usage rights from.""" params["file_ids"] = file_ids # OPTIONAL - folder_ids """List of ids of folders. Usage rights will be removed from all files in these folders.""" if folder_ids is not None: params["folder_ids"] = folder_ids self.logger.debug("DELETE /api/v1/courses/{course_id}/usage_rights with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("DELETE", "/api/v1/courses/{course_id}/usage_rights".format(**path), data=data, params=params, no_data=True)
def _indexOfEndTag(istack): """ Go through `istack` and search endtag. Element at first index is considered as opening tag. Args: istack (list): List of :class:`.HTMLElement` objects. Returns: int: Index of end tag or 0 if not found. """ if len(istack) <= 0: return 0 if not istack[0].isOpeningTag(): return 0 cnt = 0 opener = istack[0] for index, el in enumerate(istack[1:]): if el.isOpeningTag() and \ el.getTagName().lower() == opener.getTagName().lower(): cnt += 1 elif el.isEndTagTo(opener): if cnt == 0: return index + 1 cnt -= 1 return 0
Go through `istack` and search endtag. Element at first index is considered as opening tag. Args: istack (list): List of :class:`.HTMLElement` objects. Returns: int: Index of end tag or 0 if not found.
Below is the the instruction that describes the task: ### Input: Go through `istack` and search endtag. Element at first index is considered as opening tag. Args: istack (list): List of :class:`.HTMLElement` objects. Returns: int: Index of end tag or 0 if not found. ### Response: def _indexOfEndTag(istack): """ Go through `istack` and search endtag. Element at first index is considered as opening tag. Args: istack (list): List of :class:`.HTMLElement` objects. Returns: int: Index of end tag or 0 if not found. """ if len(istack) <= 0: return 0 if not istack[0].isOpeningTag(): return 0 cnt = 0 opener = istack[0] for index, el in enumerate(istack[1:]): if el.isOpeningTag() and \ el.getTagName().lower() == opener.getTagName().lower(): cnt += 1 elif el.isEndTagTo(opener): if cnt == 0: return index + 1 cnt -= 1 return 0
def _validate_virtualbox(self): ''' a method to validate that virtualbox is running on Win 7/8 machines :return: boolean indicating whether virtualbox is running ''' # validate operating system if self.localhost.os.sysname != 'Windows': return False win_release = float(self.localhost.os.release) if win_release >= 10.0: return False # validate docker-machine installation from os import devnull from subprocess import call, check_output, STDOUT sys_command = 'docker-machine --help' try: check_output(sys_command, shell=True, stderr=STDOUT).decode('utf-8') except Exception as err: raise Exception('Docker requires docker-machine to run on Win7/8. GoTo: https://www.docker.com') # validate virtualbox is running sys_command = 'docker-machine status %s' % self.vbox try: vbox_status = check_output(sys_command, shell=True, stderr=open(devnull, 'wb')).decode('utf-8').replace('\n', '') except Exception as err: if not self.vbox: raise Exception('Docker requires VirtualBox to run on Win7/8. GoTo: https://www.virtualbox.org') elif self.vbox == "default": raise Exception('Virtualbox "default" not found. Container will not start without a valid virtualbox.') else: raise Exception('Virtualbox "%s" not found. Try using "default" instead.' % self.vbox) if 'Stopped' in vbox_status: raise Exception('Virtualbox "%s" is stopped. Try first running: docker-machine start %s' % (self.vbox, self.vbox)) return True
a method to validate that virtualbox is running on Win 7/8 machines :return: boolean indicating whether virtualbox is running
Below is the the instruction that describes the task: ### Input: a method to validate that virtualbox is running on Win 7/8 machines :return: boolean indicating whether virtualbox is running ### Response: def _validate_virtualbox(self): ''' a method to validate that virtualbox is running on Win 7/8 machines :return: boolean indicating whether virtualbox is running ''' # validate operating system if self.localhost.os.sysname != 'Windows': return False win_release = float(self.localhost.os.release) if win_release >= 10.0: return False # validate docker-machine installation from os import devnull from subprocess import call, check_output, STDOUT sys_command = 'docker-machine --help' try: check_output(sys_command, shell=True, stderr=STDOUT).decode('utf-8') except Exception as err: raise Exception('Docker requires docker-machine to run on Win7/8. GoTo: https://www.docker.com') # validate virtualbox is running sys_command = 'docker-machine status %s' % self.vbox try: vbox_status = check_output(sys_command, shell=True, stderr=open(devnull, 'wb')).decode('utf-8').replace('\n', '') except Exception as err: if not self.vbox: raise Exception('Docker requires VirtualBox to run on Win7/8. GoTo: https://www.virtualbox.org') elif self.vbox == "default": raise Exception('Virtualbox "default" not found. Container will not start without a valid virtualbox.') else: raise Exception('Virtualbox "%s" not found. Try using "default" instead.' % self.vbox) if 'Stopped' in vbox_status: raise Exception('Virtualbox "%s" is stopped. Try first running: docker-machine start %s' % (self.vbox, self.vbox)) return True
def set_relative_path(self, common_prefix, base_dir): """ generate output representation of rows """ self.short_filename = self.filename.replace(common_prefix, '', 1)
generate output representation of rows
Below is the the instruction that describes the task: ### Input: generate output representation of rows ### Response: def set_relative_path(self, common_prefix, base_dir): """ generate output representation of rows """ self.short_filename = self.filename.replace(common_prefix, '', 1)
def random_hex(length): """ Return a random hex string. :param int length: The length of string to return :returns: A random string :rtype: str """ charset = ''.join(set(string.hexdigits.lower())) return random_string(length, charset)
Return a random hex string. :param int length: The length of string to return :returns: A random string :rtype: str
Below is the the instruction that describes the task: ### Input: Return a random hex string. :param int length: The length of string to return :returns: A random string :rtype: str ### Response: def random_hex(length): """ Return a random hex string. :param int length: The length of string to return :returns: A random string :rtype: str """ charset = ''.join(set(string.hexdigits.lower())) return random_string(length, charset)
def fetch_logs(self, lambda_name, filter_pattern='', limit=10000, start_time=0): """ Fetch the CloudWatch logs for a given Lambda name. """ log_name = '/aws/lambda/' + lambda_name streams = self.logs_client.describe_log_streams( logGroupName=log_name, descending=True, orderBy='LastEventTime' ) all_streams = streams['logStreams'] all_names = [stream['logStreamName'] for stream in all_streams] events = [] response = {} while not response or 'nextToken' in response: extra_args = {} if 'nextToken' in response: extra_args['nextToken'] = response['nextToken'] # Amazon uses millisecond epoch for some reason. # Thanks, Jeff. start_time = start_time * 1000 end_time = int(time.time()) * 1000 response = self.logs_client.filter_log_events( logGroupName=log_name, logStreamNames=all_names, startTime=start_time, endTime=end_time, filterPattern=filter_pattern, limit=limit, interleaved=True, # Does this actually improve performance? **extra_args ) if response and 'events' in response: events += response['events'] return sorted(events, key=lambda k: k['timestamp'])
Fetch the CloudWatch logs for a given Lambda name.
Below is the the instruction that describes the task: ### Input: Fetch the CloudWatch logs for a given Lambda name. ### Response: def fetch_logs(self, lambda_name, filter_pattern='', limit=10000, start_time=0): """ Fetch the CloudWatch logs for a given Lambda name. """ log_name = '/aws/lambda/' + lambda_name streams = self.logs_client.describe_log_streams( logGroupName=log_name, descending=True, orderBy='LastEventTime' ) all_streams = streams['logStreams'] all_names = [stream['logStreamName'] for stream in all_streams] events = [] response = {} while not response or 'nextToken' in response: extra_args = {} if 'nextToken' in response: extra_args['nextToken'] = response['nextToken'] # Amazon uses millisecond epoch for some reason. # Thanks, Jeff. start_time = start_time * 1000 end_time = int(time.time()) * 1000 response = self.logs_client.filter_log_events( logGroupName=log_name, logStreamNames=all_names, startTime=start_time, endTime=end_time, filterPattern=filter_pattern, limit=limit, interleaved=True, # Does this actually improve performance? **extra_args ) if response and 'events' in response: events += response['events'] return sorted(events, key=lambda k: k['timestamp'])
def find_and_replace(self, node): """Parses URIs containing .md and replaces them with their HTML page. Args: node(node): docutils node. Returns: node: docutils node. """ if isinstance(node, nodes.reference) and 'refuri' in node: reference_uri = node['refuri'] if reference_uri.endswith('.md') and not reference_uri.startswith('http'): reference_uri = reference_uri[:-3] + '.html' node['refuri'] = reference_uri else: match = self.ANCHOR_REGEX.match(reference_uri) if match: node['refuri'] = '{0:s}.html#{1:s}'.format( match.group('uri'), match.group('anchor')) return node
Parses URIs containing .md and replaces them with their HTML page. Args: node(node): docutils node. Returns: node: docutils node.
Below is the the instruction that describes the task: ### Input: Parses URIs containing .md and replaces them with their HTML page. Args: node(node): docutils node. Returns: node: docutils node. ### Response: def find_and_replace(self, node): """Parses URIs containing .md and replaces them with their HTML page. Args: node(node): docutils node. Returns: node: docutils node. """ if isinstance(node, nodes.reference) and 'refuri' in node: reference_uri = node['refuri'] if reference_uri.endswith('.md') and not reference_uri.startswith('http'): reference_uri = reference_uri[:-3] + '.html' node['refuri'] = reference_uri else: match = self.ANCHOR_REGEX.match(reference_uri) if match: node['refuri'] = '{0:s}.html#{1:s}'.format( match.group('uri'), match.group('anchor')) return node
def iter_markers(self): """ Generate a (marker_code, segment_offset) 2-tuple for each marker in the JPEG *stream*, in the order they occur in the stream. """ marker_finder = _MarkerFinder.from_stream(self._stream) start = 0 marker_code = None while marker_code != JPEG_MARKER_CODE.EOI: marker_code, segment_offset = marker_finder.next(start) marker = _MarkerFactory( marker_code, self._stream, segment_offset ) yield marker start = segment_offset + marker.segment_length
Generate a (marker_code, segment_offset) 2-tuple for each marker in the JPEG *stream*, in the order they occur in the stream.
Below is the the instruction that describes the task: ### Input: Generate a (marker_code, segment_offset) 2-tuple for each marker in the JPEG *stream*, in the order they occur in the stream. ### Response: def iter_markers(self): """ Generate a (marker_code, segment_offset) 2-tuple for each marker in the JPEG *stream*, in the order they occur in the stream. """ marker_finder = _MarkerFinder.from_stream(self._stream) start = 0 marker_code = None while marker_code != JPEG_MARKER_CODE.EOI: marker_code, segment_offset = marker_finder.next(start) marker = _MarkerFactory( marker_code, self._stream, segment_offset ) yield marker start = segment_offset + marker.segment_length
def save(self, chunk_size=DEFAULT_DATA_CHUNK_SIZE, named=False): """ Get a tarball of an image. Similar to the ``docker save`` command. Args: chunk_size (int): The generator will return up to that much data per iteration, but may return less. If ``None``, data will be streamed as it is received. Default: 2 MB named (str or bool): If ``False`` (default), the tarball will not retain repository and tag information for this image. If set to ``True``, the first tag in the :py:attr:`~tags` list will be used to identify the image. Alternatively, any element of the :py:attr:`~tags` list can be used as an argument to use that specific tag as the saved identifier. Returns: (generator): A stream of raw archive data. Raises: :py:class:`docker.errors.APIError` If the server returns an error. Example: >>> image = cli.get_image("busybox:latest") >>> f = open('/tmp/busybox-latest.tar', 'wb') >>> for chunk in image: >>> f.write(chunk) >>> f.close() """ img = self.id if named: img = self.tags[0] if self.tags else img if isinstance(named, six.string_types): if named not in self.tags: raise InvalidArgument( "{} is not a valid tag for this image".format(named) ) img = named return self.client.api.get_image(img, chunk_size)
Get a tarball of an image. Similar to the ``docker save`` command. Args: chunk_size (int): The generator will return up to that much data per iteration, but may return less. If ``None``, data will be streamed as it is received. Default: 2 MB named (str or bool): If ``False`` (default), the tarball will not retain repository and tag information for this image. If set to ``True``, the first tag in the :py:attr:`~tags` list will be used to identify the image. Alternatively, any element of the :py:attr:`~tags` list can be used as an argument to use that specific tag as the saved identifier. Returns: (generator): A stream of raw archive data. Raises: :py:class:`docker.errors.APIError` If the server returns an error. Example: >>> image = cli.get_image("busybox:latest") >>> f = open('/tmp/busybox-latest.tar', 'wb') >>> for chunk in image: >>> f.write(chunk) >>> f.close()
Below is the the instruction that describes the task: ### Input: Get a tarball of an image. Similar to the ``docker save`` command. Args: chunk_size (int): The generator will return up to that much data per iteration, but may return less. If ``None``, data will be streamed as it is received. Default: 2 MB named (str or bool): If ``False`` (default), the tarball will not retain repository and tag information for this image. If set to ``True``, the first tag in the :py:attr:`~tags` list will be used to identify the image. Alternatively, any element of the :py:attr:`~tags` list can be used as an argument to use that specific tag as the saved identifier. Returns: (generator): A stream of raw archive data. Raises: :py:class:`docker.errors.APIError` If the server returns an error. Example: >>> image = cli.get_image("busybox:latest") >>> f = open('/tmp/busybox-latest.tar', 'wb') >>> for chunk in image: >>> f.write(chunk) >>> f.close() ### Response: def save(self, chunk_size=DEFAULT_DATA_CHUNK_SIZE, named=False): """ Get a tarball of an image. Similar to the ``docker save`` command. Args: chunk_size (int): The generator will return up to that much data per iteration, but may return less. If ``None``, data will be streamed as it is received. Default: 2 MB named (str or bool): If ``False`` (default), the tarball will not retain repository and tag information for this image. If set to ``True``, the first tag in the :py:attr:`~tags` list will be used to identify the image. Alternatively, any element of the :py:attr:`~tags` list can be used as an argument to use that specific tag as the saved identifier. Returns: (generator): A stream of raw archive data. Raises: :py:class:`docker.errors.APIError` If the server returns an error. Example: >>> image = cli.get_image("busybox:latest") >>> f = open('/tmp/busybox-latest.tar', 'wb') >>> for chunk in image: >>> f.write(chunk) >>> f.close() """ img = self.id if named: img = self.tags[0] if self.tags else img if isinstance(named, six.string_types): if named not in self.tags: raise InvalidArgument( "{} is not a valid tag for this image".format(named) ) img = named return self.client.api.get_image(img, chunk_size)
def arg_types(parsed: Parsed, errors: Errors) -> Tuple[Parsed, Errors]: """Add argument types to parsed function data structure Args: parsed: function and arg locations in BEL string errors: error messages Returns: (parsed, errors): parsed, arguments with arg types plus error messages """ func_pattern = re.compile(r"\s*[a-zA-Z]+\(") nsarg_pattern = re.compile(r"^\s*([A-Z]+):(.*?)\s*$") for span in parsed: if parsed[span]["type"] != "Function" or "parens_span" not in parsed[span]: continue for i, arg in enumerate(parsed[span]["args"]): nsarg_matches = nsarg_pattern.match(arg["arg"]) if func_pattern.match(arg["arg"]): parsed[span]["args"][i].update({"type": "Function"}) elif nsarg_matches: (start, end) = arg["span"] ns = nsarg_matches.group(1) ns_val = nsarg_matches.group(2) ns_span = nsarg_matches.span(1) ns_span = (ns_span[0] + start, ns_span[1] + start - 1) ns_val_span = nsarg_matches.span(2) ns_val_span = (ns_val_span[0] + start, ns_val_span[1] + start - 1) parsed[span]["args"][i].update( { "type": "NSArg", "ns": ns, "ns_span": ns_span, "ns_val": ns_val, "ns_val_span": ns_val_span, } ) else: parsed[span]["args"][i].update({"type": "StrArg"}) return parsed, errors
Add argument types to parsed function data structure Args: parsed: function and arg locations in BEL string errors: error messages Returns: (parsed, errors): parsed, arguments with arg types plus error messages
Below is the the instruction that describes the task: ### Input: Add argument types to parsed function data structure Args: parsed: function and arg locations in BEL string errors: error messages Returns: (parsed, errors): parsed, arguments with arg types plus error messages ### Response: def arg_types(parsed: Parsed, errors: Errors) -> Tuple[Parsed, Errors]: """Add argument types to parsed function data structure Args: parsed: function and arg locations in BEL string errors: error messages Returns: (parsed, errors): parsed, arguments with arg types plus error messages """ func_pattern = re.compile(r"\s*[a-zA-Z]+\(") nsarg_pattern = re.compile(r"^\s*([A-Z]+):(.*?)\s*$") for span in parsed: if parsed[span]["type"] != "Function" or "parens_span" not in parsed[span]: continue for i, arg in enumerate(parsed[span]["args"]): nsarg_matches = nsarg_pattern.match(arg["arg"]) if func_pattern.match(arg["arg"]): parsed[span]["args"][i].update({"type": "Function"}) elif nsarg_matches: (start, end) = arg["span"] ns = nsarg_matches.group(1) ns_val = nsarg_matches.group(2) ns_span = nsarg_matches.span(1) ns_span = (ns_span[0] + start, ns_span[1] + start - 1) ns_val_span = nsarg_matches.span(2) ns_val_span = (ns_val_span[0] + start, ns_val_span[1] + start - 1) parsed[span]["args"][i].update( { "type": "NSArg", "ns": ns, "ns_span": ns_span, "ns_val": ns_val, "ns_val_span": ns_val_span, } ) else: parsed[span]["args"][i].update({"type": "StrArg"}) return parsed, errors
def set_doc_comment(self, doc, comment): """Sets document comment, Raises CardinalityError if comment already set. """ if not self.doc_comment_set: self.doc_comment_set = True doc.comment = comment else: raise CardinalityError('Document::Comment')
Sets document comment, Raises CardinalityError if comment already set.
Below is the the instruction that describes the task: ### Input: Sets document comment, Raises CardinalityError if comment already set. ### Response: def set_doc_comment(self, doc, comment): """Sets document comment, Raises CardinalityError if comment already set. """ if not self.doc_comment_set: self.doc_comment_set = True doc.comment = comment else: raise CardinalityError('Document::Comment')
def _create_epoch_data(self, streams: Optional[Iterable[str]]=None) -> EpochData: """Create empty epoch data double dict.""" if streams is None: streams = [self._train_stream_name] + self._extra_streams return OrderedDict([(stream_name, OrderedDict()) for stream_name in streams])
Create empty epoch data double dict.
Below is the the instruction that describes the task: ### Input: Create empty epoch data double dict. ### Response: def _create_epoch_data(self, streams: Optional[Iterable[str]]=None) -> EpochData: """Create empty epoch data double dict.""" if streams is None: streams = [self._train_stream_name] + self._extra_streams return OrderedDict([(stream_name, OrderedDict()) for stream_name in streams])
def register_on_event_source_changed(self, callback): """Set the callback function to consume on event source changed events. This occurs when a listener is added or removed. Callback receives a IEventStateChangedEvent object. Returns the callback_id """ event_type = library.VBoxEventType.on_event_source_changed return self.event_source.register_callback(callback, event_type)
Set the callback function to consume on event source changed events. This occurs when a listener is added or removed. Callback receives a IEventStateChangedEvent object. Returns the callback_id
Below is the the instruction that describes the task: ### Input: Set the callback function to consume on event source changed events. This occurs when a listener is added or removed. Callback receives a IEventStateChangedEvent object. Returns the callback_id ### Response: def register_on_event_source_changed(self, callback): """Set the callback function to consume on event source changed events. This occurs when a listener is added or removed. Callback receives a IEventStateChangedEvent object. Returns the callback_id """ event_type = library.VBoxEventType.on_event_source_changed return self.event_source.register_callback(callback, event_type)
def add_service(self, zeroconf, srv_type, srv_name): """Method called when a new Zeroconf client is detected. Return True if the zeroconf client is a Glances server Note: the return code will never be used """ if srv_type != zeroconf_type: return False logger.debug("Check new Zeroconf server: %s / %s" % (srv_type, srv_name)) info = zeroconf.get_service_info(srv_type, srv_name) if info: new_server_ip = socket.inet_ntoa(info.address) new_server_port = info.port # Add server to the global dict self.servers.add_server(srv_name, new_server_ip, new_server_port) logger.info("New Glances server detected (%s from %s:%s)" % (srv_name, new_server_ip, new_server_port)) else: logger.warning( "New Glances server detected, but Zeroconf info failed to be grabbed") return True
Method called when a new Zeroconf client is detected. Return True if the zeroconf client is a Glances server Note: the return code will never be used
Below is the the instruction that describes the task: ### Input: Method called when a new Zeroconf client is detected. Return True if the zeroconf client is a Glances server Note: the return code will never be used ### Response: def add_service(self, zeroconf, srv_type, srv_name): """Method called when a new Zeroconf client is detected. Return True if the zeroconf client is a Glances server Note: the return code will never be used """ if srv_type != zeroconf_type: return False logger.debug("Check new Zeroconf server: %s / %s" % (srv_type, srv_name)) info = zeroconf.get_service_info(srv_type, srv_name) if info: new_server_ip = socket.inet_ntoa(info.address) new_server_port = info.port # Add server to the global dict self.servers.add_server(srv_name, new_server_ip, new_server_port) logger.info("New Glances server detected (%s from %s:%s)" % (srv_name, new_server_ip, new_server_port)) else: logger.warning( "New Glances server detected, but Zeroconf info failed to be grabbed") return True
def probe(self, ipaddr=None): """ Probe given address for bulb. """ if ipaddr is None: # no address so use broadcast ipaddr = self._broadcast_addr cmd = {"payloadtype": PayloadType.GET, "target": ipaddr} self._send_command(cmd)
Probe given address for bulb.
Below is the the instruction that describes the task: ### Input: Probe given address for bulb. ### Response: def probe(self, ipaddr=None): """ Probe given address for bulb. """ if ipaddr is None: # no address so use broadcast ipaddr = self._broadcast_addr cmd = {"payloadtype": PayloadType.GET, "target": ipaddr} self._send_command(cmd)
def _cmp_by_asn(local_asn, path1, path2): """Select the path based on source (iBGP/eBGP) peer. eBGP path is preferred over iBGP. If both paths are from same kind of peers, return None. """ def get_path_source_asn(path): asn = None if path.source is None: asn = local_asn else: asn = path.source.remote_as return asn p1_asn = get_path_source_asn(path1) p2_asn = get_path_source_asn(path2) # If path1 is from ibgp peer and path2 is from ebgp peer. if (p1_asn == local_asn) and (p2_asn != local_asn): return path2 # If path2 is from ibgp peer and path1 is from ebgp peer, if (p2_asn == local_asn) and (p1_asn != local_asn): return path1 # If both paths are from ebgp or ibpg peers, we cannot decide. return None
Select the path based on source (iBGP/eBGP) peer. eBGP path is preferred over iBGP. If both paths are from same kind of peers, return None.
Below is the the instruction that describes the task: ### Input: Select the path based on source (iBGP/eBGP) peer. eBGP path is preferred over iBGP. If both paths are from same kind of peers, return None. ### Response: def _cmp_by_asn(local_asn, path1, path2): """Select the path based on source (iBGP/eBGP) peer. eBGP path is preferred over iBGP. If both paths are from same kind of peers, return None. """ def get_path_source_asn(path): asn = None if path.source is None: asn = local_asn else: asn = path.source.remote_as return asn p1_asn = get_path_source_asn(path1) p2_asn = get_path_source_asn(path2) # If path1 is from ibgp peer and path2 is from ebgp peer. if (p1_asn == local_asn) and (p2_asn != local_asn): return path2 # If path2 is from ibgp peer and path1 is from ebgp peer, if (p2_asn == local_asn) and (p1_asn != local_asn): return path1 # If both paths are from ebgp or ibpg peers, we cannot decide. return None
def get_pypi_package_data(package_name, version=None): """ Get package data from pypi by the package name https://wiki.python.org/moin/PyPIJSON :param package_name: string :param version: string :return: dict """ pypi_url = 'https://pypi.org/pypi' if version: package_url = '%s/%s/%s/json' % (pypi_url, package_name, version, ) else: package_url = '%s/%s/json' % (pypi_url, package_name, ) try: response = requests.get(package_url) except requests.ConnectionError: raise RuntimeError('Connection error!') # Package not available on pypi if not response.ok: return None return response.json()
Get package data from pypi by the package name https://wiki.python.org/moin/PyPIJSON :param package_name: string :param version: string :return: dict
Below is the the instruction that describes the task: ### Input: Get package data from pypi by the package name https://wiki.python.org/moin/PyPIJSON :param package_name: string :param version: string :return: dict ### Response: def get_pypi_package_data(package_name, version=None): """ Get package data from pypi by the package name https://wiki.python.org/moin/PyPIJSON :param package_name: string :param version: string :return: dict """ pypi_url = 'https://pypi.org/pypi' if version: package_url = '%s/%s/%s/json' % (pypi_url, package_name, version, ) else: package_url = '%s/%s/json' % (pypi_url, package_name, ) try: response = requests.get(package_url) except requests.ConnectionError: raise RuntimeError('Connection error!') # Package not available on pypi if not response.ok: return None return response.json()
def new_cast_status(self, status): """ Called when a new status received from the Chromecast. """ self.status = status if status: self.status_event.set()
Called when a new status received from the Chromecast.
Below is the the instruction that describes the task: ### Input: Called when a new status received from the Chromecast. ### Response: def new_cast_status(self, status): """ Called when a new status received from the Chromecast. """ self.status = status if status: self.status_event.set()
def init(len,default_element=None): ''' from elist.elist import * init(5) init(5,"x") ''' rslt = [] for i in range(0,len): rslt.append(copy.deepcopy(default_element)) return(rslt)
from elist.elist import * init(5) init(5,"x")
Below is the the instruction that describes the task: ### Input: from elist.elist import * init(5) init(5,"x") ### Response: def init(len,default_element=None): ''' from elist.elist import * init(5) init(5,"x") ''' rslt = [] for i in range(0,len): rslt.append(copy.deepcopy(default_element)) return(rslt)
def connected_socket(address, timeout=3): """ yields a connected socket """ sock = socket.create_connection(address, timeout) yield sock sock.close()
yields a connected socket
Below is the the instruction that describes the task: ### Input: yields a connected socket ### Response: def connected_socket(address, timeout=3): """ yields a connected socket """ sock = socket.create_connection(address, timeout) yield sock sock.close()
def on_files_dropped_on_group(self, files, group_id: int): """ :param group_id: :type files: list of QtCore.QUrl """ self.__add_urls_to_group(files, group_id=group_id)
:param group_id: :type files: list of QtCore.QUrl
Below is the the instruction that describes the task: ### Input: :param group_id: :type files: list of QtCore.QUrl ### Response: def on_files_dropped_on_group(self, files, group_id: int): """ :param group_id: :type files: list of QtCore.QUrl """ self.__add_urls_to_group(files, group_id=group_id)
def nvalues(self): """Returns the number of values recorded on this single line. If the number is variable, it returns -1.""" if self._nvalues is None: self._nvalues = 0 for val in self.values: if type(val) == type(int): self._nvalues += val else: self._nvalues = -1 break return self._nvalues
Returns the number of values recorded on this single line. If the number is variable, it returns -1.
Below is the the instruction that describes the task: ### Input: Returns the number of values recorded on this single line. If the number is variable, it returns -1. ### Response: def nvalues(self): """Returns the number of values recorded on this single line. If the number is variable, it returns -1.""" if self._nvalues is None: self._nvalues = 0 for val in self.values: if type(val) == type(int): self._nvalues += val else: self._nvalues = -1 break return self._nvalues
def description(pokemon): """Return a description of the given Pokemon.""" r = requests.get('http://pokeapi.co/' + (pokemon.descriptions.values()[0])) desc = eval(r.text)['description'].replace('Pokmon', 'Pokémon') return desc
Return a description of the given Pokemon.
Below is the the instruction that describes the task: ### Input: Return a description of the given Pokemon. ### Response: def description(pokemon): """Return a description of the given Pokemon.""" r = requests.get('http://pokeapi.co/' + (pokemon.descriptions.values()[0])) desc = eval(r.text)['description'].replace('Pokmon', 'Pokémon') return desc
def execute(self, task, script, **kwargs): """ Execute the script, within the context of the specified task """ locals().update(kwargs) exec(script)
Execute the script, within the context of the specified task
Below is the the instruction that describes the task: ### Input: Execute the script, within the context of the specified task ### Response: def execute(self, task, script, **kwargs): """ Execute the script, within the context of the specified task """ locals().update(kwargs) exec(script)
def project(dest, app_bundle, force, dev, admin, api, celery, graphene, mail, oauth, security, session, sqlalchemy, webpack): """ Create a new Flask Unchained project. """ if os.path.exists(dest) and os.listdir(dest) and not force: if not click.confirm(f'WARNING: Project directory {dest!r} exists and is ' f'not empty. It will be DELETED!!! Continue?'): click.echo(f'Exiting.') sys.exit(1) # build up a list of dependencies # IMPORTANT: keys here must match setup.py's `extra_requires` keys ctx = dict(dev=dev, admin=admin, api=api, celery=celery, graphene=graphene, mail=mail, oauth=oauth, security=security or oauth, session=security or session, sqlalchemy=security or sqlalchemy, webpack=webpack) ctx['requirements'] = [k for k, v in ctx.items() if v] # remaining ctx vars ctx['app_bundle_module_name'] = app_bundle # copy the project template into place copy_file_tree(PROJECT_TEMPLATE, dest, ctx, [ (option, files) for option, files in [('api', ['app/serializers']), ('celery', ['app/tasks', 'celery_app.py']), ('graphene', ['app/graphql']), ('mail', ['templates/email']), ('security', ['app/models/role.py', 'app/models/user.py', 'db/fixtures/Role.yaml', 'db/fixtures/User.yaml']), ('webpack', ['assets', 'package.json', 'webpack']), ] if not ctx[option] ]) click.echo(f'Successfully created a new project at: {dest}')
Create a new Flask Unchained project.
Below is the the instruction that describes the task: ### Input: Create a new Flask Unchained project. ### Response: def project(dest, app_bundle, force, dev, admin, api, celery, graphene, mail, oauth, security, session, sqlalchemy, webpack): """ Create a new Flask Unchained project. """ if os.path.exists(dest) and os.listdir(dest) and not force: if not click.confirm(f'WARNING: Project directory {dest!r} exists and is ' f'not empty. It will be DELETED!!! Continue?'): click.echo(f'Exiting.') sys.exit(1) # build up a list of dependencies # IMPORTANT: keys here must match setup.py's `extra_requires` keys ctx = dict(dev=dev, admin=admin, api=api, celery=celery, graphene=graphene, mail=mail, oauth=oauth, security=security or oauth, session=security or session, sqlalchemy=security or sqlalchemy, webpack=webpack) ctx['requirements'] = [k for k, v in ctx.items() if v] # remaining ctx vars ctx['app_bundle_module_name'] = app_bundle # copy the project template into place copy_file_tree(PROJECT_TEMPLATE, dest, ctx, [ (option, files) for option, files in [('api', ['app/serializers']), ('celery', ['app/tasks', 'celery_app.py']), ('graphene', ['app/graphql']), ('mail', ['templates/email']), ('security', ['app/models/role.py', 'app/models/user.py', 'db/fixtures/Role.yaml', 'db/fixtures/User.yaml']), ('webpack', ['assets', 'package.json', 'webpack']), ] if not ctx[option] ]) click.echo(f'Successfully created a new project at: {dest}')
def unserialize(wd: WordDictionary, text: Dict): """ Transforms back a serialized value of `serialize()` """ if not isinstance(text, Mapping): raise ValueError('Text has not the right format') try: t = text['type'] if t == 'string': return text['value'] elif t == 'trans': if not isinstance(text['params'], Mapping): raise ValueError('Params should be a dictionary') for param in text['params']: if not isinstance(param, str): raise ValueError('Params are not all text-keys') return StringToTranslate( wd=wd, key=text['key'], count=text['count'], params=text['params'], ) else: raise ValueError('Unknown type "{}"'.format(t)) except KeyError: raise ValueError('Not enough information to unserialize')
Transforms back a serialized value of `serialize()`
Below is the the instruction that describes the task: ### Input: Transforms back a serialized value of `serialize()` ### Response: def unserialize(wd: WordDictionary, text: Dict): """ Transforms back a serialized value of `serialize()` """ if not isinstance(text, Mapping): raise ValueError('Text has not the right format') try: t = text['type'] if t == 'string': return text['value'] elif t == 'trans': if not isinstance(text['params'], Mapping): raise ValueError('Params should be a dictionary') for param in text['params']: if not isinstance(param, str): raise ValueError('Params are not all text-keys') return StringToTranslate( wd=wd, key=text['key'], count=text['count'], params=text['params'], ) else: raise ValueError('Unknown type "{}"'.format(t)) except KeyError: raise ValueError('Not enough information to unserialize')
def _indexable_roles_and_users(self): """Return a string made for indexing roles having :any:`READ` permission on this object.""" from abilian.services.indexing import indexable_role from abilian.services.security import READ, Admin, Anonymous, Creator, Owner from abilian.services import get_service result = [] security = get_service("security") # roles - required to match when user has a global role assignments = security.get_permissions_assignments(permission=READ, obj=self) allowed_roles = assignments.get(READ, set()) allowed_roles.add(Admin) for r in allowed_roles: result.append(indexable_role(r)) for role, attr in ((Creator, "creator"), (Owner, "owner")): if role in allowed_roles: user = getattr(self, attr) if user: result.append(indexable_role(user)) # users and groups principals = set() for user, role in security.get_role_assignements(self): if role in allowed_roles: principals.add(user) if Anonymous in principals: # it's a role listed in role assignments - legacy when there wasn't # permission-role assignments principals.remove(Anonymous) for p in principals: result.append(indexable_role(p)) return " ".join(result)
Return a string made for indexing roles having :any:`READ` permission on this object.
Below is the the instruction that describes the task: ### Input: Return a string made for indexing roles having :any:`READ` permission on this object. ### Response: def _indexable_roles_and_users(self): """Return a string made for indexing roles having :any:`READ` permission on this object.""" from abilian.services.indexing import indexable_role from abilian.services.security import READ, Admin, Anonymous, Creator, Owner from abilian.services import get_service result = [] security = get_service("security") # roles - required to match when user has a global role assignments = security.get_permissions_assignments(permission=READ, obj=self) allowed_roles = assignments.get(READ, set()) allowed_roles.add(Admin) for r in allowed_roles: result.append(indexable_role(r)) for role, attr in ((Creator, "creator"), (Owner, "owner")): if role in allowed_roles: user = getattr(self, attr) if user: result.append(indexable_role(user)) # users and groups principals = set() for user, role in security.get_role_assignements(self): if role in allowed_roles: principals.add(user) if Anonymous in principals: # it's a role listed in role assignments - legacy when there wasn't # permission-role assignments principals.remove(Anonymous) for p in principals: result.append(indexable_role(p)) return " ".join(result)
def bool_value(self): """Infer the truth value for an Instance The truth value of an instance is determined by these conditions: * if it implements __bool__ on Python 3 or __nonzero__ on Python 2, then its bool value will be determined by calling this special method and checking its result. * when this method is not defined, __len__() is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither __len__() nor __bool__(), all its instances are considered true. """ context = contextmod.InferenceContext() context.callcontext = contextmod.CallContext(args=[]) context.boundnode = self try: result = _infer_method_result_truth(self, BOOL_SPECIAL_METHOD, context) except (exceptions.InferenceError, exceptions.AttributeInferenceError): # Fallback to __len__. try: result = _infer_method_result_truth(self, "__len__", context) except (exceptions.AttributeInferenceError, exceptions.InferenceError): return True return result
Infer the truth value for an Instance The truth value of an instance is determined by these conditions: * if it implements __bool__ on Python 3 or __nonzero__ on Python 2, then its bool value will be determined by calling this special method and checking its result. * when this method is not defined, __len__() is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither __len__() nor __bool__(), all its instances are considered true.
Below is the the instruction that describes the task: ### Input: Infer the truth value for an Instance The truth value of an instance is determined by these conditions: * if it implements __bool__ on Python 3 or __nonzero__ on Python 2, then its bool value will be determined by calling this special method and checking its result. * when this method is not defined, __len__() is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither __len__() nor __bool__(), all its instances are considered true. ### Response: def bool_value(self): """Infer the truth value for an Instance The truth value of an instance is determined by these conditions: * if it implements __bool__ on Python 3 or __nonzero__ on Python 2, then its bool value will be determined by calling this special method and checking its result. * when this method is not defined, __len__() is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither __len__() nor __bool__(), all its instances are considered true. """ context = contextmod.InferenceContext() context.callcontext = contextmod.CallContext(args=[]) context.boundnode = self try: result = _infer_method_result_truth(self, BOOL_SPECIAL_METHOD, context) except (exceptions.InferenceError, exceptions.AttributeInferenceError): # Fallback to __len__. try: result = _infer_method_result_truth(self, "__len__", context) except (exceptions.AttributeInferenceError, exceptions.InferenceError): return True return result
def raster_collection_vrt(fc, relative_to_vrt=True, nodata=None, mask_band=None): """Make a VRT XML document from a feature collection of GeoRaster2 objects. Parameters ---------- rasters : FeatureCollection The FeatureCollection of GeoRasters. relative_to_vrt : bool, optional If True the bands simple source url will be related to the VRT file nodata : int, optional If supplied is the note data value to be used mask_band: int, optional If specified detrimes from which band to use the mask Returns ------- bytes An ascii-encoded string (an ElementTree detail) """ def max_resolution(): max_affine = max(fc, key=lambda f: f.raster().resolution()).raster().affine return abs(max_affine.a), abs(max_affine.e) from telluric import rasterization from telluric.georaster import band_names_tag assert all(fc.crs == f.crs for f in fc), "all rasters should have the same CRS" rasters = (f.raster() for f in fc) bounds = fc.convex_hull.get_bounds(fc.crs) resolution = max_resolution() width, height, affine = rasterization.raster_data(bounds, resolution) bands = {} # type: Dict[str, tuple] band_names = [] # type: List[Any] vrt = BaseVRT(width, height, fc.crs, affine) last_band_idx = 0 if mask_band is not None: mask_band = vrt.add_mask_band("Byte") for raster in rasters: for i, band_name in enumerate(raster.band_names): if band_name in bands: band_element, band_idx = bands[band_name] else: last_band_idx += 1 band_idx = last_band_idx band_element = vrt.add_band(raster.dtype, band_idx, band_name_to_color_interpretation(band_name), nodata=nodata) bands[band_name] = (band_element, last_band_idx) band_names.append(band_name) src_window = Window(0, 0, raster.width, raster.height) xoff = (raster.affine.xoff - affine.xoff) / affine.a yoff = (raster.affine.yoff - affine.yoff) / affine.e xsize = raster.width * raster.affine.a / affine.a ysize = raster.height * raster.affine.e / affine.e dst_window = Window(xoff, yoff, xsize, ysize) file_name = raster.source_file if relative_to_vrt else os.path.join(os.getcwd(), raster.source_file) vrt.add_band_simplesource(band_element, band_idx, raster.dtype, relative_to_vrt, file_name, raster.width, raster.height, raster.block_shape(i)[1], raster.block_shape(i)[0], src_window, dst_window) if i == mask_band: vrt.add_band_simplesource(mask_band, "mask,%s" % (mask_band + 1), "Byte", relative_to_vrt, file_name, raster.width, raster.height, raster.block_shape(i)[1], raster.block_shape(i)[0], src_window, dst_window) vrt.add_metadata(items={band_names_tag: json.dumps(band_names)}) return vrt
Make a VRT XML document from a feature collection of GeoRaster2 objects. Parameters ---------- rasters : FeatureCollection The FeatureCollection of GeoRasters. relative_to_vrt : bool, optional If True the bands simple source url will be related to the VRT file nodata : int, optional If supplied is the note data value to be used mask_band: int, optional If specified detrimes from which band to use the mask Returns ------- bytes An ascii-encoded string (an ElementTree detail)
Below is the the instruction that describes the task: ### Input: Make a VRT XML document from a feature collection of GeoRaster2 objects. Parameters ---------- rasters : FeatureCollection The FeatureCollection of GeoRasters. relative_to_vrt : bool, optional If True the bands simple source url will be related to the VRT file nodata : int, optional If supplied is the note data value to be used mask_band: int, optional If specified detrimes from which band to use the mask Returns ------- bytes An ascii-encoded string (an ElementTree detail) ### Response: def raster_collection_vrt(fc, relative_to_vrt=True, nodata=None, mask_band=None): """Make a VRT XML document from a feature collection of GeoRaster2 objects. Parameters ---------- rasters : FeatureCollection The FeatureCollection of GeoRasters. relative_to_vrt : bool, optional If True the bands simple source url will be related to the VRT file nodata : int, optional If supplied is the note data value to be used mask_band: int, optional If specified detrimes from which band to use the mask Returns ------- bytes An ascii-encoded string (an ElementTree detail) """ def max_resolution(): max_affine = max(fc, key=lambda f: f.raster().resolution()).raster().affine return abs(max_affine.a), abs(max_affine.e) from telluric import rasterization from telluric.georaster import band_names_tag assert all(fc.crs == f.crs for f in fc), "all rasters should have the same CRS" rasters = (f.raster() for f in fc) bounds = fc.convex_hull.get_bounds(fc.crs) resolution = max_resolution() width, height, affine = rasterization.raster_data(bounds, resolution) bands = {} # type: Dict[str, tuple] band_names = [] # type: List[Any] vrt = BaseVRT(width, height, fc.crs, affine) last_band_idx = 0 if mask_band is not None: mask_band = vrt.add_mask_band("Byte") for raster in rasters: for i, band_name in enumerate(raster.band_names): if band_name in bands: band_element, band_idx = bands[band_name] else: last_band_idx += 1 band_idx = last_band_idx band_element = vrt.add_band(raster.dtype, band_idx, band_name_to_color_interpretation(band_name), nodata=nodata) bands[band_name] = (band_element, last_band_idx) band_names.append(band_name) src_window = Window(0, 0, raster.width, raster.height) xoff = (raster.affine.xoff - affine.xoff) / affine.a yoff = (raster.affine.yoff - affine.yoff) / affine.e xsize = raster.width * raster.affine.a / affine.a ysize = raster.height * raster.affine.e / affine.e dst_window = Window(xoff, yoff, xsize, ysize) file_name = raster.source_file if relative_to_vrt else os.path.join(os.getcwd(), raster.source_file) vrt.add_band_simplesource(band_element, band_idx, raster.dtype, relative_to_vrt, file_name, raster.width, raster.height, raster.block_shape(i)[1], raster.block_shape(i)[0], src_window, dst_window) if i == mask_band: vrt.add_band_simplesource(mask_band, "mask,%s" % (mask_band + 1), "Byte", relative_to_vrt, file_name, raster.width, raster.height, raster.block_shape(i)[1], raster.block_shape(i)[0], src_window, dst_window) vrt.add_metadata(items={band_names_tag: json.dumps(band_names)}) return vrt
def ellipticity2phi_q(e1, e2): """ :param e1: :param e2: :return: """ phi = np.arctan2(e2, e1)/2 c = np.sqrt(e1**2+e2**2) if c > 0.999: c = 0.999 q = (1-c)/(1+c) return phi, q
:param e1: :param e2: :return:
Below is the the instruction that describes the task: ### Input: :param e1: :param e2: :return: ### Response: def ellipticity2phi_q(e1, e2): """ :param e1: :param e2: :return: """ phi = np.arctan2(e2, e1)/2 c = np.sqrt(e1**2+e2**2) if c > 0.999: c = 0.999 q = (1-c)/(1+c) return phi, q
def body(self): """The body of the packet.""" view = ffi.buffer(self.packet.m_body, self.packet.m_nBodySize) return view[:]
The body of the packet.
Below is the the instruction that describes the task: ### Input: The body of the packet. ### Response: def body(self): """The body of the packet.""" view = ffi.buffer(self.packet.m_body, self.packet.m_nBodySize) return view[:]
def list_rulesets(debug): """ List available rulesets. """ try: rulesets = get_rulesets() max_len = max([len(r[0]) for r in rulesets]) for r in rulesets: click.echo('{0: <{1}} ({2})'.format(r[0], max_len, r[1])) except Exception as ex: logger.error("An error occurred: %r", ex) if debug: raise else: raise click.ClickException(str(ex))
List available rulesets.
Below is the the instruction that describes the task: ### Input: List available rulesets. ### Response: def list_rulesets(debug): """ List available rulesets. """ try: rulesets = get_rulesets() max_len = max([len(r[0]) for r in rulesets]) for r in rulesets: click.echo('{0: <{1}} ({2})'.format(r[0], max_len, r[1])) except Exception as ex: logger.error("An error occurred: %r", ex) if debug: raise else: raise click.ClickException(str(ex))
def clean(self, is_table=False): """ Remove reserved keywords from the header. These are keywords that the fits writer must write in order to maintain consistency between header and data. keywords -------- is_table: bool, optional Set True if this is a table, so extra keywords will be cleaned """ rmnames = [ 'SIMPLE', 'EXTEND', 'XTENSION', 'BITPIX', 'PCOUNT', 'GCOUNT', 'THEAP', 'EXTNAME', 'BLANK', 'ZQUANTIZ', 'ZDITHER0', 'ZIMAGE', 'ZCMPTYPE', 'ZSIMPLE', 'ZTENSION', 'ZPCOUNT', 'ZGCOUNT', 'ZBITPIX', 'ZEXTEND', # 'FZTILELN','FZALGOR', 'CHECKSUM', 'DATASUM'] if is_table: # these are not allowed in tables rmnames += [ 'BUNIT', 'BSCALE', 'BZERO', ] self.delete(rmnames) r = self._record_map.get('NAXIS', None) if r is not None: naxis = int(r['value']) self.delete('NAXIS') rmnames = ['NAXIS%d' % i for i in xrange(1, naxis+1)] self.delete(rmnames) r = self._record_map.get('ZNAXIS', None) self.delete('ZNAXIS') if r is not None: znaxis = int(r['value']) rmnames = ['ZNAXIS%d' % i for i in xrange(1, znaxis+1)] self.delete(rmnames) rmnames = ['ZTILE%d' % i for i in xrange(1, znaxis+1)] self.delete(rmnames) rmnames = ['ZNAME%d' % i for i in xrange(1, znaxis+1)] self.delete(rmnames) rmnames = ['ZVAL%d' % i for i in xrange(1, znaxis+1)] self.delete(rmnames) r = self._record_map.get('TFIELDS', None) if r is not None: tfields = int(r['value']) self.delete('TFIELDS') if tfields > 0: nbase = [ 'TFORM', 'TTYPE', 'TDIM', 'TUNIT', 'TSCAL', 'TZERO', 'TNULL', 'TDISP', 'TDMIN', 'TDMAX', 'TDESC', 'TROTA', 'TRPIX', 'TRVAL', 'TDELT', 'TCUNI', # 'FZALG' ] for i in xrange(1, tfields+1): names = ['%s%d' % (n, i) for n in nbase] self.delete(names)
Remove reserved keywords from the header. These are keywords that the fits writer must write in order to maintain consistency between header and data. keywords -------- is_table: bool, optional Set True if this is a table, so extra keywords will be cleaned
Below is the the instruction that describes the task: ### Input: Remove reserved keywords from the header. These are keywords that the fits writer must write in order to maintain consistency between header and data. keywords -------- is_table: bool, optional Set True if this is a table, so extra keywords will be cleaned ### Response: def clean(self, is_table=False): """ Remove reserved keywords from the header. These are keywords that the fits writer must write in order to maintain consistency between header and data. keywords -------- is_table: bool, optional Set True if this is a table, so extra keywords will be cleaned """ rmnames = [ 'SIMPLE', 'EXTEND', 'XTENSION', 'BITPIX', 'PCOUNT', 'GCOUNT', 'THEAP', 'EXTNAME', 'BLANK', 'ZQUANTIZ', 'ZDITHER0', 'ZIMAGE', 'ZCMPTYPE', 'ZSIMPLE', 'ZTENSION', 'ZPCOUNT', 'ZGCOUNT', 'ZBITPIX', 'ZEXTEND', # 'FZTILELN','FZALGOR', 'CHECKSUM', 'DATASUM'] if is_table: # these are not allowed in tables rmnames += [ 'BUNIT', 'BSCALE', 'BZERO', ] self.delete(rmnames) r = self._record_map.get('NAXIS', None) if r is not None: naxis = int(r['value']) self.delete('NAXIS') rmnames = ['NAXIS%d' % i for i in xrange(1, naxis+1)] self.delete(rmnames) r = self._record_map.get('ZNAXIS', None) self.delete('ZNAXIS') if r is not None: znaxis = int(r['value']) rmnames = ['ZNAXIS%d' % i for i in xrange(1, znaxis+1)] self.delete(rmnames) rmnames = ['ZTILE%d' % i for i in xrange(1, znaxis+1)] self.delete(rmnames) rmnames = ['ZNAME%d' % i for i in xrange(1, znaxis+1)] self.delete(rmnames) rmnames = ['ZVAL%d' % i for i in xrange(1, znaxis+1)] self.delete(rmnames) r = self._record_map.get('TFIELDS', None) if r is not None: tfields = int(r['value']) self.delete('TFIELDS') if tfields > 0: nbase = [ 'TFORM', 'TTYPE', 'TDIM', 'TUNIT', 'TSCAL', 'TZERO', 'TNULL', 'TDISP', 'TDMIN', 'TDMAX', 'TDESC', 'TROTA', 'TRPIX', 'TRVAL', 'TDELT', 'TCUNI', # 'FZALG' ] for i in xrange(1, tfields+1): names = ['%s%d' % (n, i) for n in nbase] self.delete(names)
async def servo_config(self, pin, min_pulse=544, max_pulse=2400): """ Configure a pin as a servo pin. Set pulse min, max in ms. Use this method (not set_pin_mode) to configure a pin for servo operation. :param pin: Servo Pin. :param min_pulse: Min pulse width in ms. :param max_pulse: Max pulse width in ms. :returns: No return value """ command = [pin, min_pulse & 0x7f, (min_pulse >> 7) & 0x7f, max_pulse & 0x7f, (max_pulse >> 7) & 0x7f] await self._send_sysex(PrivateConstants.SERVO_CONFIG, command)
Configure a pin as a servo pin. Set pulse min, max in ms. Use this method (not set_pin_mode) to configure a pin for servo operation. :param pin: Servo Pin. :param min_pulse: Min pulse width in ms. :param max_pulse: Max pulse width in ms. :returns: No return value
Below is the the instruction that describes the task: ### Input: Configure a pin as a servo pin. Set pulse min, max in ms. Use this method (not set_pin_mode) to configure a pin for servo operation. :param pin: Servo Pin. :param min_pulse: Min pulse width in ms. :param max_pulse: Max pulse width in ms. :returns: No return value ### Response: async def servo_config(self, pin, min_pulse=544, max_pulse=2400): """ Configure a pin as a servo pin. Set pulse min, max in ms. Use this method (not set_pin_mode) to configure a pin for servo operation. :param pin: Servo Pin. :param min_pulse: Min pulse width in ms. :param max_pulse: Max pulse width in ms. :returns: No return value """ command = [pin, min_pulse & 0x7f, (min_pulse >> 7) & 0x7f, max_pulse & 0x7f, (max_pulse >> 7) & 0x7f] await self._send_sysex(PrivateConstants.SERVO_CONFIG, command)
def getPlatformInfo(): """Identify platform.""" if "linux" in sys.platform: platform = "linux" elif "darwin" in sys.platform: platform = "darwin" # win32 elif sys.platform.startswith("win"): platform = "windows" else: raise Exception("Platform '%s' is unsupported!" % sys.platform) return platform
Identify platform.
Below is the the instruction that describes the task: ### Input: Identify platform. ### Response: def getPlatformInfo(): """Identify platform.""" if "linux" in sys.platform: platform = "linux" elif "darwin" in sys.platform: platform = "darwin" # win32 elif sys.platform.startswith("win"): platform = "windows" else: raise Exception("Platform '%s' is unsupported!" % sys.platform) return platform
def DeregisterAnalyzer(cls, analyzer_class): """Deregisters a analyzer class. The analyzer classes are identified based on their lower case name. Args: analyzer_class (type): class object of the analyzer. Raises: KeyError: if analyzer class is not set for the corresponding name. """ analyzer_name = analyzer_class.NAME.lower() if analyzer_name not in cls._analyzer_classes: raise KeyError('analyzer class not set for name: {0:s}'.format( analyzer_class.NAME)) del cls._analyzer_classes[analyzer_name]
Deregisters a analyzer class. The analyzer classes are identified based on their lower case name. Args: analyzer_class (type): class object of the analyzer. Raises: KeyError: if analyzer class is not set for the corresponding name.
Below is the the instruction that describes the task: ### Input: Deregisters a analyzer class. The analyzer classes are identified based on their lower case name. Args: analyzer_class (type): class object of the analyzer. Raises: KeyError: if analyzer class is not set for the corresponding name. ### Response: def DeregisterAnalyzer(cls, analyzer_class): """Deregisters a analyzer class. The analyzer classes are identified based on their lower case name. Args: analyzer_class (type): class object of the analyzer. Raises: KeyError: if analyzer class is not set for the corresponding name. """ analyzer_name = analyzer_class.NAME.lower() if analyzer_name not in cls._analyzer_classes: raise KeyError('analyzer class not set for name: {0:s}'.format( analyzer_class.NAME)) del cls._analyzer_classes[analyzer_name]
def _expand_inputs(step, steps=None): """ Returns the set of this step and all steps passed to the constructor (recursively). """ if steps is None: steps = set() for arg in step._kwargs.values(): if isinstance(arg, Step): _expand_inputs(arg, steps=steps) elif util.is_instance_collection(arg, Step): for s in util.get_collection_values(arg): _expand_inputs(s, steps=steps) steps.add(step) return steps
Returns the set of this step and all steps passed to the constructor (recursively).
Below is the the instruction that describes the task: ### Input: Returns the set of this step and all steps passed to the constructor (recursively). ### Response: def _expand_inputs(step, steps=None): """ Returns the set of this step and all steps passed to the constructor (recursively). """ if steps is None: steps = set() for arg in step._kwargs.values(): if isinstance(arg, Step): _expand_inputs(arg, steps=steps) elif util.is_instance_collection(arg, Step): for s in util.get_collection_values(arg): _expand_inputs(s, steps=steps) steps.add(step) return steps
def assemble(self): """Assemble a QasmQobjInstruction""" instruction = QasmQobjInstruction(name=self.name) # Evaluate parameters if self.params: params = [ x.evalf() if hasattr(x, 'evalf') else x for x in self.params ] params = [ sympy.matrix2numpy(x, dtype=complex) if isinstance( x, sympy.Matrix) else x for x in params ] instruction.params = params # Add placeholder for qarg and carg params if self.num_qubits: instruction.qubits = list(range(self.num_qubits)) if self.num_clbits: instruction.memory = list(range(self.num_clbits)) # Add control parameters for assembler. This is needed to convert # to a qobj conditional instruction at assemble time and after # conversion will be deleted by the assembler. if self.control: instruction._control = self.control return instruction
Assemble a QasmQobjInstruction
Below is the the instruction that describes the task: ### Input: Assemble a QasmQobjInstruction ### Response: def assemble(self): """Assemble a QasmQobjInstruction""" instruction = QasmQobjInstruction(name=self.name) # Evaluate parameters if self.params: params = [ x.evalf() if hasattr(x, 'evalf') else x for x in self.params ] params = [ sympy.matrix2numpy(x, dtype=complex) if isinstance( x, sympy.Matrix) else x for x in params ] instruction.params = params # Add placeholder for qarg and carg params if self.num_qubits: instruction.qubits = list(range(self.num_qubits)) if self.num_clbits: instruction.memory = list(range(self.num_clbits)) # Add control parameters for assembler. This is needed to convert # to a qobj conditional instruction at assemble time and after # conversion will be deleted by the assembler. if self.control: instruction._control = self.control return instruction
def find_prop_overlap(rdf, prop1, prop2): """Generate (subject,object) pairs connected by two properties.""" for s, o in sorted(rdf.subject_objects(prop1)): if (s, prop2, o) in rdf: yield (s, o)
Generate (subject,object) pairs connected by two properties.
Below is the the instruction that describes the task: ### Input: Generate (subject,object) pairs connected by two properties. ### Response: def find_prop_overlap(rdf, prop1, prop2): """Generate (subject,object) pairs connected by two properties.""" for s, o in sorted(rdf.subject_objects(prop1)): if (s, prop2, o) in rdf: yield (s, o)
def publish(self, path): """Publish file or folder and return public url""" def parseContent(content): root = ET.fromstring(content) prop = root.find(".//d:prop", namespaces=self.namespaces) return prop.find("{urn:yandex:disk:meta}public_url").text.strip() data = """ <propertyupdate xmlns="DAV:"> <set> <prop> <public_url xmlns="urn:yandex:disk:meta">true</public_url> </prop> </set> </propertyupdate> """ _check_dst_absolute(path) resp = self._sendRequest("PROPPATCH", addUrl=path, data=data) if resp.status_code == 207: return parseContent(resp.content) else: raise YaDiskException(resp.status_code, resp.content)
Publish file or folder and return public url
Below is the the instruction that describes the task: ### Input: Publish file or folder and return public url ### Response: def publish(self, path): """Publish file or folder and return public url""" def parseContent(content): root = ET.fromstring(content) prop = root.find(".//d:prop", namespaces=self.namespaces) return prop.find("{urn:yandex:disk:meta}public_url").text.strip() data = """ <propertyupdate xmlns="DAV:"> <set> <prop> <public_url xmlns="urn:yandex:disk:meta">true</public_url> </prop> </set> </propertyupdate> """ _check_dst_absolute(path) resp = self._sendRequest("PROPPATCH", addUrl=path, data=data) if resp.status_code == 207: return parseContent(resp.content) else: raise YaDiskException(resp.status_code, resp.content)
def add_eval(self, agent, e, fr=None): """Add or change agent's evaluation of the artifact with given framing information. :param agent: Name of the agent which did the evaluation. :param float e: Evaluation for the artifact. :param object fr: Framing information for the evaluation. """ self._evals[agent.name] = e self._framings[agent.name] = fr
Add or change agent's evaluation of the artifact with given framing information. :param agent: Name of the agent which did the evaluation. :param float e: Evaluation for the artifact. :param object fr: Framing information for the evaluation.
Below is the the instruction that describes the task: ### Input: Add or change agent's evaluation of the artifact with given framing information. :param agent: Name of the agent which did the evaluation. :param float e: Evaluation for the artifact. :param object fr: Framing information for the evaluation. ### Response: def add_eval(self, agent, e, fr=None): """Add or change agent's evaluation of the artifact with given framing information. :param agent: Name of the agent which did the evaluation. :param float e: Evaluation for the artifact. :param object fr: Framing information for the evaluation. """ self._evals[agent.name] = e self._framings[agent.name] = fr
def command(self, name, handler_name, **kwargs): """ Register a command into the command table :param name: The name of the command :type name: str :param handler_name: The name of the handler that will be applied to the operations template :type handler_name: str :param kwargs: Kwargs to apply to the command. Possible values: `client_factory`, `arguments_loader`, `description_loader`, `description`, `formatter_class`, `table_transformer`, `deprecate_info`, `validator`, `confirmation`. """ import copy command_name = '{} {}'.format(self.group_name, name) if self.group_name else name command_kwargs = copy.deepcopy(self.group_kwargs) command_kwargs.update(kwargs) # don't inherit deprecation info from command group command_kwargs['deprecate_info'] = kwargs.get('deprecate_info', None) self.command_loader._populate_command_group_table_with_subgroups(' '.join(command_name.split()[:-1])) # pylint: disable=protected-access self.command_loader.command_table[command_name] = self.command_loader.create_command( command_name, self.operations_tmpl.format(handler_name), **command_kwargs)
Register a command into the command table :param name: The name of the command :type name: str :param handler_name: The name of the handler that will be applied to the operations template :type handler_name: str :param kwargs: Kwargs to apply to the command. Possible values: `client_factory`, `arguments_loader`, `description_loader`, `description`, `formatter_class`, `table_transformer`, `deprecate_info`, `validator`, `confirmation`.
Below is the the instruction that describes the task: ### Input: Register a command into the command table :param name: The name of the command :type name: str :param handler_name: The name of the handler that will be applied to the operations template :type handler_name: str :param kwargs: Kwargs to apply to the command. Possible values: `client_factory`, `arguments_loader`, `description_loader`, `description`, `formatter_class`, `table_transformer`, `deprecate_info`, `validator`, `confirmation`. ### Response: def command(self, name, handler_name, **kwargs): """ Register a command into the command table :param name: The name of the command :type name: str :param handler_name: The name of the handler that will be applied to the operations template :type handler_name: str :param kwargs: Kwargs to apply to the command. Possible values: `client_factory`, `arguments_loader`, `description_loader`, `description`, `formatter_class`, `table_transformer`, `deprecate_info`, `validator`, `confirmation`. """ import copy command_name = '{} {}'.format(self.group_name, name) if self.group_name else name command_kwargs = copy.deepcopy(self.group_kwargs) command_kwargs.update(kwargs) # don't inherit deprecation info from command group command_kwargs['deprecate_info'] = kwargs.get('deprecate_info', None) self.command_loader._populate_command_group_table_with_subgroups(' '.join(command_name.split()[:-1])) # pylint: disable=protected-access self.command_loader.command_table[command_name] = self.command_loader.create_command( command_name, self.operations_tmpl.format(handler_name), **command_kwargs)
def setup_singlecolor(self): """ initial setup of single color options and variables""" self.singlecolorframe = tk.Frame(self.tab_configure, bg=self.single_color_theme) channel_choices = sorted(list(self.data.keys())) self.singlecolorlabel = tk.Label(self.singlecolorframe, text="single", bg=self.single_color_theme, width=10) self.singlecolorvar = tk.StringVar() self.singlecolorpower = tk.DoubleVar() self.singlecolormin = tk.DoubleVar() self.singlecolormax = tk.DoubleVar() self.singlecolordropdown = tk.OptionMenu(self.singlecolorframe, self.singlecolorvar, *channel_choices) self.singlecolorscale = tk.Scale(self.singlecolorframe, variable=self.singlecolorpower, orient=tk.HORIZONTAL, from_=self.config.ranges['single_color_power_min'], bg=self.single_color_theme, to_=self.config.ranges['single_color_power_max'], resolution=self.config.ranges['single_color_power_resolution'], length=200) self.singlecolorminscale = tk.Scale(self.singlecolorframe, variable=self.singlecolormin, orient=tk.HORIZONTAL, from_=0, bg=self.single_color_theme, to_=self.config.ranges['single_color_vmin'], resolution=self.config.ranges['single_color_vresolution'], length=200) self.singlecolormaxscale = tk.Scale(self.singlecolorframe, variable=self.singlecolormax, orient=tk.HORIZONTAL, from_=self.config.ranges['single_color_vmax'], bg=self.single_color_theme, to_=100, resolution=self.config.ranges['single_color_vresolution'], length=200) self.singlecolorvar.set(self.config.products_map[self.config.default['single']]) self.singlecolorpower.set(self.config.default['single_power']) self.singlecolormin.set(0) self.singlecolormax.set(100) self.singlecolordropdown.config(bg=self.single_color_theme, width=10) self.singlecolorlabel.pack(side=tk.LEFT) self.singlecolorscale.pack(side=tk.RIGHT) self.singlecolormaxscale.pack(side=tk.RIGHT) self.singlecolorminscale.pack(side=tk.RIGHT) self.singlecolordropdown.pack() self.singlecolorframe.grid(row=4, columnspan=5, rowspan=1)
initial setup of single color options and variables
Below is the the instruction that describes the task: ### Input: initial setup of single color options and variables ### Response: def setup_singlecolor(self): """ initial setup of single color options and variables""" self.singlecolorframe = tk.Frame(self.tab_configure, bg=self.single_color_theme) channel_choices = sorted(list(self.data.keys())) self.singlecolorlabel = tk.Label(self.singlecolorframe, text="single", bg=self.single_color_theme, width=10) self.singlecolorvar = tk.StringVar() self.singlecolorpower = tk.DoubleVar() self.singlecolormin = tk.DoubleVar() self.singlecolormax = tk.DoubleVar() self.singlecolordropdown = tk.OptionMenu(self.singlecolorframe, self.singlecolorvar, *channel_choices) self.singlecolorscale = tk.Scale(self.singlecolorframe, variable=self.singlecolorpower, orient=tk.HORIZONTAL, from_=self.config.ranges['single_color_power_min'], bg=self.single_color_theme, to_=self.config.ranges['single_color_power_max'], resolution=self.config.ranges['single_color_power_resolution'], length=200) self.singlecolorminscale = tk.Scale(self.singlecolorframe, variable=self.singlecolormin, orient=tk.HORIZONTAL, from_=0, bg=self.single_color_theme, to_=self.config.ranges['single_color_vmin'], resolution=self.config.ranges['single_color_vresolution'], length=200) self.singlecolormaxscale = tk.Scale(self.singlecolorframe, variable=self.singlecolormax, orient=tk.HORIZONTAL, from_=self.config.ranges['single_color_vmax'], bg=self.single_color_theme, to_=100, resolution=self.config.ranges['single_color_vresolution'], length=200) self.singlecolorvar.set(self.config.products_map[self.config.default['single']]) self.singlecolorpower.set(self.config.default['single_power']) self.singlecolormin.set(0) self.singlecolormax.set(100) self.singlecolordropdown.config(bg=self.single_color_theme, width=10) self.singlecolorlabel.pack(side=tk.LEFT) self.singlecolorscale.pack(side=tk.RIGHT) self.singlecolormaxscale.pack(side=tk.RIGHT) self.singlecolorminscale.pack(side=tk.RIGHT) self.singlecolordropdown.pack() self.singlecolorframe.grid(row=4, columnspan=5, rowspan=1)
def execute(self): """ self.params = { "ActionScriptType" : "None", "ExecutableEntityId" : "01pd0000001yXtYAAU", "IsDumpingHeap" : True, "Iteration" : 1, "Line" : 3, "ScopeId" : "005d0000000xxzsAAA" } """ config.logger.debug('logging self') config.logger.debug(self.params ) if 'project_name' in self.params: self.params.pop('project_name', None) if 'settings' in self.params: self.params.pop('settings', None) create_result = config.sfdc_client.create_apex_checkpoint(self.params) if type(create_result) is list: create_result = create_result[0] IndexApexOverlaysCommand(params=self.params).execute() if type(create_result) is not str and type(create_result) is not unicode: return json.dumps(create_result) else: return create_result
self.params = { "ActionScriptType" : "None", "ExecutableEntityId" : "01pd0000001yXtYAAU", "IsDumpingHeap" : True, "Iteration" : 1, "Line" : 3, "ScopeId" : "005d0000000xxzsAAA" }
Below is the the instruction that describes the task: ### Input: self.params = { "ActionScriptType" : "None", "ExecutableEntityId" : "01pd0000001yXtYAAU", "IsDumpingHeap" : True, "Iteration" : 1, "Line" : 3, "ScopeId" : "005d0000000xxzsAAA" } ### Response: def execute(self): """ self.params = { "ActionScriptType" : "None", "ExecutableEntityId" : "01pd0000001yXtYAAU", "IsDumpingHeap" : True, "Iteration" : 1, "Line" : 3, "ScopeId" : "005d0000000xxzsAAA" } """ config.logger.debug('logging self') config.logger.debug(self.params ) if 'project_name' in self.params: self.params.pop('project_name', None) if 'settings' in self.params: self.params.pop('settings', None) create_result = config.sfdc_client.create_apex_checkpoint(self.params) if type(create_result) is list: create_result = create_result[0] IndexApexOverlaysCommand(params=self.params).execute() if type(create_result) is not str and type(create_result) is not unicode: return json.dumps(create_result) else: return create_result
async def _poll(self): """Poll status of operation so long as operation is incomplete and we have an endpoint to query. :param callable update_cmd: The function to call to retrieve the latest status of the long running operation. :raises: OperationFailed if operation status 'Failed' or 'Cancelled'. :raises: BadStatus if response status invalid. :raises: BadResponse if response invalid. """ while not self.finished(): await self._delay() await self.update_status() if failed(self._operation.status): raise OperationFailed("Operation failed or cancelled") elif self._operation.should_do_final_get(): if self._operation.method == 'POST' and self._operation.location_url: final_get_url = self._operation.location_url else: final_get_url = self._operation.initial_response.request.url self._response = await self.request_status(final_get_url) self._operation.get_status_from_resource(self._response)
Poll status of operation so long as operation is incomplete and we have an endpoint to query. :param callable update_cmd: The function to call to retrieve the latest status of the long running operation. :raises: OperationFailed if operation status 'Failed' or 'Cancelled'. :raises: BadStatus if response status invalid. :raises: BadResponse if response invalid.
Below is the the instruction that describes the task: ### Input: Poll status of operation so long as operation is incomplete and we have an endpoint to query. :param callable update_cmd: The function to call to retrieve the latest status of the long running operation. :raises: OperationFailed if operation status 'Failed' or 'Cancelled'. :raises: BadStatus if response status invalid. :raises: BadResponse if response invalid. ### Response: async def _poll(self): """Poll status of operation so long as operation is incomplete and we have an endpoint to query. :param callable update_cmd: The function to call to retrieve the latest status of the long running operation. :raises: OperationFailed if operation status 'Failed' or 'Cancelled'. :raises: BadStatus if response status invalid. :raises: BadResponse if response invalid. """ while not self.finished(): await self._delay() await self.update_status() if failed(self._operation.status): raise OperationFailed("Operation failed or cancelled") elif self._operation.should_do_final_get(): if self._operation.method == 'POST' and self._operation.location_url: final_get_url = self._operation.location_url else: final_get_url = self._operation.initial_response.request.url self._response = await self.request_status(final_get_url) self._operation.get_status_from_resource(self._response)
def get_dump_names(self, names, dumps=None): """ Find and return all dump names required (by dependancies) for a given dump names list Beware, the returned name list does not respect order, you should only use it when walking throught the "original" dict builded by OrderedDict """ # Default value for dumps argument is an empty set (setting directly # as a python argument would result as a shared value between # instances) if dumps is None: dumps = set([]) # Add name to the dumps and find its dependancies for item in names: if item not in self: if not self.silent_key_error: raise KeyError("Dump name '{0}' is unknowed".format(item)) else: continue dumps.add(item) # Add dependancies names to the dumps deps = self.__getitem__(item).get('dependancies', []) dumps.update(deps) # Avoid maximum recursion when we allready find all dependancies if names == dumps: return dumps # Seems we don't have finded other dependancies yet, recurse to do it return self.get_dump_names(dumps.copy(), dumps)
Find and return all dump names required (by dependancies) for a given dump names list Beware, the returned name list does not respect order, you should only use it when walking throught the "original" dict builded by OrderedDict
Below is the the instruction that describes the task: ### Input: Find and return all dump names required (by dependancies) for a given dump names list Beware, the returned name list does not respect order, you should only use it when walking throught the "original" dict builded by OrderedDict ### Response: def get_dump_names(self, names, dumps=None): """ Find and return all dump names required (by dependancies) for a given dump names list Beware, the returned name list does not respect order, you should only use it when walking throught the "original" dict builded by OrderedDict """ # Default value for dumps argument is an empty set (setting directly # as a python argument would result as a shared value between # instances) if dumps is None: dumps = set([]) # Add name to the dumps and find its dependancies for item in names: if item not in self: if not self.silent_key_error: raise KeyError("Dump name '{0}' is unknowed".format(item)) else: continue dumps.add(item) # Add dependancies names to the dumps deps = self.__getitem__(item).get('dependancies', []) dumps.update(deps) # Avoid maximum recursion when we allready find all dependancies if names == dumps: return dumps # Seems we don't have finded other dependancies yet, recurse to do it return self.get_dump_names(dumps.copy(), dumps)
def focus(self, height, width, center_i=None, center_j=None): """Zero out all of the image outside of a crop box. Parameters ---------- height : int The height of the desired crop box. width : int The width of the desired crop box. center_i : int The center height point of the crop box. If not specified, the center of the image is used. center_j : int The center width point of the crop box. If not specified, the center of the image is used. Returns ------- :obj:`Image` A new Image of the same type and size that is zeroed out except within the crop box. """ if center_i is None: center_i = self.height / 2 if center_j is None: center_j = self.width / 2 start_row = int(max(0, center_i - height / 2)) end_row = int(min(self.height - 1, center_i + height / 2)) start_col = int(max(0, center_j - width / 2)) end_col = int(min(self.width - 1, center_j + width / 2)) focus_data = np.zeros(self._data.shape) focus_data[start_row:end_row + 1, start_col:end_col + \ 1] = self._data[start_row:end_row + 1, start_col:end_col + 1] return type(self)(focus_data.astype(self._data.dtype), self._frame)
Zero out all of the image outside of a crop box. Parameters ---------- height : int The height of the desired crop box. width : int The width of the desired crop box. center_i : int The center height point of the crop box. If not specified, the center of the image is used. center_j : int The center width point of the crop box. If not specified, the center of the image is used. Returns ------- :obj:`Image` A new Image of the same type and size that is zeroed out except within the crop box.
Below is the the instruction that describes the task: ### Input: Zero out all of the image outside of a crop box. Parameters ---------- height : int The height of the desired crop box. width : int The width of the desired crop box. center_i : int The center height point of the crop box. If not specified, the center of the image is used. center_j : int The center width point of the crop box. If not specified, the center of the image is used. Returns ------- :obj:`Image` A new Image of the same type and size that is zeroed out except within the crop box. ### Response: def focus(self, height, width, center_i=None, center_j=None): """Zero out all of the image outside of a crop box. Parameters ---------- height : int The height of the desired crop box. width : int The width of the desired crop box. center_i : int The center height point of the crop box. If not specified, the center of the image is used. center_j : int The center width point of the crop box. If not specified, the center of the image is used. Returns ------- :obj:`Image` A new Image of the same type and size that is zeroed out except within the crop box. """ if center_i is None: center_i = self.height / 2 if center_j is None: center_j = self.width / 2 start_row = int(max(0, center_i - height / 2)) end_row = int(min(self.height - 1, center_i + height / 2)) start_col = int(max(0, center_j - width / 2)) end_col = int(min(self.width - 1, center_j + width / 2)) focus_data = np.zeros(self._data.shape) focus_data[start_row:end_row + 1, start_col:end_col + \ 1] = self._data[start_row:end_row + 1, start_col:end_col + 1] return type(self)(focus_data.astype(self._data.dtype), self._frame)
def pow(x, y, context=None): """ Return ``x`` raised to the power ``y``. Special values are handled as described in the ISO C99 and IEEE 754-2008 standards for the pow function. * pow(±0, y) returns plus or minus infinity for y a negative odd integer. * pow(±0, y) returns plus infinity for y negative and not an odd integer. * pow(±0, y) returns plus or minus zero for y a positive odd integer. * pow(±0, y) returns plus zero for y positive and not an odd integer. * pow(-1, ±Inf) returns 1. * pow(+1, y) returns 1 for any y, even a NaN. * pow(x, ±0) returns 1 for any x, even a NaN. * pow(x, y) returns NaN for finite negative x and finite non-integer y. * pow(x, -Inf) returns plus infinity for 0 < abs(x) < 1, and plus zero for abs(x) > 1. * pow(x, +Inf) returns plus zero for 0 < abs(x) < 1, and plus infinity for abs(x) > 1. * pow(-Inf, y) returns minus zero for y a negative odd integer. * pow(-Inf, y) returns plus zero for y negative and not an odd integer. * pow(-Inf, y) returns minus infinity for y a positive odd integer. * pow(-Inf, y) returns plus infinity for y positive and not an odd integer. * pow(+Inf, y) returns plus zero for y negative, and plus infinity for y positive. """ return _apply_function_in_current_context( BigFloat, mpfr.mpfr_pow, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), context, )
Return ``x`` raised to the power ``y``. Special values are handled as described in the ISO C99 and IEEE 754-2008 standards for the pow function. * pow(±0, y) returns plus or minus infinity for y a negative odd integer. * pow(±0, y) returns plus infinity for y negative and not an odd integer. * pow(±0, y) returns plus or minus zero for y a positive odd integer. * pow(±0, y) returns plus zero for y positive and not an odd integer. * pow(-1, ±Inf) returns 1. * pow(+1, y) returns 1 for any y, even a NaN. * pow(x, ±0) returns 1 for any x, even a NaN. * pow(x, y) returns NaN for finite negative x and finite non-integer y. * pow(x, -Inf) returns plus infinity for 0 < abs(x) < 1, and plus zero for abs(x) > 1. * pow(x, +Inf) returns plus zero for 0 < abs(x) < 1, and plus infinity for abs(x) > 1. * pow(-Inf, y) returns minus zero for y a negative odd integer. * pow(-Inf, y) returns plus zero for y negative and not an odd integer. * pow(-Inf, y) returns minus infinity for y a positive odd integer. * pow(-Inf, y) returns plus infinity for y positive and not an odd integer. * pow(+Inf, y) returns plus zero for y negative, and plus infinity for y positive.
Below is the the instruction that describes the task: ### Input: Return ``x`` raised to the power ``y``. Special values are handled as described in the ISO C99 and IEEE 754-2008 standards for the pow function. * pow(±0, y) returns plus or minus infinity for y a negative odd integer. * pow(±0, y) returns plus infinity for y negative and not an odd integer. * pow(±0, y) returns plus or minus zero for y a positive odd integer. * pow(±0, y) returns plus zero for y positive and not an odd integer. * pow(-1, ±Inf) returns 1. * pow(+1, y) returns 1 for any y, even a NaN. * pow(x, ±0) returns 1 for any x, even a NaN. * pow(x, y) returns NaN for finite negative x and finite non-integer y. * pow(x, -Inf) returns plus infinity for 0 < abs(x) < 1, and plus zero for abs(x) > 1. * pow(x, +Inf) returns plus zero for 0 < abs(x) < 1, and plus infinity for abs(x) > 1. * pow(-Inf, y) returns minus zero for y a negative odd integer. * pow(-Inf, y) returns plus zero for y negative and not an odd integer. * pow(-Inf, y) returns minus infinity for y a positive odd integer. * pow(-Inf, y) returns plus infinity for y positive and not an odd integer. * pow(+Inf, y) returns plus zero for y negative, and plus infinity for y positive. ### Response: def pow(x, y, context=None): """ Return ``x`` raised to the power ``y``. Special values are handled as described in the ISO C99 and IEEE 754-2008 standards for the pow function. * pow(±0, y) returns plus or minus infinity for y a negative odd integer. * pow(±0, y) returns plus infinity for y negative and not an odd integer. * pow(±0, y) returns plus or minus zero for y a positive odd integer. * pow(±0, y) returns plus zero for y positive and not an odd integer. * pow(-1, ±Inf) returns 1. * pow(+1, y) returns 1 for any y, even a NaN. * pow(x, ±0) returns 1 for any x, even a NaN. * pow(x, y) returns NaN for finite negative x and finite non-integer y. * pow(x, -Inf) returns plus infinity for 0 < abs(x) < 1, and plus zero for abs(x) > 1. * pow(x, +Inf) returns plus zero for 0 < abs(x) < 1, and plus infinity for abs(x) > 1. * pow(-Inf, y) returns minus zero for y a negative odd integer. * pow(-Inf, y) returns plus zero for y negative and not an odd integer. * pow(-Inf, y) returns minus infinity for y a positive odd integer. * pow(-Inf, y) returns plus infinity for y positive and not an odd integer. * pow(+Inf, y) returns plus zero for y negative, and plus infinity for y positive. """ return _apply_function_in_current_context( BigFloat, mpfr.mpfr_pow, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), context, )
def configure(self, **_options): ''' Sets language-specific configuration. Raises TTSError on error. ''' language, voice, voiceinfo, options = self._configure(**_options) self.languages_options[language] = (voice, options)
Sets language-specific configuration. Raises TTSError on error.
Below is the the instruction that describes the task: ### Input: Sets language-specific configuration. Raises TTSError on error. ### Response: def configure(self, **_options): ''' Sets language-specific configuration. Raises TTSError on error. ''' language, voice, voiceinfo, options = self._configure(**_options) self.languages_options[language] = (voice, options)
def _unpack_episode_title(element: ET.Element): """Unpack EpisodeTitle from title XML element.""" return EpisodeTitle(title=element.text, lang=element.get(f'{XML}lang'))
Unpack EpisodeTitle from title XML element.
Below is the the instruction that describes the task: ### Input: Unpack EpisodeTitle from title XML element. ### Response: def _unpack_episode_title(element: ET.Element): """Unpack EpisodeTitle from title XML element.""" return EpisodeTitle(title=element.text, lang=element.get(f'{XML}lang'))
def roots(self): """ Utilises Boyd's O(n^2) recursive subdivision algorithm. The chebfun is recursively subsampled until it is successfully represented to machine precision by a sequence of piecewise interpolants of degree 100 or less. A colleague matrix eigenvalue solve is then applied to each of these pieces and the results are concatenated. See: J. P. Boyd, Computing zeros on a real interval through Chebyshev expansion and polynomial rootfinding, SIAM J. Numer. Anal., 40 (2002), pp. 1666–1682. """ if self.size() == 1: return np.array([]) elif self.size() <= 100: ak = self.coefficients() v = np.zeros_like(ak[:-1]) v[1] = 0.5 C1 = linalg.toeplitz(v) C2 = np.zeros_like(C1) C1[0,1] = 1. C2[-1,:] = ak[:-1] C = C1 - .5/ak[-1] * C2 eigenvalues = linalg.eigvals(C) roots = [eig.real for eig in eigenvalues if np.allclose(eig.imag,0,atol=1e-10) and np.abs(eig.real) <=1] scaled_roots = self._ui_to_ab(np.array(roots)) return scaled_roots else: # divide at a close-to-zero split-point split_point = self._ui_to_ab(0.0123456789) return np.concatenate( (self.restrict([self._domain[0],split_point]).roots(), self.restrict([split_point,self._domain[1]]).roots()) )
Utilises Boyd's O(n^2) recursive subdivision algorithm. The chebfun is recursively subsampled until it is successfully represented to machine precision by a sequence of piecewise interpolants of degree 100 or less. A colleague matrix eigenvalue solve is then applied to each of these pieces and the results are concatenated. See: J. P. Boyd, Computing zeros on a real interval through Chebyshev expansion and polynomial rootfinding, SIAM J. Numer. Anal., 40 (2002), pp. 1666–1682.
Below is the the instruction that describes the task: ### Input: Utilises Boyd's O(n^2) recursive subdivision algorithm. The chebfun is recursively subsampled until it is successfully represented to machine precision by a sequence of piecewise interpolants of degree 100 or less. A colleague matrix eigenvalue solve is then applied to each of these pieces and the results are concatenated. See: J. P. Boyd, Computing zeros on a real interval through Chebyshev expansion and polynomial rootfinding, SIAM J. Numer. Anal., 40 (2002), pp. 1666–1682. ### Response: def roots(self): """ Utilises Boyd's O(n^2) recursive subdivision algorithm. The chebfun is recursively subsampled until it is successfully represented to machine precision by a sequence of piecewise interpolants of degree 100 or less. A colleague matrix eigenvalue solve is then applied to each of these pieces and the results are concatenated. See: J. P. Boyd, Computing zeros on a real interval through Chebyshev expansion and polynomial rootfinding, SIAM J. Numer. Anal., 40 (2002), pp. 1666–1682. """ if self.size() == 1: return np.array([]) elif self.size() <= 100: ak = self.coefficients() v = np.zeros_like(ak[:-1]) v[1] = 0.5 C1 = linalg.toeplitz(v) C2 = np.zeros_like(C1) C1[0,1] = 1. C2[-1,:] = ak[:-1] C = C1 - .5/ak[-1] * C2 eigenvalues = linalg.eigvals(C) roots = [eig.real for eig in eigenvalues if np.allclose(eig.imag,0,atol=1e-10) and np.abs(eig.real) <=1] scaled_roots = self._ui_to_ab(np.array(roots)) return scaled_roots else: # divide at a close-to-zero split-point split_point = self._ui_to_ab(0.0123456789) return np.concatenate( (self.restrict([self._domain[0],split_point]).roots(), self.restrict([split_point,self._domain[1]]).roots()) )
def get_files_changed(repository, review_id): """ Get a list of files changed compared to the given review. Compares against current directory. :param repository: Git repository. Used to get remote. - By default uses first remote in list. :param review_id: Gerrit review ID. :return: List of file paths relative to current directory. """ repository.git.fetch([next(iter(repository.remotes)), review_id]) files_changed = repository.git.diff_tree(["--no-commit-id", "--name-only", "-r", "FETCH_HEAD"]).splitlines() print("Found {} files changed".format(len(files_changed))) return files_changed
Get a list of files changed compared to the given review. Compares against current directory. :param repository: Git repository. Used to get remote. - By default uses first remote in list. :param review_id: Gerrit review ID. :return: List of file paths relative to current directory.
Below is the the instruction that describes the task: ### Input: Get a list of files changed compared to the given review. Compares against current directory. :param repository: Git repository. Used to get remote. - By default uses first remote in list. :param review_id: Gerrit review ID. :return: List of file paths relative to current directory. ### Response: def get_files_changed(repository, review_id): """ Get a list of files changed compared to the given review. Compares against current directory. :param repository: Git repository. Used to get remote. - By default uses first remote in list. :param review_id: Gerrit review ID. :return: List of file paths relative to current directory. """ repository.git.fetch([next(iter(repository.remotes)), review_id]) files_changed = repository.git.diff_tree(["--no-commit-id", "--name-only", "-r", "FETCH_HEAD"]).splitlines() print("Found {} files changed".format(len(files_changed))) return files_changed
def add_template(self, template_short_id, keyword_id_list): """ 组合模板,并将其添加至账号下的模板列表里 详情请参考 https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&id=open1500465446_j4CgR :param template_short_id: 模板标题ID :param keyword_id_list: 按照顺序排列的模板关键词列表,最多10个 :type keyword_id_list: list[int] :return: 模板ID """ return self._post( 'cgi-bin/wxopen/template/add', data={ 'id': template_short_id, 'keyword_id_list': keyword_id_list, }, result_processor=lambda x: x['template_id'], )
组合模板,并将其添加至账号下的模板列表里 详情请参考 https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&id=open1500465446_j4CgR :param template_short_id: 模板标题ID :param keyword_id_list: 按照顺序排列的模板关键词列表,最多10个 :type keyword_id_list: list[int] :return: 模板ID
Below is the the instruction that describes the task: ### Input: 组合模板,并将其添加至账号下的模板列表里 详情请参考 https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&id=open1500465446_j4CgR :param template_short_id: 模板标题ID :param keyword_id_list: 按照顺序排列的模板关键词列表,最多10个 :type keyword_id_list: list[int] :return: 模板ID ### Response: def add_template(self, template_short_id, keyword_id_list): """ 组合模板,并将其添加至账号下的模板列表里 详情请参考 https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&id=open1500465446_j4CgR :param template_short_id: 模板标题ID :param keyword_id_list: 按照顺序排列的模板关键词列表,最多10个 :type keyword_id_list: list[int] :return: 模板ID """ return self._post( 'cgi-bin/wxopen/template/add', data={ 'id': template_short_id, 'keyword_id_list': keyword_id_list, }, result_processor=lambda x: x['template_id'], )
def round(self, value_array): """ Rounds a discrete variable by selecting the closest point in the domain Assumes an 1d array with a single element as an input. """ value = value_array[0] rounded_value = self.domain[0] for domain_value in self.domain: if np.abs(domain_value - value) < np.abs(rounded_value - value): rounded_value = domain_value return [rounded_value]
Rounds a discrete variable by selecting the closest point in the domain Assumes an 1d array with a single element as an input.
Below is the the instruction that describes the task: ### Input: Rounds a discrete variable by selecting the closest point in the domain Assumes an 1d array with a single element as an input. ### Response: def round(self, value_array): """ Rounds a discrete variable by selecting the closest point in the domain Assumes an 1d array with a single element as an input. """ value = value_array[0] rounded_value = self.domain[0] for domain_value in self.domain: if np.abs(domain_value - value) < np.abs(rounded_value - value): rounded_value = domain_value return [rounded_value]
def _extract_links(self, selector, response_url, response_encoding, base_url): ''' Pretty much the same function, just added 'ignore' to to_native_str() ''' links = [] # hacky way to get the underlying lxml parsed document for el, attr, attr_val in self._iter_links(selector.root): # pseudo lxml.html.HtmlElement.make_links_absolute(base_url) try: attr_val = urljoin(base_url, attr_val) except ValueError: continue # skipping bogus links else: url = self.process_attr(attr_val) if url is None: continue # added 'ignore' to encoding errors url = to_native_str(url, encoding=response_encoding, errors='ignore') # to fix relative links after process_value url = urljoin(response_url, url) link = Link(url, _collect_string_content(el) or u'', nofollow=rel_has_nofollow(el.get('rel'))) links.append(link) return self._deduplicate_if_needed(links)
Pretty much the same function, just added 'ignore' to to_native_str()
Below is the the instruction that describes the task: ### Input: Pretty much the same function, just added 'ignore' to to_native_str() ### Response: def _extract_links(self, selector, response_url, response_encoding, base_url): ''' Pretty much the same function, just added 'ignore' to to_native_str() ''' links = [] # hacky way to get the underlying lxml parsed document for el, attr, attr_val in self._iter_links(selector.root): # pseudo lxml.html.HtmlElement.make_links_absolute(base_url) try: attr_val = urljoin(base_url, attr_val) except ValueError: continue # skipping bogus links else: url = self.process_attr(attr_val) if url is None: continue # added 'ignore' to encoding errors url = to_native_str(url, encoding=response_encoding, errors='ignore') # to fix relative links after process_value url = urljoin(response_url, url) link = Link(url, _collect_string_content(el) or u'', nofollow=rel_has_nofollow(el.get('rel'))) links.append(link) return self._deduplicate_if_needed(links)
def copy(self): """Create a copy. Examples: This example copies constraint :math:`a \\ne b` and tests a solution on the copied constraint. >>> import dwavebinarycsp >>> import operator >>> const = dwavebinarycsp.Constraint.from_func(operator.ne, ... ['a', 'b'], 'BINARY') >>> const2 = const.copy() >>> const2 is const False >>> const2.check({'a': 1, 'b': 1}) False """ # each object is itself immutable (except the function) return self.__class__(self.func, self.configurations, self.variables, self.vartype, name=self.name)
Create a copy. Examples: This example copies constraint :math:`a \\ne b` and tests a solution on the copied constraint. >>> import dwavebinarycsp >>> import operator >>> const = dwavebinarycsp.Constraint.from_func(operator.ne, ... ['a', 'b'], 'BINARY') >>> const2 = const.copy() >>> const2 is const False >>> const2.check({'a': 1, 'b': 1}) False
Below is the the instruction that describes the task: ### Input: Create a copy. Examples: This example copies constraint :math:`a \\ne b` and tests a solution on the copied constraint. >>> import dwavebinarycsp >>> import operator >>> const = dwavebinarycsp.Constraint.from_func(operator.ne, ... ['a', 'b'], 'BINARY') >>> const2 = const.copy() >>> const2 is const False >>> const2.check({'a': 1, 'b': 1}) False ### Response: def copy(self): """Create a copy. Examples: This example copies constraint :math:`a \\ne b` and tests a solution on the copied constraint. >>> import dwavebinarycsp >>> import operator >>> const = dwavebinarycsp.Constraint.from_func(operator.ne, ... ['a', 'b'], 'BINARY') >>> const2 = const.copy() >>> const2 is const False >>> const2.check({'a': 1, 'b': 1}) False """ # each object is itself immutable (except the function) return self.__class__(self.func, self.configurations, self.variables, self.vartype, name=self.name)
def _instant_search(self): """Determine possible keys after a push or pop """ _keys = [] for k,v in self.searchables.iteritems(): if self.string in v: _keys.append(k) self.candidates.append(_keys)
Determine possible keys after a push or pop
Below is the the instruction that describes the task: ### Input: Determine possible keys after a push or pop ### Response: def _instant_search(self): """Determine possible keys after a push or pop """ _keys = [] for k,v in self.searchables.iteritems(): if self.string in v: _keys.append(k) self.candidates.append(_keys)
def _osx_memdata(): ''' Return the memory information for BSD-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} sysctl = salt.utils.path.which('sysctl') if sysctl: mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl)) swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.') if swap_total.endswith('K'): _power = 2**10 elif swap_total.endswith('M'): _power = 2**20 elif swap_total.endswith('G'): _power = 2**30 swap_total = float(swap_total[:-1]) * _power grains['mem_total'] = int(mem) // 1024 // 1024 grains['swap_total'] = int(swap_total) // 1024 // 1024 return grains
Return the memory information for BSD-like systems
Below is the the instruction that describes the task: ### Input: Return the memory information for BSD-like systems ### Response: def _osx_memdata(): ''' Return the memory information for BSD-like systems ''' grains = {'mem_total': 0, 'swap_total': 0} sysctl = salt.utils.path.which('sysctl') if sysctl: mem = __salt__['cmd.run']('{0} -n hw.memsize'.format(sysctl)) swap_total = __salt__['cmd.run']('{0} -n vm.swapusage'.format(sysctl)).split()[2].replace(',', '.') if swap_total.endswith('K'): _power = 2**10 elif swap_total.endswith('M'): _power = 2**20 elif swap_total.endswith('G'): _power = 2**30 swap_total = float(swap_total[:-1]) * _power grains['mem_total'] = int(mem) // 1024 // 1024 grains['swap_total'] = int(swap_total) // 1024 // 1024 return grains
def get_random_telephonenumber(): """Get a random 10 digit phone number that complies with most of the requirements. Returns: str: The random telephone number. """ phone = [ RandomInputHelper.get_random_value(3, "123456789"), RandomInputHelper.get_random_value(3, "12345678"), "".join(map(str, random.sample(range(10), 4))) ] return "-".join(phone)
Get a random 10 digit phone number that complies with most of the requirements. Returns: str: The random telephone number.
Below is the the instruction that describes the task: ### Input: Get a random 10 digit phone number that complies with most of the requirements. Returns: str: The random telephone number. ### Response: def get_random_telephonenumber(): """Get a random 10 digit phone number that complies with most of the requirements. Returns: str: The random telephone number. """ phone = [ RandomInputHelper.get_random_value(3, "123456789"), RandomInputHelper.get_random_value(3, "12345678"), "".join(map(str, random.sample(range(10), 4))) ] return "-".join(phone)
def for_user(cls, user): """ Returns an authorization token for the given user that will be provided after authenticating the user's credentials. """ user_id = getattr(user, api_settings.USER_ID_FIELD) if not isinstance(user_id, int): user_id = str(user_id) token = cls() token[api_settings.USER_ID_CLAIM] = user_id return token
Returns an authorization token for the given user that will be provided after authenticating the user's credentials.
Below is the the instruction that describes the task: ### Input: Returns an authorization token for the given user that will be provided after authenticating the user's credentials. ### Response: def for_user(cls, user): """ Returns an authorization token for the given user that will be provided after authenticating the user's credentials. """ user_id = getattr(user, api_settings.USER_ID_FIELD) if not isinstance(user_id, int): user_id = str(user_id) token = cls() token[api_settings.USER_ID_CLAIM] = user_id return token
def load_b26_file(file_name): """ loads a .b26 file into a dictionary Args: file_name: Returns: dictionary with keys instrument, scripts, probes """ # file_name = "Z:\Lab\Cantilever\Measurements\\tmp_\\a" assert os.path.exists(file_name) with open(file_name, 'r') as infile: data = yaml.safe_load(infile) return data
loads a .b26 file into a dictionary Args: file_name: Returns: dictionary with keys instrument, scripts, probes
Below is the the instruction that describes the task: ### Input: loads a .b26 file into a dictionary Args: file_name: Returns: dictionary with keys instrument, scripts, probes ### Response: def load_b26_file(file_name): """ loads a .b26 file into a dictionary Args: file_name: Returns: dictionary with keys instrument, scripts, probes """ # file_name = "Z:\Lab\Cantilever\Measurements\\tmp_\\a" assert os.path.exists(file_name) with open(file_name, 'r') as infile: data = yaml.safe_load(infile) return data
def poly_energies(samples_like, poly): """Calculates energy of samples from a higher order polynomial. Args: sample (samples_like): A collection of raw samples. `samples_like` is an extension of NumPy's array_like structure. See :func:`.as_samples`. poly (dict): Polynomial as a dict of form {term: bias, ...}, where `term` is a tuple of variables and `bias` the associated bias. Variable labeling/indexing of terms in poly dict must match that of the sample(s). Returns: list/:obj:`numpy.ndarray`: The energy of the sample(s). """ msg = ("poly_energies is deprecated and will be removed in dimod 0.9.0." "In the future, use BinaryPolynomial.energies") warnings.warn(msg, DeprecationWarning) # dev note the vartype is not used in the energy calculation and this will # be deprecated in the future return BinaryPolynomial(poly, 'SPIN').energies(samples_like)
Calculates energy of samples from a higher order polynomial. Args: sample (samples_like): A collection of raw samples. `samples_like` is an extension of NumPy's array_like structure. See :func:`.as_samples`. poly (dict): Polynomial as a dict of form {term: bias, ...}, where `term` is a tuple of variables and `bias` the associated bias. Variable labeling/indexing of terms in poly dict must match that of the sample(s). Returns: list/:obj:`numpy.ndarray`: The energy of the sample(s).
Below is the the instruction that describes the task: ### Input: Calculates energy of samples from a higher order polynomial. Args: sample (samples_like): A collection of raw samples. `samples_like` is an extension of NumPy's array_like structure. See :func:`.as_samples`. poly (dict): Polynomial as a dict of form {term: bias, ...}, where `term` is a tuple of variables and `bias` the associated bias. Variable labeling/indexing of terms in poly dict must match that of the sample(s). Returns: list/:obj:`numpy.ndarray`: The energy of the sample(s). ### Response: def poly_energies(samples_like, poly): """Calculates energy of samples from a higher order polynomial. Args: sample (samples_like): A collection of raw samples. `samples_like` is an extension of NumPy's array_like structure. See :func:`.as_samples`. poly (dict): Polynomial as a dict of form {term: bias, ...}, where `term` is a tuple of variables and `bias` the associated bias. Variable labeling/indexing of terms in poly dict must match that of the sample(s). Returns: list/:obj:`numpy.ndarray`: The energy of the sample(s). """ msg = ("poly_energies is deprecated and will be removed in dimod 0.9.0." "In the future, use BinaryPolynomial.energies") warnings.warn(msg, DeprecationWarning) # dev note the vartype is not used in the energy calculation and this will # be deprecated in the future return BinaryPolynomial(poly, 'SPIN').energies(samples_like)
def is_mirrable(d): ''' d = {1:'a',2:'a',3:'b'} ''' vl = list(d.values()) lngth1 = vl.__len__() uvl = elel.uniqualize(vl) lngth2 = uvl.__len__() cond = (lngth1 == lngth2) return(cond)
d = {1:'a',2:'a',3:'b'}
Below is the the instruction that describes the task: ### Input: d = {1:'a',2:'a',3:'b'} ### Response: def is_mirrable(d): ''' d = {1:'a',2:'a',3:'b'} ''' vl = list(d.values()) lngth1 = vl.__len__() uvl = elel.uniqualize(vl) lngth2 = uvl.__len__() cond = (lngth1 == lngth2) return(cond)
def validate_usage(self, key_usage, extended_key_usage=None, extended_optional=False): """ Validates the certificate path and that the certificate is valid for the key usage and extended key usage purposes specified. :param key_usage: A set of unicode strings of the required key usage purposes. Valid values include: - "digital_signature" - "non_repudiation" - "key_encipherment" - "data_encipherment" - "key_agreement" - "key_cert_sign" - "crl_sign" - "encipher_only" - "decipher_only" :param extended_key_usage: A set of unicode strings of the required extended key usage purposes. These must be either dotted number OIDs, or one of the following extended key usage purposes: - "server_auth" - "client_auth" - "code_signing" - "email_protection" - "ipsec_end_system" - "ipsec_tunnel" - "ipsec_user" - "time_stamping" - "ocsp_signing" - "wireless_access_points" An example of a dotted number OID: - "1.3.6.1.5.5.7.3.1" :param extended_optional: A bool - if the extended_key_usage extension may be ommited and still considered valid :raises: certvalidator.errors.PathValidationError - when an error occurs validating the path certvalidator.errors.RevokedError - when the certificate or another certificate in its path has been revoked certvalidator.errors.InvalidCertificateError - when the certificate is not valid for the usages specified :return: A certvalidator.path.ValidationPath object of the validated certificate validation path """ self._validate_path() validate_usage( self._context, self._certificate, key_usage, extended_key_usage, extended_optional ) return self._path
Validates the certificate path and that the certificate is valid for the key usage and extended key usage purposes specified. :param key_usage: A set of unicode strings of the required key usage purposes. Valid values include: - "digital_signature" - "non_repudiation" - "key_encipherment" - "data_encipherment" - "key_agreement" - "key_cert_sign" - "crl_sign" - "encipher_only" - "decipher_only" :param extended_key_usage: A set of unicode strings of the required extended key usage purposes. These must be either dotted number OIDs, or one of the following extended key usage purposes: - "server_auth" - "client_auth" - "code_signing" - "email_protection" - "ipsec_end_system" - "ipsec_tunnel" - "ipsec_user" - "time_stamping" - "ocsp_signing" - "wireless_access_points" An example of a dotted number OID: - "1.3.6.1.5.5.7.3.1" :param extended_optional: A bool - if the extended_key_usage extension may be ommited and still considered valid :raises: certvalidator.errors.PathValidationError - when an error occurs validating the path certvalidator.errors.RevokedError - when the certificate or another certificate in its path has been revoked certvalidator.errors.InvalidCertificateError - when the certificate is not valid for the usages specified :return: A certvalidator.path.ValidationPath object of the validated certificate validation path
Below is the the instruction that describes the task: ### Input: Validates the certificate path and that the certificate is valid for the key usage and extended key usage purposes specified. :param key_usage: A set of unicode strings of the required key usage purposes. Valid values include: - "digital_signature" - "non_repudiation" - "key_encipherment" - "data_encipherment" - "key_agreement" - "key_cert_sign" - "crl_sign" - "encipher_only" - "decipher_only" :param extended_key_usage: A set of unicode strings of the required extended key usage purposes. These must be either dotted number OIDs, or one of the following extended key usage purposes: - "server_auth" - "client_auth" - "code_signing" - "email_protection" - "ipsec_end_system" - "ipsec_tunnel" - "ipsec_user" - "time_stamping" - "ocsp_signing" - "wireless_access_points" An example of a dotted number OID: - "1.3.6.1.5.5.7.3.1" :param extended_optional: A bool - if the extended_key_usage extension may be ommited and still considered valid :raises: certvalidator.errors.PathValidationError - when an error occurs validating the path certvalidator.errors.RevokedError - when the certificate or another certificate in its path has been revoked certvalidator.errors.InvalidCertificateError - when the certificate is not valid for the usages specified :return: A certvalidator.path.ValidationPath object of the validated certificate validation path ### Response: def validate_usage(self, key_usage, extended_key_usage=None, extended_optional=False): """ Validates the certificate path and that the certificate is valid for the key usage and extended key usage purposes specified. :param key_usage: A set of unicode strings of the required key usage purposes. Valid values include: - "digital_signature" - "non_repudiation" - "key_encipherment" - "data_encipherment" - "key_agreement" - "key_cert_sign" - "crl_sign" - "encipher_only" - "decipher_only" :param extended_key_usage: A set of unicode strings of the required extended key usage purposes. These must be either dotted number OIDs, or one of the following extended key usage purposes: - "server_auth" - "client_auth" - "code_signing" - "email_protection" - "ipsec_end_system" - "ipsec_tunnel" - "ipsec_user" - "time_stamping" - "ocsp_signing" - "wireless_access_points" An example of a dotted number OID: - "1.3.6.1.5.5.7.3.1" :param extended_optional: A bool - if the extended_key_usage extension may be ommited and still considered valid :raises: certvalidator.errors.PathValidationError - when an error occurs validating the path certvalidator.errors.RevokedError - when the certificate or another certificate in its path has been revoked certvalidator.errors.InvalidCertificateError - when the certificate is not valid for the usages specified :return: A certvalidator.path.ValidationPath object of the validated certificate validation path """ self._validate_path() validate_usage( self._context, self._certificate, key_usage, extended_key_usage, extended_optional ) return self._path
def write_xml(xml, output_file=None): """Outputs the XML content into a file.""" gen_filename = "requirements-{:%Y%m%d%H%M%S}.xml".format(datetime.datetime.now()) utils.write_xml(xml, output_loc=output_file, filename=gen_filename)
Outputs the XML content into a file.
Below is the the instruction that describes the task: ### Input: Outputs the XML content into a file. ### Response: def write_xml(xml, output_file=None): """Outputs the XML content into a file.""" gen_filename = "requirements-{:%Y%m%d%H%M%S}.xml".format(datetime.datetime.now()) utils.write_xml(xml, output_loc=output_file, filename=gen_filename)
def get_article_by_search(text): """从搜索文章获得的文本 提取章列表信息 Parameters ---------- text : str or unicode 搜索文章获得的文本 Returns ------- list[dict] { 'article': { 'title': '', # 文章标题 'url': '', # 文章链接 'imgs': '', # 文章图片list 'abstract': '', # 文章摘要 'time': '' # 文章推送时间 }, 'gzh': { 'profile_url': '', # 公众号最近10条群发页链接 'headimage': '', # 头像 'wechat_name': '', # 名称 'isv': '', # 是否加v } } """ page = etree.HTML(text) lis = page.xpath('//ul[@class="news-list"]/li') articles = [] for li in lis: url = get_first_of_element(li, 'div[1]/a/@href') if url: title = get_first_of_element(li, 'div[2]/h3/a') imgs = li.xpath('div[1]/a/img/@src') abstract = get_first_of_element(li, 'div[2]/p') time = get_first_of_element(li, 'div[2]/div/span/script/text()') gzh_info = li.xpath('div[2]/div/a')[0] else: url = get_first_of_element(li, 'div/h3/a/@href') title = get_first_of_element(li, 'div/h3/a') imgs = [] spans = li.xpath('div/div[1]/a') for span in spans: img = span.xpath('span/img/@src') if img: imgs.append(img) abstract = get_first_of_element(li, 'div/p') time = get_first_of_element(li, 'div/div[2]/span/script/text()') gzh_info = li.xpath('div/div[2]/a')[0] if title is not None: title = get_elem_text(title).replace("red_beg", "").replace("red_end", "") if abstract is not None: abstract = get_elem_text(abstract).replace("red_beg", "").replace("red_end", "") time = re.findall('timeConvert\(\'(.*?)\'\)', time) time = list_or_empty(time, int) profile_url = get_first_of_element(gzh_info, '@href') headimage = get_first_of_element(gzh_info, '@data-headimage') wechat_name = get_first_of_element(gzh_info, 'text()') gzh_isv = get_first_of_element(gzh_info, '@data-isv', int) articles.append({ 'article': { 'title': title, 'url': url, 'imgs': format_image_url(imgs), 'abstract': abstract, 'time': time }, 'gzh': { 'profile_url': profile_url, 'headimage': headimage, 'wechat_name': wechat_name, 'isv': gzh_isv, } }) return articles
从搜索文章获得的文本 提取章列表信息 Parameters ---------- text : str or unicode 搜索文章获得的文本 Returns ------- list[dict] { 'article': { 'title': '', # 文章标题 'url': '', # 文章链接 'imgs': '', # 文章图片list 'abstract': '', # 文章摘要 'time': '' # 文章推送时间 }, 'gzh': { 'profile_url': '', # 公众号最近10条群发页链接 'headimage': '', # 头像 'wechat_name': '', # 名称 'isv': '', # 是否加v } }
Below is the the instruction that describes the task: ### Input: 从搜索文章获得的文本 提取章列表信息 Parameters ---------- text : str or unicode 搜索文章获得的文本 Returns ------- list[dict] { 'article': { 'title': '', # 文章标题 'url': '', # 文章链接 'imgs': '', # 文章图片list 'abstract': '', # 文章摘要 'time': '' # 文章推送时间 }, 'gzh': { 'profile_url': '', # 公众号最近10条群发页链接 'headimage': '', # 头像 'wechat_name': '', # 名称 'isv': '', # 是否加v } } ### Response: def get_article_by_search(text): """从搜索文章获得的文本 提取章列表信息 Parameters ---------- text : str or unicode 搜索文章获得的文本 Returns ------- list[dict] { 'article': { 'title': '', # 文章标题 'url': '', # 文章链接 'imgs': '', # 文章图片list 'abstract': '', # 文章摘要 'time': '' # 文章推送时间 }, 'gzh': { 'profile_url': '', # 公众号最近10条群发页链接 'headimage': '', # 头像 'wechat_name': '', # 名称 'isv': '', # 是否加v } } """ page = etree.HTML(text) lis = page.xpath('//ul[@class="news-list"]/li') articles = [] for li in lis: url = get_first_of_element(li, 'div[1]/a/@href') if url: title = get_first_of_element(li, 'div[2]/h3/a') imgs = li.xpath('div[1]/a/img/@src') abstract = get_first_of_element(li, 'div[2]/p') time = get_first_of_element(li, 'div[2]/div/span/script/text()') gzh_info = li.xpath('div[2]/div/a')[0] else: url = get_first_of_element(li, 'div/h3/a/@href') title = get_first_of_element(li, 'div/h3/a') imgs = [] spans = li.xpath('div/div[1]/a') for span in spans: img = span.xpath('span/img/@src') if img: imgs.append(img) abstract = get_first_of_element(li, 'div/p') time = get_first_of_element(li, 'div/div[2]/span/script/text()') gzh_info = li.xpath('div/div[2]/a')[0] if title is not None: title = get_elem_text(title).replace("red_beg", "").replace("red_end", "") if abstract is not None: abstract = get_elem_text(abstract).replace("red_beg", "").replace("red_end", "") time = re.findall('timeConvert\(\'(.*?)\'\)', time) time = list_or_empty(time, int) profile_url = get_first_of_element(gzh_info, '@href') headimage = get_first_of_element(gzh_info, '@data-headimage') wechat_name = get_first_of_element(gzh_info, 'text()') gzh_isv = get_first_of_element(gzh_info, '@data-isv', int) articles.append({ 'article': { 'title': title, 'url': url, 'imgs': format_image_url(imgs), 'abstract': abstract, 'time': time }, 'gzh': { 'profile_url': profile_url, 'headimage': headimage, 'wechat_name': wechat_name, 'isv': gzh_isv, } }) return articles
def warm(self, jittering_ratio=0.2): """Progressively load the previous snapshot during the day. Loading all the snapshots at once can takes a substantial amount of time. This method, if called periodically during the day will progressively load those snapshots one by one. Because many workers are going to use this method at the same time, we add a jittering to the period between load to avoid hammering the disk at the same time. """ if self.snapshot_to_load == None: last_period = self.current_period - dt.timedelta(days=self.expiration-1) self.compute_refresh_period() self.snapshot_to_load = [] base_filename = "%s/%s_%s_*.dat" % (self.snapshot_path, self.name, self.expiration) availables_snapshots = glob.glob(base_filename) for filename in availables_snapshots: snapshot_period = dt.datetime.strptime(filename.split('_')[-1].strip('.dat'), "%Y-%m-%d") if snapshot_period >= last_period: self.snapshot_to_load.append(filename) self.ready = False if self.snapshot_to_load and self._should_warm(): filename = self.snapshot_to_load.pop() self._union_bf_from_file(filename) jittering = self.warm_period * (np.random.random()-0.5) * jittering_ratio self.next_snapshot_load = time.time() + self.warm_period + jittering if not self.snapshot_to_load: self.ready = True
Progressively load the previous snapshot during the day. Loading all the snapshots at once can takes a substantial amount of time. This method, if called periodically during the day will progressively load those snapshots one by one. Because many workers are going to use this method at the same time, we add a jittering to the period between load to avoid hammering the disk at the same time.
Below is the the instruction that describes the task: ### Input: Progressively load the previous snapshot during the day. Loading all the snapshots at once can takes a substantial amount of time. This method, if called periodically during the day will progressively load those snapshots one by one. Because many workers are going to use this method at the same time, we add a jittering to the period between load to avoid hammering the disk at the same time. ### Response: def warm(self, jittering_ratio=0.2): """Progressively load the previous snapshot during the day. Loading all the snapshots at once can takes a substantial amount of time. This method, if called periodically during the day will progressively load those snapshots one by one. Because many workers are going to use this method at the same time, we add a jittering to the period between load to avoid hammering the disk at the same time. """ if self.snapshot_to_load == None: last_period = self.current_period - dt.timedelta(days=self.expiration-1) self.compute_refresh_period() self.snapshot_to_load = [] base_filename = "%s/%s_%s_*.dat" % (self.snapshot_path, self.name, self.expiration) availables_snapshots = glob.glob(base_filename) for filename in availables_snapshots: snapshot_period = dt.datetime.strptime(filename.split('_')[-1].strip('.dat'), "%Y-%m-%d") if snapshot_period >= last_period: self.snapshot_to_load.append(filename) self.ready = False if self.snapshot_to_load and self._should_warm(): filename = self.snapshot_to_load.pop() self._union_bf_from_file(filename) jittering = self.warm_period * (np.random.random()-0.5) * jittering_ratio self.next_snapshot_load = time.time() + self.warm_period + jittering if not self.snapshot_to_load: self.ready = True
def PUT(self, rest_path_list, **kwargs): """Send a PUT request with optional streaming multipart encoding. See requests.sessions.request for optional parameters. See post() for parameters. :returns: Response object """ fields = kwargs.pop("fields", None) if fields is not None: return self._send_mmp_stream("PUT", rest_path_list, fields, **kwargs) else: return self._request("PUT", rest_path_list, **kwargs)
Send a PUT request with optional streaming multipart encoding. See requests.sessions.request for optional parameters. See post() for parameters. :returns: Response object
Below is the the instruction that describes the task: ### Input: Send a PUT request with optional streaming multipart encoding. See requests.sessions.request for optional parameters. See post() for parameters. :returns: Response object ### Response: def PUT(self, rest_path_list, **kwargs): """Send a PUT request with optional streaming multipart encoding. See requests.sessions.request for optional parameters. See post() for parameters. :returns: Response object """ fields = kwargs.pop("fields", None) if fields is not None: return self._send_mmp_stream("PUT", rest_path_list, fields, **kwargs) else: return self._request("PUT", rest_path_list, **kwargs)
def get_cantera_mass_fraction(self, species_conversion=None): """Get the mass fractions in a string format suitable for input to Cantera. Arguments: species_conversion (`dict`, optional): Mapping of species identifier to a species name. This argument should be supplied when the name of the species in the ChemKED YAML file does not match the name of the same species in a chemical kinetic mechanism. The species identifier (the key of the mapping) can be the name, InChI, or SMILES provided in the ChemKED file, while the value associated with a key should be the desired name in the Cantera format output string. Returns: `str`: String of mass fractions in the ``SPEC:AMT, SPEC:AMT`` format Raises: `ValueError`: If the composition type is ``'mole fraction'`` or ``'mole percent'``, the conversion cannot be done because no molecular weight information is known Examples: >>> dp = DataPoint(properties) >>> dp.get_cantera_mass_fraction() 'H2:2.2525e-04, O2:4.4775e-03, Ar:9.9530e-01' >>> species_conversion = {'H2': 'h2', 'O2': 'o2'} >>> dp.get_cantera_mass_fraction(species_conversion) 'h2:2.2525e-04, o2:4.4775e-03, Ar:9.9530e-01' >>> species_conversion = {'1S/H2/h1H': 'h2', '1S/O2/c1-2': 'o2'} >>> dp.get_cantera_mass_fraction(species_conversion) 'h2:2.2525e-04, o2:4.4775e-03, Ar:9.9530e-01' """ if self.composition_type in ['mole fraction', 'mole percent']: raise ValueError('Cannot get mass fractions from the given composition.\n' '{}'.format(self.composition) ) else: return self.get_cantera_composition_string(species_conversion)
Get the mass fractions in a string format suitable for input to Cantera. Arguments: species_conversion (`dict`, optional): Mapping of species identifier to a species name. This argument should be supplied when the name of the species in the ChemKED YAML file does not match the name of the same species in a chemical kinetic mechanism. The species identifier (the key of the mapping) can be the name, InChI, or SMILES provided in the ChemKED file, while the value associated with a key should be the desired name in the Cantera format output string. Returns: `str`: String of mass fractions in the ``SPEC:AMT, SPEC:AMT`` format Raises: `ValueError`: If the composition type is ``'mole fraction'`` or ``'mole percent'``, the conversion cannot be done because no molecular weight information is known Examples: >>> dp = DataPoint(properties) >>> dp.get_cantera_mass_fraction() 'H2:2.2525e-04, O2:4.4775e-03, Ar:9.9530e-01' >>> species_conversion = {'H2': 'h2', 'O2': 'o2'} >>> dp.get_cantera_mass_fraction(species_conversion) 'h2:2.2525e-04, o2:4.4775e-03, Ar:9.9530e-01' >>> species_conversion = {'1S/H2/h1H': 'h2', '1S/O2/c1-2': 'o2'} >>> dp.get_cantera_mass_fraction(species_conversion) 'h2:2.2525e-04, o2:4.4775e-03, Ar:9.9530e-01'
Below is the the instruction that describes the task: ### Input: Get the mass fractions in a string format suitable for input to Cantera. Arguments: species_conversion (`dict`, optional): Mapping of species identifier to a species name. This argument should be supplied when the name of the species in the ChemKED YAML file does not match the name of the same species in a chemical kinetic mechanism. The species identifier (the key of the mapping) can be the name, InChI, or SMILES provided in the ChemKED file, while the value associated with a key should be the desired name in the Cantera format output string. Returns: `str`: String of mass fractions in the ``SPEC:AMT, SPEC:AMT`` format Raises: `ValueError`: If the composition type is ``'mole fraction'`` or ``'mole percent'``, the conversion cannot be done because no molecular weight information is known Examples: >>> dp = DataPoint(properties) >>> dp.get_cantera_mass_fraction() 'H2:2.2525e-04, O2:4.4775e-03, Ar:9.9530e-01' >>> species_conversion = {'H2': 'h2', 'O2': 'o2'} >>> dp.get_cantera_mass_fraction(species_conversion) 'h2:2.2525e-04, o2:4.4775e-03, Ar:9.9530e-01' >>> species_conversion = {'1S/H2/h1H': 'h2', '1S/O2/c1-2': 'o2'} >>> dp.get_cantera_mass_fraction(species_conversion) 'h2:2.2525e-04, o2:4.4775e-03, Ar:9.9530e-01' ### Response: def get_cantera_mass_fraction(self, species_conversion=None): """Get the mass fractions in a string format suitable for input to Cantera. Arguments: species_conversion (`dict`, optional): Mapping of species identifier to a species name. This argument should be supplied when the name of the species in the ChemKED YAML file does not match the name of the same species in a chemical kinetic mechanism. The species identifier (the key of the mapping) can be the name, InChI, or SMILES provided in the ChemKED file, while the value associated with a key should be the desired name in the Cantera format output string. Returns: `str`: String of mass fractions in the ``SPEC:AMT, SPEC:AMT`` format Raises: `ValueError`: If the composition type is ``'mole fraction'`` or ``'mole percent'``, the conversion cannot be done because no molecular weight information is known Examples: >>> dp = DataPoint(properties) >>> dp.get_cantera_mass_fraction() 'H2:2.2525e-04, O2:4.4775e-03, Ar:9.9530e-01' >>> species_conversion = {'H2': 'h2', 'O2': 'o2'} >>> dp.get_cantera_mass_fraction(species_conversion) 'h2:2.2525e-04, o2:4.4775e-03, Ar:9.9530e-01' >>> species_conversion = {'1S/H2/h1H': 'h2', '1S/O2/c1-2': 'o2'} >>> dp.get_cantera_mass_fraction(species_conversion) 'h2:2.2525e-04, o2:4.4775e-03, Ar:9.9530e-01' """ if self.composition_type in ['mole fraction', 'mole percent']: raise ValueError('Cannot get mass fractions from the given composition.\n' '{}'.format(self.composition) ) else: return self.get_cantera_composition_string(species_conversion)
def do_photometry(self): """ Does photometry and estimates uncertainties by calculating the scatter around a linear fit to the data in each orientation. This function is called by other functions and generally the user will not need to interact with it directly. """ std_f = np.zeros(4) data_save = np.zeros_like(self.postcard) self.obs_flux = np.zeros_like(self.reference_flux) for i in range(4): g = np.where(self.qs == i)[0] wh = np.where(self.times[g] > 54947) data_save[g] = np.roll(self.postcard[g], int(self.roll_best[i,0]), axis=1) data_save[g] = np.roll(data_save[g], int(self.roll_best[i,1]), axis=2) self.target_flux_pixels = data_save[:,self.targets == 1] self.target_flux = np.sum(self.target_flux_pixels, axis=1) self.obs_flux[g] = self.target_flux[g] / self.reference_flux[g] self.obs_flux[g] /= np.median(self.obs_flux[g[wh]]) fitline = np.polyfit(self.times[g][wh], self.obs_flux[g][wh], 1) std_f[i] = np.max([np.std(self.obs_flux[g][wh]/(fitline[0]*self.times[g][wh]+fitline[1])), 0.001]) self.flux_uncert = std_f
Does photometry and estimates uncertainties by calculating the scatter around a linear fit to the data in each orientation. This function is called by other functions and generally the user will not need to interact with it directly.
Below is the the instruction that describes the task: ### Input: Does photometry and estimates uncertainties by calculating the scatter around a linear fit to the data in each orientation. This function is called by other functions and generally the user will not need to interact with it directly. ### Response: def do_photometry(self): """ Does photometry and estimates uncertainties by calculating the scatter around a linear fit to the data in each orientation. This function is called by other functions and generally the user will not need to interact with it directly. """ std_f = np.zeros(4) data_save = np.zeros_like(self.postcard) self.obs_flux = np.zeros_like(self.reference_flux) for i in range(4): g = np.where(self.qs == i)[0] wh = np.where(self.times[g] > 54947) data_save[g] = np.roll(self.postcard[g], int(self.roll_best[i,0]), axis=1) data_save[g] = np.roll(data_save[g], int(self.roll_best[i,1]), axis=2) self.target_flux_pixels = data_save[:,self.targets == 1] self.target_flux = np.sum(self.target_flux_pixels, axis=1) self.obs_flux[g] = self.target_flux[g] / self.reference_flux[g] self.obs_flux[g] /= np.median(self.obs_flux[g[wh]]) fitline = np.polyfit(self.times[g][wh], self.obs_flux[g][wh], 1) std_f[i] = np.max([np.std(self.obs_flux[g][wh]/(fitline[0]*self.times[g][wh]+fitline[1])), 0.001]) self.flux_uncert = std_f
def gen_non_ca_cert(filename, dirname, days, ip_list, dns_list, ca_crt, ca_key, silent=False): """ generate a non CA key and certificate key pair signed by the private CA key and crt. :param filename: prefix for the key and cert file :param dirname: name of the directory :param days: days of the certificate being valid :ip_list: a list of ip address to be included in the certificate :dns_list: a list of dns names to be included in the certificate :ca_key: file path to the CA key :ca_crt: file path to the CA crt :param silent: whether to suppress output """ key_file = os.path.join(dirname, '{}.key'.format(filename)) req = os.path.join(dirname, '{}.csr'.format(filename)) crt = os.path.join(dirname, '{}.crt'.format(filename)) gen_private_key(key_file, silent) alt_names = [] for ind, ip in enumerate(ip_list): alt_names.append('IP.{} = {}'.format(ind + 1, ip)) for ind, dns in enumerate(dns_list): alt_names.append('DNS.{} = {}'.format(ind + 1, dns)) conf = tempfile.mktemp() open(conf, 'w').write(SUBJECT_ALT_NAME + '\n'.join(alt_names)) gen_cert_request(req, key_file, conf, silent) sign_cert_request(crt, req, ca_crt, ca_key, days, conf, silent)
generate a non CA key and certificate key pair signed by the private CA key and crt. :param filename: prefix for the key and cert file :param dirname: name of the directory :param days: days of the certificate being valid :ip_list: a list of ip address to be included in the certificate :dns_list: a list of dns names to be included in the certificate :ca_key: file path to the CA key :ca_crt: file path to the CA crt :param silent: whether to suppress output
Below is the the instruction that describes the task: ### Input: generate a non CA key and certificate key pair signed by the private CA key and crt. :param filename: prefix for the key and cert file :param dirname: name of the directory :param days: days of the certificate being valid :ip_list: a list of ip address to be included in the certificate :dns_list: a list of dns names to be included in the certificate :ca_key: file path to the CA key :ca_crt: file path to the CA crt :param silent: whether to suppress output ### Response: def gen_non_ca_cert(filename, dirname, days, ip_list, dns_list, ca_crt, ca_key, silent=False): """ generate a non CA key and certificate key pair signed by the private CA key and crt. :param filename: prefix for the key and cert file :param dirname: name of the directory :param days: days of the certificate being valid :ip_list: a list of ip address to be included in the certificate :dns_list: a list of dns names to be included in the certificate :ca_key: file path to the CA key :ca_crt: file path to the CA crt :param silent: whether to suppress output """ key_file = os.path.join(dirname, '{}.key'.format(filename)) req = os.path.join(dirname, '{}.csr'.format(filename)) crt = os.path.join(dirname, '{}.crt'.format(filename)) gen_private_key(key_file, silent) alt_names = [] for ind, ip in enumerate(ip_list): alt_names.append('IP.{} = {}'.format(ind + 1, ip)) for ind, dns in enumerate(dns_list): alt_names.append('DNS.{} = {}'.format(ind + 1, dns)) conf = tempfile.mktemp() open(conf, 'w').write(SUBJECT_ALT_NAME + '\n'.join(alt_names)) gen_cert_request(req, key_file, conf, silent) sign_cert_request(crt, req, ca_crt, ca_key, days, conf, silent)
def glob_config(pattern, *search_dirs): """Return glob results for all possible configuration locations. Note: This method does not check the configuration "base" directory if the pattern includes a subdirectory. This is done for performance since this is usually used to find *all* configs for a certain component. """ patterns = config_search_paths(pattern, *search_dirs, check_exists=False) for pattern in patterns: for path in glob.iglob(pattern): yield path
Return glob results for all possible configuration locations. Note: This method does not check the configuration "base" directory if the pattern includes a subdirectory. This is done for performance since this is usually used to find *all* configs for a certain component.
Below is the the instruction that describes the task: ### Input: Return glob results for all possible configuration locations. Note: This method does not check the configuration "base" directory if the pattern includes a subdirectory. This is done for performance since this is usually used to find *all* configs for a certain component. ### Response: def glob_config(pattern, *search_dirs): """Return glob results for all possible configuration locations. Note: This method does not check the configuration "base" directory if the pattern includes a subdirectory. This is done for performance since this is usually used to find *all* configs for a certain component. """ patterns = config_search_paths(pattern, *search_dirs, check_exists=False) for pattern in patterns: for path in glob.iglob(pattern): yield path
def velocity(data, vkey='velocity', mode=None, fit_offset=False, fit_offset2=False, filter_genes=False, groups=None, groupby=None, groups_for_fit=None, use_raw=False, perc=[5, 95], copy=False): """Estimates velocities in a gene-specific manner Arguments --------- data: :class:`~anndata.AnnData` Annotated data matrix. vkey: `str` (default: `'velocity'`) Name under which to refer to the computed velocities for `velocity_graph` and `velocity_embedding`. mode: `'deterministic'`, `'stochastic'` or `'bayes'` (default: `'stochastic'`) Whether to run the estimation using the deterministic or stochastic model of transcriptional dynamics. `'bayes'` solves the stochastic model and accounts for heteroscedasticity, but is slower than `'stochastic'`. fit_offset: `bool` (default: `False`) Whether to fit with offset for first order moment dynamics. fit_offset2: `bool`, (default: `False`) Whether to fit with offset for second order moment dynamics. filter_genes: `bool` (default: `True`) Whether to remove genes that are not used for further velocity analysis. groups: `str`, `list` (default: `None`) Subset of groups, e.g. [‘g1’, ‘g2’, ‘g3’], to which velocity analysis shall be restricted. groupby: `str`, `list` or `np.ndarray` (default: `None`) Key of observations grouping to consider. groups_for_fit: `str`, `list` or `np.ndarray` (default: `None`) Subset of groups, e.g. [‘g1’, ‘g2’, ‘g3’], to which steady-state fitting shall be restricted. use_raw: `bool` (default: `False`) Whether to use raw data for estimation. perc: `float` (default: `None`) Percentile, e.g. 98, upon for extreme quantile fit (to better capture steady states for velocity estimation). copy: `bool` (default: `False`) Return a copy instead of writing to `adata`. Returns ------- Returns or updates `adata` with the attributes velocity: `.layers` velocity vectors for each individual cell variance_velocity: `.layers` velocity vectors for the cell variances velocity_offset, velocity_beta, velocity_gamma, velocity_r2: `.var` parameters """ adata = data.copy() if copy else data if not use_raw and 'Ms' not in adata.layers.keys(): moments(adata) logg.info('computing velocities', r=True) strings_to_categoricals(adata) categories = adata.obs[groupby].cat.categories \ if groupby is not None and groups is None and groups_for_fit is None else [None] for cat in categories: groups = cat if cat is not None else groups cell_subset = groups_to_bool(adata, groups, groupby) _adata = adata if groups is None else adata[cell_subset] velo = Velocity(_adata, groups_for_fit=groups_for_fit, groupby=groupby, use_raw=use_raw) velo.compute_deterministic(fit_offset, perc=perc) if any([mode is not None and mode in item for item in ['stochastic', 'bayes', 'alpha']]): if filter_genes and len(set(velo._velocity_genes)) > 1: adata._inplace_subset_var(velo._velocity_genes) residual = velo._residual[:, velo._velocity_genes] _adata = adata if groups is None else adata[cell_subset] velo = Velocity(_adata, residual=residual, groups_for_fit=groups_for_fit, groupby=groupby) velo.compute_stochastic(fit_offset, fit_offset2, mode, perc=perc) write_residuals(adata, vkey, velo._residual, cell_subset) write_residuals(adata, 'variance_' + vkey, velo._residual2, cell_subset) write_pars(adata, vkey, velo.get_pars(), velo.get_pars_names(), add_key=cat) if filter_genes and len(set(velo._velocity_genes)) > 1: adata._inplace_subset_var(velo._velocity_genes) logg.info(' finished', time=True, end=' ' if settings.verbosity > 2 else '\n') logg.hint('added \n' ' \'' + vkey + '\', velocity vectors for each individual cell (adata.layers)') return adata if copy else None
Estimates velocities in a gene-specific manner Arguments --------- data: :class:`~anndata.AnnData` Annotated data matrix. vkey: `str` (default: `'velocity'`) Name under which to refer to the computed velocities for `velocity_graph` and `velocity_embedding`. mode: `'deterministic'`, `'stochastic'` or `'bayes'` (default: `'stochastic'`) Whether to run the estimation using the deterministic or stochastic model of transcriptional dynamics. `'bayes'` solves the stochastic model and accounts for heteroscedasticity, but is slower than `'stochastic'`. fit_offset: `bool` (default: `False`) Whether to fit with offset for first order moment dynamics. fit_offset2: `bool`, (default: `False`) Whether to fit with offset for second order moment dynamics. filter_genes: `bool` (default: `True`) Whether to remove genes that are not used for further velocity analysis. groups: `str`, `list` (default: `None`) Subset of groups, e.g. [‘g1’, ‘g2’, ‘g3’], to which velocity analysis shall be restricted. groupby: `str`, `list` or `np.ndarray` (default: `None`) Key of observations grouping to consider. groups_for_fit: `str`, `list` or `np.ndarray` (default: `None`) Subset of groups, e.g. [‘g1’, ‘g2’, ‘g3’], to which steady-state fitting shall be restricted. use_raw: `bool` (default: `False`) Whether to use raw data for estimation. perc: `float` (default: `None`) Percentile, e.g. 98, upon for extreme quantile fit (to better capture steady states for velocity estimation). copy: `bool` (default: `False`) Return a copy instead of writing to `adata`. Returns ------- Returns or updates `adata` with the attributes velocity: `.layers` velocity vectors for each individual cell variance_velocity: `.layers` velocity vectors for the cell variances velocity_offset, velocity_beta, velocity_gamma, velocity_r2: `.var` parameters
Below is the the instruction that describes the task: ### Input: Estimates velocities in a gene-specific manner Arguments --------- data: :class:`~anndata.AnnData` Annotated data matrix. vkey: `str` (default: `'velocity'`) Name under which to refer to the computed velocities for `velocity_graph` and `velocity_embedding`. mode: `'deterministic'`, `'stochastic'` or `'bayes'` (default: `'stochastic'`) Whether to run the estimation using the deterministic or stochastic model of transcriptional dynamics. `'bayes'` solves the stochastic model and accounts for heteroscedasticity, but is slower than `'stochastic'`. fit_offset: `bool` (default: `False`) Whether to fit with offset for first order moment dynamics. fit_offset2: `bool`, (default: `False`) Whether to fit with offset for second order moment dynamics. filter_genes: `bool` (default: `True`) Whether to remove genes that are not used for further velocity analysis. groups: `str`, `list` (default: `None`) Subset of groups, e.g. [‘g1’, ‘g2’, ‘g3’], to which velocity analysis shall be restricted. groupby: `str`, `list` or `np.ndarray` (default: `None`) Key of observations grouping to consider. groups_for_fit: `str`, `list` or `np.ndarray` (default: `None`) Subset of groups, e.g. [‘g1’, ‘g2’, ‘g3’], to which steady-state fitting shall be restricted. use_raw: `bool` (default: `False`) Whether to use raw data for estimation. perc: `float` (default: `None`) Percentile, e.g. 98, upon for extreme quantile fit (to better capture steady states for velocity estimation). copy: `bool` (default: `False`) Return a copy instead of writing to `adata`. Returns ------- Returns or updates `adata` with the attributes velocity: `.layers` velocity vectors for each individual cell variance_velocity: `.layers` velocity vectors for the cell variances velocity_offset, velocity_beta, velocity_gamma, velocity_r2: `.var` parameters ### Response: def velocity(data, vkey='velocity', mode=None, fit_offset=False, fit_offset2=False, filter_genes=False, groups=None, groupby=None, groups_for_fit=None, use_raw=False, perc=[5, 95], copy=False): """Estimates velocities in a gene-specific manner Arguments --------- data: :class:`~anndata.AnnData` Annotated data matrix. vkey: `str` (default: `'velocity'`) Name under which to refer to the computed velocities for `velocity_graph` and `velocity_embedding`. mode: `'deterministic'`, `'stochastic'` or `'bayes'` (default: `'stochastic'`) Whether to run the estimation using the deterministic or stochastic model of transcriptional dynamics. `'bayes'` solves the stochastic model and accounts for heteroscedasticity, but is slower than `'stochastic'`. fit_offset: `bool` (default: `False`) Whether to fit with offset for first order moment dynamics. fit_offset2: `bool`, (default: `False`) Whether to fit with offset for second order moment dynamics. filter_genes: `bool` (default: `True`) Whether to remove genes that are not used for further velocity analysis. groups: `str`, `list` (default: `None`) Subset of groups, e.g. [‘g1’, ‘g2’, ‘g3’], to which velocity analysis shall be restricted. groupby: `str`, `list` or `np.ndarray` (default: `None`) Key of observations grouping to consider. groups_for_fit: `str`, `list` or `np.ndarray` (default: `None`) Subset of groups, e.g. [‘g1’, ‘g2’, ‘g3’], to which steady-state fitting shall be restricted. use_raw: `bool` (default: `False`) Whether to use raw data for estimation. perc: `float` (default: `None`) Percentile, e.g. 98, upon for extreme quantile fit (to better capture steady states for velocity estimation). copy: `bool` (default: `False`) Return a copy instead of writing to `adata`. Returns ------- Returns or updates `adata` with the attributes velocity: `.layers` velocity vectors for each individual cell variance_velocity: `.layers` velocity vectors for the cell variances velocity_offset, velocity_beta, velocity_gamma, velocity_r2: `.var` parameters """ adata = data.copy() if copy else data if not use_raw and 'Ms' not in adata.layers.keys(): moments(adata) logg.info('computing velocities', r=True) strings_to_categoricals(adata) categories = adata.obs[groupby].cat.categories \ if groupby is not None and groups is None and groups_for_fit is None else [None] for cat in categories: groups = cat if cat is not None else groups cell_subset = groups_to_bool(adata, groups, groupby) _adata = adata if groups is None else adata[cell_subset] velo = Velocity(_adata, groups_for_fit=groups_for_fit, groupby=groupby, use_raw=use_raw) velo.compute_deterministic(fit_offset, perc=perc) if any([mode is not None and mode in item for item in ['stochastic', 'bayes', 'alpha']]): if filter_genes and len(set(velo._velocity_genes)) > 1: adata._inplace_subset_var(velo._velocity_genes) residual = velo._residual[:, velo._velocity_genes] _adata = adata if groups is None else adata[cell_subset] velo = Velocity(_adata, residual=residual, groups_for_fit=groups_for_fit, groupby=groupby) velo.compute_stochastic(fit_offset, fit_offset2, mode, perc=perc) write_residuals(adata, vkey, velo._residual, cell_subset) write_residuals(adata, 'variance_' + vkey, velo._residual2, cell_subset) write_pars(adata, vkey, velo.get_pars(), velo.get_pars_names(), add_key=cat) if filter_genes and len(set(velo._velocity_genes)) > 1: adata._inplace_subset_var(velo._velocity_genes) logg.info(' finished', time=True, end=' ' if settings.verbosity > 2 else '\n') logg.hint('added \n' ' \'' + vkey + '\', velocity vectors for each individual cell (adata.layers)') return adata if copy else None
def get_variables(run_name): """ Returns a dict of variables in the selected run table. :param run_name: str, required run table name :return: dict -> {<int_keys>: <variable_name>} """ conn, c = open_data_base_connection() try: # Get latest project c.execute("""SELECT variable_name FROM {}""".format(run_name)) variable_names = np.array(c.fetchall()).squeeze(axis=1) variable_names = convert_list_to_dict(variable_names) return variable_names except sqlite3.OperationalError: logging.info("{} not found".format(run_name)) finally: conn.close()
Returns a dict of variables in the selected run table. :param run_name: str, required run table name :return: dict -> {<int_keys>: <variable_name>}
Below is the the instruction that describes the task: ### Input: Returns a dict of variables in the selected run table. :param run_name: str, required run table name :return: dict -> {<int_keys>: <variable_name>} ### Response: def get_variables(run_name): """ Returns a dict of variables in the selected run table. :param run_name: str, required run table name :return: dict -> {<int_keys>: <variable_name>} """ conn, c = open_data_base_connection() try: # Get latest project c.execute("""SELECT variable_name FROM {}""".format(run_name)) variable_names = np.array(c.fetchall()).squeeze(axis=1) variable_names = convert_list_to_dict(variable_names) return variable_names except sqlite3.OperationalError: logging.info("{} not found".format(run_name)) finally: conn.close()
def get_gaf_gene_ontology_file(path): """Extract the gene ontology file associated with a GO annotation file. Parameters ---------- path: str The path name of the GO annotation file. Returns ------- str The URL of the associated gene ontology file. """ assert isinstance(path, str) version = None with misc.smart_open_read(path, encoding='UTF-8', try_gzip=True) as fh: for l in fh: if l[0] != '!': break if l.startswith('!GO-version:'): version = l.split(' ')[1] break return version
Extract the gene ontology file associated with a GO annotation file. Parameters ---------- path: str The path name of the GO annotation file. Returns ------- str The URL of the associated gene ontology file.
Below is the the instruction that describes the task: ### Input: Extract the gene ontology file associated with a GO annotation file. Parameters ---------- path: str The path name of the GO annotation file. Returns ------- str The URL of the associated gene ontology file. ### Response: def get_gaf_gene_ontology_file(path): """Extract the gene ontology file associated with a GO annotation file. Parameters ---------- path: str The path name of the GO annotation file. Returns ------- str The URL of the associated gene ontology file. """ assert isinstance(path, str) version = None with misc.smart_open_read(path, encoding='UTF-8', try_gzip=True) as fh: for l in fh: if l[0] != '!': break if l.startswith('!GO-version:'): version = l.split(' ')[1] break return version
def set_current_limit(self, channel, value, unit='A'): '''Setting current limit Note: same limit for all channels. ''' # TODO: add units / calibration if unit == 'raw': value = value elif unit == 'A': value = int(value * 1000 * self.CURRENT_LIMIT_GAIN) elif unit == 'mA': value = int(value * self.CURRENT_LIMIT_GAIN) elif unit == 'uA': value = int(value / 1000 * self.CURRENT_LIMIT_GAIN) else: raise TypeError("Invalid unit type.") I2cAnalogChannel._set_dac_value(self, address=self.CURRENT_LIMIT_DAC_SLAVE_ADD, dac_ch=self.CURRENT_LIMIT_DAC_CH, value=value)
Setting current limit Note: same limit for all channels.
Below is the the instruction that describes the task: ### Input: Setting current limit Note: same limit for all channels. ### Response: def set_current_limit(self, channel, value, unit='A'): '''Setting current limit Note: same limit for all channels. ''' # TODO: add units / calibration if unit == 'raw': value = value elif unit == 'A': value = int(value * 1000 * self.CURRENT_LIMIT_GAIN) elif unit == 'mA': value = int(value * self.CURRENT_LIMIT_GAIN) elif unit == 'uA': value = int(value / 1000 * self.CURRENT_LIMIT_GAIN) else: raise TypeError("Invalid unit type.") I2cAnalogChannel._set_dac_value(self, address=self.CURRENT_LIMIT_DAC_SLAVE_ADD, dac_ch=self.CURRENT_LIMIT_DAC_CH, value=value)
async def join(self, ctx): """Sends you the bot invite link.""" perms = discord.Permissions.none() perms.read_messages = True perms.send_messages = True perms.manage_messages = True perms.embed_links = True perms.read_message_history = True perms.attach_files = True perms.add_reactions = True await self.bot.send_message(ctx.message.author, discord.utils.oauth_url(self.bot.client_id, perms))
Sends you the bot invite link.
Below is the the instruction that describes the task: ### Input: Sends you the bot invite link. ### Response: async def join(self, ctx): """Sends you the bot invite link.""" perms = discord.Permissions.none() perms.read_messages = True perms.send_messages = True perms.manage_messages = True perms.embed_links = True perms.read_message_history = True perms.attach_files = True perms.add_reactions = True await self.bot.send_message(ctx.message.author, discord.utils.oauth_url(self.bot.client_id, perms))
def update(self, uid): ''' in infor. ''' postinfo = MPost.get_by_uid(uid) if postinfo.kind == self.kind: pass else: return False post_data, ext_dic = self.fetch_post_data() if 'gcat0' in post_data: pass else: return False if 'valid' in post_data: post_data['valid'] = int(post_data['valid']) else: post_data['valid'] = postinfo.valid ext_dic['def_uid'] = str(uid) cnt_old = tornado.escape.xhtml_unescape(postinfo.cnt_md).strip() cnt_new = post_data['cnt_md'].strip() if cnt_old == cnt_new: pass else: MPostHist.create_post_history(postinfo) MPost.modify_meta(uid, post_data, extinfo=ext_dic) self._add_download_entity(ext_dic) # self.update_tag(uid=uid) update_category(uid, post_data) update_label(uid, post_data) # self.update_label(uid) logger.info('post kind:' + self.kind) # cele_gen_whoosh.delay() tornado.ioloop.IOLoop.instance().add_callback(self.cele_gen_whoosh) self.redirect('/{0}/{1}'.format(router_post[postinfo.kind], uid))
in infor.
Below is the the instruction that describes the task: ### Input: in infor. ### Response: def update(self, uid): ''' in infor. ''' postinfo = MPost.get_by_uid(uid) if postinfo.kind == self.kind: pass else: return False post_data, ext_dic = self.fetch_post_data() if 'gcat0' in post_data: pass else: return False if 'valid' in post_data: post_data['valid'] = int(post_data['valid']) else: post_data['valid'] = postinfo.valid ext_dic['def_uid'] = str(uid) cnt_old = tornado.escape.xhtml_unescape(postinfo.cnt_md).strip() cnt_new = post_data['cnt_md'].strip() if cnt_old == cnt_new: pass else: MPostHist.create_post_history(postinfo) MPost.modify_meta(uid, post_data, extinfo=ext_dic) self._add_download_entity(ext_dic) # self.update_tag(uid=uid) update_category(uid, post_data) update_label(uid, post_data) # self.update_label(uid) logger.info('post kind:' + self.kind) # cele_gen_whoosh.delay() tornado.ioloop.IOLoop.instance().add_callback(self.cele_gen_whoosh) self.redirect('/{0}/{1}'.format(router_post[postinfo.kind], uid))
def n_leaves(neurites, neurite_type=NeuriteType.all): '''number of leaves points in a collection of neurites''' return n_sections(neurites, neurite_type=neurite_type, iterator_type=Tree.ileaf)
number of leaves points in a collection of neurites
Below is the the instruction that describes the task: ### Input: number of leaves points in a collection of neurites ### Response: def n_leaves(neurites, neurite_type=NeuriteType.all): '''number of leaves points in a collection of neurites''' return n_sections(neurites, neurite_type=neurite_type, iterator_type=Tree.ileaf)
def add_mismatch(self, entity, *traits): """ Add a mismatching entity to the index. We do this by simply adding the mismatch to the index. :param collections.Hashable entity: an object to be mismatching the values of `traits_indexed_by` :param list traits: a list of hashable traits to index the entity with """ for trait in traits: self.index[trait].add(entity)
Add a mismatching entity to the index. We do this by simply adding the mismatch to the index. :param collections.Hashable entity: an object to be mismatching the values of `traits_indexed_by` :param list traits: a list of hashable traits to index the entity with
Below is the the instruction that describes the task: ### Input: Add a mismatching entity to the index. We do this by simply adding the mismatch to the index. :param collections.Hashable entity: an object to be mismatching the values of `traits_indexed_by` :param list traits: a list of hashable traits to index the entity with ### Response: def add_mismatch(self, entity, *traits): """ Add a mismatching entity to the index. We do this by simply adding the mismatch to the index. :param collections.Hashable entity: an object to be mismatching the values of `traits_indexed_by` :param list traits: a list of hashable traits to index the entity with """ for trait in traits: self.index[trait].add(entity)
def get_serializer( self, action_kwargs: Dict=None, *args, **kwargs) -> Serializer: """ Return the serializer instance that should be used for validating and deserializing input, and for serializing output. """ serializer_class = self.get_serializer_class( **action_kwargs ) kwargs['context'] = self.get_serializer_context( **action_kwargs ) return serializer_class(*args, **kwargs)
Return the serializer instance that should be used for validating and deserializing input, and for serializing output.
Below is the the instruction that describes the task: ### Input: Return the serializer instance that should be used for validating and deserializing input, and for serializing output. ### Response: def get_serializer( self, action_kwargs: Dict=None, *args, **kwargs) -> Serializer: """ Return the serializer instance that should be used for validating and deserializing input, and for serializing output. """ serializer_class = self.get_serializer_class( **action_kwargs ) kwargs['context'] = self.get_serializer_context( **action_kwargs ) return serializer_class(*args, **kwargs)
def _register_name(self, name): """Get register name. """ if name not in self._var_name_mappers: self._var_name_mappers[name] = VariableNamer(name)
Get register name.
Below is the the instruction that describes the task: ### Input: Get register name. ### Response: def _register_name(self, name): """Get register name. """ if name not in self._var_name_mappers: self._var_name_mappers[name] = VariableNamer(name)
def publish(self, service, routing_id, method, args=None, kwargs=None, broadcast=False, udp=False): '''Send a 1-way message :param service: the service name (the routing top level) :type service: anything hash-able :param int routing_id: the id used for routing within the registered handlers of the service :param string method: the method name to call :param tuple args: The positional arguments to send along with the request. If the first positional argument is a generator object, the publish will be sent in chunks :ref:`(more info) <chunked-messages>`. :param dict kwargs: keyword arguments to send along with the request :param bool broadcast: if ``True``, send to every peer with a matching subscription. :param bool udp: deliver the message over UDP instead of the usual TCP :returns: None. use 'rpc' methods for requests with responses. :raises: :class:`Unroutable <junction.errors.Unroutable>` if no peers are registered to receive the message ''' if udp: func = self._dispatcher.send_publish_udp else: func = self._dispatcher.send_publish if not func(None, service, routing_id, method, args or (), kwargs or {}, singular=not broadcast): raise errors.Unroutable()
Send a 1-way message :param service: the service name (the routing top level) :type service: anything hash-able :param int routing_id: the id used for routing within the registered handlers of the service :param string method: the method name to call :param tuple args: The positional arguments to send along with the request. If the first positional argument is a generator object, the publish will be sent in chunks :ref:`(more info) <chunked-messages>`. :param dict kwargs: keyword arguments to send along with the request :param bool broadcast: if ``True``, send to every peer with a matching subscription. :param bool udp: deliver the message over UDP instead of the usual TCP :returns: None. use 'rpc' methods for requests with responses. :raises: :class:`Unroutable <junction.errors.Unroutable>` if no peers are registered to receive the message
Below is the the instruction that describes the task: ### Input: Send a 1-way message :param service: the service name (the routing top level) :type service: anything hash-able :param int routing_id: the id used for routing within the registered handlers of the service :param string method: the method name to call :param tuple args: The positional arguments to send along with the request. If the first positional argument is a generator object, the publish will be sent in chunks :ref:`(more info) <chunked-messages>`. :param dict kwargs: keyword arguments to send along with the request :param bool broadcast: if ``True``, send to every peer with a matching subscription. :param bool udp: deliver the message over UDP instead of the usual TCP :returns: None. use 'rpc' methods for requests with responses. :raises: :class:`Unroutable <junction.errors.Unroutable>` if no peers are registered to receive the message ### Response: def publish(self, service, routing_id, method, args=None, kwargs=None, broadcast=False, udp=False): '''Send a 1-way message :param service: the service name (the routing top level) :type service: anything hash-able :param int routing_id: the id used for routing within the registered handlers of the service :param string method: the method name to call :param tuple args: The positional arguments to send along with the request. If the first positional argument is a generator object, the publish will be sent in chunks :ref:`(more info) <chunked-messages>`. :param dict kwargs: keyword arguments to send along with the request :param bool broadcast: if ``True``, send to every peer with a matching subscription. :param bool udp: deliver the message over UDP instead of the usual TCP :returns: None. use 'rpc' methods for requests with responses. :raises: :class:`Unroutable <junction.errors.Unroutable>` if no peers are registered to receive the message ''' if udp: func = self._dispatcher.send_publish_udp else: func = self._dispatcher.send_publish if not func(None, service, routing_id, method, args or (), kwargs or {}, singular=not broadcast): raise errors.Unroutable()
def stopService(self): """ Stop the writer thread, wait for it to finish. """ Service.stopService(self) removeDestination(self) self._reactor.callFromThread(self._reactor.stop) return deferToThreadPool( self._mainReactor, self._mainReactor.getThreadPool(), self._thread.join)
Stop the writer thread, wait for it to finish.
Below is the the instruction that describes the task: ### Input: Stop the writer thread, wait for it to finish. ### Response: def stopService(self): """ Stop the writer thread, wait for it to finish. """ Service.stopService(self) removeDestination(self) self._reactor.callFromThread(self._reactor.stop) return deferToThreadPool( self._mainReactor, self._mainReactor.getThreadPool(), self._thread.join)
def GetSubNodeByLocation(self, location): """Retrieves a sub scan node based on the location. Args: location (str): location that should match the location of the path specification of a sub scan node. Returns: SourceScanNode: sub scan node or None if not available. """ for sub_node in self.sub_nodes: sub_node_location = getattr(sub_node.path_spec, 'location', None) if location == sub_node_location: return sub_node return None
Retrieves a sub scan node based on the location. Args: location (str): location that should match the location of the path specification of a sub scan node. Returns: SourceScanNode: sub scan node or None if not available.
Below is the the instruction that describes the task: ### Input: Retrieves a sub scan node based on the location. Args: location (str): location that should match the location of the path specification of a sub scan node. Returns: SourceScanNode: sub scan node or None if not available. ### Response: def GetSubNodeByLocation(self, location): """Retrieves a sub scan node based on the location. Args: location (str): location that should match the location of the path specification of a sub scan node. Returns: SourceScanNode: sub scan node or None if not available. """ for sub_node in self.sub_nodes: sub_node_location = getattr(sub_node.path_spec, 'location', None) if location == sub_node_location: return sub_node return None
def _convert_camera(camera): """ Convert a trimesh camera to a GLTF camera. Parameters ------------ camera : trimesh.scene.cameras.Camera Trimesh camera object Returns ------------- gltf_camera : dict Camera represented as a GLTF dict """ result = { "name": camera.name, "type": "perspective", "perspective": { "aspectRatio": camera.fov[0] / camera.fov[1], "yfov": np.radians(camera.fov[1]), }, } return result
Convert a trimesh camera to a GLTF camera. Parameters ------------ camera : trimesh.scene.cameras.Camera Trimesh camera object Returns ------------- gltf_camera : dict Camera represented as a GLTF dict
Below is the the instruction that describes the task: ### Input: Convert a trimesh camera to a GLTF camera. Parameters ------------ camera : trimesh.scene.cameras.Camera Trimesh camera object Returns ------------- gltf_camera : dict Camera represented as a GLTF dict ### Response: def _convert_camera(camera): """ Convert a trimesh camera to a GLTF camera. Parameters ------------ camera : trimesh.scene.cameras.Camera Trimesh camera object Returns ------------- gltf_camera : dict Camera represented as a GLTF dict """ result = { "name": camera.name, "type": "perspective", "perspective": { "aspectRatio": camera.fov[0] / camera.fov[1], "yfov": np.radians(camera.fov[1]), }, } return result