code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def test_wrapped_adds_outputs2(self): <NEW_LINE> <INDENT> @has_units(outputs="out: out desc:units=m/s") <NEW_LINE> def func(v1, v2): <NEW_LINE> <INDENT> return v1 + v2 <NEW_LINE> <DEDENT> self.assertTrue(len(func.outputs) == 1) <NEW_LINE> self.assertTrue(func.outputs[0].name == 'out') <NEW_LINE> self.assertTrue(func.ou...
Are output specifications added correctly?
625941ea0c0af96317bb86b3
def dice_single_sample(generated, real): <NEW_LINE> <INDENT> generated = generated.astype(np.int) <NEW_LINE> real = real.astype(np.int) <NEW_LINE> cross_mat = (generated & real) <NEW_LINE> tp = cross_mat.nonzero()[0].shape[0] <NEW_LINE> size_gen = generated.nonzero()[0].shape[0] <NEW_LINE> size_real = real.nonzero()[0]...
Calculates dice between single "binary" generated and real samples :param generated: A batch of generated samples :param real: a batch of real samples :return: Dice score
625941ea21bff66bcd684e19
def generic_count(start, step): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> yield start <NEW_LINE> start += step
A generic version of `itertools.count` which works with anything that has an addition operator, ie. datetime objects.
625941ea498bea3a759b9f79
def test_rar(self): <NEW_LINE> <INDENT> if not rarfile: <NEW_LINE> <INDENT> raise SkipTest('Needs RarFile module.') <NEW_LINE> <DEDENT> shutil.copy(self.rar_name, self.temp_rar) <NEW_LINE> self.execute_task('test_rar') <NEW_LINE> assert os.path.exists(self.temp_out), 'Output file does not exist at the correct path.' <N...
Test basic RAR extraction
625941ea7b25080760e39922
def test_add_comment_auth(self): <NEW_LINE> <INDENT> c = Client() <NEW_LINE> user = User.objects.create_user('krop', 'lennon@thebeatles.com', 'mypassword') <NEW_LINE> Product(name='iPhone X', description='olo', slug='iphonex', price=1000, rate=5).save() <NEW_LINE> c.login(username='krop', password='mypassword') <NEW_LI...
Check adding comment with authorization
625941ea656771135c3ebd40
def create_class_balance_df(x_dictionary, label_col, columns): <NEW_LINE> <INDENT> ticker_dict = {} <NEW_LINE> for ticker in x_dictionary.keys(): <NEW_LINE> <INDENT> key_val_dict = {} <NEW_LINE> for key,value in x_dictionary[ticker][label_col].value_counts().items(): <NEW_LINE> <INDENT> key_val_dict[key] = value <NEW_L...
Calculates the number of high risk and low risk occurences as well as totals for each ticker in input dictionary. Returns a pandas DataFrame object. *!Check for NaNs!*
625941ea2ae34c7f2600d5fc
def accumulate(self, spikes_in): <NEW_LINE> <INDENT> cur_state = 0 <NEW_LINE> state = [0] <NEW_LINE> time = [0.] <NEW_LINE> spike_times = [] <NEW_LINE> spike_weights = [] <NEW_LINE> for t, w in zip(spikes_in.times, spikes_in.weights): <NEW_LINE> <INDENT> time.append(t) <NEW_LINE> state.append(cur_state) <NEW_LINE> cur_...
Computes the output spike times of the accumulator Inputs: spikes_in: Outputs: spikes_out:
625941ea31939e2706e4d32f
def _gen_color(): <NEW_LINE> <INDENT> rgb = [(0.5, 0, 0), (0, 0.5, 0), (0, 0, 0.5)] <NEW_LINE> for i in count(): <NEW_LINE> <INDENT> yield tuple((c + (0.2 * i) % 1) % 1 for c in rgb[i%3])
A color generator that attempts to generate distinct color every time.
625941ea6fece00bbac2dc10
@app.route('/nodes/resolve', methods=['GET']) <NEW_LINE> def consensus(): <NEW_LINE> <INDENT> replaced = blockchain.resolve_conflicts() <NEW_LINE> if replaced: <NEW_LINE> <INDENT> response = { 'message': 'Our chain was replaced.', 'new_chain': blockchain.chain, } <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> response =...
Consensus Endpoint ------------------ This is the Flask API endpoint that will be used to call resolve_conflicts() which will run our Consensus algorithm. :param: None :return: None
625941eabde94217f36832b8
def numIslands(self, grid): <NEW_LINE> <INDENT> m = len(grid) <NEW_LINE> if m == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> n = len(grid[0]) <NEW_LINE> visited = [[0 for i in range(n)] for j in range(m)] <NEW_LINE> def dfs(ni, nj): <NEW_LINE> <INDENT> visited[ni][nj] = -1 <NEW_LINE> if ni - 1 >= 0 and grid[ni ...
:type grid: List[List[str]] :rtype: int
625941ea287bf620b61d3f2c
def has_add_permission(self, request): <NEW_LINE> <INDENT> return self.has_generic_permission(request, "add")
Has user ability to add page under current page?
625941ea21bff66bcd684e1a
def get_app_stats(app_name: str, configuration: Configuration, secrets: Secrets, org_name: str = None, space_name: str = None) -> Dict[str, Any]: <NEW_LINE> <INDENT> app = get_app_by_name( app_name, configuration, secrets, org_name=org_name, space_name=space_name) <NEW_LINE> return call_api( "/v2/apps/{a}/stats".format...
Fetch the metrics of the given application. See https://apidocs.cloudfoundry.org/280/apps/get_detailed_stats_for_a_started_app.html for more information.
625941ea046cf37aa974d20f
def db_for_write(self, model, **hints): <NEW_LINE> <INDENT> if model._meta.app_label == 'establishmentDataManagement': <NEW_LINE> <INDENT> return 'hoteldemo.com.v6' <NEW_LINE> <DEDENT> return None
Attempts to write auth models go to auth_db.
625941ea7cff6e4e81117e51
def get_data_signature(data: dict) -> Dict[str, Type]: <NEW_LINE> <INDENT> d: Dict[str, Type] = {} <NEW_LINE> for key, value in data.items(): <NEW_LINE> <INDENT> d[key] = type(value) <NEW_LINE> <DEDENT> return d
Return dict values types.
625941ea99fddb7c1c9de85a
def main(): <NEW_LINE> <INDENT> logging.basicConfig(format='%(message)s', level=logging.INFO) <NEW_LINE> book = Book( title='Example', authors='Max Mustermann', language='en') <NEW_LINE> book.chapters.extend( [Chapter(src='first_chapter.md'), Chapter(src='second_chapter.md'), Chapter(src='unfinished_chapter.md', publis...
Shows how to use publish to produce an html file and an epub file while also applying a substitution to the markdown text in the process. Note that logging of everything but exceptions is turned off by default and has to be turned on by the user by configuring the python standard logging module, for example by calling...
625941eac432627299f05116
def test_add_station_for_one_instance(self): <NEW_LINE> <INDENT> with patch('sapphire.clusters.Station') as mock_station: <NEW_LINE> <INDENT> mock_station.return_value = Mock() <NEW_LINE> cluster1 = clusters.BaseCluster() <NEW_LINE> cluster1._add_station((0, 0, 0), 0, [(0, 0, 'LR')]) <NEW_LINE> mock_station.return_valu...
Unfortunately, if you naively declare __stations = [] as a *class* variable, you will share the same list with *all instances*.
625941ea57b8e32f5248396a
def initialize_chain(test_dir): <NEW_LINE> <INDENT> if not os.path.isdir(os.path.join("cache", "node0")): <NEW_LINE> <INDENT> devnull = open("/dev/null", "w+") <NEW_LINE> for i in range(4): <NEW_LINE> <INDENT> datadir=initialize_datadir("cache", i) <NEW_LINE> args = [ os.getenv("BITCOIND", "octod"), "-keypool=1", "-dat...
Create (or copy from cache) a 200-block-long chain and 4 wallets. octod and octo-cli must be in search path.
625941eacb5e8a47e48b7f6f
def add_command_line_args_to_step( cluster_config, correlation_id, s3_prefix, snapshot_type, export_date, step_name, skip_pdm_trigger="NOT_SET", ): <NEW_LINE> <INDENT> if ( next( (sub for sub in cluster_config[STEPS] if sub[NAME_KEY] == step_name), None, ) is not None ): <NEW_LINE> <INDENT> script_args = next( (sub for...
Adding command line arguments to an individual step.
625941ead58c6744b425812a
@contextmanager <NEW_LINE> def handle_gce_http_errors(type_name, resource_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> yield <NEW_LINE> <DEDENT> except HttpError as error: <NEW_LINE> <INDENT> message = get_message_from_http_error(error, resource_name) <NEW_LINE> raise GCECloudException( 'Unable to retrieve {type...
Context manager to handle GCE HTTP Errors.
625941ea167d2b6e31219061
def mark_process_done(self, process, pid, entry): <NEW_LINE> <INDENT> if process is not None: <NEW_LINE> <INDENT> entry['processes'].remove(process) <NEW_LINE> <DEDENT> entry['processids'].remove(pid) <NEW_LINE> entry['done'] += 1 <NEW_LINE> self.allocator.free(entry['slots'], pid)
remove process from list of running processes for this command set and add it to the done count for this command set
625941eade87d2750b860264
def render_noderef(self, ontol, n, query_ids=None, **args): <NEW_LINE> <INDENT> if query_ids is None: <NEW_LINE> <INDENT> query_ids = [] <NEW_LINE> <DEDENT> marker = "" <NEW_LINE> if n in query_ids: <NEW_LINE> <INDENT> marker = " * " <NEW_LINE> <DEDENT> label = ontol.label(n) <NEW_LINE> s = None <NEW_LINE> if label is ...
Render a node object
625941ea99fddb7c1c9de85b
def import_system_description_elements(self): <NEW_LINE> <INDENT> self.xml_state.copy_displayname( self.boot_xml_state ) <NEW_LINE> self.xml_state.copy_name( self.boot_xml_state ) <NEW_LINE> self.xml_state.copy_repository_sections( target_state=self.boot_xml_state, wipe=True ) <NEW_LINE> self.xml_state.copy_drivers_sec...
Copy information from the system image relevant to create the boot image to the boot image state XML description
625941ea67a9b606de4a8383
def remove_completer(self): <NEW_LINE> <INDENT> if self.__completer: <NEW_LINE> <INDENT> LOGGER.debug("> Removing '{0}' completer.".format(self.__completer)) <NEW_LINE> self.__completer.activated.disconnect(self.__insert_completion) <NEW_LINE> self.__completer.deleteLater() <NEW_LINE> self.__completer = None <NEW_LINE>...
Removes current completer. :return: Method success. :rtype: bool
625941ea32920d7e50b286a0
def read_cdx(file, encoding='utf8'): <NEW_LINE> <INDENT> with codecs.getreader(encoding)(file) as stream: <NEW_LINE> <INDENT> header_line = stream.readline() <NEW_LINE> separator = header_line[0] <NEW_LINE> field_keys = header_line.strip().split(separator) <NEW_LINE> if field_keys.pop(0) != 'CDX': <NEW_LINE> <INDENT> r...
Iterate CDX file. Args: file (str): A file object. encoding (str): The encoding of the file. Returns: iterator: Each item is a dict that maps from field key to value.
625941ea293b9510aa2c375d
def has_table(table_name, con, flavor='sqlite', schema=None): <NEW_LINE> <INDENT> pandas_sql = pandasSQL_builder(con, flavor=flavor, schema=schema) <NEW_LINE> return pandas_sql.has_table(table_name)
Check if DataBase has named table. Parameters ---------- table_name: string Name of SQL table con: SQLAlchemy engine or sqlite3 DBAPI2 connection Using SQLAlchemy makes it possible to use any DB supported by that library. If a DBAPI2 object, only sqlite3 is supported. flavor: {'sqlite', 'mysql'}, defau...
625941ead8ef3951e3243a0a
def test_begin(self): <NEW_LINE> <INDENT> self.begin_time = utils.get_current_epoch_time()
Call this when the test case it records begins execution. Sets the begin_time of this record.
625941eaa05bb46b383ecce9
def get_machine_current(self): <NEW_LINE> <INDENT> if self.bl_control.machine_current: <NEW_LINE> <INDENT> return self.bl_control.machine_current.getCurrent() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0
Descript. :
625941ea85dfad0860c3b328
def _find_nearest_star(self, x, y): <NEW_LINE> <INDENT> mouse_pos = self.axis.origin + self.axis.scale * np.asarray([x, self.size[1]-y]) <NEW_LINE> return ((self.simu.coords() - mouse_pos) ** 2).sum(axis=1).argmin()
Return the index of the nearest star from mouse coordinates.
625941ead486a94d0b98e613
def determine_db_dir(): <NEW_LINE> <INDENT> if platform.system() == "Darwin": <NEW_LINE> <INDENT> return os.path.expanduser("~/Library/Application Support/XBI/") <NEW_LINE> <DEDENT> elif platform.system() == "Windows": <NEW_LINE> <INDENT> return os.path.join(os.environ['APPDATA'], "XBI") <NEW_LINE> <DEDENT> return os.p...
Return the default location of the xbi data directory
625941eacdde0d52a9e53503
def test_find_pv_attrs(self): <NEW_LINE> <INDENT> m = Magnet() <NEW_LINE> self.assertEqual(m.find_pv_attrs(), ATTRS)
Test we have correct attributes
625941ea15fb5d323cde0fe3
def handshake( client_factory, server_factory, hostname, server_endpoint, acceptable_protocols=None, ): <NEW_LINE> <INDENT> def connect_client(listening_port): <NEW_LINE> <INDENT> port_number = listening_port.getHost().port <NEW_LINE> client = endpoints.TCP4ClientEndpoint( reactor, '127.0.0.1', port_number ) <NEW_LINE>...
Connect a basic Twisted TLS client endpoint to the provided TxSNI TLSEndpoint. Returns a Deferred that fires when the connection has been established with a tuple of an instance of the client protocol and the listening port.
625941ea97e22403b379d468
def __init__(self, arr=(), key=lambda x: x, cmp=lambda x, y: x < y): <NEW_LINE> <INDENT> self._arr = list(arr) <NEW_LINE> self._key = key <NEW_LINE> self._cmp = cmp <NEW_LINE> self.__heapify()
Implementing Priority Queue using Heap Data Structure. :param arr: * Initial elements of to be inserted in the heap. * Type : List * Default : Empty List. :param key: * Function to evaluate the element of the heap. Default : element itself. * Type : Method or lambda function: ...
625941ea5fdd1c0f98dc0702
def feed(self, dealer): <NEW_LINE> <INDENT> dealer.feed_result_fat_food(self.fat_species_index, self.storage_num)
Effect: Add fat food to species at self.fat_species_index :param dealer: The dealer of the Evolution game return: Void
625941eac4546d3d9de72f05
def __init__(self, *args, **kwds): <NEW_LINE> <INDENT> if args or kwds: <NEW_LINE> <INDENT> super(EulerAngles, self).__init__(*args, **kwds) <NEW_LINE> if self.phi is None: <NEW_LINE> <INDENT> self.phi = 0. <NEW_LINE> <DEDENT> if self.theta is None: <NEW_LINE> <INDENT> self.theta = 0. <NEW_LINE> <DEDENT> if self.psi is...
Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments. The available fields are: phi,theta,psi :param args: comple...
625941ea4c3428357757c7f1
def strip_ext(filenames): <NEW_LINE> <INDENT> return [os.path.splitext(fname)[0] for fname in filenames]
Remove filename extensions from the list of filenames
625941ea0a50d4780f667363
def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ExtensionsV1beta1IDRange): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict()
Returns true if both objects are not equal
625941eacc0a2c11143dd35e
def get_available_actions(state): <NEW_LINE> <INDENT> actions = [] <NEW_LINE> empty_row = 0 <NEW_LINE> empty_col = 0 <NEW_LINE> for row_idx in range(BOARD_SIZE): <NEW_LINE> <INDENT> for col_idx in range(BOARD_SIZE): <NEW_LINE> <INDENT> if state[row_idx][col_idx] is None: <NEW_LINE> <INDENT> empty_row = row_idx <NEW_LIN...
Returns a list of actions that can be performed for the given state.
625941eafb3f5b602dac3b65
def _get_packages_directory_contents(self): <NEW_LINE> <INDENT> data = urllib.urlopen(self._PACKAGES_DIRECTORY) <NEW_LINE> return ''.join(data.readlines())
Returns the contents of the directory where releases are kept. @return: The contents @rtype: str
625941ea76e4537e8c351b43
def getName(self, id = None): <NEW_LINE> <INDENT> if id is None: <NEW_LINE> <INDENT> if not self.id: <NEW_LINE> <INDENT> return("no id specified") <NEW_LINE> <DEDENT> elif type(self.id) == int or self.id.isnumeric(): <NEW_LINE> <INDENT> id = self.id <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> id = int(self.conn.sendR...
Get the list name of the player with entity id => [name:str] Also can be used to find name of entity if entity is not a player.
625941ead164cc617578321c
def shell_exec(command, path='.'): <NEW_LINE> <INDENT> proc = Popen(shlex.split(command), stdout=PIPE, stderr=PIPE, cwd=path) <NEW_LINE> out, err = [x.decode("utf-8") for x in proc.communicate()] <NEW_LINE> return {'out': out, 'err': err, 'code': proc.returncode}
Excecutes the given command silently.
625941ea6fb2d068a760f572
def honk_horn(self) -> dict: <NEW_LINE> <INDENT> return self.__execute_command('HORN_BLOW')
Sound the vehicle's horn. This apparently doesn't work with UK-registered BMW vehicles, but I have no way to test and cannot verify. Regardless, don't be a jerk. Returns: Details of the horn command event.
625941ea21a7993f00bc81c5
def _tick_check_max_hp(self): <NEW_LINE> <INDENT> if self.mw.current_hp() >= self.mw.max_hp(): <NEW_LINE> <INDENT> self._timer_check_max_hp.stop() <NEW_LINE> self._hp_maximum.emit()
Функция для проверки максимума жизней. Если жизни максимальны, отправляется сигнал _hp_maximum.
625941ea30dc7b7665901e2e
def ambient_ray_indices(self): <NEW_LINE> <INDENT> return self._ambient_ray_indices
Return indices of rays of the ambient structure generating ``self``. OUTPUT: - increasing :class:`tuple` of integers. EXAMPLES:: sage: quadrant = Cone([(1,0), (0,1)]) sage: quadrant.ambient_ray_indices() (0, 1) sage: quadrant.facets()[1].ambient_ray_indices() (1,)
625941ea596a897236089f87
def get_ship_name(ship): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return SHIP_NAMES[ship] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return 'Unknown'
Get the name of a ship from a SHIP_Xxx constant.
625941ea30bbd722463cc296
def _add_method( ctx: ClassDefContext, name: str, args: List[Argument], return_type: Type, self_type: Optional[Type] = None, tvar_def: Optional[TypeVarDef] = None, ) -> None: <NEW_LINE> <INDENT> info = ctx.cls.info <NEW_LINE> self_type = self_type or fill_typevars(info) <NEW_LINE> function_type = ctx.api.named_type('__...
Adds a new method to a class.
625941eacc40096d61595e1b
def correct(self): <NEW_LINE> <INDENT> correct_answers = list( a.lower() for a in Question.objects.get(pk=self.question.pk).answers ) <NEW_LINE> return any( (word in correct_answers) for word in self.answer.lower().split(' '))
Checks if the answer given is one of the correct answers. An answer counts as correct if any of the words in it are a correct answer.
625941eacdde0d52a9e53504
def parse_uniprot_txt_file(infile): <NEW_LINE> <INDENT> uniprot_metadata_dict = {} <NEW_LINE> metadata = old_parse_uniprot_txt_file(infile) <NEW_LINE> metadata_keys = list(metadata.keys()) <NEW_LINE> if metadata_keys: <NEW_LINE> <INDENT> metadata_key = metadata_keys[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> retu...
Parse a raw UniProt metadata file and return a dictionary. Args: infile: Path to metadata file Returns: dict: Metadata dictionary
625941ea5fc7496912cc3e4a
def lanacion_headlines(use_descriptions=True): <NEW_LINE> <INDENT> url = 'http://contenidos.lanacion.com.ar/herramientas/rss/categoria_id=30' <NEW_LINE> rh = RequestHandler([url], RequestData(GET), RequestErrorData(allow_errors=False)) <NEW_LINE> rh.run() <NEW_LINE> bs = BeautifulSoup(rh.responses[0].text, 'html.parser...
:param use_descriptions: bool, if true add descriptions to each title, default= True :return: str, the titles of the La Nacion headlines for latest news
625941eaa219f33f34628e2f
def getEventsCounts(uid): <NEW_LINE> <INDENT> pass
return all the event counts for this context
625941ea8e05c05ec3eea846
def setzero(self): <NEW_LINE> <INDENT> self.data=zeros(self.nzcount[self.size-1]) <NEW_LINE> return None
setzero: makes sure all values are zero
625941ead4950a0f3b08c815
def test_empty(self): <NEW_LINE> <INDENT> with self.assertNumQueries(0): <NEW_LINE> <INDENT> qss = self.all.filter(title='') <NEW_LINE> <DEDENT> self.assertIsInstance(qss, QuerySetSequence) <NEW_LINE> with self.assertNumQueries(2): <NEW_LINE> <INDENT> self.assertEqual(qss.count(), 0) <NEW_LINE> <DEDENT> data = list(qss...
Ensure that filter() works when it results in an empty QuerySet.
625941ea3eb6a72ae02ec9b7
def destroy_worker_thread(self): <NEW_LINE> <INDENT> worker_thread_task = WorkerThreadTask(STOP_THREAD_TASK_TYPE, ()) <NEW_LINE> self.insert_worker_thread_task(worker_thread_task, False)
Destroys a worker thread for the thread pool.
625941ea94891a1f4081bf78
def get_item_decomposition(item_type, quality_level): <NEW_LINE> <INDENT> _conf = sysconfig.get('item_decomposition', {}) <NEW_LINE> return _conf.get(item_type, {}).get(quality_level, [])
get decomposition by item type and quality level
625941eab5575c28eb68e4d2
def load_xml(path, dirname, res): <NEW_LINE> <INDENT> with open(path) as fd: <NEW_LINE> <INDENT> doc = xmltodict.parse(fd.read()) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> tile_xml=doc["annotation"]["object"] <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise Exception("error {} for path {} with do...
Load a single .xml annotations
625941ead53ae8145f87a733
def shape_path_points(svg_path_d): <NEW_LINE> <INDENT> def _update_path_state(path_state, match): <NEW_LINE> <INDENT> if match.group('xy_command'): <NEW_LINE> <INDENT> for dim_j in 'xy': <NEW_LINE> <INDENT> path_state[dim_j] = float(match.group(dim_j)) <NEW_LINE> <DEDENT> if path_state.get('x0') is None: <NEW_LINE> <IN...
Parameters ---------- svg_path_d : str ``"d"`` attribute of SVG ``path`` element. Returns ------- list List of coordinates of points found in SVG path. Each point is represented by a dictionary with keys ``x`` and ``y``.
625941eacad5886f8bd274a5
def deal(self, tileNames=None, deadEnd=False): <NEW_LINE> <INDENT> if tileNames is None: <NEW_LINE> <INDENT> tileNames = [None] <NEW_LINE> <DEDENT> count = len(tileNames) <NEW_LINE> if deadEnd: <NEW_LINE> <INDENT> if len(self.kongBox) < count: <NEW_LINE> <INDENT> raise WallEmpty <NEW_LINE> <DEDENT> tiles = self.kongBox...
deal tiles. May raise WallEmpty. Returns a list of tiles
625941ea442bda511e8be8de
def update_screen(disp, rows_g, rows_n, ad_by_key, then_ns, sum_dob, tot_mac, tot_oui, tot_names, *, mem_free=None): <NEW_LINE> <INDENT> if mem_free is None: <NEW_LINE> <INDENT> summary_text = "MACs:{:<4d} OUIs:{:<4d} Names:{:<4d}".format(tot_mac, tot_oui, tot_names) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> summ...
Update the screen with the entries with highest RSSI, recenctly seen. The text colour is used to indicate how recent.
625941eaff9c53063f47c6be
def test_get_one_highlights(self): <NEW_LINE> <INDENT> response = self.client.get( reverse('highlights:get-highlights', kwargs={ "slug": "test-slug", "highlight_id": 1 }), HTTP_AUTHORIZATION=self.hauth, content_type='application/json' ) <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
Tests the successfult retirieve of a highlight
625941eaa17c0f6771cbe51c
def _gettype(self): <NEW_LINE> <INDENT> targetnode = self._gettargetnode() <NEW_LINE> if targetnode is not None: <NEW_LINE> <INDENT> return targetnode.get("type") <NEW_LINE> <DEDENT> return None
Returns the type of this translation.
625941eacad5886f8bd274a6
def normalize_arrows(arrows, length=0.3): <NEW_LINE> <INDENT> arrows = (arrows.T / np.linalg.norm(arrows, axis=1)).T <NEW_LINE> arrows *= length <NEW_LINE> return arrows
normalize_arrows :param arrows: array of shape (n_samples, 2) :param length: scalar, desired Euclidean length of arrows
625941ea293b9510aa2c375e
def sqexp_invL( x, y, **cpars ): <NEW_LINE> <INDENT> amp = cpars['amp'] <NEW_LINE> iscale = cpars['iscale'] <NEW_LINE> x = np.matrix( x )*np.sqrt( iscale ) <NEW_LINE> if y is None: <NEW_LINE> <INDENT> n = np.shape( x )[0] <NEW_LINE> cov = ( amp**2. ) + np.zeros( n ) <NEW_LINE> cov = np.reshape( cov, [ n, 1 ] ) <NEW_LIN...
Squared exponential kernel for 1D input.
625941ea0fa83653e4657485
def __init__(self): <NEW_LINE> <INDENT> BaseGameObject.__init__(self) <NEW_LINE> self._game_object_name = "" <NEW_LINE> self._id = "" <NEW_LINE> self._logs = []
initializes a GameObject with basic logic as provided by the Creer code generator
625941eabe7bc26dc91cdac4
def __init__(self, session): <NEW_LINE> <INDENT> self.session = session <NEW_LINE> self.logger = logging.getLogger(__name__)
Constructor
625941ea2c8b7c6e89b35c8a
def _clean_tmp(self) -> None: <NEW_LINE> <INDENT> messages.info('Cleaning out the temporary folder before dispatch.') <NEW_LINE> for file in os.listdir(f'{self.tmp_dir}'): <NEW_LINE> <INDENT> if os.path.isdir(f'{self.tmp_dir}/{file}') and file.startswith('_'): <NEW_LINE> <INDENT> shutil.rmtree(f'{self.tmp_dir}/{file}')...
Cleans the temporary directory for any remaining artifacts. To clean the temporary directory, we will remove all folders that start with an underscore (_), as well as all original markdown files (.md / .markdown) in both the original directory, as in the posts directory. TODO: Make this more readable, this is a bit c...
625941ea8a43f66fc4b5452d
def testMatchAtAssertAssociated(self): <NEW_LINE> <INDENT> parser = MockParser([' \n']) <NEW_LINE> atAssertAssociated = AtAssertAssociated(parser) <NEW_LINE> self.assertFalse(atAssertAssociated.match('@assertAssociated')) <NEW_LINE> self.assertFalse(atAssertAssociated.match('@assertAssociated()')) <NEW_LINE> self.asser...
Check that a line starting with '@assertAssociated' is detected as an annotation.
625941ead268445f265b533c
def compare_fscore(models, y_preds, y_test): <NEW_LINE> <INDENT> arr = pd.DataFrame(0, index = [i for i in range(y_test.shape[1])], columns = models) <NEW_LINE> for i in range(len(y_preds)): <NEW_LINE> <INDENT> y_pred = y_preds[i] <NEW_LINE> for col in range(y_test.shape[1]): <NEW_LINE> <INDENT> arr.iloc[col, i] = roun...
Compares f scores of different models for each category INPUTs: models - (list) list of models' names y_preds - (list) list of predicted values of different models to be compared y_test - (dataframe) df of test values to be used in calculation of fscores OUTPUT: arr - (dataframe) d...
625941ea9b70327d1c4e12a5
def watch(self, name): <NEW_LINE> <INDENT> if self.subscribed: <NEW_LINE> <INDENT> raise RedisError("Can't call 'watch' from a pipeline'") <NEW_LINE> <DEDENT> return self.execute_command(b'WATCH', name)
Watches the value at key ``name``, or None of the key doesn't exist
625941ead58c6744b425812b
def send_event(self, event, event_type='workflow_stage', args=None, additional_context=None): <NEW_LINE> <INDENT> send_event_task = self.internal.handler.get_send_workflow_event_task( event, event_type, args, additional_context) <NEW_LINE> return self.local_task( local_task=send_event_task, info=event)
Sends a workflow event to RabbitMQ :param event: The event :param event_type: The event type :param args: additional arguments that may be added to the message :param additional_context: additional context to be added to the context
625941ea29b78933be1e5b73
def EvaluateDerivative(self, *args): <NEW_LINE> <INDENT> return _itkBSplineInterpolateImageFunctionPython.itkBSplineInterpolateImageFunctionIUS3DUS_EvaluateDerivative(self, *args)
EvaluateDerivative(self, itkPointD3 point) -> itkCovariantVectorD3 EvaluateDerivative(self, itkPointD3 point, unsigned int threadID) -> itkCovariantVectorD3
625941eaf8510a7c17cf9bcd
def get_contacts(self): <NEW_LINE> <INDENT> return list(self.contacts.values())
:returns: the contact objects in this contact list as a list :rtype: List[Contact]
625941ead6c5a1020814451c
def positional_encoding(inputs, num_units, zero_pad=True, scale=True, scope="positional_encoding", reuse=None): <NEW_LINE> <INDENT> N, T = inputs.get_shape().as_list() <NEW_LINE> with tf.variable_scope(scope, reuse=reuse): <NEW_LINE> <INDENT> position_ind = tf.tile(tf.expand_dims(tf.range(T), 0), [N, 1]) <NEW_LINE> pos...
Sinusoidal Positional_Encoding. Args: inputs: A 2d Tensor with shape of (N, T). num_units: Output dimensionality zero_pad: Boolean. If True, all the values of the first row (id = 0) should be constant zero scale: Boolean. If True, the output will be multiplied by sqrt num_units(check details from paper) scop...
625941eaa4f1c619b28b04fb
def timeout(self): <NEW_LINE> <INDENT> self._insertNewDelayedCalls() <NEW_LINE> if not self._pendingTimedCalls: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> delay = self._pendingTimedCalls[0].time - self.seconds() <NEW_LINE> longest = 2147483 <NEW_LINE> return max(0, min(longest, delay))
Determine the longest time the reactor may sleep (waiting on I/O notification, perhaps) before it must wake up to service a time-related event. @return: The maximum number of seconds the reactor may sleep. @rtype: L{float}
625941ead8ef3951e3243a0b
def newFilename(data_dir, direction, pulse_time, image_id, IMAGE_EXTENSION): <NEW_LINE> <INDENT> fname = "{}\\step_{:03d}_d{}_{}ms{}".format(data_dir, image_id, direction, pulse_time, IMAGE_EXTENSION) <NEW_LINE> image_id += 1 <NEW_LINE> return fname, image_id
Generate new FITS image name
625941ea7b180e01f3dc4cc1
def close(self): <NEW_LINE> <INDENT> pass
Close the selector. This must be called to make sure that any underlying resource is freed.
625941eabe8e80087fb21109
def clockSerialNumber(self): <NEW_LINE> <INDENT> return _DataModel.Stream_clockSerialNumber(self)
clockSerialNumber(Stream self) -> std::string const &
625941ea498bea3a759b9f7b
def authenticate_user(request): <NEW_LINE> <INDENT> if is_authenticated(request): <NEW_LINE> <INDENT> return redirect('/home') <NEW_LINE> <DEDENT> username = password = '' <NEW_LINE> if request.POST: <NEW_LINE> <INDENT> username = request.POST['username'] <NEW_LINE> password = request.POST['password'] <NEW_LINE> user =...
Authenticate user. :param request: Obj - Request. :return: Renders to home page otherwise login page.
625941ea3cc13d1c6d3c7845
def stack_chart(self, boolean): <NEW_LINE> <INDENT> self.chart_options.update({'stacked': boolean}) <NEW_LINE> return self
Should area/bar charts in the visualization be stacked. Arguments: boolean: Boolean to turn on/off chart stacking
625941ea187af65679ca55ee
def create_snapshot(self, name, snap_name): <NEW_LINE> <INDENT> with RBDVolumeProxy(self, name) as volume: <NEW_LINE> <INDENT> snap = snap_name.encode('utf-8') <NEW_LINE> volume.create_snap(snap) <NEW_LINE> if self.supports_layering(): <NEW_LINE> <INDENT> volume.protect_snap(snap)
Creates an rbd snapshot.
625941ea287bf620b61d3f2e
def fetch_all(self, params=None): <NEW_LINE> <INDENT> params = params and params.copy() or {} <NEW_LINE> first_page = self.get_func(**params) <NEW_LINE> results = first_page['results'] <NEW_LINE> params['session_id'] = first_page['session_id'] <NEW_LINE> start, end = self._remaining_page_range(first_page) <NEW_LINE> fe...
Fetch all results from all pages, and return as a list. If params need to be sent with each request (in addition to the pagination) params, they may be passed in via the `params` kwarg.
625941eae76e3b2f99f3acd2
def get_short_branches(node): <NEW_LINE> <INDENT> for edge in edge_iter(node): <NEW_LINE> <INDENT> if edge.length <= 0.001: <NEW_LINE> <INDENT> yield edge
Yields an iterator of especially short edges under `node`.
625941ea046cf37aa974d211
def portfolio_discrete_mutation(parent: ArrayLike, u: Optional[int] = None) -> ArrayLike: <NEW_LINE> <INDENT> dimension = len(parent) <NEW_LINE> if u is None: <NEW_LINE> <INDENT> u = int(np.random.randint(1, dimension)) <NEW_LINE> <DEDENT> boolean_vector = [True for _ in parent] <NEW_LINE> while all(boolean_vector): <N...
Mutation discussed in https://arxiv.org/pdf/1606.05551v1.pdf We mutate a randomly drawn number of variables in average.
625941ea1b99ca400220af81
def __init__(self, device, etree1, etree2, preferred_create='merge', preferred_replace='merge', preferred_delete='delete'): <NEW_LINE> <INDENT> BaseCalculator.__init__(self, device, etree1, etree2) <NEW_LINE> if preferred_create in ['merge', 'create', 'replace']: <NEW_LINE> <INDENT> self.preferred_create = preferred_cr...
__init__ instantiates a NetconfCalculator instance.
625941ea82261d6c526ab975
def axiom_generator_initial_location_assertions(x, y): <NEW_LINE> <INDENT> axiom_str = '' <NEW_LINE> sign_negation = '~' <NEW_LINE> sign_conjunction = '&' <NEW_LINE> prepo_string = '' <NEW_LINE> horizontal_counterpart = x <NEW_LINE> vertical_counterpart = y <NEW_LINE> prepo_string = prepo_string + sign_negation + wumpu...
Assert that there is no Pit and no Wumpus in the location x,y := the location
625941eab7558d58953c53d8
def compute_w_gradient(self, x, u, t, recompute=True): <NEW_LINE> <INDENT> tmp = x[:self.nq] - self.q_post <NEW_LINE> tmp[0] = 0.0 <NEW_LINE> cost = 0.5*(tmp).dot(tmp) <NEW_LINE> grad_x = np.zeros(x.shape[0]) <NEW_LINE> grad_x[0:self.robot.nq] = tmp <NEW_LINE> grad_x[0] = 0.0 <NEW_LINE> grad_u = np.zeros(u.shape[0]) <N...
Compute the cost for a single time instant and its gradient w.r.t. x and u
625941eae64d504609d74d0e
def to_permutation(self): <NEW_LINE> <INDENT> from sage.combinat.permutation import Permutation <NEW_LINE> return Permutation([x+1 for x in self._twin[1]])
Returns the permutation as an element of the symmetric group. EXAMPLES:: sage: p = iet.Permutation('a b c','c b a') sage: p.to_permutation() [3, 2, 1] :: sage: p = Permutation([2,4,1,3]) sage: q = iet.Permutation(p) sage: q.to_permutation() == p True
625941ea7d847024c06be78e
def initFromString(self, parameters_string, warnings = True): <NEW_LINE> <INDENT> nodes = ElementTree.fromstring(parameters_string) <NEW_LINE> return self.initAttr(nodes, warnings = warnings)
Set the attributes of the params Parameters object from an XML string.
625941ea2c8b7c6e89b35c8b
def logcat_bg(patt): <NEW_LINE> <INDENT> if type(patt) != str: <NEW_LINE> <INDENT> raise Exception("patt must be a string") <NEW_LINE> <DEDENT> patt = re.compile(patt) <NEW_LINE> def logcat_thread(): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> print("logcat begin.", end="\r\n") <NEW_LINE> for line in proc_lines...
Show filtered logcat in a background thread.
625941ea26068e7796caf1b5
def forward(data, model, mlm_loss, nsp_loss, vocab_size): <NEW_LINE> <INDENT> (input_id, masked_id, masked_position, masked_weight, next_sentence_label, segment_id, valid_length) = data <NEW_LINE> num_masks = masked_weight.sum() + 1e-8 <NEW_LINE> valid_length = valid_length.reshape(-1) <NEW_LINE> masked_id = masked...
forward computation for evaluation
625941ead268445f265b533d
def detectNewFileWriteEncoding(editor, fName): <NEW_LINE> <INDENT> isPython = isPythonFile(fName) <NEW_LINE> if editor.explicitUserEncoding: <NEW_LINE> <INDENT> if isPython: <NEW_LINE> <INDENT> encFromText = getCodingFromText(editor.text) <NEW_LINE> if encFromText: <NEW_LINE> <INDENT> if not isValidEncoding(encFromText...
Detects a new file encoding
625941ea76d4e153a657f001
def logistic_embedding4(k=1, dataset='epinions', epoch=6, dirname='graphssa-results'): <NEW_LINE> <INDENT> print('item: graphssa with feo', k, epoch) <NEW_LINE> filename = os.path.join(dirname, 'embedding-{}-{}-{}.npy'.format(dataset, k, epoch)) <NEW_LINE> embeddings = np.load(filename) <NEW_LINE> pos_ratio, accuracy, ...
use graphssa to train logistic function Returns: pos_ratio, accuracy, f1_score0, f1_score1, f1_score2, auc_score
625941ea566aa707497f4a30
def __eq__(self, other): <NEW_LINE> <INDENT> if other is self: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if isinstance(other, self.__class__): <NEW_LINE> <INDENT> self_dict = { enc[0] : getattr(self, enc[0]) for enc in self._encoders if enc[0] } <NEW_LINE> other_dict = { enc[0] : getattr(other, enc[0]) for en...
Return True if `self` equals `other`.
625941ead4950a0f3b08c816
def __init__(self): <NEW_LINE> <INDENT> Document.__init__(self) <NEW_LINE> RdfGraph.__init__(self) <NEW_LINE> self.namespaces = [] <NEW_LINE> self.annotations = [] <NEW_LINE> self.roles = [] <NEW_LINE> self.chosen_part2 = kb.ns_dm_part2 <NEW_LINE> self.namespaces_by_uri = {} <NEW_LINE> self.annotations_by_name = {} <NE...
Constructor.
625941ea236d856c2ad44caf
def train(params, dtrain, num_boost_round=10, evals=(), obj=None, feval=None): <NEW_LINE> <INDENT> evals = list(evals) <NEW_LINE> bst = Booster(params, [dtrain] + [d[0] for d in evals]) <NEW_LINE> for i in range(num_boost_round): <NEW_LINE> <INDENT> bst.update(dtrain, i, obj) <NEW_LINE> if len(evals) != 0: <NEW_LINE> <...
Train a booster with given parameters. Parameters ---------- params : dict Booster params. dtrain : DMatrix Data to be trained. num_boost_round: int Number of boosting iterations. watchlist : list of pairs (DMatrix, string) List of items to be evaluated during training, this allows user to watch pe...
625941ea07d97122c4178d65
def get_calibration(self): <NEW_LINE> <INDENT> return GetCalibration(*self.ipcon.send_request(self, BrickletIndustrialDualAnalogIn.FUNCTION_GET_CALIBRATION, (), '', '2i 2i'))
Returns the calibration as set by :func:`SetCalibration`.
625941ea8c3a87329515888f
def _update_reference_dictionary(self, position, ref_base): <NEW_LINE> <INDENT> self.reference_dictionary[position] = ref_base
Update the reference dictionary :param position: Genomic position :param ref_base: Reference base at that position :return:
625941ea1f5feb6acb0c5018
def load_corpus(): <NEW_LINE> <INDENT> script_dir = os.path.dirname(__file__) <NEW_LINE> corpusfile = os.path.join(script_dir, 'generate_corpus_missing_words/corpus.json') <NEW_LINE> with open(corpusfile) as f_obj: <NEW_LINE> <INDENT> corpus = json.load(f_obj) <NEW_LINE> return corpus
Load the corpus as a string.
625941ead99f1b3c44c67a54
def mlab_imshow_color(img_array, **kwargs): <NEW_LINE> <INDENT> my_lut = pl.c_[img_array.reshape(-1, 4)] <NEW_LINE> my_lut_lookup_array = pl.arange(img_array.shape[0] * img_array.shape[1]).reshape(img_array.shape[0], img_array.shape[1]) <NEW_LINE> the_imshow = mlab.imshow(my_lut_lookup_array, colormap='binary', **kwarg...
Plot a color image with mayavi.mlab.imshow. img_array is a ndarray with dim (n, m, 4) and scale (0->255] **kwargs is passed onto mayavi.mlab.imshow(..., **kwargs)
625941eaf7d966606f6aa4d8
def fetch(self): <NEW_LINE> <INDENT> return read_voltage()
Same as read_voltage. Keep for backward compatibility.
625941ea283ffb24f3c55dca
def list_account_containers(self, params=None): <NEW_LINE> <INDENT> url = '?%s' % urllib.urlencode(params) if params else '' <NEW_LINE> resp, body = self.get(url, headers={}) <NEW_LINE> if params and params.get('format') == 'json': <NEW_LINE> <INDENT> body = json.loads(body) <NEW_LINE> <DEDENT> elif params and params.g...
List all containers for the account. Given valid X-Auth-Token, returns a list of all containers for the account. For a full list of available parameters, please refer to the official API reference: https://developer.openstack.org/api-ref/object-store/#show-account-details-and-list-containers
625941eaa8ecb033257d3599
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <...
Returns the model properties as a dict
625941eadc8b845886cb5a05