dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def create_near_sorted_list(length, max_value, swaps):
L = create_random_list(length, max_value)
L.sort()
for _ in range(swaps):
r1 = random.randint(0, length - 1)
r2 = random.randint(0, length - 1)
swap(L, r1, r2)
return L
def insertion_sort(L):
for i in range(1, len(L)):
... | The code measures and compares the execution times of insertion sort, bubble sort, and selection sort on nearly sorted lists of varying sizes. It runs each sorting algorithm multiple times, records the time taken for each run, and returns three lists containing the time measurements for analysis. | def exp3(n):
insert_times=[]
bubble_times=[]
select_times=[]
for i in range(0,n,1):
L = create_near_sorted_list(5000, 100, i)
L2 = L.copy()
L3 = L.copy()
start= timeit.default_timer()
insertion_sort(L)
end=timeit.default_timer()
insert_times.a... |
def purgeExports(dirToRemove):
try:
shutil.rmtree(dirToRemove)
except OSError as e:
print("Error: %s - %s." % (e.filename, e.strerror))
def pickRandomIndex(index, limit):
return random.randint(index, limit - 1)
def calculateTimeseriesFitness(self, control, datasetFiles, c... | The code generates a specified number of time series pairs by randomly selecting file indices from a dataset, calculating their fitness, and purging prior exports to ensure each pair is uniquely processed and stored. | def findTimeseriesPairs(self, changeDataset, numberOfPairs):
if changeDataset:
self.purgeExports(self.exports)
datasetFiles = os.listdir(self.path)
for i in range(numberOfPairs):
pairFound = False
while not pairFound:
self.p... |
def convertRawToSax(word_size, alphabet_size, files):
return_list = []
dat_list = []
for f in files:
df = pd.read_csv(f, sep=',', names=["id", "time", "price", "volume"])
dat = df['price'].to_numpy()
dat_list.append(dat)
sax = convert_to_sax(dat, word_size, alphabet_size)
... | This function evaluates the compression efficiency and lower bound tightness of SAX (Symbolic Aggregate Approximation) representations of time series data. It converts raw time series into SAX formats, calculates compression ratios, compares SAX-based distance lower bounds to actual distances, and outputs metrics like ... | def handler(word_length, alphabet_size, change_dataset=False):
word_size, alphabet_size = word_length, alphabet_size
sax1, sax2, dat1, dat2, od = convertRawToSax(word_size, alphabet_size, fetchTimeseriesFiles(change_dataset))
print("Tightness of Lower bound: ", calculateSaxDistance(sax1, sax2, alphabet_size... |
def PCD_WriteRegister(self,
_reg, #The register to write to. One of the PCD_Register enums.
_dat #The value to write.
):
self.Write(self.addr, _reg, _dat)
def PCD_SetRegisterBitMask(self,
reg, ... | (PCD_CommunicateWithPICC executes a PCD command to communicate with a PICC, sending data via FIFO, waiting for completion, and handling responses. It initializes registers, transmits data, checks for errors (timeout, collision, CRC), validates received data, and returns status codes. If requested, it verifies CRC_A and... | def PCD_CommunicateWithPICC(self,
command, # The command to execute. One of the PCD_Command enums.
waitIRq, # The bits in the ComIrqReg register that signals successful completion of the command.
sendData, ... |
def PCD_ClearRegisterBitMask(self,
reg, # The register to update. One of the PCD_Register enums.
mask # The bits to clear.
):
tmp = self.PCD_ReadRegister(reg)
self.PCD_WriteRegister(reg, tmp & (~mask))... | The main task of the code is to select a PICC (Proximity Integrated Circuit Card) by its UID using anti-collision and cascade level handling. It processes UID bits in stages, constructs SELECT/ANTICOLLISION commands, manages CRC validation, and resolves collisions to uniquely identify a card, supporting multi-level UID... | def PICC_Select(self,
uid, # Pointer to Uid struct. Normally output, but can also be used to supply a known UID.
validBits # The number of known UID bits supplied in *uid. Normally 0. If set you must also supply uid->size.
):
uidComplete... |
def _extractIdFromURL(self, url: str) -> str:
"""
A URL is of the form:
```url
http://metadata.un.org/thesaurus/{id}
```
This function extracts the ID from the URL.
Parameters
----------
`url` : `str`
The URL to extract the ID from
... | The main task of the code is to crawl meta topics by fetching JSON data from URLs generated from provided IDs, extract topic IDs and labels, add meta-topic nodes and edges to a graph network, and return the set of all discovered topic IDs. | def crawlMetaTopics(self, ids: Set[str]) -> Set[str]:
"""
Crawls the meta topics and adds them to the graph.
Parameters
----------
`ids` : `Set[str]`
The list of meta topic IDs
Returns
-------
`Set[str]`
The set of topic IDs
... |
def _extractIdFromURL(self, url: str) -> str:
"""
A URL is of the form:
```url
http://metadata.un.org/thesaurus/{id}
```
This function extracts the ID from the URL.
Parameters
----------
`url` : `str`
The URL to extract the ID from
... | This function crawls topic data from URLs, extracts labels, clusters, and subtopics, then adds topic nodes to a graph with connections to clusters and subtopics. It returns a set of subtopic IDs while logging progress and node/edge counts if verbose. | def crawlTopics(self, ids: Set[str]) -> Set[str]:
"""
Crawls the topics and adds them to the graph.
Parameters
----------
`ids` : `List[str]`
The list of topic IDs
Returns
-------
`Set[str]`
The set of subtopic IDs
"""
... |
def _extractIdFromURL(self, url: str) -> str:
"""
A URL is of the form:
```url
http://metadata.un.org/thesaurus/{id}
```
This function extracts the ID from the URL.
Parameters
----------
`url` : `str`
The URL to extract the ID from
... | The function crawls subtopics by downloading JSON data for given IDs, extracts node attributes (labels, clusters) and relationships, adds nodes/edges to a graph, and returns discovered subsubtopic IDs. It processes each JSON to create subtopic nodes, links them to clusters and related topics, and collects IDs of newly ... | def crawlSubtopics(self, ids: Set[str]) -> Set[str]:
"""
Crawls the subtopics and adds them to the graph.
Parameters
----------
`ids` : `Set[str]`
The list of subtopic IDs
Returns
-------
`Set[str]`
The list of subsubtopic IDs
... |
def getMetaTopicsIds(self) -> Set[str]:
"""
This function parses the home page of the Thesaurus and returns the
meta topics ids. It doesn't add nodes to the graph - it only returns
the ids.
Returns
-------
`Set[str]`
The set of meta topic ids
... | The main task of the code is to crawl the UNBIS Thesaurus by systematically retrieving meta topics, topics, and subtopics, recursively exploring all levels of hierarchical data, and constructing a graph represented as JSON. It logs progress, handles errors, and ensures database cleanup on failure, returning the final g... | def crawl(self) -> JSON:
"""
Crawls the whole UNBIS Thesaurus and returns the graph JSON.
It first gets the meta topics, then the topics, and finally
the subtopics, by getting each JSON file for each topic and
parsing its content.
Returns
-------
`JSON`
... |
def _get_k_nodes(self, node: ParseTreeNode, level=0) -> List[ParseTreeNode]:
if level == self.K:
return [node]
k_nodes = []
for branch in node.branches.values():
nodes = self._get_k_nodes(branch, level=level + 1)
for node in nodes:
k_nodes.appe... | The code identifies unique morphs in a parse tree by comparing probability distributions of nodes, avoiding duplicates via O(N²) checks. It updates each node's morph identifier, logs unique morph counts, and computes transitions for further processing. | def process_morphs(self, root: ParseTreeNode):
"""Computes morphs in a tree and updates ParseTreeNode.morph with the morph number of that node"""
root.update_probabilities()
l_nodes = self._get_k_nodes(root)
# Unfortunately, comparing morphs takes O(N^2) time
# Didn't want to h... |
def download_NHIS(outpath='raw_data/nhis/'):
zipurl = "https://ftp.cdc.gov/pub/Health_Statistics/NCHS/Datasets/NHIS/2019/adult19csv.zip"
download_zip(zipurl, outpath + '2019/', "adult19.csv")
zipurl = 'https://ftp.cdc.gov/pub/Health_Statistics/NCHS/Datasets/NHIS/2018/samadultcsv.zip'
download_zip(zipurl... | The function `process_download_target` selects and executes specific download tasks based on the `download_option` parameter. If the option is 'nhis', 'util', 'nadac', or 'all', it triggers corresponding functions to download NHIS data, drug utilization data, NADAC pricing data, or diabetes-related products, respective... | def process_download_target(download_option):
"""
Select targets for download
"""
if download_option in ['nhis', 'all']:
download_NHIS()
if download_option in ['util', 'all']:
download_drug_utiliztion()
if download_option in ['nadac', 'all']:
download_nadac_pricing()
# ... |
def clean_NHIS(path='raw_data/nhis',
outfile='artifacts/nhis_cleaned.csv'):
if os.path.exists(outfile):
return
print('cleaning: ', path)
# Cleaning code here
nhis19 = pd.read_csv('raw_data/nhis/2019/adult19.csv')
nhis18 = pd.read_csv('raw_data/nhis/2018/samadult.csv')
nhi... | The function `process_clean` executes specific data-cleaning tasks based on the `cleaning_option` input. If the option is 'nhis', 'nadac', 'diap', 'util', or 'all', it triggers corresponding cleaning functions (e.g., `clean_NHIS`, `clean_nadac_pricing`). If 'mmeds', it merges medications. The 'clean' option separately ... | def process_clean(cleaning_option):
if cleaning_option in ['nhis', 'all']:
clean_NHIS()
if cleaning_option in ['nadac', 'all']:
clean_nadac_pricing()
if cleaning_option in ['diap', 'all']:
clean_diabetes_products()
if cleaning_option in ['util', 'all']:
clean_drug_utiliza... |
def alert_fire(payload, timestamp):
# print("\n\nEnter alert_fire")
# Fetching all the data from FD database and storing in a variable
retrieve = "SELECT * FROM FireDepartmentDB;"
cursor.execute(retrieve)
data = cursor.fetchall()
# print("\n\n Fire Data = ", data)
# Fetching the emergency detai... | The main task of the code is to handle emergency alerts from IoT sensors by notifying relevant emergency services (fire, police, EMS) and users, while logging incident details (timestamp, response time) for each detected alert type (fire, flood, wind disaster, security alarm, critical button). The function processes JS... | def on_message(client, userdata, msg):
print('------------------------------------------------------------------------------------------------------------------')
print('Start')
startTime = datetime.now()
print('--------------------------------------------------------------------------------------------... |
def create_db(name: str='tidepool', cfg: str='cfg.ini'):
cfg = helpers.load_config(cfg)
client = pymongo.MongoClient(cfg['db_string'])
return client[name]
def verify_instrument(instrument, db=create_db()):
return instrument in list_instruments(db)
def generate_file_path(instrument: str, before: datetime... | The main task of the code is to create a binary file containing processed data for a specified instrument from a database. It verifies the instrument's validity, generates a file path, checks for existing files (with optional overwrite), and iteratively gathers, processes, and appends data between specified time ranges... | def create_binary(instrument: str, db=create_db(), file: str = None, before: datetime.datetime = None, after: datetime.datetime = None, force=False):
if not verify_instrument(instrument, db):
raise ValueError(f'Invalid instrument "{instrument}"')
if file is None:
file = generate_file_path(instr... |
def makeGrid(self):
central_widget = QGroupBox(self)
# central_widget.setFixedSize(450, 450)
self.setCentralWidget(central_widget)
self.cell_size = (45, 45)
self.outer_grid_layout = QGridLayout()
self.outer_grid_layout.setSpacing(0)
self.outer_gr... | The code initializes a Sudoku game interface with features like difficulty selection, timer, hint functionality, and solution checking. It sets up the game board, solves the puzzle, and manages user interactions through buttons and labels. The timer tracks playtime, while the 'Check Solve' button validates the user's s... | def __init__(self, given_difficulty, loaded_account = None):
super().__init__()
self.hint_mode = False
self.testing_val = False
self.error_cell_list = {}
if loaded_account is not None:
self.account_data = loaded_account
self.logged_in = T... |
def returnCell(self, col : int, row : int) -> QSpinBox:
"""
Returns the cell of position row, col in the sudoku grid.
Args:
Returns:
QSpinBox: cell of position row, col
"""
inner_row = row // 3
inner_col = col // 3
inner_group_box = ... | This method checks for value conflicts in a grid (e.g., Sudoku) by comparing the current cell's value with its row and column siblings. If duplicates are found, it marks cells as conflicting, updates an error list, and adjusts visual styles. If no conflicts, it removes prior conflict markings. | def checkConflicting(self):
self.conflicted = False
error_cell_siblings = []
if self.testing_val:
sender = self.sender()
cell_name = sender.objectName()
cell_parent = sender.parent().objectName()
x_factor, y_factor = map(int, cell_par... |
def get_available_batteries(self, house: House) -> tuple[list[list[int]], list[Battery]]:
"""
Returns gridpoints batteries and cables that are available.
"""
list_grids = []
list_batteries = []
for battery in self.district.batteries:
if self.battery_capacity[b... | The main task of the code is to connect a house to the nearest available battery by checking compatible positions, reducing battery capacity, and recording the connection in the solution. It identifies available batteries, locates the closest grid position, and verifies cable compatibility before establishing a route a... | def set_connection(self, house: House, houses: list[House]) -> None:
"""
Set the connection between house and battery.
"""
if self.get_available_batteries(house) != []:
list_grids, list_batteries = self.get_available_batteries(house)
position = house.get_closest_b... |
def check_capacity(self, house: House, battery: Battery) -> bool:
"""
Returns True if the max capacity of the house is less than the available
capacity of the given battery.
"""
if self.battery_capacity[battery] > house.maxoutput:
return True
return False
def ... | The main task of the code is to connect a house to a suitable battery by checking if the house's position is already connected to any battery, verifying battery capacity, and updating the solution if a valid connection is established. It returns True if successful, False otherwise. | def set_connection_block_given_battery(self, house: House, position: list[int], list_batteries: list[Battery]) -> bool:
"""
Sets the connection between block and a given battery.
"""
battery = None
for key in list_batteries:
for list in self.battery_cable[key]:
... |
def set_screen(maze ,episode = 0, h=34):
pygame.init()
screen = pygame.display.set_mode((1800,1000))
set_screen_qtable(screen)
set_screen_board(screen , maze , episode)
def update(self, st , at ,rt , st1):
'''updates q table : st = n_house , at = n_action , x of house / rt is reward / st1 = next... | This function simulates an agent navigating a maze for one episode. It randomly selects moves, updates the Q-table using current state, action, reward, and next state, and visualizes progress. The loop terminates if the goal is reached, the score drops below a threshold, or the user quits. | def run_episode(self , maze , n_episode = 1, score_limit = -1 ):
set_screen(maze.env)
while not maze.reached_goal() :
#if n_episodes -a <n_episodes : break
pygame.display.update()
for event in pygame.event.get():
# close it and exit the program
... |
def is_request(self):
return self.request_id() and self.method()
def request_id(self):
return (
self.rpcValue.meta.get(RpcMessage.TagRequestId) if self.is_valid() else None
)
def caller_ids(self):
return (
self.rpcValue.meta.get(RpcMessage.TagCallerIds) if self.is... | The main task of the code is to generate an `RpcMessage` response object from a valid request. It first validates that the current instance represents a request, then constructs a response by copying the request's ID and caller IDs into a new `RpcMessage` object, which is returned as the response. | def make_response(self):
if not self.is_request():
raise ValueError("Response can be created from request only.")
resp = RpcMessage()
resp.set_request_id(self.request_id())
resp.set_caller_ids(self.caller_ids())
return resp |
def find_position(code):
if code == [1, 0, 1]:
return 1
elif code == [0, 0, 1]:
return 2
elif code == [0, 1, 1]:
return 3
elif code == [0, 1, 0]:
return 4
elif code == [1, 1, 0]:
return 5
elif code == [1, 0, 0]:
return 6
else:
return 0
... | The code performs motor health monitoring by analyzing sensor data (temp_data) to detect stalls. It updates the motor's position, calculates RPM and filtered frequency, and triggers a shutdown if no position change is detected for 500ms. It also tracks position changes, computes motor reluctance, and periodically calcu... | def health_check(temp_data):
global last_position
global position_hold_time
global position_cntr
code = [0,0,0]
for i in range(1,4):
if(temp_data[i] > 2500):
code[i-1] = 1
else:
code[i-1] = 0
position = find_position(code)
if(last_position != position)... |
def _get_rpm(self, pos_hold_time):
freq = (100000/((get_us() - pos_hold_time)*6))
self.freq_count[0].append(get_elapsed_us(self.INITIAL_US))
self.freq_count[1].append(freq)
return freq
def running_filter(self, data):
x_k = self.kX1 + kDt * self.kV1
r_k = data - x_k
... | The code performs a health check on a motor by analyzing sensor data thresholds, tracking positional changes, calculating RPM and filtered frequencies, detecting stalls, and logging diagnostic metrics like reluctance and RMS current. It returns 1 for normal operation or 0 if a stall is detected, ensuring real-time moto... | def health_check(self, data):
code = [0,0,0]
for i in range(1,4):
if(data[i] > 2500):
code[i-1] = 1
else:
code[i-1] = 0
position = self._find_position(code)
if(self.last_position != position):
if(self.last_position != 0)... |
def get_us():
now = datetime.datetime.now()
return (now.minute*60000000)+(now.second*1000000)+(now.microsecond)
def pwm_control():
global pwm_current
if(pwm_current < int(pwm_target)):
pwm_current = pwm_current + 1
print("PWM: {}".format(pwm_current))
pi_pwm.ChangeDutyCycle(pwm_curre... | The code reads ADC data from multiple channels, processes it, and logs timestamps and values to a CSV file. It continuously controls PWM signals, monitors system health, and terminates after a specified duration or on interruption, ensuring motor ramp-down. | def read_adc():
global initial_us
global position_hold_time
global data
global data_single_revolution
temp_data = np.uint32([0,0,0,0,0,0,0,0,0])
adc_reading = 0x0
index = 0x0
dat_16bit = 0x0
pwm_counter = 0
initial_us = get_us()
my_functions.getAnalogInAll_InitialSend()
p... |
def SetWindowTitle(self):
title = self.maze.name
if not self.saved:
title = title + "*"
title = title + " " + str(self.maze.cellnb_x) + "x" + str(self.maze.cellnb_y)
if self.maze.wall_density > 0:
title = title + " ({}%)".format(int(100*self.maze.wall_density))... | The code generates a maze by iteratively adding random walls until full density is achieved, updating the GUI in real-time with each addition. It initializes a robot once the maze is complete, managing visual feedback and state changes throughout the process. | def NewMaze(self):
self.status = "Generating..."
self.SetWindowTitle()
self.maze.CleanUp()
wall_density = self.maze.GenerateRandom_Init()
self.DrawMaze()
while wall_density < 1:
wall_density = self.maze.GenerateRandom_AddWall()
[i,j,f]=self.ma... |
def SetWindowTitle(self):
title = self.maze.name
if not self.saved:
title = title + "*"
title = title + " " + str(self.maze.cellnb_x) + "x" + str(self.maze.cellnb_y)
if self.maze.wall_density > 0:
title = title + " ({}%)".format(int(100*self.maze.wall_density))... | This code tests a robot's sensor functionality in a 12x12 maze with predefined walls. It initializes the maze, positions the robot, and simulates sensor readings at specific angles to detect wall distances. The results are visualized by drawing lines from the robot to detected walls, validating sensor accuracy and coll... | def Test_Sensor(self):
# create a 12x12 maze
self.status = "Test"
self.SetWindowTitle()
Maze_cellnb_x = 12
Maze_cellnb_y = 12
self.maze = Maze(Maze_cellnb_x, Maze_cellnb_y)
self.robot = Robot(self.maze)
self.canvas.destroy()
self.InitTKWindow()
... |
def NewMaze(self):
self.status = "Generating..."
self.SetWindowTitle()
self.maze.CleanUp()
wall_density = self.maze.GenerateRandom_Init()
self.DrawMaze()
while wall_density < 1:
wall_density = self.maze.GenerateRandom_AddWall()
[i,j,f]=self.ma... | This code defines a `KeyPressed` method that handles keyboard input events. It maps specific keys to actions: 'q' quits the application, 'N'/'C' control maze generation steps, 'n' generates a new maze, 's' solves it, 't' runs tests, 'r'/'e' control robot operations. The method enables interactive control of a maze-solv... | def KeyPressed(self, event):
key = event.char
if key == 'q':
self.tkapp.quit()
elif key == 'N': # to test step by step maze generation
self.NewMaze_Init()
elif key == 'C': # to test step by step maze generation
self.NewMaze_Continue()
elif key ... |
def default_app_data_dir():
APPNAME = "bonnie"
if sys.platform == 'win32':
return os.path.join(os.environ['APPDATA'], APPNAME)
else:
return os.path.expanduser(os.path.join("~", "." + APPNAME))
def _authorize_session(self):
self.s = requests.Session()
self.s.headers.update({'content-type':'appli... | This code initializes an object to handle quiz submission by setting up parameters, authorizing a session, packaging files into a zip archive, and submitting them to a server via a POST request, with error handling for access issues and server responses. | def __init__(self, gtcode, quiz_name,
filenames = [],
exclude = False,
environment = 'production',
provider = 'gt',
app_data_dir = None,
max_zip_size = 8388608):
self.gtcode = gtcode
self.quiz_name = quiz_name
... |
def firstPlayer():
myPawns = {'P1': 'P1_pawn1', 'P2': 'P1_pawn2', 'P3': 'P1_pawn3', 'P4': 'P1_pawn4'}
stepsLeftForPawn = {'P1': (maxNumOfSteps - player1['P1_pawn1']), 'P2': (maxNumOfSteps - player1['P1_pawn2']), 'P3': (maxNumOfSteps - player1['P1_pawn3']), 'P4': (maxNumOfSteps - player1['P1_pawn4'])}
print(... | The main task of the code is to run a Ludo game where two players take turns, with the game restarting if a player's move is invalid. It checks for a winner after each turn and ends the game when either player wins, displaying the winner's message and terminating the loop. | def mainLudoGame():
start = input('Press Enter to start the game>>>>')
if start == '':
print('WELCOME TO LUDO GAME VERSION 2: THE FIRST PLAYER WILL START>>\n__________\n')
playGame = True
while playGame == True:
playerOne = firstPlayer()
while playerOne == 1:
print(... |
def calc_new_vels(self):
# using bug 0
# -> propagate to next expected position using current velocities
# -> if next position is close enough to a collision point, turn CCW away from it
# -> otherwise, continue forward (aka to your goal position)
# NEED TO MODIFY TO ACCOUNT FOR ANGULAR VELOCITY (SL... | The main task of the code is to calculate new wheel velocities based on collision points, current position, and body velocity by transforming world velocities to body frame and then to wheel-specific velocities, returning the updated values for control or simulation purposes. | def get_new_wheel_velocities(self):
# using the new collision points, current position, and current body velocity,
# calculate new wheel velocities
self.calc_new_vels()
self.new_body_velocities = self.world2body()
self.new_wheel_velocities.data = self.body2wheel()
return self |
def wheel2body(self, w_vels):
# WHEEL TO BODY VELOCITY
# vels = [vel motor A, B, C, D] of each wheel as a float
# output: q_dot = [x_dot,y_dot,theta_dot]
H_0_pinv = np.array([[ 1/4, 1/4, 1/4, 1/4],
[-1/4, 1/4, 1/4, -1/4],
[... | This function processes a message in a simulated environment by converting wheel velocities to body and world coordinates, updating the robot's state (self.q), generating collision points, adding them to the list, printing collision points, retrieving new wheel velocities, publishing data, and storing the current state... | def sim_handle_msg(self, msg):
# SIM ENVIRONMENT: takes no sensor data,
w_vels = self.new_wheel_velocities.data
self.wheel2body(w_vels)
self.body2world(self.body_vels)
self.q = self.propagate_q()
self.new_cPoints = self.sim_cPoints()
self.add_new_points()
print("list of collision points... |
def wheel2body(self, w_vels):
# WHEEL TO BODY VELOCITY
# vels = [vel motor A, B, C, D] of each wheel as a float
# output: q_dot = [x_dot,y_dot,theta_dot]
H_0_pinv = np.array([[ 1/4, 1/4, 1/4, 1/4],
[-1/4, 1/4, 1/4, -1/4],
[... | The code processes sensor data (wheel velocities, distance, IR states) to update the robot's world state (x,y,theta), compute collision points, filter duplicates, and propagate new velocities. It then publishes updated data for display and robot control, storing the new state for future reference. | def handle_msg(self, msg):
# shouldn't the velocities get changed at the end, using prev velocities
# to measure current sensors?
# msg format: msg = [velA, velB, velC, velD, distance, ir_states]
w_vels = [round(vel,4) for vel in [msg.velA, msg.velB, msg.velC, msg.velD]]
# input wheel velocities, o... |
def open_text(output_filename: Optional[str], mode: str) -> Iterable[TextIO]:
"""Open the output file, or the appropriate standard stream
if output_filename is None.
Throws if there is an error opening the output file"""
if mode not in ["w", "a", "r"]:
raise ValueError(f"Invalid text file mode ... | The main task of the code is to process input text by splitting it into sections, normalizing characters, generating n-grams, handling optional character typing and extra keys, filtering rare characters, calculating probabilities, and saving structured n-gram data as JSON. It uses parallel processing for efficiency and... | def create_ngrams(
max_ngram_class: int,
type_characters: bool,
add_extra_keys: bool,
rare_character_threshold: int,
input_filename: Optional[str],
output_filename: Optional[str],
) -> int:
try:
bar: tqdm
with open_text(input_filename, "r") as input_file:
chars = ... |
def multi_head_attention(x, c_attn, c_proj, n_head):
x = linear(x,
w=c_attn['w'],
b=c_attn['b'])
qkv = np.split(x, 3, axis=-1)
qkv_heads = []
for elt in qkv:
qkv_head_split = np.split(elt, n_head, axis=-1)
qkv_heads.append(qkv_head_split)
causal_mask ... | The code implements a transformer block that processes input `x` through multi-head attention and feed-forward networks (FFN) with layer normalization and residual connections. It applies attention using parameters from `attn`, normalizes with `ln_1`, then adds the attention output to `x`. Next, it processes `x` throug... | def transformer_block(x, mlp, attn, ln_1, ln_2, n_head):
x = x + multi_head_attention(layer_norm(x, g=ln_1['g'], b=ln_1['b']),
c_attn=attn['c_attn'],
c_proj=attn['c_proj'],
n_head=n_head)
x = x + ffn(layer_norm(x,... |
def get_keyboard():
global Barcodes,key_press,press_start,df_customer,customer
if Barcodes:
if keyboard.is_pressed('-') and key_press == False:
Barcodes.pop()
key_press = True
press_start = time.time()
if time.time()-press_start > 0.5:
key_press = False
if B... | This code generates and updates a table with barcode and customer data, handling states like insufficient funds, resetting idle states after 60 seconds, and clearing temporary customer displays after 15 seconds. It yields the table for output, managing data flow between barcode input, customer info, and state transitio... | def generate():
global Barcodes,df,customer,finish_start,data_saved,notEnoughtMoneyState,showCustomState,showcustom_start,xBarcodes,start_nobody_time
print('Barcodes',Barcodes)
get_keyboard()
table = create_table(df,Barcodes)
if customer != '':
save_data()
if data_saved ... |
def read_excel(filename, sheet_name="Sheet1"):
# try except for file / path
try:
wb = excel.Workbooks.Open(filename)
except com_error as e:
if e.excepinfo[5] == -2146827284:
print(f'Failed to open spreadsheet. Invalid filename or location: {filename}')
else:
... | This function copies data from a specified Excel sheet to a destination file/sheet, optionally filtering columns based on a list of required column names. It handles default values for destination parameters, determines column indices from the source sheet, and writes the filtered data to a new Excel sheet, returning t... | def copy_excel(source_file, source_sheet, destination_file="", destination_sheet="",req_cols=[]):
if destination_file == "":
destination_file = source_file
if destination_sheet == "":
destination_sheet = source_sheet + " copy"
old_wb, old_ws = read_excel(source_file, source_sheet)
... |
def write_excel(filename, sheet_name="Sheet1",sheet_obj=None,req_cols=[]):
if isinstance(filename,str):
# try except for file / path
try:
wb = excel.Workbooks.Open(filename)
except com_error as e:
if e.excepinfo[5] == -2146827284:
print(f'Existing file... | This function creates an Excel pivot table comparing old and new datasets by copying required columns, formatting sheets with headers/colors, generating pivot tables for each column in list_of_columns, adding analysis metrics, and saving the output file. It handles file cleanup, data copying, pivot table creation, and ... | def create_excel_pivot():
# Delete old file if already exist if remove_output_if_exist is True
if remove_output_if_exist:
if os.path.isfile(output):
try:
os.remove(output)
print(f"{output} removed successfully")
except OSError as error:
... |
def _q(angle,vector):
vx,vy,vz = normalizeV(vector)
halfangle = angle/2
cos = math.cos(halfangle)
sin = math.sin(halfangle)
return (cos,vx*sin,vy*sin,vz*sin)
def rotq(vertex,q):
vx,vy,vz = vertex
#qw,qx,qy,qz = normalizeQ(q)
qw,qx,qy,qz = normalizeQ(q)
x,y,z = _rotq(vx,vy,vz,qw,qx,qy... | The function `genq(phi, alpha)` constructs a composite rotation quaternion by first applying a Z-axis rotation (using `_q(phi, (0,0,1))`), then rotating the Y-axis vector to a new direction (Y') using this rotation. It subsequently applies a rotation of `-alpha` around this new Y' axis, and combines the two rotations v... | def genq(phi,alpha):
#alpha = (np.pi/2) - theta
qA = _q(phi,(0,0,1)) # Z-rotation
uvector = rotq((0,1,0),qA) # Y -> Y'
qB = _q(-alpha,uvector) # Y'-rotation
return multQ(qB,qA) |
def standardButton(self, master, textField, com, co, ro):
"""Define standard tkinter-Button format"""
button = Button(master, text=textField, font=('Arial', 12), width=25, height=1, bg="white", borderwidth=4,
relief="groove", command=com)
button.grid(column=co, row=ro)
... | The function reads OPC UA values from a server, manages data recording over a specified duration or indefinitely, updates a progress bar, handles exceptions by retrying failed tags, and periodically writes data to CSV files. It supports stopping the recording, logs errors, and ensures scan intervals are maintained. | def readOPC_values(self, opc, recordingTime_s, scanInterval_s, lab_aktiv, lab_tags, lab_server):
"""Read values over the initiated OPC connection"""
dataBank = []
startTime = time.time()
# Make it possible to change color of progressbar
s = ttk.Style()
s.theme_use('defau... |
def find_in_grid(master, column, row):
"""Find an element (like a label) in master grid and return it"""
for child in master.children.values():
info = child.grid_info()
if info['row'] == str(row) and info['column'] == str(column):
return child
return None... | The main task of the code is to handle user-initiated server connection attempts by updating the UI to reflect connection status, attempting to connect to the selected server, and handling errors if the connection fails. It resets visual indicators, displays "Connecting..." feedback, establishes the connection via self... | def chooseServer(self, id, instance, label_config):
"""Connects to the server the user clicked on"""
try:
self.find_in_grid(self.master, label_config[2], label_config[3]).destroy()
except Exception:
pass
for i in range(0, len(self.serverNames)):
self... |
def writeError(self, error):
"""Write error message to external error-log file"""
s = ''
# If file exists, read it
try:
f = open('Error-log.txt', 'r')
s = str(f.read())
s += str(error) + '\n'
f.close()
except:
pass
... | This function records OPC server data over a specified duration with a defined scan interval, validates input, updates UI elements, converts the data to CSV format, saves it to a file, and attempts to display a plot. It handles errors, adjusts scan intervals if necessary, and manages temporary file storage for the reco... | def startRecording(self, duration_lab, scanInterval_lab, button, label_config, button_config, lab_tags, lab_server):
"""Read the values from OPC server and save them in a CSV string
Parameter:
Label which contains the duration
Label which contains the scan interval
St... |
def standardLabel(self, master, textField, co, ro):
"""Define standard tkinter-Label format"""
lab = Label(master, bg="white", text=textField, font=('Arial', 12, 'bold'))
lab.grid(column=co, row=ro)
return lab
def writeError(self, error):
"""Write error message to external error... | The main task of the code is to scan the system for running OPC servers (e.g., KEPServerEx) using the OpenOPC library, display the found servers as interactive buttons in a GUI, and handle errors like no servers found. It creates labels, buttons, and updates the interface to show server names, enabling users to select ... | def scanOPCServer(self, listrow, listcol, label_config):
"""Scan the system for running OPC servers like KEPServerEx"""
print('Searching for OPC servers on user system')
label = self.standardLabel(label_config[0], label_config[1], label_config[2], label_config[3])
try:
self.... |
def standardLabel(self, master, textField, co, ro):
"""Define standard tkinter-Label format"""
lab = Label(master, bg="white", text=textField, font=('Arial', 12, 'bold'))
lab.grid(column=co, row=ro)
return lab
def testTags(self, opc, tagArray):
"""Try to read all tags independen... | This function initializes the second GUI screen for OPC connections, displaying server status, validating tags, determining minimal scan intervals, and setting up user inputs for recording duration and scan rate to start data acquisition. | def screen_2(self):
"""Second screen of GUI"""
self.master.destroy()
self.master = Tk()
self.master.title('OPC Connections')
self.master.config(bg='white')
tmp_lab = self.standardLabel(self.master, self.serverName, 0, 1)
tmp_lab.config(font=('Arial', 12, 'bold')... |
def standardLabel(self, master, textField, co, ro):
"""Define standard tkinter-Label format"""
lab = Label(master, bg="white", text=textField, font=('Arial', 12, 'bold'))
lab.grid(column=co, row=ro)
return lab
def standardButton(self, master, textField, com, co, ro):
"""Define s... | This code initializes the first GUI screen of an OPC Tag Reader application. It creates a window titled 'Tag Reader', adds a bold title label, and a 'Search Server' button. The button triggers the scanOPCServer method via a lambda function, which likely discovers OPC servers. The Tkinter main loop starts the GUI. | def screen_0(self):
"""First half of first GUI screen"""
print('Init program')
self.master = Tk()
self.master.title('Tag Reader')
self.master.config(bg='white')
label = self.standardLabel(self.master, 'OPC Tag Reader', 0, 0)
label.config(font=('Arial', 12, 'bold'... |
def encode_faces(self):
# Each subfolder's name becomes our label (name)
known_faces = []
known_names = []
for name in os.listdir(self.KNOWN_FACES_DIR):
# Next we load every file of faces of known person
# Load an image
image = face_recognition.load_im... | This code processes a video to detect faces and potential violence. It captures frames, resizes them, and uses face recognition to identify known faces. When a frame limit is reached, it checks for violence using a detection model. If violence exceeds a threshold, it analyzes faces against known encodings. The loop con... | def process_video(self):
video_capture = cv2.VideoCapture(self.video_file)
known_face_encodings, known_face_names = self.encode_faces()
# Initialize some variables
frames = []
small_frames = []
can_analyze = False
f_count = 0
while video_capture.isOpened... |
def get_categorical_base_data() -> List[List[str]]:
# This acts a a base for the different edge cases considered for the type of data that is used when constructing
# a Categorical. The other Categorical data functions, such as the one for bytes and numerics, derive from this table.
# If new edge cases are ... | This function generates and returns a list of categorical data based on specified modes. It dynamically selects and combines different data types (base, numeric, multikey) using helper functions, depending on the input `category_modes` parameter, which can be a single mode or a list of modes. If no modes are provided, ... | def get_categorical_data_factory_method(
category_modes: Optional[Union[CategoryMode, List[CategoryMode]]] = None
) -> List[List[Any]]:
if category_modes is None: # return all types of categories
return get_categorical_base_data() + _get_categorical_numeric_data() # + _get_categorical_multikey_dat... |
def to_riptable():
input_cols = [
bool_col(name="Boolean", data=[True, False]),
byte_col(name="Byte", data=(1, -1)),
char_col(name="Char", data='-1'),
short_col(name="Short", data=[1, -1]),
int_col(name="Int", data=[1, -1]),
long_col(name="Long", data=[1, -1]),
... | The main task of the code is to execute three functions—`to_riptable()`, `to_table_datetime()`, and `to_table_categorical()`—which likely convert or process data into specific table formats, handling datetime and categorical data types. The code orchestrates these transformations sequentially to prepare or structure da... | def main():
to_riptable()
to_table_datetime()
to_table_categorical() |
def post_new_assignment_todos(api_wrapper: ApiWrapper):
assignments = api_wrapper.get_unscheduled_assignments()
for assignment in assignments:
# generate and post todo for each assignment
todos = generate_assignment_todos(assignment, api_wrapper)
for todo in todos:
api_wrappe... | The code's main task is to manage and update an Airtable todo system by deleting existing todos, posting new assignment tasks, adding office hour reminders, and reassigning overdue items, ensuring the task list remains current and organized. | def run():
print("Started!")
api_wrapper = ApiWrapper(AirtableApiClient())
api_wrapper.api_client.delete_all_todo()
post_new_assignment_todos(api_wrapper)
post_new_office_hour_reminders(api_wrapper)
reassign_overdue_assignment_todos(api_wrapper)
print("Finished, yayy!") |
def _interpret_shortcut(self, r, train_request):
journey_list = r["journeys"]
# Find the ones that are express trains and have stra enroute
filtered_list = list(filter(lambda x: "legs" in x.keys() and
len(x["legs"]) == 1 and "transportation" in x["legs"][0]
and x["legs"][0]["transportatio... | This function processes a trip request to filter and extract relevant train journey details. It uses a shortcut flag to determine filtering logic, extracts departure/arrival times, validates against requested times, and constructs Train objects for matching journeys. The result is a list of filtered train trips meeting... | def _interpret_trip_request(self, r, train_request, shortcut):
if (shortcut):
try:
filtered_list = \
self._interpret_shortcut(r, train_request)
except IndexError:
filtered_list = []
# No shortcut finding needed. Just make sure o... |
def _tree_policy(self,v:Node):
while not v.is_terminal(): #TODO: Figure out how the root node would behave here.
if not v.is_fully_expanded(self.sim_env):
return self._expand(v)
else:
v = self._selection(v) # Traverse the search tree using UTC to select t... | The code performs Monte Carlo Tree Search (MCTS) by conducting `m` simulations from the current state. Each simulation involves deep copying the environment, traversing the tree to a leaf node, executing a default policy to obtain a reward, and backpropagating the reward to update node values. After all simulations, it... | def search(self):
"""
Do the MCTS by doing m simulations from the current state s.
After doing m simulations we simply choose the action that maximizes the estimate of Q(s,a)
"""
for k in range(self.m):
self.sim_env = deepcopy(self.env) # make a deep copy of of the o... |
def pick_action(self, action_vector):
action_vector = self.softmax(action_vector)
legal_action_mask = np.array(self.state.legal_actions_mask())[52:52+self.action_space.shape[0]]
masked_action_vector = action_vector*legal_action_mask
action = np.argmax(masked_action_vector)
retur... | The code executes a step in a reinforcement learning environment by selecting an action, applying it to the state, checking if the current phase is terminal (phase 3), and returning a terminal reward if so. If not, it lets an adversary act, rechecks for termination, and returns a default reward otherwise. The main task... | def step(self, action_dist):
action = self.pick_action(action_dist)
self.state.apply_action(action+52)
if self.state.current_phase() == 3:
return self.calculate_terminal_reward(action)
# opposing team action
self.adversary_step()
if self.sta... |
def copyToClipBoard(self, colorType):
if colorType == 0:
self.ui.colorComboBox.setCurrentIndex(colorType)
global content
content = self.ui.RgbLabel.text()
cb = QApplication.clipboard()
cb.clear(mode=cb.Clipboard)
cb.setText(content, mode = ... | This code initializes a GUI application with a main window, setting up UI components like labels, buttons, and image display. It configures tooltips, icons, and styles for widgets, connects buttons to functions for copying color codes, browsing files, and generating colors. A timer tracks mouse position to display colo... | def __init__(self, parent=None):
QMainWindow.__init__(self)
self.ui = Ui_Form()
self.ui.setupUi(self)
self.ui.PictureLabel.setCursor(Qt.CrossCursor)
self.setFixedHeight(680)
self.setFixedWidth(1016)
self.ui.rgbCopy.setToolTip("Copy content to clipboard")
... |
def parse_new_moves(moves):
move_file_moves = parse_move_file();
return move_file_moves;
def init_boards():
boards = [];
for board in range(9):
boards.append(init_classic_board());
return boards;
def apply_move(boards, move):
# copy board
new_boards = copy_boards(boards);
board_n... | The main task of the code is to determine the game outcome after applying a sequence of moves to a board state. It processes moves, updates the game board, checks for a win by the AI ("I win!"), opponent victory, or a draw, then logs the result accordingly. | def end_game_print(moves):
moves += parse_new_moves(moves);
boards = init_boards();
for move in moves:
boards = apply_move(boards, move);
if wongtron_global_win(boards):
log(f"I win! Muahahahahaaaa");
elif opp_global_win(boards):
log(f"Opponent wins. ):");
elif global_tie... |
def apply_move(boards, move):
# copy board
new_boards = copy_boards(boards);
board_number = move.board_number;
cell_number = move.cell_number;
cell_state = CellState.WONG if move.wongtron else CellState.OPP;
new_boards[board_number][cell_number] = cell_state;
return new_boards;
def wongtron_... | This function implements a minmax algorithm with alpha-beta pruning to determine the optimal move in a game, evaluating board states recursively. It checks for terminal conditions (win/loss/tie), respects depth limits, and prunes branches based on dominant scores to optimize performance while adhering to a time deadlin... | def minmax(boards, last_move, deadline, depth, levels_dominant_score):
result_boards = apply_move(boards, last_move);
# check time
if time() > deadline:
return INVALID_SCORE;
# win
elif wongtron_global_win(result_boards):
return W_SCORE;
# loss
elif opp_global_win(r... |
def build_picos_vars(self):
for v in self.list_vars:
if not(self._get_pic_var_from_sage_var(v)):
self._sage_to_pic[str(v)] = picos.RealVariable(str(v))
def build_equality_constraints(self):
pic_lhs = map(self._get_pic_expr_from_sage_expr, self.sage_equality_constraints)
... | This code initializes a Semidefinite Programming (SDP) problem using the PICOS library. It sets up variables, equality/inequality constraints, PSD matrices, and an objective function. The method debug prints problem dimensions, maps constraints to PICOS formats, and constructs the optimization problem structure for sol... | def __init__(self, list_vars, equality_constraints, inequality_constraints,
psd_matrices, objective, debug=False):
if debug:
print('SDP with {} variables, involving {} matrices of sizes:'\
.format(len(list_vars), len(psd_matrices)))
print(list(map(lamb... |
def get_path (input):
pipgrid = [[0 for _ in range(len(input[0])+2)] for _ in range(len(input)+2)]
org_x,org_y = 0,0
for i in range(len(input)):
for j in range(len(input[i])):
if input[i][j] != '.':
pipgrid[i+1][j+1] = input[i][j]
if input[i][j] == 'S':
... | The code processes an input grid by expanding it into a larger grid, mapping paths, and identifying isolated cells. It creates a padded grid, transfers non '.' elements, generates a path map, and constructs a larger grid with connections. Using DFS, it marks reachable areas and counts remaining isolated cells (value 1)... | def solver2 (input):
pipgrid = [[0 for _ in range(len(input[0])+2)] for _ in range(len(input)+2)]
for i in range(len(input)):
for j in range(len(input[i])):
if input[i][j] != '.':
pipgrid[i+1][j+1] = input[i][j]
maped_pipgrid = get_path(input)
print_map_2(maped_pipg... |
def average_time(list_of_times):
total_sum = sum(list_of_times)
return total_sum / len(list_of_times)
def measure_lin_times(sorted_list):
key =random.choice(sorted_list)
times = timeit.repeat(lambda:lin_search(sorted_list,key), number = 100, repeat = 1000)
return times
def measure_bin_times(sorted_... | The code measures and compares the average time complexity of linear and binary search algorithms on lists of varying sizes (1000 to 32000 elements). It generates scatter plots with linear and logarithmic fits, printing the derived equations to illustrate the theoretical time complexities (O(n) for linear search, O(log... | def main():
list_sizes = [1000, 2000, 4000, 8000, 16000, 32000]
list_1000 = [i for i in range(1000)]
list_2000 = [i for i in range(2000)]
list_4000 = [i for i in range(4000)]
list_8000= [i for i in range(8000)]
list_16000= [i for i in range(16000)]
list_32000 = [i for i in range(32000)]
... |
def get_dos(filename='dos_input'):
"""read dos from file"""
# read without header and use whitespace
dos = pd.read_csv(filename, header=None, delim_whitespace=True)
dos = dos.astype(float)
dos = dos.to_numpy()
# vasp use state/eV
dos_data = [dos[:, 0], dos[:, 1]/volume]
E = dos[:, 0]
... | This code calculates thermodynamic quantities (free energy, chemical potential) from DOSCAR data across a temperature range, computes Fermi energy, and saves results to CSV files for analysis. | def main():
free = np.zeros(T_num+1)
temp = np.zeros(T_num+1)
[dos_data, E, dos] = get_dos('DOSCAR')
K0 = do_integral(E, dos)
minus_K0 = -1*K0
K2 = do_integral(E, minus_K0)
[Ef, Ef_index, n0] = fermienergy(E, dos, ne, volume, K0)
Tmin = 0
Tmax = 600
[mu_data, mu_index_data] = g... |
def read_poscar(filename, cart=False):
"""
read from the poscar
args:
filename(str): path of POSCAR
cart(bol): transform atomic position into cartesian coordinate
return:
dict: dictionary include all the information of POSCAR
"""
with open(filename, 'r') as file:
... | The function `distorted_poscar` generates a distorted crystal structure by applying a percentage of atomic displacement from a given distorted POSCAR to a nondistorted POSCAR. It reads both POSCAR files, calculates the displacement vectors between corresponding atoms, scales these vectors by the specified percentage, a... | def distorted_poscar(nondistorted, distorted, percentage):
"""
args:
nondistorted(str): filename of nondistorted poscar
distorted(str): filename of distorted poscar
percentage(float): the distorted percentage
e.g. 0.1, shift atoms from nondistorted to distorted
in 10% dis... |
def speak(self, command: str):
print(command)
self.engine.say(command)
self.engine.runAndWait()
def listen(self, errMsg: str = ""):
if errMsg:
self.speak(errMsg)
self.device_index = 1
for index, mic in enumerate(sr.Microphone.list_microphone_names()):
if "Headset" in mic:
sel... | The code initializes a speech recognition and text-to-speech system, loads saved settings (rate, voice ID) from storage, configures the TTS engine, greets the user, and enters a loop to listen for voice input and process responses. | def __init__(self):
self.r = sr.Recognizer()
self.engine = pyttsx3.init()
data = storage.getItem("assistant", ["engine"])
if not data:
# Restart or Ask to download again
terminal.shutDown(0)
pass
if "rate" in data.keys():
self.engine.setProperty("rate", 150)
if "voice_id"... |
def parse_args():
parser = argparse.ArgumentParser("Fuzzer runner")
parser.add_argument('--afl-debug-log', required=False, action='store_true', help='More verbose output from AFL')
parser.add_argument('--fuzzer-debug-log', required=False, action='store_true', help="More verbose log from QEMU")
parser.a... | The main task of the code is to parse command-line arguments, execute corresponding functions based on the 'command' parameter (e.g., running QEMU, test cases, fuzzers, or generating test cases), and optionally delete a specified 'drive' file if provided. It handles different operations through conditional logic and en... | def main():
args = parse_args()
print(args)
if args.command == 'qemu':
run_qemu(args, None)
elif args.command == 'testcase':
run_testcase(args)
elif args.command == 'tcgen':
run_tcgen(args)
elif args.command == 'fuzzer':
run_fuzzer(args)().communicate()
if a... |
def isCostLower(b, a):
if(b.k1 < a.k1):
return 1
elif(a.k1 == b.k1):
if(b.k2 < a.k2):
return 1
else:
return 0;
else:
return 0;
def TopKey():
'''
Returns top vertex as the vertex class type
'''
global priorityQueue
if(len(prior... | This function computes the shortest path in a grid using a priority queue and dynamic updates. It iteratively checks if the current node's cost is lower than the start node's or if the cost estimates need adjustment. When valid, it updates neighboring cells' costs and propagates changes to adjacent vertices, ensuring o... | def ComputeShortestPath():
global priorityQueue
global s_start
while(isCostLower(TopKey(),CalculateKey(s_start)) or
rhs[s_start.x][s_start.y] != g[s_start.x][s_start.y]):
k_old = TopKey()
cell_index = getIndex(k_old.x,k_old.y)
rospy.loginfo('size = '+ str(len(priorit... |
def getRow(index):
return int(index % width)
def getCol(index):
return index//width
def initialize():
global priorityQueue
global s_goal
priorityQueue = []
heapq.heapify(priorityQueue) #heapify
global km
km = 0
for i in range(0,width):
for j in range(0,height):
... | The code implements the DStarLite algorithm to compute the shortest path on a 2D grid from a start to a goal position, using a costmap for obstacle detection. It initializes grid parameters, processes the costmap to define traversable areas, and executes path computation. The function returns the list of indices repres... | def d_star_lite(start_index, goal_index, width_, height_, costmap, resolution, origin, grid_viz):
'''
Performs DStarLite's shortes path algorithm search on a costmap with a given start and goal node
'''
global s_start
global s_goal
global width
global height
global rhs
global GRID
... |
def load_data(knob='default', replication=1, model='baseline', train_test='test',ihdp_dir='idhp'):
"""
loading train test experiment results
"""
file_path = 'result/{}/{}/'.format(ihdp_dir,knob)
data = load(file_path + '{}/{}/0_replication_{}.npz'.format(replication, model, train_test))
return... | The code processes simulation results from different models and knobs to calculate and compare their performance metrics. It loads data for each repetition, computes mean absolute errors (MAE) for naive and TMLE estimators, and aggregates results into dictionaries containing average MAE and standard errors for each kno... | def make_table(train_test='train',
ihdp_dir='idhp',
truncate_level=0.01):
dict, tmle_dict = {}, {}
knob_list = sorted(glob.glob('result/{}/*'.format(ihdp_dir)))
knob_list = [ aa.split('/')[-1] for aa in knob_list]
print("knob_list::",knob_list)
for knob in list(... |
def verify_type(name, var, ver_func, *args, **kwargs):
try:
var = ver_func(var, *args, **kwargs)
except TypeError as exc:
raise TypeError(f'"{name}" {exc}')
return var
def verify_value(name, var, ver_func, *args, **kwargs):
try:
var = ver_func(var, *args, **kwargs)
except Val... | This function positions a ChaCha keystream generator at a specific byte offset by calculating the corresponding block and byte index, seeking to the block, and advancing the stream if necessary. It validates the offset, computes block/index, seeks to the block, and if the index is non-zero, generates the keystream bloc... | def seek_offset(self, nonce: int, offset: int):
# Validate offset input
offset = verify_type('offset', offset, verify_int)
offset = verify_value('offset', offset, verify_int, 0, U64_MAX)
# Determine keystream block and index
block = offset // CHACHA_BLOCK_SIZE
index = of... |
def verify_type(name, var, ver_func, *args, **kwargs):
try:
var = ver_func(var, *args, **kwargs)
except TypeError as exc:
raise TypeError(f'"{name}" {exc}')
return var
def memxor(dst, src, size):
for i in range(size):
dst[i] ^= src[i]
def chacha_block(input, stream):
# Load i... | This code performs ChaCha stream cipher encryption/decryption on input data. It XORs the data with keystream bytes generated from the ChaCha state, handling both full blocks and partial blocks. The function updates the cipher's internal state and index, ensuring continuous processing of data chunks while maintaining cr... | def update(self, data: bytearray):
# Validate input data
data = verify_type('data', data, verify_bytes_mutable)
data_size = len(data)
offset = 0
stream_size = CHACHA_BLOCK_SIZE - self.index
# Crypt data using any available keystream bytes
if data_size > 0 and st... |
def format_numerically(date):
return date.strftime("%d/%m/%Y")
def format_verbosely(date):
extramark = get_extramark(date)
return date.strftime(f"%d<sup>{extramark}</sup> %B %Y")
def format_both(date):
f_sub = format_numerically(date)
f_verb = format_verbosely(date)
return f"{f_sub}<br>{f_verb}" | The main task of the code is to format a given date according to a specified style. It checks the `choice_str` parameter and calls corresponding helper functions: `format_numerically`, `format_verbosely`, or `format_both` based on the input. If the input is invalid, it raises an exception. The function acts as a dispat... | def format_option(date,choice_str):
if choice_str == "numerically":
return format_numerically(date)
if choice_str == "verbosely":
return format_verbosely(date)
if choice_str == "both":
return format_both(date)
raise Exception("Invalid choice string") |
def sentence_length(sentence):
"""
Finds the sentence length
:param sentence: str
:return: int
"""
return len(sentence.split())
def unnormalised_np_length(doc):
"""
Finds the sum length of noun phrases in a sentence
:param doc: Doc
:return: int
"""
np_length = 0
for x... | The code extracts syntactic features from a sentence's dependency tree, including raw and normalized lengths of noun phrases (NP), verb phrases (VP), and maximum tree depth. It calculates sentence length, unnormalized NP/VP lengths, normalizes them relative to sentence length, and returns these metrics as a list for li... | def dependency_tree_feature_extraction(sentence):
doc = nlp(sentence)
s_length = sentence_length(sentence)
np_length = unnormalised_np_length(doc)
vp_length = unnormalised_vp_length(doc)
normalised_np_length = np_length / s_length
normalised_vp_length = vp_length / s_length
depth = max_tree_... |
def to_numpy(location):
"""
Don't care about location[1], which is the height
"""
return np.float32([location[0], location[2]])
def check_reset(self, kart_loc):
threshold = 5
last_loc = self.past_kart_locs[-1]
x_diff = abs(last_loc[0] - kart_loc[0])
y_diff... | This code determines a kart's action in a game by analyzing the environment image to detect puck locations, tracking kart position, and using state-based logic (e.g., 'kickoff', 'attack') to control acceleration, steering, and other maneuvers. It adjusts speed dynamically based on velocity ratios and maintains historic... | def act(self, image, player_info):
"""
Set the action given the current image
:param image: numpy array of shape (300, 400, 3)
:param player_info: pystk.Player object for the current kart -> https://pystk.readthedocs.io/en/latest/state.html?highlight=pystk.Player#pystk.Player
ret... |
def virtual_disk_json():
global vdata
global slot_to_virtual_disk_data
if not vdata: vdata = storcli_call('/call/vall show all')
return vdata
def _get(o, k, d=''):
# Inspired by lodash _.get()
r = o
for key in k.split('.'):
try: r = r[key]
except:
if not (isinstan... | The code retrieves and formats virtual disk (VD) information from a JSON data structure, mapping statuses, processing cache flags, and organizing details like RAID type, size, disk count, and operations into a structured table. It sanitizes, colors, and sorts data for display, returning headers, alignments, values, and... | def get_virtual_disk_info():
vd_words = {
"Disk's Default": 'Default',
'Optl': 'Optimal',
'Dgrd': 'Degraded',
}
header = ['VID', 'Type', 'Size', '#Dsk', 'StrpSz', 'CacheFlg', 'DskCache', 'Status', 'CacheCade', 'Path', 'Name', 'In progress']
aligns = ['l', 'l', 'r', 'r', 'r', 'l'... |
def slot_to_virtual_disk_json():
global slot_to_virtual_disk_data
if not slot_to_virtual_disk_data:
slot_to_virtual_disk_data = {}
vdata = virtual_disk_json()
for controller in _get(vdata, 'Controllers', []):
cid = getcid(controller)
for k, v in _get(controller, '... | The function `get_physical_disk_info` retrieves and formats physical disk information from storage controllers, mapping technical statuses to human-readable terms. It collects details like disk model, serial, speed, status, temperature, and topology, applying filters based on the `configured` parameter to include/exclu... | def get_physical_disk_info(configured=None):
pd_words = {
'U': 'Up',
'D': 'Down',
'Onln': 'Online',
'Offln': 'Offline',
'Rbld': 'Rebuild',
'Sntze': 'Sanitize',
'GHS': 'Global Hot Spare',
'DHS': 'Dedicated Hot Spare',
'UGood': 'Unconfigured Good... |
def time_difference_json():
global time_difference_data
if not time_difference_data:
time_difference_data = {}
cdata = controller_json()
for controller in _get(cdata, 'Controllers', []):
cid = getcid(controller)
controller_clock = strstrip(_get(controller, 'Respon... | The code retrieves and formats controller scheduling information for Consistency Check (CC) and Patrol Read (PR) tasks, including their modes, delays, next start times, statuses, and excluded virtual disks. It processes JSON data, standardizes values, formats dates, applies color coding to statuses, and returns structu... | def get_controller_schedule_info():
header = ['CID', 'Task', 'Excl VIDs', 'Mode', 'Delay', 'Next start (system)', 'Next start (controller)', 'Status']
aligns = ['l', 'l', 'l', 'l', 'r', 'l', 'l', 'l']
values = []
footer = []
time_difference_data = time_difference_json()
controller_schedule_data... |
def controller_count_json():
return storcli_call('show ctrlcount')
def _get(o, k, d=''):
# Inspired by lodash _.get()
r = o
for key in k.split('.'):
try: r = r[key]
except:
if not (isinstance(r, list) or isinstance(r, tuple)): return d
try:
if len(... | The function `get_event_logs` parses event logs from storage controllers, filtering and formatting data based on input parameters. It processes event details, categorizes severity levels, and structures output with headers, alignments, and filtered values for display, handling multiple controllers if specified. | def get_event_logs(cid, event_filters, event_type):
ignores = ['', '===========', 'None']
event_terminator = 'CLI Version ='
header = ['CID', 'SeqNum', 'Event time (system)', 'Severity', 'Description', 'Data', 'Code', 'Locl', 'Event time (controller)']
aligns = ['l', 'l', 'r', 'l', 'l', 'l', 'l', 'l', ... |
def energy_potential(
self,
frequency: str = "project",
by: str = "windfarm",
units: str = "gw",
per_capacity: str | None = None,
aep: bool = False,
) -> pd.DataFrame | float:
"""Computes the potential energy production, or annual potential energy production, ... | The function calculates energy losses by subtracting actual energy production from potential energy production, considering parameters like frequency (project/annual/monthly), aggregation level (windfarm/turbine), units (GW/MW/KW), and loss ratios. It returns a DataFrame with losses in specified units, optionally norma... | def energy_losses(
self,
frequency: str = "project",
by: str = "windfarm",
units: str = "gw",
per_capacity: str | None = None,
with_losses: bool = False,
loss_ratio: float | None = None,
aep: bool = False,
) -> pd.DataFrame:
"""Computes the ene... |
def energy_production(
self,
frequency: str = "project",
by: str = "windfarm",
units: str = "gw",
per_capacity: str | None = None,
with_losses: bool = False,
loss_ratio: float | None = None,
aep: bool = False,
) -> pd.DataFrame | float:
"""Comp... | The function calculates the capacity factor for wind energy production, returning values aggregated by project lifetime, annually, or monthly, and by windfarm or turbine. It computes "net" (actual energy) or "gross" (potential energy) ratios, optionally adjusting for losses. The result is a DataFrame or float represent... | def capacity_factor(
self,
which: str,
frequency: str = "project",
by: str = "windfarm",
with_losses: bool = False,
loss_ratio: float | None = None,
) -> pd.DataFrame | float:
"""Calculates the capacity factor over a project's lifetime as a single value, annua... |
def capex(
self, breakdown: bool = False, per_capacity: str | None = None
) -> pd.DataFrame | float:
"""Provides a thin wrapper to ORBIT's ``ProjectManager`` CapEx calculations that
can provide a breakdown of total or normalize it by the project's capacity, in MW.
Parameters
... | This function calculates the Levelized Cost of Energy (LCOE) using the formula (CapEx × Fixed Charge Rate + OpEx) / AEP, returning the result in $/MWh. It accepts optional parameters for CapEx, OpEx, AEP, and Fixed Charge Rate, defaulting to instance attributes if unspecified. The method ensures correct unit handling a... | def lcoe(
self,
fixed_charge_rate: float | None = None,
capex: float | None = None,
opex: float | None = None,
aep: float | None = None,
) -> float:
"""Calculates the levelized cost of energy (LCOE) as the following:
LCOE = (CapEx * FCR + OpEx) / AEP, in $/MWh... |
def convert_to_multi_index(
date_tuples: tuple[int, int] | list[tuple[int, int]] | pd.MultiIndex | None, name: str
) -> pd.MultiIndex:
"""Converts year and month tuple(s) into a pandas MultiIndex.
Parameters
----------
date_tuples : tuple[int, int] | list[tuple[int, int]] | pd.MultiIndex | None
... | This function calculates and returns a cash flow DataFrame for a project, considering various CapEx costs (soft, project, system, turbine) allocated over specified dates, combined with operational expenses and revenue. It aggregates results at the desired frequency ("project", "annual", or "month-year") and optionally ... | def cash_flow(
self,
frequency: str = "month-year",
installation_start_date: str | None = None,
soft_capex_date: tuple[int, int] | list[tuple[int, int]] | None = None,
project_capex_date: tuple[int, int] | list[tuple[int, int]] | None = None,
system_capex_date: tuple[int,... |
def solve_line(rules, length):
# try to reduce each line, filling in things that must be true
# generate all possible solutions
line = [2] * length
n = 0
for soln in generate_lines(rules, length):
for i, val in enumerate(soln):
if line[i] == 2 or line[i] == val:
l... | The code solves a grid puzzle where each row and column must match given constraints (left and top). It initializes a grid with unknown values (2), then fills rows and columns using a helper function `solve_line`. Conflicts are resolved by backtracking, toggling unknowns between 0 (white) and 1 (black) while ensuring r... | def solve(left, top):
# initialize
grid = [
[2 for i in range(len(top))]
for j in range(len(left))
] # grid[row][col]
# 2 = unknown, 0 = white, 1 = black
# solve rows
for i, row in enumerate(left):
grid[i] = solve_line(row, len(top))
#print(i, grid[i])
#... |
def events(self): # Game Loop - Events
"""
This function also term the way that game is operated such as:
- Move to other screen
- Catch the user's actions
- Catch the mouse's position
In conclusion this function stipulate out the logic of operating ... | The main task of the code is to manage the game loop, handling user input, updating game state, rendering visuals, and maintaining game flow until exit. It processes events, updates game logic, draws frames, and controls the loop's timing, ensuring smooth operation and responsiveness. The loop terminates when the user ... | def run(self): # Game Loop
"""
This function is used for keeping game playing unless user choses to exit with options are provided in the game
Moreover this function also term the way that game is operated such as:
- Move to other screen
- Catch the user's ac... |
def bootstrap(remote_addr_name, remote_port):
# get remote info
remote_addr = socket.gethostbyname(remote_addr_name)
remote_port = int(remote_port)
# connect
channel = grpc.insecure_channel(remote_addr + ':' + str(remote_port))
stub = csci4220_hw3_pb2_grpc.KadImplStub(channel)
# find self
nodelist = stub.FindNo... | This code defines a command-line interface that processes input commands in an infinite loop. It executes functions like bootstrap, find_node, find_value, store, or quit based on the command. Each command uses subsequent input arguments as parameters. The loop terminates only when 'QUIT' is received, otherwise it conti... | def start():
while(1):
i = input()
args = i.split()
command = args[0]
if command == 'BOOTSTRAP':
remote_addr_name = args[1]
remote_port = int(args[2])
bootstrap(remote_addr_name, remote_port)
elif command == 'FIND_NODE':
target_node_id = int(args[1])
find_node(target_node_id)
elif command ==... |
def ideal_lowpass_filter_rgb_dynamic(image):
"""Apply ideal lowpass filter to an RGB image with dynamic radius and padding."""
radius, padding = calculate_dynamic_parameters(image.shape)
# Rest of the processing is same as before
filtered_image = ideal_lowpass_filter_rgb_with_padding(image, radius, pad... | The main task of the code is to process three color images (color1.jpg to color3.jpg) by applying three distinct filters: an ideal lowpass filter with dynamic parameters, a Gaussian lowpass filter with padding, and unsharp masking for sharpening. Each processed image is saved with specific naming conventions (filtered_... | def main():
for i in range(1, 4):
# problem 1
image_path = f'color{i}.jpg'
image = cv2.imread(image_path)
filtered1_img = ideal_lowpass_filter_rgb_dynamic(image)
cv2.imwrite(f'filtered_image_dynamic{i}.jpg', filtered1_img)
# problem 2
sigma = 10
paddi... |
def init_placeholder(self):
# 32 x 32 images
self.x = tf.placeholder(tf.float32, [None, 3072])
# one-hot vector
self.y = tf.placeholder(tf.float32, [None, 10])
def init_params(self):
self.vgg_model = VGG_16()
self.vgg_model.init_conv_parameters()
self.vgg_model.... | The code initializes a model component by setting up checkpoint directory, model ID, placeholders, parameters, softmax parameters, and a TensorFlow variable for tracking epochs. It prepares the model structure and initializes session-related attributes, likely for training or inference in a machine learning framework. | def __init__(self, id, checkpoint_dir):
self.checkpoint_dir = checkpoint_dir
self.MODEL_ID = id
self.init_placeholder()
self.init_params()
self.init_softmax_parameters()
self.init_model()
self.sess = None
self.sess_saver = None
self.EPO... |
def print(self):
print('╔═══' + '══' * (self.n_cols - 2) + '══╗')
for row in self.freeze():
row_strings = [element.draw() for element in row]
string = ' '.join(row_strings)
print('║ ' + string + ' ║')
print('╚═══' + '══' * (self.n_cols - 2) + '══╝')
def freeze... | The code simulates a turn-based game where players from two teams move on a grid, handle invalid moves, capture flags, and manage prison releases. The game ends when a player holding a flag reaches a DividerSquare, triggering a win message. | def play_game(self, board):
game_finished = False
while not game_finished:
for team in [self.blue_team, self.red_team]:
self.print()
current_grid = self.freeze()
while True:
try:
player_number, direct... |
def _slice(self, X, Xs):
if self.active_dim is None:
if Xs is None:
return X, Xs
else:
return X, Xs
else:
if Xs is None:
return X[:,self.active_dim].reshape(len(X), 1), Xs
else:
return X[:,sel... | The code computes the full covariance matrix Kxx for a Gaussian process, combining kernel evaluations and derivatives. It constructs Kxx by concatenating blocks involving kernel values (K11), first derivatives (K10, K01), and second derivatives (K00), using either standard or lengthscale-specific kernels. The result is... | def full(self, X=None, Xs=None, kappa=None, gp=False):
X, X_df = X[0], X[1]
X, Xs = self._slice(X, Xs)
if kappa == None:
kappa = self.kappa
# Check if lengthscale specific to density field is provided,
# if so, use lsf for just density block of covar matrix
... |
def _slice(self, X, Xs):
if Xs is None:
return X, Xs
else:
return X, Xs
def kernel(self, X, Xs=None):
X, Xs = self._slice(X, Xs)
return tt.square(self.sigma_f) * tt.exp(-0.5 * self.square_dist(X, Xs))
def kernel_derivative(self, X1, X2):
m = len(X1)
... | The main task of the code is to compute a full kernel matrix $ K_{xx} $ by combining the kernel function $ K $, its first derivative $ K' $, and second derivative $ K'' $, handling cases where input $ X $ may be None. It constructs $ K_{xx} $ by vertically concatenating rows formed from horizontal concatenations of $ K... | def full(self, X=None, Xs=None):
X, X_df = X[0], X[1]
X, Xs = self._slice(X, Xs)
if X is not None:
K11 = self.kernel(X, Xs)
if X_df is None:
return K11
if X is not None:
K10 = self.kernel_derivative(X, X_df)
else:
... |
def accept_connection(self):
connection, addr = self.__soc.accept()
accepted = self.add_client(addr, connection)
if accepted:
side_ = self.clients[addr][0]
self._send_response(WHICH_SIDE.format(side=side_), side=side_)
return connection, addr
def _send_response(se... | This code manages a two-player game by accepting two client connections, initializing the game, and alternating turns. It processes client moves, updates the game field, checks for a winner, and sends real-time updates. If a move is invalid (e.g., cell occupied), it prompts the player to retry. The loop continues until... | def run(self):
while len(self.clients) < 2:
_, _ = self.accept_connection()
logger.info(self.clients)
self._send_response(START_GAME)
previous_side_step = random.choice(self.SIDES)
self._send_response(START_WITH.format(side=previous_side_step))
while se... |
def make_rand_file(n):
'''Creates a file consisting of n symbols chosen uniformly at random
from the standard Roman uppercase and lowercase alphabet'''
alphabet = ascii_uppercase + ascii_lowercase
rand_file = open('random.txt','wb')
rand_file.write(''.join(choice(alphabet) for i in range(n)))
ra... | The main task of the code is to generate diverse test files (random data, all 'A's, alternating 'A'/'B's, and empty files) for evaluating lossless compression algorithms, then visualize results in a table and test compression efficiency. It creates standardized datasets to benchmark how well different compression metho... | def main():
'''Main function for final assignment'''
print("Executing main() on",platform()+':\n')
make_rand_file(20000)
make_all_As(20000)
make_all_ABs(20000)
make_empty_file()
print(draw_table())
print(test_lossless_compression()) |
def is_laptop() -> bool:
"""
Check for the existance of a battery file
return True if file exist False otherwise
"""
batt_file = "/sys/class/power_supply/BAT0/model_name"
if exists(batt_file):
return True
return False
def make_laptop_widgets(colours: Dict[str, str], style, powerlin... | The function `initialize_widgets` generates a list of widgets based on a provided color scheme and style. It checks if the device is a laptop; if true, it returns laptop-specific widgets, otherwise, it returns base widgets. The `powerline` parameter influences widget styling. The main task is to dynamically select and ... | def initialize_widgets(colours: dict, style, powerline=True):
"""return list of widgets based on a colour scheme"""
if is_laptop():
return make_laptop_widgets(colours, style, powerline)
return base_widgets(colours, style, powerline) |
def find_current_config():
logger.info("Finding latest com.docker.ucp.config")
filter = '{"name":["com.docker.ucp.config"]}'
configs = ucp_api.find_configs(filter)
config_file = {}
for config_entry in configs:
config_file[config_entry['Spec']['Name']] = config_entry
latest = natural_... | (This function configures LDAP authentication and authorization by interacting with a UCP API. It initializes the API client, logs in, retrieves the current configuration, generates a new configuration, updates the UCP agent service settings, and logs out. The process ensures secure access control by modifying UCP's au... | def configure_authentication_and_authorization():
global config
global ucp_api
logger.info("Starting LDAP configuration")
ucp_api = UcpApi(endpoint=config['ucp']['endpoint'],
username=config['ucp']['username'],
password=config['ucp']['password'],
... |
def gen_define (problem):
return "(define (problem " + problem + ")\n"
def gen_domain (domain):
return "(:domain "+ domain + ")\n"
def gen_objects(shape, size):
if(shape=="triangle"):
holes = sum(range(1,size+1))
return objects(holes)
elif(shape=="square"):
holes = size*size
... | The code generates a PDDL problem description for a peg puzzle. It constructs the problem by combining predefined components: problem definition, domain, objects, initial state, and goal state. Helper functions format each section based on inputs like shape, size, empty positions, and target peg hole. The final output ... | def create_peg_problem(problem_name, domain, shape, size, empty, end_peg_hole):
formatted_define = gen_define(problem_name)
formatted_domain = gen_domain(domain)
formatted_objects = gen_objects(shape, size)
formatted_init = gen_init(shape, size, empty)
formatted_goal = gen_goal(shape, size, end_peg_... |
def check_if_move_allowed(self, peg, source_hole, over_hole, destination_hole):
if self.peg_exists(peg) and self.peg_in(peg, source_hole) and not self.hole_empty(over_hole) and self.hole_empty(destination_hole) and ([source_hole, over_hole, destination_hole] in self.lines):
return True
else:
... | The main task of the code is to process a given action in a peg solitaire-like game by attempting a peg move, validating its legality, updating the game state, and returning the new state, reward, and termination status. The reward depends on whether the move completes the game (with positive rewards for fewer pegs) or... | def step(self, action):
move = self.lines[action] #self.holes[x],self.holes[y], self.holes[z]
peg = move[0].peg
source = move[0]
over = move[1]
dest = move[2]
if self.check_if_move_allowed(peg, source, over, dest):
self.move_peg(peg, source, over, dest)
... |
def precision(Y, Y_hat):
if (Y_hat.shape[0] != Y.shape[0]):
return None
st = statmetrics(Y, Y_hat)
if (st['tp'] == 0):
return float(0)
return st['tp'] / (st['tp'] + st['fp'])
def recall(Y, Y_hat):
if (Y_hat.shape[0] != Y.shape[0]):
return None
st = statmetrics(Y, Y_hat)
... | The code computes precision, recall, and F1 score for binary classification by converting input arrays Y and Y_hat into binary labels (1 if first element > second, else 0) and validating shape consistency. | def getmetrics(Y, Y_hat):
if (Y.shape[0] != Y_hat.shape[0]):
return None
SY = np.array([1 if i[0] > i[1] else 0 for i in Y])
SY_hat = np.array([1 if i[0] > i[1] else 0 for i in Y_hat])
return(precision(SY, SY_hat), recall(SY, SY_hat), f1_score(SY, SY_hat)) |
def get_game(api_call):
gameData = api_call['gameData']
dateTime = gameData['datetime']
game = gameData['game']
weather = gameData['weather']
status = gameData['status']
probablePitchers = gameData['probablePitchers']
keys_to_add = ['dateTime','originalDate',
... | The code initializes an object to fetch or load MLB game data from an API, caching results in pickle files to avoid redundant calls. It processes the data into structured attributes like games, teams, players, pitches, and stats, separating pitch data into hit and non-hit categories for analysis. | def __init__(self,gamePk):
gamePk = str(gamePk)
storedResultsDirectory = "API_results/"
self._pickle_path = str(storedResultsDirectory+gamePk+'.pkl')
if gamePk in API_call.pickled_calls:
self._result = joblib.load(self._pickle_path)
else:
... |
def read_node(node_file_name, link_file_name):
global node_header, link_header
global node_list, node_dic, link_list
node_file = open(node_file_name, "r", 1)
node_header = node_file.readline()
str = node_file.readline()
while str != '':
cells = str.split(',')
node = Node(int(cell... | The main task of the code is to process node and link data from CSV files, perform variable node analysis, and generate output based on clustering parameters minPoints and eps, likely for density-based clustering or network analysis tasks. | def main(file_name, minPoints, eps):
node_file_name=file_name+'/node.csv'
link_file_name=file_name+'/link.csv'
read_node(node_file_name, link_file_name)
get_var_node()
output(minPoints, eps) |
def post_logs(filename):
#Extract all logs
with open(filename, 'r') as log_file:
fieldnames = 'time', 'level', 'module', 'line', 'message'
table = csv.DictReader(
log_file,
fieldnames = fieldnames
)
#Create a snapshot of the log file
listoflists = ... | The main task of the code is to rename multiple files in a directory using specified patterns, with an option to copy instead of renaming. It validates the 'copy' parameter, retrieves and sorts files matching the pattern, then iteratively renames them using a counter, ensuring proper error handling and parameter conver... | def rename_bulk(file_pattern, new_pattern, target_dir, copy='False'):
#Check if Copy is either True or False
if copy != 'True' and copy != 'False':
log.error('Invalid copy parameter. Must be either True or False!')
post_logs(log_filename)
sys.exit(1)
if copy == 'False':
copy ... |
def csv_downloader(url):
try:
filename = url.split('/')[-1]
filename = filename.split('.')[0]
r = requests.get(url)
r.raise_for_status()
with open(filename, 'wb') as file:
file.write(r.content)
log.info('File Downloaded Successfully')
return filena... | The main task of the code is to download a CSV file from a user-provided URL, filter its contents to extract data related to 'Categories', rewrite the filtered data into a new CSV file, log the process, and terminate the program. The code sequentially handles input, data processing, file manipulation, logging, and exit... | def main():
url = input("Please enter the URL of the CSV file: ")
filename = csv_downloader(url)
listoflists, fieldnames = csv_filter(filename, 'Categories')
csv_rewriter(filename, fieldnames, listoflists)
log.info('Done')
post_logs(log_filename)
sys.exit(0) |
def new_generation(self):
"""
Takes a copy of the existing population and applies mutations and crossing-over to it
:return: None
"""
self._copy_population()
self._mutate_new_population()
self._crossing_over_in_new_population()
def get_rest_data(data_url, batch_si... | The main task of the code is to perform a single training epoch by generating a new generation, evaluating both old and new populations using the same data batch, merging populations to retain the best models, and returning the evaluation of the top-performing model along with its trade count. | def train(self):
"""
Single epoch
:return: evaluation of the best model and the number of trades it took
"""
# Create a new generation and evaluate it
self.new_generation()
# Get batch of random sequences from the REST data service
batch = get_rest_data(se... |
def loadVCAsFiles(self):
self.prepareBaseData()
self.vcaData = []
self.vcaDocs = []
for vcaFile in self.opt.VCAsFiles:
print(vcaFile)
vcaDocument = self.gspreadWrapper.gc.open_by_key(vcaFile)
try:
vcaSheet = vcaDocument.worksheet("Asses... | The code processes VCA assessments by validating integrity, updating feedback counts, calculating yellow/red cards, and filtering valid assessments. It generates a structured spreadsheet with sheets for valid assessments, excluded assessments, assessor recaps, VCA listings, and aggregated proposal scores, applying spec... | def createDoc(self):
self.loadVCAsFiles()
# Loop over master ids as reference
for id, row in self.dfVca.iterrows():
# Loop over all vca files
for vcaDf in self.vcaData:
if (id in vcaDf.index):
locAss = vcaDf.loc[id]
... |
def quit_sys(self):
"""quit system"""
self.view.quit_system_message()
sys.exit()
def view_all(self):
# first page is set to 1 instead of 0.
# ticket ID will start with 1 instead of 0.
current_page = 1
total_page = math.ceil(len(self.__tickets) / self.__item_per_p... | The code defines a menu method that repeatedly displays options to the user, processes their input to navigate between viewing all items, viewing a single item, quitting the system, or returning to a previous menu. It validates input and handles invalid entries with an error message. | def menu(self):
while True:
answer2 = self.view.option2()
if answer2 == 'quit':
self.quit_sys()
elif answer2 == '1':
self.view_all()
elif answer2 == '2':
self.view_one()
elif answer2 == '3':
... |
def __read_config(self):
try:
config = configparser.RawConfigParser()
config.read('config.txt')
self.__url = config.get('configuration', 'url')
self.__username = config.get('configuration', 'username')
self.__password = config.get('configuration', 'pas... | The code initializes a system by reading configuration, authenticating via base64, retrieving tickets from a server, updating the UI with tickets, and entering a loop to handle user commands for quitting, updating tickets, or accessing a menu. | def run(self):
"""System starts"""
##1.read config file
self.__read_config()
##2.auth string after base64 authentication
auth = self.__base64_auth('%s:%s' % (self.__username, self.__password))
##3. Retrieve tickets from the server
self.model.retrieve_ticket(se... |
def matrix_multiplication(self, a, b):
'''Method implemented for matrix multiplication.'''
r = []
for i in range(a.shape[0]):
c = []
for j in range(b.shape[1]):
s = 0
for k in range(b.shape[0]):
s += a[i][k] * b[k][j]
... | The code performs a forward pass through a neural network, computing hidden and output layer activations using sigmoid functions. It appends bias terms and handles three modes: 'train' (computes error, triggers backpropagation, returns MSE), 'validate' (computes and returns MSE), and 'predict' (returns output activatio... | def feed_forward(self, x, y, mode='train'):
'''Internal method. Method for feed forward the network. This method is not meant to be called from outside
of this class. Different modes you can pass are train, validate and predict. This method is
called from the fit method internally.'''
x ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.