dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def make_args_parser():
parser = argparse.ArgumentParser(description="OpenWeatherAPI to modbus adapter.")
parser.add_argument(
"api_key", action=EnvDefault, envvar="API_KEY", help="Openweather API key."
)
parser.add_argument(
"--api-query-period",
default=5 * 60,
type=flo... | The code defines a main function that parses command-line arguments, configures an asynchronous TCP server for updating data, and launches the server using asyncio. It enables debug mode if the log level is set to "DEBUG", handling server initialization and runtime parameters through argument parsing. | def main():
parser = make_args_parser()
cmd_args = parser.parse_args()
run_args = complete_updating_tcp_async_server(cmd_args)
asyncio.run(
start_updating_server(run_args), debug=("DEBUG" == get_log_level(cmd_args))
) |
def deploy(port, k = K, consistency=consistency, killable = False):
global server_processes
print(f'deploying server at port {port}')
if port not in PORTS:
PORTS.add(port)
command = f'python3 node.py --port {port} -k {k} --local'.split(' ')
if port == 5000:
command.append('--bootstr... | The main task of the code is to test a distributed system's behavior by deploying multiple servers, inserting/deleting data, and verifying replica consistency. It simulates server additions/removals, checks data replication across nodes, and ensures consistency after modifications, validating the system's resilience an... | def main():
print(f'Initiating test with k = {K} and consistency = {consistency}\n')
deploy(5000, killable = True)
deploy(4000, killable = True)
deploy(3000, killable = True)
deploy(5050, killable = True)
deploy(8080, killable = True)
# servers are deployed at this point
print_graph()
... |
def get_grid_cell(x,y):
global pitch
global grid_max
grid_cell=[int(min(np.floor(x/pitch),grid_max[0]-1)),int(min(np.floor(y/pitch),grid_max[1]-1))]
return grid_cell
def fill_rect(ll,ur):
draw_power_box()
for row in range(ur[0]-ll[0]+1):
for col in range(ur[1]-ll[1]+1):
draw_grid_cell([row+ll[0],col+ll[1]],"... | This function handles canvas clicks in different modes: drawing power lines between two points, adding/removing pillars, and erasing power lines. It updates the grid's visual elements and associated data structures (like power_rects, scaff_rects) based on the current mode, which cycles through "power_ll", "power_ur", "... | def click_canvas(event):
global mode
global power_ll
if mode=="power_ll":
power_ll=get_grid_cell(event.x,event.y)
mode="power_ur"
elif mode=="power_ur":
global power_count
fill_rect(power_ll,get_grid_cell(event.x,event.y))
power_count+=1
mode="power_ll"
elif mode=="pillar":
grid_cell=get_grid_cell(ev... |
def glob_image_files(a_dir, img_exts=["jpg", "jpeg", "JPG", "JPG", "png", "PNG"], sort=True, silent=True):
return glob_ext_files(a_dir, img_exts, sort=sort, silent=silent)
def brisque_score(an_img):
if type(an_img) == str:
an_img = PIL.Image.open(an_img)
return brisque.score(an_img)
def blur_detect(... | The function processes images in a folder to calculate blur scores using BRISQUE and Laplace methods, logs errors encountered during processing, and saves results to a CSV file. It uses progress bars for tracking progress and errors, handles exceptions gracefully, and outputs error details if any. | def batch_get_image_blur(a_folder):
results = []
error_list = []
images = glob_image_files(a_folder)
pbar = tqdm(total=len(images))
errors = tqdm(total=len(images))
pbar.set_description("Image: ".ljust(50))
errors.set_description("Error: ".ljust(50))
for a_file in images:
try:
... |
def gtid():
"""
:return: The GT ID of the student
:rtype: int
""" ... | The code tests roulette simulation experiments by setting a win probability (18/38), initializing a random seed, and running simulations. It executes three experiments: (1) a small-scale test with 10 episodes, (2) larger-scale simulations (1,000 episodes) for figures analyzing outcomes, and (3) additional experiments f... | def test_code():
"""
Method to test your code
"""
win_prob = 18/38 # set appropriately to the probability of a ... |
def makeIngridients(self):
foodItem=input("Enter the food you want to make")
numberOfpple=input("Enter the number number of people")
def selectRecipe():
choice=displayMenu.availableRecipe()
if choice==1:
print("here is your sadza recipe")
elif choice==2:
print("here is your r... | The function `selectIngridients()` displays a menu of available ingredients based on user choice (1-6), prints corresponding ingredient lists, and directs to other functions like `makeIngridients()`, `selectRecipe()`, or `selectSpecialIngridient()` for further actions. Invalid inputs prompt retries or special dish opti... | def selectIngridients():
choice=displayMenu.availableIngridients()
if choice==1:
print("here is your sadza ingridients")
elif choice==2:
print("here is your rice ingridients")
elif choice==3:
print("here is your means ingridients")
elif choice==4:
print("here is your ... |
def billTop(self):
self.invoice=int(time.strftime("%y%m%d"))+int(time.strftime("%H%M%S"))
date_=time.strftime("%b %d,%Y")
billTopTemplate=f"Inventory Management System".center(45)+"\n"+f" Phone No. 808*****74".ljust(30)+f"Kharar - 140301".rjust(15)+"\n"+"="*45+"\n"+f" Customer Name: {self.varCNa... | The code generates a customer bill by validating input details, ensuring the cart isn't empty, and structuring the bill into top, middle, and bottom sections. It saves the generated bill to a text file, displays a success message, updates the UI state, clears the cart, and refreshes the cart display to finalize the tra... | def generateBill(self):
if self.varCName.get()=="" or self.varCContact.get()=="":
messagebox.showerror("Error",f"Customer Details are required",parent=self.root)
elif self.cartItems==0:
messagebox.showerror("Error",f"Add products to the Cart first!!!",parent=self.root)
el... |
def sanitize_blurb(text):
BLURB_THRESHOLD = 120
text = text.replace('"', '').strip()
return shorten(text, width=BLURB_THRESHOLD, placeholder='...')
def extract_text(parse_node):
if not hasattr(parse_node, 'children'):
return ''
if type(parse_node) in skip_types:
return ''
if type... | The main task of the code is to parse markdown files with YAML front matter, extract metadata (title, blurb, category) and content, sanitize them, and add structured data to a file list for indexing. It validates file format, skips invalid entries, and handles missing fields by deriving defaults from filenames or conte... | def index_file(fname):
if fname in skipped_files:
return
if not fname.endswith('.md'):
return
with open(fname, 'r') as f:
text = f.read()
splits = text.split('---', 2)
if len(splits) != 3:
print(f"No 3 splits for file '{fname}', missing header?")
exit(1)
t... |
def sanitize_function(text):
return (
text.replace(' , ', ', ').replace('( ', '(').replace(' )', ')').replace("'", '')
)
def normal_whitespace(desc: str) -> str:
return re.sub(r'\s+', ' ', desc.strip())
def extract_markdown_text(text):
parse_node = marko.parse(text)
return extract_text(parse... | This code extracts function data from markdown text by parsing structured entries, sanitizing names and descriptions, filtering out invalid entries, and organizing them into a dictionary with metadata like category, URL, and blurb for documentation purposes. | def extract_functions(text, full_path):
functions = re.findall(
r'\n[|]([^|\n]+)[|]([^|\n]+)[|]([^|\n]+)[|]([^|\n]+)[|]', text
)
for function in functions:
name = sanitize_function(
normal_whitespace(extract_markdown_text(function[0].strip()).strip())
)
desc = (
... |
def BaseSort(stat_count:list,k:int) -> list:
'''
Get top k frequent elements in stat_count via base sorting algorithm
Args:
stat_count(list): the frequent of elements in a list
k(int): top k frequent
Return:
the top k frequent of stat(sorted)
e.g.
stat_count: [('A',2),('B',1)... | The function `top_frequent` returns the top `k` most frequent elements from the input list `stat_count` using different algorithms. It dispatches to `BaseSort`, `HeapFrequent`, or `BucketFrequent` based on the `algo` parameter ("sort", "heap", or "bucket"). The "bucket" method is currently disabled via `assert 0`. The ... | def top_frequent(stat_count:list,k:int,algo="heap") -> list:
if algo == "sort":
return BaseSort(stat_count,k)
elif algo == "heap":
return HeapFrequent(stat_count,k)
elif algo == "bucket":
assert 0 #Ban bucket
return BucketFrequent(stat_count,k)
else:
print("Algori... |
def auth(self):
raise NotImplementedError
def get_df(self):
raise NotImplementedError
def process_df(self):
for col in self.df:
self.process_column(col) | This code initializes an object to handle spreadsheet data by setting up configurations, authenticating with API credentials, loading data into a DataFrame, and preparing structures for processing data to create groups/contacts. | def __init__(self, spreadsheet, spreadsheet_worksheet, spreadsheet_range, api_config, token_config=None, scopes=None, *args, **kwargs):
self.spreadsheet = spreadsheet
self.spreadsheet_worksheet = spreadsheet_worksheet
self.spreadsheet_range = spreadsheet_range
self.api_config_file = api_... |
def _rename_file(self, file: str) -> None:
"""Rename file and add one to global counter.
Args:
file (str): file name without path
"""
old_file = f"{self.filepath}/{file}"
new_file: str = self.conform_filepath(file)
os.rename(old_file, new_file)
def add_one_it... | The function processes an iterable of file paths by renaming each file and tracking the total count. It extracts file names, iterates through them to trigger renaming, updates a counter, and returns the final result of the renaming operation. | def iterate_filtered_files(self, filter_items: Iterable[Path]) -> str:
"""Iterate through an iterable with all files you want to rename.
Args:
filter_items (Iterable[Path]): Iterable
Returns:
str: final result from operation
"""
files: list[str] = [x.nam... |
def check_existence(file: Path) -> bool:
"""Check if file exists and create a new one if needed at set path.
Args:
file (Path): where the file is
Returns:
bool: boolean value
"""
if not file.exists():
file.touch()
return True
def chec... | The main task of the code is to validate the integrity of `self.destiny` by performing three checks: existence, integrity, and data consistency. It returns `True` only if all checks pass, ensuring everything is correct. | def __make_checks(self) -> bool:
"""Validate integrity and check everything is OK.
Returns:
bool: boolean value
"""
checks: list[bool] = [
self.check_existence(self.destiny),
self.check_integrity(self.destiny),
self.check_same_data(self.de... |
def __make_checks(self) -> bool:
"""Validate integrity and check everything is OK.
Returns:
bool: boolean value
"""
checks: list[bool] = [
self.check_existence(self.destiny),
self.check_integrity(self.destiny),
self.check_same_data(self.de... | The code's main task is to populate a destination file with correct paths by first validating prerequisites, reading the origin file's content, and handling errors like file not found. If checks fail or the origin file is missing, it returns error messages; otherwise, it proceeds to populate new data. | def __call__(self) -> str:
"""Populate destiny file with correct path."""
if not self.__make_checks():
return "Failed operation."
try:
self.origin_file: list[str] = self.read_text(self.origin)
except FileNotFoundError:
return "Origin file not found."
... |
def logError(msg):
print("%s%s%s"%(red, msg, end))
sys.exit(1)
def loadConfig():
confirmDir(configDir)
confirmDir(appConfigDir)
if not os.path.exists(configFile):
with open(configFile, 'w') as file:
file.write('{\n "appid" : "",\n "secretKey" : ""\n}')
configur... | The main task of the code is to send a translation request to the Baidu API using parameters like query text, source and target languages, and authentication credentials. It generates a cryptographic signature for API authentication, handles response parsing, and optionally copies the translated text to the clipboard. ... | def sendRequest(query=None, fromLang='en', toLang='zh', copy=False):
# print('query:', query)
if query is None or len(query) == 0:
logError("Please select at least one parameter.")
return 0
data = loadConfig()
appid = data['appid']
secretKey = data['secretKey']
myurl = '/api/tran... |
def logError(msg):
print("%s%s%s"%(red, msg, end))
sys.exit(1)
def normalizationData(word):
if word is None:
logError('Please input what you want to translation')
word = word.replace(',', '')
word = word.replace('(', '')
word = word.replace(')', ',')
return word
def sendRequest(quer... | The function translates text between English and Chinese based on the 'verb' parameter. If 'verb' is 'ez' or 'ze', it normalizes the input 'word' and sends a translation request (English→Chinese or Chinese→English) using 'copy'. For other verbs, it normalizes the word and sends a default translation request with 'copy'... | def translation(verb, word, copy):
# print('word:', word)
paramList = ['ez', 'ze']
if verb in paramList:
if len(word) <= 1:
logError("Please input the sentence that needs to be translated.")
word = normalizationData(word)
if verb == "ez":
# print('en:', word)
... |
def handleSimpleOption(verb):
if verb is None:
logError("Please select at least one parameter.")
if verb == '-h':
help()
sys.exit(0)
if verb == '-v':
print('version: 0.2.2')
sys.exit(0)
def logError(msg):
print("%s%s%s"%(red, msg, end))
sys.exit(1)
def trans... | This function processes command-line parameters, handling a '-c' flag to enable a copy operation. It adjusts the verb and arguments accordingly, extracts the last argument as a word, and invokes the translation function with the processed parameters. | def handleParam(verb=None, *args):
# print('input param: ', verb, args)
handleSimpleOption(verb)
copy = False
if verb == '-c':
if len(args) == 0:
logError("Please select at least one parameter.")
sys.exit(1)
verb = args[0]
args = args[1:]
copy... |
def getInvalidNumbers():
"""
- Gets the numbers with ILL or ERR status.
- Returns a dictioanry.
"""
numMap = getNumbers()
numbers = {}
for number in numMap:
if getNumberStatus(number) != STATUS_VALID:
numbers[number] = numMap[number]
return numbers
def getInvalidNumbe... | The main task of the code is to validate account numbers by identifying invalid positions (bad indexes), generating possible valid replacements for those positions, and attempting validation using these corrections. It collects invalid numbers, determines their problematic indexes, generates candidate numbers for corre... | def validateIllegalNumbers():
"""
- Collects all bad indexes and possible numbers for the bad indexes and sends it to the validator definition.
"""
numbers = getInvalidNumbers()
for accNumber in numbers:
bad_indexes = getInvalidNumbersIndex(accNumber, getNumberStatus(accNumber))
poss... |
def getNumbers():
"""
- Returns a dictionary based on scanned entries.
- The key will be the number and the value will be the account number map.
"""
numbers = {}
for accountNumber in data.readNumbers():
numbers[checker.getAccountNumber(accountNumber)] = accountNumber
return numbers
d... | The main task of the code is to process a list of numbers by iterating through them, determining each number's status, writing the number along with its status, and then validating any illegal numbers. The function `start()` orchestrates this workflow by calling `getNumbers()` to retrieve numbers, `getNumberStatus()` t... | def start():
for number in getNumbers():
writeNumberWithStatus(number, getNumberStatus(number))
validateIllegalNumbers() |
def get_input(self):
print("Welcome to XXX 8 puzzle solver.")
print("Type '1' to use a default puzzle, or '2' to enter your own puzzle.")
choice = input()
if choice == '1':
self.initial_state = self.random_puzzle()
self.goal_state = [1, 2, 3, 4, 5, 6, 7, 8, 0]
... | The code executes a selected pathfinding algorithm (Uniform Cost Search, A* with misplaced tiles, or A* with Euclidean distance) on a puzzle problem, prints the solution's move count, initial/goal states, and maximum queue size during execution. | def run(self):
algo = self.get_input()
if algo == 1:
moves, goal_state = self.uniform_cost_search()
print("Solution found in {} moves.".format(moves))
if (algo == 2):
self.a_star_misplaced()
if algo == 3:
self.a_star_euclidean()
pr... |
def remove_zeros(num: str) -> str:
n = str(float(num))
return n[:-2] if n[-2:] == ".0" else n
def get_sign_from_temp(self) -> str | None:
if self.temp.text():
return self.temp.text().strip(".").split()[-1]
def get_temp_num(self) -> int | float | None:
if self.temp.text():
... | The code performs a calculation using values from `self.entry` and `self.temp`, applies an operation based on `self.get_sign_from_temp()`, handles errors like division by zero, updates UI elements with the result, and returns the calculated value as a string. | def calc(self) -> str | None:
entry = self.entry.text()
temp = self.temp.text()
if temp:
try:
result = self.remove_zeros(
str(operations[self.get_sign_from_temp()](self.get_temp_num(), self.get_entry_num()))
)
self.... |
def clear_error(self) -> None:
if self.entry.text() in (error_undefined, error_zero_div):
self.entry.setText("0")
self.entry.setMaxLength(self.entry_max_len)
self.adjust_entry_font_size()
def replace_prev(self) -> None:
if self.get_sign_from_temp() == "=":
... | This method handles digit button input in a calculator interface. It clears previous states, checks if the pressed button is a digit, and updates the display field by either replacing initial "0" or appending digits. It ensures proper numeric input handling and adjusts the entry's font size for optimal display. | def add_digit(self) -> None:
self.clear_error()
self.replace_prev()
self.clear_temp()
btn = self.sender()
digit_buttons = ("btn_0", "btn_1", "btn_2", "btn_3", "btn_4",
"btn_5", "btn_6", "btn_7", "btn_8", "btn_9")
if btn.objectName() in digit_but... |
def clear_error(self) -> None:
if self.entry.text() in (error_undefined, error_zero_div):
self.entry.setText("0")
self.entry.setMaxLength(self.entry_max_len)
self.adjust_entry_font_size()
def clear_temp(self) -> None:
if self.get_sign_from_temp() == "=":
s... | This code implements a backspace functionality for an entry field. It clears errors and temporary data, then removes the last character from the entry text. Special cases handle resetting to "0" when the entry is length 1 or a 2-character negative number. Finally, it adjusts the entry's font size for display consistenc... | def backspace(self) -> None:
self.clear_error()
self.clear_temp()
entry = self.entry.text()
match len(entry):
case 1:
self.entry.setText("0")
case 2 if "-" in entry:
self.entry.setText("0")
case _:
self... |
def add_temp(self) -> None:
btn = self.sender()
entry = self.remove_zeros(self.entry.text())
if not self.temp.text() or self.get_sign_from_temp() == "=":
self.temp.setText(entry + f" {btn.text()} ")
self.adjust_temp_font_size()
self.entry.setText("0")
def get... | This code processes mathematical operations in a GUI calculator by updating the display text based on button inputs. It checks if the current expression is empty, replaces operators if needed, calculates results when appropriate, and adjusts formatting. The function ensures correct operator precedence and updates the d... | def math_operation(self) -> None:
temp = self.temp.text()
btn = self.sender()
if not temp:
self.add_temp()
else:
if self.get_sign_from_temp() != btn.text():
if self.get_sign_from_temp() == "=":
self.add_temp()
e... |
def read_input(filename):
with open(filename) as f:
lines = f.readlines()
return [line[:-1] for line in lines]
def parse_rules(rules):
graph = {}
for rule in rules:
key, val = _parse(rule)
graph[key] = val
return graph
def find_bag(graph, bag):
# Don't count the shiny go... | The code reads rules from a text file, constructs a graph representing bag containment relationships, and calculates how many distinct bag types can directly or indirectly contain a 'shiny gold' bag, then outputs the count as the solution to "PROBLEM 1". | def main():
input_path = '../input/mock.txt'
rules = read_input(input_path)
graph = parse_rules(rules)
num_contain = find_bag(graph, 'shiny gold')
print(f"PROBLEM 1: {num_contain}") |
def load_report(filename):
with open(filename) as f:
return [int(x) for x in f.readlines()]
def find_expenses(report, total):
for i, expense in enumerate(report):
target = total - expense
if search(report, i, len(report), target):
return target * expense
return -1
def ... | The code's main task is to solve two problems by finding pairs and triplets in a sorted input report that sum to a specified "magic number" (2020). It loads data from a file, sorts it, then uses `find_expenses` to identify two numbers and `find_expenses_3` to identify three numbers that sum to 2020, printing both resul... | def main():
magic_number = 2020
input_path = '../input/d1p1.txt'
report = load_report(input_path)
report.sort()
problem1 = find_expenses(report, magic_number)
print(f'PROBLEM 1: {problem1}')
problem2 = find_expenses_3(report, magic_number)
print(f'PROBLEM 2: {problem2}') |
def read_input(filename):
with open(filename) as f:
return [line[:-1] for line in f]
def get_highest_seat_id(passes):
return max([get_seat_id(p) for p in passes])
def find_missing_seat(passes):
ids = get_all_seat_ids(passes)
ids.sort()
for i in range(len(ids) - 1):
if ids[i+1] == ids... | The code reads input data from a file, processes it to determine the highest seat ID (Problem 1) and identifies a missing seat ID (Problem 2), then prints both results. It uses helper functions to parse input, compute the maximum seat number, and detect the absent seat. The main task involves solving two related challe... | def main():
input_path = '../input/d5p1.txt'
passes = read_input(input_path)
highest = get_highest_seat_id(passes)
missing = find_missing_seat(passes)
print(f"PROBLEM 1: {highest}")
print(f"PROBLEM 2: {missing}") |
def __transpose(self, data: List[List[Any]]):
return [list(x) for x in zip(*data)]
def __req(self, url: str, data: Dict[str, Any], isPred=False, retry=3, timeout=30):
for i in range(retry):
start_time = datetime.now()
try:
# print(f"RETRY {i + 1}")
... | The main task of the code is to process seismic waveform data for a given station and timestamp. It retrieves cached data, transposes it, sends a prediction request, and stores results in Redis. If valid waveform data (≥3 points) is found, it generates predictions, constructs metadata payloads, and sends them via a pro... | def __pred_stats(self, station: str, time: datetime):
data_cache = self.pooler.get_cache(station)
data_cache_t = self.__transpose(data_cache)
res = self.__req(
STAT_URL, {"x": data_cache_t, "station_code": station}, isPred=True
)
if res:
result = res["resu... |
def eat_token(self, expected_type):
if self.current_token.type != expected_type:
raise ParseError(f"Expected token type: {expected_type}, got: {self.current_token.type}, at: {self.current_token.pointer}")
self.next_token()
def parse_parameter(self):
span_start = self.current_token.po... | The main task of the code is to parse a function prototype by extracting its name, arguments, and return type (if present) from a token stream. It captures the function's span, processes parameters within parentheses, and constructs a `FunctionPrototype` object with parsed details, including argument types and return t... | def parse_function_prototype(self):
# store name, arguments, argument_types and the start of the signature
span_start = self.current_token.pointer
name = self.current_token.value
self.eat_token("TOKEN_ID")
self.eat_token("LPAREN")
# While we are inbetween the brackets, a... |
def sub_objects(self, parent, level=0, query=None):
""" Returns the sub objects of a given parent.
Checks if the objects should be listed in navi.
"""
# if the parent is the portal and its not level 0,
# return no children
portal = getToolByName(self.context, 'portal_url'... | This code generates a navigation menu (HTML list) by processing sub-objects of a context, adjusting URLs based on portal settings, and handling default page logic. It disables theming for AJAX requests, retrieves navigation items, formats them with titles/links, and returns structured HTML for dynamic navigation render... | def __call__(self):
# Disable theming for ajax requests
self.request.response.setHeader('X-Theme-Disabled', 'True')
properties = getToolByName(self.context, 'portal_properties')
view_action_types = properties.site_properties.getProperty(
'typesUseViewActionInListings', ())
... |
def create_query_job(self, soql):
"""create a bulk job"""
uri = self.instance_url + "/services/data/{}/jobs/query".format(
self.api_version
)
body = {"operation": "query", "query": soql}
response = requests.post(
url=uri, headers=self.__get_request_heade... | The main task of the code is to execute a SOQL query in batches, handling large datasets by splitting results into chunks if the total record count exceeds a predefined limit (`max_records`). It creates a query job, waits for completion, retrieves results either fully or partially based on the record count, and returns... | def query(self, soql):
"""execute soql query and return results"""
job_id = self.create_query_job(soql)
job_status_response = self.wait_for_job_complete(job_id, "query")
total_number_of_records = job_status_response["numberRecordsProcessed"]
print("records to be fetched :{}".form... |
def create_job(self, object_api_name, operation, external_id_field_name=None):
request_url = self.instance_url + "/services/data/{}/jobs/ingest".format(
self.api_version
)
body = {
"operation": operation,
"object": object_api_name,
"contentType":... | The code inserts data into a system by creating a job, uploading the data, marking the upload as complete, waiting for the job to finish, and returning the job ID. The main task is to handle data insertion through a structured job process, ensuring completion before returning the job identifier. | def insert(self, object_api_name, data):
job_id = self.create_job(object_api_name, "insert")
self.upload_data(job_id, data)
self.upload_complete(job_id)
self.wait_for_job_complete(job_id)
return job_id |
def create_job(self, object_api_name, operation, external_id_field_name=None):
request_url = self.instance_url + "/services/data/{}/jobs/ingest".format(
self.api_version
)
body = {
"operation": operation,
"object": object_api_name,
"contentType":... | This method performs an upsert operation in Salesforce by creating a job, uploading data, completing the upload, waiting for job completion, and returning the job ID. It uses the specified object API name, external ID field, and data to synchronize records, updating existing ones or inserting new ones based on the exte... | def upsert(self, object_api_name, external_id_field_name, data):
job_id = self.create_job(object_api_name, "upsert", external_id_field_name)
self.upload_data(job_id, data)
self.upload_complete(job_id)
self.wait_for_job_complete(job_id)
return job_id |
def create_job(self, object_api_name, operation, external_id_field_name=None):
request_url = self.instance_url + "/services/data/{}/jobs/ingest".format(
self.api_version
)
body = {
"operation": operation,
"object": object_api_name,
"contentType":... | This code deletes data by initiating a job, uploading the data, and waiting for completion. It first creates a deletion job using the specified object API name, uploads the provided data to the job, marks the upload as complete, and then waits until the job finishes processing. The main task is to securely delete data ... | def delete(self, object_api_name, data):
job_id = self.create_job(object_api_name, "delete")
self.upload_data(job_id, data)
self.upload_complete(job_id)
self.wait_for_job_complete(job_id) |
def updateAndReturnChain(name, chain, t):
#if last update was more than an hour ago check for new tweets and get them
now = datetime.datetime.utcnow().replace(tzinfo=utc)
timediff = now - chain.last_updated
if timediff.total_seconds() > UPDATE_THRESHOLD:
return updateTweets(name, chain, t)
e... | The main task of the code is to generate a Markov chain-based tweet by aggregating Twitter data from multiple users. It retrieves OAuth tokens for authentication, fetches tweets for each provided username, updates or creates Markov chains for each user, combines these chains, and outputs a 250-character sentence. The p... | def generateTweet(nameArray, userid):
authinfo = UserSocialAuth.objects.get(user_id = userid)
user_token = authinfo.extra_data['access_token']['oauth_token'] #get users' tokens
user_token_secret = authinfo.extra_data['access_token']['oauth_token_secret']
print(datetime.datetime.now())
t = Twitter(
... |
def get_device() -> torch.device:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
return device
def relu_evidence(y: torch.tensor) -> torch.tensor:
return F.relu(y)
def mse_loss(y: torch.tensor,
alpha: torch.tensor,
epoch_num: int,
num_classes: in... | This function computes the evidential deep learning mean squared error (MSE) loss by applying ReLU to the model's output to obtain evidence, converting it to alpha (evidence + 1), and calculating the MSE between the target and alpha values. The loss is averaged over the batch, incorporating parameters related to the tr... | def edl_mse_loss(output: torch.tensor,
target: torch.tensor,
epoch_num: int,
num_classes: int,
device: torch.device = None) -> torch.tensor:
if not device:
device = get_device()
evidence = relu_evidence(output)
alpha = evidence + 1... |
def define_queryset(self):
"""
Returns the queryset for exporting data to BigQuery.
This method can be overridden in subclasses to specify additional filters or ordering
for the queryset. For example, you can use this method to filter data based on date ranges
or status fields.
... | The code exports data from a queryset to BigQuery in batches, using a specified or current timestamp. It processes each batch, handles errors during export, adjusts error indices for batch offsets, logs progress, and raises Google API errors. The function returns a list of errors encountered during the export process. | def export(self, pull_date=None):
"""
Export data to BigQuery.
Args:
pull_date (datetime.datetime, optional): The datetime used to populate the pull_date field.
If not provided, the current date and time will be used.
Raises:
Exception: If an err... |
def multiply_with_test_function(self):
self.debug_print("Multiply with Test Function", "heading")
self.lhs_terms = execute_test_multiplications(self.lhs_terms)
self.rhs_terms = execute_test_multiplications(self.rhs_terms)
self.update_equation()
def integrate_over_domain(self):
se... | The code's main task is to generate a weak form equation in UFL (Unified Form Language) for a finite element problem. It performs essential operations like multiplying with test functions, integrating over a domain, and applying integration by parts. The method constructs an executable script, formats the weak form equ... | def solve(self):
self.multiply_with_test_function()
self.integrate_over_domain()
self.integraty_by_parts()
self.convert_to_ufl_string()
commands = get_executable_string(self.functions, self.mesh, self.lhs_ufl_string, self.rhs_ufl_string)
final_string_eq = str(self.lhs_ufl... |
def get():
key = request.args.get('str_key')
update_nodes_list()
key_v_node_id = xxhash.xxh64_intdigest(key) % 1024
if key in cache:
return {"cache": cache[key]}, 200
node = nodes_list.get_node(key_v_node_id)
try:
ans = requests.get(f'http://{node}:5000/load?str_key={key}')
... | The main task of the code is to store data in a distributed cache system by hashing a key to determine a target node, validating the expiration date format, and attempting to save the data to the primary node. If that fails, it tries an alternative node. It returns the cache response or error messages if both attempts ... | def put():
key = request.args.get('str_key')
data = request.args.get('data')
expiration_date = request.args.get('expiration_date')
try:
datetime.strptime(expiration_date, "%Y-%m-%d")
except ValueError:
return "invalid date format, should be YYYY-MM-DD", 200
update_nodes_list()
... |
def is_full(board):
m, n = len(board), len(board[0])
count = 0
for i in range(m):
for j in range(n):
if board[i][j] != 0:
count += 1
return count == m * n, count
def mobility(board, player):
mob = len(get_valid_moves(board, player)) - len(get_valid_moves(board, 3 ... | The function evaluates a board state for a given player in a game like Reversi/Othello, calculating a score based on piece count, strategic positions (corners, edges), mobility, and stability. It assigns positive/negative values to the player's/opponent's pieces, applies weighted adjustments for corner and edge positio... | def evaluate(board, player):
score = 0
for i in range(BOARD_SIZE):
for j in range(BOARD_SIZE):
if board[i][j] == player:
score += 1
elif board[i][j] == 3 - player:
score -= 1
conner = [(0, 0), (0, BOARD_SIZE - 1), (BOARD_SIZE - 1, 0), (BOARD_S... |
def get_valid_moves(board, player):
valid_moves = []
for i in range(BOARD_SIZE):
for j in range(BOARD_SIZE):
if is_valid_move(board, player, (i, j)):
valid_moves.append((i, j))
return valid_moves
def make_move(board, player, move):
new_board = [row[:] for row in board... | The main task of the code is to order valid moves for a player based on their evaluation scores, prune the list by removing lower-scoring moves (if needed), and return a prioritized list of moves. It first generates valid moves, evaluates each move's score, shuffles the scored moves, sorts them in descending order of s... | def move_ordering(board, player, r):
scored_moves = []
valid_moves = get_valid_moves(board, player)
for move in valid_moves:
new_board = make_move(board, player, move)
score = evaluate(new_board, player)
scored_moves.append((move, score))
random.shuffle(scored_moves)
scored_m... |
def evaluate(board, player):
score = 0
for i in range(BOARD_SIZE):
for j in range(BOARD_SIZE):
if board[i][j] == player:
score += 1
elif board[i][j] == 3 - player:
score -= 1
conner = [(0, 0), (0, BOARD_SIZE - 1), (BOARD_SIZE - 1, 0), (BOARD_S... | This function implements the minimax algorithm with alpha-beta pruning and move ordering to determine the optimal move for a player in a two-player game. It evaluates board states recursively, alternating between maximizing and minimizing players, while pruning suboptimal branches to improve efficiency. The function re... | def minimax(board, player, depth, alpha, beta, max_player, op, full):
if depth == 0:
return evaluate(board, op), None
if full:
ordered_moves_1 = get_valid_moves(board, player)
ordered_moves_2 = get_valid_moves(board, player)
else:
ordered_moves_1 = move_ordering(board, player... |
def config_parser():
import configargparse
parser = configargparse.ArgumentParser()
parser.add_argument('--config', is_config_file=True,
help='config file path')
parser.add_argument("--expname", type=str,
help='experiment name')
parser.add_argument(... | The code performs rendering tasks using a NeRF model with latent embeddings and varying lighting conditions. It loads datasets, initializes neural networks, and renders images/videos for different configurations (e.g., single views, all IDs, training data). It handles OLAT lighting setups, processes latent vectors, and... | def test(args):
global NUM_RELIT_EMAPs
NUM_RELIT_EMAPs = args.num_relit_emaps
parser = config_parser()
args = parser.parse_args()
use_OLAT = False
prefix = 'images'
if args.use_shading_nw:
use_OLAT = True
prefix = 'OLAT_images'
test_dataset = ImagesDataset(args, args.da... |
def verbruikvergelijking(dictH,dictN):
comp = {}
for k,v in dictH.items():
if k not in dictN.keys():
a = {k:v}
elif k in dictN.keys():
a = {k:v-dictN.get(k)}
comp.update(a)
return comp
def verbruikskost(verbruik):
c = 0
for key, value in verbruik.item... | The code compares two energy profiles (huidProf and nieuwProf) to calculate savings in primary energy, CO2 emissions, consumption, and costs. It computes percentage reductions, total cost savings, and financial metrics like cash flow and payback time (tvt). The results are returned as a dictionary containing all compar... | def profileComparison(huidProf, nieuwProf):
vergelijking = {}
vergelijking['PV'] = nieuwProf.get('PV')
vergelijking["besparing primaire energie"] = huidProf.get('primaire energie') - nieuwProf.get('primaire energie')
vergelijking["besparing primaire energie perc"] =(vergelijking.get('besparing primaire e... |
def verbruikverdeling(verbruik,pers, huidigevoorziening): #verbruik is een dictionary met elke verbruiker en het verbruik, Swwvraag is een input, huidigevoorziening is een dict van de huidige voorzieningen per toepassing
volumevraagSWW = 40.71*pers*365
cp = 4186 #j/kg*k
dt = 50 #°c
rho = 0.997 #kg/l
... | The function updates user data, adjusts scenarios to reflect current installations, calculates energy consumption distribution, generates new profiles for scenarios, compares them with the current profile, sorts results by CO2 savings, and returns sorted data, current profile, and graph-ready results for energy and cos... | def main(toepass,huidigeVoorzieningen,huidigverbruik,scenariosList,updateverbruikers,PV,inwoners,COPindex):
#data in verbruikers update (persoonlijke kostprijs per kwh bijvoorbeeld)
print(huidigeVoorzieningen)
for k,v in updateverbruikers.items():
verbruikers.get(k).update(v)
#sanitair warm... |
def _convert_data_to_segments(self, data):
size = len(data)
n_of_segments = math.ceil(size / self._mss)
self._segments = []
for i in range(n_of_segments):
curr_segment_size = self._mss if size >= self._mss else size
size -= self._mss
flags = 8 if i == ... | The main task of the code is to transmit data in segments over a network connection using congestion control and sliding window mechanisms. It initializes parameters for tracking segments, acknowledgments, and congestion, then iteratively sends data segments while ensuring the receive window allows transmission. The lo... | def sendall(self, data):
self._last_received_ack = self._seq_num
self._convert_data_to_segments(data)
self._next_segment = 0
self._n_of_acked_segments = 0
self._expected_acks = []
self._connection_error_counter = 0
self._congestion_window_factor = 4
self._... |
def Min(self):
tmp = self.NodesList[0]
self.NodesList[0]=self.NodesList[len(self.NodesList)- 1]
del self.NodesList[len(self.NodesList)- 1]
self.Arrange(0)
return tmp
def Arrange(self, i):
tmp =i
l = 2 * i + 1
r = 2 * i + 2
if l < len(self.NodesList... | The main task of the code is to construct a Huffman tree by repeatedly combining the two smallest nodes (via self.Min()) into an internal node, appending it to the node list, and reorganizing the list until only one node remains. Finally, it retrieves the root node and initiates code generation using PrintCodes. | def FooTree(self):
while True:
left = self.Min()
right = self.Min()
tmp = InternalNode(right, left)
self.NodesList.append(tmp)
self.Arrange(len(self.NodesList)-1)
if len(self.NodesList) == 1:
break
root = self.Min()... |
def match():
global i
global string
global la
if i < len(string):
la = string[i]
i = i + 1
def A():
global la
if la == 'a':
match()
A()
elif la == 'b' or la == 'c' or la == 'd':
return
else:
global flag
flag = False
print("f... | The function `S()` processes operations based on the global variable `la`. If `la` is `'f'`, it calls `match()` and exits. Otherwise, it sequentially executes functions `A()`, `B()`, `C()`, recursively invokes itself, then calls `D()` and `E()`, forming a loop with conditional branching. The main task is to handle diff... | def S():
global la
if la == 'f':
match()
return
else:
A()
B()
C()
S()
D()
E() |
def parse_heightmap(data):
for r in range(len(data)):
for c in range(len(data[r])):
if data[r][c] == 'S':
start = (r, c)
elif data[r][c] == 'E':
stop = (r, c)
heightmap = []
for row in data:
heightmap.append([elevation(i) for i in row]... | The code solves two pathfinding tasks on a heightmap parsed from input data. It calculates the shortest path length (task1) using `find_path` and a modified approach (task2) with `find_path_2`, returning the minimum steps required minus one for each. The function also measures execution time. Both tasks involve analyzi... | def day12():
data = [line.strip() for line in open('input12.txt')]
start_time = time.time()
heightmap = parse_heightmap(data)
paths = find_path(heightmap)
task1 = min([len(v) for v in [p.visited for p in paths]]) - 1
heightmap = parse_heightmap(data)
paths = find_path_2(heightmap)
task... |
def game_is_won(board, chip):
"""check if current board contain a sequence of 4-in-a-row of in the board
for the player that play with "chip" """
winning_Sequence = np.array([chip, chip, chip, chip])
# Check horizontal sequences
for r in range(ROW_COUNT):
if "".join(list(map(str, winning_... | The function simulates a game where two players take turns making random moves on a board. It alternates between the given player's chip and the opponent's chip, checking after each move if the current player has won. If the opponent wins or no valid moves remain, it returns False. If the initial player wins, it return... | def playRestOfGame(board,chip):
otherChip = -1
if chip == BLUE_INT:
otherChip = RED_INT
else:
otherChip = BLUE_INT
turn = otherChip
while True:
if game_is_won(board,chip):
return True
if game_is_won(board, otherChip) or len(get_valid_locations(board)) == 0... |
def get_next_open_row(board, col):
"""assuming column is available to drop the chip,
the function returns the lowest empty row """
for r in range(ROW_COUNT):
if board[r][col] == 0:
return r
return -1
def drop_chip(board, row, col, chip):
"""place a chip (red or BLUE) in a certai... | The function `MC` evaluates each column's potential to win by simulating random games after placing a chip, then returns the column with the highest win rate. | def MC(board,chip):
winsPerCol = [0,0,0,0,0,0,0] #times the agent one when decding to place chip in column i
for col in range(7):
row = get_next_open_row(board,col)
#if the column is full, skip it
if row == -1:
winsPerCol[col] = -1
else:
for i in range(... |
def parse_args_and_config():
parser = argparse.ArgumentParser(description=globals()['__doc__'])
# SDEdit
parser.add_argument('--config', type=str, default=os.path.join("configs", "celeba.yml"), help='Path to the config file')
parser.add_argument('--seed', type=int, default=1234, help='Random seed')
... | The code performs face-based image editing by segmenting target and source images, resizing masks, detecting landmarks, transforming images, filling artifacts, and applying diffusion editing. It uses segmentation, alignment, and diffusion models to generate edited images from input pairs, saving outputs and logging pro... | def main():
args, config = parse_args_and_config()
segment = face_segment(seg_model_path=args.seg_model_path,
label_config=args.label_config,
input_image_size=args.input_image_size)
# read original image
target_image = read_image(args.target_image_... |
def check_screen_presence():
""" Checks if a display is connected, eventually via VNC; This is not the (SPI) display at Raspberry Pi."""
import os # os library is imported
if 'DISPLAY' in os.environ: # case the environment variable DISP... | The main task of the code is to read and validate configuration settings from a `settings.txt` file, adjust them based on hardware constraints (e.g., screen presence, Raspberry Pi model), initialize camera and display settings, and return a dictionary of processed variables along with an error code. It handles paramete... | def setup():
""" Reads settings from the settings.txt file and add them in a dictionary.
Sets the camera, and the display
"""
variables={} # empty dictionary to store the local variable
screen = check_screen_presence() # screen presence... |
def start_time_end_time(start_hhmm, end_hhmm, interval_s):
"""Converts the strings 'start_hhmm' 'end_hhmm'to seconds from midnight.
Adjust the end_time to be an exact multiple of interval_s.
"""
try:
start_time = datetime.strptime(str(start_hhmm),'%H:%M') # start_hhmm string is parsed to... | The function calculates the shooting duration (shoot_time_s) between start and end times, adjusting for power outages and start_now settings. It handles time intervals across midnight, adjusts start times during power outages, and ensures the shooting period meets the minimum interval requirement. It returns the adjust... | def time_management(start_hhmm, end_hhmm, start_now, interval_s, last_frame, power_outage):
"""Function managing some time related task, according to the settings and eventual power_outage."""
start_time_s, end_time_s, shoot_time_s = start_time_end_time(start_hhmm, end_hhmm, interval_s)
if start_n... |
def toDraw(points, hasAce, dealerFirstCard, remainings, depth=1, logging=[]):
noDrawExpectedValue = gameProb(points, hasAce, dealerFirstCard, remainings)
drawExpectedValue = calculateExpectedWithDepth(points, hasAce, dealerFirstCard, remainings, depth)
if drawExpectedValue >= noDrawExpectedValue:
re... | This function calculates the expected probability of winning a blackjack-like game by recursively evaluating all possible outcomes of drawing cards from the remaining deck. It considers the player's current points, ace status, dealer's first card, and remaining card counts. For each potential card draw, it updates prob... | def expectedWin(points, hasAce, dealerFirstCard, remainings):
if toDraw(points, hasAce, dealerFirstCard, remainings, 1)==False:
return gameProb(points, hasAce, dealerFirstCard, remainings)
else:
size = float(sum([v for v in remainings.values()]))
currentAce = hasAce
expectedValue... |
def _a_command(self, address):
self.assembly_lines += [
f"@{address}"
]
def _c_command(self, computation, dest=None, jump=None):
first_half = f"{dest}={computation}" if dest else computation
self.assembly_lines += [
f"{first_half}; {jump}"
if jump els... | This function handles popping a value from a specified memory segment (e.g., THIS, THAT, LOCAL, ARGUMENT, TEMP, STATIC) and stores it at a calculated address. It uses R13 as a temporary register to store the target address, then transfers the value from the stack to that location. Different memory types require distinc... | def _pop(self, pop_type, val=None):
if pop_type == "pointer":
self._a_command("THIS" if val == "0" else "THAT")
self._c_command(dest="D", computation="A") # D=THIS|THAT
elif pop_type in ("this", "that", "local", "argument"):
mapping = {
"this": "T... |
def _read_sp(self, dest):
self._decrement_sp()
self._a_command("SP")
self._c_command(dest="A", computation="M")
self._c_command(dest=dest, computation="M")
def _c_command(self, computation, dest=None, jump=None):
first_half = f"{dest}={computation}" if dest else computation
... | This method performs a computation on the stack value by first loading the stack pointer (SP) into register D, then applying the given computation to D, and finally writing the result back to the stack pointer. | def _operate_one(self, computation):
self._read_sp("D") # D=*SP
self._c_command(dest="D", computation=computation)
# D=COMP
self._write_sp("D") |
def _read_sp(self, dest):
self._decrement_sp()
self._a_command("SP")
self._c_command(dest="A", computation="M")
self._c_command(dest=dest, computation="M")
def _c_command(self, computation, dest=None, jump=None):
first_half = f"{dest}={computation}" if dest else computation
... | This function computes a value using the provided 'computation' operation on the SP register's value. It first loads SP into D and A, applies the computation to D, then writes the result back to SP. The core task is to perform a register-based arithmetic/logic operation and store the result in SP. | def _operate_two(self, computation):
self._read_sp("D") # D=*SP
self._read_sp("A") # A=*SP
self._c_command(dest="D", computation=computation)
# D=comp
self._write_sp("D") |
def _read_sp(self, dest):
self._decrement_sp()
self._a_command("SP")
self._c_command(dest="A", computation="M")
self._c_command(dest=dest, computation="M")
def _c_command(self, computation, dest=None, jump=None):
first_half = f"{dest}={computation}" if dest else computation
... | This code implements a comparison operation between two values on the stack. It reads the top two values into registers, computes their difference, and uses conditional jumps to set the stack to 0 (equal) or -1 (not equal) based on the comparison result. Labels and jumps handle branching logic, with EQ/NE labels determ... | def _compare_two(self, jump):
cmp_label = next(self.cmp_label)
self._read_sp("D") # D=*SP
self._read_sp("A") # A=*SP
self._c_command(dest="D", computation="A-D")
# D=A-D
self._a... |
def _a_command(self, address):
self.assembly_lines += [
f"@{address}"
]
def _c_command(self, computation, dest=None, jump=None):
first_half = f"{dest}={computation}" if dest else computation
self.assembly_lines += [
f"{first_half}; {jump}"
if jump els... | This function generates assembly code to push a value onto the stack based on the specified memory segment type. It handles constants, pointers, segment registers (this/that/local/argument), temp, and static segments. For each type, it uses A and C commands to load the value into the D register, compute the correct add... | def _push(self, push_type, val):
if push_type == "constant":
self._a_command(val)
self._c_command(dest="D", computation="A") # D=VAL
elif push_type == "pointer":
self._a_command("THIS" if val == "0" else "THAT")
self._c_com... |
def _a_command(self, address):
self.assembly_lines += [
f"@{address}"
]
def _c_command(self, computation, dest=None, jump=None):
first_half = f"{dest}={computation}" if dest else computation
self.assembly_lines += [
f"{first_half}; {jump}"
if jump els... | This function generates assembly code to handle a function call in a virtual machine. It saves the return address, pushes frame pointers (LCL, ARG, THIS, THAT) onto the stack, adjusts the ARG and LCL pointers to set up the new stack frame, and jumps to the target function. The process ensures proper context preservatio... | def _call(self, functionname, call_functionname, num_args):
return_addr = f"{functionname}$ret.{next(self.return_address_label)}"
self._a_command(return_addr)
self._c_command(dest="D", computation="A")
self._write_sp("D") # *SP=returnAddr
self._a_command("L... |
def read_puzzle_board(filename):
with open(filename) as f:
board = [line.strip() for line in f]
return board
def run_backtracking_search(csp):
return backtrack({}, csp)
def make_board(puzzle_board, assignment):
board = []
for i in range(len(puzzle_board)):
board.append([])
fo... | The code solves a puzzle by reading a board from a file, converting it into a Constraint Satisfaction Problem (CSP), applying backtracking search to find a solution, and printing the resulting solved board row by row. | def run_program(filename):
puzzle_board = read_puzzle_board(filename)
csp = Csp(puzzle_board)
result = run_backtracking_search(csp)
board = make_board(puzzle_board, result)
for row in board:
print(''.join(row)) |
def generate_dataList(scaleX = 2.0, scaleY = 0.8):
dataList = []
x = []
y = []
for i in range(2000):
temp = random.random()
x.append(temp*scaleX*np.pi)
sin_part = np.sin(temp * scaleX * np.pi) + scaleY * random.random() - (scaleY / 0.5)
cos_part = np.cos(temp * scaleX/100... | The code's main task is to iteratively optimize parameters using a delta calculation function (`delta_para`) to fit a hypothesis model to generated data. It updates parameters in each iteration, visualizes the hypothesis results with a colormap, and displays the final output after 9 iterations. The process involves gen... | def main():
# Hypothesis([1., 2., 3.], [2, 3, 3])
parameters = [2,3,3]
# data_list = [[1,2,3,4,5],[2,3,4,5,6]]
# Hypothesis_Offset(data_list, parameters)
# Jacobian(data_list[0], parameters)
scaleX = 4.0
scaleY = 0.8
data_list = generate_dataList(scaleX, scaleY)
parameters = [1, 0... |
def get_initial_mean_theta_pairs(data_list, classes_expect_to_divide):
'''
:param data_list:
:param classes_expect_to_divide: This is how many parts you want to get for the final division result
:return:
'''
new_mean_pairs_list = [] # store seperate $classes_expect_to_divide$ number pairs of ... | This code implements the Expectation-Maximization (EM) algorithm for clustering data, likely image pixels. It initializes cluster parameters (means and thetas), iteratively assigns data points to clusters based on probabilities, updates cluster parameters using grouped data, and visualizes cluster assignments as images... | def Expectation_Maximization_clustring(data_list, classes_expect_to_divide):
mean_pair, theta_pair = get_initial_mean_theta_pairs(data_list, classes_expect_to_divide)
print(mean_pair)
print(theta_pair)
possibility_of_all_instance = calculate_the_possibility(data_list, mean_pair, theta_pair, classes_expe... |
def startWrite(self):
pass
def writeFillRect(self, x, y, w, h, c):
x, y = self._rotateCoordinates(x, y)
if self.rotation in (1, 3):
w, h = h, w
if self.rotation in (1, 2):
x -= w - 1
if self.rotation in (2, 3):
y -= h - 1
(self.ipm.fill... | (The code defines a method `fillRect` that initiates a drawing operation by calling `startWrite`, then draws a filled rectangle at coordinates `(x, y)` with width `w`, height `h`, and color `c` using `writeFillRect`, and finally finalizes the operation with `endWrite`. The primary task is to render a filled rectangle o... | def fillRect(self, x, y, w, h, c):
self.startWrite()
self.writeFillRect(x, y, w, h, c)
self.endWrite() |
def http_get(url):
import usocket as socket
import ussl as ssl
af = socket.AF_INET
proto = socket.IPPROTO_TCP
socktype = socket.SOCK_STREAM
socket_timeout = 10 # seconds
res = ""
scheme, _, host, path = url.split("/", 3)
#print("scheme: %s, host: %s, path: %s" % (scheme, host, path)... | The code fetches weather forecast data from an API, reads the Inkplate's temperature and battery levels, combines this information into a string, and displays it on a 1-bit e-ink display. It handles power-on resets by clearing the screen and formats the output with temperature in Fahrenheit and battery voltage, then up... | def main(reset_cause):
from soldered_inkplate10 import Inkplate
import machine
#print ("Debug: Starting fetching data")
#response = http_get("http://micropython.org/ks/test.html")
# If you were to do a GET request to a different page, change the URL here
# See https://www.weather.gov/d... |
def fillRect(self, x, y, w, h, c):
self.startWrite()
self.writeFillRect(x, y, w, h, c)
self.endWrite()
def width(self):
return self._width
def height(self):
return self._height | The main task of the code is to fill the entire screen with a specified color by calling the fillRect method with coordinates starting at (0, 0) and dimensions matching the screen's width and height, using the provided color parameter 'c'. | def fillScreen(self, c):
self.fillRect(0, 0, self.width(), self.height(), c) |
def startWrite(self):
pass
def writeFastVLine(self, x, y, h, c):
if self.rotation in (1, 3):
self._writeFastHLine(x, y, h, c)
return
self._writeFastVLine(x, y, h, c)
def endWrite(self):
pass | The main task of the code is to efficiently draw a vertical line on a display by initiating a write operation, executing a fast vertical line drawing command with coordinates (x, y), height (h), and color (c), then finalizing the write process to ensure proper rendering. | def drawFastVLine(self, x, y, h, c):
self.startWrite()
self.writeFastVLine(x, y, h, c)
self.endWrite() |
def startWrite(self):
pass
def writeFastHLine(self, x, y, w, c):
if self.rotation in (1, 3):
self._writeFastVLine(x, y, w, c)
return
self._writeFastHLine(x, y, w, c)
def endWrite(self):
pass | The code defines a method `drawFastHLine` that initiates a write operation, draws a horizontal line using the `writeFastHLine` method with parameters `x`, `y`, `w` (width), and `c` (color), then finalizes the write process. Its primary task is to efficiently render a horizontal line on a display or graphics context by ... | def drawFastHLine(self, x, y, w, c):
self.startWrite()
self.writeFastHLine(x, y, w, c)
self.endWrite() |
def read_page(self, page_index: int) -> bytes:
"""
Read page at index
:param page_index: Index of page from which it will be read
:return: Page in bytes
"""
self.current_disk_operations += 1
self.disk_operations += 1
with open(self.path, "rb") as database:... | The main task of the code is to add a new record to a specified page in a file, managing potential overflow when the page exceeds its size limit. It updates record counts, handles special dummy records, and returns whether the file needs reorganization based on overflow page constraints. Debugging outputs track operati... | def add_record(self, record: GradesRecord, page_index: int) -> bool:
"""
Add new record to page at index
:param record: New record to be added
:param page_index: Page number where the record should be inserted to
:return: True if file should be reorganized, False otherwise
... |
def clear_database(self) -> None:
"""
Remove contents in database path
:return: None
"""
open(self.path, "w").close()
def initialize_empty_pages(self, number_of_pages: int = INITIAL_NO_OF_PAGES) -> None:
"""
Initialize main area with empty pages
:param num... | The main task of the code is to initialize a database system by loading configuration parameters, setting up overflow handling, clearing the database, initializing empty pages, and adding a dummy record. It also initializes counters for tracking disk operations and records, preparing the database for data storage and m... | def __init__(self, database_path: str, overflow_path: str):
global MAX_OVERFLOW_PAGE_NO
global ALPHA
with open(CONFIG_PATH, "r") as json_config:
CONFIG = json.load(json_config)
MAX_OVERFLOW_PAGE_NO = CONFIG["MAX_OVERFLOW_PAGE_NO"]
ALPHA = CONFIG["ALPHA"]
self.... |
def getFile(self, *args, **kwargs):
if kwargs['menuOption'] == 'Open':
ftypes = 'Comma-separated Values (*.CSV);; Tab-separated Values (*.TSV, *.TXT)'
elif kwargs['menuOption'] == 'Import':
ftypes = 'JavaScript Object Notation (*.JSON);; Microsoft Excel Spreadsheet (*.XLSX)'
... | The main task of the code is to initialize a GUI application for managing a book archive. It sets up interactive fields for inputting book details (title, author, genre, format, etc.), a table to display archived books, and menu options for file operations (open, save, import), data analysis, and report generation. The... | def __init__(self):
super(UI, self).__init__()
#Global Variables
self.DEFAULT_SAVE_PATH = os.path.expanduser('~\Documents')
self.FILE_SAVE = '' #str
self.FILE_ACTIVE = '' #str
self.DATAFRAME_IN = DataFrame(None)
self.DATAFRAME_OUT = DataFrame(None)
self.DE... |
def _start_momentum_generator(self) -> np.array:
new_momentum = np.array([normalvariate(0, m**0.5) for m in self.momentum_gen_Normal_cov])
return new_momentum
def _leap_frog_step(self, start_position, start_momentum):
end_position = np.array([x for x in start_position], dtype="float64") #x
... | This function performs a Metropolis-Hastings sampling step in a Hamiltonian Monte Carlo (HMC) framework. It generates a new momentum, advances the position via a leap-frog integrator, evaluates acceptance probability, updates the Markov chain with the new state if accepted, and tracks total iterations and acceptance co... | def sampler(self, **kwargs):
start_position = self.MC_sample[-1]
start_momentum = self._start_momentum_generator()
end_position, end_momentum = self._leap_frog_step(start_position, start_momentum)
accept_bool = self._MH_rejection_step(start_position, start_momentum, end_position, end_mom... |
def instantiate_graph_features():
'''
because we iterate over subgraphs and get features individually, it helps to have a dictionary to sum up
graph features throughout the process - instantiating beforehand to set most features to zero for summing
:return: a dictionary of features
'''
features ... | This function calculates graph features, including node counts and subgraph statistics, for a given networkx graph. It checks connectivity: if connected, it computes non-isolated nodes and small-world features; if disconnected, it splits into subgraphs, counts non-isolated nodes across subgraphs with more than 3 nodes,... | def get_graph_statistics(graph):
"""
Calculate features from a graph
:param graph: networkx graph
:return: dictionary of features
"""
features = instantiate_graph_features()
if nx.is_connected(graph):
features['Non-isolated Nodes'] = len(graph.nodes)
return (get_small_world_f... |
def get_correlation_features(corr_df, feature_dict, prefix=''):
"""
Function to put correlations (already computed) into the feature return.
in this function instead of a correlation numpy array , we have to pass a correlation pandas dataframe to preserve the names of the rows
:param corr_df: pandas dat... | The function extracts features from an ICA signal file by calculating signal variances, generating correlation-based graph features (if enabled), and computing graph statistics at specified thresholds. It returns a dictionary containing variance metrics, correlation features, and threshold-dependent graph properties li... | def ICA_graph_feature_extraction(ica_file, thresholds, valid_regions, add_correlation_features=False):
"""
take an ICA file from UKBiobank and return a dictionary of features from this file
:param ica_file: a space delimited file of signals from each ICA region, an example is provided in utilities
:para... |
def get_correlation_features(corr_df, feature_dict, prefix=''):
"""
Function to put correlations (already computed) into the feature return.
in this function instead of a correlation numpy array , we have to pass a correlation pandas dataframe to preserve the names of the rows
:param corr_df: pandas dat... | The function extracts signal variance features from brain region time series data and optionally computes network/correlation features using correlation matrices and graph statistics at specified thresholds. It returns a dictionary containing region-specific variance metrics and threshold-dependent network properties i... | def atlas_time_series_feature_extraction(time_series_df, thresholds=[], add_network_features=False,
add_correlation_features=False):
"""
Function that calculates signal variance of regions of the brain as extracted from brainnetome labeled areas
:param time_series_df... |
def GetUserPage(self, username) -> requests.Response:
user_url = f"https://twitcasting.tv/{username}/"
page = self.session.get(user_url)
if page.headers.get('Set-Cookie', '').find('tc_ss=deleted') > -1:
print("Logged out by server, session stored in cookies file is no longer valid")
... | The code initializes a class to authenticate a Twitcast user, retrieve stream data, and prepare necessary tokens/URLs. It uses provided cookies/credentials to fetch user pages, handle password submission, extract session IDs, and gather stream information, token, and PubSub URL for real-time streaming access. | def __init__(self, UserInput) -> None:
# Input TwitcastStream.py Userinput object
self.userInput = UserInput
self.session = requests.Session()
self.session.cookies = self.userInput["cookies"] or requests.cookies.RequestsCookieJar()
user_page = self.GetUserPage(self.userInput["us... |
def add_book(file):
new_title = input("Enter the title: ")
new_author = input("Enter the author: ")
new_genre = input("Enter the genre: ")
new_page = input("Enter the number of page: ")
new_notes = input("Enter the notes: ")
fields = ["Title", "Author", "Genre", "Pages", "Notes"]
fields_di... | The code defines a menu-driven interface for managing a book list stored in a CSV file. It allows users to add, search, delete, print, edit books, calculate total pages read, or exit. Based on user input, it calls corresponding functions to perform tasks, ensuring interaction until a valid option is chosen or the menu ... | def menu():
book_list = "book_list.csv"
print("1. Add book")
print("2. Search books")
print("3. Delete book")
print("4. Print books")
print("5. Edit book")
print("6. Total pages read")
print("0. exit menu")
selection = input()
if selection == "1":
add_book(book_list)
... |
def _drawBase(self, page: int):
for i, date in enumerate(self.dates):
x = self.GAP * (2 * i + 1) + (self.CARD_WIDTH * i)
y = self.HEIGHT - self.GAP - self.CARD_HEIGHT
bgColor = Colors.DARK_CHARCOAL if i == page else Colors.RAISIN_BLACK
self.drawRoundedRectangle(x,... | The `drawChart` method renders a chart based on the specified `view` parameter. It sets the page and view, draws a base layout, displays the view title at the center, and conditionally renders temperature, precipitation, or wind graphs by calling respective methods depending on the `view` value. | def drawChart(self, page: int, view: str) -> None:
self.page = page
self.view = view
self._drawBase(page)
self.drawText(self.WIDTH / 2, self.HEIGHT / 8, view, font_size=15)
if view == Views.TEMPERATURE:
self.drawTemperatureGraph()
elif view == Views.PRECIPITAT... |
def write_header(self, header, root):
if not header or not header.files:
return
header_el = self._create_element(root, "Header")
files_el = self._create_element(header_el, "Files")
file_el = self._create_element(
files_el, "File"
) ##doubt about the root ... | This code generates an XML markup file for a topic, updating creation/modification metadata, and structuring elements like ReferenceLinks, Labels, BimSnippet, DocumentReferences, and RelatedTopics. It uses minidom to create a hierarchical XML document from topic data, saving it as "markup.bcf" in the specified director... | def edit_topic(self, topic):
if not topic.creation_date:
topic.creation_date = datetime.utcnow().isoformat()
topic.creation_author = self.author
else:
topic.modified_date = datetime.utcnow().isoformat()
topic.modified_author = self.author
self.doc... |
def generate_key(message, key):
if len(key) > len(message):
return key[:len(message)]
i = 0
while True:
if len(key) == len(message):
break
if message[i] == ' ':
i += 1
else:
key += message[i]
i += 1
return key
def getCipherT... | The main task of the code is to implement a cipher encryption/decryption process using a key, followed by a dictionary attack to attempt decryption. It takes user inputs for a message and key, generates an extended key, encrypts the message, decrypts it using the same key, and then tries to decrypt the ciphertext using... | def main():
message = input("Enter the message: ").upper()
key = input("Enter the key: ").upper()
key_full = generate_key(message, key)
cipher_text = getCipherText(message, key_full)
print("Cipher text generated =", cipher_text)
print('-'*24)
original_text = getOriginalText(cipher_text, k... |
def lineage_day_plot(df, dates_df, day_lineage_out):
merged_df = {}
df_lineages = get_lineage_info(df)
merged_df = pd.merge(df_lineages, dates_df, left_on='sample', right_on='sample')
# group rows that have the same sample id together
# group sample ids with the same date together
merged_df['no... | The code processes Freyja variant results and metadata to generate time-series stacked bar plots showing lineage and variant abundances over days, weeks, and months, saving outputs to specified paths. | def main(argv):
# step 0 get paths set up
freyja_results = argv[1]
edited_metadata_file = argv[2]
day_lineage_out = argv[3]
day_variant_out = argv[4]
week_lineage_out = argv[5]
week_variant_out = argv[6]
month_lineage_out = argv[7]
month_variant_out = argv[8]
df = pd.read_csv(fr... |
def set_up_sample_dictionary(input_dir, input_dict, output_dir, cores):
# set up the sample dictionary
input_info = {}
#### paired reads ####
to_copy = []
if len(input_dict["paired_end_libs"]) != 0:
paired_sample_dict = {}
ws_paired_reads = []
ws_paired_reads = input_dict["pa... | The code processes a configuration file to set up sample data, validate metadata against input files, and execute workflows via Snakefiles for data processing, using parameters specified in the config. | def main(argv):
config_file = argv[1]
print("Wrapper command recieved \n")
try:
fh = open(config_file)
config = json.load(fh)
fh.close()
except IOError:
msg = f"Could not read params file {config_file}"
sys.stderr.write(msg)
sys.exit(1)
except json.Jas... |
def encryptPassword(pw, salt=uuid.uuid4().hex):
return hashlib.sha256(salt.encode() + pw.encode()).hexdigest() + salt
def checkUser(name):
query = "SELECT username FROM users"
users = execQuery(query, "auth")
for i in users:
if i[0] == name:
return True
return False
def commitQuery(query, db):
cnx = connect... | The main task of the code is to register a new user by inserting their lowercase username, encrypted password, and unique salt into a database, then creating a user-specific database with their UID. It returns success if the username is available, or failure if it already exists. | def registerUser(request):
name = request["username"].lower()
pwenc = encryptPassword(request["password"])
if not checkUser(name):
query = "INSERT INTO users (username, password, salt) VALUES (\"{}\", \"{}\", \"{}\")".format(name, pwenc, uuid.uuid4().hex)
commitQuery(query, "auth")
query = "SELECT uid FROM use... |
def addFormHeadToHTML(html, *args):
auth = ""
for x in args:
auth = "<input type=\"hidden\" name=\"authkey\" value=\"{}\">\n".format(x)
return html + "<form method=\"post\" action=\"/\">\n" + auth
def getUserFromAuth(authkey):
query = "SELECT oid FROM authkeys WHERE uid = \"{}\"".format(authkey)
user = execQuery... | The main task of the code is to generate HTML form buttons for each table associated with a user's authentication key. It retrieves user-specific tables, creates submit buttons for each, and integrates them into the provided HTML structure along with form headers and footers. The function returns the modified HTML with... | def addTablesToHTML(html, authkey):
html = addFormHeadToHTML(html, authkey)
buttons = ""
uid = getUserFromAuth(authkey)
for t in getTables(uid):
t = t[0]
buttons += "<input type=\"submit\" value=\"{}\" name=\"openTable\"/>\n".format(t)
html += buttons
html = addFormFootToHTML(html)
return html |
def getUserFromAuth(authkey):
query = "SELECT oid FROM authkeys WHERE uid = \"{}\"".format(authkey)
user = execQuery(query, "auth")
return user[0][0]
def getTableContents(table, uid):
output = execQuery("SELECT SID,Website,User,Password,Comment FROM {}".format(table), "user_{}".format(uid))
return output
def decry... | The code generates an HTML form for a password table, displaying entries with fields for website, user, password, and comments. It includes buttons to update/delete entries, add new entries, and delete the entire table, with encrypted password handling and user authentication via authkey. | def printTableToHTML(table, authkey):
output = ""
uid = getUserFromAuth(authkey)
content = getTableContents(table, uid)
for x in content:
sid = x[0]
website = x[1]
user = x[2]
password = decryptStoredPassword(x[3], uid)
comment = x[4]
output = addFormHeadToHTML(output, authkey)
output += "<input type=... |
def getHTMLHead():
return "<!DOCTYPE html>\n<head>\n<title>Malns Passwordmanager</title>\n</head>\n<body>\n"
def addCreateTableButtonToHTML(html, authkey):
html = addFormHeadToHTML(html, authkey)
html += "<input name=\"text\">"
html += "<input type=\"submit\" value=\"{}\" name=\"{}\"/>\n".format("Add Folder", "addF... | The main task of the code is to generate an HTML document by combining predefined elements (head, buttons, tables) with dynamically added content from input arguments. It constructs an HTML string through sequential function calls, incorporating a "Create Table" button, line breaks, existing tables, and additional tabl... | def main(authkey, *args ):
html = getHTMLHead()
html = addCreateTableButtonToHTML(html, authkey)
html = addLinebreak(html)
html = addTablesToHTML(html, authkey)
html = addLinebreak(html)
for i in args:
html += printTableToHTML(i, authkey)
html += getHTMLFoot()
return html |
def checkPassword(name, pw):
query = "SELECT password FROM users WHERE username = \"{}\"".format(name)
data = execQuery(query, "auth")
salt = data[0][0][-32:]
pwenc = data[0][0]
if encryptPassword(pw, salt) == pwenc:
return True
return False
def generateAuthKey(name):
query = "SELECT uid FROM users WHERE usern... | The main task of the code is to authenticate a user by verifying their username and password. If successful, it generates an authentication key, registers it, and redirects to the main function with the key. If authentication fails, it displays a login page with a "Login failed!" message. | def loginUser(request):
name = request["username"]
pw = request["password"]
if checkPassword(name, pw):
key, oid = generateAuthKey(name)
registerAuthKey(key, oid)
return main(key)
return drawLoginPage("Login failed!") |
def forwardprop(self, X, activation_function='relU'):
"""
Implements the forward propagation algorithm for a neural network.
Parameters:
X (numpy.ndarray): Input data of shape (number of features, number of examples).
parameters (dict): Dictionary containing the parameters (weig... | This function implements batch gradient descent to optimize neural network parameters by iteratively updating weights using forward and backward propagation on shuffled mini-batches of data, tracking accuracy and loss metrics per epoch, and returning the optimized parameters after specified iterations. | def gradient_descent_batch(self, X, Y, max_iter, alpha, batchsize, actifunc):
"""
Optimizes the neural network parameters using gradient descent optimization algorithm.
This is the training loop of the nn , this is not the smartest way since it optimizez after every sample.
this could be... |
def classify(root, input):
correct = 0
for data in input:
if data[-1] == predict(root, data):
correct += 1
return correct / len(input)
def majority(data):
labelCount = countLabels(data, -1)
res = max(labelCount, key=labelCount.get)
return res | The function prunes a decision tree node by checking if converting it to a leaf node (using majority class) improves validation accuracy. If not, it retains the node's structure. It recursively traverses the tree, evaluating accuracy before/after pruning, and discards changes if accuracy decreases, thus preventing over... | def prune(node, root):
# current node is leaf
if node.label:
return
lessLeaf = True
greaterLeaf = True
# left is not a leaf node
if (node.less != None) & (node.less.label == None):
lessLeaf = False
prune(node.less, root)
# greater is not a leaf node
if (node.grea... |
def removeStopWords(data, stop):
result = []
for line in data:
newWords = []
words = line.split()
for w in words:
if w not in stop:
newWords.append(w)
result.append(newWords)
return result
def buildDict(wordList):
wordSet = set()
for line... | The main task of the code is to implement and evaluate a text classification model. It processes training and test data by removing stop words, builds a dictionary and word matrix, then calculates prediction accuracy using a custom `predict` function. It also compares this with a scikit-learn Multinomial Naive Bayes cl... | def main():
Utils.startTime()
xTrainWords = removeStopWords(Utils.xTrain, Utils.stop)
xTestWords = removeStopWords(Utils.xTest, Utils.stop)
dictList = buildDict(xTrainWords)
wordMatrix = buildMatrix(xTrainWords, dictList)
# predict
correct = 0
for i in range(len(xTrainWords)):
... |
def initialize_pieces(self):
for r in range(NUMBER_OF_ROWS):
for c in range(NUMBER_OF_COLUMNS):
if self.boardsquares[r][c] != EMPTY_IDENTIFIER:
if self.boardsquares[r][c] == BLACK_PAWN_IDENTIFIER and self.white_top == True:
self.boardpieces... | This code initializes a chess game environment by setting up the board configuration, game parameters (like AI mode, testing, and player turns), tracking game state variables (e.g., game end status, captures), and preparing for move calculations. It configures the board layout based on `white_top` and `testing` flags, ... | def __init__(self, type, white_top=False, ai=1, testing=False, boardsquares=[]):
self.ai = ai
self.testing = testing
self.white_top = white_top
self.currently_playing = WHITE_COLOR_IDENTIFIER
self.game_ended = False
self.show_end_screen = False
self.game_ended_rea... |
def check_queen_promotion(self, r, c):
"""
Queen promotion for white pawns
"""
if Helpers.is_pawn(self.boardpieces[r][c]) and (r == 0 and self.boardpieces[r][c].color == WHITE_COLOR_IDENTIFIER):
self.boardpieces[r][c] = ChessPiece(
WHITE_QUEEN_IDENTIFIER)
... | This function executes a move in a board game, handling piece movement, captures, king interactions, queen promotions, board updates, turn switching, and engine synchronization. It checks for captures, updates the board state, promotes queens if applicable, interacts with a chess engine (Stockfish), and manages game fl... | def make_move(self, r, c, r2, c2):
will_capture = False
if not Helpers.is_empty(self.boardpieces[r][c]):
will_capture = True
if not self.testing:
self.captures[self.currently_playing][self.boardpieces[r]
[c].id... |
def get_scores_by_threshold(self, distances=None, labels=None):
"""
Calculates scores as a function of threshold
:param distances: Distances to predict, and calculate score of
:param labels: True labels
:return: List of accuracy, precision, recall, F1 as a function of threshold.
... | This function performs 10-fold cross-validation on dataset distances/labels by iteratively training models to find optimal thresholds, evaluating test performance metrics (accuracy, precision, recall, F1) using these thresholds, and returning average scores across all folds. | def get_cross_validation_scores(self):
"""
Performs K-fold cross-validation on data.
:return: Average scores.
"""
kf = KFold(n_splits=10)
accuracy = 0
precision = 0
recall = 0
f_one = 0
# For each train, test
for train_index, tes... |
def job_classifier(spy_link):
'''
Extracts the job type and platform information from SpyglassLink.
Parameter:
spy_link (string): SpyglassLink used to filter the job_type and job_platform.
Returns:
job_type(string): It is a important keyword used while constructing url to access the ... | The function `get_testcase_frequency` analyzes a list of builds (`spylinks`) to count the frequency of failing test cases. It filters builds by zone (if specified) and checks cluster status. For successful clusters, it retrieves failed test cases, aggregates their occurrences in a dictionary, and sorts them by frequenc... | def get_testcase_frequency(spylinks, zone=None, tc_name = None):
"""
To get the testcases failing with its frequency
Args:
spylinks (list): list of builds which needs to be checked.
zone (list): List of the zones/leases that need to checked.
tc_name (list): list of testcase name.
... |
def check_ts_exe_status(spylink,jobtype):
'''
Checks conformance Test suite execution status.
Parameter:
spylink (string): SpyglassLink used to generate url to access logs of a job.
jobtype (string): Keyword used to construct url to access logs of a job.
Returns:
str: Status ... | The function `print_all_failed_tc` prints details of failed test cases and errors based on a job's execution status (FAILURE, SUCCESS, ABORTED, or ERROR). It retrieves failure data via `get_all_failed_tc` and `get_junit_symptom_detection_testcase_failures`, prints specific test failures, error messages, or abort notice... | def print_all_failed_tc(spylink,jobtype):
'''
Prints all the failed testcases.
Parameter:
spylink (string): SpyglassLink used to generate url to access logs of a job.
jobtype (string): Keyword used to construct url to access logs of a job.
Returns:
str: Status of test suite... |
def get_quota_and_nightly(spy_link):
'''
Gets lease/region where cluster is deployed and the nightly image used.
Parameter:
spy_link (string): SpyglassLink used to generate url to access logs of a job.
Returns:
lease(string): Acquired lease/region.
nightly(string): Nighlty im... | The function `get_brief_job_info` processes a list of builds to generate concise job summaries. It extracts build IDs, checks cluster and test statuses, filters by deployment zone, and handles sensitive data exposure. It constructs dictionaries with job details like CI name, lease status, test results (PASS/FAIL), and ... | def get_brief_job_info(build_list,prow_ci_name,zone=None):
"""
Gets brief information of all the jobs
Args:
build_list: list of builds
prow_ci_name: CI name
zone(string, optional): Cluster deployment zone
Return:
List(string): List of jobs with the brief information.
... |
def get_quota_and_nightly(spy_link):
'''
Gets lease/region where cluster is deployed and the nightly image used.
Parameter:
spy_link (string): SpyglassLink used to generate url to access logs of a job.
Returns:
lease(string): Acquired lease/region.
nightly(string): Nighlty im... | The function processes a list of builds to display detailed job information, including links, statuses, and quota details. It filters builds by deployment zone, counts successful deployments and e2e tests, checks for sensitive data exposure, and reports cluster creation outcomes. It also removes builds not matching the... | def get_detailed_job_info(build_list,prow_ci_name,zone=None):
"""
Prints detailed information of all the jobs.
Args:
build_list: list of builds
prow_ci_name: CI name
zone(string, optional): Cluster deployment zone
"""
if isinstance(build_list,str):
print(build_... |
def _to_user_id(user_identifier):
try:
return int(user_identifier)
except ValueError:
return None
def photos(request, user_id=None):
if not request.user.is_authenticated:
return redirect(reverse('login') + '?next=' + request.path)
if request.method == 'POST':
return post... | This function retrieves user details by either user ID or username. It checks if the user is authenticated; if not, it redirects to the login page with a return URL. If authenticated, it attempts to convert the identifier to a user ID. If successful, it returns the user's photos view; otherwise, it returns the general ... | def user_details(request, user_identifier):
"""
Take either a user_id or a username and return the appropriate user view for that user if it exists
:param request:
:param user_identifier: either a user_id or username of a particular user
:return: the user view for the identified user
"""
if ... |
def load_json(self, json_path):
with open(json_path, "r") as f:
js = f.read()
self.json_data = json.loads(js)
return self.json_data
def get_distortion(self, img_path=None):
if img_path is None:
w, h = self.img.shape[:2]
newcameramtx, roi = cv2.getO... | The main task of the code is to load camera parameters and coordinates from a JSON file, handle missing data by initializing defaults, validate coordinate counts, flip image coordinates, and display them if requested, finally calculating a projection parameter. It ensures proper setup for camera calibration or image pr... | def load_params(self, json_path, camera_num, show=True):
self.camera_num = camera_num
self.json_data = self.load_json(json_path)
self.img = cv2.imread(self.img_path)
try:
self.dist = np.asanyarray(self.json_data["dists"][str(camera_num)])
self.mtx = np.as... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.