code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def singleshot(self, name, target=None, **kwargs): <NEW_LINE> <INDENT> if target is not None: <NEW_LINE> <INDENT> return self.__singleshot.run(name, target=target, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.__singleshot[name]
Handles single shot events specific to this state :param name: :param target: :param kwargs: :return:
625941c3090684286d50ec96
def change_path(self,path): <NEW_LINE> <INDENT> os.chdir(path) <NEW_LINE> log.info('now relocating to '+path) <NEW_LINE> log.info('done') <NEW_LINE> return
Change the current path. Parameters ---------- Path: string Path name Return ------ None.
625941c34a966d76dd550fc0
def _world_tick_planets(self): <NEW_LINE> <INDENT> for planet in self._planets: <NEW_LINE> <INDENT> mps = planet.res_per_hour.met / 3600 <NEW_LINE> cps = planet.res_per_hour.cry / 3600 <NEW_LINE> dps = planet.res_per_hour.deit / 3600 <NEW_LINE> planet.res_current.met += mps <NEW_LINE> planet.res_current.cry += cps <NEW...
This should do the following: - increase planet resources every second - move planet buildings progress :return: None
625941c329b78933be1e5661
def build_label(self, nombrecampo): <NEW_LINE> <INDENT> nombres = {'planta': 'Trabaja en planta', 'activo': 'Trabajador con alta en la empresa', 'categoriaLaboralID': 'Categoría laboral', 'centroTrabajoID': 'Centro de trabajo', 'dni': 'DNI', 'nomina': 'Sueldo base', 'apellidos': '<b>Apellidos</b>', 'nombre': '<b>Nombre...
Construye la etiqueta correspondiente a "nombrecampo".
625941c392d797404e30413c
def clean_dates(self, task): <NEW_LINE> <INDENT> user_tz = self.env.user.tz or pytz.utc <NEW_LINE> if len(task['start_date']) > 16: <NEW_LINE> <INDENT> task['start_date'] = datetime.datetime.strptime( task['start_date'][:-8], "%Y-%m-%dT%H:%M").astimezone(pytz.timezone(user_tz)).strftime('%Y-%m-%d %H:%M') <NEW_LINE> <DE...
pulisce le date di una task con il fuso orario e il formato giusto in modo che vengano accettate dall'ORM di odoo :param task: :return:
625941c3d8ef3951e32434ef
def import_csv_data(mode): <NEW_LINE> <INDENT> print("Starting import data...") <NEW_LINE> InitialImport.UploadCollData.coll_data_handler(mode, collCSV) <NEW_LINE> InitialImport.UploadPhenoData.pheno_data_handler(mode, phenoCSV) <NEW_LINE> print("Data has been imported into postgres DB")
import_csv_data imports csv files, formats them, and stores them in db mode - 0 = print data, 1 = push data to SQL table
625941c36fb2d068a760f04e
@click.command() <NEW_LINE> @click.pass_context <NEW_LINE> @click.option( '--scenario-name', '-s', default=base.MOLECULE_DEFAULT_SCENARIO_NAME, help='Name of the scenario to target. ({})'.format( base.MOLECULE_DEFAULT_SCENARIO_NAME)) <NEW_LINE> def lint(ctx, scenario_name): <NEW_LINE> <INDENT> args = ctx.obj.get('args'...
Lint the role.
625941c376e4537e8c351623
def setResults(self, results): <NEW_LINE> <INDENT> sum_kills = 0 <NEW_LINE> sum_lives = 0 <NEW_LINE> for result in results: <NEW_LINE> <INDENT> if "ship_id" not in result or "kills" not in result or "lives" not in result: <NEW_LINE> <INDENT> raise Exception("Missing values in ship_results dictionary") <NEW_LINE> <DEDEN...
Set result of battle. Check the consistency of input data. Confirm the correct results @param results: array of {ship_id:x, kills:x, lives:x} dictionaries
625941c3c432627299f04bf7
def _build_datasets(self): <NEW_LINE> <INDENT> self.datasets = data_partitioner.load_dataset(Constants.config['root_dir'], Constants.config['dataset']) <NEW_LINE> self.data_interface = DataInterface(self.datasets)
Retrieve the train/test datasets
625941c32eb69b55b151c860
def readPointsFile(filename): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> fd = open(filename, 'r') <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> msg = "Can't find points file '%s'" % filename <NEW_LINE> raise RuntimeError(msg) <NEW_LINE> <DEDENT> layer_data = [] <NEW_LINE> for (lnum, line) in enumerate(fd.re...
Read a file of points data into memory. filename path to the points data Returns a list of [lon, lat, ...]. Any fields after lon & lat are split on space and added to data list.
625941c3379a373c97cfaaf6
def __init__(self, jobs=None): <NEW_LINE> <INDENT> self._jobs = None <NEW_LINE> self.discriminator = None <NEW_LINE> if jobs is not None: <NEW_LINE> <INDENT> self.jobs = jobs
JobPartsDto - a model defined in Swagger
625941c3e64d504609d747f2
def _cleanup_links_qemu(self): <NEW_LINE> <INDENT> qemu_path = os.path.join(self.test_builddir, self.QEMU_BIN) <NEW_LINE> qemu_img_path = os.path.join(self.test_builddir, self.QEMU_IMG_BIN) <NEW_LINE> qemu_io_path = os.path.join(self.test_builddir, self.QEMU_IO_BIN) <NEW_LINE> qemu_fs_proxy_path = os.path.join(self.tes...
Removes previously created links, if they exist :return: None
625941c3956e5f7376d70e21
def on_message(self, message): <NEW_LINE> <INDENT> pass
Called when a message has been decoded from the SockJS session. The message is what was sent from the SockJS client, this could be a simple string or a dict etc. It is up to subclasses to handle validation of the message.
625941c355399d3f05588666
def digits_to_words(input_string): <NEW_LINE> <INDENT> digit_string = "" <NEW_LINE> number = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] <NEW_LINE> for i in input_string: <NEW_LINE> <INDENT> if i.isdigit(): <NEW_LINE> <INDENT> if digit_string != "": <NEW_LINE> <INDENT> digit_string ...
인풋으로 받는 스트링에서 숫자만 추출하여 영어 단어로 변환하여 단어들이 연결된 스트링을 반환함 아래의 요건들을 충족시켜야함 * 반환하는 단어들은 영어 소문자여야함 * 단어들 사이에는 띄어쓰기 한칸이 있음 * 만약 인풋 스트링에서 숫자가 존재하지 않는 다면, 빈 문자열 (empty string)을 반환함 Parameters: input_string (string): 영어로 된 대문자, 소문자, 띄어쓰기, 문장부호, 숫자로 이루어진 string ex - "Zip Code: 19104" Returns: digit...
625941c3498bea3a759b9a62
def _decide_row_lfs(self, row, column): <NEW_LINE> <INDENT> lfs_oid = _lfs_oid(row, column) <NEW_LINE> if lfs_oid is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> _set_decided_lfs(row, column) <NEW_LINE> if column == self._gdest_column: <NEW_LINE> <INDENT> row.p4_request = common.P4_REQUEST_LFS_COPY <NEW_L...
If this file is tracked by LFS, then record a decision to 'p4 copy' it from LFS de-dupe storage. Sets p4_request and p4filetype, through the RowWrapper. Return True if decided to copy LFS, False if not.
625941c34a966d76dd550fc1
def test_item_model_represents_object_by_name(self): <NEW_LINE> <INDENT> self.assertIn("Enjoy", str(Item.query.all()))
Test the __repr__ of the Item model.
625941c376e4537e8c351624
def register_function(self): <NEW_LINE> <INDENT> self.show_message( main_handler.insert(self.sales_text.toPlainText(), self.purchases_text.toPlainText()))
Show the result of the insertion to the user.
625941c3cb5e8a47e48b7a5f
def wrapped(cls): <NEW_LINE> <INDENT> for name, path in suite_paths: <NEW_LINE> <INDENT> def test_suite(self): <NEW_LINE> <INDENT> return SelexeRunner(path, **self.options).run() <NEW_LINE> <DEDENT> test_suite.__name__ = 'test_%s' % ''.join(i if i in ALPHADIGIT else '_' for i in name) <NEW_LINE> test_suite.__doc__ = 'S...
Inner wrapper for 'include_selexe_tests' decorator. This function must be called with the class-to-decorate as its only argument. This function uses arguments given to 'include_selexe_tests' for adding 'test_'-prefixed methods to class. @param cls: class to decorate @return given class
625941c3a219f33f3462891f
def close_all(self, closer_method='close'): <NEW_LINE> <INDENT> for conn in self._connections: <NEW_LINE> <INDENT> getattr(conn, closer_method)() <NEW_LINE> <DEDENT> self.empty_cache() <NEW_LINE> return self.current
Closes connections using given closer method and empties cache. If simply calling the closer method is not adequate for closing connections, clients should close connections themselves and use :meth:`empty_cache` afterwards.
625941c3236d856c2ad4478b
def __draw_snap_indicator(self, cr): <NEW_LINE> <INDENT> offset = self.get_hadjustment().get_value() <NEW_LINE> x = self.nsToPixel(self.snap_position) - offset <NEW_LINE> if x <= 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.__draw_vertical_bar(cr, x, SNAPBAR_WIDTH, SNAPBAR_COLOR)
Draws a snapping indicator line.
625941c316aa5153ce36242b
def push_file(filename, parent=None): <NEW_LINE> <INDENT> if(os.path.isdir(filename)): <NEW_LINE> <INDENT> print("%s is a directory, use: push -r %s to upload recursively" % (filename, filename)) <NEW_LINE> return; <NEW_LINE> <DEDENT> if(not os.path.isfile(filename)): <NEW_LINE> <INDENT> print("Can not find %s, no such...
Uploads a file to google drive
625941c3d6c5a10208143ffc
def test_register_delete_view(self): <NEW_LINE> <INDENT> self.login("awilliam") <NEW_LINE> user = get_user_model().objects.get(username="awilliam") <NEW_LINE> phone = PhoneRegistration.objects.create(user=user, manufacturer="other", imei="351756051523999", description="A phone") <NEW_LINE> calc = CalculatorRegistration...
Test register_delete_view, the view to delete a registered item.
625941c31f5feb6acb0c4b06
def validate(self, standalone): <NEW_LINE> <INDENT> return True
Perform validation
625941c34c3428357757c2dd
def describe_restaurant(self): <NEW_LINE> <INDENT> print(f"{self.restaurant_name} is a new restaurant opening on Main Street!") <NEW_LINE> print(f"The restaurant specializes in {self.cuisine_type}.")
Description of the restaurant
625941c3435de62698dfdbff
def get_relations_attributes(self): <NEW_LINE> <INDENT> cursor = self.conn.cursor() <NEW_LINE> q = ( "SELECT c.table_name, c.column_name FROM information_schema.columns c " "INNER JOIN information_schema.tables t ON c.table_name = t.table_name " "AND c.table_schema = t.table_schema " "AND t.table_type = 'BASE TABLE' " ...
Returns relations and their attributes Uses tables/attributes from the database but also aliases found on the dataset's queries Args: None Returns: relations: list ['alias1','alias2',..] relations_attributes: dict {'alias1':['attr1','attr2',..], .. }
625941c350812a4eaa59c2d6
def __init__(self, k=None, W=None, alpha=100, init='random', n_inits=1, tol=1e-3, max_iter=1000, n_jobs=1, parallel_backend='multiprocessing'): <NEW_LINE> <INDENT> self.k = k <NEW_LINE> self.W = W <NEW_LINE> if W is not None: <NEW_LINE> <INDENT> self.D = sparse.coo_matrix(np.diagflat(W.sum(axis=1))) <NEW_LINE> self.L =...
k: number of components W: Adjacency matrix of the nearest neighboor matrix alpha: regularization parameter init: 'random' initializes to a random W,H n_inits: number of runs to make with different random inits (in order to avoid being stuck in local minima) n_jobs: number of paralle...
625941c34e696a04525c93ff
def message_subscribe(self, partner_ids=None, channel_ids=None, subtype_ids=None): <NEW_LINE> <INDENT> res = super(Outsourcing, self).message_subscribe(partner_ids=partner_ids, channel_ids=channel_ids, subtype_ids=subtype_ids) <NEW_LINE> outsourcing_subtypes = self.env['mail.message.subtype'].browse(subtype_ids) if sub...
Subscribe to all existing active tasks when subscribing to a outsourcing
625941c376d4e153a657eae3
def test_manager_cache_relationships_only_sub(self): <NEW_LINE> <INDENT> team = Team.objects.create() <NEW_LINE> for i in range(5): <NEW_LINE> <INDENT> Account.objects.create(team=team) <NEW_LINE> <DEDENT> with self.assertNumQueries(3): <NEW_LINE> <INDENT> entities = Entity.objects.cache_relationships(cache_super=False...
Tests a retrieval of cache relationships on the manager and verifies it results in the smallest amount of queries when only caching sub entities.
625941c366656f66f7cbc15d
def get_symmetrized_structure(self): <NEW_LINE> <INDENT> ds = self.get_symmetry_dataset() <NEW_LINE> sg = SpacegroupOperations(self.get_space_group_symbol(), self.get_space_group_number(), self.get_symmetry_operations()) <NEW_LINE> return SymmetrizedStructure(self._structure, sg, ds["equivalent_atoms"])
Get a symmetrized structure. A symmetrized structure is one where the sites have been grouped into symmetrically equivalent groups. Returns: :class:`pymatgen.symmetry.structure.SymmetrizedStructure` object.
625941c3851cf427c661a4c4
def update_dir_names(all_lowercase): <NEW_LINE> <INDENT> if os.path.exists("../pluginApp"): <NEW_LINE> <INDENT> os.rename("../pluginApp", "../"+all_lowercase+"App")
Updates the name of the main plugin directory
625941c33c8af77a43ae3751
def _bfs(objs, get_referrers, ignore=None, action=None, getid=id): <NEW_LINE> <INDENT> import types <NEW_LINE> visited = set() <NEW_LINE> referrers = list(objs) <NEW_LINE> extraids = set() <NEW_LINE> extraids.add(getid(objs)) <NEW_LINE> while True: <NEW_LINE> <INDENT> front = [] <NEW_LINE> for ref in referrers: <NEW_LI...
A breadth first search traverse of the graph.
625941c3d4950a0f3b08c304
def get_rgb(self, index): <NEW_LINE> <INDENT> index = int(index) <NEW_LINE> return tuple(self.arr[index])
Return a tuple of (R, G, B) values in the 0-maxc range associated mapped by the value of `index`.
625941c3ff9c53063f47c1a7
def tearDown(self): <NEW_LINE> <INDENT> self.report_timeout() <NEW_LINE> self._teardown_errors = self.pre_tear_down() <NEW_LINE> self._teardown_errors.extend(self.stop_job_managers()) <NEW_LINE> self._teardown_errors.extend(self.destroy_containers(self.container)) <NEW_LINE> self._teardown_errors.extend(self.destroy_po...
Tear down after each test case.
625941c371ff763f4b54963b
def list_cortana_endpoints( self, custom_headers=None, raw=False, **operation_config): <NEW_LINE> <INDENT> url = self.list_cortana_endpoints.metadata['url'] <NEW_LINE> path_format_arguments = { 'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True) } <NEW_LINE> url = self....
Gets the endpoint URLs for the prebuilt Cortana applications. :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return:...
625941c3d58c6744b4257c13
def getOptimizer(opt: str): <NEW_LINE> <INDENT> import os <NEW_LINE> from keras import optimizers as k_opt <NEW_LINE> if not os.path.isfile(default_opt_cfg): <NEW_LINE> <INDENT> writeDefaultConfig() <NEW_LINE> <DEDENT> opt_cfg = configparser.ConfigParser() <NEW_LINE> opt_cfg.read(default_opt_cfg) <NEW_LINE> if opt == '...
Returns a Keras optimizer object
625941c3498bea3a759b9a63
def vect_from_qarray(q): <NEW_LINE> <INDENT> v = scipy.array(q[:,1:]) <NEW_LINE> return v
Return vector array from quaternion array
625941c33c8af77a43ae3752
def Meld(*args): <NEW_LINE> <INDENT> return _MEDCouplingCorba.DataArrayInt_Meld(*args)
Meld(DataArrayInt a1, DataArrayInt a2) -> DataArrayInt Meld(std::vector<(p.q(const).ParaMEDMEM::DataArrayInt,std::allocator<(p.q(const).ParaMEDMEM::DataArrayInt)>)> arr) -> DataArrayInt Meld(PyObject li) -> DataArrayInt 1
625941c396565a6dacc8f67f
def get_reset_channel(self): <NEW_LINE> <INDENT> return self._reset_send.clone()
Get a channel that can send resets to the rate limiter. :rtype: trio.ReceiveChannel
625941c3009cb60464c63366
def test_get_dataset_files(self): <NEW_LINE> <INDENT> pass
Test case for get_dataset_files Get Dataset Files # noqa: E501
625941c345492302aab5e275
def write_index(self, outdir, froot="index", relative_to=None, rst_extension=".rst"): <NEW_LINE> <INDENT> if self.written_usecases is None: <NEW_LINE> <INDENT> raise ValueError('No modules written') <NEW_LINE> <DEDENT> path = os.path.join(outdir, froot + rst_extension) <NEW_LINE> if relative_to is not None: <NEW_LINE> ...
Make a reST API index file from written files Parameters ---------- outdir : string (mandatory) Directory to which to write generated index file froot : string (optional) root (filename without extension) of filename to write to Defaults to 'index'. We add ``rst_extension``. relative_to : string path ...
625941c329b78933be1e5662
def ensure_iso_8859_15_only(commit): <NEW_LINE> <INDENT> if git_config("hooks.no-rh-character-range-check"): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for lineno, line in enumerate(commit.raw_revlog_lines, start=1): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> line.encode("ISO-8859-15") <NEW_LINE> <DEDENT> except ...
Raise InvalidUpdate if the revision log contains non-ISO-8859-15 chars. The purpose of this check is make sure there are no unintended characters that snuck in, particularly non-printable characters accidently copy/pasted (this has been seen on MacOS X for instance, where the <U+2069> character was copy/pasted without...
625941c3090684286d50ec97
def stop(self): <NEW_LINE> <INDENT> if self._play_thread is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not self._play_thread.is_alive(): <NEW_LINE> <INDENT> self._play_thread = None <NEW_LINE> return <NEW_LINE> <DEDENT> global event_queue <NEW_LINE> event_queue.put({'key':EVENT_STOP}) <NEW_LINE> while self...
Stops the current playback and cancels the playing thread.
625941c3de87d2750b85fd44
def get_template( self, url, dest, template='jinja', makedirs=False, saltenv='base', cachedir=None, **kwargs): <NEW_LINE> <INDENT> if 'env' in kwargs: <NEW_LINE> <INDENT> salt.utils.warn_until( 'Oxygen', 'Parameter \'env\' has been detected in the argument list. This ' 'parameter is no longer used and has been replace...
Cache a file then process it as a template
625941c3b57a9660fec33836
def watcher(fn): <NEW_LINE> <INDENT> @functools.wraps(fn) <NEW_LINE> def _watcher(*, config, num=None, **kwargs): <NEW_LINE> <INDENT> name = fn.__name__ <NEW_LINE> if num is not None: <NEW_LINE> <INDENT> name += "-" + str(num) <NEW_LINE> <DEDENT> with file_logger.FileLogger(config.path, name, config.quiet) as logger: <...
A decorator to fn/processes that gives a logger and logs exceptions.
625941c3925a0f43d2549e29
def run(args: argparse.Namespace) -> None: <NEW_LINE> <INDENT> lister = MergeRequestList(args.project, args.merged, args.opened, args.closed, args.url) <NEW_LINE> lister.print_formatted_list()
run merge request list command :param args: parsed arguments
625941c33cc13d1c6d3c732e
def testNumber(self): <NEW_LINE> <INDENT> num = ee.Number(1) <NEW_LINE> self.assertEqual(1, num.encode()) <NEW_LINE> computed = ee.Number(1).add(2) <NEW_LINE> self.assertIsInstance(computed, ee.Number) <NEW_LINE> self.assertEqual(ee.ApiFunction.lookup('Number.add'), computed.func) <NEW_LINE> self.assertEqual({ 'left': ...
Verifies basic behavior of ee.Number.
625941c38e05c05ec3eea326
def pad_identities_right(self, d, L): <NEW_LINE> <INDENT> npad = L - self.iend <NEW_LINE> self.oplist += [np.identity(d) for _ in range(npad)] <NEW_LINE> self.qD += npad*[0]
Pad identity matrices on the right.
625941c3d58c6744b4257c14
def Process(self, save = True): <NEW_LINE> <INDENT> self.ReadData(); <NEW_LINE> self.Filter(); <NEW_LINE> self.Normalize(); <NEW_LINE> self.Transform(); <NEW_LINE> if save: <NEW_LINE> <INDENT> self.Save(); <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logging.info("Skipping save as it was passed to this method")
To automate the preprocessing procedure in one go! returns: None class variable return: method based modification: method based
625941c3aad79263cf3909f2
def tabOpen(self, tab_name): <NEW_LINE> <INDENT> for other_tab_name in self._page_tabs.tabNames(): <NEW_LINE> <INDENT> if tab_name == other_tab_name: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False
Checks if the selected tab name already exists within the tabs.
625941c371ff763f4b54963c
def get_LogNegNum(CovM): <NEW_LINE> <INDENT> V = np.linalg.det(CovM) <NEW_LINE> A = np.linalg.det(CovM[:2, :2]) <NEW_LINE> B = np.linalg.det(CovM[2:, 2:]) <NEW_LINE> C = np.linalg.det(CovM[:2, 2:]) <NEW_LINE> sigma = A + B - 2.0 * C <NEW_LINE> if sigma*sigma-4.0*V < 0.0: <NEW_LINE> <INDENT> return 0.0 <NEW_LINE> <DEDEN...
function to calculate Log-Negativity from a covariance matrix CovM looks a bit like: I1 I1I1 I1Q1 I1I2 I1Q2 Q1 Q1I1 Q1Q1 Q1I2 Q1Q2 I2 I2I1 I2Q1 I2I2 I2Q2 Q2 Q2I1 Q2Q1 Q2I2 Q2Q2 I1 Q1 I2 Q2
625941c3a17c0f6771cbe006
def call(self, inputs, state): <NEW_LINE> <INDENT> sigmoid = math_ops.sigmoid <NEW_LINE> input_size = inputs.get_shape().with_rank(2).dims[1] <NEW_LINE> if input_size.value is None: <NEW_LINE> <INDENT> raise ValueError("Could not infer input size from inputs.get_shape()[-1]") <NEW_LINE> <DEDENT> with vs.variable_scope(...
Run one step of UGRNN. Args: inputs: input Tensor, 2D, batch x input size. state: state Tensor, 2D, batch x num units. Returns: new_output: batch x num units, Tensor representing the output of the UGRNN after reading `inputs` when previous state was `state`. Identical to `new_state`. new_state: batch ...
625941c3ac7a0e7691ed4083
def GetAllCompany(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!')
获取所有公司
625941c366673b3332b92044
def Variables(self, x_in, y_in, z_in, theta, direction): <NEW_LINE> <INDENT> altitude = round(z_in/float(1000), 2) <NEW_LINE> font = pygame.font.SysFont("Arial", 15) <NEW_LINE> sprites = pygame.sprite.Group() <NEW_LINE> altitude_group = pygame.sprite.Group() <NEW_LINE> direction_sprite = pygame.sprite.Sprite() <NEW_LIN...
display the location of the object
625941c3bde94217f3682da6
def get_cargo_by_sequence_number(self, sequence_number): <NEW_LINE> <INDENT> return self.cargoes[sequence_number]
:rtype: Cargo
625941c3a4f1c619b28afff1
def test_ensemble(tmpdir, request, H0, H1, L1, L2, pop1, pop2): <NEW_LINE> <INDENT> filename = request.module.__file__ <NEW_LINE> test_dir, _ = os.path.splitext(filename) <NEW_LINE> psi = np.array([0, 1, 1, 0], dtype=np.complex128) / np.sqrt(2.0) <NEW_LINE> pulse = AnalyticalPulse.from_func( partial(blackman, t_start=0...
Test ensemble of multiple Hamiltonians
625941c38e71fb1e9831d75e
def get_welcome_message(self, user): <NEW_LINE> <INDENT> username = user.first_name if user.first_name else user.username <NEW_LINE> return mark_safe('<strong>Welcome back to %s, %s.</strong><br/>%s' % ( self.get_site_name(), username, ('Your last login was on %s (%s).' % ( filter_date(user.last_login), naturaltime(use...
Return welcome message addressing the user who logged in.
625941c3bde94217f3682da7
def test_post_watermark(self): <NEW_LINE> <INDENT> pass
Test case for post_watermark Add custom watermark
625941c391f36d47f21ac4a4
def share_data(self, override_previous=True, **parameters): <NEW_LINE> <INDENT> if not self.IS_COMPLEX: <NEW_LINE> <INDENT> self.parent._set_parameters(override_previous=override_previous, **parameters) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._set_parameters(override_previous=override_previous, **parameters)
Inject the parameters to the parent and sibling components. Args: override_previous (bool): whether to override previous value of the parameters if they were already injected or not.
625941c344b2445a3393204b
def test_count_data_test_1(self): <NEW_LINE> <INDENT> row_count = self.fetcher.count_data(text='test_1') <NEW_LINE> self.assertEqual(row_count, 10)
text=test_1
625941c33346ee7daa2b2d1f
def finish_initializing(self, builder): <NEW_LINE> <INDENT> self.builder = builder <NEW_LINE> self.ui = builder.get_ui(self)
Called when we're finished initializing. finish_initalizing should be called after parsing the ui definition and creating a PreviewDialog object with it in order to finish initializing the start of the new PreviewDialog instance.
625941c3fb3f5b602dac3645
def __init__(self, arch='r2plus1d_18', pretrained=True, progress=True, block=BasicBlock, conv_makers=[Conv2Plus1D] * 4, layers=[2, 2, 2, 2], stem=R2Plus1dStem, keyfeatures=512, zero_init_residual=False): <NEW_LINE> <INDENT> super(VideoResNetAttention3C, self).__init__() <NEW_LINE> self.inplanes = 64 <NEW_LINE> self.ste...
Generic resnet video generator. Args: block (nn.Module): resnet building block conv_makers (list(functions)): generator function for each layer layers (List[int]): number of blocks per layer stem (nn.Module, optional): Resnet stem, if None, defaults to conv-bn-relu. Defaults to None. num_classes (i...
625941c3293b9510aa2c324c
def authenticate(func): <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> def authenticate_and_call(*args, **kwargs): <NEW_LINE> <INDENT> flag = False <NEW_LINE> can_auth = request.json and 'session_id' in request.json <NEW_LINE> if can_auth: <NEW_LINE> <INDENT> flag = authentication_check( request.json['session_id'])['statu...
AuthN decorator. Applying this decorator to a method will require any request to successfully pass an authentication challenge or return an error response. :param func: Method to decorate :type func: callable :return: Wrapped method :rtype: callable
625941c331939e2706e4ce20
def populate_database(self): <NEW_LINE> <INDENT> self.dye_stocks.add_new_dye_stocks() <NEW_LINE> self.detections.add_new_detections() <NEW_LINE> self.profiles.add_new_profiles()
Adds the data to the database. Run this only after parsing all database entries. That way errors will be detected before database entry.
625941c3fbf16365ca6f6174
def time_alive(self): <NEW_LINE> <INDENT> return time.time() - self._time
Retourne le temps depuis lequel le socket n'a pas ete utilise
625941c385dfad0860c3ae0e
def __init__(self, channels, colorspace): <NEW_LINE> <INDENT> colorspace = colorspace.lower() <NEW_LINE> if colorspace not in self.COLORSPACES: <NEW_LINE> <INDENT> raise ValueError('Colorspace must be one of %s.' % self.COLORSPACES) <NEW_LINE> <DEDENT> self.colorspace = colorspace <NEW_LINE> datatype = self.COLORSPACE_...
channels: a tuple colorspace: hsv or rgb
625941c323e79379d52ee51a
def test_related_tree_manager(self): <NEW_LINE> <INDENT> self.assertIs(type(Page.objects.get_for_path('/').children.all()), UrlNodeQuerySet) <NEW_LINE> self.assertEqual(Page.objects.get_for_path('/').children.in_navigation()[0].slug, 'level1')
The tree manager should get the same abilities as the original manager. This was broken in django-mptt 0.5.2
625941c3e76e3b2f99f3a7c3
def test_pairwise_align_sequences_with_gaps_in_first_sequence(self): <NEW_LINE> <INDENT> seq1 = "GSNAKFGLWVDGNCEDIPHVNEFPAID" <NEW_LINE> seq1_bio = Seq(seq1) <NEW_LINE> seq2 = "NAKFLWVDG" <NEW_LINE> seq2_bio = Seq(seq2) <NEW_LINE> test_map_reverse, test_map_forward = seqtools.pairwise_align(seq2, seq1) <NEW_LINE> forwa...
Test with reverse input (ie gaps in first sequence)
625941c36aa9bd52df036d57
def _update_lp(self, dmu_code): <NEW_LINE> <INDENT> self._concrete_model.update_objective(self.input_data, dmu_code, self._input_variables, self._output_variables, self.lp_model) <NEW_LINE> self._concrete_model.update_equality_constraint(self.input_data, dmu_code, self._input_variables, self._output_variables, self.lp_...
Updates existing linear program with coefficients corresponding to a given DMU. Args: dmu_code (str): DMU code.
625941c373bcbd0ca4b2c02a
def mouseReleaseEvent(self, event): <NEW_LINE> <INDENT> super(TabBarDe, self).mouseReleaseEvent(event) <NEW_LINE> self.mPos = None <NEW_LINE> event.accept()
鼠标弹起事件
625941c3ec188e330fd5a757
def part2(entries: list) -> int: <NEW_LINE> <INDENT> count = 0 <NEW_LINE> for group in entries: <NEW_LINE> <INDENT> for key in group[1].keys(): <NEW_LINE> <INDENT> if group[1][key] == group[0]: <NEW_LINE> <INDENT> count += 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return count
part2 solver take a list of sets and return an int
625941c321bff66bcd684909
def put(self, key, value): <NEW_LINE> <INDENT> if key in self.setkeys: <NEW_LINE> <INDENT> for i in range(len(self.keys)): <NEW_LINE> <INDENT> if self.keys[i] == key: <NEW_LINE> <INDENT> self.values[i] = value <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.keys.append(key) <NEW_LINE> self.values.append(va...
value will always be non-negative. :type key: int :type value: int :rtype: void
625941c3187af65679ca50d2
def isoweekday(): <NEW_LINE> <INDENT> pass
Return the day of the week as an integer. Monday is 1 and Sunday is 7. The same as self.date().isoweekday. .. seealso:: `weekday`, `isocalendar`.
625941c3a4f1c619b28afff2
def store_tracer(self): <NEW_LINE> <INDENT> match_dict = self.get_all_matches() <NEW_LINE> with h5py.File(self.storage_file, 'w') as f: <NEW_LINE> <INDENT> for snap_id, matches in match_dict.items(): <NEW_LINE> <INDENT> h5_group = '/Heritage/{}/{}'.format(self.branching, str(snap_id)) <NEW_LINE> f.create_group(h5_group...
Save another copy of the matches into a NumPy file.
625941c321a7993f00bc7ca1
def asrequirement(self): <NEW_LINE> <INDENT> return u"%s(=%s)" % (self.package,self.version)
Return package and version for designing this package in depends or install actions Returns: str: "packagename (=version)"
625941c3b830903b967e98c1
def parse(self, content): <NEW_LINE> <INDENT> self.found = False <NEW_LINE> self.anime = None <NEW_LINE> self.feed(content) <NEW_LINE> title = self.anime.strip().replace( ' - MyAnimeList.net', '') if self.found else None <NEW_LINE> return dict(title=title)
Parse content and return object
625941c34a966d76dd550fc2
def setup(root=None, settings_module_name=None): <NEW_LINE> <INDENT> root = root or os.path.dirname(os.path.abspath(__file__)) <NEW_LINE> path = lambda *a: os.path.join(root, *a) <NEW_LINE> settings_module_name = settings_module_name or 'settings' <NEW_LINE> settings = import_module(settings_module_name) <NEW_LINE> if ...
Simple setup snippet that makes easy to create fast sandbox to try new things. :param root: the root of your project :param settings_module_name: name of settings module eg: "project.setting" Usage: >>> import env >>> env.setup() >>> # from now on paths are setup, and django is configured >>> # you can use it in...
625941c32eb69b55b151c861
def test_options_structure(self): <NEW_LINE> <INDENT> deploy = self.wsgiDeploy() <NEW_LINE> expected_keys = self.DEFAULTS.keys() <NEW_LINE> actual_keys = deploy.options.keys() <NEW_LINE> self.assertListEqual(expected_keys, actual_keys)
A test to ensure that HendrixDeploy.options also has the complete set of options available
625941c3de87d2750b85fd45
def count_possible_inputs(meta_data, networks): <NEW_LINE> <INDENT> input_counts = [defaultdict(int) for g in xrange(meta_data.G)] <NEW_LINE> for net in networks: <NEW_LINE> <INDENT> for g in xrange(meta_data.G): <NEW_LINE> <INDENT> input_counts[g][net.input_parameters[g]] += 1 <NEW_LINE> <DEDENT> <DEDENT> return input...
Count how often each possible input parameters occurs.
625941c3cdde0d52a9e52fe6
def cmd_user(self, line): <NEW_LINE> <INDENT> if len(line) > 1: <NEW_LINE> <INDENT> self.user = line[1] <NEW_LINE> self.respond('331 Password required.') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.command_not_understood(string.join(line))
specify user name
625941c31b99ca400220aa66
def tupleify_state(state): <NEW_LINE> <INDENT> temp = [] <NEW_LINE> for row in state: <NEW_LINE> <INDENT> temp.append(tuple(row)) <NEW_LINE> <DEDENT> return tuple(temp)
Returns the state as a tuple
625941c329b78933be1e5663
def nextAction(game, player): <NEW_LINE> <INDENT> output("What do you want to do today ?") <NEW_LINE> connections = game.rooms[player.where].connections <NEW_LINE> names = [] <NEW_LINE> for c in connections: <NEW_LINE> <INDENT> if game.rooms[c].explored: <NEW_LINE> <INDENT> names.append(game.rooms[c].description) <NEW_...
ask the user to select only one of many options
625941c3796e427e537b0579
def loc_glbl_var(individual: np.ndarray) -> float: <NEW_LINE> <INDENT> mids = tuple(map(lambda x: int(x/2), individual.shape)) <NEW_LINE> s1 = np.var(individual[:mids[0], :mids[1]]) <NEW_LINE> s2 = np.var(individual[:mids[0], mids[1]:]) <NEW_LINE> s3 = np.var(individual[mids[0]:, :mids[1]]) <NEW_LINE> s4 = np.var(indiv...
Computes score as function of quadrant and global variance :param individual: candidate to score :return: sum of quadrant variance - 5*global variance
625941c315baa723493c3f28
def __init__(self,spec_path='M:\\fwog\\members\\qiu05\\Dec_2017_APS\\fer',spec_name='rcut_cmp_zn_7mm_1.spec',scan_number=[15]+range(17,41), corr_params=CORR_PARAMS, integ_pars=INTEG_PARS, general_labels=GENERAL_LABELS, correction_labels=CORRECTION_LABELS, angl...
spec_path:full path to the directory of the spec file spec_name:full name of the spec file scan_number= []:do nothing but initilize the instance (do this when you want to reload a saved dump data_info file) None: do all rodscan and Escan throughout the spec file [13,14,15,16]:a list of integers specify the ...
625941c38e7ae83300e4af80
def my_service(): <NEW_LINE> <INDENT> logging.debug("Starting") <NEW_LINE> time.sleep(0.3) <NEW_LINE> logging.debug("Stopping")
"thread service function
625941c396565a6dacc8f680
def test_if_delete_allowed_photograph_detail(self): <NEW_LINE> <INDENT> handpiece = Handpiece.objects.get(name="testhandpiece") <NEW_LINE> photograph = Photograph.objects.get(handpiece=handpiece) <NEW_LINE> response = self.client.delete( reverse('api:photograph-detail', kwargs={'pk': photograph.id}), kwargs={'id': 300}...
Test if DELETE method is NOT allowed on photograph detail view.
625941c36fece00bbac2d6f2
def parse_config(path=DEFAULT_CONFIG_PATH, section=None, eval_keys=['metrics', 'queries']): <NEW_LINE> <INDENT> configreader = configparser.RawConfigParser() <NEW_LINE> try: <NEW_LINE> <INDENT> configreader.read(path) <NEW_LINE> configdict = configreader._sections <NEW_LINE> configdict = configdict[section] if section ...
Pares a cfg file, retrieving the requested section as a dictionary Args: section (str): name of the section you'd like to extract eval_keys (list of str): Parser will try to evaluate strings in the config variables for the indicated eval_keys
625941c33d592f4c4ed1d027
def test_parent(self) -> None: <NEW_LINE> <INDENT> state = State() <NEW_LINE> cloned_state = state.clone() <NEW_LINE> assert cloned_state.parent is state <NEW_LINE> del state <NEW_LINE> gc.collect() <NEW_LINE> assert cloned_state.parent is None
Test referencing parent and weak reference handling.
625941c360cbc95b062c64f7
def chunks(iterable, chunk_size: int = 1000): <NEW_LINE> <INDENT> iter_data = iter(iterable) <NEW_LINE> while True: <NEW_LINE> <INDENT> chunk = tuple(itertools.islice(iter_data, chunk_size)) <NEW_LINE> if not chunk: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> yield chunk
split iterable array into chunks >>> chunks(range(6),chunk_size=2) ... [(0,1),(2,3),(4,5)] :param iterable: list, iter :param chunk_size: chunk split size :return: yield iterable values
625941c3d99f1b3c44c67546
@contract(res='dict') <NEW_LINE> def _dynreports_getres(res): <NEW_LINE> <INDENT> return res['f-result']
gets only the result
625941c376e4537e8c351626
def on_intent(intent_request, session): <NEW_LINE> <INDENT> print("on_intent requestId=" + intent_request['requestId'] + ", sessionId=" + session['sessionId']) <NEW_LINE> intent = intent_request['intent'] <NEW_LINE> intent_name = intent_request['intent']['name'] <NEW_LINE> if intent_name == "CityIntent": <NEW_LINE> <IN...
Called when the user specifies an intent for this skill
625941c307f4c71912b11436
def get_stock_balance(code): <NEW_LINE> <INDENT> cpTradeUtil.TradeInit() <NEW_LINE> acc = cpTradeUtil.AccountNumber[0] <NEW_LINE> accFlag = cpTradeUtil.GoodsList(acc, 1) <NEW_LINE> cpBalance.SetInputValue(0, acc) <NEW_LINE> cpBalance.SetInputValue(1, accFlag[0]) <NEW_LINE> cpBalance.SetInputValue(2, 50) <NEW_LINE> cpBa...
인자로 받은 종목의 종목명과 수량을 반환한다.
625941c3be383301e01b543e
def site_read(context, data_dict): <NEW_LINE> <INDENT> return {'success': True}
This function should be deprecated. It is only here because we couldn't get hold of Friedrich to ask what it was for. ./ckan/controllers/api.py
625941c3a219f33f34628921
def mutated_additional_data(func): <NEW_LINE> <INDENT> func_name = func.__name__ <NEW_LINE> @wraps(func) <NEW_LINE> def handle_mutate(session, *args, **kwargs): <NEW_LINE> <INDENT> log.debug("Mutating value on function %s with args %s and kwargs %s" % (func_name, unicode(args), unicode(kwargs))) <NEW_LINE> ret = func(s...
A decorator to track mutation and propagate it to the database. The decorator is to be used on all functions that change the value of the :attr:`Session.additional_data` dict. Functions like ``set`` or ``pop`` need this decorator to ensure the changes are afterwards propagated into the database. From an implementatio...
625941c31d351010ab855ad1
def twoSum(self, nums, target): <NEW_LINE> <INDENT> dict = {} <NEW_LINE> for i in range(len(nums)): <NEW_LINE> <INDENT> x = nums[i] <NEW_LINE> if target - x in dict: <NEW_LINE> <INDENT> return [dict[target - x], i] <NEW_LINE> <DEDENT> dict[x] = i <NEW_LINE> <DEDENT> return []
:type nums: List[int] :type target: int :rtype: List[int]
625941c3656771135c3eb821
def _insert_object_resp(bucket=None, name=None, data=None): <NEW_LINE> <INDENT> assert type(data) is bytes <NEW_LINE> hasher = hashlib.md5() <NEW_LINE> hasher.update(data) <NEW_LINE> md5_hex_hash = hasher.hexdigest() <NEW_LINE> return { u'bucket': bucket, u'name': name, u'md5Hash': _hex_to_base64(md5_hex_hash), u'timeC...
Fake GCS object metadata
625941c3d6c5a10208143ffe
def test_favoriting_referendum_without_existent_user(new_session): <NEW_LINE> <INDENT> from sqlalchemy.exc import IntegrityError <NEW_LINE> new_session.add(make_test_referendum(666)) <NEW_LINE> with pytest.raises(IntegrityError): <NEW_LINE> <INDENT> new_session.flush()
Test the database rejects favoriting a candidate without a user.
625941c36e29344779a625c8
def box(): <NEW_LINE> <INDENT> print("---Box---") <NEW_LINE> D1 = Symbol('D1') <NEW_LINE> D2 = Symbol('D2') <NEW_LINE> D3 = Symbol('D3') <NEW_LINE> D4 = Symbol('D4') <NEW_LINE> h1 = h3 = D3 <NEW_LINE> h2 = D2 - h1 - h3 <NEW_LINE> w1 = w3 = D4 <NEW_LINE> w2 = D1 - w1 - w3 <NEW_LINE> o2 = Rational(1, 2) <NEW_LINE> p1 = [...
y ^ | w1 | w2 w3 | a-----p1------b | | | h1 | e--|----f | | | | | | | | | | | h2 | | o-------|--> x | | | | | h-------g | | | h3 d-------------c # given #a-d = D2 #(f-g)_y = D3 #d-c = D1 #(g-c)_x = D4
625941c37d43ff24873a2c54
def InterpolateValueCore(self,*args): <NEW_LINE> <INDENT> pass
InterpolateValueCore(self: SplineSingleKeyFrame,baseValue: Single,keyFrameProgress: float) -> Single Uses splined interpolation to transition between the previous key frame value and the value of the current key frame. baseValue: The value to animate from. keyFrameProgress: A value between 0.0 and 1.0,i...
625941c3f8510a7c17cf96b0
def read_filtered_directory_content(dirpath, *filters): <NEW_LINE> <INDENT> def filter_directory_files(dirpath, *filters): <NEW_LINE> <INDENT> return it.chain.from_iterable(glob.iglob(dirpath + '/' + filter) for filter in filters) <NEW_LINE> <DEDENT> content_dict = {} <NEW_LINE> for filename in filter_directory_files(d...
Reads the content of a directory, filtered on glob like expressions. Returns a dictionary, with the "key" being the filename and the "value" being the content of that file.
625941c3d18da76e23532489
def __json_struct__(self): <NEW_LINE> <INDENT> if self._value or self._value == 0: <NEW_LINE> <INDENT> super().__json_struct__()
:return:
625941c3ad47b63b2c509f34