anchor
stringlengths
10
14.3k
positive
stringlengths
10
14.9k
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)
Test user's dict is empty at first
def dtype(self): return self.config["dtype"]
The data type of the master array.
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
Convert a pygame surface into a cv image
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]
Load QA data from night objects on disk
def saveClassroomData(): with open("ClassRoomData.txt","wb") as classroomData: pickle.dump(classroomEntities,classroomData)
saves classroomEntities in the ClassRoomData file
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() ...
Wrapper for reference pixel calculation
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)) ...
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 reset_obstacles(self): self.obstacles = np.array([])
Reset the obstacles' positions within the map (should be called when map is refreshed to clean the array)
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()...
Should render to the console using a write_source function call on the internal step report's stdout_interceptor.
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
generates and returns overlap graph from .paf files
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" ] ...
Generate seed for the MFA TOTP device.
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...
Add a session to the user's wishlist, returning a boolean.
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))
Return the Hamming distance between equallength sequences
def pre_installation(self): pass
Called before anything else, i.e. just after installer controller creation. Return value is ignored.
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
Get the center of the projection.
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...
returns output of new layer
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)
Check {sysproid}.{appname}.{cell} is running.
def test_for_template(self): self.assertTemplateUsed(self.response, 'my_info_template.html')
Test for template correctness
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", "")
Setup authorization for whole API. Can be redefined for an endpoint. OpenAPI Authorization Specs
def RestoreDatabase(self, database, backupfile, arguments, result): self.RunProgram("\""+self.__context["gbak_path"]+"\"", [ self.__context["gbak_path"] ] + [ "-C ", backupfile ] + arguments + [ database ], "", self.__context, result)
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 get_epoch(timestamp): timestamp_dt = datetime.datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%SZ") epoch = calendar.timegm(timestamp_dt.timetuple()) return epoch
Converts Strava datetime to epoch timestamp
def roundUP(x): return int(ceil(x / 10.0)) * 10
Rounding up to next 10th
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...
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 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_...
Performs a standard classification test with the given classifier.
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...
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 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()
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 authorizes(self, user): return self.owner == user or self.workers.filter(pk=user.id).exists()
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 description(self) -> pulumi.Output[str]: return pulumi.get(self, "description")
A humanreadable description of the new Role.
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)
Calculates the solar elevation angle for a specific time.
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...
Tests that stock and price fields must be numbers
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, {})
after _send_celery_mail finishes, the tenant should be cleared again
def args(self): return self._parse_args
The arguments into which the python args and kwargs are collected
def itkTernaryAddImageFilterIUL2IUL2IUL2IUL2_cast(*args): return _itkTernaryAddImageFilterPython.itkTernaryAddImageFilterIUL2IUL2IUL2IUL2_cast(*args)
itkTernaryAddImageFilterIUL2IUL2IUL2IUL2_cast(itkLightObject obj) > itkTernaryAddImageFilterIUL2IUL2IUL2IUL2
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()
Poll tests for completion. When one finishes, start another one if there are more to run. Stop when all are finished.
def _get(self, *args, **kwargs): return self._request('get', *args, **kwargs)
Wrapper for requests GET method
def is_active(self): return self.active
DEPERECIATED FUNCTION PLEASE USE active field of subscription
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) ...
Used to allow a user to edit their own profile.
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_)))) ...
Sets the dual solution for a semidefinite variable. putbarsj(self,whichsol_,j_,barsj_)
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 == ...
Computes the (exact or approximate) Wasserstein distance of order 1 or 2 between empirical distributions
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 = [] ...
Return a list of (name, arguments, return type) for all function definition2 found in code. Arguments are returned as [(type, name), ...].
def s(self, s: ComType): self._pwr = s
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 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
Return whether an image needs pushing
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...
Setter method for priority, mapped from YANG variable /input/LocatorRecord/priority (uint8)
def test_auth_sharable_owned(self): self.do_sharable(True, 'pattieblack', None, tenant='pattieblack')
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 handle_build_error(error): sys.stderr.write('Error running command `%s`. Returned %s.\n' % ( ' '.join(error.argv), str(error.error_code)))
Prints an error message to stderr for BuildErrors.
def show_scores(self): for text in self.score_text: text.draw()
Blit all the high score related text to the screen
def zero(*_, **__) -> None: return
take anything, return nothing
def dt_last_update(self): return self.last_update
return when was the last update. Once again this is used in the scraper to determine newly updated data.
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...
Return contacts metadata for a dataproduct.
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)
Main driver, parse the feed and output the JSON list of sources
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...
Execute the workflow of pyRiverBed.
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...
Allow to scroll through the raw data of the csv file selected
def pile_shuffle(array, n): result = [] for i in reversed(range(n)): result += array[i::n] return result
Shuffle a list by partition into n piles.
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') ...
Goes through the first column of input table and returns the first sequence of dates it finds.
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...
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 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)
Initialize the weights of a Pytorch module.
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...
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_cosine_similarity(self, query: list): question_vector = self.get_vector(query) return cosine_similarity(question_vector, self.vectors).flatten()
Returns cosine similarity between the input question and our dataset questions
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)
Updates a Deployment Manager. [Arguments]
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)])
replace the accented char to unicode
def last_executed_query(self, cursor, sql, params): return super(DatabaseOperations, self).last_executed_query(cursor, cursor.last_sql, cursor.last_params)
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 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
Convert list literal to function call.
def color(self): return self._color
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 is_horizontal(line:tuple)->bool: return line[0][1] == line[1][1]
Determines if a line is horizontal.
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...
r""" Computes the gradient of conv2d with respect to the weight of the convolution.
def CreateConfig(self, request, context): context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!')
Creates a new RuntimeConfig resource. The configuration name must be unique within project.
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...
options object is global
def __init__(self): self.items = []
__init__ is used to establish baseline of calss for each instantiation
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...
Get distribution for atoms.
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() ) ...
Very unlikely case; can happen only in case of divergence of clocks between local and remote (which is simulated in this test).
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...
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 test_class_method() -> None: assert inspect.signature(lmp.tknzr._bpe.BPETknzr.add_CLI_args) == inspect.signature(BaseTknzr.add_CLI_args)
Ensure class methods' signatures.
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...
Returns the most recent transactions by members of government
def appendvars(self,num_): res = __library__.MSK_XX_appendvars(self.__nativep,num_) if res != 0: _,msg = self.__getlasterror(res) raise Error(rescode(res),msg)
Appends a number of variables to the optimization task. appendvars(self,num_)
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...
Plot transparent fem result on highres srt hillshade with summit and stations, etc comp=0,1,2,3 > ux, uy, uz, ur
def get_hosts_fanout(self, target, listener_type):
Get all hosts for fanout from nameserver by target.
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) ...
Mimic the & operator in R. This has to have Expression objects to be involved to work
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...
Function that builds the DenseNet121 architecture
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...
Compile the .qrc (Qt Designer resource files) into .py files.
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...
Get next release version.
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_...
Try to move 1 customer to anywhere it can be put, and see if the move can cut the total cost.
def compare(isamAppliance1, isamAppliance2): ret_obj1 = get_all(isamAppliance1) ret_obj2 = get_all(isamAppliance2) return ibmsecurity.utilities.tools.json_compare(ret_obj1, ret_obj2)
Compare the list of groups between two appliances
def bin2dec(x): return int(x, 2)
Convert binary string to decimal number.
def get_config(): return json.loads(CONFIG_FILE.read_text())
Return the parsed contents of the config file.
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
log Normal, NormalinverseWishart marginal likelihood
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
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 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')
This function tests for bad x value with sets
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...
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 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 ...
gets the number of runnning transcription processes
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),...
Adds the commit to the commits array if it doesn't already exist, and returns the commit's index in the array.
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...
Prepare session; attempts database connection, verify provided credentials and validate.
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...
Generate an LR(1) state table
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...
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 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...
gets to resource name attached to a domain name
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_...
Drop these calculated rates because they don't provide any information. If you want these, you can just use a view.
def prox(self, x, lmbda=1): return proj_nneg(x)
Projection onto the nonnegative reals (negatives set to zero).
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( ...
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 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]-...
Simulates a smooth mouse drag
def one_dim_index(self, i, j): return int(i + j * self.nx)
Convert two dimensional index to 1d.
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
A posteriori SNR estimate.