dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def __load_data(self):
"""
This method will load data from the given dataset and convert it into in a suitable
chromosone representation
"""
nodes_and_points = {}
file = open("TSP_dataset/qa194.tsp", "r")
for line in file.readlines()[7:-1]:
line = line... | The code initializes an object by loading data into a dictionary, generating an initial population for optimization, and computing fitness scores for the population. It sets up essential attributes for subsequent evolutionary algorithm operations, including data storage, population generation, and fitness evaluation. | def __init__(self) -> None:
self.data = {}
self.__load_data()
self.population = self.__generate_initial_population()
self.fitness_scores = self.fitness_score() |
def get_topic_page(topic):
"""Get the web page containing the top repositories for a topic as a Beautiful Soup document"""
topic_repos_url = 'https://github.com/topics/' + topic
response = requests.get(topic_repos_url)
if response.status_code != 200:
print('Status code:', response.status_code)
... | This function scrapes the top repositories for a specified GitHub topic, saves them to a CSV file (using the topic name as the default filename), and returns the file path. It handles default path generation, data extraction from the topic page, CSV writing, and user feedback via a printed message. | def scrape_topic_repositories(topic, path=None):
"""Get the top repositories for a topic and write them to a CSV file"""
if path is None:
path = topic + '.csv'
topic_page_doc = get_topic_page(topic)
topic_repositories = get_top_repositories(topic_page_doc)
write_csv(topic_repositories, path)... |
def process_filter(self):
'''
Process the time filter, which is used to handle time requirements.
Sometimes we need news from a certain period of time,
so we use this filter to standardize the time list we input into a format
that can be put into the URL.
'''
if s... | This class is designed to crawl news articles from specified websites using keywords, parse their content, and save the results. It handles URL extraction, data parsing, and storage, with configurable parameters for retry intervals, page limits, and filtering. The class supports different news sites, each with specific... | def __init__(self,
name='CNN',
keyword='US',
startpage=1,
endpage=2,
sleep1=0.5,
sleep2=0.5,
sleep3=0.5,
filter_=None,
process=True,
parse=False,
... |
def get_all_urls(self):
'''
Get all the news urls by repeatedly calling get_urls()
'''
urls = []
while self.page <= self.endpage:
try:
urls = self.get_urls(self.page)
self.page += 1
self.count1 = 0
self.c... | The main task of the code is to execute the entire process of retrieving news related to a keyword from media sources. It first gathers all URLs using `get_all_urls()`, determines the number of URLs, parses the content with `parse()`, and saves the results via `save()`, ultimately returning None to indicate completion ... | def go(self):
'''
the main function to run the whole process to get the news of the keyword from the media
'''
self.get_all_urls()
self.num = len(self.urls)
self.parse()
self.save()
return None |
def init(self):
'''
Initialize the parameters for another keyword or another media
'''
self.count1 = 0
self.count2 = 0
self.count3 = 0
self.count = 0
self.urls = []
self.news = []
self.titles = []
self.texts = []
self.publis... | The code automatically retrieves news articles related to specified keywords from given media sources. It iterates through each media and keyword combination, initializes processing, fetches data, removes duplicates, and prints progress updates. The task involves systematic news gathering and data cleaning across multi... | def auto(self, medias, keywords):
'''
Automatically get the news of the keywords from the medias
'''
print(f'Reminder: you can only stop this process by restarting the kernel, '
f'or double click the stop button in some cases', flush=True)
for media in medias:
... |
def get_config(s3_config_bucket,s3_config_file ):
s3 = boto3.client('s3')
body_content = s3.get_object(Bucket=s3_config_bucket, Key=s3_config_file)['Body'].read().decode('utf-8')
config = ConfigParser()
config.read_string(body_content)
#config.read("glue_config.conf")
return config
def get_clien... | The code synchronizes AWS Glue catalogs and LakeFormation permissions between source and destination regions by reading a config file from S3. It processes specified data sources, extracts database metadata, restores data to target S3 paths, and applies permissions. Optional tasks include deleting existing target catal... | def main():
global source_session
global destination_session
start_time = time.time()
args = getResolvedOptions(sys.argv, ['CONFIG_BUCKET','CONFIG_FILE_KEY'])
config_file_bucket = args['CONFIG_BUCKET']
config_file_key = args['CONFIG_FILE_KEY']
## if there is / in the key name, this wi... |
def fly_to(self, x, y):
while (self.position_x != x) or (self.position_y != y):
if self.weather.wind_speed >= self.wind_thresh:
break
self.forward(x, y)
self.scan_and_report(x, y)
time.sleep(Chronos.drone_waiting())
def swap(x, y):
tmp = x
... | The code implements a drone navigation routine that alternates between predefined coordinates while managing charging and environmental conditions. It initializes a random starting point, toggles exploration mode, and loops to either charge the drone if needed or fly to swapped/shifted positions. The drone avoids night... | def fast_brute_force_routine(self):
seed = random.randint(0, self.area_x + self.area_y)
if seed <= self.area_y:
x, y = (0, seed)
else:
x, y = (seed - self.area_y, self.area_y)
self.exploring = True if random.randint(0, 1) == 0 else False
while True:
... |
def check_pydot():
"""Returns True if PyDot and Graphviz are available."""
passed = False
if pydot is not None:
try:
# Attempt to create an image of a blank graph
# to check the pydot/graphviz installation.
pydot.Dot.create(pydot.Dot())
passed = True
except (OSError, pydot.Invocati... | This function converts one or two graph definitions into a visual image file using pydot. It creates a directed graph with specific formatting, adds clusters for each graph definition, compares them if two are provided, and exports the result to the specified file. | def graphdef_to_image(graphdefs, to_file):
"""Converts graphdef(s) to a file. """
try:
check_pydot()
except ImportError as e:
raise e
if len(graphdefs) < 1 or len(graphdefs) > 2:
raise ValueError("The lenghth of graphdefs must be contain 1 or 2.")
dot = pydot.Dot()
dot.set('rankdir', 'TB')
d... |
def getTweets(cursor, user_ID):
# Execute SQL query to select tweets and retweets of the people the user follows
cursor.execute(
'''
SELECT t.tid, u.name, t.text, t.tdate
FROM follows f
JOIN users u ON u.usr = f.flwee
JOIN tweets t ON f.flwee = t.writer
WHERE f.fl... | The function `homepage` displays a user's homepage with their tweets, allowing navigation through tweet lists, composing new tweets, searching tweets/users, viewing followers, and logging out. It manages user interactions via command inputs, handles pagination for tweets, and routes actions to respective functions like... | def homepage(conn, cursor, user_ID): # Main function to display the homepage and handle user input.
print()
print("UserID: " + user_ID)
printIndex = 0 # For tracking which 5 tweets to show
tweetMax = 5 #
showOptions = True # Use to not repeatedly print options when an invalid input was entered
... |
def all(self):
with self.file() as f:
return [list(line.strip().split(self.delimiter)) for line in f]
def get(self, pattern):
pattern = list(pattern)
return [line for line in self.all() if pattern == line]
def file(self, mode='r'):
return open(self.file_name, mode)
def add(se... | This method deletes lines matching a given pattern from a file by first retrieving all lines, identifying those to delete, clearing the file, and re-adding only the non-matching lines. | def delete(self, pattern):
lines = self.all()
lines_to_delete = self.get(pattern)
self.file('w').close() # empty file
for line in lines:
if line not in lines_to_delete:
self.add(line) |
def is_done(self):
return self.done or self.done_time < time.time()
def acknowledge(self, request):
ack = WriteBootProtocolPacket(self.get_configuration(request))
ack.parameter_order = request.parameter_request_list
ack.transaction_id = request.transaction_id
# ack.next_server_ip... | The main task of the code is to handle a received DHCP request by notifying the server of the client's choice, acknowledging the request, and closing the connection. It first checks if the process is already complete, returning early if so. Otherwise, it updates the server state, sends an acknowledgment, and terminates... | def received_dhcp_request(self, request):
if self.is_done():
return
self.server.client_has_chosen(request)
self.acknowledge(request)
self.close() |
def _augment(self, input_pack: MultiPack, aug_pack_names: List[str]):
r"""
This function calls the data augmentation ops and
modifies the input in-place. This function only applies for
replacement-based methods. The subclasses should override
this function to implement other data... | The main task of the code is to process input data packs by augmenting specified packs, renaming them, aligning annotations, adding the modified packs back to the original, copying associated links/groups, and resetting internal states. It identifies packs for augmentation, applies transformations, ensures compatibilit... | def _process(self, input_pack: MultiPack):
# Get the pack names for augmentation.
aug_pack_names: List[str] = []
# Check if the DataPack exists.
for pack_name in self.configs["augment_pack_names"].keys():
if pack_name in input_pack.pack_names:
aug_pack_names.... |
def reset_row_data(self):
self.row_data={"run_id":self.timestamp}
def process_metrics(self, skill_name):
for metric in self.query_sets[skill_name]:
# validate the entry has the required keys
self.logger.debug(f"Validating entry format for {metric}")
try:
... | The code processes metrics either once for a specified time range or repeatedly at intervals. It handles 'range' mode by processing features/labels, committing data, and saving to parquet/csv. For other modes, it runs in a loop, resetting data, processing metrics, saving results, and waiting for the next interval. The ... | def start(self, scheduler_interval=0):
self.logger.debug(f"Starting MetricsProcessor with query sets: {self.query_sets}")
# If query_mode is set to range, the script should process the time range specified by time_range
if self.query_mode == 'range':
self.reset_row_data() # reset a... |
def getOppositePossibleMoves(self):
# get all opposite player moves
self.whiteToMove = not self.whiteToMove # swap players move
oppositeMoves = self.getPossibleMoves()
self.whiteToMove = not self.whiteToMove # swap players move
return oppositeMoves
def checkExist(self, opposite... | The main task of the code is to determine if a checkmate exists by iterating through possible moves, temporarily applying each move, checking if the opponent can escape check, and removing invalid moves. If no valid moves remain or the only move involves capturing a protected piece, it returns True, indicating checkmat... | def mateExist(self, moves):
# check if check-mate exists
for i in range(len(moves) - 1, -1, -1):
bol = True
startMove = self.board[moves[i].startRow][moves[i].startCol]
endMove = self.board[moves[i].endRow][moves[i].endCol]
self.board[moves[i].startRow][mo... |
def step_location(location, color):
"""Update the location color based on the rules, return the new color"""
if color == 0 and black_check(location) == 2:
return 1
elif color == 1 and black_check(location) == 0 or black_check(location) > 2:
return 0
return color
def all_neighbors(locatio... | This function processes tile locations to determine new states by applying rules based on neighbors. It updates new_locations with transformed states from flip_locations and checks neighboring tiles, adding those with exactly two black neighbors to new_locations as white (value 1). The dealt_with set ensures each neigh... | def advance(flip_locations):
new_locations = {}
# Neighbors that have already been investigated
dealt_with = set()
for location, color in flip_locations.items():
new_locations[location] = step_location(location, color)
# Check neighbors too
for n_loc in all_neighbors(location):
... |
def get_text_ids(self, index, analyzer, path, granularity):
query = hashlib.sha256(path.encode()).hexdigest()
array = np.array(self.info_ret.search_multiple_options(query, index, analyzer, granularity, ['id_paragraph', 'text']))
text = ''
if(len(array) > 0):
texts = [base64.b... | The function generates extractive summaries for specified topics using article and paragraph data, maps document IDs to paths, and saves the top-level summaries in a structured format (e.g., '_toplevel.qrels'). It processes each topic by extracting relevant text, creating summary mappings, and persisting results for fu... | def save_passage_toplevel_by_summary(self, article_file, paragraph_file, topics, dict_topics):
analyzer, index = self.info_ret.index_articles_paragraphs(article_file, paragraph_file)
ext_sum = ExtractiveSummary()
for topic in topics:
text, array = self.get_text_ids(index, analyzer, t... |
def get_text_ids(self, index, analyzer, path, granularity):
query = hashlib.sha256(path.encode()).hexdigest()
array = np.array(self.info_ret.search_multiple_options(query, index, analyzer, granularity, ['id_paragraph', 'text']))
text = ''
if(len(array) > 0):
texts = [base64.b... | The main task of the code is to generate and save hierarchical extractive summaries for given topics by processing article and paragraph files. It uses an analyzer to index content, extracts summaries with ExtractiveSummary, maps document IDs to hierarchical paths, and stores results in structured files like '_hierarch... | def save_passage_hierarchical_by_summary(self, article_file, paragraph_file, topics, dict_topics):
analyzer, index = self.info_ret.index_articles_paragraphs(article_file, paragraph_file)
ext_sum = ExtractiveSummary()
for topic in topics:
text, array = self.get_text_ids(index, analyze... |
def get_id_path_dictionary(self, index, analyzer, paths, granularity):
id_path_dict = {}
for path in paths:
encoded_path = hashlib.sha256(path.encode()).hexdigest()
ids = self.info_ret.search(encoded_path, index, analyzer, granularity, 'id_paragraph')
for id in ids:
... | The main task of the code is to generate extractive summaries for toplevel sections of specified topics using information retrieval (IR). It indexes articles and paragraphs, extracts text for each toplevel section, applies an extractive summarizer, and saves the results in a structured format with '_toplevel_ir.qrels' ... | def save_passage_toplevel_by_ir_summary(self, article_file, paragraph_file, topics, dict_topics):
analyzer, index = self.info_ret.index_articles_paragraphs(article_file, paragraph_file)
ext_sum = ExtractiveSummary()
for topic in topics:
section_toplevels = dict_topics.get(topic).get(... |
def get_id_path_dictionary(self, index, analyzer, paths, granularity):
id_path_dict = {}
for path in paths:
encoded_path = hashlib.sha256(path.encode()).hexdigest()
ids = self.info_ret.search(encoded_path, index, analyzer, granularity, 'id_paragraph')
for id in ids:
... | This code generates hierarchical extractive summaries for specified topics using information retrieval methods. It processes article and paragraph files to extract text segments, applies summarization, and saves results with '_hierarchical_ir.qrels' suffix, organizing outputs by topic-specific hierarchical paths. | def save_passage_hierarchical_by_ir_summary(self, article_file, paragraph_file, topics, dict_topics):
analyzer, index = self.info_ret.index_articles_paragraphs(article_file, paragraph_file)
ext_sum = ExtractiveSummary()
for topic in topics:
path_sections = dict_topics.get(topic).get(... |
def get_sorted_topics(self, outline_file):
dict_topics = self.info_ret.get_topics_by_granularity(outline_file)
topics = list(dict_topics.keys())
topics.sort()
return topics, dict_topics
def save_passage_article_by_summary(self, article_file, paragraph_file, topics):
analyzer, ind... | The main task of the code is to save relevant passages from article and paragraph files based on hierarchical topics derived from an outline file. It organizes content into article-level, top-level, and hierarchical structures using sorted topics and their mappings, ensuring alignment between textual content and outlin... | def save_relevance_passage_by_summary(self, article_file, paragraph_file, outline_file):
topics, dict_topics = self.get_sorted_topics(outline_file)
self.save_passage_article_by_summary(article_file, paragraph_file, topics)
self.save_passage_toplevel_by_summary(article_file, paragraph_file, topic... |
def get_suffixes(out_dir):
suffixes = []
#scan files in GENE output directory, find all run suffixes, return as list
files = next(os.walk(out_dir))[2]
for count, name in enumerate(files, start=0):
if name.startswith('parameters_'):
suffix = name.split('_',1)[1]
suffi... | The function `scan_info` processes simulation data from multiple scans stored in a directory. It reads parameters, computes physical quantities (e.g., `kymin`, `x0`, `kx_center`, `n0_global`), extracts frequency data (`omega`), analyzes field distributions (e.g., z-averages, correlation lengths, parity factors), and ca... | def scan_info(out_dir):
par = Parameters()
par.Read_Pars(out_dir + '/parameters')
pars = par.pardict
suffixes = get_suffixes(out_dir)
numscan = len(suffixes)
scan_info = np.zeros((numscan,14),dtype='float64')
for i in range(numscan):
suffix = suffixes[i]
par0 = Parameter... |
def isUploaded(out_dir,runs_coll):
inDb = runs_coll.find({ "run_collection_name": out_dir })
for run in inDb:
runIn = run["run_collection_name"]
return(runIn == out_dir)
def remove_from_mongo(out_dir, runs_coll):
#find all documents containing collection name
inDb = runs_coll.find({ "run... | This function uploads run data (linear or nonlinear) to MongoDB. It checks if the output directory already exists in the database, prompting the user to delete and reupload or skip. If not existing, it directly uploads. The process involves connecting to the appropriate collection, handling updates by removing existing... | def upload_to_mongo(out_dir, user, linear, confidence, input_heat, keywords):
#for linear runs
if linear:
#connect to linear collection
runs_coll = config.database_connect.runs
#check if folder is already uploaded, prompt update?
if isUploaded(out_dir, runs_coll):
upd... |
def load(img_file):
img = tf.io.read_file(img_file)
img = tf.io.decode_jpeg(img)
w = tf.shape(img)[1]
w = w // 2
inp_img = img[:, w:, :]
tar_img = img[:, :w, :]
inp_img = tf.cast(inp_img, tf.float32)
tar_img = tf.cast(tar_img, tf.float32)
return inp_img, tar_img
def random_jitter... | The main task of the code is to preprocess training images by loading an image pair, applying random jittering for data augmentation, and normalizing pixel values to prepare them for model training. | def load_image_train(img_file):
inp_img, tar_img = load(img_file)
inp_img, tar_img = random_jitter(inp_img, tar_img)
inp_img, tar_img = normalize(inp_img, tar_img)
return inp_img, tar_img |
def getPQ(nbits=512):
p = getPrime(nbits)
q = getPrimeIn(p+1, 2*p)
return (p,q)
def gcd(x,y):
if x<y:
(x, y) = (y, x)
while y>0:
(x, y) = (y, x%y)
return x
def modInv(n, e):
return (extEuclid(e,n)[0])%n | The code generates RSA cryptographic keys (N, e, d) by selecting prime numbers p and q, computing the modulus N = p*q, Euler's totient function φ(N), and determining a valid private exponent d that satisfies gcd(d, φ(N)) = 1 and 36*d⁴ < N. The public exponent e is derived as the modular inverse of d modulo φ(N). | def getKeys(nbits=1024):
(p,q) = getPQ(nbits//2)
N = p*q
totient = (p-1) * (q-1)
isGood_d = False
# Loop to generate private decryption exponent
while not isGood_d:
d = random.getrandbits(nbits//4)
if gcd(d,totient) == 1 and 36*pow(d,4) < N :
isGood_d ... |
def collect_anchors(version):
download(version)
a_list = list()
with open('/tmp/kde_apps') as fp:
doc = BeautifulSoup(fp.read(), features="lxml")
anchors = doc.select('a')
for anchor in anchors:
a_list.append(anchor)
return a_list
def get_url(apps_url, anchor):
re... | The main task of the code is to generate a list of package dictionaries for KDE Frameworks 5-based applications. It collects anchors for a given version, filters them based on inclusion criteria, and constructs package metadata including names, descriptions, versions, download URLs, and build commands. Each package ent... | def get_packages(version, plasma_all, frameworks):
anchors = collect_anchors(version)
packages = list()
for anchor in anchors:
url = get_url(apps_url(version), anchor)
tarball = get_tarball(anchor)
if url.endswith('.tar.xz'):
if get_name(anchor) not in inclusions:
... |
def get_latest_urls_for_selected():
latest_version = get_latest_framework_version()
frameworks_url = frameworks_version_url + '/' + latest_version
response = requests.get(frameworks_url)
if response.status_code == 200:
doc = BeautifulSoup(response.content, 'lxml')
select_anchors = list()
all_anchors = doc.sel... | The main task of the code is to generate structured data entries for each URL in `latest_urls`, including download URLs, metadata (name, version, tarball), and predefined build commands. It customizes the commands based on a `prefixes` dictionary if the package name matches a key. The function returns a list of these d... | def get_data(debug_mode):
latest_urls = get_latest_urls_for_selected()
all_data = list()
for url in latest_urls:
data = create_data()
data['download_urls'].append(url)
data['name'] = get_name(url)
data['version'] = get_version(url)
data['tarball'] = get_tarball(url)
data['commands'] = 'mkdir build\ncd bu... |
def fetch_sections(self):
data = self.retrieve_sheet_data(
sheet_id=self.DOCUMENT_ID,
sheet_range=self.SECTIONS_RANGE,
)
return list(self._sections(data))
def fetch_persons(self):
data = self.retrieve_sheet_data(
sheet_id=self.DOCUMENT_ID,
... | This code synchronizes team section and person data from external sources into the database. It atomically updates or creates TeamSection entries with code/name/email, then processes Person records with code/name/email/phone/city. For each person, it links them to a section via TeamMembership, deleting existing links b... | def store(self):
sections_data = self.fetch_sections()
persons_data = self.fetch_persons()
with transaction.atomic():
sections = {}
for s in sections_data:
section, _ = TeamSection.objects.update_or_create(
code=s["code"].strip(),
... |
def OpenOnlyInBrowser(self, url):
self.bot.get(url)
def login(self):
self.login_trys = self.login_trys - 1
if 'https://support.halabtech.com/index.php?a=login' not in self.bot.current_url:
self.bot.get('https://support.halabtech.com/index.php?a=login')
time.sleep(page_loa... | The main task of the code is to navigate to a specified URL using a browser bot, handle retries on failures, detect login pages, and either redirect to a login function or report errors if the page fails to load within retry limits. It also sets an end URL status based on success or error conditions, with optional brow... | def CrackedMindBot(self, url, open_only_browser=False):
if open_only_browser == True:
self.OpenOnlyInBrowser(url)
self.end_url = messages.on_browser_open_request
return 1
self.url = url
print('opening: '+url)
global retries
self.retries = 0
... |
def generate_fof_test_file(polishes, file_name, fof_counter_formula, **kwargs):
"""
Generates an fof test file. See generate_fof_test_file_text for more details.
Parameters:
polishes: List of polish formulas that make up the axioms of a logic.
fof_counter_formula: Usually a tautology/axiom of a lo... | The function `run_fof_test_on_formula` executes a set of logical axioms (provided as `lines`) through the Vampire theorem prover to check if they entail a given higher-order logic counterformula. It generates a temporary file with the axioms and counterformula, runs Vampire to search for a finite model, and verifies th... | def run_fof_test_on_formula(lines,
fof_counter_formula='i(i(i(i(i(X,Y),i(n(Z),n(U))),Z),V),i(i(V,X),i(U,X)))',
verify_model=False, **kwargs):
"""
Runs a set of lines in a file through vampire, each line is a potential axiom system.
Parameters:
lines: lines to run through vampire
f... |
def default(val, d):
if exists(val):
return val
return d() if isfunction(d) else d
def Downsample(dim, dim_out=None):
# No More Strided Convolutions or Pooling
return nn.Sequential(
Rearrange("b c (h p1) (w p2) -> b (c p1 p2) h w", p1=2, p2=2),
nn.Conv2d(dim * 4, default(dim_out,... | This code defines a UNet-based neural network model with residual blocks, attention mechanisms, and upsampling/downsampling layers. It processes input images through convolutional layers, time-embedded MLPs, and self-conditioning (if enabled), ultimately generating output images. The architecture includes downsampling,... | def __init__(
self,
dim,
init_dim=None,
out_dim=None,
dim_mults=(1, 2, 4, 8),
channels=3,
self_condition=False,
resnet_block_groups=4,
):
super().__init__()
# determine dimensions
self.channels =... |
def parse(input_string):
line_split = input_string.splitlines()
split_div = list(map(lambda x: x.split(' | '), line_split))
return list(map(lambda x: list(map(lambda y: y.split(' '), x)), split_div))
def count_1_4_7_8(input_list):
count = 0
for _, results in input_list:
for r in results:
... | The code processes input data for a programming problem (likely Advent of Code Day 8), parsing both sample and actual inputs. It counts occurrences of digits 1, 4, 7, and 8 in part 1, then decodes output values using a separate parsing method for part 2. Results for both sample and actual inputs are printed, demonstrat... | def main():
sample_input = '''be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe
edbfga begcd cbg gc gcadebf fbgde acbgfd abcde gfcbed gfec | fcgedb cgb dgebacf gc
fgaebd cg bdaec gdafb agbcfd gdcbef bgcad gfac gcb cdgabef | cg cg fdcagb cbg
fbegcd cbd adcefb dageb afcb bc aefdc ... |
def parse(input_str):
return list(map(lambda x: list(map(int, list(x))), input_str.splitlines()))
def p1(ticks, matrix):
count = 0
for _ in range(ticks):
count += tick(matrix)
return count
def p2(matrix):
steps = 1
while tick(matrix) != 100:
steps += 1
return steps | The code processes two input datasets (sample and actual) for a problem with two parts. It parses the input strings into structured data, then computes results using functions `p1` (with a threshold of 100) and `p2` for both datasets. The outputs are printed to demonstrate solutions for each part. The task involves ana... | def main():
sample_input = '''\
5483143223
2745854711
5264556173
6141336146
6357385478
4167524645
2176841721
6882881134
4846848554
5283751526\
'''
parsed_sample = parse(sample_input)
actual_input = '''\
4134384626
7114585257
1582536488
4865715538
5733423513
8532144181
1288614583
2248711141
6415871681
78815... |
def parse(input_string):
return list(map(lambda x: list(map(int, list(x))), input_string.splitlines()))
def calc_risk(matrix):
score = 0
for row in range(len(matrix)):
for col in range(len(matrix[0])):
if is_low_point(row, col, matrix):
score += matrix[row][col] + 1
r... | The main task of the code is to process input data representing a terrain map, calculate the risk level for low points (Part 1), and determine the sizes of basins surrounding these points (Part 2). It uses parsed input data to compute results for both sample and actual inputs, printing outputs for each part. | def main():
sample_input = '''2199943210
3987894921
9856789892
8767896789
9899965678'''
parsed_sample = parse(sample_input)
print('sample part 1')
print(calc_risk(parsed_sample))
actual_input = open('day9-input.txt').read()
parsed_actual = parse(actual_input)
print('actual part 1')
pr... |
def init_(input_folder_, patient_id_, slices_):
k_ = 'LIDC-IDRI-%s' % patient_id_
patients_ = input_folder_ + '/' + k_
date = os.listdir(patients_)
date.sort()
# To pick a specific scan (date)
for k in range(0, len(date)):
# Skip if encounter non-folder objects
if date[k].starts... | The function generates semantic labels for medical CT scans by processing annotations and DICOM data. It skips scans with slice thickness >2.5mm, initializes data structures, and creates labels using consensus masks and thresholds. Labels are generated for all slices or a subset, depending on the 'use_all_data' flag, a... | def create_labels(patient_id_, input_folder_, radiologists_, class1_, class2_, class3_, region_threshold_,
region_threshold2_, lower_, output_folder_, use_all_data=True):
# Create container for all slices and nodule slices
slices_ = []
# quickly analyze scan/annotations and continue if sl... |
def fix_tif_name(d):
import os
import shutil
for _f in os.listdir(d):
_f_out = _check_tif_name(d, _f)
if _f_out and _f != _f_out:
shutil.move(os.path.join(d, _f), os.path.join(d, _f_out.upper()))
def to_toa(sid, d_inp):
import os
if os.path.exists(os.path.join(d_inp, 'c... | The main task of the code is to process Landsat satellite data by parsing metadata from a MTL.txt file, converting the data to top-of-atmosphere (TOA) reflectance, and extracting specified bands to an output directory. It involves fixing TIFF file names, handling scene identification, and organizing processed data for ... | def main(opts):
from gio import landsat
import os
_f = '/mnt/data1/mfeng/test/test2/tmp/LE07_L1TP_153028_20001009_20170209_01_T1_MTL.txt'
_d_out = '/mnt/data1/mfeng/test/test2/tmp/test1'
_sid = landsat.parse(_f)
if _sid is None:
raise Exception('failed to parse the Landsat scene')
... |
def accept_me(response, question, user_data, user_info, current_question):
pprint(question)
date_detected = [i for i in datefinder.find_dates(response)][0].strftime("%Y-%m-%d %H:%M") if [i for i in datefinder.find_dates(response)] else False
companies = list(i.name for i in Company.objects.all())
flag ... | This code manages user interaction by retrieving or creating a user profile, tracking their current question, updating status based on responses, and triggering actions like sending messages. It processes user data, updates progress, and calls a 'mother' function for further handling. | def father(response, fbid):
try:
user_info = UserInfo.objects.get(fb_id=fbid)
except:
user_info = UserInfo.objects.create(fb_id=fbid)
# user_info.save()
user_data = json.loads(user_info.user_data)
pprint(user_data)
if user_data.get("current_question", None) == None:
... |
def printBoard(self):
for row in range(self.numrows):
for col in range(self.numcols):
# print cell
if not self.canMove((row,col),(row+1,col)):
if self.playerPos == (row,col):
print("\033[4mp\033[0m",end="")
... | The main task of the code is to execute a sequence of moves in a game, updating the board state after each move and checking for win/loss conditions. It prints the board before and after each move, terminates early if the game is won or lost, and completes all moves otherwise. | def RunGame(self, moves:str):
# Do the moves
print("Executing moves...")
self.printBoard()
for move in moves:
self.ExecuteMove(move)
print("============== Board state: ============")
self.printBoard()
if self.IsGameLost():
... |
def reset(self):
self.minotaurPos = self.InitialMinotaurPos
self.playerPos = self.InitialPlayerPos
def CanExecuteMove(self, move) -> bool:
curX, curY = self.playerPos
if move == "U":
return self.canMovePlayer((curX-1, curY))
elif move == "D":
return self.c... | This function simulates a sequence of moves in a game, checking after each move if the game is lost or won. It resets the game state, processes each move in the input string, and returns True if the game is won, False if lost or if all moves are exhausted without winning. | def RunGameQuiet(self, moves:str):
# Reset state
self.reset()
# Do the moves
for move in moves:
if not self.CanExecuteMove(move):
return False
self.ExecuteMove(move)
if self.IsGameLost():
return False
elif se... |
def hk_icosahedron_lattice(h, k, radius, orientation, alpha):
# Find triangles for the hk lattice covering one asymmetric unit equilateral triangle.
# The asym unit triangle (corners) and hk lattice triangles are in the xy plane in 3-d.
if alpha == 2:
corners, triangles, t_hex_edges = hk_triangle_tr... | This function generates and visualizes an icosahedron lattice structure defined by parameters h, k, and radius in a 3D session. It creates a geometric mesh or marker-based representation, applies color and transparency settings, and returns the modeled structure. The lattice can be displayed as a mesh with hidden hexag... | def show_hk_lattice(session, h, k, radius, orientation='222',
color=(255, 255, 255, 255), sphere_factor=0,
edge_radius=None, mesh=False, replace=True, alpha=1):
varray, tarray, hex_edges = hk_icosahedron_lattice(h, k, radius, orientation, alpha)
interpolate_with_sphere(va... |
def get_points_number() -> int:
"""Get number of points"""
try:
return int(input())
except ValueError:
raise ValueError("Incorrect data type for points number.")
def get_player_coords() -> List[float]:
"""Get player coords and sight angle"""
player_coords_float = get_float_list(input... | The main task of the code is to translate and rotate coordinates relative to a player's position, evaluate visibility within a specified sight angle, and output the results. It processes input values for points and player coordinates, applies transformation operations, and determines which points are within the player'... | def main() -> None:
"""Performs coordinates translation and rotation and prints output"""
points_number = get_points_number()
player_coords = get_player_coords()
points_coords = get_points_coords(points_number, 0, [])
translated = translate_coords(player_coords, points_coords, [], 0)
rotated = r... |
def get_testcases_number() -> int:
"""Get number of test cases to be read"""
try:
return int(input())
except ValueError:
raise ValueError("Incorrect data type for testcases number.")
def get_testcases(number: int, index: int, testcases: List[str]) -> List[str]:
"""Reads testcases"""
... | The main task of the code is to process input test cases, convert them into a list of musical notes using a predefined dictionary, evaluate chords from the notes, and print the resulting chord names. The function retrieves test data, processes it, and outputs evaluated chords as space-separated strings. | def main() -> None:
"""Prints chords founded from input"""
notes_dict = {
0: "C",
1: "C#",
2: "D",
3: "D#",
4: "E",
5: "F",
6: "F#",
7: "G",
8: "G#",
9: "A",
10: "A#",
11: "B"
}
testcases_number = get_testca... |
def checkForPinsAndChecks(self):
pins = []
checks = []
inCheck = False
if self.whiteToMove:
enemyColor = 'b'
allyColor = 'w'
startRow = self.whiteKingPosition[0]
startCol = self.whiteKingPosition[1]
else:
enemyColor = 'w... | This function generates valid chess moves for the current player, considering check/checkmate conditions. It determines if the king is in check, filters moves to escape or block checks, handles castling when not in check, and identifies checkmate/stalemate if no valid moves remain. | def getValidMoves(self):
moves = []
self.inCheck, self.pins, self.checks = self.checkForPinsAndChecks()
if self.whiteToMove:
kingRow = self.whiteKingPosition[0]
kingCol = self.whiteKingPosition[1]
else:
kingRow = self.blackKingPosition[0]
k... |
def divide_query_string_and_parse(query_string):
"""
Divide query string into two query at AND/OR.
Then parse the query separately.
Check error after calling each helper functions.
Parameters:
query_string (str): query string for search
"""
for i, logical_operator in enumerate(LOGICAL_O... | This function queries a MongoDB database based on a provided string. It checks for logical operators (AND/OR) in the query string, parses it accordingly, and returns a database cursor. If errors occur during parsing, they are returned. The query is executed on either 'all_recipes_tb' or 'favourites_tb' collections, exc... | def query(query_string, mongo_db):
"""
Query the database and return cursor according to the query.
If error happens during the process, then related error is returned.
Parameters:
query_string (str): query string for search
mongo_db (object): database object
"""
has_logical_operator = ... |
def download_album(self, album):
# Get album source
r = self.web.get('%s/noscript' % album)
# Get images
links = self.web.between(r, 'img src="http://i.', '"')
for index, link in enumerate(links):
if '?' in link: link = link[:link.find('?')]
if '#' in link: link = link[:link.find('#')]
link = self.ge... | The `download` method initializes a directory, sets a maximum of 5000 images, and downloads content based on the `album_type`. If the type is 'direct' or 'domain', it downloads a single album; if 'subreddit', it downloads a subreddit; otherwise, it downloads an account-level album. | def download(self):
self.init_dir()
self.max_images = 5000
if self.album_type == 'direct' or \
self.album_type == 'domain':
# Single album
self.download_album(self.url)
elif self.album_type == 'subreddit':
# Subreddit
self.download_subreddit(self.url)
else:
# Account-level album
self.do... |
def showWelcome(self):
""" Shows welcome screen animation of flappy bird """
# reset
self.bird.reset()
self.pipes.clear()
self.score = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT or \
(event.type... | The main task of the code is to run an infinite game loop that repeatedly displays a welcome message, executes the game logic, and checks for game-over conditions. The loop continues indefinitely unless the `gameOver()` method explicitly terminates it, though the current implementation lacks an exit condition. | def main(self):
""" main loop """
while True:
self.showWelcome()
self.play()
self.gameOver() |
def convert_quant(ff):
if not ff.columns.str.contains('fct_std').all():
ff.loc[:,'fct_std']=(ff.loc[:,'fct_ub']-ff.loc[:,'fct_lb'])/3.92
fmt_df=pd.DataFrame()
for i in ff.index:
fmt_df=pd.concat([fmt_df,conv_quant(ff.loc[[i]])])
id_vars=['point','gt_avl_date','target_end_date','horiz... | This function performs ARIMA time series forecasting on input data, applying log transformations if specified. It generates point forecasts and confidence intervals, adjusts for potential bias, and creates categorical forecasts by mapping quantiles to probability bins. The output includes quantitative forecasts with un... | def ARIMA_func(input_ts,cat_method, num_bins, win_size=None, horizon=4, verbose=True,log=False,bias_on=False):
y = input_ts.set_index('date')['value']
if log:
y[y<0]=0
y=np.log(y+1)
model = pm.auto_arima((y[:]), seasonal=False,error_action="ignore")
fct,fct_ci=model.predict(horizon,... |
def model_var_log_var(self, model_var_type):
if model_var_type == 'fixedlarge':
var = self.betas
log_var = torch.log(torch.cat([self.betas[1].view(1,), self.betas[1:].view(-1,)]))
elif model_var_type == 'fixedsmall':
var = self.posterior_variance
log_var =... | This function computes the mean and variance for a diffusion model's denoising process, returning predicted values based on the model's output and time step t. It handles different mean parametrizations (xprev, xstart, eps, dualx), clips denoised outputs, and calculates posterior means/log variances, with optional outp... | def p_mean_variance(self, model, x, t, clip_denoised, return_pred_x0, return_model_output=False):
N, C, H, W = x.shape
assert t.shape == (N,)
model_output = model(x, t)
# Learned or fixed variance?
if self.is_implicit:
var = log_var = None
else:
v... |
def predict_start_from_prev(self, x_t, t, x_prev):
x_0 = (extract(1./self.posterior_mean_coef1, t, x_t.shape) * x_prev -
extract(self.posterior_mean_coef2 / self.posterior_mean_coef1, t, x_t.shape) * x_t)
return x_0
def predict_start_from_noise(self, x_t, t, noise):
x_0 = (extract... | This function computes mean squared error (MSE) losses for three components—initial image (x₀), noise, and mean—by comparing true values with model predictions. It uses conditional logic based on `self.model_mean_type` to derive predicted values (pred_x₀, pred_noise, pred_mean) and calculates per-sample losses for visu... | def compute_mse_losses(self, x_0, t, noise, x_t, mean, model_output):
"""Compute independent losses for visualization"""
pred_x_0 = {
'xprev': lambda: self.predict_start_from_prev(x_t=x_t, t=t, x_prev=model_output),
'xstart': lambda: model_output,
'eps': lam... |
def q_sample(self, x_0, t, noise=None):
if noise is None:
noise = torch.randn_like(x_0)
sqrt_alpha_cumprod_t = extract(self.sqrt_alphas_cumprod, t, x_0.shape)
sqrt_one_minus_alpha_cumprod_t = extract(self.sqrt_one_minus_alphas_cumprod, t, x_0.shape)
return sqrt_alpha_cumpro... | The main task of the code is to compute training losses for a diffusion model by comparing the model's predicted outputs against target values derived from input data, noise, and time steps. It handles different model mean types (e.g., x0, noise, or combined), calculates mean squared error losses, and returns both loss... | def training_losses(self, model, x_0, t, noise=None):
if noise is None:
noise = torch.randn_like(x_0)
x_t = self.q_sample(x_0=x_0, t=t, noise=noise)
# Calculate the loss
model_output = model(x_t, t)
mean = self.q_posterior_mean(x_0=x_0, x_t=x_t, t=t)
targe... |
def click_cell(cell: Cell):
point = cell.point
click(point['x'], point['y'])
def get_value_of_elem(elem : WebElement):
class_name = elem.get_attribute('class')
if 'blank' in class_name:
return 'o'
elif 'bombflagged' in class_name:
return 'x'
elif 'bombdeath' in class_name:
... | The function `reveal` processes a cell by checking if its value is 'o'. If true, it simulates a click, updates the cell's value using `get_value_of_elem`, triggers `read_pocket` if the new value is 0, and returns 1. Otherwise, it returns 0, indicating no action was taken. | def reveal(cell : Cell):
if cell.value == 'o':
click_cell(cell)
cell.value = get_value_of_elem(cell.elem)
if cell.value == 0:
read_pocket(cell)
return 1
return 0 |
def initialize_cells():
# remove existing columns
while len(cells) > 0:
cells.pop(0)
# add new columns
for x in range(width):
column = []
for y in range(height):
elem = driver.find_element_by_id('{}_{}'.format(y+1, x+1))
value = 'o'
column.appen... | The code automates solving Minesweeper by using logical deductions to flag and reveal cells based on neighboring mine counts, iterating through the board to apply rules for safe moves. If stuck, it resorts to random guessing. The script navigates to a game, initializes the board, and attempts to solve it within 100 loo... | def solve():
driver.refresh()
driver.get('https://minesweeperonline.com/#{}-200'.format(difficulty))
driver.fullscreen_window()
time.sleep(3)
pyautogui.press('f2')
time.sleep(2)
initialize_cells()
# reveal a cell
reveal(cells[math.floor(width/2)][math.floor(height/2)])
# reveal(... |
def _do_tfidf(self, fit_on: Optional[str] = "clean_text", data: Optional[List[pd.DataFrame]] = None, min_df: Optional[int] = 3):
assert fit_on in ["clean_text", "lemmatized_text", "stemmed_text"], f"TF-IDF must be learnt on either of [`clean_text`, `lemmatized_text`]"
assert min_df > 0, f"min_df should ... | The code evaluates SVM performance with varying regularization parameters (C values) on TF-IDF features derived from lemmatized text. It trains and compares hard-margin SVM models with C = 0.0001, 1000, and 100000, generating classification reports, confusion matrices, and ROC curves. A grid search identifies the optim... | def Q5(self):
fit_on = "lemmatized_text"
(train_X_tfidf, test_X_tfidf), _ = self._do_tfidf(fit_on = fit_on, min_df = 3)
if fit_on == "clean_text":
y = self.train_df_clean['binary_category']
else:
y = self.train_df_lemmatized['binary_category']
ls... |
def _load_glove_embeddings(self, path = None):
if path is None:
path = self.path_to_glove_300_txt
with open(path, encoding = "utf8") as f:
word_embeddings = dict()
for line in f:
values = line.split(' ')
word_embeddings[values[0]] = np... | The code trains and evaluates an SVM classifier on feature-engineered text data (using "keywords") by splitting data, generating GloVe embeddings, fitting an SVM model, and outputting performance metrics like classification reports, confusion matrices, and ROC curves. | def Q11(self):
fit_on = "keywords"
word_embeddings = self._load_glove_embeddings()
if fit_on == "clean_text":
df_train, df_test = train_test_split(self.df[["clean_text", "binary_category"]],
test_size = 0.2,
... |
def _do_tfidf(self, fit_on: Optional[str] = "clean_text", data: Optional[List[pd.DataFrame]] = None, min_df: Optional[int] = 3):
assert fit_on in ["clean_text", "lemmatized_text", "stemmed_text"], f"TF-IDF must be learnt on either of [`clean_text`, `lemmatized_text`]"
assert min_df > 0, f"min_df should ... | The main task of the code is to evaluate and compare logistic regression classifiers (un-regularized, L1, and L2) on text data using TF-IDF features derived from lemmatized text. It performs grid search to optimize regularization strength (C) for L1/L2 models, generates evaluation metrics (classification reports, confu... | def Q6(self):
fit_on = "lemmatized_text"
(train_X_tfidf, test_X_tfidf), _ = self._do_tfidf(fit_on = fit_on, min_df = 3)
if fit_on == "clean_text":
df_train, df_test = self.train_df_clean, self.test_df_clean
elif fit_on == "lemmatized_text":
df_train, df_test = se... |
def _do_tfidf(self, fit_on: Optional[str] = "clean_text", data: Optional[List[pd.DataFrame]] = None, min_df: Optional[int] = 3):
assert fit_on in ["clean_text", "lemmatized_text", "stemmed_text"], f"TF-IDF must be learnt on either of [`clean_text`, `lemmatized_text`]"
assert min_df > 0, f"min_df should ... | The main task of the code is to build and evaluate a Gaussian Naive Bayes classifier using TF-IDF features and LSI (Latent Semantic Indexing) on lemmatized text. It processes training/test data, trains the model, generates performance metrics (classification report, confusion matrix, ROC curve), and visualizes the ROC ... | def Q7(self):
fit_on = "lemmatized_text"
(train_X_tfidf, test_X_tfidf), _ = self._do_tfidf(fit_on = fit_on, min_df = 3)
if fit_on == "clean_text":
df_train, df_test = self.train_df_clean, self.test_df_clean
elif fit_on == "lemmatized_text":
df_train, df_test = se... |
def to_dict(self):
return dict(self.spec)
def id_to_commonsdict(self, incoming_id: str, commons_template_dict: dict):
'''
Return a dict of keyword/value pairs corresponding to how to fill in the template
Parameters
----------
incoming_id: item identifier
... | The function `api_crossformat` converts API content into a specified format (default: `commons_template`) by processing an `incoming_id`. It returns a list of dictionaries containing media/metadata pairs, including title, URL, and a filled Commons template or Wikibase data. The method handles two formats: `commons_temp... | def api_crossformat(self, incoming_id: str, crossformat: str = 'commons_template') -> list:
'''
Crossformat out the API content into a format as specified
Parameters
----------
incoming_id: identifier
format:
commons_template is usually desired, otherw... |
def api_crossformat(self, incoming_id: str, crossformat: str = 'commons_template') -> list:
'''
Crossformat out the API content into a format as specified
Parameters
----------
incoming_id: identifier
format:
commons_template is usually desired, otherw... | The function `identifier_to_commons_csv_entry` generates structured CSV data for uploading media to Wikimedia Commons. It takes an identifier, queries an API for item details, and constructs entries with fields like `record_id`, `source_image_url`, `commons_filename`, `edit_summary`, and `description`. It processes URL... | def identifier_to_commons_csv_entry(self, identifier: str) -> List[Dict[str, str]]:
'''
Take an identifier to the API and generate a CSV entry (or entries) of the crucial fields for Commons upload
Example:
record_id, source_image_url, commons_filename, edit_summary, description
... |
def __build_pause_screen(self):
pause_screen = arcade.gui.UIBoxLayout()
pause_title = arcade.gui.UITextArea(text="Paused", font_size=20, font_name="Arial", color=arcade.color.GRAY_BLUE)
pause_buttons = arcade.gui.UIBoxLayout()
resume_button = arcade.gui.UIFlatButton(text="Resume", width... | This code initializes a UI manager for a game, creates pause screen, settings menu, and view selection menu components, and anchors the pause screen at the center using the UI manager. It sets up essential UI elements for game state management and user interaction. | def setup(self):
self.uimanager = arcade.gui.UIManager()
self._pause_screen = self.__build_pause_screen()
self._settings_menu = self.__build_settings_menu()
self._view_select_menu = self.__build_view_select_menu()
self._exit_dialog_handle = None
self._selected_view = No... |
def get_bert_embedding(all_sens, model, tokenizer, idf_dict,
batch_size=-1, device='cuda:0'):
padded_sens, padded_idf, lens, mask, tokens = collate_idf(all_sens,
tokenizer.tokenize, tokenizer.convert_tokens_to_ids,
... | The function computes the Word Mover's Distance (WMD) and its variants (WCD, RWMD) between source and hypothesis sentences using BERT embeddings. It processes text in batches, applies cross-lingual projections, generates n-gram embeddings, and calculates similarity scores based on specified distance metrics. The functi... | def word_mover_score(mapping, projection, bias, model, tokenizer, src, hyps, \
n_gram=2, layer=8, dropout_rate=0.3, batch_size=256, distance='wmd', device='cuda:0'):
idf_dict_src = defaultdict(lambda: 1.)
idf_dict_hyp = defaultdict(lambda: 1.)
preds = []
time_a, time_b, time_c ... |
def findCurrentParent(self):
if self._data[self._sel].type == 'group':
return self._sel
else:
return 0
def updateTree(self):
if self._update_tree_callback is not None:
self._update_tree_callback(self._data, self._sel)
def dumpToFile(self):
os.makedirs(... | This code adds a new shape object to a data structure with a unique ID, sets its properties, assigns a parent, and updates the system. It creates a new object based on the input shape type (sphere, box, or stl), assigns it an incremental ID, links it to a parent, and triggers updates to the data structure and file. | def addShape(self, shape):
self._no += 1
par = self.findCurrentParent()
name = "{} {}".format(shape, self._no)
if shape == 'sphere':
self._data[self._no] = SphereObject(name)
elif shape == 'box':
self._data[self._no] = BoxObject(name)
elif shape ==... |
def findCurrentParent(self):
if self._data[self._sel].type == 'group':
return self._sel
else:
return 0
def updateTree(self):
if self._update_tree_callback is not None:
self._update_tree_callback(self._data, self._sel)
def dumpToFile(self):
os.makedirs(... | The main task of the code is to add a new group object to a data structure. It increments an internal counter, generates a unique group name, creates a GroupObject instance, assigns it an ID and parent reference, updates the data structure, and triggers a UI refresh and file save. The function manages group creation wi... | def addGroup(self):
self._no += 1
par = self.findCurrentParent()
name = "{} {}".format("Group", self._no)
self._data[self._no] = GroupObject(name)
self._data[self._no].assignID(self._no)
self._data[self._no].setParent(par, self._data[par])
self.updateTree()
... |
def updateDetail(self):
if self._update_detail_callback is not None:
self._update_detail_callback(self._sel, self._data[self._sel])
def updateTree(self):
if self._update_tree_callback is not None:
self._update_tree_callback(self._data, self._sel)
def dumpToFile(self):
os.... | This code deletes a selected shape by its ID. If no ID is provided, it uses the currently selected ID. It removes the shape from the data structure, destroys it, resets the selection to 0, and triggers updates to the UI and file. | def delShape(self, _id=None):
if _id is None:
_id = self._sel
if _id != 0:
el = self._data[_id]
el.destroy(self._data)
del self._data[_id]
self._sel = 0
self.updateDetail()
self.updateTree()
self.dumpToFile() |
def updateTree(self):
if self._update_tree_callback is not None:
self._update_tree_callback(self._data, self._sel)
def dumpToFile(self):
os.makedirs(os.path.expanduser("~/.pyqt3dviewer"), exist_ok=True)
fp = open(os.path.expanduser("~/.pyqt3dviewer/data.json"), "w")
json.dump... | The main task of the code is to update an object's properties (name, translation, rotation, color, shape dimensions) based on input parameters, trigger UI updates (updateTree, updateDetail), and save changes to a file. It handles entity/group-specific attributes, checks for parameter existence, applies transformations,... | def setValue(self, _id, **vargs):
if _id != 0:
if "name" in vargs:
self._data[_id].setName(vargs["name"])
self.updateTree()
if self._data[_id].type == 'entity' or self._data[_id].type == 'group':
do_translate = False
... |
def distance_checker(words, token, corrections):
for word in words:
distance = calculate_distance(word, token)
if distance <= 4:
corrections.setdefault(token, [])
corrections[token].append(word)
corrections[token] = list(set(corrections[token]))
def deletes2(word)... | The code performs spelling correction on input text by checking each token against a dictionary (index) and possible variations (sym_index). It identifies potential corrections for misspelled words through deletion/insertion operations, evaluates candidates using distance metrics, and selects the best match. The functi... | def check_query(text, index, sym_index):
# get a list of words from query
tokens = nltk.word_tokenize(text.lower())
corrections = {}
results = {}
for token in tokens:
# if token is correct
if index.get(token) is not None:
pass
# if 2 deletions were made
... |
def build_index(path):
index = index_path(path)
file_name = os.path.basename(path)
file_name = file_name.rpartition('.')[0] + "_index"
with open(file_name + '.p', 'wb') as wf:
pickle.dump(index, wf, protocol=pickle.HIGHEST_PROTOCOL)
def symspell_index(dict):
sym_dict = {}
for word in d... | The main task of the code is to build and load two indexes (en_index.p and symindex.p) for text processing, then use them to analyze and check the content of "check.txt" via the check_query function, outputting the result. It leverages preprocessed data for efficient text analysis, likely for spell-checking or search t... | def main():
path = "en.txt"
if not os.path.isfile('en_index.p'):
build_index(path)
with open('en_index.p', 'rb') as fp:
index = pickle.load(fp)
if not os.path.isfile('symindex.p'):
symspell_index(index)
with open('symindex.p', 'rb') as fp:
sym_index = pickle.load(f... |
def initScores():
'''initialize the scores to 0'''
# How you create and work with the scores is up to you!
return [0,0]
def gameOver(scores):
'''checks if the game is over
game is over when either player reaches >= POINTS_TO_WIN.
[ or 4 ones are rolled :3]
Prints the win message for the player who won
I... | The code implements a turn-based game of Pig, alternating between two players. It initializes scores, repeatedly prints current scores, processes each player's move, and switches turns until the game ends. The core task is to manage game flow, score tracking, and player alternation while displaying progress after each ... | def playGame():
'''Play one game of pig
Alternates between players, and at the end of a player's turn,
prints the overall game score for both players'''
player = 1
scores = initScores()
while not gameOver(scores):
print()
print('Current Scores:')
printScore(scores)
getMove(scores, player)
... |
def welcome():
'''Prints the welcome message for the game.
We might also print the rules for the game and any other
information that the user might need to know.'''
print('Welcome to Pig!')
def playGame():
'''Play one game of pig
Alternates between players, and at the end of a player's turn,
prints the o... | The main task of the code is to execute the Pig game loop, repeatedly calling the playGame() function to run the game, and checking if the user wants to play again via wantsPlayAgain(). If not, it prints "Bye!" and exits. The code also includes a welcome message and handles game continuation logic. | def main():
'''This is the main function for the pig game'''
welcome()
while True:
# Extra Credit: Choose whether or not to AI for each game, and do the rest.
playGame()
if not wantsPlayAgain():
print('Bye!')
return |
def create_userList(length):
length = int(length)
solution = []
# continue until userList is inputted length
while len(solution) < length:
num = random.randint(0, 1000)
# add num to userList if it is unique
if num not in solution:
solution.append(num)
return so... | The main task of the code is to generate a list of random integers, sort them, and use binary search (iterative or recursive) to find a randomly selected target within the sorted list. It prompts the user for list size, displays original and sorted lists, and allows selection of the search algorithm type before executi... | def main():
# outline program details
print("\nThis program creates a list of random integers and then sorts them \n"
"It then picks random integers in the same interval until it gets a hit \n"
"using the binary search algorithm\n")
# get user userList size and create, display, and sort... |
def get_api():
config.load_incluster_config()
api = core_v1_api.CoreV1Api()
return api
def are_all_running(api_instance):
global hadoop_pod, jupyter_pod, spark_pod, sonar_pod
return is_hadoop_running(api_instance) and \
is_running(api_instance, 'jupyter') and \
is_running(api_instanc... | The code checks if critical services (Hadoop, Jupyter, Spark, Sonar) are all running via an API. If any service is down, it renders a "wait.html" page. If all are operational, it retrieves each service's URL and displays them in "index.html" for user access. | def index():
api = get_api()
all_running = are_all_running(api)
service_urls = {
'Hadoop': hadoop(api),
'Jupyter': jupyter(api),
'Spark': spark(api),
'Sonar': sonar(api)
}
if not all_running:
return render_template('wait.html')
else:
return render_... |
def get_CL(self, **kwargs):
"""Returns the coefficient of lift. Note: all parameters can be given as numpy arrays, in which case a numpy array of the coefficient will be returned.
To do this, all parameter arrays must have only one dimension and must have the same length.
Parameters
---... | This function creates a consistent d-dimensional database by filling missing values. It gathers unique independent variables, sorts them, generates a grid, and populates arrays (filled_CL, filled_CD, filled_Cm) with computed values using getters. The process ensures all combinations of independent variables are evaluat... | def _create_filled_database(self):
# Fills in missing values in the database to make it a consistent d-dimensional array.
# Initialize storage for independent vars
self._dof_filled = []
for i in range(self._num_dofs):
self._dof_filled.append([])
# Gather independent... |
def get_CL(self, **kwargs):
"""Returns the coefficient of lift. Note: all parameters can be given as numpy arrays, in which case a numpy array of the coefficient will be returned.
To do this, all parameter arrays must have only one dimension and must have the same length.
Parameters
---... | The function generates a linearized aerodynamic model for an airfoil by fitting polynomial approximations to lift (CL), moment (Cm), and drag (CD) coefficients over a selected alpha range. It either uses user-defined linear limits or prompts graphical selection of the linear region. The model updates the airfoil's type... | def generate_linear_model(self, **kwargs):
"""Creates a linearized model of the airfoil coefficients in alpha. Pulls from the
database or poly_fit information to generate this model. Cannot be used on a type
"linear" airfoil.
linear_limits : list, optional
Limits in ... |
def calcJ(Nvec):
J = 1
for n in Nvec:
J *= n + 1
return J
def decompose_j(j, Nvec):
"""
Eq. 5 in Poly Fits Derivation. Routine to decompose the j counter into
the n values. Can also be used as Eq. 1 with the i counter and the nhat
values.
inputs:
j = integer rep... | This function performs multivariable polynomial regression by fitting a polynomial model to input data (x, y) with customizable constraints. It constructs a system of equations based on polynomial orders (Nvec), interaction terms, symmetry conditions, and zero/equality constraints. The model solves for coefficients usi... | def multivariablePolynomialFit(Nvec, xx, yy ,interaction=True, sym=[], sym_same=[], sym_diff=[], zeroConstraints=[], constraints=[], percent=False, weighting=None, verbose=True):
"""
inputs
Nvec = list with a length V equal to the number of independent
variables. The ith element values ... |
def kCompose(n):
########################################
V = len(n)
if V == 1: return calcJ(n)
mx = max(n)
if mx == 0: return 1
k = 1
## calculate lower number sets
for i in range(1,mx):
m = [i] * (V-1)
k += calcJ(m)
for j in range(V-1):
m[j] -= 1
... | The function `autoPolyFit` performs multivariable polynomial curve fitting on a dataset, automatically selecting polynomial terms by balancing goodness-of-fit and model compactness. It generates orthogonal polynomial basis functions, ranks them by effectiveness, and determines the optimal number of terms using a criter... | def autoPolyFit(X, y, max_order=6, tol=1.e-12, sigma=None, sigma_multiplier=1., verbose=True):
'''
autoPolyFit function performs a mutivariable polynomial curve
fit to a dataset and automatically determines which terms in the
polynomial to use based on a balance between a goodness of the fit and a
p... |
def _load_params(self, airfoil_input):
# Load input dict
if isinstance(airfoil_input, str):
# Load JSON object
with open(airfoil_input, 'r') as json_handle:
self._input_dict = json.load(json_handle)
elif isinstance(airfoil_input, dict):
self._... | The code initializes an airfoil object by loading parameters, configuring camber solver settings from input or kwargs, loading flaps, initializing geometry, defining allowable degrees of freedom, and importing database/polynomial data based on type. It sets up the object's configuration and data structures for aerodyna... | def __init__(self, name, airfoil_input, **kwargs):
self.name = name
self._load_params(airfoil_input)
if "camber_solver_kwargs" in list(self._input_dict.keys()):
kwarg_dict = self._input_dict["camber_solver_kwargs"]
self._verbose = kwarg_dict.get("verbose", False)... |
def _setup_ind_var(self, input_dict):
# Sets up a range of independent variables
# Constant value
if isinstance(input_dict, float):
lower = input_dict
upper = input_dict
N = 1
index = None
log_step = False
# Range
else... | The main task of the code is to generate a database of aerodynamic coefficients (CL, CD, Cm) by running Xfoil simulations across specified degrees of freedom (e.g., alpha, Re, Mach). It organizes results into a structured format for interpolation, handling both variable ranges and fixed parameters, while managing Xfoil... | def generate_database(self, **kwargs):
"""Makes calls to Xfoil to calculate CL, CD, and Cm as a function of each given degree of freedom.
Parameters
----------
degrees_of_freedom : dict
A dict specifying which degrees of freedom the database should perturb. Allowable degrees... |
def promo_wave_cal(tpr_data):
tpr_data['Promo_wave']=0
c=1
i=0
while(i<=tpr_data.shape[0]-1):
if(tpr_data.loc[i,'TPR_Discount']>0):#####Also tpr ??since in validation consdered tpr
tpr_data.loc[i,'Promo_wave']=c
j=i+1
if(j==tpr_data.shape[0]):
break
... | The code processes financial data for a retailer's promotional scenarios by merging model coefficients, sales data, and ROI metrics. It calculates key financial metrics (e.g., sales, trade expenses, NSV) using predefined formulas, applies base variables for scenario analysis, and computes uplift and ROI values. The out... | def main(file1,file2, retailer , ppg, segment):
model_data = pd.read_excel(file1,sheet_name='MODEL_DATA')
model_coeff = pd.read_excel(file1,sheet_name='MODEL_COEFFICIENT')
ROI_data = pd.read_csv(file2)
ROI_data['Date'] = pd.to_datetime(ROI_data['Date'])
ret = retailer
ppg = ppg
PPG_nam... |
def _check_fleet_edges(self):
"""Function to check if any aliens have reached the edges"""
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_direction()
break
def _ship_hit(self):
"""Function for alien-ship hit"""
i... | This function updates alien movement, checks for collisions between the ship and aliens, and verifies if aliens have reached the bottom of the screen. It first checks fleet edges to adjust alien positions, updates alien sprites, detects ship-alien collisions to trigger a ship hit response, and checks if aliens have mov... | def _update_aliens(self):
"""Function to update the aliens in the fleet"""
self._check_fleet_edges()
self.aliens.update()
if pygame.sprite.spritecollideany(self.ship, self.aliens):
self._ship_hit()
self._check_aliens_bottom() |
def _check_events(self):
"""Respond to key presses and mouse events."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
if self.stats.score >= self.stats.high_score:
self.stats.save_high_score()
sys.exit()
elif ev... | The code runs the main game loop, continuously checking for events, updating game elements like the ship, bullets, lasers, and aliens when the game is active, and rendering the screen at 60 FPS to maintain smooth gameplay. | def run_game(self):
"""Start the main loop for the game."""
while True:
self._check_events()
if self.game_active:
self.ship.update()
self._update_bullets()
self._update_lasers()
self._update_aliens()
se... |
def update_corners(self):
for r in range (self.squaresHeight + 1):
for c in range (self.squaresWidth + 1):
self.corners[r][c] = self.above_threshold(c * self.squareSide, r * self.squareSide)
def draw_by_index(self, index, r, c):
if index == 0 or index == 15: # no lines
... | The main task of the code is to render a grid of squares on the screen by clearing the background, updating corner states, and iterating through each cell to draw its content based on its current state. It uses nested loops to process each square, determining its visual representation via `get_square_case` and renderin... | def draw(self):
self.screen.fill(bg_color)
self.update_corners()
for r in range (self.squaresHeight):
for c in range (self.squaresWidth):
self.draw_by_index(self.get_square_case(r, c), r, c) |
def convert_date(time: str):
today = datetime.datetime.now(tz)
return datetime.datetime(today.year, today.month, today.day, int(time.split(':')[0]), int(time.split(':')[1]))
def day_tick():
global s, assessments, assessment_queue, scheduled_messages_status, todays_assessment, todays_classes
if datetime.... | The code continuously monitors the current time, triggers a `day_tick()` function at specified intervals, and executes scheduled messages when their predefined times match the current time. It uses a loop with a 10-second delay to periodically check and handle time-based events, updating global variables for time track... | def event_loop():
global current_time, tz, day_tick_time
while True:
current_time = convert_date("{:02d}:{:02d}".format(datetime.datetime.now(tz).hour, datetime.datetime.now(tz).minute))
current_time_f = "{:02d}:{:02d}".format(datetime.datetime.now(tz).hour, datetime.datetime.now(tz).minute)
... |
def stdFiltIt(arr_1d, weights_1d, sdms, box_wid, sudo_noise, plot_q):
if plot_q:
fig = plt.gcf()
fig.clf()
plt.title('Filter plot')
xx = np.arange(len(arr_1d))
plt.plot(xx, arr_1d, '.k')
fit = arr_1d + np.nan
for sdm in sdms:
gi = np.logical_and(np.isfinit... | The code fits a Voigt profile (a combination of Gaussian and Lorentzian profiles) to a spectral line in FITS data, estimating parameters like amplitude, wavelength center, standard deviations, and continuum level. It calculates the equivalent width (EW) and its error, returning these values along with the full width at... | def solve(File, filenum, linenum):
################################################################
################################################################
# HOW TO FIT A VOIGT PROFILE
################################################################
#####################... |
def create_fused_model(args, branches_paths):
optz = Adam(lr=1e-5)
global_branch_model = branches_paths["model_global"]
local_branch_model = branches_paths["model_local"]
for layer in global_branch_model.layers:
layer.name = layer.name + "_m1"
layer.trainable = False
for layer in ... | This function trains or loads a machine learning model based on the specified mode. If in training mode, it initializes a model from a pre-trained version, fused branches, or a new configuration, then trains it using provided data generators with specified epochs and callbacks. If in loading mode, it retrieves a saved ... | def train_or_load_model(args, trn_flow, val_flow, filepath, training_examples, validation_examples,
branches_models=None, branch=None, pre_trained_model=None):
if args['mode'] == Mode.train:
if pre_trained_model is not None:
optz = Adam(lr=1e-4)
model = clone... |
def check_path(filepath):
parent = os.path.dirname(filepath)
if not os.path.isdir(parent):
os.makedirs(parent)
return filepath
def get_training_and_validation_flow(args, df, class_mode=None, split_size=0.10):
random_seed = args['random_seed']
x, y = df.iloc[:, 0].values, df.iloc[:, 1].values... | The function trains a DenseNet model on a dataset, splits training data into training/validation sets, evaluates on test data, computes classification metrics (accuracy, precision, recall, F1), generates class activation maps, and outputs predictions and performance results for a given dataset configuration. | def train_test_dense_net_split(args):
filepath = check_path("weights/{}_split/weights.hdf5".format(args['dataset']))
train_df = get_train_dataset_info(args['dataset'])
test_df = get_test_dataset_info(args['dataset'])
trn_flow, val_flow = get_training_and_validation_flow(args, train_df, split_size=0.10... |
def check_path(filepath):
parent = os.path.dirname(filepath)
if not os.path.isdir(parent):
os.makedirs(parent)
return filepath
def get_training_and_validation_flow(args, df, class_mode=None, split_size=0.10):
random_seed = args['random_seed']
x, y = df.iloc[:, 0].values, df.iloc[:, 1].values... | This function trains and evaluates a DenseNet model for regression on a split dataset, using separate branches for classification and height prediction. It loads data, splits into training/validation/test sets, generates data flows, merges outputs, trains the model, predicts on test data, calculates performance metrics... | def train_test_dense_net_split_regression(args):
filepath = check_path("weights/{}_split/weights.hdf5".format(args['dataset']))
train_df = get_train_dataset_info(args['dataset'])
test_df = get_test_dataset_info(args['dataset'])
trn_df_1 = pd.DataFrame(data={'filename': train_df['filename'].values, 'cl... |
def check_path(filepath):
parent = os.path.dirname(filepath)
if not os.path.isdir(parent):
os.makedirs(parent)
return filepath
def get_training_and_validation_flow(args, df, class_mode=None, split_size=0.10):
random_seed = args['random_seed']
x, y = df.iloc[:, 0].values, df.iloc[:, 1].values... | This function trains and evaluates an attention-guided CNN for split regression tasks. It separately trains a global branch (class prediction) and a local branch (height prediction), then merges them into a fused model. It loads datasets, creates data generators, trains models, predicts outcomes, and evaluates metrics ... | def train_test_attention_guided_cnn_split_regression(args):
train_df = get_train_dataset_info(args['dataset'])
test_df = get_test_dataset_info(args['dataset'])
first_branch_path = "weights/{}_attention_guided_global_branch/weights.hdf5"
first_branch_path = check_path(first_branch_path.format(args['data... |
def check_path(filepath):
parent = os.path.dirname(filepath)
if not os.path.isdir(parent):
os.makedirs(parent)
return filepath
def get_training_and_validation_flow(args, df, class_mode=None, split_size=0.10):
random_seed = args['random_seed']
x, y = df.iloc[:, 0].values, df.iloc[:, 1].values... | The function trains and evaluates an attention-guided CNN with two branches (global and local) on a dataset, then combines them into a fused model. It loads training/test data, trains each branch separately, generates class activation maps, merges data flows, trains the combined model, and evaluates all branches' perfo... | def train_test_attention_guided_cnn_split(args):
train_df = get_train_dataset_info(args['dataset'])
test_df = get_test_dataset_info(args['dataset'])
first_branch_path = "weights/{}_attention_guided_global_branch/weights.hdf5"
first_branch_path = check_path(first_branch_path.format(args['dataset']))
... |
def check_path(filepath):
parent = os.path.dirname(filepath)
if not os.path.isdir(parent):
os.makedirs(parent)
return filepath
def get_training_and_validation_flow(args, df, class_mode=None, split_size=0.10):
random_seed = args['random_seed']
x, y = df.iloc[:, 0].values, df.iloc[:, 1].values... | This function performs cross-validation (k-fold) for training and evaluating a dense neural network model. It splits the dataset using StratifiedKFold, trains the model on each fold, predicts on the test set, computes accuracy, precision, recall, and F1-score metrics, and aggregates results across folds. It also genera... | def train_test_dense_net_cv(args):
info = get_train_dataset_info(args['dataset'])
x, y, = info.iloc[:, 0].values, info.iloc[:, 1].values
metrics_dict, y_pred_prob_classes, fold_nr = defaultdict(int), [], 1
k_fold = StratifiedKFold(n_splits=args['nr_folds'], shuffle=True, random_state=args['random_seed'... |
def sample_uniform(m,rng):
assert isinstance(m,int) #python 3
#assert isinstance(m,(int,long)) #python 2
assert m>0
return rng.randrange(m)
def sample_bernoulli_exp(x,rng):
assert isinstance(x,Fraction)
assert x >= 0
#Sample floor(x) independent Bernoulli(exp(-1))
#If all are 1, return B... | The function generates a geometrically distributed random integer using an efficient algorithm. It samples a uniform value 'u' from the denominator of the input fraction 'x', performs a Bernoulli trial with probability 'u/t' (where t is x's denominator), and combines this with a geometric sample 'v'. The result is scal... | def sample_geometric_exp_fast(x,rng):
assert isinstance(x,Fraction)
if x==0: return 0 #degenerate case
assert x>0
t=x.denominator
while True:
u=sample_uniform(t,rng)
b=sample_bernoulli_exp(Fraction(u,t),rng)
if b==1:
break
v=sample_geometric_exp_slow(Fraction... |
def build_input_forms(self, frame):
entries = {}
for field in self.FORM_FIELDS:
row = tk.Frame(frame)
label = tk.Label(row, width=22, text=field, anchor='w')
sv = None
if field == 'Segment':
sv = tk.StringVar()
sv.trace('w', lambda name, index, mode, sv=sv: self.update_with_segment_data(sv))
... | The code initializes a Tkinter GUI for a TMS User Management application, setting up window frames, form fields, dropdowns, checkboxes, and buttons. It configures logging and prepares UI components for user interaction, enabling data entry, selection, and actions like Submit, Exit, and Clear. | def __init__(self):
self.__window = tk.Tk()
self.__cnxn_str = CNXN
self.mappy = Client(self.__cnxn_str)
self.__window.title('TMS User Management')
self.__top = tk.Frame(self.__window)
self.__bottom =tk.Frame(self.__window)
self.__top_frame = tk.Frame(self.__top)
self.__left_frame = tk.Frame(self.__top)
... |
def update_env(self, percepts):
'''
Calls the necessary methods to update the game environment variables based on the most current user position
'''
new_loc = self.update_tile_lists(percepts)
# Remove current loc from the ones pending to be explored
if self.agent_loc in ... | The code determines the next action for an agent by updating its environment with incoming percepts. If the action list is empty, it generates new actions. It then selects the first action from the list, executes it, and returns it. If no actions remain, it returns `None`, ensuring the agent performs sequential actions... | def get_action(self, percepts):
'''
Get the subsequent action to be performed by the agent.
If the action list is empty, a new set of actions is computed.
'''
self.update_env(percepts)
if not self.action_list:
self.action_list = self.build_action_list()
... |
def get_heuristic(self):
'''
Computes (and returns) the integer value of the chosen heuristic given the current agent position
'''
heuristic = 0
heuristic += distance.cityblock(self.agent_loc, self.target_location) # Manhattan distance
heuristic += self.compute_manhattan... | The code implements the A* algorithm to find the shortest path from the agent's starting position to a target location. It uses a priority queue to explore paths, prioritizing nodes with the lowest combined cost (path cost + heuristic). The algorithm tracks the lowest cost to reach each node, updates paths when cheaper... | def run_AStar(self):
priority_queue = PriorityQueue()
priority_queue.put(QueueItem(self.get_heuristic(), self.get_heuristic(), None, None)) # Root node
reached = {} # Key is node coordinates. Value is lowest cost found to reach the state
solution = Solution(math.inf, []) # Solution cost... |
def create_controls(self):
self.sizer_main.Add(self.create_folder_menu(), flag=wx.ALL, border=5)
self.sizer_main.Add(self.create_anime_name_menu(), flag=wx.ALL, border=5)
self.sizer_main.Add(self.create_subgroup_menu(), flag=wx.ALL, border=5)
self.sizer_main.Add(self.create_name_auto_men... | This code initializes a GUI application for managing anime file renaming and statistics. It sets up UI components like text inputs, checkboxes, and a list control, initializes helper classes for name handling and folder management, and prepares data structures to track episode/special lists and user preferences for ren... | def __init__(self, parent):
super().__init__(parent)
self.name_getter = NameGetter()
self.anime_stats = AnimeStatistics()
self.folder_manager = FolderManager()
self.current_folder_path = None
self.current_name_file_path = self.__DEFAULT_NAME_FILE_PATH + '\\names.txt'
... |
def state(self,open_sys,pH,pC):
#calculates the concetration of all species given pH and
#if open pC is the gas pressure while if not open it pc is the total amount
if (open_sys == 1 and self.volatile == 1) :
c_tot = self.ct_from_p(pH,pC)
else:
c_tot = pC
... | The function calculates the partial conductivity of a compound by summing the contributions of each solute species, considering their charge squared, a diffusion factor, and their concentration. It multiplies this sum by a scaling factor derived from fundamental constants and a provided epsilon value to return the cond... | def partial_conductivity(self,open_sys,pH,pC,eps):
#calculates the partial conductivity of compound
# eps = 10**-5 gives conductivity as mS/cm
f = (Fa**2)/(Rg*Ts)
c = self.state(open_sys,pH,pC)
l = 0
for i in range(self.n_solutes):
l = l +(q(self.species[i])*... |
def equi_E_res(self,res_comp,x_fixed):
y = brentq(lambda x: self.ass_res_charge_balance(x,res_comp,x_fixed),-1,1)
return y
def K_res(self,E):
E_dim = E*Fa/(Rg*Ts)
K = exp(E_dim)
return K
def equi(self):
# find pH at which charge balance = 0
y = brentq(self.cha... | This function calculates and collects residue characteristics, including equilibrium parameters (E, Kd), solute concentrations (c_t) based on pH and volatility, and charge balance (EN) for each compound in the system. It returns a concatenated list containing compound names, calculated concentrations, fixed values, equ... | def ass_res_characteristics(self,res_comp,x_fixed):
E = self.equi_E_res(res_comp,x_fixed)
# print('E = ',E)
Kd = self.K_res(E)
pH_sol = self.equi()
res_con =[]
for i in range(self.n_compounds):
c_t =0
fractions = self.comp[i].fractions(pH_sol)
... |
def get_n_resin(self):
# calculates the location of the resin species in the state vector
n_resin =-1
n_species = len(self.state())
for i in range(n_species):
if Phase(self.state()[i][0])== 'r':
n_resin =i
return n_resin
def equi_E_sol(self):
... | This function calculates and returns solution characteristics including equilibrium parameters (E, EN), solute concentrations (c_t), and charge balance. It iterates through compounds, computes species fractions, applies distribution coefficients (Kd), and aggregates results into a list with compound names, concentratio... | def ass_sol_characteristics(self):
n_resin = self.get_n_resin()
E = self.equi_E_sol()
# print('E = ',E)
Kd = self.K_res(E)
pH_sol = self.equi()
res_con =[]
for i in range(self.n_compounds):
c_t =0
fractions = self.comp[i].fractions(pH_sol)
... |
def get_title(source: dict) -> str:
return source.get("sub", "")
def get_text(source: dict) -> str:
text = source.get("com")
if text:
return cleanhtml(text)
return ""
def get_date(source: dict) -> str:
dt = source.get("time", "")
return datetime.datetime.fromtimestamp(dt).strftime('%a, %... | The main task of the code is to retrieve data from a 4channel thread API using a thread index, extract structured information including title, text, date, image links, and replies, and save this data as a JSON file in the specified directory. | def create_file(no: int, directory: str) -> None:
"""
Creates a file with title, text and link on image of thread and comments with text and image link
:param no: index of thread (["no"] parameter in API)
:param directory: directory where to save file
:return: nothing
"""
link = fr"https://b... |
def set_catalog_mod_date():
with open("config.json", "r") as file:
config = json.load(file)
config["catalog_modified_date"] = datetime.datetime.now().strftime('%a, %d %b %Y %H:%M:%S') + " GMT"
with open("config.json", "w") as file:
json.dump(config, file)
def change_comments(no: int, path: s... | The code synchronizes files from a catalog by updating existing JSON files or creating new ones based on data fetched from a remote endpoint. It reads configuration details, checks file existence, and applies updates or creates files accordingly, with a delay mechanism to control request frequency. | def check_catalog() -> None:
"""
:return: updates files from catalog
"""
with open("config.json", "r") as file:
config = json.load(file)
directory = config["folder_path"]
last_modified = config["catalog_modified_date"]
set_catalog_mod_date()
reply = requests.get(CATALOG).json()
... |
def set_archive_mod_date():
with open("config.json", "r") as file:
config = json.load(file)
config["archive_modified_date"] = datetime.datetime.now().strftime('%a, %d %b %Y %H:%M:%S') + " GMT"
with open("config.json", "w") as file:
json.dump(config, file)
def change_comments(no: int, path: s... | The main task of the code is to synchronize local archived thread files with a remote server's latest threads. It reads configuration data, fetches updated thread data from a URL, identifies new/changed threads, and either updates existing local files or creates new ones. It ensures processing rate limits by timing eac... | def archive_rec() -> None:
"""
Updating archived threads
:return: nothing
"""
with open("config.json", "r") as file:
config = json.load(file)
last_local_thread = config["last_archive_element"]
last_modified = config["archive_modified_date"]
set_archive_mod_date()
reply = requ... |
def wait(end, interrupter=INTERRUPTER, maxsleep=0.1):
# Added features to interrupter sleep and set max sleeping interval
while not interrupter.is_set(): # Basic implementation of pause module until()
now = time.time()
diff = min(end - now, maxsleep)
if diff <= 0:
break
... | This code executes tasks from a queue at their scheduled times, handling interruptions and errors. It waits until the task's start time, runs the task function with an interrupt flag, logs outcomes, and updates the queue state by removing completed tasks. | def execute_task(self):
delta = 0.1
with self._task_queue_lock:
try:
start_time, priority, count, task = self.task_queue[0]
except IndexError as e:
logger.debug("Task queue checking exception: {}".format(e))
self._timeshift = 0.0
... |
def changevis(self, list, bool):
for x in list:
x.setVisible(bool)
def typeImgMchanged(self):
if self.roiTypeComboBox.currentText() == "Area":
self.typeImgMArea()
elif self.roiTypeComboBox.currentText() == "Line":
self.typeImgMLine()
def updatelayer(self):
... | This code initializes a Napari plugin UI for ROI generation and image analysis, loading a .ui file, configuring UI elements, connecting event handlers for dynamic interactions, updating layer lists, and initializing a temporary SQLite database for data storage. | def __init__(self, napari_viewer):
super().__init__()
self.viewer = napari_viewer
self.UI_FILE = str(f"{os.path.dirname(os.path.abspath(__file__))}/static/form.ui") # path to .ui file
uic.loadUi(self.UI_FILE, self)
# Functional UI dynamics
self.dict_organize = {
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.