code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def compute_shifts(cube, ref_frame=None, processes=1, **kwargs): <NEW_LINE> <INDENT> if ref_frame is not None: <NEW_LINE> <INDENT> print('Computing shifts...', end=' ') <NEW_LINE> p = mp.Pool(processes) <NEW_LINE> try: <NEW_LINE> <INDENT> shifts = p.map( functools.partial(track, ref_frame, **kwargs), iter(cube), chunks...
Compute the shifts between each frame of a cube. Parameters ========== cube : 3D ndarray The cube for which to compute the shifts. ref_frame : ndarray or None (default: None) - If ndarray, compute the shifts for each frame of the cube relatively to this reference frame only. - If None, compute the sh...
625941e74527f215b584c8b3
def get_temp_file_path(self, name_base=None): <NEW_LINE> <INDENT> if name_base is None: <NEW_LINE> <INDENT> name_base = 'temp' <NEW_LINE> <DEDENT> temp_dir = self.temp_dir <NEW_LINE> if temp_dir is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> while True: <NEW_LINE> <INDENT> path = self.temp_dir[name_base +...
Locate a path where a temporary file can be safely created. :param name_base: An optional base for the file name. :return: A temporary file path, or None.
625941e7a05bb46b383ecc7e
def seresnet20_cifar100(classes=100, **kwargs): <NEW_LINE> <INDENT> return get_seresnet_cifar(classes=classes, blocks=20, bottleneck=False, model_name="seresnet20_cifar100", **kwargs)
SE-ResNet-20 model for CIFAR-100 from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.chainer/model...
625941e7ff9c53063f47c652
def find_word(words, w, index, distance_penalty=0.0): <NEW_LINE> <INDENT> index = min(len(words), max(index, -1)) <NEW_LINE> index_offset = -1 <NEW_LINE> if index < len(words) - 1: <NEW_LINE> <INDENT> index_offset, rel_score = compare_word( words[index + 1:], w, distance_penalty) <NEW_LINE> index_offset += index + 1 <N...
Find the first occurrence of a word in a sentence after a given word. Searches forward and if no match is found backward around the index-th word in the sentence. :param words: List of words that should be searched :param w: Word to be searched for :param index: Position in the array at which the search begins :param...
625941e7c4546d3d9de72e99
def items_all(api_key=None, region=None, **kwargs): <NEW_LINE> <INDENT> region = get_region(region) <NEW_LINE> url = '{}{}/{}/item'.format(api_url, region, version) <NEW_LINE> return get_data_from_api(api_key, url, **kwargs)
Retrieves item list. https://developer.riotgames.com/api/methods#!/1055/3621
625941e74f6381625f114e9d
def basic_name(self, name: str=None) -> str: <NEW_LINE> <INDENT> return self.test_case.create_name(name)
Shortcut function to generate common name
625941e766656f66f7cbc60e
def get_estimated_z(ghz): <NEW_LINE> <INDENT> differences = [] <NEW_LINE> for key, values in transitions.items(): <NEW_LINE> <INDENT> if True: <NEW_LINE> <INDENT> sghz = convert_to_rest_frame_ghz(values[3], ghz) <NEW_LINE> delta_z, matched_key = get_delta_z(values[3], sghz) <NEW_LINE> differences.append((matched_key, d...
Estimate the CO line based on Wide-ASPECS one, (3-2), z > 2 or higher J, calculate possible Z's and find which Z is closest to the <z> value from Wide ASPECS :param ghz: :return: transition, estimated_z
625941e723849d37ff7b34ec
def stop(self, wait=False): <NEW_LINE> <INDENT> if self.instance_id is not None: <NEW_LINE> <INDENT> log.info("Shutting down node `%s` (VM instance `%s`) ...", self.name, self.instance_id) <NEW_LINE> self._cloud_provider.stop_instance(self.instance_id) <NEW_LINE> if wait: <NEW_LINE> <INDENT> while self.is_alive(): <NEW...
Terminate the VM instance launched on the cloud for this specific node.
625941e7a8370b7717052cfe
def checkGroupsState( self, isPENDING=True, timeout=60, noExit=False ): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> states = [ "PENDING_ADD", "PENDING_ADD_RETRY", "PENDING_DELETE", "PENDING_UPDATE", "WAITING_AUDIT_COMPLETE" ] <NEW_LINE> checkedStates = [] <NEW_LINE> statesCount = [ 0, 0, 0, 0, 0 ] <NEW_LINE> for s in ...
Description: Check the if all the current groups are in ADDED state We check PENDING_ADD, PENDING_REMOVE, REMOVED, and FAILED groups, if the count of those states is 0, which means all current groups are in ADDED state, and return main.TRUE otherwise return main.FALSE Optional: * isPENDING: whether...
625941e7b7558d58953c536c
def shift(top, token): <NEW_LINE> <INDENT> global stack
state = getState(top,token) if(state == 126): semantic_functions["semanticIf"]() elif(state == 162): semantic_funtions["semanticElif"]() elif(state == 154): semantic_funtions["semanticElse"]()*/
625941e72eb69b55b151cd17
def _score(self, A, c, x): <NEW_LINE> <INDENT> num_nodes = A.shape[0] <NEW_LINE> Q, qs = _score_(A.indptr, A.indices, A.data, c, x, num_nodes) <NEW_LINE> return qs
Calculate the strength of core-periphery pairs. :param A: Adjacency amtrix :type A: scipy sparse matrix :param c: group to which a node belongs :type c: dict :param x: core (x=1) or periphery (x=0) :type x: dict :return: strength of core-periphery :rtype: float
625941e78c3a873295158821
def run(rank, size): <NEW_LINE> <INDENT> torch.manual_seed(1234) <NEW_LINE> train_set, bsz = partition_dataset() <NEW_LINE> model = Net() <NEW_LINE> model = model <NEW_LINE> optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5) <NEW_LINE> num_batches = ceil(len(train_set.dataset) / float(bsz)) <NEW_LINE> for...
Distributed Synchronous SGD Example
625941e7baa26c4b54cb157c
def smart_move(board_string): <NEW_LINE> <INDENT> winning_move = first_move(board_string, move_wins) <NEW_LINE> if winning_move: <NEW_LINE> <INDENT> return winning_move <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return first_move(board_string, lambda b,i: b[i] == '-')
Return an optimal move if one exists. Picks a random winning move if possible, and if not, makes a random move.
625941e7d7e4931a7ee9e380
def create_user(self,email,password=None,**extra_fields): <NEW_LINE> <INDENT> if not email: <NEW_LINE> <INDENT> raise ValueError("Email invalid") <NEW_LINE> <DEDENT> email=self.normalize_email(email) <NEW_LINE> user=self.model(email=email,**extra_fields) <NEW_LINE> user.set_password(password) <NEW_LINE> user.save(using...
Creates and save new user
625941e7e8904600ed9f2395
def test2_right_rotation(self): <NEW_LINE> <INDENT> P, Q, A, B, C = self.nodes <NEW_LINE> self.tree.right_rotation(Q) <NEW_LINE> self.assertIs( P.right, Q, "Rotating {0} right should move it as the right child of its old left child, {1}" .format(Q, P) ) <NEW_LINE> self.assertIs( Q.left, B, "Rotating {0} right should mo...
Rotating a node right moves the node down to the right and its left child up. (0p)
625941e77c178a314d6ef8c8
def add_product(self, product): <NEW_LINE> <INDENT> product = product or 'unknown' <NEW_LINE> product = product[0:50] <NEW_LINE> self._add_name( product, self.product_lookup, self.product_placeholders, self.unique_products, self.product_where_in_list )
Add product names
625941e74c3428357757c787
def __init__(self, equity=None, available_balance=None, used_margin=None, order_margin=None, position_margin=None, occ_closing_fee=None, occ_funding_fee=None, wallet_balance=None, realised_pnl=None, unrealised_pnl=None, cum_realised_pnl=None, given_cash=None, service_cash=None): <NEW_LINE> <INDENT> self._equity = None ...
WalletBalance - a model defined in Swagger
625941e760cbc95b062c69a5
def get_single_sale(self, sale_id): <NEW_LINE> <INDENT> if len(self.all_Sales) > 0: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> SaleRecord = next(sale for sale in self.all_Sales if sale["sale_id"] == int(sale_id)) <NEW_LINE> return SaleRecord <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> return Fals...
This method fetches a single sale
625941e73539df3088e2e7ad
def wolfram_api_call(self, api, **kwargs): <NEW_LINE> <INDENT> return WolframAPICallAsync(self, api, **kwargs)
Build an helper class instance to call a given API.
625941e75f7d997b87174efd
def maxCoins(self, nums): <NEW_LINE> <INDENT> return self.burstBallon(nums)
:type nums: List[int] :rtype: int
625941e7de87d2750b8601f8
def handle(self, *args, **kwargs): <NEW_LINE> <INDENT> self.stdout.write( "Creating or updating PurBeurre database...", ending='\n') <NEW_LINE> CATEGORIES = ( "Petit-déjeuners", "Snacks sucrés", "Snacks salés", "Boissons", "Desserts", "Produits laitiers", "Viandes", "Produits de la mer", "Plats préparés", "Epicerie", "...
List of categories.
625941e7fff4ab517eb2f8a0
def AsJsonString(self): <NEW_LINE> <INDENT> return json.dumps(self.AsDict(), sort_keys=True)
Returns the TiendaMobilModel as a JSON string based on key/value pairs returned from the AsDict() method.
625941e7a4f1c619b28b0490
@verify_request <NEW_LINE> def get_ranking(request): <NEW_LINE> <INDENT> user = get_login_user(request) <NEW_LINE> user_sub_feeds = [] <NEW_LINE> if user: <NEW_LINE> <INDENT> user_sub_feeds = get_user_subscribe_feeds(user.oauth_id, user_level=user.level) <NEW_LINE> <DEDENT> feed_ranking = get_feed_ranking_dict() <NEW_L...
获取订阅源排行榜
625941e75fcc89381b1e1b23
def saveobj(filename=None, obj=None, compresslevel=5, verbose=True, folder=None): <NEW_LINE> <INDENT> fullpath = makefilepath(filename=filename, folder=folder, sanitize=True) <NEW_LINE> with GzipFile(fullpath, 'wb', compresslevel=compresslevel) as fileobj: <NEW_LINE> <INDENT> fileobj.write(pkl.dumps(obj, protocol=-1)) ...
Save an object to file -- use compression 5 by default, since more is much slower but not much smaller. Once saved, can be loaded with loadobj() (q.v.). Usage: myobj = ['this', 'is', 'a', 'weird', {'object':44}] saveobj('myfile.obj', myobj)
625941e7ff9c53063f47c653
def go_line_start(self): <NEW_LINE> <INDENT> self.mark_set('insert', 'insert linestart')
It goes to the beginning of the cursor position line.
625941e756b00c62f0f14abe
def ResizeBrowser(self, width, height): <NEW_LINE> <INDENT> if not self._driver: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.ExecuteScript('window.resizeTo(%(width)d, %(height)d);' % {'width': width, 'height': height}) <NEW_LINE> <DEDENT> except ExecutionError: <NEW_LINE> <INDENT> ...
Attempt to resize the browser to the given width and height. Args: width: An int representing the requested width for the browser in pixels. height: An int representing the requested height for the browser in pixels.
625941e7ad47b63b2c50a3e0
def value(self,varName): <NEW_LINE> <INDENT> if varName not in self.pcfg: <NEW_LINE> <INDENT> regx = re.compile(varName + ' = (.*)$', re.MULTILINE) <NEW_LINE> rematch = regx.search(self.puppetCfgFull); <NEW_LINE> self.pcfg[varName] = rematch.group(1) <NEW_LINE> <DEDENT> return self.pcfg[varName]
returns the value of the config variable as a string caching values as used.
625941e763f4b57ef000156e
def make_bash(gen_out) -> None: <NEW_LINE> <INDENT> if gen_out.arguments['custom_check_bins_provided'] == 'true': <NEW_LINE> <INDENT> package_filename = 'packages/{}/{}.tar.xz'.format( gen_out.arguments['custom_check_bins_package_name'], gen_out.arguments['custom_check_bins_package_id'], ) <NEW_LINE> make_custom_check_...
Build bash deployment artifacts and return a list of their filenames.
625941e77b180e01f3dc4c56
def createLinearRamp(rampType=None, rampSize=256, driver=None): <NEW_LINE> <INDENT> def _versionTuple(v): <NEW_LINE> <INDENT> return tuple(map(int, v.split('.'))) <NEW_LINE> <DEDENT> if rampType is None: <NEW_LINE> <INDENT> osxVer = platform.mac_ver()[0] <NEW_LINE> if osxVer: <NEW_LINE> <INDENT> osxVerTuple = _versionT...
Generate the Nx3 values for a linear gamma ramp on the current platform. This uses heuristics about known graphics cards to guess the 'rampType' if none is explicitly given. Much of this work is ported from LoadIdentityClut.m, by Mario Kleiner for the psychtoolbox rampType 0 : an 8-bit CLUT ranging 0:1 This is se...
625941e72c8b7c6e89b35c1f
def get_claveuc_real(df: DataFrame, unidades_validas: Set[str]) -> DataFrame: <NEW_LINE> <INDENT> df: DataFrame = df.copy() <NEW_LINE> cond1: pd.Series = (df.CLAVEUC == df.CLAVEUC_PROC) <NEW_LINE> cond2: pd.Series = (df.CLAVEUC == df.CLAVEUC_NOM) <NEW_LINE> cond3: pd.Series = (df.CLAVEUC_NOM == df.CLAVEUC_PROC) <NEW_LI...
Obtiene la clave uc a partir del nombre, num de procedimiento y el directorio de UCs
625941e794891a1f4081bf0d
def secant_method(tol, f, x0): <NEW_LINE> <INDENT> x1 = x0 * 1.1 <NEW_LINE> while (abs(x1 - x0) / abs(x1) > tol): <NEW_LINE> <INDENT> x0, x1 = x1, x1 - f(x1) * (x1 - x0) / (f(x1) - f(x0)) <NEW_LINE> <DEDENT> return x1
Solve for x where f(x)=0, given starting x0 and tolerance. Arguments ---------- tol: tolerance as percentage of final result. If two subsequent x values are with tol percent, the function will return. f: a function of a single variable x0: a starting value of x to begin the solver Notes ------ The secant method for f...
625941e7379a373c97cfafa8
def __init__(self): <NEW_LINE> <INDENT> super(Werewolf, self).__init__(health=200, attack=randint(5, 30))
constructor that calls super constructor with default values
625941e77d43ff24873a3105
def test03_delslice(self): <NEW_LINE> <INDENT> for Len in range(self.limit): <NEW_LINE> <INDENT> pl, ul = self.lists_of_len(Len) <NEW_LINE> del pl[:] <NEW_LINE> del ul[:] <NEW_LINE> self.assertEqual(pl[:], ul[:], 'del slice [:]') <NEW_LINE> for i in range(-Len - 1, Len + 1): <NEW_LINE> <INDENT> pl, ul = self.lists_of_l...
Delete slice
625941e7d6c5a102081444b0
def test_sso_method_id_is_attribute(): <NEW_LINE> <INDENT> sso = types.Sso( methods=[ types.Method( id=types.SsoMethod.GUEST_AGENT ) ] ) <NEW_LINE> buf = make_buffer() <NEW_LINE> writer = XmlWriter(buf, indent=True) <NEW_LINE> SsoWriter.write_one(sso, writer) <NEW_LINE> writer.flush() <NEW_LINE> assert_equals( decode_b...
Test that writing an SSL object with one method writes the method identifier as the 'id' attribute.
625941e721a7993f00bc8159
def test_single_multiline() -> None: <NEW_LINE> <INDENT> test_input = "from os import\\\n getuid\n\nprint getuid()\n" <NEW_LINE> output = isort.code(test_input) <NEW_LINE> assert output == ("from os import getuid\n\nprint getuid()\n")
Test the case where a single import spawns multiple lines.
625941e7d8ef3951e324399f
def listxattr(self, path): <NEW_LINE> <INDENT> logger.debug("listxattr(%r)", path) <NEW_LINE> raise FuseOSError(EPERM)
listxattr Not implemented. Raises EPERM.
625941e7925a0f43d254a2dd
def get_state(self, daytime_date, after_shkia_date, after_tzais_date): <NEW_LINE> <INDENT> if self._type == "upcoming_shabbat_candle_lighting": <NEW_LINE> <INDENT> times = self.make_zmanim( after_tzais_date.upcoming_shabbat.previous_day.gdate ) <NEW_LINE> return times.candle_lighting <NEW_LINE> <DEDENT> if self._type =...
For a given type of sensor, return the state.
625941e73617ad0b5ed68358
def testJsonExportJSONRequest(self): <NEW_LINE> <INDENT> pass
Test JsonExportJSONRequest
625941e78a349b6b435e85d4
def test_naive_bayes(test_x, test_y, logprior, loglikelihood): <NEW_LINE> <INDENT> accuracy = 0 <NEW_LINE> y_hats = [] <NEW_LINE> for tweet in test_x: <NEW_LINE> <INDENT> if naive_bayes_predict(tweet, logprior, loglikelihood) > 0: <NEW_LINE> <INDENT> y_hat_i = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> y_hat_i = 0...
Input: test_x: A list of tweets test_y: the corresponding labels for the list of tweets logprior: the logprior loglikelihood: a dictionary with the loglikelihoods for each word Output: accuracy: (# of tweets classified correctly)/(total # of tweets)
625941e7009cb60464c63810
def change_governor(self, new_governor, **tx_arguments): <NEW_LINE> <INDENT> governor_address = Web3.toChecksumAddress(new_governor) <NEW_LINE> tx_args = self.tx_arguments(**tx_arguments) <NEW_LINE> tx_receipt = self.sc.changeIGovernor(governor_address, tx_args) <NEW_LINE> tx_receipt.info() <NEW_LINE> receipt_to_log(tx...
Change the contract's governor. Should be called through the old governance system new_governor New governor address
625941e71b99ca400220af15
def setstyle(self,name,val): <NEW_LINE> <INDENT> self._style[name]=val
Set a style value
625941e77b25080760e398b8
def matrix(self, matrix: np.ndarray, **kwargs) -> np.ndarray: <NEW_LINE> <INDENT> return matrix
The definition of the gate as a unitary matrix Args: matrix: 4 by 4 matrix that defines the two qubit gate **kwargs: Additional keyword arguments Returns: np.ndarray
625941e71b99ca400220af16
@group() <NEW_LINE> def piku(): <NEW_LINE> <INDENT> pass
The smallest PaaS you've ever seen
625941e791af0d3eaac9be7f
def logWarn(self, message, param=''): <NEW_LINE> <INDENT> self.log.warn(message, param)
logger helper
625941e721bff66bcd684db0
def test_resource_id_invalid_id_type(self): <NEW_LINE> <INDENT> self.assertRaisesValidationError( '42 must be a string in "resources.someobject"', APIPolicyWebAPIToken.validate_policy, { 'resources': { 'someobject': { 42: { 'allow': ['*'], } } } })
Testing BaseWebAPIToken.validate_policy with <resource>.<id> with invalid ID type
625941e70383005118ecfa43
@pytest.mark.parametrize("vals_to_add, val_to_test, result", DEPTH_TRAVERSAL_TABLE) <NEW_LINE> def test_depth_traversal_works(vals_to_add, val_to_test, result, empty_graph): <NEW_LINE> <INDENT> for val in vals_to_add: <NEW_LINE> <INDENT> empty_graph.add_edge(val[0], val[1]) <NEW_LINE> <DEDENT> assert empty_graph.depth_...
Result should happen based on val passed in. Depth Table.
625941e7046cf37aa974d1a5
def from_dict(self, data_dict): <NEW_LINE> <INDENT> self.name = data_dict['linux-bridge']['name'] <NEW_LINE> self.port_list = [] <NEW_LINE> if 'ports' in data_dict['linux-bridge']: <NEW_LINE> <INDENT> for port_dict in data_dict['linux-bridge']['ports']: <NEW_LINE> <INDENT> port_obj = _inspect_dictionary_type(port_dict)...
Populate this object with data from a dictionary. See to_dict method doc for expected format. :param data_dict: A dictionary with the data to use.
625941e7d18da76e2353293e
@Issue(4118) <NEW_LINE> @Skip() <NEW_LINE> def status_without_wc_db_and_entries(sbox): <NEW_LINE> <INDENT> sbox.build(read_only = True) <NEW_LINE> os.remove(sbox.ospath(".svn/wc.db")) <NEW_LINE> os.remove(sbox.ospath(".svn/entries")) <NEW_LINE> svntest.actions.run_and_verify_svn2( "Status when wc.db and entries are mis...
missing .svn/wc.db and .svn/entries
625941e75fdd1c0f98dc0697
def _boto_multipart(self): <NEW_LINE> <INDENT> if not os.path.exists( os.path.join( self.workdir, self.output_file.split('.')[0] ) ): <NEW_LINE> <INDENT> os.mkdir(os.path.join( self.workdir, self.output_file.split('.')[0] )) <NEW_LINE> <DEDENT> os.chdir( os.path.join(self.workdir, self.output_file.split('.')[0]) ) <NEW...
Split file into chunks, upload chunks NOTE: this should never happen, as your files should be much smaller than this, but one never knows
625941e721a7993f00bc815a
def __init__( self, tau, M ): <NEW_LINE> <INDENT> nbs.__init__(self,tau) <NEW_LINE> self.M = M
Create a NWBS algorithm object. We basically provide the threshold to declare a change-point and the number of random intervals to pick. Parameters ---------- tau : float The threshold to declare a change-point. How to set this value is discussed in the paper, although we did not implement any automatic me...
625941e73346ee7daa2b31d1
def prompt_file_name(file_list: Optional[List[str]] = None) -> str: <NEW_LINE> <INDENT> ls_output = os.listdir() if not file_list else file_list <NEW_LINE> for i, file in enumerate(ls_output): <NEW_LINE> <INDENT> p.print_yellow("({}) {}".format(i+1, file)) <NEW_LINE> <DEDENT> while True: <NEW_LINE> <INDENT> try: <NEW_L...
Prompts the user for a file to open
625941e7a934411ee3751af7
def update_priorities(self, cr, uid, model_dict, min_priority, context=None): <NEW_LINE> <INDENT> for model in model_dict: <NEW_LINE> <INDENT> domain = [ ('model', '=', model), ('priority', '<', min_priority), ('state', '!=', FILE_STATE_DONE) ] <NEW_LINE> object_ids = model_dict[model] <NEW_LINE> if object_ids is not N...
@param model_dict: Dictionary of models and IDs @param min_priority: min value of priority to set This function sets the priority of any unsent files with a lower priority, so they are processed always before than others
625941e7cdde0d52a9e53498
def get_resource(self, **kwargs) -> Resource: <NEW_LINE> <INDENT> return next((res for res in self.resources if matches(res, **kwargs)), None)
Returns the first resource whose attributes match the kwargs. :param kwargs: Desired attributes of a resource. :return: Resource.
625941e7a4f1c619b28b0491
def render(self, name, value, attrs=None): <NEW_LINE> <INDENT> html = super(CodeMirrorTextarea, self).render(name, value, attrs) <NEW_LINE> kwargs = { 'id': "\"id_%s\""%name, } <NEW_LINE> for key in kwargs.keys(): <NEW_LINE> <INDENT> kwargs[key] = mark_safe(kwargs[key]) <NEW_LINE> <DEDENT> code = render_to_string(r"sid...
Render CodeMirrorTextarea
625941e799cbb53fe6793047
def clients_evicted(ctx, config): <NEW_LINE> <INDENT> if config is None: <NEW_LINE> <INDENT> config = {} <NEW_LINE> <DEDENT> assert isinstance(config, dict), 'task only accepts a dict for configuration' <NEW_LINE> clients = config.get('clients') <NEW_LINE> if clients is None: <NEW_LINE> <INDENT> clients = {("cli...
Check clients are evicted, unmount (cleanup) if so.
625941e7e8904600ed9f2396
def to_image(self): <NEW_LINE> <INDENT> if self._cached_image: <NEW_LINE> <INDENT> return self._cached_image <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> parsed = self.dna.parse() <NEW_LINE> img = Image.new('RGB', (256, 256)) <NEW_LINE> drw = ImageDraw.Draw(img, 'RGBA') <NEW_LINE> (bg_r, bg_g, bg_b) = parsed["bg"] <NE...
Generate (and cache) a Pillow image made of this Candidate's Triangles.
625941e77c178a314d6ef8c9
def do_post(self, parent=None, headers=None, body=None, files=None, admin=True): <NEW_LINE> <INDENT> if parent is None: <NEW_LINE> <INDENT> parent = self.getBaseUri() <NEW_LINE> <DEDENT> if headers is None: <NEW_LINE> <INDENT> headers = {} <NEW_LINE> <DEDENT> my_auth = self.get_auth(admin) <NEW_LINE> return requests.po...
Do a POST
625941e75f7d997b87174efe
def get_config_variable(self, logical_name, methods=('instance', 'env', 'config'), default=None): <NEW_LINE> <INDENT> value = None <NEW_LINE> config_default = None <NEW_LINE> if logical_name in self.session_var_map: <NEW_LINE> <INDENT> if 'instance' in methods and logical_name in self._session_instan...
Retrieve the value associated with the specified logical_name from the environment or the config file. Values found in the environment variable take precedence of values found in the config file. If no value can be found, a None will be returned. :type logical_name: str :param logical_name: The logical name of the s...
625941e7e5267d203edce0f9
def count_centuries(records): <NEW_LINE> <INDENT> centuries_counter = Counter() <NEW_LINE> for record in records: <NEW_LINE> <INDENT> for k, v in record.items(): <NEW_LINE> <INDENT> if k == "Composition Year": <NEW_LINE> <INDENT> value = v.strip() <NEW_LINE> if value == "": <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDE...
Ze seznamu všech záznamů vytvoří uspořádaný seznam dvojic seřazený podle počtu výskytů skladeb v jednotlivých stoletích.
625941e76aa9bd52df037209
def _metaReader(self): <NEW_LINE> <INDENT> meta_data = None <NEW_LINE> return meta_data
############################################## ——————— Input: - ——————— Output: - ——————— status: active ##############################################
625941e7fbf16365ca6f6630
def forward_message(chat_id, from_chat_id, message_id, disable_notification=False, **kwargs): <NEW_LINE> <INDENT> params = dict( chat_id=chat_id, from_chat_id=from_chat_id, message_id=message_id, disable_notification=disable_notification, ) <NEW_LINE> return TelegramBotRPCRequest('forwardMessage', params=params, on_res...
Use this method to forward messages of any kind. :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) :param from_chat_id: Unique identifier for the chat where the original message was sent — User or GroupChat id :param message_id...
625941e79b70327d1c4e123a
def get_tangent_basis(ra, dec): <NEW_LINE> <INDENT> ra = np.atleast_1d(ra) <NEW_LINE> dec = np.atleast_1d(dec) <NEW_LINE> s = [] <NEW_LINE> for cra, cdec in zip(ra, dec): <NEW_LINE> <INDENT> s.append( np.array([ [-np.sin(cra), np.cos(cra), 0.], [-np.sin(cdec)*np.cos(cra), -np.sin(cdec)*np.sin(cra), np.cos(cdec)], [np.c...
row vectors are the tangent-space basis at (alpha, delta, r) ra, dec in radians
625941e78a43f66fc4b544c3
def run(self): <NEW_LINE> <INDENT> pydocstyle.Error.explain = self.options['explain'] <NEW_LINE> filename, source = load_file(self.filename) <NEW_LINE> for error in pydocstyle.PEP257Checker().check_source(source, filename): <NEW_LINE> <INDENT> if not hasattr(error, 'code') or ignore(error.code): <NEW_LINE> <INDENT> con...
Run analysis on a single file.
625941e7d268445f265b52d1
def __init__(self, modality_dict): <NEW_LINE> <INDENT> super(MMEN, self).__init__() <NEW_LINE> self.SMEs = nn.ModuleDict() <NEW_LINE> self.name='MMEN' <NEW_LINE> for modality in modality_dict: <NEW_LINE> <INDENT> layer_sizes = modality_dict[modality]['layer_sizes'] <NEW_LINE> num_layers = modality_dict[modality]['num_l...
modality_dict: {modality: {'layer_sizes': [], 'num_layers': \#}}
625941e7b545ff76a8914278
def update_plot(self, name, *args, **kwargs): <NEW_LINE> <INDENT> self.__plot[name].update(*args, **kwargs) <NEW_LINE> return self
Updates the plot specified by its name, passing its given arguments Parameters ---------- name : str the unique name of the plot args : ... the arguments for the plot update method kwargs : ... the keyword arguments for the plot update method Returns ------- VisdomScene the scene itself
625941e763d6d428bbe44953
def cleanupNormPath(path, dotYN=0): <NEW_LINE> <INDENT> if path is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> path = os.path.normpath( os.path.expanduser( os.path.expandvars(path))) <NEW_LINE> if dotYN and not (path and path[0] == '/'): <NEW_LINE> <INDENT> dirs = path.split('/') <NEW_LINE> if dirs[:1] no...
take ~taw/../some/path/$MOUNT_POINT/blah and make it sensible. Returned path may be relative. NOTE: python 2.2 fixes a number of bugs with this and eliminates the need for os.path.expanduser
625941e766656f66f7cbc60f
def gaussianwindow(x, sigma=0.2): <NEW_LINE> <INDENT> i = np.arange(len(x)) <NEW_LINE> m = (len(x) - 1) / 2 <NEW_LINE> return x * np.exp(-((i - m) ** 2) / (2 * (sigma * len(x)) ** 2))
Gaussian FFT window Parameters ---------- sigma : float
625941e74428ac0f6e5bac59
def ReleaseResultSet(self, *args): <NEW_LINE> <INDENT> return _ogr.DataSource_ReleaseResultSet(self, *args)
ReleaseResultSet(DataSource self, Layer layer) void OGR_DS_ReleaseResultSet(OGRDataSourceH hDS, OGRLayerH hLayer) Release results of OGR_DS_ExecuteSQL(). This function should only be used to deallocate OGRLayers resulting from an OGR_DS_ExecuteSQL() call on the same OGRDataSource. Failure to deallocate a results set...
625941e7adb09d7d5db6cbef
def toJson (self): <NEW_LINE> <INDENT> pass
Returns document representation in json
625941e7f8510a7c17cf9b62
def configure_tempesta(self): <NEW_LINE> <INDENT> for s in self.servers: <NEW_LINE> <INDENT> sg = tempesta.ServerGroup(s.group) <NEW_LINE> sg.add_server(s.ip, s.port, s.conns_n) <NEW_LINE> self.tempesta.config.add_sg(sg)
Add every server to it's own server group with default scheduler.
625941e7be7bc26dc91cda5a
def __check_same_attribute(self, parent, child, _class): <NEW_LINE> <INDENT> for p_attr in parent: <NEW_LINE> <INDENT> for c_attr in child: <NEW_LINE> <INDENT> if p_attr.name == c_attr.name: <NEW_LINE> <INDENT> raise RedefinedAttributeError(_class)
It's illegal to redefine attribute names in child class.
625941e7046cf37aa974d1a6
def u(self, arg, qubit, nested_scope=None): <NEW_LINE> <INDENT> if self.listen: <NEW_LINE> <INDENT> if "U" not in self.basis: <NEW_LINE> <INDENT> self.basis.append("U") <NEW_LINE> <DEDENT> this_gate = self.circuit.u_base(list(map(lambda x: x.real(nested_scope), arg)), self._map_qubit(qubit)) <NEW_LINE> if self.creg is ...
Fundamental single qubit gate. arg is 3-tuple of Node expression objects. qubit is (regname,idx) tuple. nested_scope is a list of dictionaries mapping expression variables to Node expression objects in order of increasing nesting depth.
625941e7627d3e7fe0d692b4
def test_add_edge_error(complex_g): <NEW_LINE> <INDENT> with pytest.raises(ValueError): <NEW_LINE> <INDENT> complex_g.add_edge('C', 'G')
Test del_edge raises error if adds an edge that already exists.
625941e7498bea3a759b9f11
def parse_matrix(matrix, GOI_set, outfile, logger): <NEW_LINE> <INDENT> f_in = open(matrix, "r") <NEW_LINE> f_out = open(outfile, "w") <NEW_LINE> matrix_found_count = 0 <NEW_LINE> for line in f_in: <NEW_LINE> <INDENT> if test_line(line): <NEW_LINE> <INDENT> if line.startswith("\t"): <NEW_LINE> <INDENT> f_out.write(line...
fucn take in the counts.matrix and GOI_set if the gene in the matrix is in the set, prints it to the file.
625941e7cc0a2c11143dd2f5
def findMedianSortedArrays(self, nums1, nums2): <NEW_LINE> <INDENT> N1, N2 = len(nums1), len(nums2) <NEW_LINE> if N1 < N2: <NEW_LINE> <INDENT> nums1, N1, nums2, N2 = nums2, N2, nums1, N1 <NEW_LINE> <DEDENT> l, r = 0, N2*2 <NEW_LINE> while l <= r: <NEW_LINE> <INDENT> j = (l + r) >> 1 <NEW_LINE> i = N1 + N2 - j <NEW_LINE...
:type nums1: List[int] :type nums2: List[int] :rtype: float
625941e7eab8aa0e5d26dfbc
def read_config(): <NEW_LINE> <INDENT> with open("config.json",'rb') as json_file: <NEW_LINE> <INDENT> config = json.load(json_file) <NEW_LINE> <DEDENT> return config
"读取配置
625941e794891a1f4081bf0e
def versioned(self): <NEW_LINE> <INDENT> box = self.store.new_sandbox() <NEW_LINE> try: <NEW_LINE> <INDENT> return bool(box.unit(DeployedVersion, ID=self.guid)) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> box.flush_all()
Return True if this installation has a DeployedVersion, false otherwise.
625941e726068e7796caf149
def bound_roombas(self, frame): <NEW_LINE> <INDENT> roombas = self.filter_roombas(frame) <NEW_LINE> frame_gray = cv2.cvtColor(roombas, cv2.COLOR_BGR2GRAY) <NEW_LINE> contours, _ = cv2.findContours(frame_gray,cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) <NEW_LINE> for c in contours: <NEW_LINE> <INDENT> rect = cv2.boundin...
Find bounding boxes for all pixel clumps (roombas) with dimensions larger than 10 pixels on each side. Also draws the bounding rects onto the original frame. :param img_gray: single channel image used to find edges :type img_gray: numpy.ndarray of shape 1 x WIDTH x HEIGHT & dtype uint8 :param img: original three chann...
625941e773bcbd0ca4b2c4d8
def create_analysis(covdata, name): <NEW_LINE> <INDENT> args = covdata.analysis2(name) <NEW_LINE> return CoverageAnalysis(*args)
Returns a CoverageAnalysis instance. :param covdata: a Coverage() instance :param name: file or module name
625941e7d164cc61757831b2
def register_batch_request_with_http_info(self, body, **kwargs): <NEW_LINE> <INDENT> all_params = ['body', 'atomic'] <NEW_LINE> all_params.append('async_req') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all_params.append('_request_timeout') <NEW_LIN...
Register a Collection of API Calls at a Single End Point # noqa: E501 Enables you to make multiple API requests using a single request. The batch API takes in an array of logical HTTP requests represented as JSON arrays. Each request has a method (GET, PUT, POST, or DELETE), a relative_url (the portion of the URL aft...
625941e74f6381625f114e9f
def inverse(self): <NEW_LINE> <INDENT> if not self.is_square(): <NEW_LINE> <INDENT> raise(ValueError, "Non-square Matrix does not have an inverse.") <NEW_LINE> <DEDENT> if self.h > 2: <NEW_LINE> <INDENT> raise(NotImplementedError, "inversion not implemented for matrices larger than 2x2.") <NEW_LINE> <DEDENT> if self.h ...
Calculates the inverse of a 1x1 or 2x2 Matrix.
625941e78e71fb1e9831dc0a
def __init__(self, lines, has_POS): <NEW_LINE> <INDENT> self.word = {} <NEW_LINE> self.pos = {} <NEW_LINE> self.rel = {} <NEW_LINE> self.dep = {} <NEW_LINE> self.children = {} <NEW_LINE> self.leaves = [] <NEW_LINE> self.root_idx = -1 <NEW_LINE> self.prepare_indice...
Constructor
625941e7cc40096d61595db2
def get_now(): <NEW_LINE> <INDENT> return pd.to_datetime('today').strftime('%Y_%m_%d_%H_%M')
Get current datetime in specific format e.g. 2020_09_10_12_10. Used to name files in chronological order ====================================================================================== Returns: datetime object of current time
625941e7236d856c2ad44c43
def doFailureActionGeneratePrediction(self, _edPlugin): <NEW_LINE> <INDENT> self.verboseDebug("EDPluginControlIndexingv10.doFailureActionGeneratePrediction") <NEW_LINE> strWarningMessage = "Cannot generate prediction pattern" <NEW_LINE> self.warning(strWarningMessage) <NEW_LINE> self.addWarningMessages([ strWarningMess...
Executed if the generate prediction plugin did not terminate correctly.
625941e716aa5153ce3628db
def from_perl_syntax(d): <NEW_LINE> <INDENT> return str(d).replace(' => ', ':').replace('(', '[').replace(')', ']').replace('@', '')
Essentially the inverse of to_perl_syntax() but we also nuke the '@' prefix on a list.
625941e7adb09d7d5db6cbf0
def test_login_required_no_such_badge(client: TestClient, session: db.Session): <NEW_LINE> <INDENT> expire = datetime.utcnow() + timedelta(minutes=15) <NEW_LINE> fake_data = {"exp": expire, "sub": "nopers", "jti": uuid.uuid4().hex} <NEW_LINE> fake_token = jwt.encode(fake_data, settings.secret_key) <NEW_LINE> response =...
login_required dependency can handled badges that don't exist
625941e767a9b606de4a831a
def __init__(self, indexShape, shape, dtype=float): <NEW_LINE> <INDENT> indexShape = np.cast[int](np.atleast_1d(indexShape)) <NEW_LINE> shape = np.cast[int](np.atleast_1d(shape)) <NEW_LINE> self._shape = tuple(shape) <NEW_LINE> self._size = np.prod(shape) <NEW_LINE> self._indexShape = tuple(indexShape) <NEW_LINE> self....
Create empty series of given shape and data type. Arguments: indexShape : shape of array of datasets shape : Shape of datasets dtype : Type of datasets
625941e7dc8b845886cb599a
def __init__(self, encoding): <NEW_LINE> <INDENT> self.encoding = encoding
Initialization :Parameters: `encoding` : ``str`` The target encoding
625941e7d6c5a102081444b1
def send_image(self, image_path): <NEW_LINE> <INDENT> self.client.messages.create(roomId=self.context["channel_id"], files=[image_path])
Send an image as a file upload.
625941e750485f2cf553d1fe
def getJointPosTicks(self, *args): <NEW_LINE> <INDENT> return _AriaPy.ArP2Arm_getJointPosTicks(self, *args)
getJointPosTicks(self, int joint) -> unsigned char
625941e7e76e3b2f99f3ac67
def close(self): <NEW_LINE> <INDENT> self._producer = []
Used to invalidate/disable this lazy stream. Replace the producer with an empty list. Any leftover bytes that have already been read will still be reported upon read() and/or next().
625941e7a79ad161976cc5a9
def CalculateTemperatureChange(numYears, radForcing): <NEW_LINE> <INDENT> ClimateSensitivity = 1.1; <NEW_LINE> result = np.zeros(len(radForcing)) <NEW_LINE> tempResFunc = GenerateTempResponseFunction(numYears) <NEW_LINE> for i in range(len(radForcing)): <NEW_LINE> <INDENT> for j in range(i, len(radForcing)): <NEW_LINE>...
This function calculates the temperature change due to changes in radiative forcing. :param numYears: number of years the temperature response function will be evaluated for. :param radForcing: changes in radiative forcing due to changes in |CO2|, |CH4|, |N2O| concentrations and |SOx| emissions. :return: numpy.array -...
625941e7283ffb24f3c55d60
def history_files_list(gen_count) -> (float, int, str, int): <NEW_LINE> <INDENT> retval = [] <NEW_LINE> for i in range(int((gen_count + 1) / 2)): <NEW_LINE> <INDENT> retval.append( ( HF_FIRST_DAY + (((((i * 24) + 9) * 60) + 0) * 60) + 0, 100, f".argle/xonsh-{2*i:05n}.json", 10000, ) ) <NEW_LINE> retval.append( ( HF_FIR...
Generate a list of history file tuples
625941e707d97122c4178cf9
def connect(self): <NEW_LINE> <INDENT> self.connector = connectWS(self)
Establish WebSocket connection to the ROS server defined for this factory.
625941e7cb5e8a47e48b7f07
def get_backward_walk_ops(seed_ops, inclusive=True, within_ops=None, control_inputs=True): <NEW_LINE> <INDENT> if not util.is_iterable(seed_ops): seed_ops = [seed_ops] <NEW_LINE> if not seed_ops: return set() <NEW_LINE> if isinstance(seed_ops[0], tf_ops.Tensor): <NEW_LINE> <INDENT> ts = util.make_list_of_t(seed_ops, al...
Do a backward graph walk and return all the visited ops. Args: seed_ops: an iterable of operations from which the backward graph walk starts. If a list of tensors is given instead, the seed_ops are set to be the generators of those tensors. inclusive: if True the given seed_ops are also part of the resulti...
625941e755399d3f05588b1a
def pyngl(self, geobounds, **kwargs): <NEW_LINE> <INDENT> if not pyngl_enabled(): <NEW_LINE> <INDENT> raise RuntimeError("'pyngl' is not " "installed or is disabled") <NEW_LINE> <DEDENT> return self._pyngl(geobounds, **kwargs)
Return a :class:`Ngl.Resources` object for the map projection. Args: geobounds (:class:`wrf.GeoBounds`, optional): The geobounds to get the extents. If set to None and using the *var* parameter, the geobounds will be taken from the variable. If using a file, then the geobounds will be...
625941e73317a56b8693a0b1
def firstUniqChar(self, s): <NEW_LINE> <INDENT> d = OrderedDict() <NEW_LINE> for i in s: <NEW_LINE> <INDENT> if ord(i) - ord('a') not in d: <NEW_LINE> <INDENT> d[ord(i) - ord('a')] = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> d[ord(i) - ord('a')] += 1 <NEW_LINE> <DEDENT> <DEDENT> for i in d.keys(): <NEW_LINE> <IND...
:type s: str :rtype: int
625941e7462c4b4f79d1db33
def _computeXdir(normal): <NEW_LINE> <INDENT> xd = Vector(0, 0, 1).cross(normal) <NEW_LINE> if xd.Length < self.ctx.tolerance: <NEW_LINE> <INDENT> xd = Vector(1, 0, 0) <NEW_LINE> <DEDENT> return xd
Figures out the X direction based on the given normal. :param :normal The direction that's normal to the plane. :type :normal A Vector :return A vector representing the X direction.
625941e73539df3088e2e7af
def get_skeletons(file): <NEW_LINE> <INDENT> flag = True; <NEW_LINE> try: <NEW_LINE> <INDENT> f = h5py.File(file) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> flag = False; <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if not flag: <NEW_LINE> <INDENT> f = scipy.io.loadmat(file) <NEW_LINE> <DEDENT> <DEDENT> except: <N...
get sequence of skeletons from a particular file
625941e79c8ee82313fbbbda
def test_logger(self): <NEW_LINE> <INDENT> root_logger = logging.getLogger() <NEW_LINE> logger = Logger(root_logger.name, log_file='logger.log', console_lvl=CRITICAL, file_lvl=None) <NEW_LINE> logger.__getstate__() <NEW_LINE> logger.__setstate__({}) <...
Simple logger operations.
625941e7baa26c4b54cb157f