_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q14300
FittingSequence.pso
train
def pso(self, n_particles, n_iterations, sigma_scale=1, print_key='PSO', threadCount=1): """ Particle Swarm Optimization :param n_particles: number of particles in the Particle Swarm Optimization :param n_iterations: number of iterations in the optimization process :param sigma_...
python
{ "resource": "" }
q14301
FittingSequence.psf_iteration
train
def psf_iteration(self, num_iter=10, no_break=True, stacking_method='median', block_center_neighbour=0, keep_psf_error_map=True, psf_symmetry=1, psf_iter_factor=1, verbose=True, compute_bands=None): """ iterative PSF reconstruction :param num_iter: number of iterations in the p...
python
{ "resource": "" }
q14302
FittingSequence.align_images
train
def align_images(self, n_particles=10, n_iterations=10, lowerLimit=-0.2, upperLimit=0.2, threadCount=1, compute_bands=None): """ aligns the coordinate systems of different exposures within a fixed model parameterisation by executing a PSO with relative coordinate shifts as f...
python
{ "resource": "" }
q14303
FittingSequence.update_settings
train
def update_settings(self, kwargs_model={}, kwargs_constraints={}, kwargs_likelihood={}, lens_add_fixed=[], source_add_fixed=[], lens_light_add_fixed=[], ps_add_fixed=[], cosmo_add_fixed=[], lens_remove_fixed=[], source_remove_fixed=[], lens_light_remove_fixed=[], ps_remove_fixe...
python
{ "resource": "" }
q14304
MamonLokasAnisotropy._B
train
def _B(self, x, a, b): """ incomplete Beta function as described in Mamon&Lokas A13 :param x: :param a: :param b: :return: """ return special.betainc(a, b, x) * special.beta(a, b)
python
{ "resource": "" }
q14305
UpdateManager.update_fixed
train
def update_fixed(self, kwargs_lens, kwargs_source, kwargs_lens_light, kwargs_ps, kwargs_cosmo, lens_add_fixed=[], source_add_fixed=[], lens_light_add_fixed=[], ps_add_fixed=[], cosmo_add_fixed=[], lens_remove_fixed=[], source_remove_fixed=[], lens_light_remove_fixed=[], ps_remo...
python
{ "resource": "" }
q14306
AnalyticKinematics.vel_disp_one
train
def vel_disp_one(self, gamma, rho0_r0_gamma, r_eff, r_ani, R_slit, dR_slit, FWHM): """ computes one realisation of the velocity dispersion realized in the slit :param gamma: power-law slope of the mass profile (isothermal = 2) :param rho0_r0_gamma: combination of Einstein radius and pow...
python
{ "resource": "" }
q14307
LensAnalysis.ellipticity_lens_light
train
def ellipticity_lens_light(self, kwargs_lens_light, center_x=0, center_y=0, model_bool_list=None, deltaPix=None, numPix=None): """ make sure that the window covers all the light, otherwise the moments may give to low answers. :param kwargs_lens_light: :par...
python
{ "resource": "" }
q14308
LensAnalysis._lens_light_internal
train
def _lens_light_internal(self, x_grid, y_grid, kwargs_lens_light, model_bool_list=None): """ evaluates only part of the light profiles :param x_grid: :param y_grid: :param kwargs_lens_light: :return: """ if model_bool_list is None: model_bool_...
python
{ "resource": "" }
q14309
LensAnalysis.multi_gaussian_lens
train
def multi_gaussian_lens(self, kwargs_lens, model_bool_list=None, e1=0, e2=0, n_comp=20): """ multi-gaussian lens model in convergence space :param kwargs_lens: :param n_comp: :return: """ if 'center_x' in kwargs_lens[0]: center_x = kwargs_lens[0]['cen...
python
{ "resource": "" }
q14310
LensAnalysis.flux_components
train
def flux_components(self, kwargs_light, n_grid=400, delta_grid=0.01, deltaPix=0.05, type="lens"): """ computes the total flux in each component of the model :param kwargs_light: :param n_grid: :param delta_grid: :return: """ flux_list = [] R_h_lis...
python
{ "resource": "" }
q14311
LensAnalysis.error_map_source
train
def error_map_source(self, kwargs_source, x_grid, y_grid, cov_param): """ variance of the linear source reconstruction in the source plane coordinates, computed by the diagonal elements of the covariance matrix of the source reconstruction as a sum of the errors of the basis set. ...
python
{ "resource": "" }
q14312
LensAnalysis.mass_fraction_within_radius
train
def mass_fraction_within_radius(self, kwargs_lens, center_x, center_y, theta_E, numPix=100): """ computes the mean convergence of all the different lens model components within a spherical aperture :param kwargs_lens: lens model keyword argument list :param center_x: center of the apert...
python
{ "resource": "" }
q14313
PointSource.update_search_window
train
def update_search_window(self, search_window, x_center, y_center): """ update the search area for the lens equation solver :param search_window: search_window: window size of the image position search with the lens equation solver. :param x_center: center of search window :param...
python
{ "resource": "" }
q14314
PointSource.point_source_list
train
def point_source_list(self, kwargs_ps, kwargs_lens, k=None): """ returns the coordinates and amplitudes of all point sources in a single array :param kwargs_ps: :param kwargs_lens: :return: """ ra_list, dec_list = self.image_position(kwargs_ps, kwargs_lens, k=k) ...
python
{ "resource": "" }
q14315
PointSource.image_amplitude
train
def image_amplitude(self, kwargs_ps, kwargs_lens, k=None): """ returns the image amplitudes :param kwargs_ps: :param kwargs_lens: :return: """ amp_list = [] for i, model in enumerate(self._point_source_list): if k is None or k == i: ...
python
{ "resource": "" }
q14316
PointSource.source_amplitude
train
def source_amplitude(self, kwargs_ps, kwargs_lens): """ returns the source amplitudes :param kwargs_ps: :param kwargs_lens: :return: """ amp_list = [] for i, model in enumerate(self._point_source_list): amp_list.append(model.source_amplitude(k...
python
{ "resource": "" }
q14317
PointSource.re_normalize_flux
train
def re_normalize_flux(self, kwargs_ps, norm_factor): """ renormalizes the point source amplitude keywords by a factor :param kwargs_ps_updated: :param norm_factor: :return: """ for i, model in enumerate(self.point_source_type_list): if model == 'UNLEN...
python
{ "resource": "" }
q14318
LensModelExtensions._tiling_crit
train
def _tiling_crit(self, edge1, edge2, edge_90, max_order, kwargs_lens): """ tiles a rectangular triangle and compares the signs of the magnification :param edge1: [ra_coord, dec_coord, magnification] :param edge2: [ra_coord, dec_coord, magnification] :param edge_90: [ra_coord, de...
python
{ "resource": "" }
q14319
LensModelExtensions.effective_einstein_radius
train
def effective_einstein_radius(self, kwargs_lens_list, k=None, spacing=1000): """ computes the radius with mean convergence=1 :param kwargs_lens: :param spacing: number of annular bins to compute the convergence (resolution of the Einstein radius estimate) :return: """ ...
python
{ "resource": "" }
q14320
LensModelExtensions.lens_center
train
def lens_center(self, kwargs_lens, k=None, bool_list=None, numPix=200, deltaPix=0.01, center_x_init=0, center_y_init=0): """ computes the convergence weighted center of a lens model :param kwargs_lens: lens model keyword argument list :param bool_list: bool list (optional) to include ce...
python
{ "resource": "" }
q14321
LensModelExtensions.profile_slope
train
def profile_slope(self, kwargs_lens_list, lens_model_internal_bool=None, num_points=10): """ computes the logarithmic power-law slope of a profile :param kwargs_lens_list: lens model keyword argument list :param lens_model_internal_bool: bool list, indicate which part of the model to co...
python
{ "resource": "" }
q14322
Background.D_dt
train
def D_dt(self, z_lens, z_source): """ time-delay distance :param z_lens: redshift of lens :param z_source: redshift of source :return: time-delay distance in units of Mpc """ return self.D_xy(0, z_lens) * self.D_xy(0, z_source) / self.D_xy(z_lens, z_source) * (1 ...
python
{ "resource": "" }
q14323
ParticleSwarmOptimizer._sample
train
def _sample(self, maxIter=1000, c1=1.193, c2=1.193, lookback = 0.25, standard_dev = None): """ Launches the PSO. Yields the complete swarm per iteration :param maxIter: maximum iterations :param c1: cognitive weight :param c2: social weight :param lookback: percentange o...
python
{ "resource": "" }
q14324
Particle.create
train
def create(cls, paramCount): """ Creates a new particle without position, velocity and -inf as fitness """ return Particle(numpy.array([[]]*paramCount), numpy.array([[]]*paramCount), -numpy.Inf)
python
{ "resource": "" }
q14325
Particle.copy
train
def copy(self): """ Creates a copy of itself """ return Particle(copy(self.position), copy(self.velocity), self.fitness)
python
{ "resource": "" }
q14326
moments
train
def moments(I_xy_input, x, y): """ compute quadrupole moments from a light distribution :param I_xy: light distribution :param x: x-coordinates of I_xy :param y: y-coordinates of I_xy :return: Q_xx, Q_xy, Q_yy """ I_xy = copy.deepcopy(I_xy_input) background = np.minimum(0, np.min(I_...
python
{ "resource": "" }
q14327
ellipticities
train
def ellipticities(I_xy, x, y): """ compute ellipticities of a light distribution :param I_xy: :param x: :param y: :return: """ Q_xx, Q_xy, Q_yy, bkg = moments(I_xy, x, y) norm = Q_xx + Q_yy + 2 * np.sqrt(Q_xx*Q_yy - Q_xy**2) e1 = (Q_xx - Q_yy) / norm e2 = 2 * Q_xy / norm ...
python
{ "resource": "" }
q14328
MultiPlane.alpha
train
def alpha(self, theta_x, theta_y, kwargs_lens, k=None): """ reduced deflection angle :param theta_x: angle in x-direction :param theta_y: angle in y-direction :param kwargs_lens: lens model kwargs :return: """ beta_x, beta_y = self.ray_shooting(theta_x, t...
python
{ "resource": "" }
q14329
MultiPlane.hessian
train
def hessian(self, theta_x, theta_y, kwargs_lens, k=None, diff=0.00000001): """ computes the hessian components f_xx, f_yy, f_xy from f_x and f_y with numerical differentiation :param theta_x: x-position (preferentially arcsec) :type theta_x: numpy array :param theta_y: y-positio...
python
{ "resource": "" }
q14330
MultiPlane._co_moving2angle_source
train
def _co_moving2angle_source(self, x, y): """ special case of the co_moving2angle definition at the source redshift :param x: :param y: :return: """ T_z = self._T_z_source theta_x = x / T_z theta_y = y / T_z return theta_x, theta_y
python
{ "resource": "" }
q14331
MultiPlane._ray_step
train
def _ray_step(self, x, y, alpha_x, alpha_y, delta_T): """ ray propagation with small angle approximation :param x: co-moving x-position :param y: co-moving y-position :param alpha_x: deflection angle in x-direction at (x, y) :param alpha_y: deflection angle in y-directio...
python
{ "resource": "" }
q14332
MultiPlane._add_deflection
train
def _add_deflection(self, x, y, alpha_x, alpha_y, kwargs_lens, idex): """ adds the pyhsical deflection angle of a single lens plane to the deflection field :param x: co-moving distance at the deflector plane :param y: co-moving distance at the deflector plane :param alpha_x: phy...
python
{ "resource": "" }
q14333
SinglePlane.mass_3d
train
def mass_3d(self, r, kwargs, bool_list=None): """ computes the mass within a 3d sphere of radius r :param r: radius (in angular units) :param kwargs: list of keyword arguments of lens model parameters matching the lens model classes :param bool_list: list of bools that are part ...
python
{ "resource": "" }
q14334
Filters.close_ns
train
def close_ns(symbol): '''generates a closing names statement from a symbol''' closing = ' '.join(['}' for x in symbol.module.name_parts]) name = '::'.join(symbol.module.name_parts) return '{0} // namespace {1}'.format(closing, name)
python
{ "resource": "" }
q14335
app
train
def app(config, src, dst, features, reload, force): """Takes several files or directories as src and generates the code in the given dst directory.""" config = Path(config) if reload: argv = sys.argv.copy() argv.remove('--reload') monitor(config.dirname(), src, dst, argv) els...
python
{ "resource": "" }
q14336
reload
train
def reload(script, input, output): """ reloads the generator script when the script files or the input files changes """ script = Path(script).expand().abspath() output = Path(output).expand().abspath() input = input if isinstance(input, (list, tuple)) else [input] output.makedirs_p() ...
python
{ "resource": "" }
q14337
_script_reload
train
def _script_reload(script, input, output): """run the named generator and monitor the input and generator folder""" input = [Path(entry).expand().abspath() for entry in input] output = Path(output).expand().abspath() cmd = 'python3 {0} {1} {2}'.format(script, ' '.join(input), output) event_handler =...
python
{ "resource": "" }
q14338
install
train
def install(editable): """install the script onto the system using pip3""" script_dir = str(Path(__file__).parent.abspath()) click.secho(script_dir, fg='blue') if editable: sh('pip3 install --editable {0} --upgrade'.format(script_dir)) else: sh('pip3 install {0} --upgrade'.format(scr...
python
{ "resource": "" }
q14339
merge
train
def merge(a, b): "merges b into a recursively if a and b are dicts" for key in b: if isinstance(a.get(key), dict) and isinstance(b.get(key), dict): merge(a[key], b[key]) else: a[key] = b[key] return a
python
{ "resource": "" }
q14340
Generator.get_template
train
def get_template(self, name): """Retrieves a single template file from the template loader""" source = name if name and name[0] is '/': source = name[1:] elif self.source is not None: source = '/'.join((self.source, name)) return self.env.get_template(sour...
python
{ "resource": "" }
q14341
Generator.render
train
def render(self, name, context): """Returns the rendered text from a single template file from the template loader using the given context data""" if Generator.strict: self.env.undefined = TestableUndefined else: self.env.undefined = Undefined template = s...
python
{ "resource": "" }
q14342
Generator.apply
train
def apply(self, template, context={}): context.update(self.context) """Return the rendered text of a template instance""" return self.env.from_string(template).render(context)
python
{ "resource": "" }
q14343
Generator.write
train
def write(self, file_path, template, context={}, preserve=False, force=False): """Using a template file name it renders a template into a file given a context """ if not file_path or not template: click.secho('source or target missing for document') return ...
python
{ "resource": "" }
q14344
RuleGenerator.process_rules
train
def process_rules(self, path: Path, system: System): """writes the templates read from the rules document""" self.context.update({ 'system': system, }) document = FileSystem.load_yaml(path, required=True) for module, rules in document.items(): click.secho(...
python
{ "resource": "" }
q14345
RuleGenerator._process_rules
train
def _process_rules(self, rules: dict, system: System): """ process a set of rules for a target """ self._source = None # reset the template source if not self._shall_proceed(rules): return self.context.update(rules.get('context', {})) self.path = rules.get('path', '')...
python
{ "resource": "" }
q14346
RuleGenerator._process_rule
train
def _process_rule(self, rule: dict, context: dict): """ process a single rule """ if not rule or not self._shall_proceed(rule): return self.context.update(context) self.context.update(rule.get('context', {})) self.path = rule.get('path', None) self.source = ru...
python
{ "resource": "" }
q14347
FileSystem._parse_document
train
def _parse_document(document: Path, system: System = None, profile=EProfile.FULL): """Parses a document and returns the resulting domain system :param path: document path to parse :param system: system to be used (optional) """ logger.debug('parse document: {0}'.format(document)...
python
{ "resource": "" }
q14348
FileSystem.merge_annotations
train
def merge_annotations(system, document): """Read a YAML document and for each root symbol identifier updates the tag information of that symbol """ if not Path(document).exists(): return meta = FileSystem.load_yaml(document) click.secho('merge: {0}'.format(doc...
python
{ "resource": "" }
q14349
FileSystem.parse
train
def parse(input, identifier: str = None, use_cache=False, clear_cache=True, pattern="*.qface", profile=EProfile.FULL): """Input can be either a file or directory or a list of files or directory. A directory will be parsed recursively. The function returns the resulting system. Stores the result ...
python
{ "resource": "" }
q14350
monitor
train
def monitor(args, watch): """ reloads the script given by argv when src files changes """ watch = watch if isinstance(watch, (list, tuple)) else [watch] watch = [Path(entry).expand().abspath() for entry in watch] event_handler = RunScriptChangeHandler(args) observer = Observer() for entr...
python
{ "resource": "" }
q14351
System.lookup
train
def lookup(self, name: str): '''lookup a symbol by fully qualified name.''' # <module> if name in self._moduleMap: return self._moduleMap[name] # <module>.<Symbol> (module_name, type_name, fragment_name) = self.split_typename(name) if not module_name and type_...
python
{ "resource": "" }
q14352
Symbol.add_tag
train
def add_tag(self, tag): """ add a tag to the tag list """ if tag not in self._tags: self._tags[tag] = dict()
python
{ "resource": "" }
q14353
Symbol.attribute
train
def attribute(self, tag, name): """ return attribute by tag and attribute name """ if tag in self._tags and name in self._tags[tag]: return self._tags[tag][name]
python
{ "resource": "" }
q14354
TypeSymbol.is_valid
train
def is_valid(self): '''checks if type is a valid type''' return (self.is_primitive and self.name) \ or (self.is_complex and self.name) \ or (self.is_list and self.nested) \ or (self.is_map and self.nested) \ or (self.is_model and self.nested)
python
{ "resource": "" }
q14355
TypeSymbol._resolve
train
def _resolve(self): """resolve the type symbol from name by doing a lookup""" self.__is_resolved = True if self.is_complex: type = self.nested if self.nested else self type.__reference = self.module.lookup(type.name)
python
{ "resource": "" }
q14356
Module.lookup
train
def lookup(self, name: str, fragment: str = None): '''lookup a symbol by name. If symbol is not local it will be looked up system wide''' if name in self._contentMap: symbol = self._contentMap[name] if fragment: return symbol._contentMap[fragment] ...
python
{ "resource": "" }
q14357
jsonify
train
def jsonify(symbol): """ returns json format for symbol """ try: # all symbols have a toJson method, try it return json.dumps(symbol.toJson(), indent=' ') except AttributeError: pass return json.dumps(symbol, indent=' ')
python
{ "resource": "" }
q14358
hash
train
def hash(symbol, hash_type='sha1'): """ create a hash code from symbol """ code = hashlib.new(hash_type) code.update(str(symbol).encode('utf-8')) return code.hexdigest()
python
{ "resource": "" }
q14359
sh
train
def sh(args, **kwargs): """ runs the given cmd as shell command """ if isinstance(args, str): args = args.split() if not args: return click.echo('$ {0}'.format(' '.join(args))) try: return subprocess.check_call(args, **kwargs) except subprocess.CalledProcessError ...
python
{ "resource": "" }
q14360
parse_doc
train
def parse_doc(s): """ parse a comment in the format of JavaDoc and returns an object, where each JavaDoc tag is a property of the object. """ if not s: return doc = DocObject() tag = None s = s[3:-2] # remove '/**' and '*/' for line in s.splitlines(): line = line.lstrip(...
python
{ "resource": "" }
q14361
IsUserInUrl.has_permission
train
def has_permission(self, request, view): """ Returns true if the current request is by the user themselves. Note: a 404 is returned for non-staff instead of a 403. This is to prevent users from being able to detect the existence of accounts. """ url_username = request.pa...
python
{ "resource": "" }
q14362
BigAutoField.db_type
train
def db_type(self, connection): """ The type of the field to insert into the database. """ conn_module = type(connection).__module__ if "mysql" in conn_module: return "bigint AUTO_INCREMENT" elif "postgres" in conn_module: return "bigserial" ...
python
{ "resource": "" }
q14363
BlockCompletionManager.submit_completion
train
def submit_completion(self, user, course_key, block_key, completion): """ Update the completion value for the specified record. Parameters: * user (django.contrib.auth.models.User): The user for whom the completion is being submitted. * course_key (opaque_k...
python
{ "resource": "" }
q14364
BlockCompletionManager.submit_batch_completion
train
def submit_batch_completion(self, user, course_key, blocks): """ Performs a batch insertion of completion objects. Parameters: * user (django.contrib.auth.models.User): The user for whom the completions are being submitted. * course_key (opaque_keys.edx.key...
python
{ "resource": "" }
q14365
BlockCompletion.full_block_key
train
def full_block_key(self): """ Returns the "correct" usage key value with the run filled in. """ if self.block_key.run is None: # pylint: disable=unexpected-keyword-arg, no-value-for-parameter return self.block_key.replace(course_key=self.course_key) return...
python
{ "resource": "" }
q14366
BlockCompletion.get_course_completions
train
def get_course_completions(cls, user, course_key): """ Returns a dictionary mapping BlockKeys to completion values for all BlockCompletion records for the given user and course_key. Return value: dict[BlockKey] = float """ user_course_completions = cls.user_c...
python
{ "resource": "" }
q14367
BlockCompletion.user_course_completion_queryset
train
def user_course_completion_queryset(cls, user, course_key): """ Returns a Queryset of completions for a given user and course_key. """ return cls.objects.filter(user=user, course_key=course_key)
python
{ "resource": "" }
q14368
scorable_block_completion
train
def scorable_block_completion(sender, **kwargs): # pylint: disable=unused-argument """ When a problem is scored, submit a new BlockCompletion for that block. """ if not waffle.waffle().is_enabled(waffle.ENABLE_COMPLETION_TRACKING): return course_key = CourseKey.from_string(kwargs['course_id...
python
{ "resource": "" }
q14369
CompletionBatchView._validate_and_parse
train
def _validate_and_parse(self, batch_object): """ Performs validation on the batch object to make sure it is in the proper format. Parameters: * batch_object: The data provided to a POST. The expected format is the following: { "username": "username", ...
python
{ "resource": "" }
q14370
CompletionBatchView._validate_and_parse_course_key
train
def _validate_and_parse_course_key(self, course_key): """ Returns a validated parsed CourseKey deserialized from the given course_key. """ try: return CourseKey.from_string(course_key) except InvalidKeyError: raise ValidationError(_("Invalid course key: {}...
python
{ "resource": "" }
q14371
CompletionBatchView._validate_and_parse_block_key
train
def _validate_and_parse_block_key(self, block_key, course_key_obj): """ Returns a validated, parsed UsageKey deserialized from the given block_key. """ try: block_key_obj = UsageKey.from_string(block_key) except InvalidKeyError: raise ValidationError(_("In...
python
{ "resource": "" }
q14372
CompletionBatchView.post
train
def post(self, request, *args, **kwargs): # pylint: disable=unused-argument """ Inserts a batch of completions. REST Endpoint Format: { "username": "username", "course_key": "course-key", "blocks": { "block_key1": 0.0, "block_key2":...
python
{ "resource": "" }
q14373
CompletionService.get_completions
train
def get_completions(self, candidates): """ Given an iterable collection of block_keys in the course, returns a mapping of the block_keys to the present completion values of their associated blocks. If a completion is not found for a given block in the current course, 0.0...
python
{ "resource": "" }
q14374
CompletionService.can_mark_block_complete_on_view
train
def can_mark_block_complete_on_view(self, block): """ Returns True if the xblock can be marked complete on view. This is true of any non-customized, non-scorable, completable block. """ return ( XBlockCompletionMode.get_mode(block) == XBlockCompletionMode.COMPLETABLE ...
python
{ "resource": "" }
q14375
CompletionService.blocks_to_mark_complete_on_view
train
def blocks_to_mark_complete_on_view(self, blocks): """ Returns a set of blocks which should be marked complete on view and haven't been yet. """ blocks = {block for block in blocks if self.can_mark_block_complete_on_view(block)} completions = self.get_completions({block.location ...
python
{ "resource": "" }
q14376
CompletionService.submit_group_completion
train
def submit_group_completion(self, block_key, completion, users=None, user_ids=None): """ Submit a completion for a group of users. Arguments: block_key (opaque_key.edx.keys.UsageKey): The block to submit completions for. completion (float): A value in the range [0.0, 1....
python
{ "resource": "" }
q14377
CompletionService.submit_completion
train
def submit_completion(self, block_key, completion): """ Submit a completion for the service user and course. Returns a (BlockCompletion, bool) where the boolean indicates whether the given BlockCompletion was newly created. """ return BlockCompletion.objects.submit_compl...
python
{ "resource": "" }
q14378
throw_if_bad_response
train
def throw_if_bad_response(response): """Throw an exception if the Cerberus response is not successful.""" try: response.raise_for_status() except RequestException: try: msg = 'Response code: {}; response body:\n{}'.format(response.status_code, json.dumps(response.json(), indent=2...
python
{ "resource": "" }
q14379
_initialize_client_from_environment
train
def _initialize_client_from_environment(): ''' Initialize a KeenClient instance using environment variables. ''' global _client, project_id, write_key, read_key, master_key, base_url if _client is None: # check environment for project ID and keys project_id = project_id or os.environ.get("K...
python
{ "resource": "" }
q14380
count
train
def count(event_collection, timeframe=None, timezone=None, interval=None, filters=None, group_by=None, order_by=None, max_age=None, limit=None): """ Performs a count query Counts the number of events that meet the given criteria. :param event_collection: string, the name of the collection to que...
python
{ "resource": "" }
q14381
sum
train
def sum(event_collection, target_property, timeframe=None, timezone=None, interval=None, filters=None, group_by=None, order_by=None, max_age=None, limit=None): """ Performs a sum query Adds the values of a target property for events that meet the given criteria. :param event_collection: string, th...
python
{ "resource": "" }
q14382
multi_analysis
train
def multi_analysis(event_collection, analyses, timeframe=None, interval=None, timezone=None, filters=None, group_by=None, order_by=None, max_age=None, limit=None): """ Performs a multi-analysis query Returns a dictionary of analysis results. :param event_collection: string, the name of ...
python
{ "resource": "" }
q14383
check_error
train
def check_error(status): """Set a generic function as the restype attribute of all OpenJPEG functions that return a BOOL_TYPE value. This way we do not have to check for error status in each wrapping function and an exception will always be appropriately raised. """ global ERROR_MSG_LST if ...
python
{ "resource": "" }
q14384
decode
train
def decode(codec, stream, image): """Reads an entire image. Wraps the openjp2 library function opj_decode. Parameters ---------- codec : CODEC_TYPE The JPEG2000 codec stream : STREAM_TYPE_P The stream to decode. image : ImageType Output image structure. Raises ...
python
{ "resource": "" }
q14385
decode_tile_data
train
def decode_tile_data(codec, tidx, data, data_size, stream): """Reads tile data. Wraps the openjp2 library function opj_decode_tile_data. Parameters ---------- codec : CODEC_TYPE The JPEG2000 codec tile_index : int The index of the tile being decoded data : array Hol...
python
{ "resource": "" }
q14386
destroy_codec
train
def destroy_codec(codec): """Destroy a decompressor handle. Wraps the openjp2 library function opj_destroy_codec. Parameters ---------- codec : CODEC_TYPE Decompressor handle to destroy. """ OPENJP2.opj_destroy_codec.argtypes = [CODEC_TYPE] OPENJP2.opj_destroy_codec.restype = c...
python
{ "resource": "" }
q14387
encode
train
def encode(codec, stream): """Wraps openjp2 library function opj_encode. Encode an image into a JPEG 2000 codestream. Parameters ---------- codec : CODEC_TYPE The jpeg2000 codec. stream : STREAM_TYPE_P The stream to which data is written. Raises ------ RuntimeError...
python
{ "resource": "" }
q14388
get_decoded_tile
train
def get_decoded_tile(codec, stream, imagep, tile_index): """get the decoded tile from the codec Wraps the openjp2 library function opj_get_decoded_tile. Parameters ---------- codec : CODEC_TYPE The jpeg2000 codec. stream : STREAM_TYPE_P The input stream. image : ImageType ...
python
{ "resource": "" }
q14389
end_compress
train
def end_compress(codec, stream): """End of compressing the current image. Wraps the openjp2 library function opj_end_compress. Parameters ---------- codec : CODEC_TYPE Compressor handle. stream : STREAM_TYPE_P Output stream buffer. Raises ------ RuntimeError ...
python
{ "resource": "" }
q14390
end_decompress
train
def end_decompress(codec, stream): """End of decompressing the current image. Wraps the openjp2 library function opj_end_decompress. Parameters ---------- codec : CODEC_TYPE Compressor handle. stream : STREAM_TYPE_P Output stream buffer. Raises ------ RuntimeError ...
python
{ "resource": "" }
q14391
image_destroy
train
def image_destroy(image): """Deallocate any resources associated with an image. Wraps the openjp2 library function opj_image_destroy. Parameters ---------- image : ImageType pointer Image resource to be disposed. """ OPENJP2.opj_image_destroy.argtypes = [ctypes.POINTER(ImageType)] ...
python
{ "resource": "" }
q14392
read_header
train
def read_header(stream, codec): """Decodes an image header. Wraps the openjp2 library function opj_read_header. Parameters ---------- stream: STREAM_TYPE_P The JPEG2000 stream. codec: codec_t The JPEG2000 codec to read. Returns ------- imagep : reference to ImageT...
python
{ "resource": "" }
q14393
read_tile_header
train
def read_tile_header(codec, stream): """Reads a tile header. Wraps the openjp2 library function opj_read_tile_header. Parameters ---------- codec : codec_t The JPEG2000 codec to read. stream : STREAM_TYPE_P The JPEG2000 stream. Returns ------- tile_index : int ...
python
{ "resource": "" }
q14394
set_decode_area
train
def set_decode_area(codec, image, start_x=0, start_y=0, end_x=0, end_y=0): """Wraps openjp2 library function opj_set_decode area. Sets the given area to be decoded. This function should be called right after read_header and before any tile header reading. Parameters ---------- codec : CODEC_T...
python
{ "resource": "" }
q14395
set_default_decoder_parameters
train
def set_default_decoder_parameters(): """Wraps openjp2 library function opj_set_default_decoder_parameters. Sets decoding parameters to default values. Returns ------- dparam : DecompressionParametersType Decompression parameters. """ ARGTYPES = [ctypes.POINTER(DecompressionParamet...
python
{ "resource": "" }
q14396
set_default_encoder_parameters
train
def set_default_encoder_parameters(): """Wraps openjp2 library function opj_set_default_encoder_parameters. Sets encoding parameters to default values. That means lossless 1 tile size of precinct : 2^15 x 2^15 (means 1 precinct) size of code-block : 64 x 64 number of r...
python
{ "resource": "" }
q14397
set_error_handler
train
def set_error_handler(codec, handler, data=None): """Wraps openjp2 library function opj_set_error_handler. Set the error handler use by openjpeg. Parameters ---------- codec : CODEC_TYPE Codec initialized by create_compress function. handler : python function The callback funct...
python
{ "resource": "" }
q14398
set_info_handler
train
def set_info_handler(codec, handler, data=None): """Wraps openjp2 library function opj_set_info_handler. Set the info handler use by openjpeg. Parameters ---------- codec : CODEC_TYPE Codec initialized by create_compress function. handler : python function The callback function...
python
{ "resource": "" }
q14399
set_warning_handler
train
def set_warning_handler(codec, handler, data=None): """Wraps openjp2 library function opj_set_warning_handler. Set the warning handler use by openjpeg. Parameters ---------- codec : CODEC_TYPE Codec initialized by create_compress function. handler : python function The callback...
python
{ "resource": "" }