code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def test_post_bookmark_with_invalid_data(self): <NEW_LINE> <INDENT> response = self.send_post( client=self.client, url=reverse('bookmarks'), data={'usage_id': 'invalid'}, expected_status=400 ) <NEW_LINE> self.assertEqual(response.data['user_message'], u'An error has occurred. Please try again.') <NEW_LINE> response = self.send_post( client=self.client, url=reverse('bookmarks'), data={'course_id': 'invalid'}, expected_status=400 ) <NEW_LINE> self.assertEqual(response.data['user_message'], u'An error has occurred. Please try again.') <NEW_LINE> self.assertEqual(response.data['developer_message'], u'Parameter usage_id not provided.') <NEW_LINE> with self.assertNumQueries(7): <NEW_LINE> <INDENT> response = self.send_post( client=self.client, url=reverse('bookmarks'), data={}, expected_status=400 ) <NEW_LINE> <DEDENT> self.assertEqual(response.data['user_message'], u'An error has occurred. Please try again.') <NEW_LINE> self.assertEqual(response.data['developer_message'], u'No data provided.') | Test that posting a bookmark for a block with invalid usage id returns a 400.
Scenarios:
1) Invalid usage id.
2) Without usage id.
3) With empty request.data | 625941c155399d3f0558862b |
def register_extensions(app): <NEW_LINE> <INDENT> db.init_app(app) <NEW_LINE> db.create_all(app=app) <NEW_LINE> provider.init_app(app) <NEW_LINE> provider._validator = RequestValidator() | Registers application extensions. | 625941c199cbb53fe6792b5f |
@sdc_min_version('3.19.0') <NEW_LINE> @database('oracle') <NEW_LINE> @pytest.mark.parametrize('buffer_locally', [True, False]) <NEW_LINE> @pytest.mark.parametrize('dictionary_source', ['DICT_FROM_REDO_LOGS', 'DICT_FROM_ONLINE_CATALOG']) <NEW_LINE> def test_disable_continuous_mine(sdc_builder, sdc_executor, database, keep_data, buffer_locally, dictionary_source): <NEW_LINE> <INDENT> table_name = f'STF_{get_random_string(string.ascii_uppercase)}' <NEW_LINE> num_records = 10 <NEW_LINE> connection = database.engine.connect() <NEW_LINE> try: <NEW_LINE> <INDENT> logger.info('Creating table %s', table_name) <NEW_LINE> connection.execute(f'CREATE TABLE {table_name} (ID NUMBER PRIMARY KEY)') <NEW_LINE> initial_scn = _get_last_scn(connection) <NEW_LINE> logger.info('Building pipeline') <NEW_LINE> builder = sdc_builder.get_pipeline_builder() <NEW_LINE> oracle_cdc = _get_oracle_cdc_client_origin(connection=connection, database=database, sdc_builder=sdc_builder, pipeline_builder=builder, buffer_locally=buffer_locally, src_table_name=table_name, initial_change='SCN', start_scn=initial_scn, dictionary_source=dictionary_source, disable_continuous_mine=True) <NEW_LINE> wiretap = builder.add_wiretap() <NEW_LINE> oracle_cdc >> wiretap.destination <NEW_LINE> pipeline = builder.build().configure_for_environment(database) <NEW_LINE> sdc_executor.add_pipeline(pipeline) <NEW_LINE> logger.info('Inserting data into %s', table_name) <NEW_LINE> input_values = list(range(num_records)) <NEW_LINE> for val in input_values: <NEW_LINE> <INDENT> connection.execute(f'INSERT INTO {table_name} VALUES ({val})') <NEW_LINE> <DEDENT> sdc_executor.start_pipeline(pipeline).wait_for_pipeline_output_records_count(num_records, timeout_sec=360) <NEW_LINE> sdc_executor.stop_pipeline(pipeline) <NEW_LINE> output_values = [rec.field['ID'].value for rec in wiretap.output_records] <NEW_LINE> assert input_values == output_values <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> if not keep_data: <NEW_LINE> <INDENT> logger.info('Dropping table %s in %s database ...', table_name, database.type) <NEW_LINE> connection.execute(f'DROP TABLE {table_name}') | Simple test to check "Disable Continuous Mine" stage option.
The test just inserts a few records in the test table and check they are successfully consumed by Oracle
CDC. This is tested with different configurations which affect how LogMiner sessions are set.
Pipeline: oracle_cdc >> wiretap | 625941c13317a56b86939bd6 |
def enable_callback_tracebacks(flag): <NEW_LINE> <INDENT> pass | By default you will not get any tracebacks in user-defined functions,
aggregates, converters, authorizer callbacks etc.
:type flag: bool
:rtype: None | 625941c1a8ecb033257d3046 |
def get_account_ids_from_match(*matches: dict): <NEW_LINE> <INDENT> account_ids = [] <NEW_LINE> for match in matches: <NEW_LINE> <INDENT> for participant in match['participantIdentities']: <NEW_LINE> <INDENT> account_ids.append(participant['player']['accountId']) <NEW_LINE> <DEDENT> <DEDENT> return list(set(account_ids)) | From an initial list of matches, find all account ids. | 625941c1dc8b845886cb54ac |
def predict_class_local(self, X): <NEW_LINE> <INDENT> result = callBigDlFunc(self.bigdl_type, "predictLocalClass", self.value, self._to_jtensors(X)) <NEW_LINE> return np.stack(result) | :param X: X can be a ndarray or list of ndarray if the model has multiple inputs.
The first dimension of X should be batch.
:return: a ndarray as the prediction result. | 625941c17b25080760e393d2 |
def backupToZip(folder): <NEW_LINE> <INDENT> folder = os.path.abspath(folder) <NEW_LINE> number = 1 <NEW_LINE> while True: <NEW_LINE> <INDENT> zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip' <NEW_LINE> if not os.path.exists(zipFilename): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> number += 1 <NEW_LINE> <DEDENT> print('Создается файл %s...' % (zipFilename)) <NEW_LINE> backupZip = zipfile.ZipFile(zipFilename, 'w') <NEW_LINE> for foldername, subfolders, filenames in os.walk(folder): <NEW_LINE> <INDENT> print('Добавления файла из папки %s...' % (foldername)) <NEW_LINE> backupZip.write(foldername) <NEW_LINE> for filename in filenames: <NEW_LINE> <INDENT> newBase = os.path.basename(folder) + '_' <NEW_LINE> if filename.startswith(newBase) and filename.endswith('.zip'): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> backupZip.write(os.path.join(foldername, filename)) <NEW_LINE> <DEDENT> <DEDENT> backupZip.close() <NEW_LINE> print('Все готово!!!') | создает резервную копию всего содержимого папки folder | 625941c1e76e3b2f99f3a788 |
def cmyk(c, m, y, k): <NEW_LINE> <INDENT> rgb_scale = 1.0 <NEW_LINE> cmyk_scale = 1.0 <NEW_LINE> r = rgb_scale * (1.0 - (c + k) / float(cmyk_scale)) <NEW_LINE> g = rgb_scale * (1.0 - (m + k) / float(cmyk_scale)) <NEW_LINE> b = rgb_scale * (1.0 - (y + k) / float(cmyk_scale)) <NEW_LINE> return r, g, b | this was taken from https://stackoverflow.com/questions/14088375/how-can-i-convert-rgb-to-cmyk-and-vice-versa-in-python | 625941c1d6c5a10208143fc1 |
def spawnlp(mode, file, *args): <NEW_LINE> <INDENT> return spawnvp(mode, file, args) | spawnlp(mode, file, *args) -> integer
Execute file (which is looked for along $PATH) with arguments from
args in a subprocess with the supplied environment.
If mode == P_NOWAIT return the pid of the process.
If mode == P_WAIT return the process's exit code if it exits normally;
otherwise return -SIG, where SIG is the signal that killed it. | 625941c1a8370b7717052819 |
def redondear(numero, full_scale): <NEW_LINE> <INDENT> if abs(numero) <= 0.001 * abs(full_scale): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if numero < 0: <NEW_LINE> <INDENT> negativo = True <NEW_LINE> numero = numero * (-1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> negativo = False <NEW_LINE> <DEDENT> numero_s = str(numero) <NEW_LINE> longitud = len(numero_s) <NEW_LINE> coma = numero_s.find('.') <NEW_LINE> n = 0 <NEW_LINE> while True: <NEW_LINE> <INDENT> digito = numero_s[n] <NEW_LINE> if digito != ".": <NEW_LINE> <INDENT> if int(digito) > 0: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> n += 1 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> n += 1 <NEW_LINE> <DEDENT> <DEDENT> if digito == '1': <NEW_LINE> <INDENT> decimales = 4 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> decimales = 3 <NEW_LINE> <DEDENT> if coma <= n: <NEW_LINE> <INDENT> longitud -= 1 <NEW_LINE> n -= 1 <NEW_LINE> <DEDENT> if longitud < 4: <NEW_LINE> <INDENT> if negativo: <NEW_LINE> <INDENT> numero = numero * (-1) <NEW_LINE> <DEDENT> return numero <NEW_LINE> <DEDENT> elif n == 0 and coma == -1: <NEW_LINE> <INDENT> cifras = decimales - longitud <NEW_LINE> <DEDENT> elif int(digito) > 1 and n > 0: <NEW_LINE> <INDENT> cifras = decimales + n - 1 <NEW_LINE> <DEDENT> elif int(digito) == 1 and n > 0: <NEW_LINE> <INDENT> cifras = decimales + n - 1 <NEW_LINE> <DEDENT> elif int(digito) == 1 and n == 0: <NEW_LINE> <INDENT> if coma > 1: <NEW_LINE> <INDENT> cifras = decimales - n - coma <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cifras = decimales - n - 1 <NEW_LINE> <DEDENT> <DEDENT> elif int(digito) > 1 and n == 0: <NEW_LINE> <INDENT> cifras = decimales - coma <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if negativo: <NEW_LINE> <INDENT> numero = numero * (-1) <NEW_LINE> <DEDENT> return numero <NEW_LINE> <DEDENT> resultado = round(numero, cifras) <NEW_LINE> if float(resultado).is_integer(): <NEW_LINE> <INDENT> resultado = int(resultado) <NEW_LINE> <DEDENT> if negativo: <NEW_LINE> <INDENT> resultado = resultado * (-1) <NEW_LINE> <DEDENT> return resultado | Función para redondear el valor pasado por argumento | 625941c10a366e3fb873e791 |
def update_state(tenant, state_code, state_name): <NEW_LINE> <INDENT> with DBConnection(tenant) as connection: <NEW_LINE> <INDENT> dim_inst_hier = connection.get_table("dim_inst_hier") <NEW_LINE> fact_asmt = connection.get_table("fact_asmt_outcome") <NEW_LINE> fact_asmt_vw = connection.get_table("fact_asmt_outcome_vw") <NEW_LINE> fact_block_asmt_outcome = connection.get_table("fact_block_asmt_outcome") <NEW_LINE> fact_student_reg = connection.get_table("student_reg") <NEW_LINE> tables = [dim_inst_hier, fact_asmt, fact_asmt_vw, fact_student_reg, fact_block_asmt_outcome] <NEW_LINE> for table in tables: <NEW_LINE> <INDENT> stmt = update(table).values(state_code=state_code) <NEW_LINE> connection.execute(stmt) | Update state_code in all the tables for a tenant | 625941c1a934411ee375160b |
def get_nonlocal_ip(host, subnet=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ailist = socket.getaddrinfo(host, None) <NEW_LINE> <DEDENT> except socket.gaierror: <NEW_LINE> <INDENT> raise exc.UnableToResolveError(host) <NEW_LINE> <DEDENT> for ai in ailist: <NEW_LINE> <INDENT> ip = ai[4][0] <NEW_LINE> if subnet and ip_in_subnet(ip, subnet): <NEW_LINE> <INDENT> LOG.info('found ip (%s) for host (%s) to be in cluster subnet (%s)' % ( ip, host, subnet,) ) <NEW_LINE> return ip <NEW_LINE> <DEDENT> if not ip.startswith('127.'): <NEW_LINE> <INDENT> if subnet: <NEW_LINE> <INDENT> LOG.warning('could not match ip (%s) for host (%s) for cluster subnet (%s)' % ( ip, host, subnet,) ) <NEW_LINE> <DEDENT> return ip <NEW_LINE> <DEDENT> <DEDENT> raise exc.UnableToResolveError(host) | Search result of getaddrinfo() for a non-localhost-net address | 625941c1711fe17d825422e8 |
def get_course_run_detail(site, course_run_key): <NEW_LINE> <INDENT> resource = "course_runs" <NEW_LINE> cache_key = get_cache_key( site_domain=site.domain, resource="{}-{}".format(resource, course_run_key) ) <NEW_LINE> return _get_discovery_response(site, cache_key, resource, course_run_key) | Return the course run information of given course_run_key from Discovery Service and cache.
Arguments:
site (Site): Site object containing Site Configuration data
course_run_key (str): Course run key
Returns:
dict: CourseRun information received from Discovery API | 625941c11b99ca400220aa2a |
def display_genre(self): <NEW_LINE> <INDENT> return ', '.join(genre.name for genre in self.genre.all()[:3]) | Create a string for the genre
:return: | 625941c173bcbd0ca4b2bfef |
def _register_controllers(self, ext): <NEW_LINE> <INDENT> handler = ext.obj <NEW_LINE> LOG.debug("Running _register_controllers on %s", ext.obj) <NEW_LINE> for extension in handler.get_controller_extensions(): <NEW_LINE> <INDENT> ext_name = extension.extension.name <NEW_LINE> collection = extension.collection <NEW_LINE> controller = extension.controller <NEW_LINE> if collection not in self.resources: <NEW_LINE> <INDENT> LOG.warning(_('Extension %(ext_name)s: Cannot extend ' 'resource %(collection)s: No such resource'), {'ext_name': ext_name, 'collection': collection}) <NEW_LINE> continue <NEW_LINE> <DEDENT> LOG.debug(_('Extension %(ext_name)s extending resource: ' '%(collection)s'), {'ext_name': ext_name, 'collection': collection}) <NEW_LINE> resource = self.resources[collection] <NEW_LINE> resource.register_actions(controller) <NEW_LINE> resource.register_extensions(controller) | Register controllers defined by the extensions
Extensions define what resources they want to add through
a get_controller_extensions function | 625941c14e696a04525c93c5 |
def shortStr(self): <NEW_LINE> <INDENT> return "%s %s '%s'" % (self.startDateTime.strftime("%Y-%m-%d %a"), self.startDateTime.time(), self.summary) | Return a short string to identify the meeting uniquely | 625941c1091ae35668666edb |
def apply_recommendation(self, customer_id, operations, partial_failure=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): <NEW_LINE> <INDENT> if 'apply_recommendation' not in self._inner_api_calls: <NEW_LINE> <INDENT> self._inner_api_calls[ 'apply_recommendation'] = google.api_core.gapic_v1.method.wrap_method( self.transport.apply_recommendation, default_retry=self._method_configs['ApplyRecommendation']. retry, default_timeout=self. _method_configs['ApplyRecommendation'].timeout, client_info=self._client_info, ) <NEW_LINE> <DEDENT> request = recommendation_service_pb2.ApplyRecommendationRequest( customer_id=customer_id, operations=operations, partial_failure=partial_failure, ) <NEW_LINE> return self._inner_api_calls['apply_recommendation']( request, retry=retry, timeout=timeout, metadata=metadata) | Applies given recommendations with corresponding apply parameters.
Args:
customer_id (str): The ID of the customer with the recommendation.
operations (list[Union[dict, ~google.ads.googleads_v1.types.ApplyRecommendationOperation]]): The list of operations to apply recommendations. If
partial\_failure=false all recommendations should be of the same type
There is a limit of 100 operations per request.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.ads.googleads_v1.types.ApplyRecommendationOperation`
partial_failure (bool): If true, successful operations will be carried out and invalid
operations will return errors. If false, operations will be carried
out as a transaction if and only if they are all valid.
Default is false.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.ads.googleads_v1.types.ApplyRecommendationResponse` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid. | 625941c107d97122c41787ff |
def insert_target(self): <NEW_LINE> <INDENT> if self.target['row'] is not None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> columns = self.target['connection'].get_mandatory_columns(self.database['table']) <NEW_LINE> columns.append(self.database['column']) <NEW_LINE> columns = set(columns) <NEW_LINE> values = [] <NEW_LINE> placeholders = [] <NEW_LINE> for column in columns: <NEW_LINE> <INDENT> values.append(self.target['connection'].adapt_param(self.source['row'][column])) <NEW_LINE> placeholders.append('%s') <NEW_LINE> <DEDENT> logging.info('inserting a minimal row into target database.. ') <NEW_LINE> cur = self.target['connection'].cursor() <NEW_LINE> insert_sql = 'insert into "{0}" ("{1}") values ({2})'.format( self.database['table'], '", "'.join(columns), ', '.join(placeholders) ) <NEW_LINE> cur.execute(insert_sql, tuple(values)) <NEW_LINE> if self.target['connection'].affected_rows(cur) != 1: <NEW_LINE> <INDENT> cur.close() <NEW_LINE> self._error('somehow we\'ve inserted multiple rows') <NEW_LINE> <DEDENT> self.target['row'] = self._get_row(self.target) <NEW_LINE> self.target['new_insert'] = True | insert as little data as possible into the target database, if nothing
exists there already. This allows us to reselect and continue as normal | 625941c124f1403a92600ae1 |
@bind_hass <NEW_LINE> def execute(hass, filename, source, data=None): <NEW_LINE> <INDENT> compiled = compile_restricted_exec(source, filename=filename) <NEW_LINE> if compiled.errors: <NEW_LINE> <INDENT> _LOGGER.error( "Error loading script %s: %s", filename, ", ".join(compiled.errors) ) <NEW_LINE> return <NEW_LINE> <DEDENT> if compiled.warnings: <NEW_LINE> <INDENT> _LOGGER.warning( "Warning loading script %s: %s", filename, ", ".join(compiled.warnings) ) <NEW_LINE> <DEDENT> def protected_getattr(obj, name, default=None): <NEW_LINE> <INDENT> if name.startswith("async_"): <NEW_LINE> <INDENT> raise ScriptError("Not allowed to access async methods") <NEW_LINE> <DEDENT> if ( obj is hass and name not in ALLOWED_HASS or obj is hass.bus and name not in ALLOWED_EVENTBUS or obj is hass.states and name not in ALLOWED_STATEMACHINE or obj is hass.services and name not in ALLOWED_SERVICEREGISTRY or obj is dt_util and name not in ALLOWED_DT_UTIL or obj is datetime and name not in ALLOWED_DATETIME or isinstance(obj, TimeWrapper) and name not in ALLOWED_TIME ): <NEW_LINE> <INDENT> raise ScriptError(f"Not allowed to access {obj.__class__.__name__}.{name}") <NEW_LINE> <DEDENT> return getattr(obj, name, default) <NEW_LINE> <DEDENT> extra_builtins = { "datetime": datetime, "sorted": sorted, "time": TimeWrapper(), "dt_util": dt_util, "min": min, "max": max, "sum": sum, "any": any, "all": all, "enumerate": enumerate, } <NEW_LINE> builtins = safe_builtins.copy() <NEW_LINE> builtins.update(utility_builtins) <NEW_LINE> builtins.update(limited_builtins) <NEW_LINE> builtins.update(extra_builtins) <NEW_LINE> logger = logging.getLogger(f"{__name__}.{filename}") <NEW_LINE> restricted_globals = { "__builtins__": builtins, "_print_": StubPrinter, "_getattr_": protected_getattr, "_write_": full_write_guard, "_getiter_": iter, "_getitem_": default_guarded_getitem, "_iter_unpack_sequence_": guarded_iter_unpack_sequence, "_unpack_sequence_": guarded_unpack_sequence, "hass": hass, "data": data or {}, "logger": logger, } <NEW_LINE> try: <NEW_LINE> <INDENT> _LOGGER.info("Executing %s: %s", filename, data) <NEW_LINE> exec(compiled.code, restricted_globals) <NEW_LINE> <DEDENT> except ScriptError as err: <NEW_LINE> <INDENT> logger.error("Error executing script: %s", err) <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> logger.exception("Error executing script: %s", err) | Execute Python source. | 625941c14e4d5625662d4353 |
def increment_values(self): <NEW_LINE> <INDENT> self.__current[:] = self.__future[:] | Increment field values | 625941c1442bda511e8be394 |
def active(self): <NEW_LINE> <INDENT> today = datetime.date.today() <NEW_LINE> return self.get_query_set().filter(Q(expiration_date__isnull=True) | Q(expiration_date__gte=today), publish_date__lte=today, is_active=True,) | Retrieves all active ads which have been published and have not yet expired. | 625941c1d53ae8145f87a1ec |
def __del__(self): <NEW_LINE> <INDENT> Rectangle.number_of_instances -= 1 <NEW_LINE> print('Bye rectangle...') | Privated instance method to delete | 625941c1e5267d203edcdc18 |
def print_sorted(self): <NEW_LINE> <INDENT> print(sorted(self)) | Fucntion that prints a sorted list | 625941c16fb2d068a760f014 |
def _read_quadrangle_annotations(csv_reader, classes, detect_text=False): <NEW_LINE> <INDENT> result = OrderedDict() <NEW_LINE> for line, row in enumerate(csv_reader, 1): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> img_file, x1, y1, x2, y2, x3, y3, x4, y4, class_name = row[:10] <NEW_LINE> if img_file not in result: <NEW_LINE> <INDENT> result[img_file] = [] <NEW_LINE> <DEDENT> if (x1, y1, x2, y2, x3, y3, x4, y4, class_name) == ('', '', '', '', '', '', '', '', ''): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> x1 = _parse(x1, int, 'line {}: malformed x1: {{}}'.format(line)) <NEW_LINE> y1 = _parse(y1, int, 'line {}: malformed y1: {{}}'.format(line)) <NEW_LINE> x2 = _parse(x2, int, 'line {}: malformed x2: {{}}'.format(line)) <NEW_LINE> y2 = _parse(y2, int, 'line {}: malformed y2: {{}}'.format(line)) <NEW_LINE> x3 = _parse(x3, int, 'line {}: malformed x3: {{}}'.format(line)) <NEW_LINE> y3 = _parse(y3, int, 'line {}: malformed y3: {{}}'.format(line)) <NEW_LINE> x4 = _parse(x4, int, 'line {}: malformed x4: {{}}'.format(line)) <NEW_LINE> y4 = _parse(y4, int, 'line {}: malformed y4: {{}}'.format(line)) <NEW_LINE> if detect_text: <NEW_LINE> <INDENT> if class_name == '###': <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> class_name = 'text' <NEW_LINE> <DEDENT> <DEDENT> if class_name not in classes: <NEW_LINE> <INDENT> raise ValueError(f'line {line}: unknown class name: \'{class_name}\' (classes: {classes})') <NEW_LINE> <DEDENT> result[img_file].append({'x1': x1, 'y1': y1, 'x2': x2, 'y2': y2, 'x3': x3, 'y3': y3, 'x4': x4, 'y4': y4, 'class': class_name}) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> raise_from(ValueError( f'line {line}: format should be \'img_file,x1,y1,x2,y2,x3,y3,x4,y4,class_name\' or \'img_file,,,,,\''), None) <NEW_LINE> <DEDENT> <DEDENT> return result | Read annotations from the csv_reader.
Args:
csv_reader: csv reader of args.annotations_path
classes: list[str] all the class names read from args.classes_path
Returns:
result: dict, dict is like {image_path: [{'x1': x1, 'y1': y1, 'x2': x2, 'y2': y2,
'x3': x3, 'y3': y3, 'x4': x4, 'y4': y4, 'class': class_name}]} | 625941c1377c676e91272122 |
def _ImageDimensions(images, dynamic_shape=False): <NEW_LINE> <INDENT> if dynamic_shape: <NEW_LINE> <INDENT> return array_ops.unpack(array_ops.shape(images)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return images.get_shape().as_list() | Returns the dimensions of an image tensor.
Args:
images: 4-D Tensor of shape [batch, height, width, channels]
dynamic_shape: Whether the input image has undertermined shape. If set to
`True`, shape information will be retrieved at run time. Default to
`False`.
Returns:
list of integers [batch, height, width, channels] | 625941c194891a1f4081ba21 |
def plot_inv_act_para(fo, ts, para, low_limit=1e-5, save=False, sfile=""): <NEW_LINE> <INDENT> act_grid = np.zeros((113,173)) <NEW_LINE> for nuc in fo.timestep_data[ts-1].inventory: <NEW_LINE> <INDENT> if float(nuc[para]) > 0: <NEW_LINE> <INDENT> if nuc[0][-1] == "n": <NEW_LINE> <INDENT> nuc[0] = nuc[0][:-1] <NEW_LINE> <DEDENT> a = nucname.anum(nuc[0]) <NEW_LINE> z = nucname.znum(nuc[0]) <NEW_LINE> n=a-z <NEW_LINE> act_grid[z,n] = np.log10(float(nuc[para])) <NEW_LINE> <DEDENT> <DEDENT> act_grid = np.ma.masked_array(act_grid, act_grid<low_limit) <NEW_LINE> make_plot(act_grid, save, sfile) | plots parameter as table of nuclides form for a timestep
this is for active parameters | 625941c15fdd1c0f98dc01ab |
def nmt(src_input, tgt_input, tgt_output, nmt_colocation, unroll=True, **kwargs): <NEW_LINE> <INDENT> hparams = create_nmt_hparams(**kwargs) <NEW_LINE> return NMT(hparams, nmt_colocation, unroll).build_graph( src_input, tgt_input, tgt_output) | Returns a NMT network. | 625941c18a349b6b435e80ec |
def temperature_linearterms(system): <NEW_LINE> <INDENT> from ...component.temperature import temperature <NEW_LINE> dT = np.zeros_like(system.Temperature) <NEW_LINE> f_m, f_p = system.b_Temperature <NEW_LINE> assert not temperature(system.nz, system.nn, dT, system.Temperature, system.dz, system.npa[0,:], f_p, f_m) <NEW_LINE> return dT | Operate the derivative of temperature linear term computer. | 625941c12ae34c7f2600d0aa |
def get_data(db_session): <NEW_LINE> <INDENT> return db_session.query(Request).all() | Equivalent function to get_data_from, but returns all data.
:param db_session: session for the database
:return list of all requests in the Request table | 625941c1956e5f7376d70de7 |
def run(self): <NEW_LINE> <INDENT> error, show = Show.pause(self.indexerid, self.pause) <NEW_LINE> if error: <NEW_LINE> <INDENT> return _responds(RESULT_FAILURE, msg=error) <NEW_LINE> <DEDENT> return _responds(RESULT_SUCCESS, msg='{0} has been {1}'.format(show.name, ('resumed', 'paused')[show.paused])) | Pause or un-pause a show | 625941c1aad79263cf3909b7 |
def test_3 (self): <NEW_LINE> <INDENT> res = solve ('PLAYS', 'WELL', 'BETTER') <NEW_LINE> self.assertEquals (res, [97426, 8077, 105503]) | PLAYS + WELL = BETTER | 625941c1046cf37aa974ccc3 |
def ingestion_complete(self): <NEW_LINE> <INDENT> if self.outcome is None: <NEW_LINE> <INDENT> self._ingestion_complete = True <NEW_LINE> self._perhaps_complete() | See superclass method for specification. | 625941c12ae34c7f2600d0ab |
def _dim_index_to_slice(index_list): <NEW_LINE> <INDENT> if len(index_list) == 1: <NEW_LINE> <INDENT> return index_list[0] <NEW_LINE> <DEDENT> elif len(index_list) == 2: <NEW_LINE> <INDENT> return slice(index_list[0],index_list[1]) <NEW_LINE> <DEDENT> elif len(index_list) == 3: <NEW_LINE> <INDENT> return slice(index_list[0],index_list[1],index_list[2]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> status('ERROR: illformed dimension subset',error=True) <NEW_LINE> exit(1) | .. function:: _dim_index_to_slice(index_list)
Convert string formatted as: dimname,start[,stop[,stride]]
to index (for the case where only 'start' is provided)
or indexing object (slice).
:param index_list: index list as passed in from
-d dimname,start,stop,stride
:returns: dict -- {dimname: indexing object} | 625941c155399d3f0558862c |
def shuffle_blocks(vlist, bsize=-1): <NEW_LINE> <INDENT> vlen = len(vlist) <NEW_LINE> if bsize < 0 or bsize >= vlen: <NEW_LINE> <INDENT> shuffle(vlist) <NEW_LINE> return <NEW_LINE> <DEDENT> if bsize < 2: return <NEW_LINE> nblocks = vlen // bsize <NEW_LINE> nrem = vlen % bsize <NEW_LINE> boff = 0 <NEW_LINE> for ind in range(nblocks): <NEW_LINE> <INDENT> shuffle(vlist, boff, boff+bsize-1) <NEW_LINE> boff += bsize <NEW_LINE> <DEDENT> shuffle(vlist, boff, boff+nrem-1) <NEW_LINE> return vlist | like shuffle, but in blocks of given size | 625941c17047854f462a1385 |
def _postback(self): <NEW_LINE> <INDENT> raise NotImplementedError | Perform postback to MoIP and store the response in self.response. | 625941c17d43ff24873a2c18 |
@_docstring_parameter(_csv_load_params_doc) <NEW_LINE> def baseline_newline_count(filename, *args, **kwargs): <NEW_LINE> <INDENT> params = _get_params(*args, **kwargs) <NEW_LINE> nc = pti.NewlineCounter(); <NEW_LINE> count = nc.load(filename, params) <NEW_LINE> return count | Computes the number of newline characters in the file.
Note: this is not the same as the number of lines in a file.
Parameters
----------
{0}
Returns
-------
n : int
The number of newlines in a file. | 625941c1eab8aa0e5d26dad0 |
def execute_system_command(self, command): <NEW_LINE> <INDENT> return subprocess.check_output(command, shell=True) | Execute a system command.
:param command: command that we want to execute
:type command: str
:return: resulting command
:rtype: str | 625941c199fddb7c1c9de30b |
def create_user(passwd, username='usuario', email='email@ucm.es'): <NEW_LINE> <INDENT> user = django.contrib.auth.get_user_model().objects.create_user( username=username, email=email, password=passwd) <NEW_LINE> return user | Creates and stores a user | 625941c11f037a2d8b946177 |
def check_and_create_dir(dir): <NEW_LINE> <INDENT> pathlib.Path(dir).mkdir(parents=True, exist_ok=True) | check_and_create_dir
Checks whether an output directory exists and creates it. | 625941c1c4546d3d9de729ab |
def test_sw1_stack_down(self): <NEW_LINE> <INDENT> dps = [valve.dp for valve in self.valves_manager.valves.values()] <NEW_LINE> for dp in dps: <NEW_LINE> <INDENT> for port in dp.ports.values(): <NEW_LINE> <INDENT> if port.lacp: <NEW_LINE> <INDENT> port.actor_up() <NEW_LINE> port.select_port() <NEW_LINE> <DEDENT> if port.stack: <NEW_LINE> <INDENT> port.stack_up() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> last_live_times = {'sw1': 100, 'sw2': 100, 'sw3': 100} <NEW_LINE> for port_num in [2, 3]: <NEW_LINE> <INDENT> port = dps[0].ports[port_num] <NEW_LINE> if port.stack: <NEW_LINE> <INDENT> port.stack_bad() <NEW_LINE> <DEDENT> <DEDENT> dps[0].stack.update_health(100, last_live_times, self.UPDATE_TIME) <NEW_LINE> self.assertEqual(dps[0].stack.dyn_healthy_info[1], 0.5) <NEW_LINE> self.assertTrue(dps[0].stack.dyn_healthy) <NEW_LINE> for port_num in [6]: <NEW_LINE> <INDENT> port = dps[0].ports[port_num] <NEW_LINE> if port.stack: <NEW_LINE> <INDENT> port.stack_bad() <NEW_LINE> <DEDENT> <DEDENT> dps[0].stack.update_health(100, last_live_times, self.UPDATE_TIME) <NEW_LINE> self.assertEqual(dps[0].stack.dyn_healthy_info[1], 0.25) <NEW_LINE> self.assertFalse(dps[0].stack.dyn_healthy) | Test stack health metrics with SW1 | 625941c1de87d2750b85fd09 |
def cleanup(self): <NEW_LINE> <INDENT> super(TrafficGen, self).cleanup() <NEW_LINE> gevent.get_hub().destroy() | Shutdown gevent as it seems to be leaking some globals. | 625941c1a05bb46b383ec79d |
def toHex(self, num): <NEW_LINE> <INDENT> if num == 0: <NEW_LINE> <INDENT> return '0' <NEW_LINE> <DEDENT> if num < 0: <NEW_LINE> <INDENT> num += 2**32 <NEW_LINE> <DEDENT> result = '' <NEW_LINE> s = ['a', 'b', 'c', 'd', 'e', 'f'] <NEW_LINE> while num: <NEW_LINE> <INDENT> temp = num % 16 <NEW_LINE> if temp > 9: <NEW_LINE> <INDENT> temp = s[temp - 10] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> temp = str(temp) <NEW_LINE> <DEDENT> result = temp + result <NEW_LINE> num //= 16 <NEW_LINE> <DEDENT> return result | :type num: int
:rtype: str | 625941c1de87d2750b85fd0a |
def get_url(song_input, auto): <NEW_LINE> <INDENT> youtube_list = OrderedDict() <NEW_LINE> num = 0 <NEW_LINE> html = requests.get("https://www.youtube.com/results", params={'search_query': song_input}) <NEW_LINE> soup = BeautifulSoup(html.text, 'html.parser') <NEW_LINE> for i in soup.findAll('a', {'rel': YOUTUBECLASS}): <NEW_LINE> <INDENT> song_url = 'https://www.youtube.com' + (i.get('href')) <NEW_LINE> song_title = (i.get('title')) <NEW_LINE> youtube_list.update({song_title: song_url}) <NEW_LINE> if not auto: <NEW_LINE> <INDENT> print('(%s) %s' % (str(num + 1), song_title)) <NEW_LINE> num = num + 1 <NEW_LINE> <DEDENT> elif auto: <NEW_LINE> <INDENT> print(song_title) <NEW_LINE> return list(youtube_list.values())[0], list(youtube_list.keys())[0] <NEW_LINE> <DEDENT> <DEDENT> if youtube_list == {}: <NEW_LINE> <INDENT> log.log_error('No match found!') <NEW_LINE> exit() <NEW_LINE> <DEDENT> song_url, song_title = prompt(youtube_list) <NEW_LINE> return song_url, song_title | Provides user with a list of songs to choose from
returns the url of chosen song. | 625941c1b7558d58953c4e92 |
def test_adjust_context_scope(time_keyed_left, time_keyed_right): <NEW_LINE> <INDENT> @adjust_context.register(CustomAsOfJoin) <NEW_LINE> def adjust_context_custom_asof_join( op: ops.AsOfJoin, scope: Scope, timecontext: TimeContext, ) -> TimeContext: <NEW_LINE> <INDENT> assert scope is not None <NEW_LINE> return timecontext <NEW_LINE> <DEDENT> expr = CustomAsOfJoin( left=time_keyed_left, right=time_keyed_right, predicates='time', by='key', tolerance=ibis.interval(days=4), ).to_expr() <NEW_LINE> expr = expr[time_keyed_left, time_keyed_right.other_value] <NEW_LINE> context = (pd.Timestamp('20170105'), pd.Timestamp('20170111')) <NEW_LINE> expr.execute(timecontext=context) | Test that `adjust_context` has access to `scope` by default. | 625941c16fece00bbac2d6b6 |
@dispatch <NEW_LINE> @abstract() <NEW_LINE> def ones(dtype: DType, *shape: Int): <NEW_LINE> <INDENT> pass | Create a tensor of ones.
Can also give a reference tensor whose data type and shape will be used to
construct a tensor of ones.
Args:
dtype (dtype, optional): Data type. Defaults to the default data type.
*shape (shape): Shape of the tensor.
Returns:
tensor: Tensor of ones of shape `shape` and data type `dtype`. | 625941c11d351010ab855a96 |
def _load_consumer(self, consumer): <NEW_LINE> <INDENT> queue = rotate_to_first_in_deque_and_pop(self._unassigned_queues, lambda q: q.active) <NEW_LINE> if queue: <NEW_LINE> <INDENT> consumer.assign_queue(queue) <NEW_LINE> return True <NEW_LINE> <DEDENT> queue = rotate_to_first_in_deque_and_pop(self._unassigned_queues, lambda q: q.count > 0) <NEW_LINE> if queue: <NEW_LINE> <INDENT> consumer.assign_queue(queue) <NEW_LINE> return True <NEW_LINE> <DEDENT> donor = self._consumers.get_donor(consumer) <NEW_LINE> if donor: <NEW_LINE> <INDENT> queue = donor.remove_youngest_active_queue() <NEW_LINE> consumer.assign_queue(queue) <NEW_LINE> self.logger.log(LogType.Debug, "%s donated %s to %s" % (donor.fetcher_id, queue.name, consumer.fetcher_id)) <NEW_LINE> return True <NEW_LINE> <DEDENT> youngest_consumer = self._consumers.get_least_senior() <NEW_LINE> if youngest_consumer: <NEW_LINE> <INDENT> self.logger.log(LogType.Info, "Stopping youngest consumer: " + youngest_consumer.fetcher_id) <NEW_LINE> youngest_consumer.request_stop() <NEW_LINE> self._recycle_queues(youngest_consumer.queues) <NEW_LINE> youngest_consumer.reset() <NEW_LINE> if consumer != youngest_consumer and len(self._unassigned_queues) > 0: <NEW_LINE> <INDENT> consumer.assign_queue(self._unassigned_queues.popleft()) <NEW_LINE> return True <NEW_LINE> <DEDENT> <DEDENT> return False | Assign the first available queue to the consumer and return immediately. If no queue can be assigned to
the consumer then the youngest consumer is scheduled to stop and one of it's queues is donated to the consumer. | 625941c1e76e3b2f99f3a789 |
def overwrite_existing_file(self, context): <NEW_LINE> <INDENT> self.current = context.transport.get(self.filename) <NEW_LINE> if self.current != self.contents: <NEW_LINE> <INDENT> self.renderer.changed_file( self.filename, self.current, self.contents, self.sensitive) <NEW_LINE> if not context.simulate: <NEW_LINE> <INDENT> context.transport.put(self.filename, self.contents, self.mode) <NEW_LINE> <DEDENT> self.changed = True | Change the content of an existing file | 625941c126068e7796caec54 |
def setup_config(command, filename, section, vars): <NEW_LINE> <INDENT> conf = appconfig('config:' + filename) <NEW_LINE> load_environment(conf.global_conf, conf.local_conf) <NEW_LINE> from oil import db as model <NEW_LINE> answer = raw_input('Delete Current Tables If any exist [y/n]?') <NEW_LINE> if answer.lower() in ('y', 'yes', ''): <NEW_LINE> <INDENT> model.metadata.drop_all(bind=config['pylons.g'].sa_engine) <NEW_LINE> log.info('Tables Deleted') <NEW_LINE> <DEDENT> log.info("Creating tables") <NEW_LINE> model.metadata.create_all(bind=config['pylons.g'].sa_engine, checkfirst=True) <NEW_LINE> log.info("Tables Created") | Place any commands to setup oil here | 625941c13cc13d1c6d3c72f4 |
def parsing_boolean(self, field, data): <NEW_LINE> <INDENT> if field in data: <NEW_LINE> <INDENT> v = data[field] <NEW_LINE> if v in ['True', '有', ]: <NEW_LINE> <INDENT> data[field] = True <NEW_LINE> <DEDENT> elif v in ['False', ]: <NEW_LINE> <INDENT> data[field] = False | 解析布尔字段 | 625941c1fbf16365ca6f6139 |
def relativeValue(self): <NEW_LINE> <INDENT> return float() | float KIntNumInput.relativeValue() | 625941c10c0af96317bb8162 |
def random_string(length): <NEW_LINE> <INDENT> s = '' <NEW_LINE> while len(s) < length: <NEW_LINE> <INDENT> s += valid_string_characters[randint(0, 84)] <NEW_LINE> <DEDENT> return s | Return a random string of given length. | 625941c1293b9510aa2c3212 |
def test2(self): <NEW_LINE> <INDENT> signal = 'onAdjournmentsList' <NEW_LINE> lines = [ 'Stored games for tester:', ' C Opponent On Type Str M ECO Date', ' 1: W TheDane N [ br 2 12] 0-0 B2 ??? Sun Nov 23, 6:14 CST 1997', ' 2: W PyChess Y [psu 2 12] 39-39 W3 C20 Sun Jan 11, 17:40 ??? 2009', 'fics% ' ] <NEW_LINE> gametime1 = datetime.datetime(1997, 11, 23, 6, 14) <NEW_LINE> gametime2 = datetime.datetime(2009, 1, 11, 17, 40) <NEW_LINE> game1 = FICSAdjournedGame( FICSPlayer(self.connection.getUsername()), FICSPlayer('TheDane'), our_color=WHITE, length=3, time=gametime1, rated=True, game_type=GAME_TYPES['blitz'], private=False, minutes=2, inc=12) <NEW_LINE> game2 = FICSAdjournedGame( FICSPlayer(self.connection.getUsername()), FICSPlayer('PyChess'), our_color=WHITE, length=4, time=gametime2, rated=False, game_type=GAME_TYPES['standard'], private=True, minutes=2, inc=12) <NEW_LINE> expectedResult = [game1, game2] <NEW_LINE> self.runAndAssertEquals(signal, lines, (expectedResult, )) | Testing a double line | 625941c15fcc89381b1e1637 |
def parse(self, entry: typing.Any): <NEW_LINE> <INDENT> return self.DescriptionNode(**entry) | Parse description data. | 625941c192d797404e304103 |
def stopTrial(self): <NEW_LINE> <INDENT> self.sendMsg('stop_trial') <NEW_LINE> time.sleep(10 / 1000.0) <NEW_LINE> self.stopRecording() | Stops the eyetracker recording mode and also sends a message to the
eyelink log that the trial is stoped. The message sent is
'stop_trial'. Use this function before the trial starts.
If dummy mode, prints the message to the console.
Examples
--------
>>> tracker.stopTrial() | 625941c14f6381625f1149b5 |
def get_feedback(self): <NEW_LINE> <INDENT> return self._feedback | :rtype: list[Feedback] | 625941c1bf627c535bc13148 |
def getRowCol(self, pixelX, pixelY): <NEW_LINE> <INDENT> x0, y0 = self.rect.topleft <NEW_LINE> if self.outOfBounds(pixelX, pixelY): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> relX = pixelX - x0 <NEW_LINE> relY = pixelY - y0 <NEW_LINE> row = int(relY / self.cellHeight) <NEW_LINE> col = int(relX / self.cellWidth) <NEW_LINE> return (row, col) | get the (row, col) coordinate for the given (x, y) location | 625941c185dfad0860c3add3 |
def main(): <NEW_LINE> <INDENT> _solution = Solution() <NEW_LINE> inp = [([1,1,1],2), ([2,3,2,3,2],5), ([28,54,7,-70,22,65,-6], 100),([0,0,0,0,0,0,0,0,0,0],0)] <NEW_LINE> for i in inp: <NEW_LINE> <INDENT> print(_solution.func(i[0], i[1])) | main function | 625941c194891a1f4081ba22 |
def __init__(self): <NEW_LINE> <INDENT> self.sections = 0 <NEW_LINE> self.close_filein = False <NEW_LINE> self.close_fileout = False <NEW_LINE> try: <NEW_LINE> <INDENT> if len(sys.argv) > 1: <NEW_LINE> <INDENT> self.filein = open(sys.argv[1], 'r') <NEW_LINE> self.close_filein = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.filein = sys.stdin <NEW_LINE> <DEDENT> if len(sys.argv) > 2: <NEW_LINE> <INDENT> self.fileout = open(sys.argv[2], 'w') <NEW_LINE> self.close_fileout = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.fileout = sys.stdout <NEW_LINE> <DEDENT> <DEDENT> except IOError as e: <NEW_LINE> <INDENT> print('Cannot open file {}!'.format(e.filename), file=sys.stderr) <NEW_LINE> sys.exit(1) | Initialize input and ouput file objects from command line options or
if absent from stdin/stdout | 625941c1925a0f43d2549def |
def stopEngine(self, engine_id): <NEW_LINE> <INDENT> for access_id, v in self.engine_instances.iteritems(): <NEW_LINE> <INDENT> if engine_id == v: <NEW_LINE> <INDENT> self.processManager.stopProcess(engine_id) <NEW_LINE> del self.engine_instances[access_id] <NEW_LINE> break | XXX hacky. improve next iteration.
| 625941c15166f23b2e1a50d3 |
def is_option_list(sValue, *aOptions): <NEW_LINE> <INDENT> return [is_option(sMem, *aOptions) for sMem in is_list(sValue)] | Validator function for option_list configspec type. | 625941c13cc13d1c6d3c72f5 |
def __init__(self, vec2d): <NEW_LINE> <INDENT> self.vec = vec2d <NEW_LINE> self.row = self.col = 0 | Initialize your data structure here.
:type vec2d: List[List[int]] | 625941c14527f215b584c3d3 |
def transition_import_(self): <NEW_LINE> <INDENT> Channel = Pool().get('sale.channel') <NEW_LINE> channel = Channel(Transaction().context.get('active_id')) <NEW_LINE> sales = [] <NEW_LINE> products = [] <NEW_LINE> if self.start.import_orders: <NEW_LINE> <INDENT> sales = channel.import_orders() <NEW_LINE> <DEDENT> if self.start.import_products: <NEW_LINE> <INDENT> products = channel.import_products() <NEW_LINE> <DEDENT> self.success.no_of_orders = len(sales) <NEW_LINE> self.success.no_of_products = len(products) <NEW_LINE> return 'success' | Downstream channel implementation can customize the wizard | 625941c157b8e32f52483413 |
def pc_work_time_var(self): <NEW_LINE> <INDENT> return _lilacsat_swig.afsk1200_rx_f_sptr_pc_work_time_var(self) | pc_work_time_var(afsk1200_rx_f_sptr self) -> float | 625941c1bde94217f3682d6d |
def number(self, number): <NEW_LINE> <INDENT> s = [ord(x) for x in str(number)] + [14] <NEW_LINE> if number == int(number) and abs(number) < 65536: <NEW_LINE> <INDENT> sign = 0xFF if number < 0 else 0 <NEW_LINE> b = [0, sign] + self.numberLH(number) + [0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (C, ED, LH) = fp.immediate_float(number) <NEW_LINE> C = C[:2] <NEW_LINE> ED = ED[:4] <NEW_LINE> LH = LH[:4] <NEW_LINE> b = [int(C, 16)] <NEW_LINE> b += [int(ED[:2], 16), int(ED[2:], 16)] <NEW_LINE> b += [int(LH[:2], 16), int(LH[2:], 16)] <NEW_LINE> <DEDENT> return s + b | Returns a floating point (or integer) number for a BASIC
program. That is: It's ASCII representation followed by 5 bytes
in floating point or integer format (if number in (-65535 + 65535) | 625941c17b180e01f3dc477b |
def qrcode_image_response(data=''): <NEW_LINE> <INDENT> img = make_qr_code_image(data) <NEW_LINE> response = HttpResponse(content_type='image/png') <NEW_LINE> img.save(response, 'png') <NEW_LINE> return response | Returns a QR Code image as an HTTP response
This method is unrestricted (i.e. you wouldn't want anyone on the web generating QR codes automatically)
For restricted access, see: restricted_qrcode_image_response
TODO: Possible improvements: Cache (for a short period) requests for the same QR Code data-payload? | 625941c1d164cc6175782cc7 |
def _DoLensAlignment(future, navcam, sem_stage): <NEW_LINE> <INDENT> logging.debug("Starting lens alignment...") <NEW_LINE> try: <NEW_LINE> <INDENT> if future._lens_alignment_state == CANCELLED: <NEW_LINE> <INDENT> raise CancelledError() <NEW_LINE> <DEDENT> image = navcam.data.get(asap=False) <NEW_LINE> try: <NEW_LINE> <INDENT> lens_coordinates = FindCircleCenter(image[:, :, 0], LENS_RADIUS, 5) <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> raise IOError("Lens not found.") <NEW_LINE> <DEDENT> pixelSize = image.metadata[model.MD_PIXEL_SIZE] <NEW_LINE> center_pxs = (image.shape[1] / 2, image.shape[0] / 2) <NEW_LINE> vector_pxs = [a - b for a, b in zip(lens_coordinates, center_pxs)] <NEW_LINE> vector = (vector_pxs[0] * pixelSize[0], vector_pxs[1] * pixelSize[1]) <NEW_LINE> return (sem_stage.position.value["x"] + vector[0], sem_stage.position.value["y"] - vector[1]) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> with future._lens_lock: <NEW_LINE> <INDENT> if future._lens_alignment_state == CANCELLED: <NEW_LINE> <INDENT> raise CancelledError() <NEW_LINE> <DEDENT> future._lens_alignment_state = FINISHED | Detects the objective lens with the NavCam and moves the SEM stage to center
them in the NavCam view. Returns the final SEM stage position.
future (model.ProgressiveFuture): Progressive future provided by the wrapper
navcam (model.DigitalCamera): The NavCam
sem_stage (model.Actuator): The SEM stage
returns sem_position (tuple of floats): SEM stage position #m,m
raises:
CancelledError() if cancelled
IOError If objective lens not found | 625941c130dc7b76659018e2 |
def get_text_data_list(self): <NEW_LINE> <INDENT> return [self.surname, self.prefix, self.connector, str(self.origintype)] | Return the list of all textual attributes of the object.
:returns: Returns the list of all textual attributes of the object.
:rtype: list | 625941c1f9cc0f698b140577 |
def handler(self): <NEW_LINE> <INDENT> if self.event == SUBSCRIBE: <NEW_LINE> <INDENT> return self.subscribe() <NEW_LINE> <DEDENT> elif self.event == SCAN: <NEW_LINE> <INDENT> return self.scan() <NEW_LINE> <DEDENT> elif self.event == CLICK: <NEW_LINE> <INDENT> return self.menu_click() <NEW_LINE> <DEDENT> elif self.event == LOCATION: <NEW_LINE> <INDENT> return self.report_location() <NEW_LINE> <DEDENT> return 'success' | 事件处理入口
@return 符合微信要求格式的字符串。xml格式 | 625941c1d58c6744b4257bda |
def test_private(self): <NEW_LINE> <INDENT> self.assertRaises(AttributeError, getattr, self.prop, '__test__') | Test private attributes. | 625941c171ff763f4b549602 |
def get_website_config(): <NEW_LINE> <INDENT> config = {"ErrorDocument": {"Key": INDEX}, "IndexDocument": {"Suffix": ERROR}, } <NEW_LINE> return config | Gets the website config | 625941c1e8904600ed9f1ea5 |
def __init__(self, type=None, title=None, result_list=None): <NEW_LINE> <INDENT> self._type = None <NEW_LINE> self._title = None <NEW_LINE> self._result_list = None <NEW_LINE> self.discriminator = None <NEW_LINE> if type is not None: <NEW_LINE> <INDENT> self.type = type <NEW_LINE> <DEDENT> if title is not None: <NEW_LINE> <INDENT> self.title = title <NEW_LINE> <DEDENT> if result_list is not None: <NEW_LINE> <INDENT> self.result_list = result_list | DeviceSLAWidgetData - a model defined in Swagger | 625941c1e1aae11d1e749c2f |
def get_virtual_machine_scale_set_ip_configuration( self, resource_group_name, virtual_machine_scale_set_name, virtualmachine_index, network_interface_name, ip_configuration_name, expand=None, **kwargs ): <NEW_LINE> <INDENT> cls = kwargs.pop('cls', None) <NEW_LINE> error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } <NEW_LINE> error_map.update(kwargs.pop('error_map', {})) <NEW_LINE> api_version = "2017-03-30" <NEW_LINE> accept = "application/json" <NEW_LINE> url = self.get_virtual_machine_scale_set_ip_configuration.metadata['url'] <NEW_LINE> path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'virtualMachineScaleSetName': self._serialize.url("virtual_machine_scale_set_name", virtual_machine_scale_set_name, 'str'), 'virtualmachineIndex': self._serialize.url("virtualmachine_index", virtualmachine_index, 'str'), 'networkInterfaceName': self._serialize.url("network_interface_name", network_interface_name, 'str'), 'ipConfigurationName': self._serialize.url("ip_configuration_name", ip_configuration_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } <NEW_LINE> url = self._client.format_url(url, **path_format_arguments) <NEW_LINE> query_parameters = {} <NEW_LINE> query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') <NEW_LINE> if expand is not None: <NEW_LINE> <INDENT> query_parameters['$expand'] = self._serialize.query("expand", expand, 'str') <NEW_LINE> <DEDENT> header_parameters = {} <NEW_LINE> header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') <NEW_LINE> request = self._client.get(url, query_parameters, header_parameters) <NEW_LINE> pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) <NEW_LINE> response = pipeline_response.http_response <NEW_LINE> if response.status_code not in [200]: <NEW_LINE> <INDENT> map_error(status_code=response.status_code, response=response, error_map=error_map) <NEW_LINE> raise HttpResponseError(response=response, error_format=ARMErrorFormat) <NEW_LINE> <DEDENT> deserialized = self._deserialize('NetworkInterfaceIPConfiguration', pipeline_response) <NEW_LINE> if cls: <NEW_LINE> <INDENT> return cls(pipeline_response, deserialized, {}) <NEW_LINE> <DEDENT> return deserialized | Get the specified network interface ip configuration in a virtual machine scale set.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param virtual_machine_scale_set_name: The name of the virtual machine scale set.
:type virtual_machine_scale_set_name: str
:param virtualmachine_index: The virtual machine index.
:type virtualmachine_index: str
:param network_interface_name: The name of the network interface.
:type network_interface_name: str
:param ip_configuration_name: The name of the ip configuration.
:type ip_configuration_name: str
:param expand: Expands referenced resources.
:type expand: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: NetworkInterfaceIPConfiguration, or the result of cls(response)
:rtype: ~azure.mgmt.network.v2018_11_01.models.NetworkInterfaceIPConfiguration
:raises: ~azure.core.exceptions.HttpResponseError | 625941c1d164cc6175782cc8 |
def calc_rh(at_date, at_val, dp_date, dp_val): <NEW_LINE> <INDENT> comp_val = 6999 <NEW_LINE> o_val = [] <NEW_LINE> index = 0 <NEW_LINE> while (index < len(at_date)): <NEW_LINE> <INDENT> rh_val = comp_val <NEW_LINE> if not(at_date[index] == dp_date[index]): <NEW_LINE> <INDENT> print_center("ERROR: dates do not match for air temp and dew point", "*") <NEW_LINE> exit_on_failure() <NEW_LINE> <DEDENT> if (at_val[index] != comp_val and dp_val[index] != comp_val): <NEW_LINE> <INDENT> denominator = 0.611 * math.exp((17.3 * at_val[index]) / (at_val[index] + 237.3)) <NEW_LINE> numerator = 0.611 * math.exp((17.3 * dp_val[index]) / (dp_val[index] + 237.3)) <NEW_LINE> rh_val = numerator / denominator * 100 <NEW_LINE> <DEDENT> o_val.insert(index, rh_val) <NEW_LINE> index = index + 1 <NEW_LINE> <DEDENT> return o_val | calcualtes the relative humidity
arguments:
at_date: ((datetime) list) air temerature date array
at_val: ((float) list) air temerature value array
dp_date: ((datetime) list) dew point date array
dp_val: ((float) list) dew point value array
returns:
an array of relative humiditys | 625941c1d7e4931a7ee9de97 |
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'google_maps_directions_proj.settings') <NEW_LINE> try: <NEW_LINE> <INDENT> from django.core.management import execute_from_command_line <NEW_LINE> <DEDENT> except ImportError as exc: <NEW_LINE> <INDENT> raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc <NEW_LINE> <DEDENT> execute_from_command_line(sys.argv) | Run administrative tasks. | 625941c1507cdc57c6306c50 |
def _get_sensor_col_files(self, gas, loc): <NEW_LINE> <INDENT> sub = os.path.join(self.GasNames[gas], self.Locs[loc]) <NEW_LINE> files = os.listdir(os.path.join(self.data_location, sub)) <NEW_LINE> files.sort() <NEW_LINE> return (sub, files) | lists the files in the directory corresponding to the gas and location. | 625941c1377c676e91272123 |
@pytest.mark.django_db <NEW_LINE> def test_sendmessage_command(mocker, organization, partner): <NEW_LINE> <INDENT> test_message = os.path.join(TEST_DIR, "testmessage.edi") <NEW_LINE> with pytest.raises(management.CommandError): <NEW_LINE> <INDENT> management.call_command( "sendas2message", "AS2 Server", "AS2 Client", test_message ) <NEW_LINE> <DEDENT> with pytest.raises(management.CommandError): <NEW_LINE> <INDENT> management.call_command( "sendas2message", organization.as2_name, "AS2 Client", test_message ) <NEW_LINE> <DEDENT> with pytest.raises(management.CommandError): <NEW_LINE> <INDENT> management.call_command( "sendas2message", organization.as2_name, partner.as2_name, "testmessage.edi" ) <NEW_LINE> <DEDENT> management.call_command( "sendas2message", organization.as2_name, partner.as2_name, test_message ) <NEW_LINE> mocked_delete = mocker.patch( "pyas2.management.commands.sendas2message.default_storage.delete" ) <NEW_LINE> management.call_command( "sendas2message", organization.as2_name, partner.as2_name, test_message, delete=True, ) <NEW_LINE> assert mocked_delete.call_count == 1 | Test the command for sending an as2 message | 625941c199cbb53fe6792b61 |
@app.route("/tags/<int:tag_id>/edit", methods=["POST"]) <NEW_LINE> def edit_tag(tag_id): <NEW_LINE> <INDENT> tag_name = request.form["tag_name"] <NEW_LINE> post_ids = [int(num) for num in request.form.getlist("posts")] <NEW_LINE> posts = Post.query.filter(Post.id.in_(post_ids)).all() <NEW_LINE> tag = Tag.query.get_or_404(tag_id) <NEW_LINE> tag.tag_name = tag_name <NEW_LINE> tag.posts = posts <NEW_LINE> db.session.commit() <NEW_LINE> return redirect(f"/tags/{tag_id}") | This view function makes changes to an existing tag and makes sure it isaved in the blogly db | 625941c1aad79263cf3909b8 |
def img_preprocess(img): <NEW_LINE> <INDENT> out = cv2.resize(img, (112, 112)) <NEW_LINE> out = cv2.cvtColor(out, cv2.COLOR_BGR2GRAY) <NEW_LINE> mu = np.mean(out) <NEW_LINE> std = np.std(out) <NEW_LINE> out = (out - mu) / std <NEW_LINE> out = out[np.newaxis, :, :, np.newaxis] <NEW_LINE> return out | Conduct gray, resize and normalization on a face image
Args:
img: np.array, bgr color face img, [h, w, 3]
Returns: [1, 112, 112, 1] gray, normalized version | 625941c150485f2cf553cd13 |
def do_quick(self, code_line, evaluate = False): <NEW_LINE> <INDENT> self.send_debug_response("<code>do_quick</code> with <code>{}</code>".format(code_line)) <NEW_LINE> if isinstance(code_line, list): <NEW_LINE> <INDENT> for line in code_line: <NEW_LINE> <INDENT> self.child.sendline(line) <NEW_LINE> self.child.expect(SCALA_PROMPT) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.child.sendline(code_line) <NEW_LINE> self.child.expect(SCALA_PROMPT) <NEW_LINE> <DEDENT> nrows = ceil(len(code_line) / 80) <NEW_LINE> output = self.child.before <NEW_LINE> lines = output.splitlines() <NEW_LINE> lines = lines[nrows:-1] <NEW_LINE> lines = '\n'.join(lines) <NEW_LINE> if evaluate: <NEW_LINE> <INDENT> return self.do_ast_eval(lines) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return lines | Quickly execute a line using the underlying REPL and, if needed,
evaluate it as Python code. | 625941c1462c4b4f79d1d64a |
def get_snp_genos(self, c, p, as_strings=True): <NEW_LINE> <INDENT> snps = [x for x in self.get_range(c,p,p,as_strings=as_strings)] <NEW_LINE> return len(snps)==1 and dict(snps[0][3]) or {} | Read a single position from a VCF file and return the genotypes
as a sample -> allele map. If there is not exactly one matching
row in the VCF file at this position (if there are none or multiple)
then we return an empty map: {}. | 625941c1cdde0d52a9e52fab |
def set_Datastreams(self, value): <NEW_LINE> <INDENT> super(CreateProductInputSet, self)._set_input('Datastreams', value) | Set the value of the Datastreams input for this Choreo. ((optional, json) Default device datastream JSON array. Every newly created device in this product will have this default datastream. Ex: [{"id":"channel1"},{"id":"demo"}]) | 625941c19f2886367277a809 |
def comment(request, template="generic/comments.html", extra_context=None): <NEW_LINE> <INDENT> response = initial_validation(request, "comment") <NEW_LINE> if isinstance(response, HttpResponse): <NEW_LINE> <INDENT> return response <NEW_LINE> <DEDENT> obj, post_data = response <NEW_LINE> form_class = import_dotted_path(settings.COMMENT_FORM_CLASS) <NEW_LINE> form = form_class(request, obj, post_data) <NEW_LINE> if form.is_valid(): <NEW_LINE> <INDENT> url = obj.get_absolute_url() <NEW_LINE> if is_spam(request, form, url): <NEW_LINE> <INDENT> return redirect(url) <NEW_LINE> <DEDENT> comment = form.save(request) <NEW_LINE> response = redirect(add_cache_bypass(comment.get_absolute_url())) <NEW_LINE> for field in ThreadedCommentForm.cookie_fields: <NEW_LINE> <INDENT> cookie_name = ThreadedCommentForm.cookie_prefix + field <NEW_LINE> cookie_value = post_data.get(field, "") <NEW_LINE> set_cookie(response, cookie_name, cookie_value) <NEW_LINE> <DEDENT> return response <NEW_LINE> <DEDENT> elif request_is_ajax(request) and form.errors: <NEW_LINE> <INDENT> return HttpResponse(dumps({"errors": form.errors})) <NEW_LINE> <DEDENT> context = {"obj": obj, "posted_comment_form": form} <NEW_LINE> context.update(extra_context or {}) <NEW_LINE> return TemplateResponse(request, template, context) | Handle a ``ThreadedCommentForm`` submission and redirect back to its
related object. | 625941c1e76e3b2f99f3a78a |
def __init__(self, OD): <NEW_LINE> <INDENT> self.od = OD | Class constructor.
>>> isinstance(Driver(OD(1, 2, 8, 15)), Driver)
True
>>> isinstance(Driver(1), Driver)
True
>>> isinstance(Driver(OD(1, 2, 8, 15)).od, OD)
True
The class contructor needs to be more precise about its input. | 625941c1d6c5a10208143fc3 |
def has_key(self, key): <NEW_LINE> <INDENT> return key.lower() in self.caseless_keys | Determines if the `dict` has an item with a specific `key`.
Args:
key: Key to check for presence. Key is case insensitive, so
`d.has_key('Key')` evaluates to the same value as `d.has_key('key')`.
Returns:
`True` if `dict` contains the specified `key`, else `False`. | 625941c166673b3332b9200b |
def _get_line_id(line): <NEW_LINE> <INDENT> if line.product.is_course_entitlement_product: <NEW_LINE> <INDENT> return line.product.attr.UUID <NEW_LINE> <DEDENT> return line.product.course_id | Return unique id of line
Args:
line: line in application orders
Returns:
if product is entitlement product then uuid
else course_id. | 625941c1851cf427c661a48c |
def ev_list(request, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> events = Event.objects.filter(end_date__gte=datetime.datetime.now()) <NEW_LINE> <DEDENT> except Event.DoesNotExist: <NEW_LINE> <INDENT> events = {} <NEW_LINE> <DEDENT> ret = dict(events=events) <NEW_LINE> return render(request, 'verbena/events/event_list.html', ret) | list all events | 625941c1cad5886f8bd26f54 |
def config_api(stream, request, query): <NEW_LINE> <INDENT> mimetype = 'application/json' <NEW_LINE> indent = None <NEW_LINE> options = cgi.parse_qs(query) <NEW_LINE> if utils.intify(options.get('debug', ['0'])[0]): <NEW_LINE> <INDENT> mimetype = 'text/plain' <NEW_LINE> indent = 4 <NEW_LINE> <DEDENT> if utils.intify(options.get('labels', ['0'])[0]): <NEW_LINE> <INDENT> obj = CONFIG.descriptions <NEW_LINE> <DEDENT> elif request.method != 'POST': <NEW_LINE> <INDENT> obj = CONFIG.conf <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> body = request.body.read() <NEW_LINE> updates = marshal.qs_to_dictionary(body) <NEW_LINE> count = privacy.count_valid(updates, 'privacy.') <NEW_LINE> if count < 0: <NEW_LINE> <INDENT> raise ConfigError('Passed invalid privacy settings') <NEW_LINE> <DEDENT> agent_interval = int(updates.get('agent.interval', 0)) <NEW_LINE> if agent_interval != 0 and agent_interval < 1380: <NEW_LINE> <INDENT> raise ConfigError('Passed invalid agent.interval') <NEW_LINE> <DEDENT> CONFIG.merge_api(updates, DATABASE.connection()) <NEW_LINE> STATE.update('config', updates) <NEW_LINE> obj = '{}' <NEW_LINE> <DEDENT> response = Message() <NEW_LINE> body = json.dumps(obj, sort_keys=True, indent=indent) <NEW_LINE> response.compose(code="200", reason="Ok", body=body, mimetype=mimetype) <NEW_LINE> stream.send_response(request, response) | Implements /api/config API | 625941c19b70327d1c4e0d4f |
def db_init(): <NEW_LINE> <INDENT> db = db_open() <NEW_LINE> with app.open_resource('schema.sql', mode='r') as f: <NEW_LINE> <INDENT> db.cursor().executescript(f.read()) <NEW_LINE> <DEDENT> db.commit() | Initializes the database. | 625941c10a366e3fb873e793 |
def freq2time(spectrum, n=None): <NEW_LINE> <INDENT> return np.fft.irfft(spectrum, axis=-1, n=n) / 2 ** 0.5 | Conversion frequency to time domain
Goal: coherent normalization of the fft: np.sum(trace**2) * dt = np.sum(spectrum**2) * df
performs backward FFT with correct normalization that conserves the power
-- addional division 1/sqrt(2) to account for omitted negative frequencies when using "real fft"
Arguments
----------
spec: complex np array
the frequency spectrum
n: int
the number of sample in the time domain (relevant if time trace has an odd number of samples)
| 625941c1d268445f265b4de9 |
def _parcel_profile_helper(pressure, temperature, dewpoint): <NEW_LINE> <INDENT> press_lcl, temp_lcl = lcl(pressure[0], temperature, dewpoint) <NEW_LINE> press_lcl = press_lcl.to(pressure.units) <NEW_LINE> press_lower = concatenate((pressure[pressure >= press_lcl], press_lcl)) <NEW_LINE> temp_lower = dry_lapse(press_lower, temperature) <NEW_LINE> if _greater_or_close(np.nanmin(pressure), press_lcl): <NEW_LINE> <INDENT> return (press_lower[:-1], press_lcl, units.Quantity(np.array([]), press_lower.units), temp_lower[:-1], temp_lcl, units.Quantity(np.array([]), temp_lower.units)) <NEW_LINE> <DEDENT> press_upper = concatenate((press_lcl, pressure[pressure < press_lcl])) <NEW_LINE> temp_upper = moist_lapse(press_upper, temp_lower[-1]).to(temp_lower.units) <NEW_LINE> return (press_lower[:-1], press_lcl, press_upper[1:], temp_lower[:-1], temp_lcl, temp_upper[1:]) | Help calculate parcel profiles.
Returns the temperature and pressure, above, below, and including the LCL. The
other calculation functions decide what to do with the pieces. | 625941c191f36d47f21ac46b |
def test_upheight(self): <NEW_LINE> <INDENT> r1 = Rectangle(2, 3, 4, 5, 6) <NEW_LINE> r1.update(85, 12, 8) <NEW_LINE> self.assertEqual(r1.width, 12) <NEW_LINE> self.assertEqual(r1.height, 8) <NEW_LINE> self.assertEqual(r1.x, 4) <NEW_LINE> self.assertEqual(r1.y, 5) <NEW_LINE> self.assertEqual(r1.id, 85) | Height Update | 625941c13539df3088e2e2c6 |
def process_property(self, resources, resource, model, prop, context, model_ids): <NEW_LINE> <INDENT> pass | Post process a property from a model.
:param resources: Resource listing object
:param resource: resource object.
:param model: Model object.
:param prop: Property object.
:type context: ParsingContext
:param context: Current context in the API. | 625941c14e696a04525c93c7 |
@onsetup <NEW_LINE> def setup_product(): <NEW_LINE> <INDENT> fiveconfigure.debug_mode = True <NEW_LINE> import plone.browserlayer <NEW_LINE> zcml.load_config('configure.zcml', plone.browserlayer) <NEW_LINE> import googlesitemap.common <NEW_LINE> zcml.load_config('configure.zcml', googlesitemap.common) <NEW_LINE> import googlesitemap.common.tests <NEW_LINE> zcml.load_config('testing.zcml', googlesitemap.common.tests) <NEW_LINE> fiveconfigure.debug_mode = False <NEW_LINE> ztc.installPackage('plone.browserlayer') <NEW_LINE> ztc.installPackage('googlesitemap.common') | Set up the package and its dependencies.
The @onsetup decorator causes the execution of this body to be
deferred until the setup of the Plone site testing layer. We could
have created our own layer, but this is the easiest way for Plone
integration tests. | 625941c15e10d32532c5eea2 |
def test_replace_namespaced_scale_scale_1(self): <NEW_LINE> <INDENT> pass | Test case for replace_namespaced_scale_scale_1
replace scale of the specified Scale | 625941c18e7ae83300e4af47 |
def DetailedStats(self, pc): <NEW_LINE> <INDENT> self.screen.clear() <NEW_LINE> L = [] <NEW_LINE> L.append(("^Y^-= %s =-" % lang.label_char_title) % (pc.name, pc.level, pc.archetype.cname)) <NEW_LINE> L.append("") <NEW_LINE> b = pc.MeleeDamageBonus() <NEW_LINE> if b >= 0: <NEW_LINE> <INDENT> b = "+%s" % b <NEW_LINE> <DEDENT> L.append("^Y^%s: %2s^0^ %s %s" % (lang.stat_abbr_str.upper(), pc.stats("str"), b, lang.label_melee_damage)) <NEW_LINE> L.append(" %.2fs carried, %s: %2s" % (pc.inventory.TotalWeight(), lang.stat_abbr_estr, pc.eSTR())) <NEW_LINE> L.append("") <NEW_LINE> b = pc.MeleeHitBonus() <NEW_LINE> if b >= 0: <NEW_LINE> <INDENT> b = "+%s" % b <NEW_LINE> <DEDENT> L.append("^Y^%s: %2s^0^ %s %s" % (lang.stat_abbr_dex.upper(), pc.stats("dex"), b, lang.label_to_hit)) <NEW_LINE> b = pc.EvasionBonus() <NEW_LINE> if b >= 0: <NEW_LINE> <INDENT> b = "+%s" % b <NEW_LINE> <DEDENT> if pc.stats("dex") - 8 > pc.eSTR(): <NEW_LINE> <INDENT> limit = "^R^ %s^0^" % lang.label_evasion_limited <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> limit = "" <NEW_LINE> <DEDENT> L.append(" %s %s%s" % (b, lang.word_evasion, limit)) <NEW_LINE> L.append("") <NEW_LINE> L.append("^Y^%s: %2s^0^ %s%% %s" % (lang.stat_abbr_int.upper(), pc.stats("int"), max(0, min(100, 25*(10-pc.stats("int")))), lang.label_spell_failure)) <NEW_LINE> L.append(" %s%% %s" % (max(0, min(100, 25*(8-pc.stats("int")))), lang.label_item_use_failure)) <NEW_LINE> L.append("") <NEW_LINE> y = 0 <NEW_LINE> for line in L: <NEW_LINE> <INDENT> self.screen.addstr_color(y, 0, line, c_yellow) <NEW_LINE> y += 1 <NEW_LINE> <DEDENT> self.screen.addstr_color(y+1, 0, "^Y^%s" % lang.prompt_any_key) <NEW_LINE> self.GetKey() <NEW_LINE> self.screen.clear() | Show a detailed player stats screen. | 625941c1656771135c3eb7e7 |
def portal_disconnect_all(self): <NEW_LINE> <INDENT> self._disconnect_all = True <NEW_LINE> for session in self.values: <NEW_LINE> <INDENT> session.disconnect() <NEW_LINE> <DEDENT> del self._disconnect_all | Called from Portal when Portal is closing down. All
Sessions should die. The Portal should not be informed. | 625941c15fdd1c0f98dc01ad |
def testRestartLastProcEmptyDb(self): <NEW_LINE> <INDENT> self.restart_with_empty_db('lastproc') | Verify we can start up in lastproc mode with an empty DB
| 625941c176e4537e8c3515eb |
def attrs(*args, **kwargs): <NEW_LINE> <INDENT> attributes = {} <NEW_LINE> for arg in args: <NEW_LINE> <INDENT> if isinstance(arg, tuple): <NEW_LINE> <INDENT> if len(arg) == 2: <NEW_LINE> <INDENT> attributes[arg[0]] = arg[1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exception('illegal argument') <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> attributes[arg] = True <NEW_LINE> <DEDENT> <DEDENT> attributes.update(kwargs) <NEW_LINE> buf = [] <NEW_LINE> for key, value in attributes.iteritems(): <NEW_LINE> <INDENT> if value: <NEW_LINE> <INDENT> key = unicode(key) <NEW_LINE> if key.endswith('_'): <NEW_LINE> <INDENT> key = key[:-1] <NEW_LINE> <DEDENT> if value is True: <NEW_LINE> <INDENT> buf.append(key) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if isinstance(value, (list, tuple)): <NEW_LINE> <INDENT> value = ' '.join([unicode(v) for v in value]) <NEW_LINE> <DEDENT> buf.append('%s="%s"' % (key, escape(unicode(value)))) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return HTML(' '.join(buf) if buf else '') | Convert arguments into a string containing HTML attributes.
Positional arguments can be either strings or key-value tuples. Keyword
arguments map strings to values. Values may be strings, booleans, or
sequences of strings. | 625941c1f8510a7c17cf9676 |
@ffi.def_extern(name="pfx_table_callback") <NEW_LINE> def pfx_table_callback(pfx_record, object_handle): <NEW_LINE> <INDENT> callback, data = ffi.from_handle(object_handle) <NEW_LINE> callback(PFXRecord(pfx_record), data) | Wraps the pfx_table callback, used for iteration of the pfx table,
to hide cffi specifics | 625941c13eb6a72ae02ec452 |
def skipgram_batches(corpus_data, batch_size, num_skips, context_window): <NEW_LINE> <INDENT> buffer_index = 0 <NEW_LINE> assert batch_size % num_skips == 0 <NEW_LINE> assert num_skips <= 2 * context_window <NEW_LINE> input_words = np.ndarray(shape=(batch_size), dtype=np.int32) <NEW_LINE> context_words = np.ndarray(shape=(batch_size, 1), dtype=np.int32) <NEW_LINE> span = 2 * context_window + 1 <NEW_LINE> buffer = collections.deque(maxlen=span) <NEW_LINE> for _ in range(span): <NEW_LINE> <INDENT> buffer.append(corpus_data[buffer_index]) <NEW_LINE> buffer_index = (buffer_index + 1) % len(corpus_data) <NEW_LINE> <DEDENT> for i in range(batch_size // num_skips): <NEW_LINE> <INDENT> target = context_window <NEW_LINE> targets_to_avoid = [context_window] <NEW_LINE> for j in range(num_skips): <NEW_LINE> <INDENT> while target in targets_to_avoid: <NEW_LINE> <INDENT> target = random.randint(0, span - 1) <NEW_LINE> <DEDENT> targets_to_avoid.append(target) <NEW_LINE> input_words[i * num_skips + j] = buffer[context_window] <NEW_LINE> context_words[i * num_skips + j, 0] = buffer[target] <NEW_LINE> <DEDENT> buffer.append(corpus_data[buffer_index]) <NEW_LINE> buffer_index = (buffer_index + 1) % len(corpus_data) <NEW_LINE> <DEDENT> buffer_index = (buffer_index + len(corpus_data) - span) % len(corpus_data) <NEW_LINE> return input_words, context_words | Generate training data mini-batches using the skip-gram method | 625941c1046cf37aa974ccc5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.