anchor
stringlengths
10
14.3k
positive
stringlengths
10
14.9k
Test user's dict is empty at first
def test_users_dictionary(self): new_user = self.app self.assertEqual(len(new_user.users), 0) new_user.create_user() self.assertIsInstance(new_user, User) self.assertEqual(len(new_user.users), 1)
The data type of the master array.
def dtype(self): return self.config["dtype"]
Convert a pygame surface into a cv image
def pygame_to_cvimage( surface ): cv_image = cv.CreateImageHeader( surface.get_size(), cv.IPL_DEPTH_8U, 3 ) image_string = surface_to_string( surface ) cv.SetData( cv_image, image_string ) return cv_image
Load QA data from night objects on disk
def load_data(self, inroot=None): self.data = {} # Load for night in self.mexp_dict.keys(): qaNight = QA_Night(night, specprod_dir=self.specprod_dir, qaprod_dir=self.qaprod_dir) qaNight.load_data() # self.data[night] = qaNight.data[night]
saves classroomEntities in the ClassRoomData file
def saveClassroomData(): with open("ClassRoomData.txt","wb") as classroomData: pickle.dump(classroomEntities,classroomData)
Wrapper for reference pixel calculation
def _ref_pixel_calc(ifg_paths: List[str], params: dict) -> Tuple[int, int]: lon = params[cf.REFX] lat = params[cf.REFY] ifg = Ifg(ifg_paths[0]) ifg.open(readonly=True) # assume all interferograms have same projection and will share the same transform transform = ifg.dataset.GetGeoTransform() ...
Compute the offset polylines of centerline. Merge coordinates data (x & y information) with bed topography data (z information) to form a point cloud dataset in 3column xyz format.
def offset_all(x, y, beck_bed, t): length = x.size xyz1 = np.zeros((length, 3)) xyz2 = np.zeros((length, 3)) xyz1[:, 0] = np.copy(x) xyz1[:, 1] = np.copy(y) xyz1[:, 2] = np.copy(beck_bed[:, NUM]) allxyz = np.copy(xyz1) offsetx = np.zeros((length, 2)) offsety = np.zeros((length, 2)) ...
Reset the obstacles' positions within the map (should be called when map is refreshed to clean the array)
def reset_obstacles(self): self.obstacles = np.array([])
Should render to the console using a write_source function call on the internal step report's stdout_interceptor.
def test_render_to_console(self, _step: PropertyMock): message = ' {{ a }} is not {{ b }}.' _step_mock = MagicMock() write_source = MagicMock() _step_mock.report.stdout_interceptor.write_source = write_source _step.return_value = _step_mock step = exposed.ExposedStep()...
generates and returns overlap graph from .paf files
def generate_graph(params): alignedreads = read_paf(params, should_filter_paf=True) aligned = [(t, h) for t, h, _ in alignedreads] graph = nx.Graph() graph.add_edges_from(aligned) return graph
Generate seed for the MFA TOTP device.
def generate_totp_seed(self, user_id, mfa_totp_device_id, **kwargs): resource_path = "/users/{userId}/mfaTotpDevices/{mfaTotpDeviceId}/actions/generateSeed" method = "POST" # Don't accept unknown kwargs expected_kwargs = [ "retry_strategy", "if_match" ] ...
Add a session to the user's wishlist, returning a boolean.
def _addSessionToWishlist(self, request): # Preload necessary data items user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') # Verify that the session actually exists session = _getEntityByWebsafeKey(request...
Return the Hamming distance between equallength sequences
def __hamming_distance(s1, s2): if len(s1) != len(s2): raise ValueError("Undefined for sequences of unequal length") return sum(el1 != el2 for el1, el2 in zip(s1, s2))
Called before anything else, i.e. just after installer controller creation. Return value is ignored.
def pre_installation(self): pass
Get the center of the projection.
def get_center(self,lonlat=False): lon, lat = np.asarray(self.rotator.rots[0][0:2])*180/pi if lonlat: return lon,lat else: return pi/2.-lat*dtor, lon*dtor
returns output of new layer
def l2_reg_create_layer(prev, n, activation, lambtha): reg = tf.contrib.layers.l2_regularizer(lambtha) init = tf.contrib.layers.variance_scaling_initializer(mode="FAN_AVG") t = tf.layers.Dense(units=n, activation=activation, kernel_initializer=init, kernel_reg...
Check {sysproid}.{appname}.{cell} is running.
def _test_app_running(self, running_set, sysproid, cell, appname): full_app_name = '%s.%s.%s' % (sysproid, appname, cell) self.assertIn(full_app_name, running_set)
Test for template correctness
def test_for_template(self): self.assertTemplateUsed(self.response, 'my_info_template.html')
Setup authorization for whole API. Can be redefined for an endpoint. OpenAPI Authorization Specs
async def authorization(request): # Decode tokens, load/check users and etc # ... # in the example we just ensure that the authorization header exists return request.headers.get("authorization", "")
Restore a database from a backup file. 'database' A database specification. 'backupfile' A backup file name. 'arguments' A list of the arguments to the GBAK without backup file name and database location. 'result' A 'Result' object. The outcome will be 'Result.PASS' when this method is called. The 'result' may be modif...
def RestoreDatabase(self, database, backupfile, arguments, result): self.RunProgram("\""+self.__context["gbak_path"]+"\"", [ self.__context["gbak_path"] ] + [ "-C ", backupfile ] + arguments + [ database ], "", self.__context, result)
Converts Strava datetime to epoch timestamp
def get_epoch(timestamp): timestamp_dt = datetime.datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%SZ") epoch = calendar.timegm(timestamp_dt.timetuple()) return epoch
Rounding up to next 10th
def roundUP(x): return int(ceil(x / 10.0)) * 10
A lightweight wrapper around `get_context()`. While this used to be the canonical method of instantiating a DataContext before 0.15.40, it is now recommended to use `get_context()`.
def BaseDataContext( # noqa: PLR0913 project_config: Union[DataContextConfig, Mapping], context_root_dir: Optional[PathStr] = None, runtime_environment: Optional[dict] = None, cloud_mode: bool = False, cloud_config: Optional[GXCloudConfig] = None, # Deprecated as of 0.15.37 ge_cloud_mode: b...
Performs a standard classification test with the given classifier.
def classify(dataset,classifier,feat_mask=None): train = dataset.get_data('train',True) X_train = train['x'] if feat_mask is not None: X_train = X_train[:,feat_mask] y_train = train['y'] classifier.fit(X_train,y_train) test = dataset.get_data('test',True) X_...
Return the nth element of the pingpong sequence. >>> pingpong(7) 7 >>> pingpong(8) 6 >>> pingpong(15) 1 >>> pingpong(21) 1 >>> pingpong(22) 0 >>> pingpong(30) 6 >>> pingpong(68) 2 >>> pingpong(69) 1 >>> pingpong(70) 0 >>> pingpong(71) 1 >>> pingpong(72) 0 >>> pingpong(100) 2 >>> from construct_check import check >>> ch...
def pingpong(n): # define two helper function, the recursion start from the bottom # from 1 to n "*** YOUR CODE HERE ***" def positive(n, k, turn): if turn == n: return k else: if (k % 7 == 0) or has_seven(k): return negative(n, k-1, turn + 1) else: return positive(n, k+1, turn + 1) def negat...
Set the RGB colour of an individual light in your Plasma chain. This will set all four LEDs on the Plasma light to the same colour.
def set_light(r, g, b): for x in range(4): set_pixel(x, r, g, b) """Output the buffer """ _sof() for pixel in pixels: r, g, b, brightness = pixel _write_byte(0b11100000 | brightness) _write_byte(b) _write_byte(g) _write_byte(r) _eof()
Return True if the campaign authorizes the user to provide data to the campaign. This is the case if the user owns or works for the campaign. Otherwise, return False.
def authorizes(self, user): return self.owner == user or self.workers.filter(pk=user.id).exists()
A humanreadable description of the new Role.
def description(self) -> pulumi.Output[str]: return pulumi.get(self, "description")
Calculates the solar elevation angle for a specific time.
def solar_elevation(self, dateandtime=None): if self.astral is None: self.astral = Astral() if dateandtime is None: dateandtime = datetime.datetime.now(tz=self.tz) return self.astral.solar_elevation(dateandtime, self.latitude, self.longitude)
Tests that stock and price fields must be numbers
def test_stock_and_price_must_be_numbers(self): resp = self.admin_register() reply = self.admin_login() token = reply['token'] product = dict( prod_name='NY_denims', category='denims', stock='stock', price='money' ) resp = s...
after _send_celery_mail finishes, the tenant should be cleared again
def test_tenant_setup_celery_reset(self): msg = mock.Mock() tenant = mock.Mock() tenant.client_name = 'mock-tenant' _send_celery_mail(msg, tenant, send=False) self.assertFalse(hasattr(properties, 'tenant')) self.assertEqual(properties.tenant_properties, {})
The arguments into which the python args and kwargs are collected
def args(self): return self._parse_args
itkTernaryAddImageFilterIUL2IUL2IUL2IUL2_cast(itkLightObject obj) > itkTernaryAddImageFilterIUL2IUL2IUL2IUL2
def itkTernaryAddImageFilterIUL2IUL2IUL2IUL2_cast(*args): return _itkTernaryAddImageFilterPython.itkTernaryAddImageFilterIUL2IUL2IUL2IUL2_cast(*args)
Poll tests for completion. When one finishes, start another one if there are more to run. Stop when all are finished.
def poll_tests(self): for i, test in enumerate(self.tests): if test.process.poll() is not None: self.check_test(test) self.tests.pop(i) if self.test_numbers: self.start_next_test()
Wrapper for requests GET method
def _get(self, *args, **kwargs): return self._request('get', *args, **kwargs)
DEPERECIATED FUNCTION PLEASE USE active field of subscription
def is_active(self): return self.active
Used to allow a user to edit their own profile.
def edit_profile(request): user = request.user profile = Profile.objects.for_user(user) if request.method != 'POST': profile_form = ProfileForm(instance=profile) user_form = UserForm(instance=user) else: profile_form = ProfileForm(request.POST, instance=profile) ...
Sets the dual solution for a semidefinite variable. putbarsj(self,whichsol_,j_,barsj_)
def putbarsj(self,whichsol_,j_,barsj_): _barsj_minlength = self.getlenbarvarj((j_)) if self.getlenbarvarj((j_)) > 0 and barsj_ is not None and len(barsj_) != self.getlenbarvarj((j_)): raise ValueError("Array argument barsj is not long enough: Is %d, expected %d" % (len(barsj_),self.getlenbarvarj((j_)))) ...
Computes the (exact or approximate) Wasserstein distance of order 1 or 2 between empirical distributions
def wass_distance(X, Y, order=2, type='exact'): if order == 2: M = ot.dist(X, Y) elif order == 1: M = ot.dist(X, Y, metric='euclidean') else: raise Exception("Order should be 1 or 2.") a = np.ones((X.shape[0],))/X.shape[0] b = np.ones((Y.shape[0],))/Y.shape[0] if type == ...
Return a list of (name, arguments, return type) for all function definition2 found in code. Arguments are returned as [(type, name), ...].
def find_functions(code): regex = "^\s*" + re_func_decl + "\s*{" funcs = [] while True: m = re.search(regex, code, re.M) if m is None: return funcs rtype, name, args = m.groups()[:3] if args == 'void' or args.strip() == '': args = [] ...
Set power as voltamps. If passed as a complex insulation_code no checking or manipulation of the insulation_code is completed. The existing insulation_code of self._pwr is overwritten.
def s(self, s: ComType): self._pwr = s
Return whether an image needs pushing
def image_needs_pushing(image): d = docker_client() try: d.images.get_registry_data(image) except docker.errors.APIError: # image not found on registry, needs pushing return True else: return False
Setter method for priority, mapped from YANG variable /input/LocatorRecord/priority (uint8)
def _set_priority(self, v, load=False): try: t = YANGDynClass(v,base=np.uint8, is_leaf=True, yang_name="priority", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True) except (TypeError, ValueError): raise ValueError("""priority must be of a type compatible w...
Tests that an authenticated context (with is_admin set to False) can share an image it owns, even if it is not shared with it.
def test_auth_sharable_owned(self): self.do_sharable(True, 'pattieblack', None, tenant='pattieblack')
Prints an error message to stderr for BuildErrors.
def handle_build_error(error): sys.stderr.write('Error running command `%s`. Returned %s.\n' % ( ' '.join(error.argv), str(error.error_code)))
Blit all the high score related text to the screen
def show_scores(self): for text in self.score_text: text.draw()
take anything, return nothing
def zero(*_, **__) -> None: return
return when was the last update. Once again this is used in the scraper to determine newly updated data.
def dt_last_update(self): return self.last_update
Return contacts metadata for a dataproduct.
def dataproduct_contacts(self, ows_layer, session): # collect contacts for layer and related GDI resources gdi_oids = [ows_layer.gdi_oid] if ows_layer.type == 'data': # include data source gdi_oids.append( ows_layer.data_set_view.data_set.gdi_oid_data_sour...
Main driver, parse the feed and output the JSON list of sources
def main(): handler = PlanetSourceHandler() parser = xml.sax.make_parser() parser.setFeature(xml.sax.handler.feature_namespaces, 1) parser.setContentHandler(handler) parser.parse(sys.stdin) print simplejson.JSONEncoder(indent=True).encode(handler.sources)
Execute the workflow of pyRiverBed.
def main(): print_banner() params = read_steering() s, x, y, cur, theta = build_kinoshita() s, x, y, cur, theta = read_centerline(s, x, y, cur, theta) s, x, y, cur, theta = extend_centerline(s, x, y, cur, theta) for t in range(TSTEPS+1): cur, theta = tan2curv(s, x, y) cur_ori = n...
Allow to scroll through the raw data of the csv file selected
def see_raw_data(city): while True: try: see_raw_data_input = input('\nIn addition of the stats above, would you like to scroll through the raw data? (y/n)\n') if see_raw_data_input not in ('y', 'n'): raise Exception ('Invalid answer') if see_raw_data_inp...
Shuffle a list by partition into n piles.
def pile_shuffle(array, n): result = [] for i in reversed(range(n)): result += array[i::n] return result
Goes through the first column of input table and returns the first sequence of dates it finds.
def get_dates(raw_table) -> "list of dates": dates = [] found_first = False for i, dstr in enumerate([raw_table[i][0] for i in range(0, len(raw_table))]): if dstr: if len(dstr.split("/")) == 3: d = datetime.datetime.strptime(dstr, '%m/%d/%Y') ...
For each point on the image (image_height x image_width) returns the sigma associated with each point due to the offset from the fovea of the image. The average of all the sigmas may be used as an approximation to the full set of all sigmas. Each sigma is used as the basis for creating the J operator which is the weigh...
def get_sigma_map(start_x = 0,field_height=100,field_width=100,viewing_distance=12.0,screen_pixel_size=0.282,debug=False): start_x_pixels = np.round(get_pixels_at_degrees(degrees=start_x,viewing_distance=viewing_distance,screen_pixel_size=screen_pixel_size)) optical_nodal_distance = 17.0 # mm from lens to fovea...
Initialize the weights of a Pytorch module.
def init_weights(m: Union[torch.nn.Conv3d, torch.nn.BatchNorm3d]) -> None: import torch if isinstance(m, torch.nn.Conv3d): torch.nn.init.normal_(m.weight, 0, 0.01) elif isinstance(m, torch.nn.BatchNorm3d): torch.nn.init.constant_(m.weight, 1) torch.nn.init.constant_(m.bias, 0)
Validate the public key if it is related to the given EC curve and formats the public key to a uncompressed byte string. Afterwards the function create a hash value of the uncompressed public key value
def get_public_key_fingerprint(curve: object, temp_public_key: object) \ -> object: vk = VerifyingKey.from_string(bytes.fromhex(temp_public_key), curve=curve) uncompressed_pub_key = vk.to_string('uncompressed') pub_key_hash_fingerprint = hashlib.sha256(uncompressed_pub_key) return pub_key_ha...
Returns cosine similarity between the input question and our dataset questions
def get_cosine_similarity(self, query: list): question_vector = self.get_vector(query) return cosine_similarity(question_vector, self.vectors).flatten()
Updates a Deployment Manager. [Arguments]
def fusion_api_update_deployment_manager(self, body=None, uri=None, api=None, headers=None): return self.dep_mgr.update(body=body, uri=uri, api=api, headers=headers)
replace the accented char to unicode
def replace_accented(input_str): nkfd_form = unicodedata.normalize('NFKD', input_str) return u"".join([c for c in nkfd_form if not unicodedata.combining(c)])
Returns a string of the query last executed by the given cursor, with placeholders replaced with actual values. `sql` is the raw query containing placeholders, and `params` is the sequence of parameters. These are used by default, but this method exists for database backends to provide a better implementation according...
def last_executed_query(self, cursor, sql, params): return super(DatabaseOperations, self).last_executed_query(cursor, cursor.last_sql, cursor.last_params)
Convert list literal to function call.
def visit_List(self, node): self.generic_visit(node) if isinstance(node.ctx, ast.Load): return to_call(to_attribute(self.operator, '__list__'), node.elts) return node
The color of this turtle. All subsequent draw commands (forward/back) draw using this color. If the color changes, it only affects future draw commands, not past ones.
def color(self): return self._color
Determines if a line is horizontal.
def is_horizontal(line:tuple)->bool: return line[0][1] == line[1][1]
r""" Computes the gradient of conv2d with respect to the weight of the convolution.
def conv2d_weight(input, weight_size, grad_output, stride=1, padding=0, dilation=1, groups=1): stride = _pair(stride) padding = _pair(padding) dilation = _pair(dilation) in_channels = input.shape[1] out_channels = grad_output.shape[1] min_batch = input.shape[0] grad_output = grad_output.con...
Creates a new RuntimeConfig resource. The configuration name must be unique within project.
def CreateConfig(self, request, context): context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!')
options object is global
def run( theNetwork ): # set up and run the simulation #cell_input = make_input_dict( theNetwork ) soln = run_simulation( theNetwork, options.tfinal ) # if necessary, move tmp time series to proper file # should always have a /var/tmp folder, right?? # TEMP = '/data/j...
__init__ is used to establish baseline of calss for each instantiation
def __init__(self): self.items = []
Get distribution for atoms.
def dist(self, x: torch.Tensor) -> torch.Tensor: feature = self.feature_layer(x) adv_hid = F.relu(self.advantage_hidden_layer(feature)) val_hid = F.relu(self.value_hidden_layer(feature)) advantage = self.advantage_layer(adv_hid).view( -1, self.out_dim, self.atom_size...
Very unlikely case; can happen only in case of divergence of clocks between local and remote (which is simulated in this test).
def test_reset_to_remote_after_rebase(self) -> None: ( self.repo_sandbox .new_branch("branch-0") .commit() .push() .new_branch("branch-1") .commit() .push() .check_out("branch-0") .commit() ) ...
This is a method to make the color segmentation of the image called 'fachada1.png', the segmentation will be using six different trackbars two per channel (H,S,V).
def color_segmentation(self): cv.namedWindow("Segmentation parameters") self.create_trackbar("h-u", "Segmentation parameters") self.create_trackbar("h-l","Segmentation parameters") self.create_trackbar("s-u","Segmentation parameters") self.create_trackbar("s-l","Segmentation para...
Ensure class methods' signatures.
def test_class_method() -> None: assert inspect.signature(lmp.tknzr._bpe.BPETknzr.add_CLI_args) == inspect.signature(BaseTknzr.add_CLI_args)
Returns the most recent transactions by members of government
def get_government_trading(gov_type: str, ticker: str = "") -> pd.DataFrame: if gov_type == "congress": if ticker: url = ( f"https://api.quiverquant.com/beta/historical/congresstrading/{ticker}" ) else: url = "https://api.quiverquant.com/beta/live...
Appends a number of variables to the optimization task. appendvars(self,num_)
def appendvars(self,num_): res = __library__.MSK_XX_appendvars(self.__nativep,num_) if res != 0: _,msg = self.__getlasterror(res) raise Error(rescode(res),msg)
Plot transparent fem result on highres srt hillshade with summit and stations, etc comp=0,1,2,3 > ux, uy, uz, ur
def uturuncu_map(surfaceFile,dem,comp=2): fig = plt.figure() ax = fig.add_subplot(111) #print(datadir) #print(dem) geosurface = pu.surface2geotiff(dem,surfaceFile,outname=None,comp=comp,nanval=-9999) #load georeferenced fem output from pu.surface2geotiff #geosurface = '/home/scott/research...
Get all hosts for fanout from nameserver by target.
def get_hosts_fanout(self, target, listener_type):
Mimic the & operator in R. This has to have Expression objects to be involved to work
def _op_and_(self, left: Any, right: Any) -> Any: if isinstance(left, list): # induce an intersect with Collection return Intersect(left, right) left, right = _recycle_left_right(left, right) left = Series(left).fillna(False) right = Series(right).fillna(False) ...
Function that builds the DenseNet121 architecture
def densenet121(growth_rate=32, compression=1.0): init = K.initializers.he_normal(seed=None) X = K.Input(shape=(224, 224, 3)) batch_1 = K.layers.BatchNormalization()(X) activation_1 = K.layers.Activation('relu')(batch_1) conv_1 = K.layers.Conv2D(filters=64, kernel_siz...
Compile the .qrc (Qt Designer resource files) into .py files.
def compile_resources(resourcename="images", location="."): res_count_ok = 0 res_count_ko = 0 for qrc_file in os.listdir(location): # Loop through directory if qrc_file.endswith(".qrc"): # We have a candidate file print(f"---> Found {qrc_file}") # get the...
Get next release version.
def bump_release( self: _R, release_type: Literal["major", "minor", "micro"] = VersionParts.MICRO, inc: int = 1, ) -> _R: if release_type == VersionParts.MAJOR: return self.bump_major(inc) if release_type == VersionParts.MINOR: return self.bump_minor(i...
Try to move 1 customer to anywhere it can be put, and see if the move can cut the total cost.
def shift_1_cust(self, sol_in1, cust, c_loc, curr_temp, sol_type1, sa_lns): route_ing = copy.deepcopy(sol_in1[c_loc[0]]) route_new = route_ing move_to_route = c_loc[0] orgn_type1 = sol_type1[c_loc[0]] origin_cost1 = check_violation(route_ing, orgn_type1)[1] route_...
Compare the list of groups between two appliances
def compare(isamAppliance1, isamAppliance2): ret_obj1 = get_all(isamAppliance1) ret_obj2 = get_all(isamAppliance2) return ibmsecurity.utilities.tools.json_compare(ret_obj1, ret_obj2)
Convert binary string to decimal number.
def bin2dec(x): return int(x, 2)
Return the parsed contents of the config file.
def get_config(): return json.loads(CONFIG_FILE.read_text())
log Normal, NormalinverseWishart marginal likelihood
def niw_ml(X, lambda_0, mu_0, kappa_0, nu_0, Z_0): X = __check_2d_and_reshape(X) ml = lgniwml(X, mu_0, lambda_0, kappa_0, nu_0, Z_0) return ml
split IOB2format tag on iobprefix and tag assert if default tag('O') is not allowed default tag assert if iobprefix not in allowed prefixes assert if tag not in allowed tags
def split_tag(elem, tags): splited_tag = elem.split(TAG_SEP) if len(splited_tag) > 1: tag_prefix, tag = splited_tag assert tag in tags.tags assert tag_prefix in tags.iob else: tag = elem tag_prefix = None assert tag == tags.default return tag_prefix, tag
This function tests for bad x value with sets
def test_badxvaluewithsets(self): Rectangle.reset_objects() with self.assertRaises(TypeError) as e: r1 = Square(1, {1, 2, 3}, 2, 3) self.assertEqual(str(e.exception), 'x must be an integer')
List all tilesets for an account. By default the response is a simple list of tileset IDs. If you would like an array of all tileset's information, use the versbose flag. tilests list
def list(username, verbose, token=None, indent=None): mapbox_api = _get_api() mapbox_token = _get_token(token) url = "{0}/tilesets/v1/{1}?access_token={2}".format( mapbox_api, username, mapbox_token ) r = requests.get(url) if r.status_code == 200: if verbose: for tile...
gets the number of runnning transcription processes
def numRunningProcesses(): try: proc = subprocess.run("ps -Af|grep -i \"online2-wav-nnet3-latgen-faster\"", stdout=subprocess.PIPE, shell=True) np = (len(str(proc.stdout).split("\\n")) - 3) if(np == None): np = 0 return np except Exception ...
Adds the commit to the commits array if it doesn't already exist, and returns the commit's index in the array.
def add_commit(self, commit): sha1 = commit.hex if sha1 in self._commits: return self._commits[sha1] title, separator, body = commit.message.partition("\n") commit = { 'explored': False, 'sha1': sha1, 'name': GitUtils.abbreviate_sha1(sha1),...
Prepare session; attempts database connection, verify provided credentials and validate.
def prepare_session(self, writer, session): # Get information about the CLIENT session['client']['ip'], port = writer.get_extra_info('peername') # Try Database connection try: self.connect_database(session) except DbException as err: LOG.debug('Could not p...
Generate an LR(1) state table
def generateStateTable(C, ruleSet, terminals, indexFunc): #initialize the state dictionary stateDict = {} for i in range(len(C)): stateDict[i] = {} gotoDict = {} for i in range(len(C)): gotoDict[i] = {} #compute the states for state in range(len(C)): for item in...
Return 'pathname' with 'new_root' prepended. If 'pathname' is relative, this is equivalent to "os.path.join(new_root,pathname)". Otherwise, it requires making 'pathname' relative and then joining the two, which is tricky on DOS/Windows and Mac OS.
def change_root(new_root, pathname): if os.name == 'posix': if not os.path.isabs(pathname): return os.path.join(new_root, pathname) else: return os.path.join(new_root, pathname[1:]) elif os.name == 'nt': (drive, path) = os.path.splitdrive(pathname) if pat...
gets to resource name attached to a domain name
def get_dns_resource_for_domain_name(session, domain_name, dns_resource, hosted_zone): if session is None: return None client = session.client('route53') hosted_zone_id = get_hosted_zone_id(session, hosted_zone) if hosted_zone_id is None: print("Error: Unable to find Route 53 Hosted Zo...
Drop these calculated rates because they don't provide any information. If you want these, you can just use a view.
def drop_calculated_rates(df): if not _all_na_or_values(df["so2_rate_measure_flg"], {"Calculated"}): raise AssertionError() if not _all_na_or_values(df["co2_rate_measure_flg"], {"Calculated"}): raise AssertionError() del df["so2_rate_measure_flg"], df["so2_rate_lbs_mmbtu"] del df["co2_...
Projection onto the nonnegative reals (negatives set to zero).
def prox(self, x, lmbda=1): return proj_nneg(x)
Check if a combination of statistics in one class is equally distributed to any combination of statistics in the other class, up to a max length.
def jointly_transformed_equally_distributed( class1: Av, class2: Av, n: int = 6, dim: int = 2 ) -> Iterator[Tuple[Tuple[str, ...], Tuple[str, ...]]]: return ( (tuple(stat[0] for stat in stats1), tuple(stat[0] for stat in stats2)) for stats1, stats2 in combinations( ...
Simulates a smooth mouse drag
def drag(source, dest, speed=1000): m = PyMouse() m.press(*source) time.sleep(0.1) # number of intermediate movements to make for our given speed npoints = int(sqrt((dest[0]-source[0])**2 + (dest[1]-source[1])**2 ) / (speed/1000)) for i in range(npoints): x = int(source[0] + ((dest[0]-...
Convert two dimensional index to 1d.
def one_dim_index(self, i, j): return int(i + j * self.nx)
A posteriori SNR estimate.
def gamma_hat(self, xi_gamma_bar_hat): _, gamma_bar_hat = tf.split(xi_gamma_bar_hat, num_or_size_splits=2, axis=-1) gamma_hat = self.gamma_map.inverse(gamma_bar_hat) return gamma_hat