id
stringlengths
20
20
title
stringclasses
1 value
text
stringlengths
8
768k
00373e7ed28f4641c072
def autocorr(arr): mean = np.ma.mean(arr) std = np.ma.std(arr) nr, nc = np.shape(arr) autocorr = np.zeros((2*nr, 2*nc)) for x in range(-nr, nr): for y in range(-nc, nc): segment = (arr[max(0, x):min(x+nr, nr), max(0, y):min(y+nc, nc)] - mean) \ ...
003751c851f7c2719c32
def run(self): self.set_pipeline() self.pipeline.fit(self.X, self.y)
00376598adb18f8c739d
def _clean_cols(self, iso_table): # Rename Columns iso_table.add_column("logA", iso_table["log10_isochrone_age_yr"][:]) iso_table.add_column("logT", iso_table["log_Teff"][:]) iso_table.add_column("logL", iso_table["log_L"][:]) iso_table.add_column("M_ini", iso_table["initial_mass...
00376ceb7d7d8a523cd9
def show_edit_menu(): print( '1. Reverse\n2. Fast forward\n3. Slow motion\n4. Volume ' 'enhancing\n5. Volume reducing\n6. Low pass filter\n7. End ' 'menu') return input("Please enter your choice: ")
0037734676862a926dc2
def prediction_label(pathname, labels_file, labels_col, preds): df = pd.read_csv(Path(pathname) / labels_file) series = df[labels_col] # labels = [(x, list(series[y])) for x, y in preds] labels = {x: list(series[y]) for x, y in preds} return labels
00377d4f1fcc62b13d9a
def bytes2str(b): return b.decode('utf8').rstrip('\0')
0037abed49e030ed6cd6
def last_updated_at(self) -> Optional[str]: return pulumi.get(self, "last_updated_at")
0037b11198813db8a0cb
def mc_trial(board, player): while board.check_win() == None: next_move = random.choice(board.get_empty_squares()) board.move(next_move[0], next_move[1], player) player = provided.switch_player(player) return
0037d448e2a32b400c85
def load_label(self, idx): label = scipy.io.loadmat('{}/segmentation/img_{}.mat'.format(self.nyud_dir, idx))['segmentation'].astype(np.uint8) label -= 1 # rotate labels label = label[np.newaxis, ...] return label
0037f437430c64d33e2b
def convert_into_image(self, request): im_b64 = request.json["image"] img_bytes = base64.b64decode(im_b64.encode("utf-8")) return Image.open(io.BytesIO(img_bytes))
0037fa2c4ec840805fb2
def text(self): return str()
00382f2651ca50d236d5
def exp(x, base=None): if base is None: return Var(np.exp(x._val), np.exp(x._val)*x._der) else: return Var(np.power(base, x._val), np.power(base, x._val)*np.log(base))
00383c7cefc8a118eeb9
def get_job_name(cpar_path): return os.popen("cat %s | grep jobname | cut -d'\"' -f2 " % cpar_path).read().strip()
0038667fc402df76f278
def interpolation_test(): Lx = 10.0 # size of the box in the x direction Ly = 20.0 # size of the box in the y direction P = 1000 # number of test points # grid size (note: it should not be a square) Mx = 101 My = 201 x = np.linspace(0, Lx, Mx) y = np.linspace(0, Ly, My) # test ...
0038687d5962981bcb8c
def on_mouse_press(self, x, y, button): pass
003888eedfbb0d026dad
def get_block(block_id):
0038aebc887be276d058
def _get_word(self): with open('words.txt') as words: word = next(words) for index, line in enumerate(words, 2): if randrange(index): continue word = line return word.strip()
0038b30258b6943597f0
def add_transaction(self, user): # Check if the user is completely locked out if self.status_locked: print('Cannot add any transaction!! You are locked out of all categories\n') return time = datetime.datetime.now() try: amt = float(input('Enter the...
0038b94e3220041a87e8
def test_convert_seconds_to_time(self): self.assertEqual("4h06m24s", sh.convert_seconds_to_time(14784)) self.assertEqual("10m06s", sh.convert_seconds_to_time(606)) # case timestamp > a day with self.assertRaises(BadArgumentError): sh.convert_seconds_to_time(25 * 60 * 60) ...
0038bfcc9cc20a919f1a
def test_group_by_group_name_get_route_400(self) -> None: response: Response = self.client.get( "/v2/groups/saintsxctf/invalid_group_name", headers={"Authorization": f"Bearer {self.jwt}"}, ) response_json: dict = response.get_json() self.assertEqual(response.statu...
0038dfe8b23d0c50d1f2
def test_merchant_renew_key_4(self, _disable_2type, _delete_merchant): user1.set_2type(tp='0') user1.merchant(method='create', params={'title': 'Title', 'payway': 'visamc'}) admin.params['lid'] = user1.resp_merchant['lid'] admin.set_model(model='merchant', selector={'lid': ['=', str(user...
00390d07bcdc29c0a307
def drop_an_item(item_id): if is_item_in_inventory(item_id, inventory): remove_item_from_inventory(item_id, inventory) return inventory else: print("You cannot drop that")
003910e4c54c03bb5dc4
def plot_superposed_gridded_los(ax, stable_interval=30, filtered_interval=2., coords="mlt", ftype="fitacf", glatc_range=[53, 58], gazmc_range=[-10, 10], gltc_ra...
00391442f5491f704494
def copy_local_directory_to_gcs(local_path, bucket_name, gcs_path): assert os.path.isdir(local_path) storage_client = storage.Client() bucket = storage_client.bucket(bucket_name) for root, dirs, files in os.walk(local_path): for name in files: local_file = os.path.join(root, name) ...
0039258eb787060e0657
def remove(self, product, options=None): key = self._get_product_key(options) cart_product = self._cart.get(str(product.pk)) if cart_product: if cart_product.get(key): del cart_product[key] self.save()
00393ab62bfbfb3244bf
def set_country_info(self, wiki, country, key, value): self.db.execute("INSERT OR REPLACE INTO country_info VALUES (?, ?, ?, ?)", (wiki, country, key, value)) self.db.commit()
00395b7c562e41347515
def plot_heatwave(df, FLAG_HEATWAVE,var_temperature = 'MAX_N_AIRTMP_MED10', var_day = 'NEW_DAY', savefig = None): # Draw horizontal lines fig, ax = plt.subplots(figsize=(16,10), dpi= 80) ax.hlines(y=np.arange(df.YEAR.nunique()), xmin=0, xmax=3000, color='gray', alpha=0.5, linewidth=.5, lin...
00395b95c344f60be4ed
async def get_events(self, url, apiuser, apikey, params=None) -> str: headers = self.get_token(url, apiuser, apikey) r = requests.get(f"https://{url}/api/2.0/events/?{params}", headers=headers) if r.status_code != 200: raise RuntimeError('Alienvault API return an error') ...
00397cf138aa78f9a418
def get_capacities(self) -> Dict: # Make the request. content = self.power_bi_session.make_request( method='get', endpoint='myorg/capacities' ) return content
0039c63cede8f0e97eec
def voxelize_subdivide(mesh, pitch, max_iter=10, edge_factor=2.0): max_edge = pitch / edge_factor if max_iter is None: longest_edge = np.linalg.norm(mesh.vertices[mesh.edges[:, 0]] - mesh.vertices...
0039e33b3bdd4fc13940
def group_by_interval(input_array,group_interval,output_list=None): array=input_array.copy() boolen_list=[] for i in range(len(group_interval)-1): if i < i == len(group_interval)-2: try: boolen_list.append(np.logical_and(np.logical_and(array>=group_interval[i], array<grou...
003a06c870681b973593
def main(): saludo() menu()
003a35b3f9c5f7d67e62
def validate(self): if self._gevent: results = [gevent.spawn(check) for check in self.checks] gevent.joinall(results, timeout=7) for result in results: if result.value: self.errors += result.value else: for result in [c...
003a41ab9787ded415cc
def passphrase_requirements() -> Dict[str, Any]: return {"is_optional": True, "min_length": MIN_PASSPHRASE_LEN} # lgtm [py/clear-text-logging-sensitive-data]
003a4f8345d6e765b4ea
def apply_style(self, tags): master_style = {} element_list = [] for tag_name, attrs in tags: style = {} # Style for this tag element_list.append(tag_name) if tag_name == 'font': color = attrs.get("color") face = attrs....
003a80dc235212605a5a
def new_client(options=None): if options is None: options = get_config().options['daemon'] client = socket() client.connect((options.listen, options.port)) return client
003a86535d0cdb8938f0
def reuse_worker(self): return False
003abd264d539fc46e44
def set_ghost_cells(self, data_all: np.ndarray, *, args=None) -> None: # calculate necessary constants data = self.get_virtual_point_data() # prepare the array of slices to index bcs offset = data_all.ndim - self.grid.num_axes # additional data axes idx_offset = [slice(None)] *...
003adc0592184cce9f17
def test_get_serializer_class(self): read_only = User.objects.create_user('public', 'public@public.com', 'public') view = DriverRecordSchemaViewSet() mock_req = mock.Mock(spec=Request) mock_req.user = read_only view.request = mock_req serializer_class = view.get_serialize...
003af3282cb1d7926b6b
def warn(msg): sys.stderr.write('%s: warning: %s\n' % (me, msg))
003b08b491a23288a1a2
def print_confusion_matrix(confusion_matrix, class_names, names, figsize=(10, 7), fontsize=14): df_cm = pd.DataFrame( confusion_matrix#, index=class_names, columns=class_names, ) df_cm = df_cm.fillna(0).astype(int) fig = plt.figure(figsize=figsize) try: heatmap = sns.heatmap(df_cm, annot=True, fmt="d"...
003b111f34ddc069ebe0
def html_calendar(self, request): tz = request.client.db.getUserTimezone() current_date = date.Date(".").local(tz) date_str = request.form.getfirst("date", current_date) display = request.form.getfirst("display", date_str) template = request.form.getfirst("@template", "calend...
003b6428813f968a3643
def test_se_bracket_balanced_retorna_false_com_lista_vazio(self): bracket = [""] self.assertEqual(bracket_balanced(bracket), False)
003b78baa907a97055cf
def check_move(self, pos: int) -> bool: return self._board[pos] == Tr.E
003b8731ae4d09fa5693
def server_normalize(): require('config', provided_by=[production, staging, dev, developer]) require('hosts', provided_by=[www, database, resque, balancer]) print("Normalize server ...") provider = env.config.get('provider') print("Loading normalize() from providers.%s" % provider) if not(provid...
003b91b829fa23b7c060
def write(self,filename,plotonly=False): with open(filename,'w') as f: if (plotonly): """an empyt block for inputpp is mandatory in QE if you only want to plot results from data""" f.write('&inputpp \n/\n') f.write(str(self))
003b9ac5b4518881bb0b
def add_weights_to_average(average, weights): for feature in weights: weights_feature = weights[feature] for tag in weights[feature]: if feature not in average: average[feature] = {} average_feature = average[feature] average_feature[tag] = average_feature.get(tag, 0) + weights_feature[tag]
003b9f4368d2a8e54efd
def _build_children(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None): super(Codelist, self)._build_children(child_, node, nodeName_, fromsubclass_, gds_collector_) if nodeName_ == 'Code': obj_ = Co...
003bb1b6214b8dad8dd4
def as_sql(self, *args, **kwargs): queries = [ (append_caller_to_sql(sql), params) for sql, params in super().as_sql(*args, **kwargs) ] return queries
003bcc87053a19122727
def test_fetch_exception_during_request_get_no_raise_on_failure(caplog): caplog.set_level(logging.WARNING) url = "https://www.example.com" r = LinkContentFetcher() with patch("haystack.nodes.retriever.link_content.requests.get", side_effect=requests.RequestException()): r.fetch(url=url) ass...
003bd757f65ce096f98d
def set_view_offset(x: Union[float, int], y: Union[float, int]) -> None: pass
003bf515147d3ddf5e5a
def encodeFloat(val): pass
003c0c85d8418bb89663
def read_lines(filename="", nb_lines=0): with open(filename, encoding='utf-8', mode='r') as file: size = sum(1 for line in file) file.seek(0) if nb_lines <= 0 or nb_lines >= size: print(file.read(), end='') else: for i in range(nb_lines): print...
003c19347c2e625ff745
def bind_extracted_variables(self, variables): for variable_name, value in variables.items(): self.testset_shared_variables_mapping[variable_name] = value self.bind_testcase_variable(variable_name, value)
003c3a2b78cb74e9d89b
def run_jobs(joblist, outlog): jobcase = '' if joblist == []: sg.PopupOK('No Jobs In Queue', no_titlebar=True, grab_anywhere=True, keep_on_top=True) return() jobnum = 0 layout1 = [[sg.Text('Select the Run Option for All ' + str(len(joblist)) + ' Cases in Queue?' )], [s...
003c4afbc487b5852702
def _var_beta_raw(self): x = self._x_trans y = self._y_trans dates = self._index nobs = self._nobs rmse = self._rmse_raw beta = self._beta_raw df = self._df_raw window = self._window cum_xx = self._cum_xx(self._x) results = [] for ...
003c5842498608a26ed3
def transfer_function(self): return self._transfer_function
003c5f6a101dcb4854d3
def get_initState(self): _d = {} _d['firm_position'] = [self.getPosFirme(i) for i in range(self.firmes)] _d['cons_preference'] = _0 = {} for i in range(self.__area): _1 = self.getConsommateur(i) if _1 is None: continue _0...
003c65a396376646bfa5
def acknowledgment(self, **kwargs: str) -> None: # date = kwargs.get("date", "") # account = kwargs.get("account", "") amount = kwargs.get("amount", "") payee = kwargs.get("payee", "") sql = """ SELECT t.id, t.account_id, t.destination_id, t.cleared_on, t.amount, ...
003c89364e78351edd4a
def test_pep8_conformance_pep8test(self): pep8style = pep8.StyleGuide(quiet=False) result = pep8style.check_files(['tests/test_pep8.py']) self.assertEqual(result.total_errors, 0, "Found code style errors (and warnings).")
003c90a4e19a571ac885
def get_color_map(old_colors, new_colors): color_map = {} print("########### BUILDING COLOR MAP ###########") print("Num olds: " + str(len(old_colors))) print("Old colors: " + str(old_colors)) print("Num news: " + str(len(new_colors))) max_colors = len(old_colors) for i in range(0, max_col...
003cb3ca66a4e4683850
def get_sources(self): self.sources = [] cur = self.app.conn.cursor() cur.execute("SELECT id, name, fulltext, mediapath, ifnull(memo,''), owner, date FROM source") results = cur.fetchall() for r in results: guid = self.create_guid() suffix = "txt" ...
003cd7af5415e6cfe58c
def on_turn(self, turn_state): game_state = gamelib.GameState(self.config, turn_state) gamelib.debug_write( "Performing turn {} of your custom algo strategy".format( game_state.turn_number ) ) # Comment or remove this line to enable warnings. ...
003d3cee5180d72bfbee
def test_defaults(): model = torch.nn.Module() dataset = torch.utils.data.Dataset() dataloader = torch.utils.data.DataLoader(dataset) loaders = OrderedDict() loaders["train"] = dataloader state_kwargs = { "discriminator_train_phase": "discriminator_train", "discriminator_train_nu...
003d679c413488d63b0c
def heartbeat_request(self, request, context): context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!')
003d745b22b7ff941230
def main_add(ctx, # type: click.Context options, # type: Dict[str, Any] build, # type: bool editable, # type: Iterable[str] tag, # type: Iterable[str] install, ...
003d7cef44db22a1f8b9
def getRandom(self): return random.randint(0, 4)
003d855dc5cddd0b7730
def screenSize(self):
003d90a5a6f4d4aa525f
def onClientConnect(self, webSock): raise NotImplementedError("onClientConnect not implemented")
003d9e18a1ccd521cd4c
def generate_freecad_trajectory(self): doc = FreeCAD.activeDocument() traj = doc.addObject("Robot::TrajectoryObject","Trajectory").Trajectory frame_curr = Pose() for target in self._path: command = target[0] if command == 'target': pose = frame_cur...
003da271843a887cde93
def params(): c = 5e1 # constant tunes duration of infection params = { 't_0':0, # h - Initial time value 't_f':1, # h - Final time value 't_den':1e-2, # h - Size of time step to evaluate with 'rW':1*c, # cells/t - Specific growth rate WT 'rR':1*c,...
003daa6383107037cc4e
def draw_houghlines(img, lines): def calc_line(img, r, t): a = np.cos(t) b = np.sin(t) x0 = a*r y0 = b*r x1 = int(x0 + 1000*(-b)) y1 = int(y0 + 1000*(a)) x2 = int(x0 - 1000*(-b)) y2 = int(y0 - 1000*(a)) cv2.line(img,(x1,y1),(x2,y2),(0,0,255),5)...
003dc9e1f745f2d308ef
def is_translationproject(self): return (self.pootle_path.count('/') == 3 and not self.pootle_path.startswith('/projects/'))
003dcf152567b21d0108
def gradientFunction(theta, X, y): m = len(y) # number of training examples n = len(X[0]) # ====================== YOUR CODE HERE ====================== # Instructions: Compute the gradient of a particular choice of theta. # Compute the partial derivatives and set grad to the partial # ...
003dd9f5fbf32931cc48
def record_raw(self, content): np.savetxt(self.file_name,content,fmt='%.5f') # %.5f specifies 5 decimal round f = open(self.file_name) if f.close == False: f.close() for clearline in range(1,10): print('\n') print "\nData has been recorded and saved in: " + str(se...
003de65fb2da805fe8cc
def __init__(self, raw_data): d1 = raw_data df_list = [pd.DataFrame(d1[key]) for key in d1.keys()] df = pd.concat(df_list) df['keen.created_at'] = pd.to_datetime(df['keen.created_at']) #remove duplicates df = df.sort_values('keen.created_at') df_non_duplicated = ...
003decefcfb024f36f27
def _get_value_str(value: Any, arguments: Sequence[str], index: int = 0) -> str: if arguments and len(arguments) > index: return f'{arguments[index]}={value}' return f'{value}'
003df6e8bca314af6940
def run_command(command): print("Running:", command) # print command to run code = os.system(command) # run command print("\"%s\" returned with code: %d\n" % (command, code))
003dfa8a38bc91a075ed
def mag_to_flux(mag,magerr,wavelength): F_Lxlambda2 = 10**(-(mag+2.406)/2.5) flux = F_Lxlambda2/wavelength**2 if magerr is None: return flux dflux = np.abs(flux*(-magerr/2.5*np.log(10))) # df/f = dcount/count return flux,dflux
003e152f01d9a2940e4c
def test_default(self): labels = [[2.0, 1.0, 0.0]] ranks = [[1, 2, 3]] scale = 3. lambda_weight = losses_impl.DCGLambdaWeightV2() self.assertAllClose( lambda_weight.pair_weights(labels, ranks) / scale, [[ [0., 1. / 2., 2. * 1. / 6.], [1. / 2., 0., 1. / 2.], ...
003e2e5293347e700097
def logout(self, request): response_with_cookie = response.Ok( { 'data': 'success' } ) response_with_cookie.set_cookie( key='token', value='', samesite='Strict', httponly=True, secure=not settings.DEBUG) return response_with_cookie
003e31d5d7b83ac031fe
def start(self): pcms = alsaaudio.pcms() mixers = alsaaudio.mixers() ...
003e325af9d6eb778d6b
def load_index(self, annoy_dir: str = None): if not annoy_dir: annoy_dir = curr_dir self.annoy_title.load(os.path.join( annoy_dir, f'{self.encoder_model}_title.ann')) self.annoy_article.load(os.path.join( annoy_dir, f'{self.encoder_model}_article.ann')) ...
003e34cbe664011e9fac
def moment(self): return np.zeros(3)
003e35c9ef3dd2caa7d5
def media(self): return []
003e35f16b653e82cf6f
def flip_card(self, card, audio=True): self.current_anims[card.id] = [0, card] if audio: self.flip_sound.play()
003e3e0f0291eae694f5
def set_text_size(self, size): self.text_size = size
003e864163bdcc2f503c
def delete_file(self, path): self.log.debug("MongoContents.GenericManager: delete_file '%s'", path) if self.file_exists(path): self.fs.rm(path,type="file") elif self.dir_exists(path): self.fs.rm(path,type="dir") else: self.no_such_entity(path)
003e88a8b2021819d6d2
def find_all(self, **kwargs): objs = self._list_method(**kwargs)[self.NAME + 's'] return objs
003ea57527145f0fa698
def train_loop(self, epoch): # Set loop counter for the epoch loop = tqdm(self.dloader.train_loader, dynamic_ncols=True) # Loop over all samples in the train set for batch_id, data in enumerate(loop): loop.set_description(f"Epoch {epoch}") # Prepare the batch ...
003eb10c6701a75ad9dd
def fumble_return_touchdowns(self, fumble_return_touchdowns): self._fumble_return_touchdowns = fumble_return_touchdowns
003eb1bb6946765b36f1
def name() -> str: return f'{TestingStack.global_prefix()}TestingStack'
003ec237807845e7c2b4
def link_arn(self) -> pulumi.Output[str]: return pulumi.get(self, "link_arn")
003ec98605a2ca318b91
def build_network(self): # Create output neurons for ii in range(self.output_size): label = self.output_labels[ii] self.g_dict[self.node_id] = { 'type': 'output', 'label': label, 'connections': None, 'function': Ac...
003edd05acb94d0931a1
async def mpub(self, topic: str, *messages: Any) -> TCPResponse: validate_topic_channel_name(topic) return await self.execute( NSQCommands.MPUB, topic, data=messages if len(messages) > 1 else messages[0], )
003ee3dc2773970f9998
def temporalIndexRange(self): return sliceToXRange(self.imgSlices[0], self.origShape[0])
003f0d52883a68ace5e4
def displayProject(project_name: str, print_active=False) -> None: if not os.path.exists(f'{c.TTN_CONFIG_DIR}/projects.db'): logging.info('ttn not initialized ! Run ttn init before trying ' 'this command') return with open(f'{c.TTN_CONFIG_DIR}/projects.db', 'r') as f: ...
003f0ec24e2461f916a7
def prepare_data(self): print("Le jeu initial de données contient {} produits. " "\n".format(len(self.products_list))) # step 1: identifying index of incomplete products incorrect_idx = self.find_incorrect_product(self.products_list) # step 2: remove unwanted products ...
003f2623d7dca26f54b8
def onclick(event,x,y,flag,image): global coords if event == cv.EVENT_LBUTTONUP: coords.append((x,y)) return
003f2dce1e55c5ad3a81
def WithTimeoutAndRetries(f): get_timeout = lambda *a, **kw: kw['timeout'] get_retries = lambda *a, **kw: kw['retries'] return _TimeoutRetryWrapper(f, get_timeout, get_retries)