content
stringlengths
7
1.05M
# -*- coding:utf-8 -*- """ @author: leonardo @created time: 2020-11-03 @last modified time:2020-11-03 """ def select(engine, backtesting_id): """ :param engine: :param backtesting_id: :return: """ sql = 'SELECT * from strategy_backtesting where backtesting_id="{}"'.format(backtesting_id) return list(engine.execute(sql)) def insert_on_duplicate_update(engine, data): """ :param engine: :param data: :return: """ sql = 'insert into strategy_backtesting(backtesting_id,strategy_id ,strategy_param,backtesting_start_time,backtesting_end_time)' \ ' values (%s,%s,%s,%s,%s)' \ ' on duplicate key update backtesting_id=values(backtesting_id),strategy_id=values(strategy_id),strategy_param=values(strategy_param),backtesting_start_time=values(backtesting_start_time),backtesting_end_time=values(backtesting_end_time)' return engine.execute(sql, data)
if type(Query.target) is IfStatement: parent = Query.target.parent parent.beginModification('If to while') condition = Query.target.condition thenBranch = Query.target.thenBranch Query.target.replaceChild(condition, Node.createNewNode('Expression', None)) Query.target.replaceChild(thenBranch, Node.createNewNode('StatementItemList', None)) whileNode = Node.createNewNode('LoopStatement', None) parent.replaceChild(Query.target, whileNode) # The while needs to be attached to the tree before it can reuse the parts of the if whileNode.condition = condition whileNode.body = thenBranch parent.endModification() else: raise Exception('ifToWhile command only works on if statements')
# -*- coding:utf-8 -*- class CocoException(Exception): pass class CoCoRuntimeError(RuntimeError): pass
#!/usr/bin/env python3 def exam_grade(score): """Students in a class receive their grades as Pass/Fail. Scores of 60 or more (out of 100) mean that the grade is "Pass". For lower scores, the grade is "Fail". In addition, scores above 95 (not included) are graded as "Top Score". This function receives the score and returns the proper grade.""" if score == 100: grade = "Top Score" elif score >= 60: grade = "Pass" else: grade = "Fail" return grade print(help(exam_grade)) print(exam_grade(65)) # Should be Pass print(exam_grade(55)) # Should be Fail print(exam_grade(60)) # Should be Pass print(exam_grade(95)) # Should be Pass print(exam_grade(100)) # Should be Top Score print(exam_grade(0)) # Should be Fail
sampleJson = { "id": 3, "pin": "700014", "cgst": 3241.53, "date": "2021-04-16", "igst": 0, "name": "Subhajit Paul", "sgst": 3241.53, "type": "S", "email": 'nulestu@gmail.com', "gstin": 'KKHUU654343KL8', "phone": 9165799976, "mobile": "7059403006", "ref_no": "GKUS/30/21", "address": "7 Dr Suresh Sarkar road Kolkata", "product": "D/CAMERA NIKON D3500COMBO", "acc_name": "Credit Card HDFC Bank", "stateCode":20, "cgstRate": 9, "sgstRate": 9, "igstRate": 0, "products": [ { "hsn": "8525", "qty": 2, "item": "D/CAMERA", "spec": "SL NO 5504415/25046293/20942790", "brand": "NIKON", "model": "D3500COMBO", "price": 36016.95, "discount": 0, "code": 12122 }, { "hsn": "8525", "qty": 5, "item": "D/CAMERA", "spec": "SL NO 5504415/25046293/20942790", "brand": "SONY", "model": "D35", "price": 22016.15, "discount": 0, "code": 12132 } ], "roundoff": -0.01, "bill_memo": "M", "total_amt": 42500.29, "companyInfo": { "pan": "AACCC5685L", "pin": "700013", "addr1": "12 J.L.Nehru Road", "addr2": "http://capital-chowringhee.com", "email": "capitalch@gmail.com", "free1": "Web site: http://capital-chowringhee.com", "free2": "For warranty and replacement please contact respective manufacturer companies.", "free3": "Materials will be delivered only after the cheque is cleared from our Bank.", "free4": "All disputes to be resolved in Kolkata jurisdiction only.", "gstin": "19AACCC5685L1Z3", "phone": "8777399268, 9163055161, 9903177904", "comp_name": "Capital Chowringhee Pvt Ltd" }, "bill_memo_id": 95 }
def dot(data, compile_to=None): notation_list = data.split('.') compiling = "" compiling += notation_list[0] beginning_string = compile_to.split('{1}')[0] compiling = beginning_string + compiling dot_split = compile_to.replace(beginning_string + '{1}', '').split('{.}') if any(len(x) > 1 for x in dot_split): raise ValueError("Cannot have multiple values between {1} and {.}") for notation in notation_list[1:]: compiling += dot_split[0] compiling += notation compiling += dot_split[1] return compiling
''' File này gồm 2 hàm kiểm tra tọa độ trước khi gửi qua serial ''' # kiểm tra tọa độ có hợp lệ không def plc1CoordinateValidator(raw_x, raw_y, raw_z): #y = int(raw_y)-59-21, -59 (mép ngoài) là khoảng cách từ camera đến khung, 21 từ khung đến trục thân xilanh trục y #231 khoảng cách hai mép trong, 59 từ cam đến mép trong, 23 từ mép trong đến cánh tay y = 275 - int(raw_y) # chieu truc X cua camera# doi tu toa do cam sang toa do khung PLC1 #80 #x = 100-20, 100 là giới hạn một nửa khoảng thu hoạch (mép trong), 20 thân xylanh đến khung theo trục x #14 từ cánh tay đến mép trong x = 87 + int(raw_x) # chieu truc Y cua camera # doi tu toa do cam sang toa do khung PLC1 #184 if y < 0 and abs(y) <= 5: y = 0 if y > 180 and y < 210 : #gán giới hạn trên trục Y y = 185 if y > 43 and y < 58 : #gán giới hạn dưới1 trục Y y = 51 if y >=58 and y < 65 : # gán giới hạn dưới2 trục Y y = 55 if x <=10 : # gán giới hạn dưới trục X x = 3 if y > 170 and x < 30: # gán giới hạn quả ngoài cùng hàng 1( gần cammera nhất) y = 185 x = 5 if y > 145 and y<= 166 and x <= 18: # giới hạn quả ngoài cùng hàng 2 y = 145 x = 5 if int(raw_z) < 70 : z = 3 if int(raw_z) >= 70 and int(raw_z) <= 80 : z = 4 if int(raw_z) > 80: z = 5 if 51 <= y <= 185 and 0 <= x <= 87: # Nếu nằm trong tầm cắt trả về tọa độ return {'x': x, 'y': y, 'z': z} # Không nằm trong tầm cắt thì không trả về gì return None # kiểm tra tọa độ có hợp lệ không def plc2CoordinateValidator(raw_x, raw_y, raw_z): #y = int(raw_y)-59-21, -59 (mép ngoài) là khoảng cách từ camera đến khung, 21 từ khung đến trục thân xilanh trục y #231 khoảng cách hai mép trong, 59 từ cam đến mép trong, 23 từ mép trong đến cánh tay y = 275 - int(raw_y) # chieu truc X cua camera# doi tu toa do cam sang toa do khung PLC1 #80 #x = 100-20, 100 là giới hạn một nửa khoảng thu hoạch (mép trong), 20 thân xylanh đến khung theo trục x #14 từ cánh tay đến mép trong x = 87 - int(raw_x) # chieu truc Y cua camera # doi tu toa do cam sang toa do khung PLC1 #184 if y < 0 and abs(y) <= 5: y = 0 if y > 180 and y < 210 : #gán giới hạn trên trục Y y = 185 if y > 43 and y < 58 : #gán giới hạn dưới1 trục Y y = 51 if y >=58 and y < 65 : # gán giới hạn dưới2 trục Y y = 55 if x <=10 : # gán giới hạn dưới trục X x = 3 if y > 170 and x < 30: # gán giới hạn quả ngoài cùng hàng 1( gần cammera nhất) y = 185 x = 5 if y > 145 and y<= 166 and x <= 18: # giới hạn quả ngoài cùng hàng 2 y = 145 x = 5 if int(raw_z) < 70 : z = 3 if int(raw_z) >= 70 and int(raw_z) <= 80 : z = 4 if int(raw_z) > 80: z = 5 if 51 <= y <= 185 and 0 <= x <= 75: # Nếu nằm trong tầm cắt trả về tọa độ return {'x': x, 'y': y, 'z': z} # Không nằm trong tầm cắt thì không trả về gì return None
"""Functions relating to grokking_algorithms qucksort chapter.""" def euclid_algorithm(area): """Return the largest square to subdivide area by.""" height = area[0] width = area[1] maxdim = max(height, width) mindim = min(height, width) remainder = maxdim % mindim if remainder == 0: return mindim else: return euclid_algorithm((mindim, remainder)) def recursive_sum(arr): """Return the sum of a 2D array.""" if len(arr) == 0: return 0 else: return arr[0] + recursive_sum(arr[1:]) def quicksort(arr, pivi=0): """Return a sorted 2D numerical array smallest -> largest.""" if len(arr) < 2: return arr else: piv = arr[pivi] lower = [v for v in arr[1:] if v <= piv] higher = [v for v in arr[1:] if v > piv] return quicksort(lower) + [piv] + quicksort(higher)
expected_output = { "tag": { "test": { "system_id": { "R2_xr": { "type": { "L1L2": { "area_address": ["49.0001"], "circuit_id": "R1_xe.01", "format": "Phase V", "interface": "GigabitEthernet2.115", "ip_address": ["10.12.115.2*"], "ipv6_address": ["FE80::F816:3EFF:FE67:2452"], "nsf": "capable", "priority": 64, "state": "up", "topology": ["ipv4", "ipv6"], "uptime": "3d04h", } } }, "R3_nx": { "type": { "L1L2": { "area_address": ["49.0001"], "circuit_id": "R1_xe.02", "format": "Phase V", "interface": "GigabitEthernet3.115", "ip_address": ["10.13.115.3*"], "ipv6_address": ["FE80::5C01:FF:FE02:7"], "nsf": "capable", "priority": 64, "state": "up", "topology": ["ipv4", "ipv6"], "uptime": "3d04h", } } }, } }, "test1": { "system_id": { "2222.22ff.4444": { "type": { "L1L2": { "area_address": ["49.0001"], "circuit_id": "2222.22ff.4444.01", "format": "Phase V", "interface": "GigabitEthernet2.415", "ip_address": ["10.12.115.2*"], "ipv6_address": ["FE80::F816:3EFF:FE67:2452"], "nsf": "capable", "priority": 128, "state": "init", "topology": ["ipv4", "ipv6"], "uptime": "3d04h", } } }, "R3_nx": { "type": { "L1L2": { "area_address": ["49.0001"], "circuit_id": "R1_xe.02", "format": "Phase V", "interface": "GigabitEthernet3.415", "ip_address": ["10.13.115.3*"], "ipv6_address": ["FE80::5C01:FF:FE02:7"], "nsf": "capable", "priority": 64, "state": "up", "topology": ["ipv4", "ipv6"], "uptime": "3d04h", } } }, } }, } }
class CliArgs(object): def __init__(self): self.search = [] self.all = False self.slim = False self.include = False self.order = False self.reverse = False self.json = False self.version = False
# -*- coding: utf-8 -*- class DataNameBuilder(object): """ data_name等拼接工具 """ def __init__(self, data_name, bk_biz_id, data_name_prefix): self.data_name = data_name self.bk_biz_id = bk_biz_id self.data_name_prefix = data_name_prefix @property def name(self): return f"{self.data_name_prefix}_{self.data_name}" @property def time_series_group_name(self): return f"{self.data_name_prefix}_{self.data_name}" @property def table_id(self): return f"{self.bk_biz_id}_{self.data_name_prefix}_{self.data_name}.base".replace("-", "_")
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. # https://projecteuler.net/problem=1 # 1, 5, 10, 15, 20, ... # 3, 6, 9, 12, 15, 18, 21, ... limit = 1000 print( sum( set(range(5,limit,5)).union(set(range(3,limit,3))) ) )
def circ_supply(height: int, nano: bool = False) -> int: """ Circulating supply at given height, in ERG (or nanoERG). """ # Emission settings initial_rate = 75 fixed_rate_blocks = 525600 - 1 epoch_length = 64800 step = 3 # At current height completed_epochs = max(0, height - fixed_rate_blocks) // epoch_length current_epoch = completed_epochs + min(1, completed_epochs) blocks_in_current_epoch = max(0, height - fixed_rate_blocks) % epoch_length current_rate = max(0, initial_rate - current_epoch * step) # Components fixed_period_cs = min(fixed_rate_blocks, height) * initial_rate completed_epochs_cs = sum( [ epoch_length * max(0, initial_rate - step * (i + 1)) for i in range(completed_epochs) ] ) current_epoch_cs = blocks_in_current_epoch * current_rate # Circulating supply cs = fixed_period_cs + completed_epochs_cs + current_epoch_cs if nano: cs *= 10**9 return cs # TODO turn this into tests # assert(circ_supply(1000) == 75000) # assert(circ_supply(608548) == 45337806) # assert(circ_supply(2080800) == 97739925) # assert(circ_supply(2180800) == 97739925) # assert(circ_supply(9080800) == 97739925)
# Resources for an MPMCT with n controls def mpmct_depth(n): return 28*n - 60 def mpmct_t_c(n): return 12*n - 20 def mpmct_t_d(n): return 4*(n-2) def mpmct_h_c(n): return 4*n - 6 def mpmct_cnot_c(n): return 24*n - 40
class Equip(): def __init__(self, name, attribute, action): self.name = name self.attribute = attribute self.action = action class Item(): def __init__(self, name, attribute, buff): self.name = name self.attribute = attribute self.buff = buff class Attribute(dict): pass
class ProxyException(Exception): """Proxy returned an error.""" def __init__(self, message='Proxy returned an error.'): # Call the base class constructor with the parameters it needs super(ProxyException, self).__init__(message)
H, W, N = map(int, input().split()) berry = [tuple(int(x) for x in input().split()) for _ in range(N)] ans = [] for i in range(1, W+1): up = 0 for x, y in berry: if i * y == H * x: break elif i * y > H * x: up += 1 else: if up * 2 == N: ans.append((i, H)) for i in range(1, H): up = 0 for x, y in berry: if W * y == i * x: break elif W * y > i * x: up += 1 else: if up * 2 == N: ans.append((W, i)) ans.sort() if ans: for x, y in ans: print('({},{})'.format(x, y)) else: print(-1)
__author__ = 'lg' a = raw_input() if a > 0: print('positive number') elif a < 0: print('negative number') else: print('the number is zero')
# Advent of Code - Day 7 - Part One def parse(input): return [int(n) for n in input[0].split(",")] def result(input): positions = parse(input) fuel_cost_options = [] for i in range(min(positions), max(positions) + 1): movements = [abs(n - i) for n in positions] fuel_cost_options.append(sum(movements)) return min(fuel_cost_options) sample_input = ["16,1,2,0,4,2,7,1,2,14"] input = sample_input print(result(input))
''' 6. Write a Python program to create a histogram from a given list of integers. ''' def histogram(values): for n in values: output = '' x = n while(x > 0): output += '*' x = x - 1 print(output) histogram([1,2,3,4,5,6])
print("#######################################") print("## AVERAGE STUDENT HEIGHT CALCULATOR ##") print("#######################################") #test heights: 123 149 175 183 166 179 125 student_heights = input(" Input a list of student heights:\n>> ").split() for n in range(0, len(student_heights)): student_heights[n] = int(student_heights[n]) #print(student_heights) total = 0 for num in student_heights: total += num #print(total) def list_height(student_heights): counter = 0 for char in student_heights: counter += 1 return counter length = list_height(student_heights) #print(length) ave = round(total / length) print(f"Average student height is: {ave}")
i = 1 while True: print(i) i += 1 if i > 10: break
# Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com) c = (a, b) d = {e: 1, f: 2} fun(a, b, *c, **d) # EXPECTED: [ ..., BUILD_TUPLE(2), ..., BUILD_TUPLE_UNPACK_WITH_CALL(2), ..., CALL_FUNCTION_EX(1), ..., ]
#A program that counts the number of characters up to the first $ in a text file. file = open("poem.txt","r") data = file.readlines() for index in range(len(data)): for secondIndex in range(len(data[index])): if data[index][secondIndex] == "$": break print( "Total number of characters up to the first $ are = ",(index+secondIndex)) file.close()
def metade(valor = 0, format = False): resp = valor/2 return resp if format is False else money(resp) def dobro(valor = 0, format = False): resp = valor*2 return resp if format is False else money(resp) def dez_porcento(valor = 0, format = False): resp = valor + (valor*10)/100 return resp if format is False else money(resp) def quinze_porcento(valor = 0, format = False): resp = valor - (valor*15)/100 return resp if format is False else money(resp) def money(valor = 0, moeda = 'R$'): return f'{moeda}{valor:.2f}'.replace('.',',')
''' Created on 2020-04-15 14:50:02 Last modified on 2020-05-07 21:21:10 Python 2.7.16 v0.1 @author: L. F. Pereira (lfpereira@fe.up.pt) Main goal --------- Develop functions to get data from odb files. ''' #%% history outputs def get_xydata_from_nodes_history_output(odb, nodes, variable, directions=(1, 2, 3), step_name=None): ''' Given a node array, returns the values for time and the given variable. Assumes the variable was requested in history outputs. Parameters ---------- odb : Abaqus odb object nodes : array-like of Abaqus OdbMeshNode objects variable : str It only works for vector-like variables. e.g. 'U' and 'RF' directions : array Directions for which to extract values. step_name : str If None, it uses the last step. Returns ------- y : array-like, shape = [n_nodes x [n_increments x n_directions]] Notes ----- -Assumes all the nodes have history output and the array contains each node only once. ''' # initialization if not step_name: step_name = odb.steps.keys()[-1] step = odb.steps[step_name] # collect data y = [] for node in nodes: instance_name = node.instanceName if node.instanceName else 'ASSEMBLY' name = 'Node ' + instance_name + '.' + str(node.label) historyOutputs = step.historyRegions[name].historyOutputs node_data = [] for direction in directions: node_data.append([data[1] for data in historyOutputs['%s%i' % (variable, direction)].data]) y.append(node_data) return y #%% field outputs def get_ydata_from_nodeSets_field_output(odb, nodeSet, variable, directions=(1, 2, 3), step_name=None, frames=None): ''' Given a node set, returns the values for the given variable. It may take a while to run. Parameters ---------- odb : Abaqus odb object nodeSet : Abaqus nodeSet object variable : str It only works for vector-like variables. e.g. 'U' and 'RF' directions : array Directions for which to extract values. The value will be subtracted by 1 when accessing abaqus data. frames : array-like of Abaqus OdbFrame objects If frames are available from outside, use it because it may significantly decreases the computational time. step_name : str If None, it uses the last step. Only required if frames=None. Returns ------- values : array-like, shape = [n_increments x n_directions x n_nodes]] ''' # TODO: extend to scalar and tensor like variables # TODO: change name to accept also elements (position should be an input) # access frames if not frames: if not step_name: step_name = odb.steps.keys()[-1] frames = [frame for frame in odb.steps[step_name].frames] # collect data values = [] for frame in frames: varFieldOutputs = frame.fieldOutputs[variable] outputs = varFieldOutputs.getSubset(region=nodeSet).values output_frame = [] for direction in directions: output_frame.append([output.data[direction - 1] for output in outputs]) values.append(output_frame) return values #%% other def get_eigenvalues(odb, frames=None, step_name=None): ''' Parameters ---------- odb : Abaqus odb object frames : array-like of Abaqus OdbFrame objects step_name : str If None, it uses the last step. Only required if frames=None. ''' # access frames if not frames: if not step_name: step_name = odb.steps.keys()[-1] frames = [frame for frame in odb.steps[step_name].frames] # get eigenvalues eigenvalues = [float(frame.description.split('EigenValue =')[1]) for frame in list(frames)[1:]] return eigenvalues
P = {} # Imputers P['mean imp'] = {'strategy': 'mean'} P['median imp'] = {'strategy': 'median'} P['most freq imp'] = {'strategy': 'most_frequent'} P['constant imp'] = {'strategy': 'constant'} P['iterative imp'] = {'initial_strategy': 'mean', 'skip_complete': True}
#23212 | Contract with Mastema isDS = chr.getJob() == 3100 sm.setSpeakerID(2450017) if not sm.canHold(1142342): sm.sendSayOkay("Please make space in your equip inventory.") sm.dispose() if sm.sendAskYesNo("Everything is ready. Let us begin the contract ritual. Focus on your mind."): sm.jobAdvance(isDS and 3110 or 3120) sm.giveItem(isDS and 1142342 or 1142554) sm.giveAndEquip(isDS and 1099002 or 1099007) #todo: upgrade instead of replace secondary? (potentials) sm.completeQuest(parentID) sm.setPlayerAsSpeaker() sm.sendNext("#b(You feel a curious energy flowing into you.)") sm.setSpeakerID(2450017) sm.sendNext("There... our contract is made. Now we can communicate through our minds. Isn't that neat?") sm.dispose() else: sm.dispose()
#prob:lem statement: Make the below pattern. Here, n =4 #4 4 4 4 4 4 4 #4 3 3 3 3 3 4 #4 3 2 2 2 3 4 #4 3 2 1 2 3 4 #4 3 2 2 2 3 4 #4 3 3 3 3 3 4 #4 4 4 4 4 4 4 n=int(input("enter any number: ")) #n is the number for the outermost lines and val is the value to be printed in row i column j #for first left quadrant for i in range(1,n+1): for j in range(1,n+1): if(i<j): val=i else: val=j print(n-val+1, end = "") #for right top quadrant for j in range(n-1,0,-1): if(i<j): val=i else: val=j print(n-val+1,end="") print() #for bottom left quadrant for i in range(n-1,0,-1): for j in range(1,n+1): if(i<j): val=i else: val=j print(n-val+1,end="") #for bottom right quadrant for j in range(n-1,0,-1): if(i<j): val=i else: val=j print(n-val+1,end="") print()
# train-project/train_schedule/views/formatters.py """Helper functions to format data for display.""" def format_station(station, show_id=False): """Format station data for display""" if station is None: return "Unknown" else: fmt_str = "{city}, {country} ({code})" if show_id: fmt_str = "{id}: " + fmt_str return fmt_str.format(**station.dict()) def format_datetime(time_value): """Format a datetime according to the current locale""" return time_value.strftime("%c") TrainFormatters = { "station_from": format_station, "station_to": format_station, "departs_at": format_datetime, "arrives_at": format_datetime, } """Lookup table for functions to format various attributes of a train""" TrainAttributeNames = { "station_from": "From", "station_to": "To", "departs_at": "Departs", "arrives_at": "Arrives", "first_class": "1st class cars", "second_class": "2nd class cars", "seats_per_car": "Seats/car", } """Lookup table for display names of train attributes""" def format_train_attr(train, attr): """Format a train attribute""" value = getattr(train, attr) formatter = TrainFormatters.get(attr) if formatter: value = formatter(value) return value def format_train(train, show_from=True, show_to=True): """Format train data for display""" columns = TrainAttributeNames.copy() if not show_from: del columns["station_from"] if not show_to: del columns["station_to"] return "\t".join( f"{heading}: {format_train_attr(train, attr)}" for attr, heading in columns.items() )
def index_settings(table_name): """ Return the Elasticsearch mapping for a given table in the database. :param table_name: The name of the table in the upstream database. :return: """ settings = { "index": { "number_of_shards": 18, "number_of_replicas": 0, "refresh_interval": "-1", }, "analysis": { "filter": { "stem_overrides": { "type": "stemmer_override", "rules": [ # Override unwanted 'anim' stems "animals => animal", "animal => animal", "anime => anime", "animate => animate", "animated => animate", ], }, "english_stop": {"type": "stop", "stopwords": "_english_"}, "english_stemmer": {"type": "stemmer", "language": "english"}, "english_possessive_stemmer": { "type": "stemmer", "language": "possessive_english", }, }, "analyzer": { "custom_english": { "tokenizer": "standard", "filter": [ # Stem overrides must appear before the primary # language stemmer. "stem_overrides", "english_possessive_stemmer", "lowercase", "english_stop", "english_stemmer", ], } }, }, } common_mappings = { "properties": { "id": {"type": "long"}, "identifier": { "fields": {"keyword": {"type": "keyword", "ignore_above": 256}}, "type": "text", }, "title": { "type": "text", "similarity": "boolean", "fields": {"keyword": {"type": "keyword", "ignore_above": 256}}, "analyzer": "custom_english", }, "foreign_landing_url": { "fields": {"keyword": {"ignore_above": 256, "type": "keyword"}}, "type": "text", }, "description": { "fields": {"keyword": {"type": "keyword", "similarity": "boolean"}}, "type": "text", "analyzer": "custom_english", }, "creator": { "type": "text", "fields": {"keyword": {"type": "keyword", "ignore_above": 256}}, }, "url": { "fields": {"keyword": {"type": "keyword", "ignore_above": 256}}, "type": "text", }, "extension": { "fields": {"keyword": {"ignore_above": 8, "type": "keyword"}}, "type": "text", }, "license": { "fields": {"keyword": {"ignore_above": 256, "type": "keyword"}}, "type": "text", }, "license_version": { "type": "text", "fields": {"keyword": {"type": "keyword", "ignore_above": 256}}, }, "license_url": { "fields": {"keyword": {"type": "keyword", "ignore_above": 256}}, "type": "text", }, "provider": { "type": "text", "fields": {"keyword": {"type": "keyword", "ignore_above": 256}}, }, "source": { "fields": {"keyword": {"ignore_above": 256, "type": "keyword"}}, "type": "text", }, "created_on": {"type": "date"}, "tags": { "properties": { "accuracy": {"type": "float"}, "name": { "type": "text", "fields": {"keyword": {"type": "keyword", "ignore_above": 256}}, "analyzer": "custom_english", }, } }, "mature": {"type": "boolean"}, "standardized_popularity": {"type": "rank_feature"}, "authority_boost": {"type": "rank_feature"}, "authority_penalty": { "type": "rank_feature", "positive_score_impact": False, }, "max_boost": {"type": "rank_feature"}, "min_boost": {"type": "rank_feature"}, } } media_properties = { "image": { "aspect_ratio": { "fields": {"keyword": {"type": "keyword"}}, "type": "text", }, "size": {"fields": {"keyword": {"type": "keyword"}}, "type": "text"}, }, "audio": { "bit_rate": {"type": "integer"}, "sample_rate": {"type": "integer"}, "genres": {"fields": {"keyword": {"type": "keyword"}}, "type": "text"}, }, } media_mappings = common_mappings.copy() media_mappings["properties"].update(media_properties[table_name]) result = {"settings": settings.copy(), "mappings": media_mappings} return result
class IntegralCalculator: def __init__(self): self.value = 0 self.last_time = 0 def get_current_integral(self) -> float: return self.value def get_and_update_integral(self, new_x, new_time) -> float: self.update_integral(new_x, new_time) return self.get_current_integral() def update_integral(self, new_x, new_time): if self.last_time == 0: self.last_time = new_time dt = new_time - self.last_time self.value += dt * new_x self.last_time = new_time
DEBUG = True TEMPLATE_DEBUG = DEBUG # Hosts/domain names that are valid for this site; required if DEBUG is False # See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts ALLOWED_HOSTS = [] ADMINS = ( ('Joe Admin', 'joe@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'chain', 'USER': 'yoda', 'PASSWORD': '123', 'HOST': 'localhost', # use domain socket (127.0.0.1 for TCP) 'PORT': '', 'CONN_MAX_AGE': 600, # keep connections open up to 10 minutes } } # these will be used by the collector scripts and should match the username and # password provided in the .htpasswd file that nginx is looking at COLLECTOR_AUTH = ('yoda', '123') # Make this unique, and don't share it with anybody. SECRET_KEY = 'jakd82l?las{19ka0n%laoeb*klanql0?kdj01kdnc1(n=lbac' # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # In a Windows environment this must be set to your system time zone. TIME_ZONE = 'America/New_York' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' ZMQ_PASSTHROUGH_URL_PULL = 'tcp://127.0.0.1:31416' ZMQ_PASSTHROUGH_URL_PUB = 'tcp://127.0.0.1:31417' # leave the websocket host as None if it is the same as the Django host WEBSOCKET_HOST = None # this is the path the user will see in stream links, so it needs to match your # front end webserver (e.g. nginx) configuration. Note this configuration has # the trailing but not leading slash WEBSOCKET_PATH = 'ws/'
n1 = int(input("Digite n1: ")) n2 = int(input("Digite n2: ")) if (n2 == 0): print("Não é possível dividir por zero.") if (n1 % 3 == 0 and n1 % 5 == 0): print("O número n1 = {} é divisível por 3 e 5.".format(n1)) else: print("O número n1 = {} não é divisível por 3 e 5 ao mesmo tempo".format(n1)) if (n2 % 3 == 0 and n2 % 5 == 0): print("O número n2 = {} é divisível por 3 e 5.".format(n2)) else: print("O número n2 = {} não é divisível por 3 e 5 ao mesmo tempo".format(n2)) if (n1 > 0): print("O número n1 = {} é positivo".format(n1)) if (n1 % 4 == 0): print("e divisível por 4") elif (n1 < 0): print("O número n1 = {} é negativo".format(n1)) if (n1 % 4 == 0): print("e divisível por 4") else: print("O número n1 é zero.") if (n2 > 0): print("O número n2 = {} é positivo".format(n2)) if (n2 % 4 == 0): print("e divisível por 4") elif (n2 < 0): print("O número n2 = {} é negativo".format(n2)) if (n2 % 4 == 0): print("e divisível por 4") else: print("O número n2 é zero.")
def countApplesAndOranges(s, t, a, b, apples, oranges): # Write your code here fallen_apples = 0 fallen_oranges = 0 for apple in apples: if a + apple >= s and a + apple <= t: fallen_apples += 1 for orange in oranges: if b + orange >= s and b + orange <= t: fallen_oranges += 1 print(fallen_apples) print(fallen_oranges)
# Create a set and check if element already exists. class Solution: def containsDuplicate(self, nums: List[int]) -> bool: return len(nums) != len(set(nums))
content = ''' <h1>{{title}}</h1> <p>所有用例:{{all_case_sum}}</p> <p>成功用例:{{success_case_sum}}</p> <p>失败用例:{{errors_case_sum}}</p> <p>跳过用例:{{skipped_case_sum}}</p> <p><a href="{{report_path}}">报告</a></p> ''' def get_maile_html_tpl(): return content if __name__ == '__main__': print(get_maile_html_tpl())
i = 2 while True: if i % 3 == 0: break print(i) i += 2
vector_collection = { 'none': None, 'empty': [], 'numerals': [1, 1, 2, 3, 5, 8, 13, 21], 'strings': ['foo', 'bar', 'zen'], 'cities': ['san fransisco', 'buenos aires', 'bern', 'kinshasa-brazzaville', 'nairobi'] }
# -*- coding: utf-8 -*- DESC = "aai-2018-05-22" INFO = { "SimultaneousInterpreting": { "params": [ { "name": "ProjectId", "desc": "腾讯云项目 ID,可填 0,总长度不超过 1024 字节。" }, { "name": "SubServiceType", "desc": "子服务类型。0:离线语音识别。1:实时流式识别,2,一句话识别。3:同传。" }, { "name": "RecEngineModelType", "desc": "识别引擎类型。8k_zh: 8k 中文会场模型;16k_zh:16k 中文会场模型,8k_en: 8k 英文会场模型;16k_en:16k 英文会场模型。当前仅支持16K。" }, { "name": "Data", "desc": "语音数据,要base64编码。" }, { "name": "DataLen", "desc": "数据长度。" }, { "name": "VoiceId", "desc": "声音id,标识一句话。" }, { "name": "IsEnd", "desc": "是否是一句话的结束。" }, { "name": "VoiceFormat", "desc": "声音编码的格式1:pcm,4:speex,6:silk,默认为1。" }, { "name": "OpenTranslate", "desc": "是否需要翻译结果,1表示需要翻译,0是不需要。" }, { "name": "SourceLanguage", "desc": "如果需要翻译,表示源语言类型,可取值:zh,en。" }, { "name": "TargetLanguage", "desc": "如果需要翻译,表示目标语言类型,可取值:zh,en。" }, { "name": "Seq", "desc": "表明当前语音分片的索引,从0开始" } ], "desc": "该接口是实时流式识别,可同时返回语音识别文本及翻译文本,当前仅支持中文和英文。该接口可配合同传windows客户端,提供会议现场同传服务。" }, "SentenceRecognition": { "params": [ { "name": "ProjectId", "desc": "腾讯云项目 ID,可填 0,总长度不超过 1024 字节。" }, { "name": "SubServiceType", "desc": "子服务类型。2,一句话识别。" }, { "name": "EngSerViceType", "desc": "引擎类型。8k:电话 8k 通用模型;16k:16k 通用模型。只支持单声道音频识别。" }, { "name": "SourceType", "desc": "语音数据来源。0:语音 URL;1:语音数据(post body)。" }, { "name": "VoiceFormat", "desc": "识别音频的音频格式(支持mp3,wav)。" }, { "name": "UsrAudioKey", "desc": "用户端对此任务的唯一标识,用户自助生成,用于用户查找识别结果。" }, { "name": "Url", "desc": "语音 URL,公网可下载。当 SourceType 值为 0 时须填写该字段,为 1 时不填;URL 的长度大于 0,小于 2048,需进行urlencode编码。音频时间长度要小于60s。" }, { "name": "Data", "desc": "语音数据,当SourceType 值为1时必须填写,为0可不写。要base64编码(采用python语言时注意读取文件应该为string而不是byte,以byte格式读取后要decode()。编码后的数据不可带有回车换行符)。音频数据要小于600kB。" }, { "name": "DataLen", "desc": "数据长度,当 SourceType 值为1时必须填写,为0可不写(此数据长度为数据未进行base64编码时的数据长度)。" } ], "desc": "识别60s内的短语音,当音频放在请求body中传输时整个请求大小不能超过600KB,当音频以url方式传输时,音频时长不可超过60s。所有请求参数放在post的body中采用x-www-form-urlencoded(数据转换成一个字符串(name1=value1&name2=value2…)进行urlencode后)编码传输。现暂只支持中文普通话识别,支持识别8k(16k)的16bit的mp3或者wav音频。" }, "Chat": { "params": [ { "name": "Text", "desc": "聊天输入文本" }, { "name": "ProjectId", "desc": "腾讯云项目 ID,可填 0,总长度不超过 1024 字节。" }, { "name": "User", "desc": "json格式,比如 {\"id\":\"test\",\"gender\":\"male\"}。记录当前与机器人交互的用户id,非必须但强烈建议传入,否则多轮聊天功能会受影响" } ], "desc": "提供基于文本的基础聊天能力,可以让您的应用快速拥有具备深度语义理解的机器聊天功能。" }, "TextToVoice": { "params": [ { "name": "Text", "desc": "合成语音的源文本,按UTF-8编码统一计算。\n中文最大支持100个汉字(全角标点符号算一个汉字);英文最大支持400个字母(半角标点符号算一个字母)。包含空格等字符时需要url encode再传输。" }, { "name": "SessionId", "desc": "一次请求对应一个SessionId,会原样返回,建议传入类似于uuid的字符串防止重复。" }, { "name": "ModelType", "desc": "模型类型,1-默认模型。" }, { "name": "Volume", "desc": "音量大小,范围:[0,10],分别对应11个等级的音量,默认为0,代表正常音量。没有静音选项。\n输入除以上整数之外的其他参数不生效,按默认值处理。" }, { "name": "Speed", "desc": "语速,范围:[-2,2],分别对应不同语速:<li>-2代表0.6倍</li><li>-1代表0.8倍</li><li>0代表1.0倍(默认)</li><li>1代表1.2倍</li><li>2代表1.5倍</li>输入除以上整数之外的其他参数不生效,按默认值处理。" }, { "name": "ProjectId", "desc": "项目id,用户自定义,默认为0。" }, { "name": "VoiceType", "desc": "音色<li>0-亲和女声(默认)</li><li>1-亲和男声</li><li>2-成熟男声</li><li>3-活力男声</li><li>4-温暖女声</li><li>5-情感女声</li><li>6-情感男声</li>" }, { "name": "PrimaryLanguage", "desc": "主语言类型:<li>1-中文(默认)</li><li>2-英文</li>" }, { "name": "SampleRate", "desc": "音频采样率:<li>16000:16k(默认)</li><li>8000:8k</li>" }, { "name": "Codec", "desc": "返回音频格式,可取值:wav(默认),mp3" } ], "desc": "腾讯云语音合成技术(TTS)可以将任意文本转化为语音,实现让机器和应用张口说话。\n腾讯TTS技术可以应用到很多场景,比如,移动APP语音播报新闻;智能设备语音提醒;依靠网上现有节目或少量录音,快速合成明星语音,降低邀约成本;支持车载导航语音合成的个性化语音播报。\n内测期间免费使用。" } }
class Solution: def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ l=nums j=0 for i in range(len(l)): if l[i]!=0: nums[j]=l[i] j+=1 for k in range(j,len(nums)): nums[k]=0
# Dev: Miguel Rovira-Gonzalez # Date: 2/11/2020 # Homework: codingbat make bricks python problem, https://codingbat.com/prob/p118406 # Problem to solve: #---------------------------------------------------------------------------------------- # We want to make a row of bricks that is goal inches long. # We have a number of small bricks (1 inch each) and big bricks (5 inches each). # Return True if it is possible to make the goal by choosing from the given bricks. # This is a little harder than it looks and can be done without any loops. See also: Introduction to MakeBricks """ make_bricks(3, 1, 8) → True make_bricks(3, 1, 9) → False make_bricks(3, 2, 10) → True """ def make_bricks(small_brick, big_brick, goal): # one small brick = 1 inch, so 3 small would be 3 inches # one big brick would be 5 inches so two big bricks would be 10 inches # you don't have to use all the bricks small = 1 big = 5 if (small_brick * small) + (big_brick * big) == goal: return True elif (small_brick * small) == goal: return True elif (big_brick * big) == goal: return True elif (big_brick * big) % big_brick == 0: big_brick = big if (small_brick * small) + big_brick == goal: return True elif (small_brick * small) + (big_brick * 2) == goal: return True elif (small_brick * small) + (big_brick * 1) == goal: return True else: return False # print(make_bricks(3, 1, 8)) # Expects True # print(make_bricks(3, 1, 9)) # Expects False # print(make_bricks(3, 2, 10)) # Expects True # print(make_bricks(3, 2, 8)) # Expect True # print(make_bricks(3, 2, 9)) # Expects False # print(make_bricks(3, 2, 9)) # Expects → False # print(make_bricks(1, 4, 11)) # Expects True # print(make_bricks(0, 3, 10)) # Expects True print(make_bricks(3, 1, 7)) # Expects True # make_bricks(1, 1, 7) → False False OK # make_bricks(2, 1, 7) → True True OK # make_bricks(7, 1, 11) → True False X # make_bricks(7, 1, 8) → True False X # make_bricks(7, 1, 13) → False False OK # make_bricks(43, 1, 46) → True False X # make_bricks(40, 1, 46) → False False OK # make_bricks(40, 2, 47) → True False X # make_bricks(40, 2, 50) → True True OK # make_bricks(40, 2, 52) → False False OK # make_bricks(22, 2, 33) → False False OK # make_bricks(0, 2, 10) → True True OK # make_bricks(1000000, 1000, 1000100) → True False X # make_bricks(2, 1000000, 100003) → False False OK # make_bricks(20, 0, 19) → True False X # make_bricks(20, 0, 21) → False False OK # make_bricks(20, 4, 51) → False False OK # make_bricks(20, 4, 39) → True False X # other tests # X
# list in python and follow indexing rule, start from 0 thisList = ["pooya","mohammad","Mahdi","Alireza"] print(thisList) thisList[1] = "Eshghe Man" print(thisList) # The list() constructor include add item to list and delete the item listTwo = list(("apple","melon","orange")) print(listTwo) # append() use to add item to the list listTwo.append("mandarin") print(listTwo) # instead the way I did for removing the element we can write the name of item listTwo.remove(listTwo[2]) print(listTwo) # get the length of the list print(len(listTwo)) # remove all the element of the list print(thisList) print(thisList.clear()) # copy of list and store in new var and we can print it x = listTwo.copy() print(x) # by count() we can get how many time variable repeat listOne = ["waac","nowo","carea","jento","nowo","waac","nowo"] z = listOne.count("nowo") print(z) print(listOne.count(listOne[0])) # built in function extend use to concat two list listOne.extend(listTwo) print(listOne) # extend with integers points = (1,2,3,4,5,6) listOne.extend(points) print(listOne) # get the index number of element in list, and you need to write the name of element animal = ["horse","eagle","elephant","monkey"] print(animal) print(animal.index("horse")) # insert element in specific position animal.insert(1,"chipmunks") print(animal) # pop popout element from list by index number animal.pop(0) print(animal) # reverse use to reverse the order of function animal.reverse() print(animal) # sort use for sort elements """will back here after function"""
''' Key points: - recognize that this is very similar to merging intervals (https://leetcode.com/problems/merge-intervals/description/) - it doesn't matter which employee an interval belongs to, so just flatten - can build result array while merging, don't have to do afterward (and don't need full merged arr) ''' def employeeFreeTime(self, schedule): ints = sorted([i for s in schedule for i in s], key=lambda x: x.start) res, pre = [], ints[0] for i in ints[1:]: if i.start <= pre.end and i.end > pre.end: pre.end = i.end elif i.start > pre.end: res.append(Interval(pre.end, i.start)) pre = i return res
""" Crie um programa que solicita vários números inteiros ao usuário, pergunte se ele quer continuar digitando e caso responda não, informe o total de números digitados, o menor, o maior e a média entre eles. """ total = soma = maior = 0 menor = 9999999999999999 resposta = 'S' while resposta in 'S': num = int(input('Digite um número: ')) total += 1 soma += num if num > maior: # 30 > 0 maior = num if num < menor: # 30 < 99999999999999 menor = num resposta = str(input('\033[32mQuer continuar? \033[m')).upper().strip() if resposta == 'N': print('Encerrando o sistema') print() # fora do while ------------------------ print(f'Total de número inseridos: {total}\nSoma dos números inseridos: {soma}\n' f'Média dos números inseridos: {soma / total:.1f}\nMaior número inserido: {maior}\n' f'Menor número inserido: {menor}') 0 2 0 1000.0 todos = [] while True: todos.append(int(input('Digite um número: '))) resposta = str(input('Quer continuar: ')).strip().upper() if resposta == 'N': break if 15 in todos: print('Achei') print(f'Total de número inseridos: {todos}\nSoma dos números inseridos: {sum(todos)}\n' f'Média dos números inseridos: {sum(todos) / len(todos)}\nMaior número inserido: {max(todos)}\n' f'Menor número inserido: {min(todos)}')
#!/usr/bin/python # -*- coding: utf-8 -*- # Дано натуральное число n. Выведите все числа от 1 до n. Без использования циклов. def print_and_decr(i: int) -> int: print("%d\n", i) i -= 1 if i > 1: print_and_decr(i) print_and_decr(821)
ligne_vide = ['o','o','o','o','o','o','o','o','o'] ligne_courte = ['o','o','.','.','.','.','.','o','o'] ligne_longue = ['o','.','.','.','.','.','.','.','o'] arche_vide = [ligne_vide,ligne_courte,ligne_longue,ligne_longue,ligne_courte,ligne_vide] #print(arche_vide) def affiche_ligne (l) : s='' for c in l : s+=c print(s) def affiche_grille (g) : for i in range(len(g)-1,-1,-1) : affiche_ligne(g[i]) #affiche_grille(arche_vide) def copie_grille(g) : r = [] for l in g : r+=[list(l)] return r #arche_pleine=copie_grille(arche_vide) #arche_pleine[2][1]='i' #affiche_grille(arche_vide) #affiche_grille(arche_pleine) lion_1 = ('L',1,[(0,0),(1,0)]) lion_2 = ('L',2,[(0,0),(0,1),(1,1)]) girafe_1 = ('G',1,[(0,0),(1,0),(1,1)]) girafe_2 = ('G',2,[(0,0),(0,1)]) hippopotame_1 = ('H',1,[(0,0),(1,0)]) hippopotame_2 = ('H',2,[(0,0),(1,0),(2,0)]) zebre_1 = ('Z',1,[(0,0),(1,0)]) zebre_2 = ('Z',2,[(0,0),(0,1)]) elephant_1 = ('E',1,[(0,0),(1,0)]) elephant_2 = ('E',2,[(0,0),(0,1),(1,0)]) liste_animaux = [lion_1,lion_2,girafe_1,girafe_2,hippopotame_1,hippopotame_2,zebre_1,zebre_2,elephant_1,elephant_2] #print(liste_animaux) def est_dans_grille (position) : return position[0] >= 0 and position[0]<=8 and position[1]>=0 and position[1]<=7 def case_libre (position,grille) : return est_dans_grille(position) and grille[position[1]][position[0]] == '.' def place_libre (position,grille,animal) : r = True (x,y) = position for (dx,dy) in animal[2] : p = (x+dx,y+dy) r = r and case_libre(p,grille) return r #test, on attend False, True, False, True #print(place_libre((0,0),arche_vide,elephant_2)) #print(place_libre((2,1),arche_vide,elephant_2)) #print(place_libre((5,4),arche_vide,elephant_2)) #print(place_libre((6,3),arche_vide,elephant_2)) def installe_animal (position,grille,animal) : (x,y) = position for (dx,dy) in animal[2] : p = (x+dx,y+dy) grille[p[1]][p[0]] = animal[0] def enleve_animal (position,grille,animal) : (x,y) = position for (dx,dy) in animal[2] : p = (x+dx,y+dy) grille[p[1]][p[0]] = '.' #arche_pleine = copie_grille(arche_vide) #installe_animal((6,3),arche_pleine,elephant_2) #affiche_grille(arche_pleine) #enleve_animal((6,3),arche_pleine,elephant_2) #affiche_grille(arche_pleine) def installe_tous (placement,grille) : for (a,p) in placement : if not place_libre(p,grille,a) : return False else : installe_animal(p,grille,a) return True placement_1 = [(lion_1,(2,4)),\ (lion_2,(4,3)),\ (girafe_1,(6,2)),\ (girafe_2,(6,3)),\ (hippopotame_1,(2,1)),\ (hippopotame_2,(4,1)),\ (zebre_1,(3,2)),\ (zebre_2,(5,2)),\ (elephant_1,(2,3)),\ (elephant_2,(1,2))] arche_pleine = copie_grille (arche_vide) print("installe tous = ", installe_tous(placement_1,arche_pleine)) affiche_grille(arche_pleine) print("") def decale_animal (animal,position) : place = [] (x,y) = position for (dx,dy) in animal[2] : place += [(x+dx,y+dy)] return place def cases_voisines (place) : voisines = [] for (x,y) in place : voisines += [(x+1,y),(x,y+1),(x-1,y),(x,y-1)] return voisines def sont_voisins (a1,p1,a2,p2) : place_1 = decale_animal(a1,p1) place_2 = decale_animal(a2,p2) voisines_1 = cases_voisines(place_1) r = False for c in voisines_1 : r = r or ( c in place_2 ) return r # test sur placement_1 #print(sont_voisins(lion_1,(2,4),lion_2,(4,3))) #print(sont_voisins(girafe_1,(6,2),girafe_2,(6,3))) #print(sont_voisins(lion_1,(2,4),girafe_2,(6,3))) #print(sont_voisins(lion_2,(4,3),girafe_2,(6,3))) def cherche_animal (type_anim,num,installation) : for i in range(len(installation)) : (a,p) = installation[i] if a[0] == type_anim and a[1] == num : return i return -1 #print (cherche_animal('G',2,placement_1)) #print (cherche_animal('Z',1,placement_1)) #print (cherche_animal('G',3,placement_1)) def verifie_voisinages (installation) : r = True for t in ['L','G','H','Z','E'] : i1 = cherche_animal(t,1,installation) i2 = cherche_animal(t,2,installation) (a1,p1) = installation[i1] (a2,p2) = installation[i2] r = r and sont_voisins (a1,p1,a2,p2) # print (a1,a2,sont_voisins (a1,p1,a2,p2)) return r #print(verifie_voisinages(placement_1)) def calculer_installation (grille, animaux, installation) : if animaux == [] : return verifie_voisinages(installation) else : a = animaux[0] for y in range(len(grille)) : for x in range(len(grille[0])) : if place_libre((x,y),grille,a) : installe_animal((x,y),grille,a) r = calculer_installation(grille,animaux[1:],[(a,(x,y))] + installation) if r : return r else : enleve_animal((x,y),grille,a) return False arche = copie_grille(arche_vide) installe_animal((4,1),arche,lion_2) affiche_grille(arche) installation = [(lion_2,(4,1))] animaux = [lion_1,girafe_1,girafe_2,hippopotame_1,hippopotame_2,zebre_1,zebre_2,elephant_1,elephant_2] calculer_installation(arche,animaux,installation) affiche_grille(arche)
class TalkMessage: def __init__(self, messageId, timeStamp, body, senderAvatarId, senderAvatarName, senderAccountId, senderAccountName, receiverAvatarId, receiverAvatarName, receiverAccountId, receiverAccountName, talkType, extraInfo=None): self.timeStamp = timeStamp self.body = body self.senderAvatarId = senderAvatarId self.senderAvatarName = senderAvatarName self.senderAccountId = senderAccountId self.senderAccountName = senderAccountName self.receiverAvatarId = receiverAvatarId self.receiverAvatarName = receiverAvatarName self.receiverAccountId = receiverAccountId self.receiverAccountName = receiverAccountName self.talkType = talkType self.extraInfo = extraInfo self.messageId = messageId def getMessageId(self): return self.messageId def setMessageId(self, id): self.messageId = id def getTimeStamp(self): return self.timeStamp def setTimeStamp(self, timeStamp): self.timeStamp = timeStamp def getBody(self): return self.body def setBody(self, body): self.body = body def getSenderAvatarId(self): return self.senderAvatarId def setSenderAvatarId(self, senderAvatarId): self.senderAvatarId = senderAvatarId def getSenderAvatarName(self): return self.senderAvatarName def setSenderAvatarName(self, senderAvatarName): self.senderAvatarName = senderAvatarName def getSenderAccountId(self): return self.senderAccountId def setSenderAccountId(self, senderAccountId): self.senderAccountId = senderAccountId def getSenderAccountName(self): return self.senderAccountName def setSenderAccountName(self, senderAccountName): self.senderAccountName = senderAccountName def getReceiverAvatarId(self): return self.receiverAvatarId def setReceiverAvatarId(self, receiverAvatarId): self.receiverAvatarId = receiverAvatarId def getReceiverAvatarName(self): return self.receiverAvatarName def setReceiverAvatarName(self, receiverAvatarName): self.receiverAvatarName = receiverAvatarName def getReceiverAccountId(self): return self.receiverAccountId def setReceiverAccountId(self, receiverAccountId): self.receiverAccountId = receiverAccountId def getReceiverAccountName(self): return self.receiverAccountName def setReceiverAccountName(self, receiverAccountName): self.receiverAccountName = receiverAccountName def getTalkType(self): return self.talkType def setTalkType(self, talkType): self.talkType = talkType def getExtraInfo(self): return self.extraInfo def setExtraInfo(self, extraInfo): self.extraInfo = extraInfo
''' While Loops Used to execute a set of statements(code) continuously as long as a condition is True. The while loop needs to be setup in a way that as long as a condition is True, Then stop when the condition becomes False. While loop can have optional else clause. ''' i = 1
def get_f(f, i, mode): try: if mode == 0: return f[f[i]] if mode == 1: return f[i] except KeyError: return 0 raise NotImplementedError def set_f(f, value, i, mode): if mode == 0: f[f[i]] = value return if mode == 1: f[i] = value return raise NotImplementedError def main(): f = [int(i) for i in [line.rstrip("\n") for line in open("Data.txt")][0].split(",")] input = 1 i = 0 while True: opcode = int(str(f[i])[-2:]) try: immediate = int(str(f[i])[:-2]) except ValueError: immediate = 0 i1 = immediate % 10 i2 = immediate//10 % 10 if opcode == 99: break elif opcode == 1: set_f(f, get_f(f, i + 1, i1) + get_f(f, i + 2, i2), i + 3, 0) i += 4 elif opcode == 2: set_f(f, get_f(f, i + 1, i1)*get_f(f, i + 2, i2), i + 3, 0) i += 4 elif opcode == 3: set_f(f, input, i + 1, 0) i += 2 elif opcode == 4: print(get_f(f, i + 1, i1)) i += 2 else: raise NotImplementedError if __name__ == "__main__": main()
""" Provides hard-coded values used in this package. No imports are allowed since many other modules import this one """ __copyright__ = "Copyright 2020, Datera, Inc." VERSION = "1.2.26" VERSION_HISTORY = """ Version History: 1.1.0 -- Initial Version 1.1.1 -- Metadata Endpoint, Pep8 cleanup, Logging revamp Python 3 compatibility, Versioning and Version Headers, 1.1.2 -- User, Event_system, Internal, Alerts Endpoints/Entities 1.2.0 -- v2.2 support, API module refactor 1.2.1 -- Massive rewrite to use /api endpoints instead of manually curated list. Log compression 1.2.2 -- Change python version check in Connection to be forgivness based 1.2.4 -- Named object support, hw metics support 1.2.5 -- v2.2 Paging support 1.2.6 -- Bugfix for API v2.1 limit parameter 1.2.7 -- Changed connection to use requests library, added support for logs_upload endpoint. Added 'strict' parameter to constructor which allows disabling endpoint validity checks if set to 'False' 1.2.8 -- Added support for certs, trace_ids and standard logging 1.2.9 -- Added stream call for use with Metrics style endpoints 1.2.10 -- Added back create/delete hooks, implemented hook loading and a hook inheritance interface. 1.2.11 -- Increased log rotation size before compression to 50MB and decreased number of retained rotations to 5 1.2.12 -- Added capability of adding custom headers to requests 1.2.13 -- Added LDAP support to UDC config 1.2.15 -- Fixed ldap server bug, dropped get_argparser requirement from scaffold, changed required requests version because of security vulnerability. Updated the readme. 1.2.16 -- 503 retry support 1.2.17 -- Bugfix for issue that prevented older API versions from being used 1.2.18 -- Added TLS verification support. Fixed bug where params were not preserved during accumulation. 1.2.19 -- Bugfix for disable_log parameter 1.2.20 -- Bugfix for incorrect API version request 1.2.21 -- Better support for Alert entities, basic healthcheck function, parameter for changing cached-schema location 1.2.22 -- Better retry support. Bugfix for mutated arguments during retries 1.2.23 -- Fix for failed retry POST requests 1.2.24 -- Accumulation skip for 3.2.X product versions when 'filter' parameter is present. Added version check system and local version update during login. 1.2.25 -- Version increment to workaround PyPI .24 version caching issue 1.2.26 -- Minor bugfix release. """ API_VERSIONS = ("v2", "v2.1", "v2.2") REST_PORT = 7717 REST_PORT_HTTPS = 7718 DEFAULT_HTTP_TIMEOUT = 300 PYTHON_2_7_0_HEXVERSION = 0x020700f0 PYTHON_2_7_9_HEXVERSION = 0x020709f0 PYTHON_3_0_0_HEXVERSION = 0x030000f0 DEFAULT_CACHED_SCHEMA = "/tmp/.cached-schema" RETRY_TIMEOUT = 300
USER = "__DUMMY_TRANSFORMERS_USER__" FULL_NAME = "Dummy User" PASS = "__DUMMY_TRANSFORMERS_PASS__" # Not critical, only usable on the sandboxed CI instance. TOKEN = "hf_94wBhPGp6KrrTH3KDchhKpRxZwd6dmHWLL" ENDPOINT_PRODUCTION = "https://huggingface.co" ENDPOINT_STAGING = "https://hub-ci.huggingface.co" ENDPOINT_STAGING_BASIC_AUTH = f"https://{USER}:{PASS}@hub-ci.huggingface.co" ENDPOINT_PRODUCTION_URL_SCHEME = ( ENDPOINT_PRODUCTION + "/{repo_id}/resolve/{revision}/{filename}" )
print("copy content from auto created ex23_sample_05.txt to ex23_sample_06.txt using 1 line only") input('In powershell: echo "This is a unicode Test." > ex23_sample_05.txt ') in_file = open('c:\\users\\roy\\ex23_sample_05.txt', encoding = 'utf-16').read() out_file = open('c:\\users\\roy\\ex23_sample_06.txt', 'w', encoding = 'utf-16').write(in_file) print("DONE!\n") #------------------------------------------------------------------- print("-------------------------------------------------------------") print("copy content from languages.txt within ex23 to languages2.txt using 1 line only") in_file = open('c:\\users\\roy\\languages.txt', encoding = 'utf-8').read() # When set encoding = utf-16 --> UnicodeDecodeError: 'utf-16-le' codec can't decode bytes in position 812-813: illegal UTF-16 surrogate # When set encoding = utf-16, errors = 'ignore' --> UnicodeError: UTF-16 stream does not start with BOM out_file = open('c:\\users\\roy\\languages2.txt', 'w', encoding = 'utf-8').write(in_file) # Before add encoding = utf-8 -->UnicodeEncodeError: 'gbk' codec can't encode character '\u0a73' in position 4: illegal multibyte sequence print("DONE!\n") # bytes can only contain ASCII literal characters.
sum = 0 count = 0 while True: try: name = input() distance = int(input()) sum += distance count += 1 except EOFError: break print("{:.1f}".format(sum/count))
# -*- coding: utf-8 -*- #from scrapy.settings.default_settings import DOWNLOAD_DELAY #from scrapy.settings.default_settings import ITEM_PIPELINES # Scrapy settings for fbo_scraper project # # For simplicity, this file contains only the most important settings by # default. All the other settings are documented here: # # http://doc.scrapy.org/en/latest/topics/settings.html # BOT_NAME = 'packard_scraper' SPIDER_MODULES = ['packard_scraper.spiders'] ITEM_PIPELINES = {'packard_scraper.pipelines.FboScraperExcelPipeline':0} NEWSPIDER_MODULE = 'packard_scraper.spiders' ROBOTSTXT_OBEY = True RANDOMIZE_DOWNLOAD_DELAY = True DOWNLOAD_DELAY = 5.0 # Crawl responsibly by identifying yourself (and your website) on the user-agent # !!! ATTENTION: PLEASE REPLACE WITH YOUR OWN WEBSITE IF YOU ARE GOING TO USE USER_AGENT! USER_AGENT = 'packard_scraper (+http://research.umd.edu/)'
#Factorial de un numero, usar recursividad. def factorial(number): if number == 0: return 1 return number * factorial(number - 1) if __name__ == '__main__': number = int(input('Ingrese numero a convertir en factorial: ')) result = factorial(number) print('El resultado es: {}'.format(result))
""" Given the root of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.   Example 1: Input: root = [5,3,6,2,4,null,8,1,null,null,null,7,9] Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9] Example 2: Input: root = [5,1,7] Output: [1,null,5,null,7]   Constraints: The number of nodes in the given tree will be in the range [1, 100]. 0 <= Node.val <= 1000 """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def increasingBST(self, root: TreeNode) -> TreeNode: def inorder(root, arr): if root is None: return inorder(root.left, arr) arr.append(root.val) inorder(root.right, arr) arr = [] inorder(root, arr) ps = [] for i, val in enumerate(arr): c = TreeNode(val) if i > 0: ps[-1].right = c ps.append(c) return ps[0]
class Student: def __init__(self, name, school): self.name = name self.school = school self.marks = [] def average(self): return sum(self.marks) / len(self.marks) def go_to_school(self): return "I'm going to {}".format(self.school) anna = Student("Anna", "Oxford") rolf = Student("Rolf", "Harvard") print(anna.go_to_school()) print(rolf.go_to_school()) ### class Student: def __init__(self, name, school): self.name = name self.school = school self.marks = [] def average(self): return sum(self.marks) / len(self.marks) def go_to_school(self): return "I'm going to school" anna = Student("Anna", "Oxford") rolf = Student("Rolf", "Harvard") print(anna.go_to_school()) print(rolf.go_to_school()) ### class Student: def __init__(self, name, school): self.name = name self.school = school self.marks = [] def average(self): return sum(self.marks) / len(self.marks) @staticmethod def go_to_school(): return "I'm going to school" anna = Student("Anna", "Oxford") rolf = Student("Rolf", "Harvard") print(anna.go_to_school()) print(rolf.go_to_school()) ### class Student: def __init__(self, name, school): self.name = name self.school = school self.marks = [] def average(self): return sum(self.marks) / len(self.marks) def friend(self, friend_name): return Student(friend_name, self.school) anna = Student("Anna", "Oxford") friend = anna.friend("Greg") print(friend.name) print(friend.school)
"""Top-level package for fdf.""" __author__ = """Ledenel Intelli""" __email__ = 'ledenelintelli@gmail.com' __version__ = '0.1.9'
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Andy Wilson, Michael Darling, David Stracuzzi, Shelley Leger Sandia National Laboratories February 25, 2020 Defines set of test sudoku problems to use to test the sudoku infrastructure """ puzzles = { 'test2-i24e40': '300000700000001000000060000000700015400300000000000020610000800000540900002000000', 'test3-i29e35': '300000700000001000000060000000700015900500000000000020610000800000340900002000000', 'test4-i28e36': '300000700000001000000090000000700014800600000000000020610000800000540300002000000', 'test5-i23e41': '560000040000010700000000000000400060030000005018000000700604000200000100000000003', 'test6-i26e38': '560000040000010700000000000000800060030000005019000000700604000200000100000000003', 'test7-i26e36hp10': '010000200800300000000000500050000410000700060002008000900000073000050000000040000', 'test8-i32e32hp2': '010000208500406000000000000306000050000020700004000000020010000000300060800000000', 'test9-i29e35hp2': '083000200000091000000000000100000409020300000000070000007600500000800030900000000', 'test10-i29e35hp7': '000090750801000000000000000050000400000801000000600000470020000000100006300000080', 'test11-i36e28hp2': '000090800704000000100000000050480000000000010090000000200600500000107000000000308', 'test12-i36e28np1': '300000700000010400506000000000200035000000080000070000070600100040005000000300000', 'test13-i34e30np1': '100000300700600000000200000060030400025000000000000800007500002300080000000000010', 'test14-i24e38np3': '100000300800007000000200000027640000060500000000000100000000042300080000000000060', 'test15-i28e34np3': '100000305600900000000080200000760010020800000050000000400000700000001000000050000', 'test16-i26e36np3': '100000305800400000000070200000640080020700000050000000400000600000001000000050000', 'test17-i24e38np4hp4': '300000670000201000080000000000570800021000000400000000600030000000000042000000009', 'test18-i29e35np3hp4': '560000030000901000000000000809000010070060000000000000104800000000050607000000200', 'test19-i21e41np8hp3': '100000306070800000000000200000236000004000085000000000000500040390000000600000000', 'test20-i22e42np3hp7': '100000306500040000000010000000000051060000200030800000700000040000602000000300000', 'test21-i16e47np1hp2': '100000340406000800000900000800040000000700009000000000097000050000031000020000000', 'test22-i33e18nt1xw1': '000400067064200000007106042000860304401000700706940000170004000940000200000010400', 'test23-i16e32nt1xw1': '700000021500402000200807000021500000073200610045700230407000802302070100106020000', 'test24-i10e41nt2xw2': '000500061516020000970060000061400000000650910000000680100806000300000506600705108', 'test25-i16e32nt1xw1': '400000081300021000100700000048010000000060210016000000601000354700504108854136000', 'test26-i8e41pp1nt4xw2xyzw1': '000605021070302000020408000100960250032087400760020000200850000000700802600200000', 'test27-i32e31yw3': '560000040700003000000800000008000030090200000000040000600050100000000908000000200', 'test28-i27e36yw1': '205700000800050300000000000090000100000200000000000030030081000400000020000900007', 'test29-i27e36yw1': '700200050000030080100000000400060700060080000000000100039500000000700000080000000', 'test30-i29e34yw1': '080000670000310000000000000000200005240000000000000013501400000000007800300000000', 'test31-i36e27yw1': '080000670000510000000000000000200004230000000000000051405300000000007800100000000', 'test32-i25e38np2hp4yw1': '000200090010000030050008000200900000000400500000000100400006020000030700000010000', 'test33-i26e38np2hp3yw1': '042080000000000001080000000700103000000000480600000000150600000000000540000900000', 'test34-i26e38np2hp3yw1': '042080000000000001080000000700103000000000480900000000150600000000000540000700000', 'test35-i24e40np3hp2yw1': '000040380050070000010000000000502008600000700000100000000200010407000000300000000', 'test36-i30e33np2hp2yw1': '100036000020000840000000000603050000500700000000000020040800000000000503000200000', 'easy1': '..3.2.6..9..3.5..1..18.64....81.29..7.......8..67.82....26.95..8..2.3..9..5.1.3..', 'easy2': '......9.7...42.18....7.5.261..9.4....5.....4....5.7..992.1.8....34.59...5.7......', 'easy3': '...1254....84.....42.8......3.....95.6.9.2.1.51.....6......3.49.....72....1298...', 'easy4': '..61.24.......457..2.9.31.8.8...56.96...9...19.13...4.5.42.9.8..627.......85.13..', 'medium1': '...439...4..6..8..395.....472..8..9....217....3..9..282.....417..9..2..3...841...', 'hard1': '4.....8.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......', # 'hard2': '6.2.5.........3.4..........43...8....1....2........7..5..27...........81...6.....', # 'hard3': '...5...........5.697.....2...48.2...25.1...3..8..3.........4.7..13.5..9..2...31..', 'hard4': '3..6.9.12..7.....6.2...1......74...3..29.65..1...23......8...9.5.....3..29.3.7..4', 'fiendish1': '.....5.8....6.1.43..........1.5........1.6...3.......553.....61........4.........', 'fiendish2': '85...24..72......9..4.........1.7..23.5...9...4...........8..7..17..........36.4.', # 'fiendish3': '..53.....8......2..7..1.5..4....53...1..7...6..32...8..6.5....9..4....3......97..', 'fiendish4': '..32.4...24.5...7.......6..9..7..1...87...53...2..5..7..1.......3...6.98...8.23..', 'naked_single_test': '246.7..38...3.6.7437..4.6....8.2.7..1.......6..7.3.4....4.8..6986.4....791..6..42', 'naked_pair_test': '4.....938.32.941...953..24.37.6.9..4529..16736.47.3.9.957..83....39..4..24..3.7.9', 'naked_pair_test_2': '.8..9..3..3.....699.2.63158.2.8.459.8519.7.463946.587.563.4.9872......15.1..5..2.', 'hidden_pair_test': '.........9.46.7....768.41..3.97.1.8.7.8...3.1.513.87.2..75.261...54.32.8.........', 'hidden_pair_test_2': '72.4.8.3..8.....474.1.768.281.739......851......264.8.2.968.41334......8168943275', 'naked_triple_test': '.7.4.8.29..2.....4854.2...7..83742...2.........32617......936122.....4.313.642.7.', 'naked_triple_test_2': '294513..66..8423193..697254....56....4..8..6....47....73.164..59..735..14..928637', 'hidden_triple_test': '.....1.3.231.9.....65..31..6789243..1.3.5...6...1367....936.57...6.198433........', 'naked_quad_test': '....3..86....2..4..9..7852.3718562949..1423754..3976182..7.3859.392.54677..9.4132', # 'hidden_quad_test': '9.15...46425.9..8186..1..2.5.2.......19...46.6.......2196.4.2532...6.817.....1694', 'pointing_pair_test': '.179.36......8....9.....5.7.72.1.43....4.2.7..6437.25.7.1....65....3......56.172.', 'pointing_pair_test_2': '.32..61..41..........9.1...5...9...4.6.....713...2...5...5.8.........519.57..986.', 'pointing_triple_test': '93..5....2..63..95856..2.....318.57...5.2.98..8...5......8..1595.821...4...56...8', 'box_line_reduction': '.16..78.3.9.8.....87...1.6..48...3..65...9.82.39...65..6.9...2..8...29369246..51.', 'box_line_reduction_2': '.2.9437159.4...6..75.....4.5..48....2.....4534..352....42....81..5..426..9.2.85.4', 'xwing_test': '1.....569492.561.8.561.924...964.8.1.64.1....218.356.4.4.5...169.5.614.2621.....5', # 'xwing_test_2': '.......9476.91..5..9...2.81.7..5..1....7.9....8..31.6724.1...7..1..9..459.....1..', 'ywing_test': '9..24.....5.69.231.2..5..9..9.7..32...29356.7.7...29...69.2..7351..79.622.7.86..9', # 'xyz_wing_test': '.92..175.5..2....8....3.2...75..496.2...6..75.697...3...8.9..2.7....3.899.38...4.', # 'xyz_wing_test_2': '6.......85..9.8..782...1.3.34.2.9.8.2...8.3..18.3.7.2575.4...929....5..44...9...3', # 'swordfish_test_333': '52941.7.3..6..3..2..32......523...76637.5.2..19.62753.3...6942.2..83.6..96.7423.5', # 'swordfish_test_222': '926...1..537.1.42.841...6.3259734816714.6..3.36812..4.1.2....84485.7136.6.3.....1', # 'swordfish_test_323': '.2..43.69..38962..96..25.3.89.56..136...3.....3..81.263...1..7...96743.227.358.9.', # TODO MAL this and the others commented out don't finish without help 'underconstrained1': '.8...9743.5...8.1..1.......8....5......8.4......3....6.......7..3.5...8.9724...5.', # 'underconstrained2': '53..7....6..1.5....98....6.8.......34..8.3..17...2...6.6....28....419..5....8..79', # 'underconstrained3': '..97.......48.9.7......2.3....3.6...3..1....9..6....58..8.3....5.....1869.2......', # 'underconstrained4': '......23....3.8.64....4.9.8573.......8652937.......8456.5.1....71...2....48......', # 'underconstrained5': '.21...9.36........83962...19...31.....2...3.....9....87...69152........92.5...74.', # 'underconstrained6': '.7.4.1..8.16.3...45.4........7.8..9.6..123........6......6...532.8.....6.......8.', # INSOLUBLE BY PROPAGATION (BASED ON EASY 0) 'insoluble_by_propagation': '..3.2.6..9..3.5..1..18.64....81.29..7.......8..67.82....26.95..8..2.3..9..5.1.8..', # INSOLUBLE BY INITIAL STATE CONFLICT (BASED ON EASY 0) 'insoluble_by_initial_state_conflict': '..3.2.6..9..3.5..1..18.64....81.29..7.......8..67.82....26.95..8..2.3..9..5.1.6..', } games = { 'test_game1_6_operators_open': { 'puzzles': ['test2-i24e40', 'easy1', 'xwing_test', 'hard4', 'underconstrained1', 'test7-i26e36hp10'], 'config_alterations': {} }, 'test_game1_6': { 'puzzles': ['test2-i24e40', 'easy1', 'xwing_test', 'hard4', 'underconstrained1', 'test7-i26e36hp10'], 'config_alterations': {'randomly_apply': ['select_ops_upfront']} }, 'test_game1_4': { 'puzzles': ['test2-i24e40', 'xwing_test', 'hard4', 'underconstrained1'], 'config_alterations': {'randomly_apply': ['select_ops_upfront']} }, 'test_game_ptgprs': { 'puzzles': ['pointing_pair_test...goal=A9', 'pointing_pair_test...goal=E2', 'pointing_pair_test...goal=B1'], 'config_alterations': {'randomly_apply': ['select_ops_upfront']} }, 'pilot_test_a_board': { # 'test7-i26e36hp10?goal=C6?costlyops=inclusion,pointingpairs,nakedpairs,xwings?name=Pilot Test Board?select_ops_upfront' 'puzzles': ['test7-i26e36hp10...goal=C6...name=Pilot Test Board...question=Can C6 be a 7?', 'test7-i26e36hp10...goal=C6...name=Pilot Test Board2...select_ops_upfront...question=Can C6 be odd?'], 'config_alterations': {'costly_ops': ['inclusion', 'pointingpairs', 'nakedpairs', 'xwings']} }, 'test_logical_operators_in_sequence': { 'puzzles': ['test2-i24e40...name=Test Inclusion...goal=C6...question=Can C6 be 4?...answer=no', 'test9-i29e35hp2...name=Test Pointing Pairs...goal=C6...question=Can C6 equal A2 or A3?...answer=yes', 'test7-i26e36hp10...name=Test Naked Pairs...goal=C6...question=Can C6 be greater than 5?...answer=no', 'hidden_pair_test_2...name=Test Hidden Pairs...goal=F7...question=Can F7 be odd?...answer=yes', 'box_line_reduction_2...name=Test Pointing Triples...goal=C5...question=Can C5 be less than 5?...answer=yes', 'hidden_triple_test...name=Test Naked Triples...goal=A9...question=Can A9 be greater than 5?...answer=no', #'...name=Test Hidden Triples...goal=...question=', 'xwing_test...name=Test X-Wings...goal=G6...question=Can G6 equal A7 or A8 or A9?...answer=no', 'test29-i27e36yw1...name=Test Y-Wings...goal=E8...question=Can E9 be a square (1 or 4 or 9)?', #'...name=Test XYZ-Wings...goal=...question=', #'...name=Test Naked Quads...goal=...question=', #'...name=Test Hidden Quads...goal=...question=', ] }, 'training_games': { 'puzzles': [ # Requires 2 calls to inclusion, resolved after 1st call to inclusion (doesn't require 2nd) 'easy2...goal=E7...name=Training #1...question=Can E7 be 6?...answer=no', 'easy2...goal=E7...name=Training #1...question=Can E7 be 6?...answer=no...select_ops_upfront', # Requires pointingpairs and inclusion, with final call to pointing pairs to resolve (no call to inclusion after pointing pairs) 'test11-i36e28hp2...goal=B8...name=Training #2...question=Can B8 be odd?...answer=yes', 'test11-i36e28hp2...goal=B8...name=Training #2...question=Can B8 be odd?...answer=yes...select_ops_upfront', # Requires pointingpairs and inclusion, but doesn't require last call to inclusion _after_ pointing pairs 'test16-i26e36np3...goal=F3...name=Training #3...question=Can F3 be 3 or 7?...answer=no', 'test16-i26e36np3...goal=F3...name=Training #3...question=Can F3 be 3 or 7?...answer=no...select_ops_upfront', ] }, 'training_games_select_ops_upfront': { 'puzzles': [ 'easy2...goal=E7...name=Training #1...question=Can E7 be 6?...answer=no...select_ops_upfront', 'test11-i36e28hp2...goal=B8...name=Training #2...question=Can B8 be odd?...answer=yes...select_ops_upfront', 'test16-i26e36np3...goal=F3...name=Training #3...question=Can F3 be 3 or 7?...answer=no...select_ops_upfront', ] }, 'training_games_always_select': { 'puzzles': [ 'easy2...goal=E7...name=Training #1...question=Can E7 be 6?...answer=no', 'test11-i36e28hp2...goal=B8...name=Training #2...question=Can B8 be odd?...answer=yes', 'test16-i26e36np3...goal=F3...name=Training #3...question=Can F3 be 3 or 7?...answer=no', ] }, 'training_games1_select_ops_upfront': { 'puzzles': [ 'easy2...goal=E7...name=Training #1...question=Can E7 be 6?...answer=no...select_ops_upfront', ] }, 'training_game2_select_ops_upfront': { 'puzzles': [ 'test11-i36e28hp2...goal=B8...name=Training #2...question=Can B8 be odd?...answer=yes...select_ops_upfront', ] }, 'training_games3_select_ops_upfront': { 'puzzles': [ 'test16-i26e36np3...goal=F3...name=Training #3...question=Can F3 be 3 or 7?...answer=no...select_ops_upfront', ] }, 'training_games1_always_select': { 'puzzles': [ 'easy2...goal=E7...name=Training #1...question=Can E7 be 6?...answer=no', ] }, 'training_game2_always_select': { 'puzzles': [ 'test11-i36e28hp2...goal=B8...name=Training #2...question=Can B8 be odd?...answer=yes', ] }, 'training_games3_always_select': { 'puzzles': [ 'test16-i26e36np3...goal=F3...name=Training #3...question=Can F3 be 3 or 7?...answer=no', ] }, 'weedout_games': { 'puzzles': [ # Requires pointing pairs and inclusion; doesn't require last inclusion after pointing pairs (poss. 1 4 6 7 9) 'test36-i30e33np2hp2yw1...goal=F7...name=WeedOut #1...question=Can F7 be 1, 6, or 7?...answer=yes', 'test36-i30e33np2hp2yw1...goal=F7...name=WeedOut #1...question=Can F7 be 1, 6, or 7?...answer=yes...select_ops_upfront', # Requires 4 calls to inclusion, resolved after 3rd call to inclusion (doesn't require 4th) (poss. 5 7 8 9) 'test4-i28e36...goal=B1...name=WeedOut #2...question=Can B1 be greater than 5?...answer=no', 'test4-i28e36...goal=B1...name=WeedOut #2...question=Can B1 be greater than 5?...answer=no...select_ops_upfront', # Requires just 1 inclusion call to solve 'test22-i33e18nt1xw1...goal=A2...name=WeedOut #3...question=Can A2 be 3?...answer=no', 'test22-i33e18nt1xw1...goal=A2...name=WeedOut #3...question=Can A2 be 3?...answer=no...select_ops_upfront', ] }, 'weedout_games_always_select': { 'puzzles': [ 'test36-i30e33np2hp2yw1...goal=F7...name=WeedOut #1...question=Can F7 be 1, 6, or 7?...answer=yes', 'test4-i28e36...goal=B1...name=WeedOut #2...question=Can B1 be greater than 5?...answer=no', 'test22-i33e18nt1xw1...goal=A2...name=WeedOut #3...question=Can A2 be 3?...answer=no', ] }, 'weedout_games_select_ops_upfront': { 'puzzles': [ 'test36-i30e33np2hp2yw1...goal=F7...name=WeedOut #1...question=Can F7 be 1, 6, or 7?...answer=yes...select_ops_upfront', 'test4-i28e36...goal=B1...name=WeedOut #2...question=Can B1 be greater than 5?...answer=no...select_ops_upfront', 'test22-i33e18nt1xw1...goal=A2...name=WeedOut #3...question=Can A2 be 3?...answer=no...select_ops_upfront', ] }, 'weedout_games1_select_ops_upfront': { 'puzzles': [ 'test36-i30e33np2hp2yw1...goal=F7...name=WeedOut #1...question=Can F7 be 1, 6, or 7?...answer=yes...select_ops_upfront', ] }, 'weedout_games2_select_ops_upfront': { 'puzzles': [ 'test4-i28e36...goal=B1...name=WeedOut #2...question=Can B1 be greater than 5?...answer=no...select_ops_upfront', ] }, 'weedout_games3_select_ops_upfront': { 'puzzles': [ 'test22-i33e18nt1xw1...goal=A2...name=WeedOut #3...question=Can A2 be 3?...answer=no...select_ops_upfront', ] }, 'weedout_games1_always_select': { 'puzzles': [ 'test36-i30e33np2hp2yw1...goal=F7...name=WeedOut #1...question=Can F7 be 1, 6, or 7?...answer=yes', ] }, 'weedout_games2_always_select': { 'puzzles': [ 'test4-i28e36...goal=B1...name=WeedOut #2...question=Can B1 be greater than 5?...answer=no', ] }, 'weedout_games3_always_select': { 'puzzles': [ 'test22-i33e18nt1xw1...goal=A2...name=WeedOut #3...question=Can A2 be 3?...answer=no', ] }, 'logical_operators_mturk_test_suite': { 'puzzles': [ # Goal: something that gets resolved by second-to-last logical operator # Inclusion # Requires 1 call to inclusion; resolved after last (1) inclusion call 'medium1...goal=I3...name=Sudoku Test #01...question=Is I3 prime (2, 3, 5, or 7)?...answer=yes', 'medium1...goal=I3...name=Sudoku Test #01...question=Is I3 prime (2, 3, 5, or 7)?...answer=yes...select_ops_upfront', # Requires 2 calls to inclusion; resolved after 1st call *** training / weed out *** 'naked_single_test...goal=E6...name=Sudoku Test #02...question=Is E6 less than 5?...answer=yes', 'naked_single_test...goal=E6...name=Sudoku Test #02...question=Is E6 less than 5?...answer=yes...select_ops_upfront', # Requires 4 calls to inclusion; resolved by exclusion propagation of 3rd call 'test2-i24e40...goal=B2...name=Sudoku Test #03...question=Is B2 less than 6?...answer=no', 'test2-i24e40...goal=B2...name=Sudoku Test #03...question=Is B2 less than 6?...answer=no...select_ops_upfront', # Requires 4 calls to inclusion; resolved on 3rd inclusion (no exclusion) to be 2 'test3-i29e35...goal=E2...name=Sudoku Test #04...question=Is E2 6?...answer=no', 'test3-i29e35...goal=E2...name=Sudoku Test #04...question=Is E2 6?...answer=no...select_ops_upfront', # Requires 3 calls to inclusion; resolved after 2nd call 'test6-i26e38...goal=C5...name=Sudoku Test #05...question=Is C5 7?...answer=no', 'test6-i26e38...goal=C5...name=Sudoku Test #05...question=Is C5 7?...answer=no...select_ops_upfront', # Process: search for last call to highest-level operator that has at least one non-exclusion operator call after it (if only one call, it can be the last). # Pick most uncertain cell (or a cell if that call doesn't resolve any uncertainty) before the call as the goal. # Determine how uncertainty changes before the next logical operator. # Design a question that is answerable by how the uncertainty changes by the time the next logical operator is called. # Do this experiment with all logical operators, not just the ones chosen for this test. # Pointing Pairs # Requires 1 pointing pairs call and 6 inclusion calls; 1 inclusion call happens after the pointing pairs call but is not required to answer. 'test8-i32e32hp2...goal=H2...name=Sudoku Test #06...question=Is H2 7?...answer=no', 'test8-i32e32hp2...goal=H2...name=Sudoku Test #06...question=Is H2 7?...answer=no...select_ops_upfront', # Requires 2 pointing pairs calls. Question resolved by first, where following inclusion, pointing pairs, inclusion solves the board. 'test9-i29e35hp2...goal=C6...name=Sudoku Test #07...question=Is C6 equal to A2 or A3?...answer=yes', 'test9-i29e35hp2...goal=C6...name=Sudoku Test #07...question=Is C6 equal to A2 or A3?...answer=yes...select_ops_upfront', # Requires 1 pointing pairs, 6 inclusions. Pointing pairs solves the board with exclusion. 'test15-i28e34np3...goal=F9...name=Sudoku Test #08...question=Is F9 odd?...answer=yes', 'test15-i28e34np3...goal=F9...name=Sudoku Test #08...question=Is F9 odd?...answer=yes...select_ops_upfront', # Requires 1 pointing pairs, 6 inclusions. Board requires 2 inclusions afterwards, but question is resolved prior to those. 'test13-i34e30np1...goal=A6...name=Sudoku Test #09...question=Is A6 5?...answer=no', 'test13-i34e30np1...goal=A6...name=Sudoku Test #09...question=Is A6 5?...answer=no...select_ops_upfront', # Requires 2 pointing pairs, 6 inclusions. Question resolved by first pointing pairs. 'hard1...goal=B9...name=Sudoku Test #10...question=Is B9 greater than 3?...answer=yes', 'hard1...goal=B9...name=Sudoku Test #10...question=Is B9 greater than 3?...answer=yes...select_ops_upfront', # Naked Pairs # 1 naked pairs, 2 pointingpairs, 7 inclusion. Solved by exclusion after nakedpairs # C6 1, 2, 6, 9 -> 1, 2 'test7-i26e36hp10...name=Sudoku Test #11...goal=C6...question=Is C6 greater than 5?...answer=no', 'test7-i26e36hp10...name=Sudoku Test #11...goal=C6...question=Is C6 greater than 5?...answer=no...select_ops_upfront', # 1 naked pair, 2 pointing pairs, 2 inclusions. Solved by exclusion after nakedpairs # A6 -> 1, 2 -> 1 # Try operator before naked pairs. Pointing pairs. # Still A6 -> 1, 2, not resolved by nakedpairs. Try to reduce uncertainty otherwise. # B5 1, 2, 7, 8 -> 7, 8 'naked_pair_test_2...goal=B5...name=Sudoku Test #12...question=Is B5 greater than 5?...answer=yes', 'naked_pair_test_2...goal=B5...name=Sudoku Test #12...question=Is B5 greater than 5?...answer=yes...select_ops_upfront', # 1 naked pairs, 2 pointing pairs, 5 inclusions. Requires 1 inclusion to solve after (followed by inclusion, pointingpairs to solve the board). # I5 4, 5, 7 -> 4, 5, 7. Need better option, so look at what's resolved before next inclusion. # A1 1, 5, 6, 7 -> 6, 7 'fiendish4...goal=A1...name=Sudoku Test #13...question=Is A1 greater than 5?...answer=yes', 'fiendish4...goal=A1...name=Sudoku Test #13...question=Is A1 greater than 5?...answer=yes...select_ops_upfront', # 1 nakedpair, 3 pointingpairs, 10 inclusion. 1 inclusion after nakedpair. # F6 2, 3, 4, 5, 7, 9 -> no change after nakedpair, requires an inclusion also to get to -> 2, 3, 4, 7, 9 'test10-i29e35hp7...goal=F6...name=Sudoku Test #14...question=Is F6 5?...answer=no', 'test10-i29e35hp7...goal=F6...name=Sudoku Test #14...question=Is F6 5?...answer=no...select_ops_upfront', # 1 naked pair, 2 pointingpairs, 10 inclusions. Solved by exclusion after nakedpairs. # B2 3, 4, 9 -> 3 'test14-i24e38np3...goal=B2...name=Sudoku Test #15...question=Is B2 a perfect square (1, 4, or 9)?...answer=no', 'test14-i24e38np3...goal=B2...name=Sudoku Test #15...question=Is B2 a perfect square (1, 4, or 9)?...answer=no...select_ops_upfront', # Y Wings # 1 ywings, 1 nakedpairs, 6 inclusion. Solved by exclusion immediately after y-wings # H9 3, 5 -> 3 # 'test29-i27e36yw1...name=Sudoku Test #16...goal=E8...question=Can E9 be a square (1 or 4 or 9)?', 'test29-i27e36yw1...name=Sudoku Test #16...goal=H9...question=Is H9 3?...answer=yes', 'test29-i27e36yw1...name=Sudoku Test #16...goal=H9...question=Is H9 3?...answer=yes...select_ops_upfront', # 1 ywings, 2 pointing pairs, 7 inclusions. solved by exclusion immediately after. # H3 6, 9 -> 9 'test32-i25e38np2hp4yw1...goal=H3...name=Sudoku Test #17...question=Is H3 even?...answer=no', 'test32-i25e38np2hp4yw1...goal=H3...name=Sudoku Test #17...question=Is H3 even?...answer=no...select_ops_upfront', # 1 ywings, 2 pointing pairs, 9 inclusions. Solved by exclusion after ywing # I2 5, 7 -> 5 # 'test27-i32e31yw3...goal=%%...name=Sudoku Test #20...question=%%?...answer=%%', # 1 ywing, 9 inclusion. solved by exclusion immediately after. # B8 4, 8 -> 4 # Solve prior to ywing insted. # B9 8, 9 -> No change prior to ywing. Try reducing uncertainty instead. # G9 2, 6, 7 -> 7 'test30-i29e34yw1...goal=G9...name=Sudoku Test #18...question=Is G9 odd?...answer=yes', 'test30-i29e34yw1...goal=G9...name=Sudoku Test #18...question=Is G9 odd?...answer=yes...select_ops_upfront', # 1 ywing, 2 pointing pairs, 2 inclusion. solved by exclusion immediately after # F3 1, 3, 4, 5, 6, 8 -> 1, 3, 4, 5, 6 # 'ywing_test...goal=%%...name=Sudoku Test #18...question=%%?...answer=%%', # 1 Ywing, 6 inclusion. Solved immediately after ywing by exclusion. # E8 4, 6, 9 -> 4, 9 'test28-i27e36yw1...goal=E8...name=Sudoku Test #19...question=Is E8 a perfect square (1, 4, or 9)?...answer=yes', 'test28-i27e36yw1...goal=E8...name=Sudoku Test #19...question=Is E8 a perfect square (1, 4, or 9)?...answer=yes...select_ops_upfront', # 1 ywings, 9 inclusion. Solved after ywing by exclusion. # B8 3, 8 -> 3 # 'test31-i36e27yw1...goal=%%...name=Sudoku Test #20...question=%%?...answer=%%', # 1 ywings, 2 pointing pairs, 7 inclusion. Solved immediately after ywings by exclusion # H3 6, 9 -> 6 # 'test32-i25e38np2hp4yw1...goal=%%...name=Sudoku Test #20...question=%%?...answer=%%', # 1 ywings, 2 pointing pairs, 5 inclusion. ywings followed by inclusion. # D5 1, 2, 5, 6 -> no change. Need a different question prior to inclusion. # C3 3, 5 -> 3 'box_line_reduction...goal=C3...name=Sudoku Test #20...question=Is C3 greater than 4?...answer=no', 'box_line_reduction...goal=C3...name=Sudoku Test #20...question=Is C3 greater than 4?...answer=no...select_ops_upfront', ] }, 'logical_operators_mturk_option1_select_upfront': { 'puzzles': [ # Inclusion 1 'medium1...goal=I3...name=Sudoku Test #01...question=Is I3 prime (2, 3, 5, or 7)?...answer=yes...select_ops_upfront', 'naked_single_test...goal=E6...name=Sudoku Test #02...question=Is E6 less than 5?...answer=yes...select_ops_upfront', 'test2-i24e40...goal=B2...name=Sudoku Test #03...question=Is B2 less than 6?...answer=no...select_ops_upfront', # Pointing Pairs 1 'test15-i28e34np3...goal=F9...name=Sudoku Test #08...question=Is F9 odd?...answer=yes...select_ops_upfront', 'test13-i34e30np1...goal=A6...name=Sudoku Test #09...question=Is A6 5?...answer=no...select_ops_upfront', # Naked Pairs 1 'naked_pair_test_2...goal=B5...name=Sudoku Test #12...question=Is B5 greater than 5?...answer=yes...select_ops_upfront', 'fiendish4...goal=A1...name=Sudoku Test #13...question=Is A1 greater than 5?...answer=yes...select_ops_upfront', # Y Wings 1 'test32-i25e38np2hp4yw1...goal=H3...name=Sudoku Test #17...question=Is H3 even?...answer=no...select_ops_upfront', 'test28-i27e36yw1...goal=E8...name=Sudoku Test #19...question=Is E8 a perfect square (1, 4, or 9)?...answer=yes...select_ops_upfront', 'test30-i29e34yw1...goal=G9...name=Sudoku Test #18...question=Is G9 odd?...answer=yes...select_ops_upfront', ] }, 'logical_operators_mturk_option2_select_upfront': { 'puzzles': [ # Inclusion 2 'test3-i29e35...goal=E2...name=Sudoku Test #04...question=Is E2 6?...answer=no...select_ops_upfront', 'test6-i26e38...goal=C5...name=Sudoku Test #05...question=Is C5 7?...answer=no...select_ops_upfront', # Pointing Pairs 2 'hard1...goal=B9...name=Sudoku Test #10...question=Is B9 greater than 3?...answer=yes...select_ops_upfront', 'test8-i32e32hp2...goal=H2...name=Sudoku Test #06...question=Is H2 7?...answer=no...select_ops_upfront', 'test9-i29e35hp2...goal=C6...name=Sudoku Test #07...question=Is C6 equal to A2 or A3?...answer=yes...select_ops_upfront', # Naked Pairs 2 'test7-i26e36hp10...name=Sudoku Test #11...goal=C6...question=Is C6 greater than 5?...answer=no...select_ops_upfront', 'test10-i29e35hp7...goal=F6...name=Sudoku Test #14...question=Is F6 5?...answer=no...select_ops_upfront', 'test14-i24e38np3...goal=B2...name=Sudoku Test #15...question=Is B2 a perfect square (1, 4, or 9)?...answer=no...select_ops_upfront', # Y Wings 2 'test29-i27e36yw1...name=Sudoku Test #16...goal=H9...question=Is H9 3?...answer=yes...select_ops_upfront', 'box_line_reduction...goal=C3...name=Sudoku Test #20...question=Is C3 greater than 4?...answer=no...select_ops_upfront', ] }, 'logical_operators_mturk_option1_always_select': { 'puzzles': [ # Inclusion 1 'medium1...goal=I3...name=Sudoku Test #01...question=Is I3 prime (2, 3, 5, or 7)?...answer=yes', 'naked_single_test...goal=E6...name=Sudoku Test #02...question=Is E6 less than 5?...answer=yes', 'test2-i24e40...goal=B2...name=Sudoku Test #03...question=Is B2 less than 6?...answer=no', # Pointing Pairs 1 'test15-i28e34np3...goal=F9...name=Sudoku Test #08...question=Is F9 odd?...answer=yes', 'test13-i34e30np1...goal=A6...name=Sudoku Test #09...question=Is A6 5?...answer=no', # Naked Pairs 1 'naked_pair_test_2...goal=B5...name=Sudoku Test #12...question=Is B5 greater than 5?...answer=yes', 'fiendish4...goal=A1...name=Sudoku Test #13...question=Is A1 greater than 5?...answer=yes', # Y Wings 1 'test32-i25e38np2hp4yw1...goal=H3...name=Sudoku Test #17...question=Is H3 even?...answer=no', 'test28-i27e36yw1...goal=E8...name=Sudoku Test #19...question=Is E8 a perfect square (1, 4, or 9)?...answer=yes', 'test30-i29e34yw1...goal=G9...name=Sudoku Test #18...question=Is G9 odd?...answer=yes', ] }, 'logical_operators_mturk_option2_always_select': { 'puzzles': [ # Inclusion 2 'test3-i29e35...goal=E2...name=Sudoku Test #04...question=Is E2 6?...answer=no', 'test6-i26e38...goal=C5...name=Sudoku Test #05...question=Is C5 7?...answer=no', # Pointing Pairs 2 'hard1...goal=B9...name=Sudoku Test #10...question=Is B9 greater than 3?...answer=yes', 'test8-i32e32hp2...goal=H2...name=Sudoku Test #06...question=Is H2 7?...answer=no', 'test9-i29e35hp2...goal=C6...name=Sudoku Test #07...question=Is C6 equal to A2 or A3?...answer=yes', # Naked Pairs 2 'test7-i26e36hp10...name=Sudoku Test #11...goal=C6...question=Is C6 greater than 5?...answer=no', 'test10-i29e35hp7...goal=F6...name=Sudoku Test #14...question=Is F6 5?...answer=no', 'test14-i24e38np3...goal=B2...name=Sudoku Test #15...question=Is B2 a perfect square (1, 4, or 9)?...answer=no', # Y Wings 2 'test29-i27e36yw1...name=Sudoku Test #16...goal=H9...question=Is H9 3?...answer=yes', 'box_line_reduction...goal=C3...name=Sudoku Test #20...question=Is C3 greater than 4?...answer=no', ] }, 'logical_operators_mturk_optionA_select_upfront': { 'puzzles': [ # Inclusion A 'medium1...goal=I3...name=Sudoku Test #01...question=Is I3 prime (2, 3, 5, or 7)?...answer=yes...select_ops_upfront', # Pointing Pairs A 'test13-i34e30np1...goal=A6...name=Sudoku Test #09...question=Is A6 5?...answer=no...select_ops_upfront', # Naked Pairs A 'fiendish4...goal=A1...name=Sudoku Test #13...question=Is A1 greater than 5?...answer=yes...select_ops_upfront', # Y Wings A 'test28-i27e36yw1...goal=E8...name=Sudoku Test #19...question=Is E8 a perfect square (1, 4, or 9)?...answer=yes...select_ops_upfront', 'test30-i29e34yw1...goal=G9...name=Sudoku Test #18...question=Is G9 odd?...answer=yes...select_ops_upfront', ] }, 'logical_operators_mturk_optionB_select_upfront': { 'puzzles': [ # Inclusion B 'naked_single_test...goal=E6...name=Sudoku Test #02...question=Is E6 less than 5?...answer=yes...select_ops_upfront', 'test2-i24e40...goal=B2...name=Sudoku Test #03...question=Is B2 less than 6?...answer=no...select_ops_upfront', # Pointing Pairs B 'test15-i28e34np3...goal=F9...name=Sudoku Test #08...question=Is F9 odd?...answer=yes...select_ops_upfront', # Naked Pairs B 'naked_pair_test_2...goal=B5...name=Sudoku Test #12...question=Is B5 greater than 5?...answer=yes...select_ops_upfront', # Y Wings B 'test32-i25e38np2hp4yw1...goal=H3...name=Sudoku Test #17...question=Is H3 even?...answer=no...select_ops_upfront', ] }, 'logical_operators_mturk_optionC_select_upfront': { 'puzzles': [ # Inclusion C 'test3-i29e35...goal=E2...name=Sudoku Test #04...question=Is E2 6?...answer=no...select_ops_upfront', # Pointing Pairs C 'hard1...goal=B9...name=Sudoku Test #10...question=Is B9 greater than 3?...answer=yes...select_ops_upfront', # Naked Pairs C 'test7-i26e36hp10...name=Sudoku Test #11...goal=C6...question=Is C6 greater than 5?...answer=no...select_ops_upfront', 'test14-i24e38np3...goal=B2...name=Sudoku Test #14...question=Is B2 a perfect square (1, 4, or 9)?...answer=no...select_ops_upfront', # Y Wings C 'box_line_reduction...goal=C3...name=Sudoku Test #20...question=Is C3 greater than 4?...answer=no...select_ops_upfront', ] }, 'logical_operators_mturk_optionD_select_upfront': { 'puzzles': [ # Inclusion D 'test6-i26e38...goal=C5...name=Sudoku Test #05...question=Is C5 7?...answer=no...select_ops_upfront', # Pointing Pairs D 'test8-i32e32hp2...goal=H2...name=Sudoku Test #06...question=Is H2 7?...answer=no...select_ops_upfront', 'test9-i29e35hp2...goal=C6...name=Sudoku Test #07...question=Is C6 equal to A2 or A3?...answer=yes...select_ops_upfront', # Naked Pairs D 'test10-i29e35hp7...goal=F6...name=Sudoku Test #14...question=Is F6 5?...answer=no...select_ops_upfront', # Y Wings D 'test29-i27e36yw1...name=Sudoku Test #16...goal=H9...question=Is H9 3?...answer=yes...select_ops_upfront', ] }, 'logical_operators_mturk_optionA_always_select': { 'puzzles': [ # Inclusion A 'medium1...goal=I3...name=Sudoku Test #01...question=Is I3 prime (2, 3, 5, or 7)?...answer=yes', # Pointing Pairs A 'test13-i34e30np1...goal=A6...name=Sudoku Test #09...question=Is A6 5?...answer=no', # Naked Pairs A 'fiendish4...goal=A1...name=Sudoku Test #13...question=Is A1 greater than 5?...answer=yes', # Y Wings A 'test28-i27e36yw1...goal=E8...name=Sudoku Test #19...question=Is E8 a perfect square (1, 4, or 9)?...answer=yes', 'test30-i29e34yw1...goal=G9...name=Sudoku Test #18...question=Is G9 odd?...answer=yes', ] }, 'logical_operators_mturk_optionB_always_select': { 'puzzles': [ # Inclusion B 'naked_single_test...goal=E6...name=Sudoku Test #02...question=Is E6 less than 5?...answer=yes', 'test2-i24e40...goal=B2...name=Sudoku Test #03...question=Is B2 less than 6?...answer=no', # Pointing Pairs B 'test15-i28e34np3...goal=F9...name=Sudoku Test #08...question=Is F9 odd?...answer=yes', # Naked Pairs B 'naked_pair_test_2...goal=B5...name=Sudoku Test #12...question=Is B5 greater than 5?...answer=yes', # Y Wings B 'test32-i25e38np2hp4yw1...goal=H3...name=Sudoku Test #17...question=Is H3 even?...answer=no', ] }, 'logical_operators_mturk_optionC_always_select': { 'puzzles': [ # Inclusion C 'test3-i29e35...goal=E2...name=Sudoku Test #04...question=Is E2 6?...answer=no', # Pointing Pairs C 'hard1...goal=B9...name=Sudoku Test #10...question=Is B9 greater than 3?...answer=yes', # Naked Pairs C 'test7-i26e36hp10...name=Sudoku Test #11...goal=C6...question=Is C6 greater than 5?...answer=no', 'test14-i24e38np3...goal=B2...name=Sudoku Test #14...question=Is B2 a perfect square (1, 4, or 9)?...answer=no', # Y Wings C 'box_line_reduction...goal=C3...name=Sudoku Test #20...question=Is C3 greater than 4?...answer=no', ] }, 'logical_operators_mturk_optionD_always_select': { 'puzzles': [ # Inclusion D 'test6-i26e38...goal=C5...name=Sudoku Test #05...question=Is C5 7?...answer=no', # Pointing Pairs D 'test8-i32e32hp2...goal=H2...name=Sudoku Test #06...question=Is H2 7?...answer=no', 'test9-i29e35hp2...goal=C6...name=Sudoku Test #07...question=Is C6 equal to A2 or A3?...answer=yes', # Naked Pairs D 'test10-i29e35hp7...goal=F6...name=Sudoku Test #14...question=Is F6 5?...answer=no', # Y Wings D 'test29-i27e36yw1...name=Sudoku Test #16...goal=H9...question=Is H9 3?...answer=yes', ] }, 'extra_games': { 'puzzles': [ # Exclusion only; resolved with anything # These are un-checked by Shelley other than to confirm that they don't need any operators. 'easy1...goal=D2...name=No Logical Ops Required #1...question=Is D2 greater than 4?...answer=no', 'easy1...goal=D2...name=No Logical Ops Required #1...question=Is D2 greater than 4?...answer=no...select_ops_upfront', 'easy4...goal=A2...name=No Logical Ops Required #2...question=Is A2 odd?...answer=yes', 'easy4...goal=A2...name=No Logical Ops Required #2...question=Is A2 odd?...answer=yes...select_ops_upfront', # May require intermediate operators. 'box_line_reduction_2...name=Extra Manipulations Required Beyond Logical Ops #1...goal=C5...question=Is C5 less than 5?...answer=yes', 'box_line_reduction_2...name=Extra Manipulations Required Beyond Logical Ops #1...goal=C5...question=Is C5 less than 5?...answer=yes...select_ops_upfront', 'hidden_pair_test_2...goal=F7...name=Extra Manipulations Required Beyond Logical Ops #2...question=Is F7 odd?...answer=yes', 'hidden_pair_test_2...goal=F7...name=Extra Manipulations Required Beyond Logical Ops #2...question=Is F7 odd?...answer=yes...select_ops_upfront', 'pointing_pair_test_2...goal=E7...name=Extra Manipulations Required Beyond Logical Ops #3...question=Is E7 8?...answer=no', 'pointing_pair_test_2...goal=E7...name=Extra Manipulations Required Beyond Logical Ops #3...question=Is E7 8?...answer=no...select_ops_upfront', 'pointing_pair_test...goal=H4...name=Extra Manipulations Required Beyond Logical Ops #4...question=Is H4 even?...answer=no', 'pointing_pair_test...goal=H4...name=Extra Manipulations Required Beyond Logical Ops #4...question=Is H4 even?...answer=no...select_ops_upfront', 'xwing_test...goal=E8...name=Extra Manipulations Required Beyond Logical Ops #5...question=Is E8 more than 5?...answer=no', 'xwing_test...goal=E8...name=Extra Manipulations Required Beyond Logical Ops #5...question=Is E8 more than 5?...answer=no...select_ops_upfront', 'hidden_triple_test...name=Extra Manipulations Required Beyond Logical Ops #6...goal=A9...question=Is A9 greater than 5?...answer=no', 'hidden_triple_test...name=Extra Manipulations Required Beyond Logical Ops #6...goal=A9...question=Is A9 greater than 5?...answer=no...select_ops_upfront', 'xwing_test...name=Extra Manipulations Required Beyond Logical Ops #7...goal=G6...question=Is G6 equal to A7 or A8 or A9?...answer=no', 'xwing_test...name=Extra Manipulations Required Beyond Logical Ops #7...goal=G6...question=Is G6 equal to A7 or A8 or A9?...answer=no...select_ops_upfront', 'naked_quad_test...goal=B2...name=Extra Manipulations Required Beyond Logical Ops #8...question=Is B2 a multiple of 3 (3 or 6 or 9)?...answer=yes', 'naked_quad_test...goal=B2...name=Extra Manipulations Required Beyond Logical Ops #8...question=Is B2 a multiple of 3 (3 or 6 or 9)?...answer=yes...select_ops_upfront', # ...select_ops_upfront # ...costly_ops': ['inclusion', 'pointingpairs', 'naked pairs', 'ywings'] ] } }
# Part 2 on day 2 on advent of code # # Tyler Stuessi def get_bathroom_code(): # get input code = "" keypaths = [] try: while True: raw = input() keypaths.append(raw) except EOFError: pass # hard code the grid grid = [["0", "0", "1", "0", "0"], ["0", "2", "3", "4", "0"], ["5", "6", "7", "8", "9"], ["0", "A", "B", "C", "0"], ["0", "0", "D", "0", "0"]] row = 2 col = 2 for path in keypaths: for c in path: if c == "L" and col != 0 and grid[row][col-1] != "0": col -= 1 elif c == "U" and row != 0 and grid[row-1][col] != "0": row -= 1 elif c == "D" and row != len(grid)-1 and grid[row+1][col] != "0": row += 1 elif c == "R" and col != len(grid[row])-1 and grid[row][col+1] != "0": col += 1 code += grid[row][col] return code if __name__ == "__main__": print(get_bathroom_code())
def fizz_buzz(input): result = [] for x in range(1, input + 1): value = '' if x % 3 == 0: value += 'Fizz' if x % 5 == 0: value += 'Buzz' value = value or x result.append(value) return result
# This sample tests annotated types on global variables. # This should generate an error because the declared # type below does not match the assigned type. glob_var1 = 4 # This should generate an error because the declared # type doesn't match the later declared type. glob_var1 = Exception() # type: str glob_var1 = Exception() # type: Exception # This should generate an error because the assigned # type doesn't match the declared type. glob_var1 = "hello" # type: Exception # This should generate an error. glob_var2 = 5 def func1(): global glob_var1 global glob_var2 # This should generate an error. glob_var1 = 3 glob_var2 = "hello" # type: str
""" Mock for the figures.permissions model. """ def is_active_staff_or_superuser(request): """ Exact copy of Figures=0.4.x `figures.permissions.is_active_staff_or_superuser` helper. """ return request.user and request.user.is_active and ( request.user.is_staff or request.user.is_superuser)
"""ssd_classes.py This file was modified from: http://github.com/AastaNV/TRT_object_detection/blob/master/coco.py """ COCO_CLASSES_LIST = [ 'background', # was 'unlabeled' 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'street sign', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'hat', 'backpack', 'umbrella', 'shoe', 'eye glasses', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket', 'bottle', 'plate', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'mirror', 'dining table', 'window', 'desk', 'toilet', 'door', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'blender', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush', ] EGOHANDS_CLASSES_LIST = [ 'background', 'hand', ] def get_cls_dict(model): """Get the class ID to name translation dictionary.""" if model == 'coco': cls_list = COCO_CLASSES_LIST elif model == 'egohands': cls_list = EGOHANDS_CLASSES_LIST else: raise ValueError('Bad model name') return dict(enumerate(cls_list))
"""Write a HashTable class that stores strings in a hash table, where keys are calculated using the first two letters of the string.""" class HashTable(object): def __init__(self): self.table = [None] * 10000 def store(self, string): """Input a string that's stored in the table.""" hash_value = self.calculate_hash_value(string) if self.table[hash_value] is None: self.table[hash_value] = [string] else: self.table[hash_value].append(string) def lookup(self, string): """Return the hash value if the string is already in the table. Return -1 otherwise.""" hash_value = self.calculate_hash_value(string) if self.table[hash_value] is not None: if string in self.table[hash_value]: return hash_value return -1 @staticmethod def calculate_hash_value(string): """Helper function to calulate a hash value from a string.""" return (ord(string[0]) * 100) + ord(string[1]) # Setup hash_table = HashTable() # Test calculate_hash_value # Should be 8568 print(hash_table.calculate_hash_value('UDACITY')) # Test lookup edge case # Should be -1 print(hash_table.lookup('UDACITY')) # Test store hash_table.store('UDACITY') # Should be 8568 print(hash_table.lookup('UDACITY')) # Test store edge case hash_table.store('UDACIOUS') # Should be 8568 print(hash_table.lookup('UDACIOUS'))
N = int(input()) for i in range(1, N): print(' ' * (N - i) + '*' * ((i * 2) - 1)) for i in range(N, 0, -1): print(' ' * (N - i) + '*' * ((i * 2) - 1))
#!/usr/bin/env python __all__ = [ "test_misc", "test_dictarray", "test_table", "test_transform", "test_recode_alignment", "test_union_dict", ] __author__ = "" __copyright__ = "Copyright 2007-2022, The Cogent Project" __credits__ = [ "Jeremy Widmann", "Sandra Smit", "Gavin Huttley", "Rob Knight", "Zongzhi Liu", "Amanda Birmingham", "Greg Caporaso", ] __license__ = "BSD-3" __version__ = "2022.4.20a1" __maintainer__ = "Gavin Huttley" __email__ = "Gavin.Huttley@anu.edu.au" __status__ = "Production"
class Config(object): DEBUG = False TESTING = False SECRET_KEY = "B\xb2?.\xdf\x9f\xa7m\xf8\x8a%,\xf7\xc4\xfa\x91" MONGO_URI="mongodb://localhost:27017/test" IMAGE_UPLOADS = "/home/username/projects/my_app/app/static/images/uploads" SESSION_COOKIE_SECURE = False class ProductionConfig(Config): DEBUG = False MONGO_URI="mongodb://localhost:27017/" DB_NAME="test" IMAGE_UPLOADS = "/home/username/projects/my_app/app/static/images/uploads" SESSION_COOKIE_SECURE = True class DevelopmentConfig(Config): DEBUG = True MONGO_URI="mongodb://localhost:27017/" DB_NAME="test" IMAGE_UPLOADS = "/home/username/projects/my_app/app/static/images/uploads" SESSION_COOKIE_SECURE = False class TestingConfig(Config): TESTING = True MONGO_URI="mongodb://localhost:27017/test" IMAGE_UPLOADS = "/home/username/projects/my_app/app/static/images/uploads" SESSION_COOKIE_SECURE = False
# Real part of spherical harmonic Y_(4,2)(theta,phi) def Y(l,m): def g(theta,phi): R = abs(fp.re(fp.spherharm(l,m,theta,phi))) x = R*fp.cos(phi)*fp.sin(theta) y = R*fp.sin(phi)*fp.sin(theta) z = R*fp.cos(theta) return [x,y,z] return g fp.splot(Y(4,2), [0,fp.pi], [0,2*fp.pi], points=300)
number = int(input()) if number % 2 == 1 or 6 <= number <= 20: print('Weird') elif 2 <= number <= 5 or number > 20: print('Not Weird')
''' Exercise 5: Take the following Python code that stores a string: str = 'X-DSPAM-Confidence:0.8475' Use find and string slicing to extract the portion of the string\ after the colon character and then use the float function to convert the extracted string into a floating point number. ''' string = 'X-DSPAM-Confidence:0.8475' num_index = string.find(':') num_float = float(string[num_index+1:]) print(num_float, type(num_float))
#$Id$ class Category: """This class is used to create object for category.""" def __init__(self): """Initialize parameters for Category.""" self.id = "" self.name = "" def set_id(self, id): """Set id. Args: id(str): Id. """ self.id = id def get_id(self): """Get id. Returns: str: Id. """ return self.id def set_name(self, name): """Set name. Args: name(str): name. """ self.name = name def get_name(self): """Get name. Returns: str: name. """ return self.name
class Song: def __init__(self, name, length, single): self.name = name self.length = length self.single = single def get_info(self): return f"{self.name} - {self.length}" #Test code # song = Song("Running in the 90s", 3.45, False) # print(song.get_info())
class MyCircularQueue: def __init__(self, k: int): self.q = [None] * k self.maxlen = k self.front = 0 self.rear = 0 def enQueue(self, value: int) -> bool: if self.q[self.rear] is None: self.q[self.rear] = value self.rear = (self.rear + 1 ) % self.maxlen return True return False def deQueue(self) -> bool: if self.front == self.rear and self.q[self.front] is None: return False self.q[self.front] = None self.front = (self.front +1) % self.maxlen return True def Front(self) -> int: if self.q[self.front] is None: return -1 return self.q[self.front] def Rear(self) -> int: if self.q[self.rear -1] is None: return -1 return self.q[self.rear-1] def isEmpty(self) -> bool: if self.front == self.rear and self.q[self.rear] is None: return True return False def isFull(self) -> bool: if self.front == self.rear and self.q[self.rear] is not None: return True return False # Your MyCircularQueue object will be instantiated and called as such: # obj = MyCircularQueue(k) # param_1 = obj.enQueue(value) # param_2 = obj.deQueue() # param_3 = obj.Front() # param_4 = obj.Rear() # param_5 = obj.isEmpty() # param_6 = obj.isFull()
load("//tools:defaults.bzl", "protractor_web_test_suite") """ Macro that can be used to define a e2e test in `modules/benchmarks`. Targets created through this macro differentiate from a "benchmark_test" as they will run on CI and do not run with `@angular/benchpress`. """ def e2e_test(name, server, **kwargs): protractor_web_test_suite( name = name, on_prepare = "@npm//@angular/dev-infra-private/bazel/benchmark/component_benchmark:start-server.js", server = server, **kwargs )
_base_ = [ '../_base_/models/lxmert/lxmert_pretrain_config.py', '../_base_/datasets/lxmert/lxmert_pretrain.py', '../_base_/default_runtime.py', ]
def print_all_binary_strings(n): helper(n, "") print("-------------------") def helper(n, s, lvl = 0): space = (" " * lvl) + s print(space) if(len(s) == n): print(s) else: helper(n, s + "0", lvl + 1) helper(n, s + "1", lvl + 1) print_all_binary_strings(1) print_all_binary_strings(2) print_all_binary_strings(3) print_all_binary_strings(4)
# DEBUG FLAGS TRAIN_JUST_ONE_BATCH = False TRAIN_JUST_ONE_ROUND = False PROFILE = False CHECK_GRADS = False # Basic LEARNING_RATE_DEFAULT = 1e-2 # 0.01 MAX_EPOCHS_DEFAULT = 100 EVAL_FREQ_DEFAULT = 5 BATCH_SIZE_DEFAULT = 5 WORKERS_DEFAULT = 4 OPTIMIZER_DEFAULT = 'ADAM' WEIGHT_DECAY_DEFAULT = 0.01 DATA_DIR_DEFAULT = 'data/EEG_age_data/' LOG_DIR_DEFAULT = 'log/' USE_GPU_DEFAULT = 1 GPU_ID_DEFAULT = 0 NETWORK_DEFAULT = 'BAPM' NETWORKS = ['FeedForward', 'GRUNet', 'BAPM', 'BAPM1', 'BAPM2'] MODE_DEFAULT = 'train' EVAL_DEFAULT = 'model_save/eval.pt' # should be a model file name MODEL_SAVE_DIR_DEFAULT = 'model_save/' MAX_NORM_DEFAULT = 10.0 NUM_HEADS_DEFAULT = 3 FEAT_DIM_DEFAULT = 1 HIDDEN_DIM_DEFAULT = 5 LOSS_FUNC_DEFAULT = 'SmoothL1Loss' SMOOTH_L1_LOSS_BETA_DEFAULT = 1 FOLDS_DEFAULT = 5 VALID_K_DEFAULT = -1 # DIY TOTAL_TIMESTAMPS = 245760 EEG_FREQUENCY = 1024 NUM_NODES = 63 NUM_SUBJECTS = 111 BAD_SUBJECT_IDS = [2, 14, 17, 18, 19, 20, 26, 35, 41, 64, 72] # Delete bad samples SAMPLE_SPLIT_DEFAULT = 16 NUM_SAMPLES_DEFAULT = -1 STCNN_STRIDE_FACTOR_DEFAULT = 4 SHUFFLE_RANDOM_SEED = 666 CUSTOMIZE_GRAPH_DEFAULT = 0
# The contents of this file has been derived code from the Twisted project # (http://twistedmatrix.com/). The original author is Jp Calderone. # Twisted project license follows: # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. class FolderNameError(ValueError): pass def encode(s): if isinstance(s, str) and sum(n for n in (ord(c) for c in s) if n > 127): raise FolderNameError("%r contains characters not valid in a str folder name. " "Convert to unicode first?" % s) r = [] _in = [] for c in s: if ord(c) in (range(0x20, 0x26) + range(0x27, 0x7f)): if _in: r.extend(['&', modified_base64(''.join(_in)), '-']) del _in[:] r.append(str(c)) elif c == '&': if _in: r.extend(['&', modified_base64(''.join(_in)), '-']) del _in[:] r.append('&-') else: _in.append(c) if _in: r.extend(['&', modified_base64(''.join(_in)), '-']) return ''.join(r) def decode(s): r = [] decode = [] for c in s: if c == '&' and not decode: decode.append('&') elif c == '-' and decode: if len(decode) == 1: r.append('&') else: r.append(modified_unbase64(''.join(decode[1:]))) decode = [] elif decode: decode.append(c) else: r.append(c) if decode: r.append(modified_unbase64(''.join(decode[1:]))) out = ''.join(r) if not isinstance(out, unicode): out = unicode(out, 'latin-1') return out def modified_base64(s): s_utf7 = s.encode('utf-7') return s_utf7[1:-1].replace('/', ',') def modified_unbase64(s): s_utf7 = '+' + s.replace(',', '/') + '-' return s_utf7.decode('utf-7')
# debug DEBUG = False
'''1. Write a Python function that takes a sequence of numbers and determines whether all the numbers are different from each other.''' def unique(string): if len(string) == len(set(string)): ans = 'True' else: ans = 'False' return ans print(unique((1, 2, 3, 4))) print(unique((1, 3, 3, 4)))
# -*- coding: utf-8 -*- { '!langcode!': 'nl', '!langname!': 'Nederlands', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN', '%(nrows)s records found': '%(nrows)s records gevonden', '%d days ago': '%d dagen geleden', '%d weeks ago': '%d weken gelden', '%s %%{row} deleted': '%s rijen verwijderd', '%s %%{row} updated': '%s rijen geupdate', '%s selected': '%s geselecteerd', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '(something like "it-it")': '(zoiets als "nl-nl")', '1 day ago': '1 dag geleden', '1 week ago': '1 week gelden', '<': '<', '<=': '<=', '=': '=', '>': '>', '>=': '>=', 'A new version of web2py is available': 'Een nieuwe versie van web2py is beschikbaar', 'A new version of web2py is available: %s': 'Een nieuwe versie van web2py is beschikbaar: %s', 'About': 'Over', 'about': 'over', 'About application': 'Over applicatie', 'Access Control': 'Toegangscontrole', 'Add': 'Toevoegen', 'additional code for your application': 'additionele code voor je applicatie', 'admin disabled because no admin password': 'admin is uitgezet omdat er geen admin wachtwoord is', 'admin disabled because not supported on google app engine': 'admin is uitgezet omdat dit niet ondersteund wordt op google app engine', 'admin disabled because unable to access password file': 'admin is uitgezet omdat het wachtwoordbestand niet geopend kan worden', 'Admin is disabled because insecure channel': 'Admin is uitgezet om het kanaal onveilig is', 'Admin is disabled because unsecure channel': 'Admin is uitgezet om het kanaal onveilig is', 'Administration': 'Administratie', 'Administrative Interface': 'Administratieve Interface', 'Administrator Password:': 'Administrator Wachtwoord', 'Ajax Recipes': 'Ajax Recepten', 'And': 'En', 'and rename it (required):': 'en hernoem deze (vereist)', 'and rename it:': 'en hernoem:', 'appadmin': 'appadmin', 'appadmin is disabled because insecure channel': 'appadmin is uitgezet vanwege een onveilig kanaal', 'application "%s" uninstalled': 'applicatie "%s" gedeïnstalleerd', 'application compiled': 'applicatie gecompileerd', 'application is compiled and cannot be designed': 'applicatie is gecompileerd en kan niet worden ontworpen', 'Are you sure you want to delete file "%s"?': 'Weet je zeker dat je bestand "%s" wilt verwijderen?', 'Are you sure you want to delete this object?': 'Weet je zeker dat je dit object wilt verwijderen?', 'Are you sure you want to uninstall application "%s"?': 'Weet je zeker dat je applicatie "%s" wilt deïnstalleren?', 'ATTENTION: Login requires a secure (HTTPS) connection or running on localhost.': 'LET OP: Login vereist een beveiligde (HTTPS) connectie of moet draaien op localhost.', 'ATTENTION: TESTING IS NOT THREAD SAFE SO DO NOT PERFORM MULTIPLE TESTS CONCURRENTLY.': 'LET OP: TESTEN IS NIET THREAD SAFE, PROBEER NIET GELIJKTIJDIG MEERDERE TESTS TE DOEN.', 'ATTENTION: you cannot edit the running application!': 'LET OP: je kan de applicatie die nu draait niet editen!', 'Authentication': 'Authenticatie', 'Available Databases and Tables': 'Beschikbare databases en tabellen', 'Back': 'Terug', 'Buy this book': 'Koop dit boek', 'Cache': 'Cache', 'cache': 'cache', 'Cache Keys': 'Cache Keys', 'cache, errors and sessions cleaned': 'cache, errors en sessies geleegd', 'Cannot be empty': 'Mag niet leeg zijn', 'Cannot compile: there are errors in your app. Debug it, correct errors and try again.': 'Kan niet compileren: er bevinden zich fouten in je app. Debug, corrigeer de fouten en probeer opnieuw.', 'cannot create file': 'kan bestand niet maken', 'cannot upload file "%(filename)s"': 'kan bestand "%(filename)s" niet uploaden', 'Change Password': 'Wijzig wachtwoord', 'Change password': 'Wijzig Wachtwoord', 'change password': 'wijzig wachtwoord', 'check all': 'vink alles aan', 'Check to delete': 'Vink aan om te verwijderen', 'clean': 'leeg', 'Clear': 'Leeg', 'Clear CACHE?': 'Leeg CACHE?', 'Clear DISK': 'Leeg DISK', 'Clear RAM': 'Clear RAM', 'click to check for upgrades': 'Klik om voor upgrades te controleren', 'Client IP': 'Client IP', 'Community': 'Community', 'compile': 'compileren', 'compiled application removed': 'gecompileerde applicatie verwijderd', 'Components and Plugins': 'Components en Plugins', 'contains': 'bevat', 'Controller': 'Controller', 'Controllers': 'Controllers', 'controllers': 'controllers', 'Copyright': 'Copyright', 'create file with filename:': 'maak bestand met de naam:', 'Create new application': 'Maak nieuwe applicatie:', 'create new application:': 'maak nieuwe applicatie', 'Created By': 'Gemaakt Door', 'Created On': 'Gemaakt Op', 'crontab': 'crontab', 'Current request': 'Huidige request', 'Current response': 'Huidige response', 'Current session': 'Huidige sessie', 'currently saved or': 'op het moment opgeslagen of', 'customize me!': 'pas me aan!', 'data uploaded': 'data geupload', 'Database': 'Database', 'Database %s select': 'Database %s select', 'database administration': 'database administratie', 'Date and Time': 'Datum en Tijd', 'db': 'db', 'DB Model': 'DB Model', 'defines tables': 'definieer tabellen', 'Delete': 'Verwijder', 'delete': 'verwijder', 'delete all checked': 'verwijder alle aangevinkten', 'Delete:': 'Verwijder:', 'Demo': 'Demo', 'Deploy on Google App Engine': 'Deploy op Google App Engine', 'Deployment Recipes': 'Deployment Recepten', 'Description': 'Beschrijving', 'design': 'design', 'DESIGN': 'DESIGN', 'Design for': 'Design voor', 'DISK': 'DISK', 'Disk Cache Keys': 'Disk Cache Keys', 'Disk Cleared': 'Disk Geleegd', 'Documentation': 'Documentatie', "Don't know what to do?": 'Weet je niet wat je moet doen?', 'done!': 'gereed!', 'Download': 'Download', 'E-mail': 'E-mail', 'E-mail invalid': 'E-mail ongeldig', 'edit': 'bewerk', 'EDIT': 'BEWERK', 'Edit': 'Bewerk', 'Edit application': 'Bewerk applicatie', 'edit controller': 'bewerk controller', 'Edit current record': 'Bewerk huidig record', 'Edit Profile': 'Bewerk Profiel', 'edit profile': 'bewerk profiel', 'Edit This App': 'Bewerk Deze App', 'Editing file': 'Bewerk bestand', 'Editing file "%s"': 'Bewerk bestand "%s"', 'Email and SMS': 'E-mail en SMS', 'enter a number between %(min)g and %(max)g': 'geef een getal tussen %(min)g en %(max)g', 'Enter an integer between %(min)g and %(max)g': 'Enter an integer between %(min)g and %(max)g', 'enter an integer between %(min)g and %(max)g': 'geef een integer tussen %(min)g en %(max)g', 'Error logs for "%(app)s"': 'Error logs voor "%(app)s"', 'errors': 'errors', 'Errors': 'Errors', 'Export': 'Export', 'export as csv file': 'exporteer als csv-bestand', 'exposes': 'stelt bloot', 'extends': 'extends', 'failed to reload module': 'niet gelukt om module te herladen', 'False': 'Onwaar', 'FAQ': 'FAQ', 'file "%(filename)s" created': 'bestand "%(filename)s" gemaakt', 'file "%(filename)s" deleted': 'bestand "%(filename)s" verwijderd', 'file "%(filename)s" uploaded': 'bestand "%(filename)s" geupload', 'file "%(filename)s" was not deleted': 'bestand "%(filename)s" was niet verwijderd', 'file "%s" of %s restored': 'bestand "%s" van %s hersteld', 'file changed on disk': 'bestand aangepast op schijf', 'file does not exist': 'bestand bestaat niet', 'file saved on %(time)s': 'bestand bewaard op %(time)s', 'file saved on %s': 'bestand bewaard op %s', 'First name': 'Voornaam', 'Forbidden': 'Verboden', 'Forms and Validators': 'Formulieren en Validators', 'Free Applications': 'Gratis Applicaties', 'Functions with no doctests will result in [passed] tests.': 'Functies zonder doctests zullen resulteren in [passed] tests.', 'Group %(group_id)s created': 'Groep %(group_id)s gemaakt', 'Group ID': 'Groep ID', 'Group uniquely assigned to user %(id)s': 'Groep is uniek toegekend aan gebruiker %(id)s', 'Groups': 'Groepen', 'Hello World': 'Hallo Wereld', 'help': 'help', 'Home': 'Home', 'How did you get here?': 'Hoe ben je hier gekomen?', 'htmledit': 'Bewerk HTML', 'import': 'import', 'Import/Export': 'Import/Export', 'includes': 'includes', 'Index': 'Index', 'insert new': 'voeg nieuwe', 'insert new %s': 'voeg nieuwe %s', 'Installed applications': 'Geïnstalleerde applicaties', 'internal error': 'interne error', 'Internal State': 'Interne State', 'Introduction': 'Introductie', 'Invalid action': 'Ongeldige actie', 'Invalid email': 'Ongeldig emailadres', 'invalid password': 'ongeldig wachtwoord', 'Invalid password': 'Ongeldig wachtwoord', 'Invalid Query': 'Ongeldige Query', 'invalid request': 'ongeldige request', 'invalid ticket': 'ongeldige ticket', 'Is Active': 'Is Actief', 'Key': 'Key', 'language file "%(filename)s" created/updated': 'taalbestand "%(filename)s" gemaakt/geupdate', 'Language files (static strings) updated': 'Taalbestanden (statische strings) geupdate', 'languages': 'talen', 'Languages': 'Talen', 'languages updated': 'talen geupdate', 'Last name': 'Achternaam', 'Last saved on:': 'Laatst bewaard op:', 'Layout': 'Layout', 'Layout Plugins': 'Layout Plugins', 'Layouts': 'Layouts', 'License for': 'Licentie voor', 'Live Chat': 'Live Chat', 'loading...': 'laden...', 'Logged in': 'Ingelogd', 'Logged out': 'Uitgelogd', 'Login': 'Login', 'login': 'login', 'Login to the Administrative Interface': 'Inloggen op de Administratieve Interface', 'logout': 'logout', 'Logout': 'Logout', 'Lost Password': 'Wachtwoord Kwijt', 'Lost password?': 'Wachtwoord kwijt?', 'Main Menu': 'Hoofdmenu', 'Manage Cache': 'Beheer Cache', 'Menu Model': 'Menu Model', 'merge': 'samenvoegen', 'Models': 'Modellen', 'models': 'modellen', 'Modified By': 'Aangepast Door', 'Modified On': 'Aangepast Op', 'Modules': 'Modules', 'modules': 'modules', 'My Sites': 'Mijn Sites', 'Name': 'Naam', 'New': 'Nieuw', 'new application "%s" created': 'nieuwe applicatie "%s" gemaakt', 'New password': 'Nieuw wachtwoord', 'New Record': 'Nieuw Record', 'new record inserted': 'nieuw record ingevoegd', 'next 100 rows': 'volgende 100 rijen', 'NO': 'NEE', 'No databases in this application': 'Geen database in deze applicatie', 'Object or table name': 'Object of tabelnaam', 'Old password': 'Oude wachtwoord', 'Online examples': 'Online voorbeelden', 'Or': 'Of', 'or import from csv file': 'of importeer van csv-bestand', 'or provide application url:': 'of geef een applicatie url:', 'Origin': 'Bron', 'Original/Translation': 'Oorspronkelijk/Vertaling', 'Other Plugins': 'Andere Plugins', 'Other Recipes': 'Andere Recepten', 'Overview': 'Overzicht', 'pack all': 'pack all', 'pack compiled': 'pack compiled', 'Password': 'Wachtwoord', "Password fields don't match": 'Wachtwoordvelden komen niet overeen', 'Peeking at file': 'Naar bestand aan het gluren', 'please input your password again': 'geef alstublieft nogmaals uw wachtwoord', 'Plugins': 'Plugins', 'Powered by': 'Powered by', 'Preface': 'Inleiding', 'previous 100 rows': 'vorige 100 rijen', 'Profile': 'Profiel', 'Python': 'Python', 'Query': 'Query', 'Query:': 'Query:', 'Quick Examples': 'Snelle Voorbeelden', 'RAM': 'RAM', 'RAM Cache Keys': 'RAM Cache Keys', 'Ram Cleared': 'Ram Geleegd', 'Recipes': 'Recepten', 'Record': 'Record', 'record does not exist': 'record bestaat niet', 'Record ID': 'Record ID', 'Record id': 'Record id', 'register': 'registreer', 'Register': 'Registreer', 'Registration identifier': 'Registratie identifier', 'Registration key': 'Registratie sleutel', 'Registration successful': 'Registratie succesvol', 'Remember me (for 30 days)': 'Onthoudt mij (voor 30 dagen)', 'remove compiled': 'verwijder gecompileerde', 'Request reset password': 'Vraag een wachtwoord reset aan', 'Reset Password key': 'Reset Wachtwoord sleutel', 'Resolve Conflict file': 'Los Conflictbestand op', 'restore': 'herstel', 'revert': 'herstel', 'Role': 'Rol', 'Rows in Table': 'Rijen in tabel', 'Rows selected': 'Rijen geselecteerd', 'save': 'bewaar', 'Save profile': 'Bewaar profiel', 'Saved file hash:': 'Opgeslagen file hash:', 'Search': 'Zoek', 'Semantic': 'Semantisch', 'Services': 'Services', 'session expired': 'sessie verlopen', 'shell': 'shell', 'site': 'site', 'Size of cache:': 'Grootte van cache:', 'some files could not be removed': 'sommige bestanden konden niet worden verwijderd', 'starts with': 'begint met', 'state': 'state', 'static': 'statisch', 'Static files': 'Statische bestanden', 'Statistics': 'Statistieken', 'Stylesheet': 'Stylesheet', 'Submit': 'Submit', 'submit': 'submit', 'Support': 'Support', 'Sure you want to delete this object?': 'Weet je zeker dat je dit object wilt verwijderen?', 'Table': 'Tabel', 'Table name': 'Tabelnaam', 'test': 'test', 'Testing application': 'Applicatie testen', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'De "query" is een conditie zoals "db.tabel1.veld1==\'waarde\'". Zoiets als "db.tabel1.veld1==db.tabel2.veld2" resulteert in een SQL JOIN.', 'the application logic, each URL path is mapped in one exposed function in the controller': 'the applicatie logica, elk URL pad is gemapped in een blootgestelde functie in de controller', 'The Core': 'De Core', 'the data representation, define database tables and sets': 'de data representatie, definieert database tabellen en sets', 'The output of the file is a dictionary that was rendered by the view %s': 'De output van het bestand is een dictionary die gerenderd werd door de view %s', 'the presentations layer, views are also known as templates': 'de presentatie laag, views zijn ook bekend als templates', 'The Views': 'De Views', 'There are no controllers': 'Er zijn geen controllers', 'There are no models': 'Er zijn geen modellen', 'There are no modules': 'Er zijn geen modules', 'There are no static files': 'Er zijn geen statische bestanden', 'There are no translators, only default language is supported': 'Er zijn geen vertalingen, alleen de standaard taal wordt ondersteund.', 'There are no views': 'Er zijn geen views', 'these files are served without processing, your images go here': 'Deze bestanden worden geserveerd zonder verdere verwerking, je afbeeldingen horen hier', 'This App': 'Deze App', 'This email already has an account': 'This email already has an account', 'This is a copy of the scaffolding application': 'Dit is een kopie van de steiger-applicatie', 'This is the %(filename)s template': 'Dit is de %(filename)s template', 'Ticket': 'Ticket', 'Time in Cache (h:m:s)': 'Tijd in Cache (h:m:s)', 'Timestamp': 'Timestamp (timestamp)', 'to previous version.': 'naar vorige versie.', 'too short': 'te kort', 'translation strings for the application': 'vertaalstrings voor de applicatie', 'True': 'Waar', 'try': 'probeer', 'try something like': 'probeer zoiets als', 'Twitter': 'Twitter', 'Unable to check for upgrades': 'Niet mogelijk om te controleren voor upgrades', 'unable to create application "%s"': 'niet mogelijk om applicatie "%s" te maken', 'unable to delete file "%(filename)s"': 'niet mogelijk om bestand "%(filename)s" te verwijderen', 'Unable to download': 'Niet mogelijk om te downloaden', 'Unable to download app': 'Niet mogelijk om app te downloaden', 'unable to parse csv file': 'niet mogelijk om csv-bestand te parsen', 'unable to uninstall "%s"': 'niet mogelijk om "%s" te deïnstalleren', 'uncheck all': 'vink alles uit', 'uninstall': ' deïnstalleer', 'update': 'update', 'update all languages': 'update alle talen', 'Update:': 'Update:', 'upload application:': 'upload applicatie:', 'Upload existing application': 'Upload bestaande applicatie', 'upload file:': 'upload bestand', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Gebruik (...)&(...) voor AND, (...)|(...) voor OR, en ~(...) voor NOT om meer complexe queries te maken.', 'User %(id)s Logged-in': 'Gebruiker %(id)s Logged-in', 'User %(id)s Logged-out': 'Gebruiker %(id)s Logged-out', 'User %(id)s Password changed': 'Wachtwoord van gebruiker %(id)s is veranderd', 'User %(id)s Password reset': 'Wachtwoord van gebruiker %(id)s is gereset', 'User %(id)s Profile updated': 'Profiel van Gebruiker %(id)s geupdate', 'User %(id)s Registered': 'Gebruiker %(id)s Geregistreerd', 'User ID': 'User ID', 'value already in database or empty': 'waarde al in database of leeg', 'Verify Password': 'Verifieer Wachtwoord', 'versioning': 'versionering', 'Videos': 'Videos', 'View': 'View', 'view': 'view', 'Views': 'Vieuws', 'views': 'vieuws', 'web2py is up to date': 'web2py is up to date', 'web2py Recent Tweets': 'web2py Recente Tweets', 'Welcome': 'Welkom', 'Welcome %s': 'Welkom %s', 'Welcome to web2py': 'Welkom bij web2py', 'Welcome to web2py!': 'Welkom bij web2py!', 'Which called the function %s located in the file %s': 'Die functie %s aanriep en zich bevindt in het bestand %s', 'YES': 'JA', 'You are successfully running web2py': 'Je draait web2py succesvol', 'You can modify this application and adapt it to your needs': 'Je kan deze applicatie aanpassen naar je eigen behoeften', 'You visited the url %s': 'Je bezocht de url %s', }
#!/usr/bin/env python """ CREATED AT: 2021/8/1 Des: https://leetcode.com/contest/weekly-contest-252/problems/three-divisors/ GITHUB: https://github.com/Jiezhi/myleetcode """ class Solution: def isThree(self, n: int) -> bool: cnt = 0 for i in range(2, int(n / 2) + 1): if n % i == 0: cnt += 1 return cnt == 1 def test(): assert not Solution().isThree(n=2) assert not Solution().isThree(n=8) assert Solution().isThree(n=4) assert Solution().isThree(n=9) if __name__ == '__main__': test()
try: var1 += 1 except: var1 = 1 def __quick_unload_script(): print("Unloaded: %s" % str(var1)) print(f"Just edit and save! {var1}")
class MissingKeyError(Exception): pass class NoneError(Exception): pass
def print_lol(the_list, indent = False, level = 0): """This function ...""" for each_item in the_list: if isinstance(each_item, list): print_lol(each_item, indent, level + 1) else: if indent: for tab_stop in range(level): print("\t", end='') print(each_item)
''' Tipo: Concepto, Ejercicio, Pregunta... Fuente: libro, curso, ... Este chunk de código tiene como propósito... '''
# Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Enforces luci-milo.cfg consistency. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details on the presubmit API built into depot_tools. """ PRESUBMIT_VERSION = '2.0.0' USE_PYTHON3 = True _IGNORE_FREEZE_FOOTER = 'Ignore-Freeze' # The time module's handling of timezones is abysmal, so the boundaries are # precomputed in UNIX time _FREEZE_START = 1639641600 # 2021/12/16 00:00 -0800 _FREEZE_END = 1641196800 # 2022/01/03 00:00 -0800 def CheckFreeze(input_api, output_api): if _FREEZE_START <= input_api.time.time() < _FREEZE_END: footers = input_api.change.GitFootersFromDescription() if _IGNORE_FREEZE_FOOTER not in footers: def convert(t): ts = input_api.time.localtime(t) return input_api.time.strftime('%Y/%m/%d %H:%M %z', ts) return [ output_api.PresubmitError( 'There is a prod freeze in effect from {} until {},' ' files in //infra/config cannot be modified'.format( convert(_FREEZE_START), convert(_FREEZE_END))) ] return [] def CheckTests(input_api, output_api): glob = input_api.os_path.join(input_api.PresubmitLocalPath(), '*_test.py') tests = input_api.canned_checks.GetUnitTests(input_api, output_api, input_api.glob(glob), run_on_python2=False, run_on_python3=True, skip_shebang_check=True) return input_api.RunTests(tests) def CheckLintLuciMilo(input_api, output_api): if ('infra/config/generated/luci/luci-milo.cfg' in input_api.LocalPaths() or 'infra/config/lint-luci-milo.py' in input_api.LocalPaths()): return input_api.RunTests([ input_api.Command( name='lint-luci-milo', cmd=[input_api.python_executable, 'lint-luci-milo.py'], kwargs={}, message=output_api.PresubmitError), ]) return [] def CheckTestingBuildbot(input_api, output_api): if ('infra/config/generated/luci/luci-milo.cfg' in input_api.LocalPaths() or 'infra/config/generated/luci/luci-milo-dev.cfg' in input_api.LocalPaths() ): return input_api.RunTests([ input_api.Command( name='testing/buildbot config checks', cmd=[input_api.python_executable, input_api.os_path.join( '..', '..', 'testing', 'buildbot', 'generate_buildbot_json.py',), '--check'], kwargs={}, message=output_api.PresubmitError), ]) return [] def CheckLucicfgGenOutputMain(input_api, output_api): return input_api.RunTests(input_api.canned_checks.CheckLucicfgGenOutput( input_api, output_api, 'main.star')) def CheckLucicfgGenOutputDev(input_api, output_api): return input_api.RunTests(input_api.canned_checks.CheckLucicfgGenOutput( input_api, output_api, 'dev.star')) def CheckChangedLUCIConfigs(input_api, output_api): return input_api.canned_checks.CheckChangedLUCIConfigs( input_api, output_api) # Footer indicating a CL that is trying to address an outage by some mechanism # other than those in infra/config/outages _OUTAGE_ACTION_FOOTER = 'Infra-Config-Outage-Action' # Footer acknowledging that an outages configuration is in effect when making an # unrelated change _IGNORE_OUTAGE_FOOTER = 'Infra-Config-Ignore-Outage' def CheckOutagesConfigOnCommit(input_api, output_api): outages_pyl = input_api.os_path.join( input_api.PresubmitLocalPath(), 'generated/outages.pyl') with open(outages_pyl) as f: outages_config = input_api.ast.literal_eval(f.read()) if not outages_config: footers = input_api.change.GitFootersFromDescription() return [ output_api.PresubmitError( 'There is no outages configuration in effect, ' 'please remove the {} footer from your CL description.' .format(footer)) for footer in (_OUTAGE_ACTION_FOOTER, _IGNORE_OUTAGE_FOOTER) if footer in footers ] # Any of the config files under infra/config/outages outages_config_files = set() # Any of the config files under infra/config/generated generated_config_files = set() # Any config files that are not under infra/config/outages or # infra/config/generated config_files = set() for p in input_api.LocalPaths(): if p in ('README.md', 'OWNERS'): continue if p.startswith('infra/config/outages/'): outages_config_files.add(p) continue if p.startswith('infra/config/generated/'): generated_config_files.add(p) continue config_files.add(p) # If the only changes to non-generated config fies were the outages files, # assume the change was addressing an outage and that no additional mechanism # needs to be added if outages_config_files and not config_files: # REVIEWER: Should we prevent the footers from being here in this case? return [] # If any non-generated, non-outages files were modified or if the generated # config files were modified without any config files being modified (lucicfg # change, etc.) then make sure the user knows that when the outages # configuration is disabled, the generated configuration may change if config_files or generated_config_files: footers = input_api.change.GitFootersFromDescription() has_action_footer = _OUTAGE_ACTION_FOOTER in footers has_ignore_footer = _IGNORE_OUTAGE_FOOTER in footers if has_action_footer and has_ignore_footer: return [ output_api.PresubmitError( 'Only one of {} or {} should be present in your CL description' .format(_OUTAGE_ACTION_FOOTER, _IGNORE_OUTAGE_FOOTER)), ] if not has_action_footer and not has_ignore_footer: outages_config_lines = ['{}: {}'.format(k, v) for k, v in sorted(outages_config.items())] return [ output_api.PresubmitError('\n'.join([ 'The following outages configuration is in effect:\n {}'.format( '\n '.join(outages_config_lines)), ('The effect of your change may not be visible ' 'in the generated configuration.'), ('If your change is addressing the outage, ' 'please add the footer {} with a link for the outage.' ).format(_OUTAGE_ACTION_FOOTER), ('If your change is not addressing the outage ' 'but you still wish to land it, please add the footer ' '{} with a reason.').format(_IGNORE_OUTAGE_FOOTER), ('For more information on outages configuration, ' 'see https://chromium.googlesource.com/chromium/src/+/HEAD/infra/config/outages' ), ])), ] return []
# A importancia de R$780.000.00 será dividida entre tres ganhadores de um concurso # sendo que da quantia total: # - O primeiro ganhador receberá 46% # - O segundo recebera 32% # - O terceiro receberá o restante premio = 780000.00 primeiro = premio * 0.46 segundo = premio * 0.32 terceiro = premio - primeiro - segundo print(f"O ganhador 1 receberá: R${primeiro:.2f}") print(f"O ganhador 2 receberá: R${segundo:.2f}") print(f"O ganhador 3 receberá: R${terceiro:.2f}")
#Also called as Circular Queue class Queue: def __init__(self, maxSize): self.items = maxSize * [None] # To initialize a list with a limit set make a list with the size u want and make all the elements None self.maxSize = maxSize self.start = -1 self.top = -1 def __str__(self): values = [str(x) for x in self.items] return " ".join(values) def isFull(self): if self.top + 1 == self.start: return True elif self.start ==0 and self.top+1 == self.top: return True else: return False def isEmpty(self): if self.top == -1: return True else: return False def enqueue(self, value): if self.isFull(): print("Queue is full :/") else: if self.top+1 == self.maxSize: #if queue is not full but top is at the end of the queue it means that we have dequeued elements and now when we enquue elements they will be added at the start of the queu and not the end self.top = 0 else: #regular adding at the end of the queue self.top+=1 if self.start == -1: self.start=0 self.items[self.top] = value return "Element is inserted at the end of the queue" def dequeue(self): if self.isEmpty(): print("Queue is empty") else: firstelement = self.items[self.start] start = self.start if self.start == self.top: #only 1 element self.start = -1 self.top = -1 elif self.start + 1 == self.maxSize: self.start = 0 else: self.start+=1 self.items[start] = None return firstelement def peek(self): if self.isEmpty(): print("Queue is empty") else: return self.items[self.start] def delete(self): self.items = self.maxSize * [None] self.top = -1 self.start = -1 customqueue = Queue(3) customqueue.enqueue(1) customqueue.enqueue(2) customqueue.enqueue(3) print(customqueue.dequeue()) print(customqueue) print(customqueue.peek()) #returns 2 not None wow
def checkorders(orders: [str]) -> [bool]: results = [] for i in orders: flag = True stock = [] for j in i: if j in '([{': stock.append(j) else: if stock == []: flag = False break symbol = stock.pop() if not match(symbol, j): flag = False break if stock != []: flag = False results.append(flag) return results def match(opens,closers): return '([{'.index(opens) == ')]}'.index(closers) print(checkorders(['()','(','{}[]','[][][]','[{]{]']))
a = int(input()) b = int(input()) if a > b: print(a) else: print(b)
""" Zadeklaruj funkcje która jako argumenty przyjmuje dwie zmienne i zwraca ich sumę """ def f(a:int, b:int): return a+b print(f(12, 12))
""" Faça um Programa que peça a temperatura em graus Fahrenheit, transforme e mostre a temperatura em graus Celsius. C = 5 * ((F-32) / 9). """ farenheit = float(input('Informe a temperatura em Farenheit: ')) celsius = 5 * (farenheit - 32) / 9.0 print(f'A temperatura em Celsius é: {celsius}')
a,b = map(int,input().split()) ans=0 k=1 while a or b: ans+=k*(((b%3)-(a%3))%3) a//=3 b//=3 k*=3 print(ans)
# Minimum Remove to Make Valid Parentheses: https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/ # Given a string s of '(' , ')' and lowercase English characters. # Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string. # Formally, a parentheses string is valid if and only if: # It is the empty string, contains only lowercase characters, or # It can be written as AB (A concatenated with B), where A and B are valid strings, or # It can be written as (A), where A is a valid string. # This problem seems really tricky but honestly you are checking that whenever you add a ( or ) that it is valid # otherwise you add it to your count # so the two ones are if you have a ( it is only valid if you have a ) so if you find a ) after it at somepoint it is valid # or if you have a ) there has to be something before it aka ( so if you have an empty stack you can add it to the count # Now the other piece of this is you need to add all ( and remove them once you have a valid combo as it has been # validated # Oh I read this a bit wrong since we need to return a valid string our stack needs to hold the index at which the invalid parens # are so that we can remove them before returning class Solution: def minRemoveToMakeValid(self, s: str) -> str: stack = [] for index in range(len(s)): char = s[index] if char == ')': if len(stack) == 0: stack.append(index) else: if s[stack[-1]] == '(': stack.pop() else: stack.append(index) elif char == '(': stack.append(index) result = '' index = 0 for i in range(len(s)): if index < len(stack) and stack[index] == i: index += 1 continue result += s[i] return result # The above works but there is definitely some improvements that could be made as I am not using a set to remove values # but rather going across iteratively. The reason why we could use a set is that we know if a value is invalid by if it # is still on the stack once we have finished parsing or if we have an invalid char befor it. # The above runs in O(N) and uses O(N) space and actually so will this second piece but it will be a slight improvement # as the string building will be using an O(1) that requires no extra operations def minRemoveToMakeValid(self, s: str) -> str: remove = set() stack = [] for i in range(len(s)): if s[i] == '(': stack.append(i) elif s[i] == ')': if len(stack) > 0 and s[stack[-1]] == '(': stack.pop() else: remove.add(i) while stack: remove.add(stack.pop()) result = '' for i in range(len(s)): if i not in remove: result += s[i] return result # This is just a slight improvement and doesn't effect the big O # Score Card # Did I need hints? Nope # Did you finish within 30 min? 10 # Was the solution optimal? Yup # Were there any bugs? None # 5 5 5 5 = 5
#!user/bin/python class MyEnv: """ """ def __init__(self): self.my_env = { "subnet": "<your_lab_subnet/mask>", "gateway": "<your_lab_gateway_ip_address>", "ansible_addr": "<ansible_container_ip_address>", "web_addr": "<wev_container_ip_address>", "db_addr": "<db_container_ip_address>", "phsical_nic": "<NIC name of docker host>", "db_password": "<mysql_password>" }
# -*- coding: utf-8 -*- """ @Author : captain @time : 18-7-11 上午12:33 @ide : PyCharm """ class DefaultConfig(object): ''' 列出所有的参数,只根据模型需要获取参数 ''' env = 'default' # visdom环境 seed = 777 # 设置随机数种子 best_score = 0 model = 'InCNN' # 使用的模型,名字必须与models/__init__.py中的名字一致 model_path = None # 如果有就加载 result_path = '' save_dir = 'snapshot/' # where to save the snapshot id = 'default' device = 0 boost = False ## 是否使用adboost bo_layers = 5 ## boost的层数 finetune = False ## 是否对训练完成的模型进行finetune aug = False ## 是否进行数据增强 # 数据集参数 data_path = '/data/yujun/captain/datasets/' text_type = 'word' # or 'article' # 决定数据集位置 # train_data_path = '/data/yujun/datasets/daguanbei_data/new_split/new_train_set.csv' # val_data_path = '/data/yujun/datasets/daguanbei_data/new_split/val_set.csv' # test_data_path = '/data/yujun/datasets/daguanbei_data/test_set.csv' # embedding_path = '/data/yujun/captain/emb' # 使用的预训练词向量 # embedding_dim = 300 # number of embedding dimension # 在自己的PC上小数据集调试代码用 # train_data_path = 'D:/git/dataset/val_set.csv' # test_data_path = 'D:/git/dataset/val_set.csv' # val_data_path = 'D:/git/dataset/val_set.csv' embedding_path = 'D:/git/emb' # 预训练词向量的位置 embedding_dim = 100 batch_size = 64 vocab_size = 10000 # 词库规模,配置中写的值没有意义,实际是预处理阶段获取 label_size = 19 # 分类类别数 max_text_len = 2000 # 之后会处理成变长的,这里的设置没有意义 # 训练参数 lr1 = 1e-3 # learning rate lr2 = 0 # embedding层的学习率 min_lr = 1e-5 # 当学习率低于这个nvi值时,就退出训练 lr_decay = 0.8 # 当一个epoch的损失开始上升时,lr = lr*lr_decay decay_every = 10000 # 每多少个batch 查看val acc,并修改学习率 weight_decay = 0 # 2e-5 # 权重衰减 max_epochs = 50 cuda = True # 模型通用 linear_hidden_size = 100 # 原来为2000(500),之后还需要修改,感觉数值有点大 # TextCNN kernel_num = 200 # number of each kind of kernel kernel_sizes = '3,4,5' # kernel size to use for convolution dropout_rate = 0.5 # the probability for dropout # LSTM hidden_dim = 256 lstm_dropout = 0.5 # 只有当lstm_layers > 1时,设置lstm_dropout才有意义 lstm_layers = 1 kmax_pooling = 2 # RCNN rcnn_kernel = 512 def parse(self, kwargs): ''' 根据字典kwargs 更新 config参数 ''' # 更新配置参数 for k, v in kwargs.items(): if not hasattr(self, k): raise Exception("Warning: config has not attribute <%s>" % k) setattr(self, k, v) def print_config(self): # 打印配置信息 print('user config:') for k, v in self.__class__.__dict__.items(): if not k.startswith('__') and k != 'parse' and k != 'print_config': print(' {} : {}'.format(k, getattr(self, k)))
app_name = "users" urlpatterns = [ ]